xref: /linux/kernel/bpf/verifier.c (revision 53dabce2)
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 
32 #include "disasm.h"
33 
34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
36 	[_id] = & _name ## _verifier_ops,
37 #define BPF_MAP_TYPE(_id, _ops)
38 #define BPF_LINK_TYPE(_id, _name)
39 #include <linux/bpf_types.h>
40 #undef BPF_PROG_TYPE
41 #undef BPF_MAP_TYPE
42 #undef BPF_LINK_TYPE
43 };
44 
45 struct bpf_mem_alloc bpf_global_percpu_ma;
46 static bool bpf_global_percpu_ma_set;
47 
48 /* bpf_check() is a static code analyzer that walks eBPF program
49  * instruction by instruction and updates register/stack state.
50  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
51  *
52  * The first pass is depth-first-search to check that the program is a DAG.
53  * It rejects the following programs:
54  * - larger than BPF_MAXINSNS insns
55  * - if loop is present (detected via back-edge)
56  * - unreachable insns exist (shouldn't be a forest. program = one function)
57  * - out of bounds or malformed jumps
58  * The second pass is all possible path descent from the 1st insn.
59  * Since it's analyzing all paths through the program, the length of the
60  * analysis is limited to 64k insn, which may be hit even if total number of
61  * insn is less then 4K, but there are too many branches that change stack/regs.
62  * Number of 'branches to be analyzed' is limited to 1k
63  *
64  * On entry to each instruction, each register has a type, and the instruction
65  * changes the types of the registers depending on instruction semantics.
66  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
67  * copied to R1.
68  *
69  * All registers are 64-bit.
70  * R0 - return register
71  * R1-R5 argument passing registers
72  * R6-R9 callee saved registers
73  * R10 - frame pointer read-only
74  *
75  * At the start of BPF program the register R1 contains a pointer to bpf_context
76  * and has type PTR_TO_CTX.
77  *
78  * Verifier tracks arithmetic operations on pointers in case:
79  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
80  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
81  * 1st insn copies R10 (which has FRAME_PTR) type into R1
82  * and 2nd arithmetic instruction is pattern matched to recognize
83  * that it wants to construct a pointer to some element within stack.
84  * So after 2nd insn, the register R1 has type PTR_TO_STACK
85  * (and -20 constant is saved for further stack bounds checking).
86  * Meaning that this reg is a pointer to stack plus known immediate constant.
87  *
88  * Most of the time the registers have SCALAR_VALUE type, which
89  * means the register has some value, but it's not a valid pointer.
90  * (like pointer plus pointer becomes SCALAR_VALUE type)
91  *
92  * When verifier sees load or store instructions the type of base register
93  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
94  * four pointer types recognized by check_mem_access() function.
95  *
96  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
97  * and the range of [ptr, ptr + map's value_size) is accessible.
98  *
99  * registers used to pass values to function calls are checked against
100  * function argument constraints.
101  *
102  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
103  * It means that the register type passed to this function must be
104  * PTR_TO_STACK and it will be used inside the function as
105  * 'pointer to map element key'
106  *
107  * For example the argument constraints for bpf_map_lookup_elem():
108  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
109  *   .arg1_type = ARG_CONST_MAP_PTR,
110  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
111  *
112  * ret_type says that this function returns 'pointer to map elem value or null'
113  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
114  * 2nd argument should be a pointer to stack, which will be used inside
115  * the helper function as a pointer to map element key.
116  *
117  * On the kernel side the helper function looks like:
118  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
119  * {
120  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
121  *    void *key = (void *) (unsigned long) r2;
122  *    void *value;
123  *
124  *    here kernel can access 'key' and 'map' pointers safely, knowing that
125  *    [key, key + map->key_size) bytes are valid and were initialized on
126  *    the stack of eBPF program.
127  * }
128  *
129  * Corresponding eBPF program may look like:
130  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
131  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
132  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
133  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
134  * here verifier looks at prototype of map_lookup_elem() and sees:
135  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
136  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
137  *
138  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
139  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
140  * and were initialized prior to this call.
141  * If it's ok, then verifier allows this BPF_CALL insn and looks at
142  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
143  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
144  * returns either pointer to map value or NULL.
145  *
146  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
147  * insn, the register holding that pointer in the true branch changes state to
148  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
149  * branch. See check_cond_jmp_op().
150  *
151  * After the call R0 is set to return type of the function and registers R1-R5
152  * are set to NOT_INIT to indicate that they are no longer readable.
153  *
154  * The following reference types represent a potential reference to a kernel
155  * resource which, after first being allocated, must be checked and freed by
156  * the BPF program:
157  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
158  *
159  * When the verifier sees a helper call return a reference type, it allocates a
160  * pointer id for the reference and stores it in the current function state.
161  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
162  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
163  * passes through a NULL-check conditional. For the branch wherein the state is
164  * changed to CONST_IMM, the verifier releases the reference.
165  *
166  * For each helper function that allocates a reference, such as
167  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
168  * bpf_sk_release(). When a reference type passes into the release function,
169  * the verifier also releases the reference. If any unchecked or unreleased
170  * reference remains at the end of the program, the verifier rejects it.
171  */
172 
173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
174 struct bpf_verifier_stack_elem {
175 	/* verifier state is 'st'
176 	 * before processing instruction 'insn_idx'
177 	 * and after processing instruction 'prev_insn_idx'
178 	 */
179 	struct bpf_verifier_state st;
180 	int insn_idx;
181 	int prev_insn_idx;
182 	struct bpf_verifier_stack_elem *next;
183 	/* length of verifier log at the time this state was pushed on stack */
184 	u32 log_pos;
185 };
186 
187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
188 #define BPF_COMPLEXITY_LIMIT_STATES	64
189 
190 #define BPF_MAP_KEY_POISON	(1ULL << 63)
191 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
192 
193 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
194 
195 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
196 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
197 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
198 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
199 static int ref_set_non_owning(struct bpf_verifier_env *env,
200 			      struct bpf_reg_state *reg);
201 static void specialize_kfunc(struct bpf_verifier_env *env,
202 			     u32 func_id, u16 offset, unsigned long *addr);
203 static bool is_trusted_reg(const struct bpf_reg_state *reg);
204 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)205 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
206 {
207 	return aux->map_ptr_state.poison;
208 }
209 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)210 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
211 {
212 	return aux->map_ptr_state.unpriv;
213 }
214 
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,struct bpf_map * map,bool unpriv,bool poison)215 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
216 			      struct bpf_map *map,
217 			      bool unpriv, bool poison)
218 {
219 	unpriv |= bpf_map_ptr_unpriv(aux);
220 	aux->map_ptr_state.unpriv = unpriv;
221 	aux->map_ptr_state.poison = poison;
222 	aux->map_ptr_state.map_ptr = map;
223 }
224 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)225 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
226 {
227 	return aux->map_key_state & BPF_MAP_KEY_POISON;
228 }
229 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)230 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
231 {
232 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
233 }
234 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)235 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
236 {
237 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
238 }
239 
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)240 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
241 {
242 	bool poisoned = bpf_map_key_poisoned(aux);
243 
244 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
245 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
246 }
247 
bpf_helper_call(const struct bpf_insn * insn)248 static bool bpf_helper_call(const struct bpf_insn *insn)
249 {
250 	return insn->code == (BPF_JMP | BPF_CALL) &&
251 	       insn->src_reg == 0;
252 }
253 
bpf_pseudo_call(const struct bpf_insn * insn)254 static bool bpf_pseudo_call(const struct bpf_insn *insn)
255 {
256 	return insn->code == (BPF_JMP | BPF_CALL) &&
257 	       insn->src_reg == BPF_PSEUDO_CALL;
258 }
259 
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)260 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
261 {
262 	return insn->code == (BPF_JMP | BPF_CALL) &&
263 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
264 }
265 
266 struct bpf_call_arg_meta {
267 	struct bpf_map *map_ptr;
268 	bool raw_mode;
269 	bool pkt_access;
270 	u8 release_regno;
271 	int regno;
272 	int access_size;
273 	int mem_size;
274 	u64 msize_max_value;
275 	int ref_obj_id;
276 	int dynptr_id;
277 	int map_uid;
278 	int func_id;
279 	struct btf *btf;
280 	u32 btf_id;
281 	struct btf *ret_btf;
282 	u32 ret_btf_id;
283 	u32 subprogno;
284 	struct btf_field *kptr_field;
285 };
286 
287 struct bpf_kfunc_call_arg_meta {
288 	/* In parameters */
289 	struct btf *btf;
290 	u32 func_id;
291 	u32 kfunc_flags;
292 	const struct btf_type *func_proto;
293 	const char *func_name;
294 	/* Out parameters */
295 	u32 ref_obj_id;
296 	u8 release_regno;
297 	bool r0_rdonly;
298 	u32 ret_btf_id;
299 	u64 r0_size;
300 	u32 subprogno;
301 	struct {
302 		u64 value;
303 		bool found;
304 	} arg_constant;
305 
306 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
307 	 * generally to pass info about user-defined local kptr types to later
308 	 * verification logic
309 	 *   bpf_obj_drop/bpf_percpu_obj_drop
310 	 *     Record the local kptr type to be drop'd
311 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
312 	 *     Record the local kptr type to be refcount_incr'd and use
313 	 *     arg_owning_ref to determine whether refcount_acquire should be
314 	 *     fallible
315 	 */
316 	struct btf *arg_btf;
317 	u32 arg_btf_id;
318 	bool arg_owning_ref;
319 
320 	struct {
321 		struct btf_field *field;
322 	} arg_list_head;
323 	struct {
324 		struct btf_field *field;
325 	} arg_rbtree_root;
326 	struct {
327 		enum bpf_dynptr_type type;
328 		u32 id;
329 		u32 ref_obj_id;
330 	} initialized_dynptr;
331 	struct {
332 		u8 spi;
333 		u8 frameno;
334 	} iter;
335 	struct {
336 		struct bpf_map *ptr;
337 		int uid;
338 	} map;
339 	u64 mem_size;
340 };
341 
342 struct btf *btf_vmlinux;
343 
btf_type_name(const struct btf * btf,u32 id)344 static const char *btf_type_name(const struct btf *btf, u32 id)
345 {
346 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
347 }
348 
349 static DEFINE_MUTEX(bpf_verifier_lock);
350 static DEFINE_MUTEX(bpf_percpu_ma_lock);
351 
verbose(void * private_data,const char * fmt,...)352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
353 {
354 	struct bpf_verifier_env *env = private_data;
355 	va_list args;
356 
357 	if (!bpf_verifier_log_needed(&env->log))
358 		return;
359 
360 	va_start(args, fmt);
361 	bpf_verifier_vlog(&env->log, fmt, args);
362 	va_end(args);
363 }
364 
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)365 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
366 				   struct bpf_reg_state *reg,
367 				   struct bpf_retval_range range, const char *ctx,
368 				   const char *reg_name)
369 {
370 	bool unknown = true;
371 
372 	verbose(env, "%s the register %s has", ctx, reg_name);
373 	if (reg->smin_value > S64_MIN) {
374 		verbose(env, " smin=%lld", reg->smin_value);
375 		unknown = false;
376 	}
377 	if (reg->smax_value < S64_MAX) {
378 		verbose(env, " smax=%lld", reg->smax_value);
379 		unknown = false;
380 	}
381 	if (unknown)
382 		verbose(env, " unknown scalar value");
383 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
384 }
385 
type_may_be_null(u32 type)386 static bool type_may_be_null(u32 type)
387 {
388 	return type & PTR_MAYBE_NULL;
389 }
390 
reg_not_null(const struct bpf_reg_state * reg)391 static bool reg_not_null(const struct bpf_reg_state *reg)
392 {
393 	enum bpf_reg_type type;
394 
395 	type = reg->type;
396 	if (type_may_be_null(type))
397 		return false;
398 
399 	type = base_type(type);
400 	return type == PTR_TO_SOCKET ||
401 		type == PTR_TO_TCP_SOCK ||
402 		type == PTR_TO_MAP_VALUE ||
403 		type == PTR_TO_MAP_KEY ||
404 		type == PTR_TO_SOCK_COMMON ||
405 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
406 		type == PTR_TO_MEM;
407 }
408 
reg_btf_record(const struct bpf_reg_state * reg)409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
410 {
411 	struct btf_record *rec = NULL;
412 	struct btf_struct_meta *meta;
413 
414 	if (reg->type == PTR_TO_MAP_VALUE) {
415 		rec = reg->map_ptr->record;
416 	} else if (type_is_ptr_alloc_obj(reg->type)) {
417 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
418 		if (meta)
419 			rec = meta->record;
420 	}
421 	return rec;
422 }
423 
subprog_is_global(const struct bpf_verifier_env * env,int subprog)424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
425 {
426 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
427 
428 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
429 }
430 
subprog_name(const struct bpf_verifier_env * env,int subprog)431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
432 {
433 	struct bpf_func_info *info;
434 
435 	if (!env->prog->aux->func_info)
436 		return "";
437 
438 	info = &env->prog->aux->func_info[subprog];
439 	return btf_type_name(env->prog->aux->btf, info->type_id);
440 }
441 
mark_subprog_exc_cb(struct bpf_verifier_env * env,int subprog)442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
443 {
444 	struct bpf_subprog_info *info = subprog_info(env, subprog);
445 
446 	info->is_cb = true;
447 	info->is_async_cb = true;
448 	info->is_exception_cb = true;
449 }
450 
subprog_is_exc_cb(struct bpf_verifier_env * env,int subprog)451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	return subprog_info(env, subprog)->is_exception_cb;
454 }
455 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
457 {
458 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
459 }
460 
type_is_rdonly_mem(u32 type)461 static bool type_is_rdonly_mem(u32 type)
462 {
463 	return type & MEM_RDONLY;
464 }
465 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)466 static bool is_acquire_function(enum bpf_func_id func_id,
467 				const struct bpf_map *map)
468 {
469 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
470 
471 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
472 	    func_id == BPF_FUNC_sk_lookup_udp ||
473 	    func_id == BPF_FUNC_skc_lookup_tcp ||
474 	    func_id == BPF_FUNC_ringbuf_reserve ||
475 	    func_id == BPF_FUNC_kptr_xchg)
476 		return true;
477 
478 	if (func_id == BPF_FUNC_map_lookup_elem &&
479 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
480 	     map_type == BPF_MAP_TYPE_SOCKHASH))
481 		return true;
482 
483 	return false;
484 }
485 
is_ptr_cast_function(enum bpf_func_id func_id)486 static bool is_ptr_cast_function(enum bpf_func_id func_id)
487 {
488 	return func_id == BPF_FUNC_tcp_sock ||
489 		func_id == BPF_FUNC_sk_fullsock ||
490 		func_id == BPF_FUNC_skc_to_tcp_sock ||
491 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
492 		func_id == BPF_FUNC_skc_to_udp6_sock ||
493 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
494 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
495 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
496 }
497 
is_dynptr_ref_function(enum bpf_func_id func_id)498 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
499 {
500 	return func_id == BPF_FUNC_dynptr_data;
501 }
502 
503 static bool is_sync_callback_calling_kfunc(u32 btf_id);
504 static bool is_async_callback_calling_kfunc(u32 btf_id);
505 static bool is_callback_calling_kfunc(u32 btf_id);
506 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
507 
508 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
509 
is_sync_callback_calling_function(enum bpf_func_id func_id)510 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
511 {
512 	return func_id == BPF_FUNC_for_each_map_elem ||
513 	       func_id == BPF_FUNC_find_vma ||
514 	       func_id == BPF_FUNC_loop ||
515 	       func_id == BPF_FUNC_user_ringbuf_drain;
516 }
517 
is_async_callback_calling_function(enum bpf_func_id func_id)518 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
519 {
520 	return func_id == BPF_FUNC_timer_set_callback;
521 }
522 
is_callback_calling_function(enum bpf_func_id func_id)523 static bool is_callback_calling_function(enum bpf_func_id func_id)
524 {
525 	return is_sync_callback_calling_function(func_id) ||
526 	       is_async_callback_calling_function(func_id);
527 }
528 
is_sync_callback_calling_insn(struct bpf_insn * insn)529 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
530 {
531 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
532 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
533 }
534 
is_async_callback_calling_insn(struct bpf_insn * insn)535 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
536 {
537 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
538 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
539 }
540 
is_may_goto_insn(struct bpf_insn * insn)541 static bool is_may_goto_insn(struct bpf_insn *insn)
542 {
543 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
544 }
545 
is_may_goto_insn_at(struct bpf_verifier_env * env,int insn_idx)546 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
547 {
548 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
549 }
550 
is_storage_get_function(enum bpf_func_id func_id)551 static bool is_storage_get_function(enum bpf_func_id func_id)
552 {
553 	return func_id == BPF_FUNC_sk_storage_get ||
554 	       func_id == BPF_FUNC_inode_storage_get ||
555 	       func_id == BPF_FUNC_task_storage_get ||
556 	       func_id == BPF_FUNC_cgrp_storage_get;
557 }
558 
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)559 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
560 					const struct bpf_map *map)
561 {
562 	int ref_obj_uses = 0;
563 
564 	if (is_ptr_cast_function(func_id))
565 		ref_obj_uses++;
566 	if (is_acquire_function(func_id, map))
567 		ref_obj_uses++;
568 	if (is_dynptr_ref_function(func_id))
569 		ref_obj_uses++;
570 
571 	return ref_obj_uses > 1;
572 }
573 
is_cmpxchg_insn(const struct bpf_insn * insn)574 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
575 {
576 	return BPF_CLASS(insn->code) == BPF_STX &&
577 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
578 	       insn->imm == BPF_CMPXCHG;
579 }
580 
__get_spi(s32 off)581 static int __get_spi(s32 off)
582 {
583 	return (-off - 1) / BPF_REG_SIZE;
584 }
585 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)586 static struct bpf_func_state *func(struct bpf_verifier_env *env,
587 				   const struct bpf_reg_state *reg)
588 {
589 	struct bpf_verifier_state *cur = env->cur_state;
590 
591 	return cur->frame[reg->frameno];
592 }
593 
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)594 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
595 {
596        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
597 
598        /* We need to check that slots between [spi - nr_slots + 1, spi] are
599 	* within [0, allocated_stack).
600 	*
601 	* Please note that the spi grows downwards. For example, a dynptr
602 	* takes the size of two stack slots; the first slot will be at
603 	* spi and the second slot will be at spi - 1.
604 	*/
605        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
606 }
607 
stack_slot_obj_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * obj_kind,int nr_slots)608 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
609 			          const char *obj_kind, int nr_slots)
610 {
611 	int off, spi;
612 
613 	if (!tnum_is_const(reg->var_off)) {
614 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
615 		return -EINVAL;
616 	}
617 
618 	off = reg->off + reg->var_off.value;
619 	if (off % BPF_REG_SIZE) {
620 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
621 		return -EINVAL;
622 	}
623 
624 	spi = __get_spi(off);
625 	if (spi + 1 < nr_slots) {
626 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
627 		return -EINVAL;
628 	}
629 
630 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
631 		return -ERANGE;
632 	return spi;
633 }
634 
dynptr_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)635 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
636 {
637 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
638 }
639 
iter_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)640 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
641 {
642 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
643 }
644 
arg_to_dynptr_type(enum bpf_arg_type arg_type)645 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
646 {
647 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
648 	case DYNPTR_TYPE_LOCAL:
649 		return BPF_DYNPTR_TYPE_LOCAL;
650 	case DYNPTR_TYPE_RINGBUF:
651 		return BPF_DYNPTR_TYPE_RINGBUF;
652 	case DYNPTR_TYPE_SKB:
653 		return BPF_DYNPTR_TYPE_SKB;
654 	case DYNPTR_TYPE_XDP:
655 		return BPF_DYNPTR_TYPE_XDP;
656 	default:
657 		return BPF_DYNPTR_TYPE_INVALID;
658 	}
659 }
660 
get_dynptr_type_flag(enum bpf_dynptr_type type)661 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
662 {
663 	switch (type) {
664 	case BPF_DYNPTR_TYPE_LOCAL:
665 		return DYNPTR_TYPE_LOCAL;
666 	case BPF_DYNPTR_TYPE_RINGBUF:
667 		return DYNPTR_TYPE_RINGBUF;
668 	case BPF_DYNPTR_TYPE_SKB:
669 		return DYNPTR_TYPE_SKB;
670 	case BPF_DYNPTR_TYPE_XDP:
671 		return DYNPTR_TYPE_XDP;
672 	default:
673 		return 0;
674 	}
675 }
676 
dynptr_type_refcounted(enum bpf_dynptr_type type)677 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
678 {
679 	return type == BPF_DYNPTR_TYPE_RINGBUF;
680 }
681 
682 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
683 			      enum bpf_dynptr_type type,
684 			      bool first_slot, int dynptr_id);
685 
686 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
687 				struct bpf_reg_state *reg);
688 
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)689 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
690 				   struct bpf_reg_state *sreg1,
691 				   struct bpf_reg_state *sreg2,
692 				   enum bpf_dynptr_type type)
693 {
694 	int id = ++env->id_gen;
695 
696 	__mark_dynptr_reg(sreg1, type, true, id);
697 	__mark_dynptr_reg(sreg2, type, false, id);
698 }
699 
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)700 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
701 			       struct bpf_reg_state *reg,
702 			       enum bpf_dynptr_type type)
703 {
704 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
705 }
706 
707 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
708 				        struct bpf_func_state *state, int spi);
709 
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)710 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
711 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
712 {
713 	struct bpf_func_state *state = func(env, reg);
714 	enum bpf_dynptr_type type;
715 	int spi, i, err;
716 
717 	spi = dynptr_get_spi(env, reg);
718 	if (spi < 0)
719 		return spi;
720 
721 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
722 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
723 	 * to ensure that for the following example:
724 	 *	[d1][d1][d2][d2]
725 	 * spi    3   2   1   0
726 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
727 	 * case they do belong to same dynptr, second call won't see slot_type
728 	 * as STACK_DYNPTR and will simply skip destruction.
729 	 */
730 	err = destroy_if_dynptr_stack_slot(env, state, spi);
731 	if (err)
732 		return err;
733 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
734 	if (err)
735 		return err;
736 
737 	for (i = 0; i < BPF_REG_SIZE; i++) {
738 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
739 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
740 	}
741 
742 	type = arg_to_dynptr_type(arg_type);
743 	if (type == BPF_DYNPTR_TYPE_INVALID)
744 		return -EINVAL;
745 
746 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
747 			       &state->stack[spi - 1].spilled_ptr, type);
748 
749 	if (dynptr_type_refcounted(type)) {
750 		/* The id is used to track proper releasing */
751 		int id;
752 
753 		if (clone_ref_obj_id)
754 			id = clone_ref_obj_id;
755 		else
756 			id = acquire_reference_state(env, insn_idx);
757 
758 		if (id < 0)
759 			return id;
760 
761 		state->stack[spi].spilled_ptr.ref_obj_id = id;
762 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
763 	}
764 
765 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
766 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
767 
768 	return 0;
769 }
770 
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)771 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
772 {
773 	int i;
774 
775 	for (i = 0; i < BPF_REG_SIZE; i++) {
776 		state->stack[spi].slot_type[i] = STACK_INVALID;
777 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
778 	}
779 
780 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
781 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
782 
783 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
784 	 *
785 	 * While we don't allow reading STACK_INVALID, it is still possible to
786 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
787 	 * helpers or insns can do partial read of that part without failing,
788 	 * but check_stack_range_initialized, check_stack_read_var_off, and
789 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
790 	 * the slot conservatively. Hence we need to prevent those liveness
791 	 * marking walks.
792 	 *
793 	 * This was not a problem before because STACK_INVALID is only set by
794 	 * default (where the default reg state has its reg->parent as NULL), or
795 	 * in clean_live_states after REG_LIVE_DONE (at which point
796 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
797 	 * verifier state exploration (like we did above). Hence, for our case
798 	 * parentage chain will still be live (i.e. reg->parent may be
799 	 * non-NULL), while earlier reg->parent was NULL, so we need
800 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
801 	 * done later on reads or by mark_dynptr_read as well to unnecessary
802 	 * mark registers in verifier state.
803 	 */
804 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
805 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
806 }
807 
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)808 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
809 {
810 	struct bpf_func_state *state = func(env, reg);
811 	int spi, ref_obj_id, i;
812 
813 	spi = dynptr_get_spi(env, reg);
814 	if (spi < 0)
815 		return spi;
816 
817 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
818 		invalidate_dynptr(env, state, spi);
819 		return 0;
820 	}
821 
822 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
823 
824 	/* If the dynptr has a ref_obj_id, then we need to invalidate
825 	 * two things:
826 	 *
827 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
828 	 * 2) Any slices derived from this dynptr.
829 	 */
830 
831 	/* Invalidate any slices associated with this dynptr */
832 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
833 
834 	/* Invalidate any dynptr clones */
835 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
836 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
837 			continue;
838 
839 		/* it should always be the case that if the ref obj id
840 		 * matches then the stack slot also belongs to a
841 		 * dynptr
842 		 */
843 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
844 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
845 			return -EFAULT;
846 		}
847 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
848 			invalidate_dynptr(env, state, i);
849 	}
850 
851 	return 0;
852 }
853 
854 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
855 			       struct bpf_reg_state *reg);
856 
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)857 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
858 {
859 	if (!env->allow_ptr_leaks)
860 		__mark_reg_not_init(env, reg);
861 	else
862 		__mark_reg_unknown(env, reg);
863 }
864 
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)865 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
866 				        struct bpf_func_state *state, int spi)
867 {
868 	struct bpf_func_state *fstate;
869 	struct bpf_reg_state *dreg;
870 	int i, dynptr_id;
871 
872 	/* We always ensure that STACK_DYNPTR is never set partially,
873 	 * hence just checking for slot_type[0] is enough. This is
874 	 * different for STACK_SPILL, where it may be only set for
875 	 * 1 byte, so code has to use is_spilled_reg.
876 	 */
877 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
878 		return 0;
879 
880 	/* Reposition spi to first slot */
881 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
882 		spi = spi + 1;
883 
884 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
885 		verbose(env, "cannot overwrite referenced dynptr\n");
886 		return -EINVAL;
887 	}
888 
889 	mark_stack_slot_scratched(env, spi);
890 	mark_stack_slot_scratched(env, spi - 1);
891 
892 	/* Writing partially to one dynptr stack slot destroys both. */
893 	for (i = 0; i < BPF_REG_SIZE; i++) {
894 		state->stack[spi].slot_type[i] = STACK_INVALID;
895 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
896 	}
897 
898 	dynptr_id = state->stack[spi].spilled_ptr.id;
899 	/* Invalidate any slices associated with this dynptr */
900 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
901 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
902 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
903 			continue;
904 		if (dreg->dynptr_id == dynptr_id)
905 			mark_reg_invalid(env, dreg);
906 	}));
907 
908 	/* Do not release reference state, we are destroying dynptr on stack,
909 	 * not using some helper to release it. Just reset register.
910 	 */
911 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
912 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
913 
914 	/* Same reason as unmark_stack_slots_dynptr above */
915 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
916 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
917 
918 	return 0;
919 }
920 
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 {
923 	int spi;
924 
925 	if (reg->type == CONST_PTR_TO_DYNPTR)
926 		return false;
927 
928 	spi = dynptr_get_spi(env, reg);
929 
930 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
931 	 * error because this just means the stack state hasn't been updated yet.
932 	 * We will do check_mem_access to check and update stack bounds later.
933 	 */
934 	if (spi < 0 && spi != -ERANGE)
935 		return false;
936 
937 	/* We don't need to check if the stack slots are marked by previous
938 	 * dynptr initializations because we allow overwriting existing unreferenced
939 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
940 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
941 	 * touching are completely destructed before we reinitialize them for a new
942 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
943 	 * instead of delaying it until the end where the user will get "Unreleased
944 	 * reference" error.
945 	 */
946 	return true;
947 }
948 
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
950 {
951 	struct bpf_func_state *state = func(env, reg);
952 	int i, spi;
953 
954 	/* This already represents first slot of initialized bpf_dynptr.
955 	 *
956 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
957 	 * check_func_arg_reg_off's logic, so we don't need to check its
958 	 * offset and alignment.
959 	 */
960 	if (reg->type == CONST_PTR_TO_DYNPTR)
961 		return true;
962 
963 	spi = dynptr_get_spi(env, reg);
964 	if (spi < 0)
965 		return false;
966 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
967 		return false;
968 
969 	for (i = 0; i < BPF_REG_SIZE; i++) {
970 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
971 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
972 			return false;
973 	}
974 
975 	return true;
976 }
977 
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
979 				    enum bpf_arg_type arg_type)
980 {
981 	struct bpf_func_state *state = func(env, reg);
982 	enum bpf_dynptr_type dynptr_type;
983 	int spi;
984 
985 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
986 	if (arg_type == ARG_PTR_TO_DYNPTR)
987 		return true;
988 
989 	dynptr_type = arg_to_dynptr_type(arg_type);
990 	if (reg->type == CONST_PTR_TO_DYNPTR) {
991 		return reg->dynptr.type == dynptr_type;
992 	} else {
993 		spi = dynptr_get_spi(env, reg);
994 		if (spi < 0)
995 			return false;
996 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
997 	}
998 }
999 
1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1001 
1002 static bool in_rcu_cs(struct bpf_verifier_env *env);
1003 
1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1005 
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)1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1007 				 struct bpf_kfunc_call_arg_meta *meta,
1008 				 struct bpf_reg_state *reg, int insn_idx,
1009 				 struct btf *btf, u32 btf_id, int nr_slots)
1010 {
1011 	struct bpf_func_state *state = func(env, reg);
1012 	int spi, i, j, id;
1013 
1014 	spi = iter_get_spi(env, reg, nr_slots);
1015 	if (spi < 0)
1016 		return spi;
1017 
1018 	id = acquire_reference_state(env, insn_idx);
1019 	if (id < 0)
1020 		return id;
1021 
1022 	for (i = 0; i < nr_slots; i++) {
1023 		struct bpf_stack_state *slot = &state->stack[spi - i];
1024 		struct bpf_reg_state *st = &slot->spilled_ptr;
1025 
1026 		__mark_reg_known_zero(st);
1027 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1028 		if (is_kfunc_rcu_protected(meta)) {
1029 			if (in_rcu_cs(env))
1030 				st->type |= MEM_RCU;
1031 			else
1032 				st->type |= PTR_UNTRUSTED;
1033 		}
1034 		st->live |= REG_LIVE_WRITTEN;
1035 		st->ref_obj_id = i == 0 ? id : 0;
1036 		st->iter.btf = btf;
1037 		st->iter.btf_id = btf_id;
1038 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1039 		st->iter.depth = 0;
1040 
1041 		for (j = 0; j < BPF_REG_SIZE; j++)
1042 			slot->slot_type[j] = STACK_ITER;
1043 
1044 		mark_stack_slot_scratched(env, spi - i);
1045 	}
1046 
1047 	return 0;
1048 }
1049 
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1050 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1051 				   struct bpf_reg_state *reg, int nr_slots)
1052 {
1053 	struct bpf_func_state *state = func(env, reg);
1054 	int spi, i, j;
1055 
1056 	spi = iter_get_spi(env, reg, nr_slots);
1057 	if (spi < 0)
1058 		return spi;
1059 
1060 	for (i = 0; i < nr_slots; i++) {
1061 		struct bpf_stack_state *slot = &state->stack[spi - i];
1062 		struct bpf_reg_state *st = &slot->spilled_ptr;
1063 
1064 		if (i == 0)
1065 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1066 
1067 		__mark_reg_not_init(env, st);
1068 
1069 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1070 		st->live |= REG_LIVE_WRITTEN;
1071 
1072 		for (j = 0; j < BPF_REG_SIZE; j++)
1073 			slot->slot_type[j] = STACK_INVALID;
1074 
1075 		mark_stack_slot_scratched(env, spi - i);
1076 	}
1077 
1078 	return 0;
1079 }
1080 
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1081 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1082 				     struct bpf_reg_state *reg, int nr_slots)
1083 {
1084 	struct bpf_func_state *state = func(env, reg);
1085 	int spi, i, j;
1086 
1087 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1088 	 * will do check_mem_access to check and update stack bounds later, so
1089 	 * return true for that case.
1090 	 */
1091 	spi = iter_get_spi(env, reg, nr_slots);
1092 	if (spi == -ERANGE)
1093 		return true;
1094 	if (spi < 0)
1095 		return false;
1096 
1097 	for (i = 0; i < nr_slots; i++) {
1098 		struct bpf_stack_state *slot = &state->stack[spi - i];
1099 
1100 		for (j = 0; j < BPF_REG_SIZE; j++)
1101 			if (slot->slot_type[j] == STACK_ITER)
1102 				return false;
1103 	}
1104 
1105 	return true;
1106 }
1107 
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1108 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1109 				   struct btf *btf, u32 btf_id, int nr_slots)
1110 {
1111 	struct bpf_func_state *state = func(env, reg);
1112 	int spi, i, j;
1113 
1114 	spi = iter_get_spi(env, reg, nr_slots);
1115 	if (spi < 0)
1116 		return -EINVAL;
1117 
1118 	for (i = 0; i < nr_slots; i++) {
1119 		struct bpf_stack_state *slot = &state->stack[spi - i];
1120 		struct bpf_reg_state *st = &slot->spilled_ptr;
1121 
1122 		if (st->type & PTR_UNTRUSTED)
1123 			return -EPROTO;
1124 		/* only main (first) slot has ref_obj_id set */
1125 		if (i == 0 && !st->ref_obj_id)
1126 			return -EINVAL;
1127 		if (i != 0 && st->ref_obj_id)
1128 			return -EINVAL;
1129 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1130 			return -EINVAL;
1131 
1132 		for (j = 0; j < BPF_REG_SIZE; j++)
1133 			if (slot->slot_type[j] != STACK_ITER)
1134 				return -EINVAL;
1135 	}
1136 
1137 	return 0;
1138 }
1139 
1140 /* Check if given stack slot is "special":
1141  *   - spilled register state (STACK_SPILL);
1142  *   - dynptr state (STACK_DYNPTR);
1143  *   - iter state (STACK_ITER).
1144  */
is_stack_slot_special(const struct bpf_stack_state * stack)1145 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1146 {
1147 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1148 
1149 	switch (type) {
1150 	case STACK_SPILL:
1151 	case STACK_DYNPTR:
1152 	case STACK_ITER:
1153 		return true;
1154 	case STACK_INVALID:
1155 	case STACK_MISC:
1156 	case STACK_ZERO:
1157 		return false;
1158 	default:
1159 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1160 		return true;
1161 	}
1162 }
1163 
1164 /* The reg state of a pointer or a bounded scalar was saved when
1165  * it was spilled to the stack.
1166  */
is_spilled_reg(const struct bpf_stack_state * stack)1167 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1168 {
1169 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1170 }
1171 
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1172 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1173 {
1174 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1175 	       stack->spilled_ptr.type == SCALAR_VALUE;
1176 }
1177 
is_spilled_scalar_reg64(const struct bpf_stack_state * stack)1178 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1179 {
1180 	return stack->slot_type[0] == STACK_SPILL &&
1181 	       stack->spilled_ptr.type == SCALAR_VALUE;
1182 }
1183 
1184 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1185  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1186  * more precise STACK_ZERO.
1187  * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take
1188  * env->allow_ptr_leaks into account and force STACK_MISC, if necessary.
1189  */
mark_stack_slot_misc(struct bpf_verifier_env * env,u8 * stype)1190 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1191 {
1192 	if (*stype == STACK_ZERO)
1193 		return;
1194 	if (env->allow_ptr_leaks && *stype == STACK_INVALID)
1195 		return;
1196 	*stype = STACK_MISC;
1197 }
1198 
scrub_spilled_slot(u8 * stype)1199 static void scrub_spilled_slot(u8 *stype)
1200 {
1201 	if (*stype != STACK_INVALID)
1202 		*stype = STACK_MISC;
1203 }
1204 
1205 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1206  * small to hold src. This is different from krealloc since we don't want to preserve
1207  * the contents of dst.
1208  *
1209  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1210  * not be allocated.
1211  */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1212 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1213 {
1214 	size_t alloc_bytes;
1215 	void *orig = dst;
1216 	size_t bytes;
1217 
1218 	if (ZERO_OR_NULL_PTR(src))
1219 		goto out;
1220 
1221 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1222 		return NULL;
1223 
1224 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1225 	dst = krealloc(orig, alloc_bytes, flags);
1226 	if (!dst) {
1227 		kfree(orig);
1228 		return NULL;
1229 	}
1230 
1231 	memcpy(dst, src, bytes);
1232 out:
1233 	return dst ? dst : ZERO_SIZE_PTR;
1234 }
1235 
1236 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1237  * small to hold new_n items. new items are zeroed out if the array grows.
1238  *
1239  * Contrary to krealloc_array, does not free arr if new_n is zero.
1240  */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1241 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1242 {
1243 	size_t alloc_size;
1244 	void *new_arr;
1245 
1246 	if (!new_n || old_n == new_n)
1247 		goto out;
1248 
1249 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1250 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1251 	if (!new_arr) {
1252 		kfree(arr);
1253 		return NULL;
1254 	}
1255 	arr = new_arr;
1256 
1257 	if (new_n > old_n)
1258 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1259 
1260 out:
1261 	return arr ? arr : ZERO_SIZE_PTR;
1262 }
1263 
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1264 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1265 {
1266 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1267 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1268 	if (!dst->refs)
1269 		return -ENOMEM;
1270 
1271 	dst->acquired_refs = src->acquired_refs;
1272 	return 0;
1273 }
1274 
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1275 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1276 {
1277 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1278 
1279 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1280 				GFP_KERNEL);
1281 	if (!dst->stack)
1282 		return -ENOMEM;
1283 
1284 	dst->allocated_stack = src->allocated_stack;
1285 	return 0;
1286 }
1287 
resize_reference_state(struct bpf_func_state * state,size_t n)1288 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1289 {
1290 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1291 				    sizeof(struct bpf_reference_state));
1292 	if (!state->refs)
1293 		return -ENOMEM;
1294 
1295 	state->acquired_refs = n;
1296 	return 0;
1297 }
1298 
1299 /* Possibly update state->allocated_stack to be at least size bytes. Also
1300  * possibly update the function's high-water mark in its bpf_subprog_info.
1301  */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1302 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1303 {
1304 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1305 
1306 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1307 	size = round_up(size, BPF_REG_SIZE);
1308 	n = size / BPF_REG_SIZE;
1309 
1310 	if (old_n >= n)
1311 		return 0;
1312 
1313 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1314 	if (!state->stack)
1315 		return -ENOMEM;
1316 
1317 	state->allocated_stack = size;
1318 
1319 	/* update known max for given subprogram */
1320 	if (env->subprog_info[state->subprogno].stack_depth < size)
1321 		env->subprog_info[state->subprogno].stack_depth = size;
1322 
1323 	return 0;
1324 }
1325 
1326 /* Acquire a pointer id from the env and update the state->refs to include
1327  * this new pointer reference.
1328  * On success, returns a valid pointer id to associate with the register
1329  * On failure, returns a negative errno.
1330  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1331 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1332 {
1333 	struct bpf_func_state *state = cur_func(env);
1334 	int new_ofs = state->acquired_refs;
1335 	int id, err;
1336 
1337 	err = resize_reference_state(state, state->acquired_refs + 1);
1338 	if (err)
1339 		return err;
1340 	id = ++env->id_gen;
1341 	state->refs[new_ofs].id = id;
1342 	state->refs[new_ofs].insn_idx = insn_idx;
1343 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1344 
1345 	return id;
1346 }
1347 
1348 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)1349 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1350 {
1351 	int i, last_idx;
1352 
1353 	last_idx = state->acquired_refs - 1;
1354 	for (i = 0; i < state->acquired_refs; i++) {
1355 		if (state->refs[i].id == ptr_id) {
1356 			/* Cannot release caller references in callbacks */
1357 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1358 				return -EINVAL;
1359 			if (last_idx && i != last_idx)
1360 				memcpy(&state->refs[i], &state->refs[last_idx],
1361 				       sizeof(*state->refs));
1362 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1363 			state->acquired_refs--;
1364 			return 0;
1365 		}
1366 	}
1367 	return -EINVAL;
1368 }
1369 
free_func_state(struct bpf_func_state * state)1370 static void free_func_state(struct bpf_func_state *state)
1371 {
1372 	if (!state)
1373 		return;
1374 	kfree(state->refs);
1375 	kfree(state->stack);
1376 	kfree(state);
1377 }
1378 
clear_jmp_history(struct bpf_verifier_state * state)1379 static void clear_jmp_history(struct bpf_verifier_state *state)
1380 {
1381 	kfree(state->jmp_history);
1382 	state->jmp_history = NULL;
1383 	state->jmp_history_cnt = 0;
1384 }
1385 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1386 static void free_verifier_state(struct bpf_verifier_state *state,
1387 				bool free_self)
1388 {
1389 	int i;
1390 
1391 	for (i = 0; i <= state->curframe; i++) {
1392 		free_func_state(state->frame[i]);
1393 		state->frame[i] = NULL;
1394 	}
1395 	clear_jmp_history(state);
1396 	if (free_self)
1397 		kfree(state);
1398 }
1399 
1400 /* copy verifier state from src to dst growing dst stack space
1401  * when necessary to accommodate larger src stack
1402  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1403 static int copy_func_state(struct bpf_func_state *dst,
1404 			   const struct bpf_func_state *src)
1405 {
1406 	int err;
1407 
1408 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1409 	err = copy_reference_state(dst, src);
1410 	if (err)
1411 		return err;
1412 	return copy_stack_state(dst, src);
1413 }
1414 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1415 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1416 			       const struct bpf_verifier_state *src)
1417 {
1418 	struct bpf_func_state *dst;
1419 	int i, err;
1420 
1421 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1422 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1423 					  GFP_USER);
1424 	if (!dst_state->jmp_history)
1425 		return -ENOMEM;
1426 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1427 
1428 	/* if dst has more stack frames then src frame, free them, this is also
1429 	 * necessary in case of exceptional exits using bpf_throw.
1430 	 */
1431 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1432 		free_func_state(dst_state->frame[i]);
1433 		dst_state->frame[i] = NULL;
1434 	}
1435 	dst_state->speculative = src->speculative;
1436 	dst_state->active_rcu_lock = src->active_rcu_lock;
1437 	dst_state->active_preempt_lock = src->active_preempt_lock;
1438 	dst_state->in_sleepable = src->in_sleepable;
1439 	dst_state->curframe = src->curframe;
1440 	dst_state->active_lock.ptr = src->active_lock.ptr;
1441 	dst_state->active_lock.id = src->active_lock.id;
1442 	dst_state->branches = src->branches;
1443 	dst_state->parent = src->parent;
1444 	dst_state->first_insn_idx = src->first_insn_idx;
1445 	dst_state->last_insn_idx = src->last_insn_idx;
1446 	dst_state->dfs_depth = src->dfs_depth;
1447 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1448 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1449 	dst_state->may_goto_depth = src->may_goto_depth;
1450 	for (i = 0; i <= src->curframe; i++) {
1451 		dst = dst_state->frame[i];
1452 		if (!dst) {
1453 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1454 			if (!dst)
1455 				return -ENOMEM;
1456 			dst_state->frame[i] = dst;
1457 		}
1458 		err = copy_func_state(dst, src->frame[i]);
1459 		if (err)
1460 			return err;
1461 	}
1462 	return 0;
1463 }
1464 
state_htab_size(struct bpf_verifier_env * env)1465 static u32 state_htab_size(struct bpf_verifier_env *env)
1466 {
1467 	return env->prog->len;
1468 }
1469 
explored_state(struct bpf_verifier_env * env,int idx)1470 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1471 {
1472 	struct bpf_verifier_state *cur = env->cur_state;
1473 	struct bpf_func_state *state = cur->frame[cur->curframe];
1474 
1475 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1476 }
1477 
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1478 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1479 {
1480 	int fr;
1481 
1482 	if (a->curframe != b->curframe)
1483 		return false;
1484 
1485 	for (fr = a->curframe; fr >= 0; fr--)
1486 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1487 			return false;
1488 
1489 	return true;
1490 }
1491 
1492 /* Open coded iterators allow back-edges in the state graph in order to
1493  * check unbounded loops that iterators.
1494  *
1495  * In is_state_visited() it is necessary to know if explored states are
1496  * part of some loops in order to decide whether non-exact states
1497  * comparison could be used:
1498  * - non-exact states comparison establishes sub-state relation and uses
1499  *   read and precision marks to do so, these marks are propagated from
1500  *   children states and thus are not guaranteed to be final in a loop;
1501  * - exact states comparison just checks if current and explored states
1502  *   are identical (and thus form a back-edge).
1503  *
1504  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1505  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1506  * algorithm for loop structure detection and gives an overview of
1507  * relevant terminology. It also has helpful illustrations.
1508  *
1509  * [1] https://api.semanticscholar.org/CorpusID:15784067
1510  *
1511  * We use a similar algorithm but because loop nested structure is
1512  * irrelevant for verifier ours is significantly simpler and resembles
1513  * strongly connected components algorithm from Sedgewick's textbook.
1514  *
1515  * Define topmost loop entry as a first node of the loop traversed in a
1516  * depth first search starting from initial state. The goal of the loop
1517  * tracking algorithm is to associate topmost loop entries with states
1518  * derived from these entries.
1519  *
1520  * For each step in the DFS states traversal algorithm needs to identify
1521  * the following situations:
1522  *
1523  *          initial                     initial                   initial
1524  *            |                           |                         |
1525  *            V                           V                         V
1526  *           ...                         ...           .---------> hdr
1527  *            |                           |            |            |
1528  *            V                           V            |            V
1529  *           cur                     .-> succ          |    .------...
1530  *            |                      |    |            |    |       |
1531  *            V                      |    V            |    V       V
1532  *           succ                    '-- cur           |   ...     ...
1533  *                                                     |    |       |
1534  *                                                     |    V       V
1535  *                                                     |   succ <- cur
1536  *                                                     |    |
1537  *                                                     |    V
1538  *                                                     |   ...
1539  *                                                     |    |
1540  *                                                     '----'
1541  *
1542  *  (A) successor state of cur   (B) successor state of cur or it's entry
1543  *      not yet traversed            are in current DFS path, thus cur and succ
1544  *                                   are members of the same outermost loop
1545  *
1546  *                      initial                  initial
1547  *                        |                        |
1548  *                        V                        V
1549  *                       ...                      ...
1550  *                        |                        |
1551  *                        V                        V
1552  *                .------...               .------...
1553  *                |       |                |       |
1554  *                V       V                V       V
1555  *           .-> hdr     ...              ...     ...
1556  *           |    |       |                |       |
1557  *           |    V       V                V       V
1558  *           |   succ <- cur              succ <- cur
1559  *           |    |                        |
1560  *           |    V                        V
1561  *           |   ...                      ...
1562  *           |    |                        |
1563  *           '----'                       exit
1564  *
1565  * (C) successor state of cur is a part of some loop but this loop
1566  *     does not include cur or successor state is not in a loop at all.
1567  *
1568  * Algorithm could be described as the following python code:
1569  *
1570  *     traversed = set()   # Set of traversed nodes
1571  *     entries = {}        # Mapping from node to loop entry
1572  *     depths = {}         # Depth level assigned to graph node
1573  *     path = set()        # Current DFS path
1574  *
1575  *     # Find outermost loop entry known for n
1576  *     def get_loop_entry(n):
1577  *         h = entries.get(n, None)
1578  *         while h in entries and entries[h] != h:
1579  *             h = entries[h]
1580  *         return h
1581  *
1582  *     # Update n's loop entry if h's outermost entry comes
1583  *     # before n's outermost entry in current DFS path.
1584  *     def update_loop_entry(n, h):
1585  *         n1 = get_loop_entry(n) or n
1586  *         h1 = get_loop_entry(h) or h
1587  *         if h1 in path and depths[h1] <= depths[n1]:
1588  *             entries[n] = h1
1589  *
1590  *     def dfs(n, depth):
1591  *         traversed.add(n)
1592  *         path.add(n)
1593  *         depths[n] = depth
1594  *         for succ in G.successors(n):
1595  *             if succ not in traversed:
1596  *                 # Case A: explore succ and update cur's loop entry
1597  *                 #         only if succ's entry is in current DFS path.
1598  *                 dfs(succ, depth + 1)
1599  *                 h = get_loop_entry(succ)
1600  *                 update_loop_entry(n, h)
1601  *             else:
1602  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1603  *                 update_loop_entry(n, succ)
1604  *         path.remove(n)
1605  *
1606  * To adapt this algorithm for use with verifier:
1607  * - use st->branch == 0 as a signal that DFS of succ had been finished
1608  *   and cur's loop entry has to be updated (case A), handle this in
1609  *   update_branch_counts();
1610  * - use st->branch > 0 as a signal that st is in the current DFS path;
1611  * - handle cases B and C in is_state_visited();
1612  * - update topmost loop entry for intermediate states in get_loop_entry().
1613  */
get_loop_entry(struct bpf_verifier_state * st)1614 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1615 {
1616 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1617 
1618 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1619 		topmost = topmost->loop_entry;
1620 	/* Update loop entries for intermediate states to avoid this
1621 	 * traversal in future get_loop_entry() calls.
1622 	 */
1623 	while (st && st->loop_entry != topmost) {
1624 		old = st->loop_entry;
1625 		st->loop_entry = topmost;
1626 		st = old;
1627 	}
1628 	return topmost;
1629 }
1630 
update_loop_entry(struct bpf_verifier_state * cur,struct bpf_verifier_state * hdr)1631 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1632 {
1633 	struct bpf_verifier_state *cur1, *hdr1;
1634 
1635 	cur1 = get_loop_entry(cur) ?: cur;
1636 	hdr1 = get_loop_entry(hdr) ?: hdr;
1637 	/* The head1->branches check decides between cases B and C in
1638 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1639 	 * head's topmost loop entry is not in current DFS path,
1640 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1641 	 * no need to update cur->loop_entry.
1642 	 */
1643 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1644 		cur->loop_entry = hdr;
1645 		hdr->used_as_loop_entry = true;
1646 	}
1647 }
1648 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1649 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1650 {
1651 	while (st) {
1652 		u32 br = --st->branches;
1653 
1654 		/* br == 0 signals that DFS exploration for 'st' is finished,
1655 		 * thus it is necessary to update parent's loop entry if it
1656 		 * turned out that st is a part of some loop.
1657 		 * This is a part of 'case A' in get_loop_entry() comment.
1658 		 */
1659 		if (br == 0 && st->parent && st->loop_entry)
1660 			update_loop_entry(st->parent, st->loop_entry);
1661 
1662 		/* WARN_ON(br > 1) technically makes sense here,
1663 		 * but see comment in push_stack(), hence:
1664 		 */
1665 		WARN_ONCE((int)br < 0,
1666 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1667 			  br);
1668 		if (br)
1669 			break;
1670 		st = st->parent;
1671 	}
1672 }
1673 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)1674 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1675 		     int *insn_idx, bool pop_log)
1676 {
1677 	struct bpf_verifier_state *cur = env->cur_state;
1678 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1679 	int err;
1680 
1681 	if (env->head == NULL)
1682 		return -ENOENT;
1683 
1684 	if (cur) {
1685 		err = copy_verifier_state(cur, &head->st);
1686 		if (err)
1687 			return err;
1688 	}
1689 	if (pop_log)
1690 		bpf_vlog_reset(&env->log, head->log_pos);
1691 	if (insn_idx)
1692 		*insn_idx = head->insn_idx;
1693 	if (prev_insn_idx)
1694 		*prev_insn_idx = head->prev_insn_idx;
1695 	elem = head->next;
1696 	free_verifier_state(&head->st, false);
1697 	kfree(head);
1698 	env->head = elem;
1699 	env->stack_size--;
1700 	return 0;
1701 }
1702 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)1703 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1704 					     int insn_idx, int prev_insn_idx,
1705 					     bool speculative)
1706 {
1707 	struct bpf_verifier_state *cur = env->cur_state;
1708 	struct bpf_verifier_stack_elem *elem;
1709 	int err;
1710 
1711 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1712 	if (!elem)
1713 		goto err;
1714 
1715 	elem->insn_idx = insn_idx;
1716 	elem->prev_insn_idx = prev_insn_idx;
1717 	elem->next = env->head;
1718 	elem->log_pos = env->log.end_pos;
1719 	env->head = elem;
1720 	env->stack_size++;
1721 	err = copy_verifier_state(&elem->st, cur);
1722 	if (err)
1723 		goto err;
1724 	elem->st.speculative |= speculative;
1725 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1726 		verbose(env, "The sequence of %d jumps is too complex.\n",
1727 			env->stack_size);
1728 		goto err;
1729 	}
1730 	if (elem->st.parent) {
1731 		++elem->st.parent->branches;
1732 		/* WARN_ON(branches > 2) technically makes sense here,
1733 		 * but
1734 		 * 1. speculative states will bump 'branches' for non-branch
1735 		 * instructions
1736 		 * 2. is_state_visited() heuristics may decide not to create
1737 		 * a new state for a sequence of branches and all such current
1738 		 * and cloned states will be pointing to a single parent state
1739 		 * which might have large 'branches' count.
1740 		 */
1741 	}
1742 	return &elem->st;
1743 err:
1744 	free_verifier_state(env->cur_state, true);
1745 	env->cur_state = NULL;
1746 	/* pop all elements and return */
1747 	while (!pop_stack(env, NULL, NULL, false));
1748 	return NULL;
1749 }
1750 
1751 #define CALLER_SAVED_REGS 6
1752 static const int caller_saved[CALLER_SAVED_REGS] = {
1753 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1754 };
1755 
1756 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1757 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1758 {
1759 	reg->var_off = tnum_const(imm);
1760 	reg->smin_value = (s64)imm;
1761 	reg->smax_value = (s64)imm;
1762 	reg->umin_value = imm;
1763 	reg->umax_value = imm;
1764 
1765 	reg->s32_min_value = (s32)imm;
1766 	reg->s32_max_value = (s32)imm;
1767 	reg->u32_min_value = (u32)imm;
1768 	reg->u32_max_value = (u32)imm;
1769 }
1770 
1771 /* Mark the unknown part of a register (variable offset or scalar value) as
1772  * known to have the value @imm.
1773  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1774 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1775 {
1776 	/* Clear off and union(map_ptr, range) */
1777 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1778 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1779 	reg->id = 0;
1780 	reg->ref_obj_id = 0;
1781 	___mark_reg_known(reg, imm);
1782 }
1783 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1784 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1785 {
1786 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1787 	reg->s32_min_value = (s32)imm;
1788 	reg->s32_max_value = (s32)imm;
1789 	reg->u32_min_value = (u32)imm;
1790 	reg->u32_max_value = (u32)imm;
1791 }
1792 
1793 /* Mark the 'variable offset' part of a register as zero.  This should be
1794  * used only on registers holding a pointer type.
1795  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1796 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1797 {
1798 	__mark_reg_known(reg, 0);
1799 }
1800 
__mark_reg_const_zero(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1801 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1802 {
1803 	__mark_reg_known(reg, 0);
1804 	reg->type = SCALAR_VALUE;
1805 	/* all scalars are assumed imprecise initially (unless unprivileged,
1806 	 * in which case everything is forced to be precise)
1807 	 */
1808 	reg->precise = !env->bpf_capable;
1809 }
1810 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1811 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1812 				struct bpf_reg_state *regs, u32 regno)
1813 {
1814 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1815 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1816 		/* Something bad happened, let's kill all regs */
1817 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1818 			__mark_reg_not_init(env, regs + regno);
1819 		return;
1820 	}
1821 	__mark_reg_known_zero(regs + regno);
1822 }
1823 
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)1824 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1825 			      bool first_slot, int dynptr_id)
1826 {
1827 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1828 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1829 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1830 	 */
1831 	__mark_reg_known_zero(reg);
1832 	reg->type = CONST_PTR_TO_DYNPTR;
1833 	/* Give each dynptr a unique id to uniquely associate slices to it. */
1834 	reg->id = dynptr_id;
1835 	reg->dynptr.type = type;
1836 	reg->dynptr.first_slot = first_slot;
1837 }
1838 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)1839 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1840 {
1841 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1842 		const struct bpf_map *map = reg->map_ptr;
1843 
1844 		if (map->inner_map_meta) {
1845 			reg->type = CONST_PTR_TO_MAP;
1846 			reg->map_ptr = map->inner_map_meta;
1847 			/* transfer reg's id which is unique for every map_lookup_elem
1848 			 * as UID of the inner map.
1849 			 */
1850 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1851 				reg->map_uid = reg->id;
1852 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
1853 				reg->map_uid = reg->id;
1854 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1855 			reg->type = PTR_TO_XDP_SOCK;
1856 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1857 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1858 			reg->type = PTR_TO_SOCKET;
1859 		} else {
1860 			reg->type = PTR_TO_MAP_VALUE;
1861 		}
1862 		return;
1863 	}
1864 
1865 	reg->type &= ~PTR_MAYBE_NULL;
1866 }
1867 
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)1868 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1869 				struct btf_field_graph_root *ds_head)
1870 {
1871 	__mark_reg_known_zero(&regs[regno]);
1872 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1873 	regs[regno].btf = ds_head->btf;
1874 	regs[regno].btf_id = ds_head->value_btf_id;
1875 	regs[regno].off = ds_head->node_offset;
1876 }
1877 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1878 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1879 {
1880 	return type_is_pkt_pointer(reg->type);
1881 }
1882 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1883 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1884 {
1885 	return reg_is_pkt_pointer(reg) ||
1886 	       reg->type == PTR_TO_PACKET_END;
1887 }
1888 
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)1889 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1890 {
1891 	return base_type(reg->type) == PTR_TO_MEM &&
1892 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1893 }
1894 
1895 /* 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)1896 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1897 				    enum bpf_reg_type which)
1898 {
1899 	/* The register can already have a range from prior markings.
1900 	 * This is fine as long as it hasn't been advanced from its
1901 	 * origin.
1902 	 */
1903 	return reg->type == which &&
1904 	       reg->id == 0 &&
1905 	       reg->off == 0 &&
1906 	       tnum_equals_const(reg->var_off, 0);
1907 }
1908 
1909 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1910 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1911 {
1912 	reg->smin_value = S64_MIN;
1913 	reg->smax_value = S64_MAX;
1914 	reg->umin_value = 0;
1915 	reg->umax_value = U64_MAX;
1916 
1917 	reg->s32_min_value = S32_MIN;
1918 	reg->s32_max_value = S32_MAX;
1919 	reg->u32_min_value = 0;
1920 	reg->u32_max_value = U32_MAX;
1921 }
1922 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1923 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1924 {
1925 	reg->smin_value = S64_MIN;
1926 	reg->smax_value = S64_MAX;
1927 	reg->umin_value = 0;
1928 	reg->umax_value = U64_MAX;
1929 }
1930 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1931 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1932 {
1933 	reg->s32_min_value = S32_MIN;
1934 	reg->s32_max_value = S32_MAX;
1935 	reg->u32_min_value = 0;
1936 	reg->u32_max_value = U32_MAX;
1937 }
1938 
__update_reg32_bounds(struct bpf_reg_state * reg)1939 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1940 {
1941 	struct tnum var32_off = tnum_subreg(reg->var_off);
1942 
1943 	/* min signed is max(sign bit) | min(other bits) */
1944 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1945 			var32_off.value | (var32_off.mask & S32_MIN));
1946 	/* max signed is min(sign bit) | max(other bits) */
1947 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1948 			var32_off.value | (var32_off.mask & S32_MAX));
1949 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1950 	reg->u32_max_value = min(reg->u32_max_value,
1951 				 (u32)(var32_off.value | var32_off.mask));
1952 }
1953 
__update_reg64_bounds(struct bpf_reg_state * reg)1954 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1955 {
1956 	/* min signed is max(sign bit) | min(other bits) */
1957 	reg->smin_value = max_t(s64, reg->smin_value,
1958 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1959 	/* max signed is min(sign bit) | max(other bits) */
1960 	reg->smax_value = min_t(s64, reg->smax_value,
1961 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1962 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1963 	reg->umax_value = min(reg->umax_value,
1964 			      reg->var_off.value | reg->var_off.mask);
1965 }
1966 
__update_reg_bounds(struct bpf_reg_state * reg)1967 static void __update_reg_bounds(struct bpf_reg_state *reg)
1968 {
1969 	__update_reg32_bounds(reg);
1970 	__update_reg64_bounds(reg);
1971 }
1972 
1973 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1974 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1975 {
1976 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
1977 	 * bits to improve our u32/s32 boundaries.
1978 	 *
1979 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
1980 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
1981 	 * [10, 20] range. But this property holds for any 64-bit range as
1982 	 * long as upper 32 bits in that entire range of values stay the same.
1983 	 *
1984 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
1985 	 * in decimal) has the same upper 32 bits throughout all the values in
1986 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
1987 	 * range.
1988 	 *
1989 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
1990 	 * following the rules outlined below about u64/s64 correspondence
1991 	 * (which equally applies to u32 vs s32 correspondence). In general it
1992 	 * depends on actual hexadecimal values of 32-bit range. They can form
1993 	 * only valid u32, or only valid s32 ranges in some cases.
1994 	 *
1995 	 * So we use all these insights to derive bounds for subregisters here.
1996 	 */
1997 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
1998 		/* u64 to u32 casting preserves validity of low 32 bits as
1999 		 * a range, if upper 32 bits are the same
2000 		 */
2001 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2002 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2003 
2004 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2005 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2006 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2007 		}
2008 	}
2009 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2010 		/* low 32 bits should form a proper u32 range */
2011 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2012 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2013 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2014 		}
2015 		/* low 32 bits should form a proper s32 range */
2016 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2017 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2018 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2019 		}
2020 	}
2021 	/* Special case where upper bits form a small sequence of two
2022 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2023 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2024 	 * going from negative numbers to positive numbers. E.g., let's say we
2025 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2026 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2027 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2028 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2029 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2030 	 * upper 32 bits. As a random example, s64 range
2031 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2032 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2033 	 */
2034 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2035 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2036 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2037 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2038 	}
2039 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2040 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2041 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2042 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2043 	}
2044 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2045 	 * try to learn from that
2046 	 */
2047 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2048 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2049 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2050 	}
2051 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2052 	 * are the same, so combine.  This works even in the negative case, e.g.
2053 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2054 	 */
2055 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2056 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2057 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2058 	}
2059 }
2060 
__reg64_deduce_bounds(struct bpf_reg_state * reg)2061 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2062 {
2063 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2064 	 * try to learn from that. Let's do a bit of ASCII art to see when
2065 	 * this is happening. Let's take u64 range first:
2066 	 *
2067 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2068 	 * |-------------------------------|--------------------------------|
2069 	 *
2070 	 * Valid u64 range is formed when umin and umax are anywhere in the
2071 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2072 	 * straightforward. Let's see how s64 range maps onto the same range
2073 	 * of values, annotated below the line for comparison:
2074 	 *
2075 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2076 	 * |-------------------------------|--------------------------------|
2077 	 * 0                        S64_MAX S64_MIN                        -1
2078 	 *
2079 	 * So s64 values basically start in the middle and they are logically
2080 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2081 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2082 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2083 	 * more visually as mapped to sign-agnostic range of hex values.
2084 	 *
2085 	 *  u64 start                                               u64 end
2086 	 *  _______________________________________________________________
2087 	 * /                                                               \
2088 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2089 	 * |-------------------------------|--------------------------------|
2090 	 * 0                        S64_MAX S64_MIN                        -1
2091 	 *                                / \
2092 	 * >------------------------------   ------------------------------->
2093 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2094 	 *
2095 	 * What this means is that, in general, we can't always derive
2096 	 * something new about u64 from any random s64 range, and vice versa.
2097 	 *
2098 	 * But we can do that in two particular cases. One is when entire
2099 	 * u64/s64 range is *entirely* contained within left half of the above
2100 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2101 	 *
2102 	 * |-------------------------------|--------------------------------|
2103 	 *     ^                   ^            ^                 ^
2104 	 *     A                   B            C                 D
2105 	 *
2106 	 * [A, B] and [C, D] are contained entirely in their respective halves
2107 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2108 	 * will be non-negative both as u64 and s64 (and in fact it will be
2109 	 * identical ranges no matter the signedness). [C, D] treated as s64
2110 	 * will be a range of negative values, while in u64 it will be
2111 	 * non-negative range of values larger than 0x8000000000000000.
2112 	 *
2113 	 * Now, any other range here can't be represented in both u64 and s64
2114 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2115 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2116 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2117 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2118 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2119 	 * ranges as u64. Currently reg_state can't represent two segments per
2120 	 * numeric domain, so in such situations we can only derive maximal
2121 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2122 	 *
2123 	 * So we use these facts to derive umin/umax from smin/smax and vice
2124 	 * versa only if they stay within the same "half". This is equivalent
2125 	 * to checking sign bit: lower half will have sign bit as zero, upper
2126 	 * half have sign bit 1. Below in code we simplify this by just
2127 	 * casting umin/umax as smin/smax and checking if they form valid
2128 	 * range, and vice versa. Those are equivalent checks.
2129 	 */
2130 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2131 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2132 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2133 	}
2134 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2135 	 * are the same, so combine.  This works even in the negative case, e.g.
2136 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2137 	 */
2138 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2139 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2140 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2141 	}
2142 }
2143 
__reg_deduce_mixed_bounds(struct bpf_reg_state * reg)2144 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2145 {
2146 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2147 	 * values on both sides of 64-bit range in hope to have tighter range.
2148 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2149 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2150 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2151 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2152 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2153 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2154 	 * We just need to make sure that derived bounds we are intersecting
2155 	 * with are well-formed ranges in respective s64 or u64 domain, just
2156 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2157 	 */
2158 	__u64 new_umin, new_umax;
2159 	__s64 new_smin, new_smax;
2160 
2161 	/* u32 -> u64 tightening, it's always well-formed */
2162 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2163 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2164 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2165 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2166 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2167 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2168 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2169 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2170 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2171 
2172 	/* if s32 can be treated as valid u32 range, we can use it as well */
2173 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2174 		/* s32 -> u64 tightening */
2175 		new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2176 		new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2177 		reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2178 		reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2179 		/* s32 -> s64 tightening */
2180 		new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value;
2181 		new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value;
2182 		reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2183 		reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2184 	}
2185 }
2186 
__reg_deduce_bounds(struct bpf_reg_state * reg)2187 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2188 {
2189 	__reg32_deduce_bounds(reg);
2190 	__reg64_deduce_bounds(reg);
2191 	__reg_deduce_mixed_bounds(reg);
2192 }
2193 
2194 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2195 static void __reg_bound_offset(struct bpf_reg_state *reg)
2196 {
2197 	struct tnum var64_off = tnum_intersect(reg->var_off,
2198 					       tnum_range(reg->umin_value,
2199 							  reg->umax_value));
2200 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2201 					       tnum_range(reg->u32_min_value,
2202 							  reg->u32_max_value));
2203 
2204 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2205 }
2206 
reg_bounds_sync(struct bpf_reg_state * reg)2207 static void reg_bounds_sync(struct bpf_reg_state *reg)
2208 {
2209 	/* We might have learned new bounds from the var_off. */
2210 	__update_reg_bounds(reg);
2211 	/* We might have learned something about the sign bit. */
2212 	__reg_deduce_bounds(reg);
2213 	__reg_deduce_bounds(reg);
2214 	/* We might have learned some bits from the bounds. */
2215 	__reg_bound_offset(reg);
2216 	/* Intersecting with the old var_off might have improved our bounds
2217 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2218 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2219 	 */
2220 	__update_reg_bounds(reg);
2221 }
2222 
reg_bounds_sanity_check(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * ctx)2223 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2224 				   struct bpf_reg_state *reg, const char *ctx)
2225 {
2226 	const char *msg;
2227 
2228 	if (reg->umin_value > reg->umax_value ||
2229 	    reg->smin_value > reg->smax_value ||
2230 	    reg->u32_min_value > reg->u32_max_value ||
2231 	    reg->s32_min_value > reg->s32_max_value) {
2232 		    msg = "range bounds violation";
2233 		    goto out;
2234 	}
2235 
2236 	if (tnum_is_const(reg->var_off)) {
2237 		u64 uval = reg->var_off.value;
2238 		s64 sval = (s64)uval;
2239 
2240 		if (reg->umin_value != uval || reg->umax_value != uval ||
2241 		    reg->smin_value != sval || reg->smax_value != sval) {
2242 			msg = "const tnum out of sync with range bounds";
2243 			goto out;
2244 		}
2245 	}
2246 
2247 	if (tnum_subreg_is_const(reg->var_off)) {
2248 		u32 uval32 = tnum_subreg(reg->var_off).value;
2249 		s32 sval32 = (s32)uval32;
2250 
2251 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2252 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2253 			msg = "const subreg tnum out of sync with range bounds";
2254 			goto out;
2255 		}
2256 	}
2257 
2258 	return 0;
2259 out:
2260 	verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2261 		"s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n",
2262 		ctx, msg, reg->umin_value, reg->umax_value,
2263 		reg->smin_value, reg->smax_value,
2264 		reg->u32_min_value, reg->u32_max_value,
2265 		reg->s32_min_value, reg->s32_max_value,
2266 		reg->var_off.value, reg->var_off.mask);
2267 	if (env->test_reg_invariants)
2268 		return -EFAULT;
2269 	__mark_reg_unbounded(reg);
2270 	return 0;
2271 }
2272 
__reg32_bound_s64(s32 a)2273 static bool __reg32_bound_s64(s32 a)
2274 {
2275 	return a >= 0 && a <= S32_MAX;
2276 }
2277 
__reg_assign_32_into_64(struct bpf_reg_state * reg)2278 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2279 {
2280 	reg->umin_value = reg->u32_min_value;
2281 	reg->umax_value = reg->u32_max_value;
2282 
2283 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2284 	 * be positive otherwise set to worse case bounds and refine later
2285 	 * from tnum.
2286 	 */
2287 	if (__reg32_bound_s64(reg->s32_min_value) &&
2288 	    __reg32_bound_s64(reg->s32_max_value)) {
2289 		reg->smin_value = reg->s32_min_value;
2290 		reg->smax_value = reg->s32_max_value;
2291 	} else {
2292 		reg->smin_value = 0;
2293 		reg->smax_value = U32_MAX;
2294 	}
2295 }
2296 
2297 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown_imprecise(struct bpf_reg_state * reg)2298 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2299 {
2300 	/*
2301 	 * Clear type, off, and union(map_ptr, range) and
2302 	 * padding between 'type' and union
2303 	 */
2304 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2305 	reg->type = SCALAR_VALUE;
2306 	reg->id = 0;
2307 	reg->ref_obj_id = 0;
2308 	reg->var_off = tnum_unknown;
2309 	reg->frameno = 0;
2310 	reg->precise = false;
2311 	__mark_reg_unbounded(reg);
2312 }
2313 
2314 /* Mark a register as having a completely unknown (scalar) value,
2315  * initialize .precise as true when not bpf capable.
2316  */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2317 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2318 			       struct bpf_reg_state *reg)
2319 {
2320 	__mark_reg_unknown_imprecise(reg);
2321 	reg->precise = !env->bpf_capable;
2322 }
2323 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2324 static void mark_reg_unknown(struct bpf_verifier_env *env,
2325 			     struct bpf_reg_state *regs, u32 regno)
2326 {
2327 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2328 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2329 		/* Something bad happened, let's kill all regs except FP */
2330 		for (regno = 0; regno < BPF_REG_FP; regno++)
2331 			__mark_reg_not_init(env, regs + regno);
2332 		return;
2333 	}
2334 	__mark_reg_unknown(env, regs + regno);
2335 }
2336 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2337 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2338 				struct bpf_reg_state *reg)
2339 {
2340 	__mark_reg_unknown(env, reg);
2341 	reg->type = NOT_INIT;
2342 }
2343 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2344 static void mark_reg_not_init(struct bpf_verifier_env *env,
2345 			      struct bpf_reg_state *regs, u32 regno)
2346 {
2347 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2348 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2349 		/* Something bad happened, let's kill all regs except FP */
2350 		for (regno = 0; regno < BPF_REG_FP; regno++)
2351 			__mark_reg_not_init(env, regs + regno);
2352 		return;
2353 	}
2354 	__mark_reg_not_init(env, regs + regno);
2355 }
2356 
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)2357 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2358 			    struct bpf_reg_state *regs, u32 regno,
2359 			    enum bpf_reg_type reg_type,
2360 			    struct btf *btf, u32 btf_id,
2361 			    enum bpf_type_flag flag)
2362 {
2363 	if (reg_type == SCALAR_VALUE) {
2364 		mark_reg_unknown(env, regs, regno);
2365 		return;
2366 	}
2367 	mark_reg_known_zero(env, regs, regno);
2368 	regs[regno].type = PTR_TO_BTF_ID | flag;
2369 	regs[regno].btf = btf;
2370 	regs[regno].btf_id = btf_id;
2371 	if (type_may_be_null(flag))
2372 		regs[regno].id = ++env->id_gen;
2373 }
2374 
2375 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2376 static void init_reg_state(struct bpf_verifier_env *env,
2377 			   struct bpf_func_state *state)
2378 {
2379 	struct bpf_reg_state *regs = state->regs;
2380 	int i;
2381 
2382 	for (i = 0; i < MAX_BPF_REG; i++) {
2383 		mark_reg_not_init(env, regs, i);
2384 		regs[i].live = REG_LIVE_NONE;
2385 		regs[i].parent = NULL;
2386 		regs[i].subreg_def = DEF_NOT_SUBREG;
2387 	}
2388 
2389 	/* frame pointer */
2390 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2391 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2392 	regs[BPF_REG_FP].frameno = state->frameno;
2393 }
2394 
retval_range(s32 minval,s32 maxval)2395 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2396 {
2397 	return (struct bpf_retval_range){ minval, maxval };
2398 }
2399 
2400 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2401 static void init_func_state(struct bpf_verifier_env *env,
2402 			    struct bpf_func_state *state,
2403 			    int callsite, int frameno, int subprogno)
2404 {
2405 	state->callsite = callsite;
2406 	state->frameno = frameno;
2407 	state->subprogno = subprogno;
2408 	state->callback_ret_range = retval_range(0, 0);
2409 	init_reg_state(env, state);
2410 	mark_verifier_state_scratched(env);
2411 }
2412 
2413 /* 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)2414 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2415 						int insn_idx, int prev_insn_idx,
2416 						int subprog, bool is_sleepable)
2417 {
2418 	struct bpf_verifier_stack_elem *elem;
2419 	struct bpf_func_state *frame;
2420 
2421 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2422 	if (!elem)
2423 		goto err;
2424 
2425 	elem->insn_idx = insn_idx;
2426 	elem->prev_insn_idx = prev_insn_idx;
2427 	elem->next = env->head;
2428 	elem->log_pos = env->log.end_pos;
2429 	env->head = elem;
2430 	env->stack_size++;
2431 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2432 		verbose(env,
2433 			"The sequence of %d jumps is too complex for async cb.\n",
2434 			env->stack_size);
2435 		goto err;
2436 	}
2437 	/* Unlike push_stack() do not copy_verifier_state().
2438 	 * The caller state doesn't matter.
2439 	 * This is async callback. It starts in a fresh stack.
2440 	 * Initialize it similar to do_check_common().
2441 	 */
2442 	elem->st.branches = 1;
2443 	elem->st.in_sleepable = is_sleepable;
2444 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2445 	if (!frame)
2446 		goto err;
2447 	init_func_state(env, frame,
2448 			BPF_MAIN_FUNC /* callsite */,
2449 			0 /* frameno within this callchain */,
2450 			subprog /* subprog number within this prog */);
2451 	elem->st.frame[0] = frame;
2452 	return &elem->st;
2453 err:
2454 	free_verifier_state(env->cur_state, true);
2455 	env->cur_state = NULL;
2456 	/* pop all elements and return */
2457 	while (!pop_stack(env, NULL, NULL, false));
2458 	return NULL;
2459 }
2460 
2461 
2462 enum reg_arg_type {
2463 	SRC_OP,		/* register is used as source operand */
2464 	DST_OP,		/* register is used as destination operand */
2465 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2466 };
2467 
cmp_subprogs(const void * a,const void * b)2468 static int cmp_subprogs(const void *a, const void *b)
2469 {
2470 	return ((struct bpf_subprog_info *)a)->start -
2471 	       ((struct bpf_subprog_info *)b)->start;
2472 }
2473 
find_subprog(struct bpf_verifier_env * env,int off)2474 static int find_subprog(struct bpf_verifier_env *env, int off)
2475 {
2476 	struct bpf_subprog_info *p;
2477 
2478 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2479 		    sizeof(env->subprog_info[0]), cmp_subprogs);
2480 	if (!p)
2481 		return -ENOENT;
2482 	return p - env->subprog_info;
2483 
2484 }
2485 
add_subprog(struct bpf_verifier_env * env,int off)2486 static int add_subprog(struct bpf_verifier_env *env, int off)
2487 {
2488 	int insn_cnt = env->prog->len;
2489 	int ret;
2490 
2491 	if (off >= insn_cnt || off < 0) {
2492 		verbose(env, "call to invalid destination\n");
2493 		return -EINVAL;
2494 	}
2495 	ret = find_subprog(env, off);
2496 	if (ret >= 0)
2497 		return ret;
2498 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2499 		verbose(env, "too many subprograms\n");
2500 		return -E2BIG;
2501 	}
2502 	/* determine subprog starts. The end is one before the next starts */
2503 	env->subprog_info[env->subprog_cnt++].start = off;
2504 	sort(env->subprog_info, env->subprog_cnt,
2505 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2506 	return env->subprog_cnt - 1;
2507 }
2508 
bpf_find_exception_callback_insn_off(struct bpf_verifier_env * env)2509 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2510 {
2511 	struct bpf_prog_aux *aux = env->prog->aux;
2512 	struct btf *btf = aux->btf;
2513 	const struct btf_type *t;
2514 	u32 main_btf_id, id;
2515 	const char *name;
2516 	int ret, i;
2517 
2518 	/* Non-zero func_info_cnt implies valid btf */
2519 	if (!aux->func_info_cnt)
2520 		return 0;
2521 	main_btf_id = aux->func_info[0].type_id;
2522 
2523 	t = btf_type_by_id(btf, main_btf_id);
2524 	if (!t) {
2525 		verbose(env, "invalid btf id for main subprog in func_info\n");
2526 		return -EINVAL;
2527 	}
2528 
2529 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2530 	if (IS_ERR(name)) {
2531 		ret = PTR_ERR(name);
2532 		/* If there is no tag present, there is no exception callback */
2533 		if (ret == -ENOENT)
2534 			ret = 0;
2535 		else if (ret == -EEXIST)
2536 			verbose(env, "multiple exception callback tags for main subprog\n");
2537 		return ret;
2538 	}
2539 
2540 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2541 	if (ret < 0) {
2542 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2543 		return ret;
2544 	}
2545 	id = ret;
2546 	t = btf_type_by_id(btf, id);
2547 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2548 		verbose(env, "exception callback '%s' must have global linkage\n", name);
2549 		return -EINVAL;
2550 	}
2551 	ret = 0;
2552 	for (i = 0; i < aux->func_info_cnt; i++) {
2553 		if (aux->func_info[i].type_id != id)
2554 			continue;
2555 		ret = aux->func_info[i].insn_off;
2556 		/* Further func_info and subprog checks will also happen
2557 		 * later, so assume this is the right insn_off for now.
2558 		 */
2559 		if (!ret) {
2560 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2561 			ret = -EINVAL;
2562 		}
2563 	}
2564 	if (!ret) {
2565 		verbose(env, "exception callback type id not found in func_info\n");
2566 		ret = -EINVAL;
2567 	}
2568 	return ret;
2569 }
2570 
2571 #define MAX_KFUNC_DESCS 256
2572 #define MAX_KFUNC_BTFS	256
2573 
2574 struct bpf_kfunc_desc {
2575 	struct btf_func_model func_model;
2576 	u32 func_id;
2577 	s32 imm;
2578 	u16 offset;
2579 	unsigned long addr;
2580 };
2581 
2582 struct bpf_kfunc_btf {
2583 	struct btf *btf;
2584 	struct module *module;
2585 	u16 offset;
2586 };
2587 
2588 struct bpf_kfunc_desc_tab {
2589 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2590 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2591 	 * available, therefore at the end of verification do_misc_fixups()
2592 	 * sorts this by imm and offset.
2593 	 */
2594 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2595 	u32 nr_descs;
2596 };
2597 
2598 struct bpf_kfunc_btf_tab {
2599 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2600 	u32 nr_descs;
2601 };
2602 
kfunc_desc_cmp_by_id_off(const void * a,const void * b)2603 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2604 {
2605 	const struct bpf_kfunc_desc *d0 = a;
2606 	const struct bpf_kfunc_desc *d1 = b;
2607 
2608 	/* func_id is not greater than BTF_MAX_TYPE */
2609 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2610 }
2611 
kfunc_btf_cmp_by_off(const void * a,const void * b)2612 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2613 {
2614 	const struct bpf_kfunc_btf *d0 = a;
2615 	const struct bpf_kfunc_btf *d1 = b;
2616 
2617 	return d0->offset - d1->offset;
2618 }
2619 
2620 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)2621 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2622 {
2623 	struct bpf_kfunc_desc desc = {
2624 		.func_id = func_id,
2625 		.offset = offset,
2626 	};
2627 	struct bpf_kfunc_desc_tab *tab;
2628 
2629 	tab = prog->aux->kfunc_tab;
2630 	return bsearch(&desc, tab->descs, tab->nr_descs,
2631 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2632 }
2633 
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)2634 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2635 		       u16 btf_fd_idx, u8 **func_addr)
2636 {
2637 	const struct bpf_kfunc_desc *desc;
2638 
2639 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2640 	if (!desc)
2641 		return -EFAULT;
2642 
2643 	*func_addr = (u8 *)desc->addr;
2644 	return 0;
2645 }
2646 
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2647 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2648 					 s16 offset)
2649 {
2650 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2651 	struct bpf_kfunc_btf_tab *tab;
2652 	struct bpf_kfunc_btf *b;
2653 	struct module *mod;
2654 	struct btf *btf;
2655 	int btf_fd;
2656 
2657 	tab = env->prog->aux->kfunc_btf_tab;
2658 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2659 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2660 	if (!b) {
2661 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2662 			verbose(env, "too many different module BTFs\n");
2663 			return ERR_PTR(-E2BIG);
2664 		}
2665 
2666 		if (bpfptr_is_null(env->fd_array)) {
2667 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2668 			return ERR_PTR(-EPROTO);
2669 		}
2670 
2671 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2672 					    offset * sizeof(btf_fd),
2673 					    sizeof(btf_fd)))
2674 			return ERR_PTR(-EFAULT);
2675 
2676 		btf = btf_get_by_fd(btf_fd);
2677 		if (IS_ERR(btf)) {
2678 			verbose(env, "invalid module BTF fd specified\n");
2679 			return btf;
2680 		}
2681 
2682 		if (!btf_is_module(btf)) {
2683 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2684 			btf_put(btf);
2685 			return ERR_PTR(-EINVAL);
2686 		}
2687 
2688 		mod = btf_try_get_module(btf);
2689 		if (!mod) {
2690 			btf_put(btf);
2691 			return ERR_PTR(-ENXIO);
2692 		}
2693 
2694 		b = &tab->descs[tab->nr_descs++];
2695 		b->btf = btf;
2696 		b->module = mod;
2697 		b->offset = offset;
2698 
2699 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2700 		     kfunc_btf_cmp_by_off, NULL);
2701 	}
2702 	return b->btf;
2703 }
2704 
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)2705 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2706 {
2707 	if (!tab)
2708 		return;
2709 
2710 	while (tab->nr_descs--) {
2711 		module_put(tab->descs[tab->nr_descs].module);
2712 		btf_put(tab->descs[tab->nr_descs].btf);
2713 	}
2714 	kfree(tab);
2715 }
2716 
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2717 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2718 {
2719 	if (offset) {
2720 		if (offset < 0) {
2721 			/* In the future, this can be allowed to increase limit
2722 			 * of fd index into fd_array, interpreted as u16.
2723 			 */
2724 			verbose(env, "negative offset disallowed for kernel module function call\n");
2725 			return ERR_PTR(-EINVAL);
2726 		}
2727 
2728 		return __find_kfunc_desc_btf(env, offset);
2729 	}
2730 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2731 }
2732 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)2733 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2734 {
2735 	const struct btf_type *func, *func_proto;
2736 	struct bpf_kfunc_btf_tab *btf_tab;
2737 	struct bpf_kfunc_desc_tab *tab;
2738 	struct bpf_prog_aux *prog_aux;
2739 	struct bpf_kfunc_desc *desc;
2740 	const char *func_name;
2741 	struct btf *desc_btf;
2742 	unsigned long call_imm;
2743 	unsigned long addr;
2744 	int err;
2745 
2746 	prog_aux = env->prog->aux;
2747 	tab = prog_aux->kfunc_tab;
2748 	btf_tab = prog_aux->kfunc_btf_tab;
2749 	if (!tab) {
2750 		if (!btf_vmlinux) {
2751 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2752 			return -ENOTSUPP;
2753 		}
2754 
2755 		if (!env->prog->jit_requested) {
2756 			verbose(env, "JIT is required for calling kernel function\n");
2757 			return -ENOTSUPP;
2758 		}
2759 
2760 		if (!bpf_jit_supports_kfunc_call()) {
2761 			verbose(env, "JIT does not support calling kernel function\n");
2762 			return -ENOTSUPP;
2763 		}
2764 
2765 		if (!env->prog->gpl_compatible) {
2766 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2767 			return -EINVAL;
2768 		}
2769 
2770 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2771 		if (!tab)
2772 			return -ENOMEM;
2773 		prog_aux->kfunc_tab = tab;
2774 	}
2775 
2776 	/* func_id == 0 is always invalid, but instead of returning an error, be
2777 	 * conservative and wait until the code elimination pass before returning
2778 	 * error, so that invalid calls that get pruned out can be in BPF programs
2779 	 * loaded from userspace.  It is also required that offset be untouched
2780 	 * for such calls.
2781 	 */
2782 	if (!func_id && !offset)
2783 		return 0;
2784 
2785 	if (!btf_tab && offset) {
2786 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2787 		if (!btf_tab)
2788 			return -ENOMEM;
2789 		prog_aux->kfunc_btf_tab = btf_tab;
2790 	}
2791 
2792 	desc_btf = find_kfunc_desc_btf(env, offset);
2793 	if (IS_ERR(desc_btf)) {
2794 		verbose(env, "failed to find BTF for kernel function\n");
2795 		return PTR_ERR(desc_btf);
2796 	}
2797 
2798 	if (find_kfunc_desc(env->prog, func_id, offset))
2799 		return 0;
2800 
2801 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2802 		verbose(env, "too many different kernel function calls\n");
2803 		return -E2BIG;
2804 	}
2805 
2806 	func = btf_type_by_id(desc_btf, func_id);
2807 	if (!func || !btf_type_is_func(func)) {
2808 		verbose(env, "kernel btf_id %u is not a function\n",
2809 			func_id);
2810 		return -EINVAL;
2811 	}
2812 	func_proto = btf_type_by_id(desc_btf, func->type);
2813 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2814 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2815 			func_id);
2816 		return -EINVAL;
2817 	}
2818 
2819 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2820 	addr = kallsyms_lookup_name(func_name);
2821 	if (!addr) {
2822 		verbose(env, "cannot find address for kernel function %s\n",
2823 			func_name);
2824 		return -EINVAL;
2825 	}
2826 	specialize_kfunc(env, func_id, offset, &addr);
2827 
2828 	if (bpf_jit_supports_far_kfunc_call()) {
2829 		call_imm = func_id;
2830 	} else {
2831 		call_imm = BPF_CALL_IMM(addr);
2832 		/* Check whether the relative offset overflows desc->imm */
2833 		if ((unsigned long)(s32)call_imm != call_imm) {
2834 			verbose(env, "address of kernel function %s is out of range\n",
2835 				func_name);
2836 			return -EINVAL;
2837 		}
2838 	}
2839 
2840 	if (bpf_dev_bound_kfunc_id(func_id)) {
2841 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2842 		if (err)
2843 			return err;
2844 	}
2845 
2846 	desc = &tab->descs[tab->nr_descs++];
2847 	desc->func_id = func_id;
2848 	desc->imm = call_imm;
2849 	desc->offset = offset;
2850 	desc->addr = addr;
2851 	err = btf_distill_func_proto(&env->log, desc_btf,
2852 				     func_proto, func_name,
2853 				     &desc->func_model);
2854 	if (!err)
2855 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2856 		     kfunc_desc_cmp_by_id_off, NULL);
2857 	return err;
2858 }
2859 
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)2860 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2861 {
2862 	const struct bpf_kfunc_desc *d0 = a;
2863 	const struct bpf_kfunc_desc *d1 = b;
2864 
2865 	if (d0->imm != d1->imm)
2866 		return d0->imm < d1->imm ? -1 : 1;
2867 	if (d0->offset != d1->offset)
2868 		return d0->offset < d1->offset ? -1 : 1;
2869 	return 0;
2870 }
2871 
sort_kfunc_descs_by_imm_off(struct bpf_prog * prog)2872 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2873 {
2874 	struct bpf_kfunc_desc_tab *tab;
2875 
2876 	tab = prog->aux->kfunc_tab;
2877 	if (!tab)
2878 		return;
2879 
2880 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2881 	     kfunc_desc_cmp_by_imm_off, NULL);
2882 }
2883 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)2884 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2885 {
2886 	return !!prog->aux->kfunc_tab;
2887 }
2888 
2889 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)2890 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2891 			 const struct bpf_insn *insn)
2892 {
2893 	const struct bpf_kfunc_desc desc = {
2894 		.imm = insn->imm,
2895 		.offset = insn->off,
2896 	};
2897 	const struct bpf_kfunc_desc *res;
2898 	struct bpf_kfunc_desc_tab *tab;
2899 
2900 	tab = prog->aux->kfunc_tab;
2901 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2902 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2903 
2904 	return res ? &res->func_model : NULL;
2905 }
2906 
add_subprog_and_kfunc(struct bpf_verifier_env * env)2907 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2908 {
2909 	struct bpf_subprog_info *subprog = env->subprog_info;
2910 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
2911 	struct bpf_insn *insn = env->prog->insnsi;
2912 
2913 	/* Add entry function. */
2914 	ret = add_subprog(env, 0);
2915 	if (ret)
2916 		return ret;
2917 
2918 	for (i = 0; i < insn_cnt; i++, insn++) {
2919 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2920 		    !bpf_pseudo_kfunc_call(insn))
2921 			continue;
2922 
2923 		if (!env->bpf_capable) {
2924 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2925 			return -EPERM;
2926 		}
2927 
2928 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2929 			ret = add_subprog(env, i + insn->imm + 1);
2930 		else
2931 			ret = add_kfunc_call(env, insn->imm, insn->off);
2932 
2933 		if (ret < 0)
2934 			return ret;
2935 	}
2936 
2937 	ret = bpf_find_exception_callback_insn_off(env);
2938 	if (ret < 0)
2939 		return ret;
2940 	ex_cb_insn = ret;
2941 
2942 	/* If ex_cb_insn > 0, this means that the main program has a subprog
2943 	 * marked using BTF decl tag to serve as the exception callback.
2944 	 */
2945 	if (ex_cb_insn) {
2946 		ret = add_subprog(env, ex_cb_insn);
2947 		if (ret < 0)
2948 			return ret;
2949 		for (i = 1; i < env->subprog_cnt; i++) {
2950 			if (env->subprog_info[i].start != ex_cb_insn)
2951 				continue;
2952 			env->exception_callback_subprog = i;
2953 			mark_subprog_exc_cb(env, i);
2954 			break;
2955 		}
2956 	}
2957 
2958 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2959 	 * logic. 'subprog_cnt' should not be increased.
2960 	 */
2961 	subprog[env->subprog_cnt].start = insn_cnt;
2962 
2963 	if (env->log.level & BPF_LOG_LEVEL2)
2964 		for (i = 0; i < env->subprog_cnt; i++)
2965 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2966 
2967 	return 0;
2968 }
2969 
check_subprogs(struct bpf_verifier_env * env)2970 static int check_subprogs(struct bpf_verifier_env *env)
2971 {
2972 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2973 	struct bpf_subprog_info *subprog = env->subprog_info;
2974 	struct bpf_insn *insn = env->prog->insnsi;
2975 	int insn_cnt = env->prog->len;
2976 
2977 	/* now check that all jumps are within the same subprog */
2978 	subprog_start = subprog[cur_subprog].start;
2979 	subprog_end = subprog[cur_subprog + 1].start;
2980 	for (i = 0; i < insn_cnt; i++) {
2981 		u8 code = insn[i].code;
2982 
2983 		if (code == (BPF_JMP | BPF_CALL) &&
2984 		    insn[i].src_reg == 0 &&
2985 		    insn[i].imm == BPF_FUNC_tail_call) {
2986 			subprog[cur_subprog].has_tail_call = true;
2987 			subprog[cur_subprog].tail_call_reachable = true;
2988 		}
2989 		if (BPF_CLASS(code) == BPF_LD &&
2990 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2991 			subprog[cur_subprog].has_ld_abs = true;
2992 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2993 			goto next;
2994 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2995 			goto next;
2996 		if (code == (BPF_JMP32 | BPF_JA))
2997 			off = i + insn[i].imm + 1;
2998 		else
2999 			off = i + insn[i].off + 1;
3000 		if (off < subprog_start || off >= subprog_end) {
3001 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3002 			return -EINVAL;
3003 		}
3004 next:
3005 		if (i == subprog_end - 1) {
3006 			/* to avoid fall-through from one subprog into another
3007 			 * the last insn of the subprog should be either exit
3008 			 * or unconditional jump back or bpf_throw call
3009 			 */
3010 			if (code != (BPF_JMP | BPF_EXIT) &&
3011 			    code != (BPF_JMP32 | BPF_JA) &&
3012 			    code != (BPF_JMP | BPF_JA)) {
3013 				verbose(env, "last insn is not an exit or jmp\n");
3014 				return -EINVAL;
3015 			}
3016 			subprog_start = subprog_end;
3017 			cur_subprog++;
3018 			if (cur_subprog < env->subprog_cnt)
3019 				subprog_end = subprog[cur_subprog + 1].start;
3020 		}
3021 	}
3022 	return 0;
3023 }
3024 
3025 /* Parentage chain of this register (or stack slot) should take care of all
3026  * issues like callee-saved registers, stack slot allocation time, etc.
3027  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)3028 static int mark_reg_read(struct bpf_verifier_env *env,
3029 			 const struct bpf_reg_state *state,
3030 			 struct bpf_reg_state *parent, u8 flag)
3031 {
3032 	bool writes = parent == state->parent; /* Observe write marks */
3033 	int cnt = 0;
3034 
3035 	while (parent) {
3036 		/* if read wasn't screened by an earlier write ... */
3037 		if (writes && state->live & REG_LIVE_WRITTEN)
3038 			break;
3039 		if (parent->live & REG_LIVE_DONE) {
3040 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3041 				reg_type_str(env, parent->type),
3042 				parent->var_off.value, parent->off);
3043 			return -EFAULT;
3044 		}
3045 		/* The first condition is more likely to be true than the
3046 		 * second, checked it first.
3047 		 */
3048 		if ((parent->live & REG_LIVE_READ) == flag ||
3049 		    parent->live & REG_LIVE_READ64)
3050 			/* The parentage chain never changes and
3051 			 * this parent was already marked as LIVE_READ.
3052 			 * There is no need to keep walking the chain again and
3053 			 * keep re-marking all parents as LIVE_READ.
3054 			 * This case happens when the same register is read
3055 			 * multiple times without writes into it in-between.
3056 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3057 			 * then no need to set the weak REG_LIVE_READ32.
3058 			 */
3059 			break;
3060 		/* ... then we depend on parent's value */
3061 		parent->live |= flag;
3062 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3063 		if (flag == REG_LIVE_READ64)
3064 			parent->live &= ~REG_LIVE_READ32;
3065 		state = parent;
3066 		parent = state->parent;
3067 		writes = true;
3068 		cnt++;
3069 	}
3070 
3071 	if (env->longest_mark_read_walk < cnt)
3072 		env->longest_mark_read_walk = cnt;
3073 	return 0;
3074 }
3075 
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3076 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3077 {
3078 	struct bpf_func_state *state = func(env, reg);
3079 	int spi, ret;
3080 
3081 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3082 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3083 	 * check_kfunc_call.
3084 	 */
3085 	if (reg->type == CONST_PTR_TO_DYNPTR)
3086 		return 0;
3087 	spi = dynptr_get_spi(env, reg);
3088 	if (spi < 0)
3089 		return spi;
3090 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3091 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3092 	 * read.
3093 	 */
3094 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3095 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3096 	if (ret)
3097 		return ret;
3098 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3099 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3100 }
3101 
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3102 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3103 			  int spi, int nr_slots)
3104 {
3105 	struct bpf_func_state *state = func(env, reg);
3106 	int err, i;
3107 
3108 	for (i = 0; i < nr_slots; i++) {
3109 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3110 
3111 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3112 		if (err)
3113 			return err;
3114 
3115 		mark_stack_slot_scratched(env, spi - i);
3116 	}
3117 
3118 	return 0;
3119 }
3120 
3121 /* This function is supposed to be used by the following 32-bit optimization
3122  * code only. It returns TRUE if the source or destination register operates
3123  * on 64-bit, otherwise return FALSE.
3124  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3125 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3126 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3127 {
3128 	u8 code, class, op;
3129 
3130 	code = insn->code;
3131 	class = BPF_CLASS(code);
3132 	op = BPF_OP(code);
3133 	if (class == BPF_JMP) {
3134 		/* BPF_EXIT for "main" will reach here. Return TRUE
3135 		 * conservatively.
3136 		 */
3137 		if (op == BPF_EXIT)
3138 			return true;
3139 		if (op == BPF_CALL) {
3140 			/* BPF to BPF call will reach here because of marking
3141 			 * caller saved clobber with DST_OP_NO_MARK for which we
3142 			 * don't care the register def because they are anyway
3143 			 * marked as NOT_INIT already.
3144 			 */
3145 			if (insn->src_reg == BPF_PSEUDO_CALL)
3146 				return false;
3147 			/* Helper call will reach here because of arg type
3148 			 * check, conservatively return TRUE.
3149 			 */
3150 			if (t == SRC_OP)
3151 				return true;
3152 
3153 			return false;
3154 		}
3155 	}
3156 
3157 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3158 		return false;
3159 
3160 	if (class == BPF_ALU64 || class == BPF_JMP ||
3161 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3162 		return true;
3163 
3164 	if (class == BPF_ALU || class == BPF_JMP32)
3165 		return false;
3166 
3167 	if (class == BPF_LDX) {
3168 		if (t != SRC_OP)
3169 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3170 		/* LDX source must be ptr. */
3171 		return true;
3172 	}
3173 
3174 	if (class == BPF_STX) {
3175 		/* BPF_STX (including atomic variants) has multiple source
3176 		 * operands, one of which is a ptr. Check whether the caller is
3177 		 * asking about it.
3178 		 */
3179 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3180 			return true;
3181 		return BPF_SIZE(code) == BPF_DW;
3182 	}
3183 
3184 	if (class == BPF_LD) {
3185 		u8 mode = BPF_MODE(code);
3186 
3187 		/* LD_IMM64 */
3188 		if (mode == BPF_IMM)
3189 			return true;
3190 
3191 		/* Both LD_IND and LD_ABS return 32-bit data. */
3192 		if (t != SRC_OP)
3193 			return  false;
3194 
3195 		/* Implicit ctx ptr. */
3196 		if (regno == BPF_REG_6)
3197 			return true;
3198 
3199 		/* Explicit source could be any width. */
3200 		return true;
3201 	}
3202 
3203 	if (class == BPF_ST)
3204 		/* The only source register for BPF_ST is a ptr. */
3205 		return true;
3206 
3207 	/* Conservatively return true at default. */
3208 	return true;
3209 }
3210 
3211 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3212 static int insn_def_regno(const struct bpf_insn *insn)
3213 {
3214 	switch (BPF_CLASS(insn->code)) {
3215 	case BPF_JMP:
3216 	case BPF_JMP32:
3217 	case BPF_ST:
3218 		return -1;
3219 	case BPF_STX:
3220 		if ((BPF_MODE(insn->code) == BPF_ATOMIC ||
3221 		     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
3222 		    (insn->imm & BPF_FETCH)) {
3223 			if (insn->imm == BPF_CMPXCHG)
3224 				return BPF_REG_0;
3225 			else
3226 				return insn->src_reg;
3227 		} else {
3228 			return -1;
3229 		}
3230 	default:
3231 		return insn->dst_reg;
3232 	}
3233 }
3234 
3235 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)3236 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3237 {
3238 	int dst_reg = insn_def_regno(insn);
3239 
3240 	if (dst_reg == -1)
3241 		return false;
3242 
3243 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3244 }
3245 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3246 static void mark_insn_zext(struct bpf_verifier_env *env,
3247 			   struct bpf_reg_state *reg)
3248 {
3249 	s32 def_idx = reg->subreg_def;
3250 
3251 	if (def_idx == DEF_NOT_SUBREG)
3252 		return;
3253 
3254 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3255 	/* The dst will be zero extended, so won't be sub-register anymore. */
3256 	reg->subreg_def = DEF_NOT_SUBREG;
3257 }
3258 
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3259 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3260 			   enum reg_arg_type t)
3261 {
3262 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3263 	struct bpf_reg_state *reg;
3264 	bool rw64;
3265 
3266 	if (regno >= MAX_BPF_REG) {
3267 		verbose(env, "R%d is invalid\n", regno);
3268 		return -EINVAL;
3269 	}
3270 
3271 	mark_reg_scratched(env, regno);
3272 
3273 	reg = &regs[regno];
3274 	rw64 = is_reg64(env, insn, regno, reg, t);
3275 	if (t == SRC_OP) {
3276 		/* check whether register used as source operand can be read */
3277 		if (reg->type == NOT_INIT) {
3278 			verbose(env, "R%d !read_ok\n", regno);
3279 			return -EACCES;
3280 		}
3281 		/* We don't need to worry about FP liveness because it's read-only */
3282 		if (regno == BPF_REG_FP)
3283 			return 0;
3284 
3285 		if (rw64)
3286 			mark_insn_zext(env, reg);
3287 
3288 		return mark_reg_read(env, reg, reg->parent,
3289 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3290 	} else {
3291 		/* check whether register used as dest operand can be written to */
3292 		if (regno == BPF_REG_FP) {
3293 			verbose(env, "frame pointer is read only\n");
3294 			return -EACCES;
3295 		}
3296 		reg->live |= REG_LIVE_WRITTEN;
3297 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3298 		if (t == DST_OP)
3299 			mark_reg_unknown(env, regs, regno);
3300 	}
3301 	return 0;
3302 }
3303 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3304 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3305 			 enum reg_arg_type t)
3306 {
3307 	struct bpf_verifier_state *vstate = env->cur_state;
3308 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3309 
3310 	return __check_reg_arg(env, state->regs, regno, t);
3311 }
3312 
insn_stack_access_flags(int frameno,int spi)3313 static int insn_stack_access_flags(int frameno, int spi)
3314 {
3315 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3316 }
3317 
insn_stack_access_spi(int insn_flags)3318 static int insn_stack_access_spi(int insn_flags)
3319 {
3320 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3321 }
3322 
insn_stack_access_frameno(int insn_flags)3323 static int insn_stack_access_frameno(int insn_flags)
3324 {
3325 	return insn_flags & INSN_F_FRAMENO_MASK;
3326 }
3327 
mark_jmp_point(struct bpf_verifier_env * env,int idx)3328 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3329 {
3330 	env->insn_aux_data[idx].jmp_point = true;
3331 }
3332 
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3333 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3334 {
3335 	return env->insn_aux_data[insn_idx].jmp_point;
3336 }
3337 
3338 /* 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)3339 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3340 			    int insn_flags)
3341 {
3342 	u32 cnt = cur->jmp_history_cnt;
3343 	struct bpf_jmp_history_entry *p;
3344 	size_t alloc_size;
3345 
3346 	/* combine instruction flags if we already recorded this instruction */
3347 	if (env->cur_hist_ent) {
3348 		/* atomic instructions push insn_flags twice, for READ and
3349 		 * WRITE sides, but they should agree on stack slot
3350 		 */
3351 		WARN_ONCE((env->cur_hist_ent->flags & insn_flags) &&
3352 			  (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3353 			  "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n",
3354 			  env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3355 		env->cur_hist_ent->flags |= insn_flags;
3356 		return 0;
3357 	}
3358 
3359 	cnt++;
3360 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3361 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3362 	if (!p)
3363 		return -ENOMEM;
3364 	cur->jmp_history = p;
3365 
3366 	p = &cur->jmp_history[cnt - 1];
3367 	p->idx = env->insn_idx;
3368 	p->prev_idx = env->prev_insn_idx;
3369 	p->flags = insn_flags;
3370 	cur->jmp_history_cnt = cnt;
3371 	env->cur_hist_ent = p;
3372 
3373 	return 0;
3374 }
3375 
get_jmp_hist_entry(struct bpf_verifier_state * st,u32 hist_end,int insn_idx)3376 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3377 						        u32 hist_end, int insn_idx)
3378 {
3379 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3380 		return &st->jmp_history[hist_end - 1];
3381 	return NULL;
3382 }
3383 
3384 /* Backtrack one insn at a time. If idx is not at the top of recorded
3385  * history then previous instruction came from straight line execution.
3386  * Return -ENOENT if we exhausted all instructions within given state.
3387  *
3388  * It's legal to have a bit of a looping with the same starting and ending
3389  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3390  * instruction index is the same as state's first_idx doesn't mean we are
3391  * done. If there is still some jump history left, we should keep going. We
3392  * need to take into account that we might have a jump history between given
3393  * state's parent and itself, due to checkpointing. In this case, we'll have
3394  * history entry recording a jump from last instruction of parent state and
3395  * first instruction of given state.
3396  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)3397 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3398 			     u32 *history)
3399 {
3400 	u32 cnt = *history;
3401 
3402 	if (i == st->first_insn_idx) {
3403 		if (cnt == 0)
3404 			return -ENOENT;
3405 		if (cnt == 1 && st->jmp_history[0].idx == i)
3406 			return -ENOENT;
3407 	}
3408 
3409 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3410 		i = st->jmp_history[cnt - 1].prev_idx;
3411 		(*history)--;
3412 	} else {
3413 		i--;
3414 	}
3415 	return i;
3416 }
3417 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)3418 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3419 {
3420 	const struct btf_type *func;
3421 	struct btf *desc_btf;
3422 
3423 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3424 		return NULL;
3425 
3426 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3427 	if (IS_ERR(desc_btf))
3428 		return "<error>";
3429 
3430 	func = btf_type_by_id(desc_btf, insn->imm);
3431 	return btf_name_by_offset(desc_btf, func->name_off);
3432 }
3433 
bt_init(struct backtrack_state * bt,u32 frame)3434 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3435 {
3436 	bt->frame = frame;
3437 }
3438 
bt_reset(struct backtrack_state * bt)3439 static inline void bt_reset(struct backtrack_state *bt)
3440 {
3441 	struct bpf_verifier_env *env = bt->env;
3442 
3443 	memset(bt, 0, sizeof(*bt));
3444 	bt->env = env;
3445 }
3446 
bt_empty(struct backtrack_state * bt)3447 static inline u32 bt_empty(struct backtrack_state *bt)
3448 {
3449 	u64 mask = 0;
3450 	int i;
3451 
3452 	for (i = 0; i <= bt->frame; i++)
3453 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3454 
3455 	return mask == 0;
3456 }
3457 
bt_subprog_enter(struct backtrack_state * bt)3458 static inline int bt_subprog_enter(struct backtrack_state *bt)
3459 {
3460 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3461 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3462 		WARN_ONCE(1, "verifier backtracking bug");
3463 		return -EFAULT;
3464 	}
3465 	bt->frame++;
3466 	return 0;
3467 }
3468 
bt_subprog_exit(struct backtrack_state * bt)3469 static inline int bt_subprog_exit(struct backtrack_state *bt)
3470 {
3471 	if (bt->frame == 0) {
3472 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3473 		WARN_ONCE(1, "verifier backtracking bug");
3474 		return -EFAULT;
3475 	}
3476 	bt->frame--;
3477 	return 0;
3478 }
3479 
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3480 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3481 {
3482 	bt->reg_masks[frame] |= 1 << reg;
3483 }
3484 
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3485 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3486 {
3487 	bt->reg_masks[frame] &= ~(1 << reg);
3488 }
3489 
bt_set_reg(struct backtrack_state * bt,u32 reg)3490 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3491 {
3492 	bt_set_frame_reg(bt, bt->frame, reg);
3493 }
3494 
bt_clear_reg(struct backtrack_state * bt,u32 reg)3495 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3496 {
3497 	bt_clear_frame_reg(bt, bt->frame, reg);
3498 }
3499 
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3500 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3501 {
3502 	bt->stack_masks[frame] |= 1ull << slot;
3503 }
3504 
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3505 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3506 {
3507 	bt->stack_masks[frame] &= ~(1ull << slot);
3508 }
3509 
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)3510 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3511 {
3512 	return bt->reg_masks[frame];
3513 }
3514 
bt_reg_mask(struct backtrack_state * bt)3515 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3516 {
3517 	return bt->reg_masks[bt->frame];
3518 }
3519 
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)3520 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3521 {
3522 	return bt->stack_masks[frame];
3523 }
3524 
bt_stack_mask(struct backtrack_state * bt)3525 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3526 {
3527 	return bt->stack_masks[bt->frame];
3528 }
3529 
bt_is_reg_set(struct backtrack_state * bt,u32 reg)3530 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3531 {
3532 	return bt->reg_masks[bt->frame] & (1 << reg);
3533 }
3534 
bt_is_frame_slot_set(struct backtrack_state * bt,u32 frame,u32 slot)3535 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
3536 {
3537 	return bt->stack_masks[frame] & (1ull << slot);
3538 }
3539 
3540 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)3541 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3542 {
3543 	DECLARE_BITMAP(mask, 64);
3544 	bool first = true;
3545 	int i, n;
3546 
3547 	buf[0] = '\0';
3548 
3549 	bitmap_from_u64(mask, reg_mask);
3550 	for_each_set_bit(i, mask, 32) {
3551 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3552 		first = false;
3553 		buf += n;
3554 		buf_sz -= n;
3555 		if (buf_sz < 0)
3556 			break;
3557 	}
3558 }
3559 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)3560 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3561 {
3562 	DECLARE_BITMAP(mask, 64);
3563 	bool first = true;
3564 	int i, n;
3565 
3566 	buf[0] = '\0';
3567 
3568 	bitmap_from_u64(mask, stack_mask);
3569 	for_each_set_bit(i, mask, 64) {
3570 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3571 		first = false;
3572 		buf += n;
3573 		buf_sz -= n;
3574 		if (buf_sz < 0)
3575 			break;
3576 	}
3577 }
3578 
3579 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3580 
3581 /* For given verifier state backtrack_insn() is called from the last insn to
3582  * the first insn. Its purpose is to compute a bitmask of registers and
3583  * stack slots that needs precision in the parent verifier state.
3584  *
3585  * @idx is an index of the instruction we are currently processing;
3586  * @subseq_idx is an index of the subsequent instruction that:
3587  *   - *would be* executed next, if jump history is viewed in forward order;
3588  *   - *was* processed previously during backtracking.
3589  */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct bpf_jmp_history_entry * hist,struct backtrack_state * bt)3590 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3591 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
3592 {
3593 	const struct bpf_insn_cbs cbs = {
3594 		.cb_call	= disasm_kfunc_name,
3595 		.cb_print	= verbose,
3596 		.private_data	= env,
3597 	};
3598 	struct bpf_insn *insn = env->prog->insnsi + idx;
3599 	u8 class = BPF_CLASS(insn->code);
3600 	u8 opcode = BPF_OP(insn->code);
3601 	u8 mode = BPF_MODE(insn->code);
3602 	u32 dreg = insn->dst_reg;
3603 	u32 sreg = insn->src_reg;
3604 	u32 spi, i, fr;
3605 
3606 	if (insn->code == 0)
3607 		return 0;
3608 	if (env->log.level & BPF_LOG_LEVEL2) {
3609 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3610 		verbose(env, "mark_precise: frame%d: regs=%s ",
3611 			bt->frame, env->tmp_str_buf);
3612 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3613 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3614 		verbose(env, "%d: ", idx);
3615 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3616 	}
3617 
3618 	if (class == BPF_ALU || class == BPF_ALU64) {
3619 		if (!bt_is_reg_set(bt, dreg))
3620 			return 0;
3621 		if (opcode == BPF_END || opcode == BPF_NEG) {
3622 			/* sreg is reserved and unused
3623 			 * dreg still need precision before this insn
3624 			 */
3625 			return 0;
3626 		} else if (opcode == BPF_MOV) {
3627 			if (BPF_SRC(insn->code) == BPF_X) {
3628 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3629 				 * dreg needs precision after this insn
3630 				 * sreg needs precision before this insn
3631 				 */
3632 				bt_clear_reg(bt, dreg);
3633 				if (sreg != BPF_REG_FP)
3634 					bt_set_reg(bt, sreg);
3635 			} else {
3636 				/* dreg = K
3637 				 * dreg needs precision after this insn.
3638 				 * Corresponding register is already marked
3639 				 * as precise=true in this verifier state.
3640 				 * No further markings in parent are necessary
3641 				 */
3642 				bt_clear_reg(bt, dreg);
3643 			}
3644 		} else {
3645 			if (BPF_SRC(insn->code) == BPF_X) {
3646 				/* dreg += sreg
3647 				 * both dreg and sreg need precision
3648 				 * before this insn
3649 				 */
3650 				if (sreg != BPF_REG_FP)
3651 					bt_set_reg(bt, sreg);
3652 			} /* else dreg += K
3653 			   * dreg still needs precision before this insn
3654 			   */
3655 		}
3656 	} else if (class == BPF_LDX) {
3657 		if (!bt_is_reg_set(bt, dreg))
3658 			return 0;
3659 		bt_clear_reg(bt, dreg);
3660 
3661 		/* scalars can only be spilled into stack w/o losing precision.
3662 		 * Load from any other memory can be zero extended.
3663 		 * The desire to keep that precision is already indicated
3664 		 * by 'precise' mark in corresponding register of this state.
3665 		 * No further tracking necessary.
3666 		 */
3667 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3668 			return 0;
3669 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3670 		 * that [fp - off] slot contains scalar that needs to be
3671 		 * tracked with precision
3672 		 */
3673 		spi = insn_stack_access_spi(hist->flags);
3674 		fr = insn_stack_access_frameno(hist->flags);
3675 		bt_set_frame_slot(bt, fr, spi);
3676 	} else if (class == BPF_STX || class == BPF_ST) {
3677 		if (bt_is_reg_set(bt, dreg))
3678 			/* stx & st shouldn't be using _scalar_ dst_reg
3679 			 * to access memory. It means backtracking
3680 			 * encountered a case of pointer subtraction.
3681 			 */
3682 			return -ENOTSUPP;
3683 		/* scalars can only be spilled into stack */
3684 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
3685 			return 0;
3686 		spi = insn_stack_access_spi(hist->flags);
3687 		fr = insn_stack_access_frameno(hist->flags);
3688 		if (!bt_is_frame_slot_set(bt, fr, spi))
3689 			return 0;
3690 		bt_clear_frame_slot(bt, fr, spi);
3691 		if (class == BPF_STX)
3692 			bt_set_reg(bt, sreg);
3693 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3694 		if (bpf_pseudo_call(insn)) {
3695 			int subprog_insn_idx, subprog;
3696 
3697 			subprog_insn_idx = idx + insn->imm + 1;
3698 			subprog = find_subprog(env, subprog_insn_idx);
3699 			if (subprog < 0)
3700 				return -EFAULT;
3701 
3702 			if (subprog_is_global(env, subprog)) {
3703 				/* check that jump history doesn't have any
3704 				 * extra instructions from subprog; the next
3705 				 * instruction after call to global subprog
3706 				 * should be literally next instruction in
3707 				 * caller program
3708 				 */
3709 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3710 				/* r1-r5 are invalidated after subprog call,
3711 				 * so for global func call it shouldn't be set
3712 				 * anymore
3713 				 */
3714 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3715 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3716 					WARN_ONCE(1, "verifier backtracking bug");
3717 					return -EFAULT;
3718 				}
3719 				/* global subprog always sets R0 */
3720 				bt_clear_reg(bt, BPF_REG_0);
3721 				return 0;
3722 			} else {
3723 				/* static subprog call instruction, which
3724 				 * means that we are exiting current subprog,
3725 				 * so only r1-r5 could be still requested as
3726 				 * precise, r0 and r6-r10 or any stack slot in
3727 				 * the current frame should be zero by now
3728 				 */
3729 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3730 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3731 					WARN_ONCE(1, "verifier backtracking bug");
3732 					return -EFAULT;
3733 				}
3734 				/* we are now tracking register spills correctly,
3735 				 * so any instance of leftover slots is a bug
3736 				 */
3737 				if (bt_stack_mask(bt) != 0) {
3738 					verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3739 					WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)");
3740 					return -EFAULT;
3741 				}
3742 				/* propagate r1-r5 to the caller */
3743 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3744 					if (bt_is_reg_set(bt, i)) {
3745 						bt_clear_reg(bt, i);
3746 						bt_set_frame_reg(bt, bt->frame - 1, i);
3747 					}
3748 				}
3749 				if (bt_subprog_exit(bt))
3750 					return -EFAULT;
3751 				return 0;
3752 			}
3753 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3754 			/* exit from callback subprog to callback-calling helper or
3755 			 * kfunc call. Use idx/subseq_idx check to discern it from
3756 			 * straight line code backtracking.
3757 			 * Unlike the subprog call handling above, we shouldn't
3758 			 * propagate precision of r1-r5 (if any requested), as they are
3759 			 * not actually arguments passed directly to callback subprogs
3760 			 */
3761 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3762 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3763 				WARN_ONCE(1, "verifier backtracking bug");
3764 				return -EFAULT;
3765 			}
3766 			if (bt_stack_mask(bt) != 0) {
3767 				verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt));
3768 				WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)");
3769 				return -EFAULT;
3770 			}
3771 			/* clear r1-r5 in callback subprog's mask */
3772 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3773 				bt_clear_reg(bt, i);
3774 			if (bt_subprog_exit(bt))
3775 				return -EFAULT;
3776 			return 0;
3777 		} else if (opcode == BPF_CALL) {
3778 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3779 			 * catch this error later. Make backtracking conservative
3780 			 * with ENOTSUPP.
3781 			 */
3782 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3783 				return -ENOTSUPP;
3784 			/* regular helper call sets R0 */
3785 			bt_clear_reg(bt, BPF_REG_0);
3786 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3787 				/* if backtracing was looking for registers R1-R5
3788 				 * they should have been found already.
3789 				 */
3790 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3791 				WARN_ONCE(1, "verifier backtracking bug");
3792 				return -EFAULT;
3793 			}
3794 		} else if (opcode == BPF_EXIT) {
3795 			bool r0_precise;
3796 
3797 			/* Backtracking to a nested function call, 'idx' is a part of
3798 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3799 			 * In case of a regular function call, instructions giving
3800 			 * precision to registers R1-R5 should have been found already.
3801 			 * In case of a callback, it is ok to have R1-R5 marked for
3802 			 * backtracking, as these registers are set by the function
3803 			 * invoking callback.
3804 			 */
3805 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3806 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3807 					bt_clear_reg(bt, i);
3808 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3809 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3810 				WARN_ONCE(1, "verifier backtracking bug");
3811 				return -EFAULT;
3812 			}
3813 
3814 			/* BPF_EXIT in subprog or callback always returns
3815 			 * right after the call instruction, so by checking
3816 			 * whether the instruction at subseq_idx-1 is subprog
3817 			 * call or not we can distinguish actual exit from
3818 			 * *subprog* from exit from *callback*. In the former
3819 			 * case, we need to propagate r0 precision, if
3820 			 * necessary. In the former we never do that.
3821 			 */
3822 			r0_precise = subseq_idx - 1 >= 0 &&
3823 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3824 				     bt_is_reg_set(bt, BPF_REG_0);
3825 
3826 			bt_clear_reg(bt, BPF_REG_0);
3827 			if (bt_subprog_enter(bt))
3828 				return -EFAULT;
3829 
3830 			if (r0_precise)
3831 				bt_set_reg(bt, BPF_REG_0);
3832 			/* r6-r9 and stack slots will stay set in caller frame
3833 			 * bitmasks until we return back from callee(s)
3834 			 */
3835 			return 0;
3836 		} else if (BPF_SRC(insn->code) == BPF_X) {
3837 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3838 				return 0;
3839 			/* dreg <cond> sreg
3840 			 * Both dreg and sreg need precision before
3841 			 * this insn. If only sreg was marked precise
3842 			 * before it would be equally necessary to
3843 			 * propagate it to dreg.
3844 			 */
3845 			bt_set_reg(bt, dreg);
3846 			bt_set_reg(bt, sreg);
3847 			 /* else dreg <cond> K
3848 			  * Only dreg still needs precision before
3849 			  * this insn, so for the K-based conditional
3850 			  * there is nothing new to be marked.
3851 			  */
3852 		}
3853 	} else if (class == BPF_LD) {
3854 		if (!bt_is_reg_set(bt, dreg))
3855 			return 0;
3856 		bt_clear_reg(bt, dreg);
3857 		/* It's ld_imm64 or ld_abs or ld_ind.
3858 		 * For ld_imm64 no further tracking of precision
3859 		 * into parent is necessary
3860 		 */
3861 		if (mode == BPF_IND || mode == BPF_ABS)
3862 			/* to be analyzed */
3863 			return -ENOTSUPP;
3864 	}
3865 	return 0;
3866 }
3867 
3868 /* the scalar precision tracking algorithm:
3869  * . at the start all registers have precise=false.
3870  * . scalar ranges are tracked as normal through alu and jmp insns.
3871  * . once precise value of the scalar register is used in:
3872  *   .  ptr + scalar alu
3873  *   . if (scalar cond K|scalar)
3874  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3875  *   backtrack through the verifier states and mark all registers and
3876  *   stack slots with spilled constants that these scalar regisers
3877  *   should be precise.
3878  * . during state pruning two registers (or spilled stack slots)
3879  *   are equivalent if both are not precise.
3880  *
3881  * Note the verifier cannot simply walk register parentage chain,
3882  * since many different registers and stack slots could have been
3883  * used to compute single precise scalar.
3884  *
3885  * The approach of starting with precise=true for all registers and then
3886  * backtrack to mark a register as not precise when the verifier detects
3887  * that program doesn't care about specific value (e.g., when helper
3888  * takes register as ARG_ANYTHING parameter) is not safe.
3889  *
3890  * It's ok to walk single parentage chain of the verifier states.
3891  * It's possible that this backtracking will go all the way till 1st insn.
3892  * All other branches will be explored for needing precision later.
3893  *
3894  * The backtracking needs to deal with cases like:
3895  *   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)
3896  * r9 -= r8
3897  * r5 = r9
3898  * if r5 > 0x79f goto pc+7
3899  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3900  * r5 += 1
3901  * ...
3902  * call bpf_perf_event_output#25
3903  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3904  *
3905  * and this case:
3906  * r6 = 1
3907  * call foo // uses callee's r6 inside to compute r0
3908  * r0 += r6
3909  * if r0 == 0 goto
3910  *
3911  * to track above reg_mask/stack_mask needs to be independent for each frame.
3912  *
3913  * Also if parent's curframe > frame where backtracking started,
3914  * the verifier need to mark registers in both frames, otherwise callees
3915  * may incorrectly prune callers. This is similar to
3916  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3917  *
3918  * For now backtracking falls back into conservative marking.
3919  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)3920 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3921 				     struct bpf_verifier_state *st)
3922 {
3923 	struct bpf_func_state *func;
3924 	struct bpf_reg_state *reg;
3925 	int i, j;
3926 
3927 	if (env->log.level & BPF_LOG_LEVEL2) {
3928 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3929 			st->curframe);
3930 	}
3931 
3932 	/* big hammer: mark all scalars precise in this path.
3933 	 * pop_stack may still get !precise scalars.
3934 	 * We also skip current state and go straight to first parent state,
3935 	 * because precision markings in current non-checkpointed state are
3936 	 * not needed. See why in the comment in __mark_chain_precision below.
3937 	 */
3938 	for (st = st->parent; st; st = st->parent) {
3939 		for (i = 0; i <= st->curframe; i++) {
3940 			func = st->frame[i];
3941 			for (j = 0; j < BPF_REG_FP; j++) {
3942 				reg = &func->regs[j];
3943 				if (reg->type != SCALAR_VALUE || reg->precise)
3944 					continue;
3945 				reg->precise = true;
3946 				if (env->log.level & BPF_LOG_LEVEL2) {
3947 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3948 						i, j);
3949 				}
3950 			}
3951 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3952 				if (!is_spilled_reg(&func->stack[j]))
3953 					continue;
3954 				reg = &func->stack[j].spilled_ptr;
3955 				if (reg->type != SCALAR_VALUE || reg->precise)
3956 					continue;
3957 				reg->precise = true;
3958 				if (env->log.level & BPF_LOG_LEVEL2) {
3959 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3960 						i, -(j + 1) * 8);
3961 				}
3962 			}
3963 		}
3964 	}
3965 }
3966 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)3967 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3968 {
3969 	struct bpf_func_state *func;
3970 	struct bpf_reg_state *reg;
3971 	int i, j;
3972 
3973 	for (i = 0; i <= st->curframe; i++) {
3974 		func = st->frame[i];
3975 		for (j = 0; j < BPF_REG_FP; j++) {
3976 			reg = &func->regs[j];
3977 			if (reg->type != SCALAR_VALUE)
3978 				continue;
3979 			reg->precise = false;
3980 		}
3981 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3982 			if (!is_spilled_reg(&func->stack[j]))
3983 				continue;
3984 			reg = &func->stack[j].spilled_ptr;
3985 			if (reg->type != SCALAR_VALUE)
3986 				continue;
3987 			reg->precise = false;
3988 		}
3989 	}
3990 }
3991 
idset_contains(struct bpf_idset * s,u32 id)3992 static bool idset_contains(struct bpf_idset *s, u32 id)
3993 {
3994 	u32 i;
3995 
3996 	for (i = 0; i < s->count; ++i)
3997 		if (s->ids[i] == (id & ~BPF_ADD_CONST))
3998 			return true;
3999 
4000 	return false;
4001 }
4002 
idset_push(struct bpf_idset * s,u32 id)4003 static int idset_push(struct bpf_idset *s, u32 id)
4004 {
4005 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4006 		return -EFAULT;
4007 	s->ids[s->count++] = id & ~BPF_ADD_CONST;
4008 	return 0;
4009 }
4010 
idset_reset(struct bpf_idset * s)4011 static void idset_reset(struct bpf_idset *s)
4012 {
4013 	s->count = 0;
4014 }
4015 
4016 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4017  * Mark all registers with these IDs as precise.
4018  */
mark_precise_scalar_ids(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4019 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4020 {
4021 	struct bpf_idset *precise_ids = &env->idset_scratch;
4022 	struct backtrack_state *bt = &env->bt;
4023 	struct bpf_func_state *func;
4024 	struct bpf_reg_state *reg;
4025 	DECLARE_BITMAP(mask, 64);
4026 	int i, fr;
4027 
4028 	idset_reset(precise_ids);
4029 
4030 	for (fr = bt->frame; fr >= 0; fr--) {
4031 		func = st->frame[fr];
4032 
4033 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4034 		for_each_set_bit(i, mask, 32) {
4035 			reg = &func->regs[i];
4036 			if (!reg->id || reg->type != SCALAR_VALUE)
4037 				continue;
4038 			if (idset_push(precise_ids, reg->id))
4039 				return -EFAULT;
4040 		}
4041 
4042 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4043 		for_each_set_bit(i, mask, 64) {
4044 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4045 				break;
4046 			if (!is_spilled_scalar_reg(&func->stack[i]))
4047 				continue;
4048 			reg = &func->stack[i].spilled_ptr;
4049 			if (!reg->id)
4050 				continue;
4051 			if (idset_push(precise_ids, reg->id))
4052 				return -EFAULT;
4053 		}
4054 	}
4055 
4056 	for (fr = 0; fr <= st->curframe; ++fr) {
4057 		func = st->frame[fr];
4058 
4059 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4060 			reg = &func->regs[i];
4061 			if (!reg->id)
4062 				continue;
4063 			if (!idset_contains(precise_ids, reg->id))
4064 				continue;
4065 			bt_set_frame_reg(bt, fr, i);
4066 		}
4067 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4068 			if (!is_spilled_scalar_reg(&func->stack[i]))
4069 				continue;
4070 			reg = &func->stack[i].spilled_ptr;
4071 			if (!reg->id)
4072 				continue;
4073 			if (!idset_contains(precise_ids, reg->id))
4074 				continue;
4075 			bt_set_frame_slot(bt, fr, i);
4076 		}
4077 	}
4078 
4079 	return 0;
4080 }
4081 
4082 /*
4083  * __mark_chain_precision() backtracks BPF program instruction sequence and
4084  * chain of verifier states making sure that register *regno* (if regno >= 0)
4085  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4086  * SCALARS, as well as any other registers and slots that contribute to
4087  * a tracked state of given registers/stack slots, depending on specific BPF
4088  * assembly instructions (see backtrack_insns() for exact instruction handling
4089  * logic). This backtracking relies on recorded jmp_history and is able to
4090  * traverse entire chain of parent states. This process ends only when all the
4091  * necessary registers/slots and their transitive dependencies are marked as
4092  * precise.
4093  *
4094  * One important and subtle aspect is that precise marks *do not matter* in
4095  * the currently verified state (current state). It is important to understand
4096  * why this is the case.
4097  *
4098  * First, note that current state is the state that is not yet "checkpointed",
4099  * i.e., it is not yet put into env->explored_states, and it has no children
4100  * states as well. It's ephemeral, and can end up either a) being discarded if
4101  * compatible explored state is found at some point or BPF_EXIT instruction is
4102  * reached or b) checkpointed and put into env->explored_states, branching out
4103  * into one or more children states.
4104  *
4105  * In the former case, precise markings in current state are completely
4106  * ignored by state comparison code (see regsafe() for details). Only
4107  * checkpointed ("old") state precise markings are important, and if old
4108  * state's register/slot is precise, regsafe() assumes current state's
4109  * register/slot as precise and checks value ranges exactly and precisely. If
4110  * states turn out to be compatible, current state's necessary precise
4111  * markings and any required parent states' precise markings are enforced
4112  * after the fact with propagate_precision() logic, after the fact. But it's
4113  * important to realize that in this case, even after marking current state
4114  * registers/slots as precise, we immediately discard current state. So what
4115  * actually matters is any of the precise markings propagated into current
4116  * state's parent states, which are always checkpointed (due to b) case above).
4117  * As such, for scenario a) it doesn't matter if current state has precise
4118  * markings set or not.
4119  *
4120  * Now, for the scenario b), checkpointing and forking into child(ren)
4121  * state(s). Note that before current state gets to checkpointing step, any
4122  * processed instruction always assumes precise SCALAR register/slot
4123  * knowledge: if precise value or range is useful to prune jump branch, BPF
4124  * verifier takes this opportunity enthusiastically. Similarly, when
4125  * register's value is used to calculate offset or memory address, exact
4126  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4127  * what we mentioned above about state comparison ignoring precise markings
4128  * during state comparison, BPF verifier ignores and also assumes precise
4129  * markings *at will* during instruction verification process. But as verifier
4130  * assumes precision, it also propagates any precision dependencies across
4131  * parent states, which are not yet finalized, so can be further restricted
4132  * based on new knowledge gained from restrictions enforced by their children
4133  * states. This is so that once those parent states are finalized, i.e., when
4134  * they have no more active children state, state comparison logic in
4135  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4136  * required for correctness.
4137  *
4138  * To build a bit more intuition, note also that once a state is checkpointed,
4139  * the path we took to get to that state is not important. This is crucial
4140  * property for state pruning. When state is checkpointed and finalized at
4141  * some instruction index, it can be correctly and safely used to "short
4142  * circuit" any *compatible* state that reaches exactly the same instruction
4143  * index. I.e., if we jumped to that instruction from a completely different
4144  * code path than original finalized state was derived from, it doesn't
4145  * matter, current state can be discarded because from that instruction
4146  * forward having a compatible state will ensure we will safely reach the
4147  * exit. States describe preconditions for further exploration, but completely
4148  * forget the history of how we got here.
4149  *
4150  * This also means that even if we needed precise SCALAR range to get to
4151  * finalized state, but from that point forward *that same* SCALAR register is
4152  * never used in a precise context (i.e., it's precise value is not needed for
4153  * correctness), it's correct and safe to mark such register as "imprecise"
4154  * (i.e., precise marking set to false). This is what we rely on when we do
4155  * not set precise marking in current state. If no child state requires
4156  * precision for any given SCALAR register, it's safe to dictate that it can
4157  * be imprecise. If any child state does require this register to be precise,
4158  * we'll mark it precise later retroactively during precise markings
4159  * propagation from child state to parent states.
4160  *
4161  * Skipping precise marking setting in current state is a mild version of
4162  * relying on the above observation. But we can utilize this property even
4163  * more aggressively by proactively forgetting any precise marking in the
4164  * current state (which we inherited from the parent state), right before we
4165  * checkpoint it and branch off into new child state. This is done by
4166  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4167  * finalized states which help in short circuiting more future states.
4168  */
__mark_chain_precision(struct bpf_verifier_env * env,int regno)4169 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4170 {
4171 	struct backtrack_state *bt = &env->bt;
4172 	struct bpf_verifier_state *st = env->cur_state;
4173 	int first_idx = st->first_insn_idx;
4174 	int last_idx = env->insn_idx;
4175 	int subseq_idx = -1;
4176 	struct bpf_func_state *func;
4177 	struct bpf_reg_state *reg;
4178 	bool skip_first = true;
4179 	int i, fr, err;
4180 
4181 	if (!env->bpf_capable)
4182 		return 0;
4183 
4184 	/* set frame number from which we are starting to backtrack */
4185 	bt_init(bt, env->cur_state->curframe);
4186 
4187 	/* Do sanity checks against current state of register and/or stack
4188 	 * slot, but don't set precise flag in current state, as precision
4189 	 * tracking in the current state is unnecessary.
4190 	 */
4191 	func = st->frame[bt->frame];
4192 	if (regno >= 0) {
4193 		reg = &func->regs[regno];
4194 		if (reg->type != SCALAR_VALUE) {
4195 			WARN_ONCE(1, "backtracing misuse");
4196 			return -EFAULT;
4197 		}
4198 		bt_set_reg(bt, regno);
4199 	}
4200 
4201 	if (bt_empty(bt))
4202 		return 0;
4203 
4204 	for (;;) {
4205 		DECLARE_BITMAP(mask, 64);
4206 		u32 history = st->jmp_history_cnt;
4207 		struct bpf_jmp_history_entry *hist;
4208 
4209 		if (env->log.level & BPF_LOG_LEVEL2) {
4210 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4211 				bt->frame, last_idx, first_idx, subseq_idx);
4212 		}
4213 
4214 		/* If some register with scalar ID is marked as precise,
4215 		 * make sure that all registers sharing this ID are also precise.
4216 		 * This is needed to estimate effect of find_equal_scalars().
4217 		 * Do this at the last instruction of each state,
4218 		 * bpf_reg_state::id fields are valid for these instructions.
4219 		 *
4220 		 * Allows to track precision in situation like below:
4221 		 *
4222 		 *     r2 = unknown value
4223 		 *     ...
4224 		 *   --- state #0 ---
4225 		 *     ...
4226 		 *     r1 = r2                 // r1 and r2 now share the same ID
4227 		 *     ...
4228 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4229 		 *     ...
4230 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4231 		 *     ...
4232 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4233 		 *     r3 = r10
4234 		 *     r3 += r1                // need to mark both r1 and r2
4235 		 */
4236 		if (mark_precise_scalar_ids(env, st))
4237 			return -EFAULT;
4238 
4239 		if (last_idx < 0) {
4240 			/* we are at the entry into subprog, which
4241 			 * is expected for global funcs, but only if
4242 			 * requested precise registers are R1-R5
4243 			 * (which are global func's input arguments)
4244 			 */
4245 			if (st->curframe == 0 &&
4246 			    st->frame[0]->subprogno > 0 &&
4247 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4248 			    bt_stack_mask(bt) == 0 &&
4249 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4250 				bitmap_from_u64(mask, bt_reg_mask(bt));
4251 				for_each_set_bit(i, mask, 32) {
4252 					reg = &st->frame[0]->regs[i];
4253 					bt_clear_reg(bt, i);
4254 					if (reg->type == SCALAR_VALUE)
4255 						reg->precise = true;
4256 				}
4257 				return 0;
4258 			}
4259 
4260 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4261 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4262 			WARN_ONCE(1, "verifier backtracking bug");
4263 			return -EFAULT;
4264 		}
4265 
4266 		for (i = last_idx;;) {
4267 			if (skip_first) {
4268 				err = 0;
4269 				skip_first = false;
4270 			} else {
4271 				hist = get_jmp_hist_entry(st, history, i);
4272 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4273 			}
4274 			if (err == -ENOTSUPP) {
4275 				mark_all_scalars_precise(env, env->cur_state);
4276 				bt_reset(bt);
4277 				return 0;
4278 			} else if (err) {
4279 				return err;
4280 			}
4281 			if (bt_empty(bt))
4282 				/* Found assignment(s) into tracked register in this state.
4283 				 * Since this state is already marked, just return.
4284 				 * Nothing to be tracked further in the parent state.
4285 				 */
4286 				return 0;
4287 			subseq_idx = i;
4288 			i = get_prev_insn_idx(st, i, &history);
4289 			if (i == -ENOENT)
4290 				break;
4291 			if (i >= env->prog->len) {
4292 				/* This can happen if backtracking reached insn 0
4293 				 * and there are still reg_mask or stack_mask
4294 				 * to backtrack.
4295 				 * It means the backtracking missed the spot where
4296 				 * particular register was initialized with a constant.
4297 				 */
4298 				verbose(env, "BUG backtracking idx %d\n", i);
4299 				WARN_ONCE(1, "verifier backtracking bug");
4300 				return -EFAULT;
4301 			}
4302 		}
4303 		st = st->parent;
4304 		if (!st)
4305 			break;
4306 
4307 		for (fr = bt->frame; fr >= 0; fr--) {
4308 			func = st->frame[fr];
4309 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4310 			for_each_set_bit(i, mask, 32) {
4311 				reg = &func->regs[i];
4312 				if (reg->type != SCALAR_VALUE) {
4313 					bt_clear_frame_reg(bt, fr, i);
4314 					continue;
4315 				}
4316 				if (reg->precise)
4317 					bt_clear_frame_reg(bt, fr, i);
4318 				else
4319 					reg->precise = true;
4320 			}
4321 
4322 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4323 			for_each_set_bit(i, mask, 64) {
4324 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4325 					verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n",
4326 						i, func->allocated_stack / BPF_REG_SIZE);
4327 					WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)");
4328 					return -EFAULT;
4329 				}
4330 
4331 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4332 					bt_clear_frame_slot(bt, fr, i);
4333 					continue;
4334 				}
4335 				reg = &func->stack[i].spilled_ptr;
4336 				if (reg->precise)
4337 					bt_clear_frame_slot(bt, fr, i);
4338 				else
4339 					reg->precise = true;
4340 			}
4341 			if (env->log.level & BPF_LOG_LEVEL2) {
4342 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4343 					     bt_frame_reg_mask(bt, fr));
4344 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4345 					fr, env->tmp_str_buf);
4346 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4347 					       bt_frame_stack_mask(bt, fr));
4348 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4349 				print_verifier_state(env, func, true);
4350 			}
4351 		}
4352 
4353 		if (bt_empty(bt))
4354 			return 0;
4355 
4356 		subseq_idx = first_idx;
4357 		last_idx = st->last_insn_idx;
4358 		first_idx = st->first_insn_idx;
4359 	}
4360 
4361 	/* if we still have requested precise regs or slots, we missed
4362 	 * something (e.g., stack access through non-r10 register), so
4363 	 * fallback to marking all precise
4364 	 */
4365 	if (!bt_empty(bt)) {
4366 		mark_all_scalars_precise(env, env->cur_state);
4367 		bt_reset(bt);
4368 	}
4369 
4370 	return 0;
4371 }
4372 
mark_chain_precision(struct bpf_verifier_env * env,int regno)4373 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4374 {
4375 	return __mark_chain_precision(env, regno);
4376 }
4377 
4378 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4379  * desired reg and stack masks across all relevant frames
4380  */
mark_chain_precision_batch(struct bpf_verifier_env * env)4381 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4382 {
4383 	return __mark_chain_precision(env, -1);
4384 }
4385 
is_spillable_regtype(enum bpf_reg_type type)4386 static bool is_spillable_regtype(enum bpf_reg_type type)
4387 {
4388 	switch (base_type(type)) {
4389 	case PTR_TO_MAP_VALUE:
4390 	case PTR_TO_STACK:
4391 	case PTR_TO_CTX:
4392 	case PTR_TO_PACKET:
4393 	case PTR_TO_PACKET_META:
4394 	case PTR_TO_PACKET_END:
4395 	case PTR_TO_FLOW_KEYS:
4396 	case CONST_PTR_TO_MAP:
4397 	case PTR_TO_SOCKET:
4398 	case PTR_TO_SOCK_COMMON:
4399 	case PTR_TO_TCP_SOCK:
4400 	case PTR_TO_XDP_SOCK:
4401 	case PTR_TO_BTF_ID:
4402 	case PTR_TO_BUF:
4403 	case PTR_TO_MEM:
4404 	case PTR_TO_FUNC:
4405 	case PTR_TO_MAP_KEY:
4406 	case PTR_TO_ARENA:
4407 		return true;
4408 	default:
4409 		return false;
4410 	}
4411 }
4412 
4413 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4414 static bool register_is_null(struct bpf_reg_state *reg)
4415 {
4416 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4417 }
4418 
4419 /* check if register is a constant scalar value */
is_reg_const(struct bpf_reg_state * reg,bool subreg32)4420 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4421 {
4422 	return reg->type == SCALAR_VALUE &&
4423 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4424 }
4425 
4426 /* assuming is_reg_const() is true, return constant value of a register */
reg_const_value(struct bpf_reg_state * reg,bool subreg32)4427 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4428 {
4429 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4430 }
4431 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)4432 static bool __is_pointer_value(bool allow_ptr_leaks,
4433 			       const struct bpf_reg_state *reg)
4434 {
4435 	if (allow_ptr_leaks)
4436 		return false;
4437 
4438 	return reg->type != SCALAR_VALUE;
4439 }
4440 
assign_scalar_id_before_mov(struct bpf_verifier_env * env,struct bpf_reg_state * src_reg)4441 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4442 					struct bpf_reg_state *src_reg)
4443 {
4444 	if (src_reg->type != SCALAR_VALUE)
4445 		return;
4446 
4447 	if (src_reg->id & BPF_ADD_CONST) {
4448 		/*
4449 		 * The verifier is processing rX = rY insn and
4450 		 * rY->id has special linked register already.
4451 		 * Cleared it, since multiple rX += const are not supported.
4452 		 */
4453 		src_reg->id = 0;
4454 		src_reg->off = 0;
4455 	}
4456 
4457 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4458 		/* Ensure that src_reg has a valid ID that will be copied to
4459 		 * dst_reg and then will be used by find_equal_scalars() to
4460 		 * propagate min/max range.
4461 		 */
4462 		src_reg->id = ++env->id_gen;
4463 }
4464 
4465 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)4466 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4467 {
4468 	struct bpf_reg_state *parent = dst->parent;
4469 	enum bpf_reg_liveness live = dst->live;
4470 
4471 	*dst = *src;
4472 	dst->parent = parent;
4473 	dst->live = live;
4474 }
4475 
save_register_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)4476 static void save_register_state(struct bpf_verifier_env *env,
4477 				struct bpf_func_state *state,
4478 				int spi, struct bpf_reg_state *reg,
4479 				int size)
4480 {
4481 	int i;
4482 
4483 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4484 	if (size == BPF_REG_SIZE)
4485 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4486 
4487 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4488 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4489 
4490 	/* size < 8 bytes spill */
4491 	for (; i; i--)
4492 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4493 }
4494 
is_bpf_st_mem(struct bpf_insn * insn)4495 static bool is_bpf_st_mem(struct bpf_insn *insn)
4496 {
4497 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4498 }
4499 
get_reg_width(struct bpf_reg_state * reg)4500 static int get_reg_width(struct bpf_reg_state *reg)
4501 {
4502 	return fls64(reg->umax_value);
4503 }
4504 
4505 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4506  * stack boundary and alignment are checked in check_mem_access()
4507  */
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)4508 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4509 				       /* stack frame we're writing to */
4510 				       struct bpf_func_state *state,
4511 				       int off, int size, int value_regno,
4512 				       int insn_idx)
4513 {
4514 	struct bpf_func_state *cur; /* state of the current function */
4515 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4516 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4517 	struct bpf_reg_state *reg = NULL;
4518 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
4519 
4520 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4521 	 * so it's aligned access and [off, off + size) are within stack limits
4522 	 */
4523 	if (!env->allow_ptr_leaks &&
4524 	    is_spilled_reg(&state->stack[spi]) &&
4525 	    size != BPF_REG_SIZE) {
4526 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4527 		return -EACCES;
4528 	}
4529 
4530 	cur = env->cur_state->frame[env->cur_state->curframe];
4531 	if (value_regno >= 0)
4532 		reg = &cur->regs[value_regno];
4533 	if (!env->bypass_spec_v4) {
4534 		bool sanitize = reg && is_spillable_regtype(reg->type);
4535 
4536 		for (i = 0; i < size; i++) {
4537 			u8 type = state->stack[spi].slot_type[i];
4538 
4539 			if (type != STACK_MISC && type != STACK_ZERO) {
4540 				sanitize = true;
4541 				break;
4542 			}
4543 		}
4544 
4545 		if (sanitize)
4546 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4547 	}
4548 
4549 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4550 	if (err)
4551 		return err;
4552 
4553 	mark_stack_slot_scratched(env, spi);
4554 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
4555 		bool reg_value_fits;
4556 
4557 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
4558 		/* Make sure that reg had an ID to build a relation on spill. */
4559 		if (reg_value_fits)
4560 			assign_scalar_id_before_mov(env, reg);
4561 		save_register_state(env, state, spi, reg, size);
4562 		/* Break the relation on a narrowing spill. */
4563 		if (!reg_value_fits)
4564 			state->stack[spi].spilled_ptr.id = 0;
4565 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4566 		   env->bpf_capable) {
4567 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
4568 
4569 		memset(tmp_reg, 0, sizeof(*tmp_reg));
4570 		__mark_reg_known(tmp_reg, insn->imm);
4571 		tmp_reg->type = SCALAR_VALUE;
4572 		save_register_state(env, state, spi, tmp_reg, size);
4573 	} else if (reg && is_spillable_regtype(reg->type)) {
4574 		/* register containing pointer is being spilled into stack */
4575 		if (size != BPF_REG_SIZE) {
4576 			verbose_linfo(env, insn_idx, "; ");
4577 			verbose(env, "invalid size of register spill\n");
4578 			return -EACCES;
4579 		}
4580 		if (state != cur && reg->type == PTR_TO_STACK) {
4581 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4582 			return -EINVAL;
4583 		}
4584 		save_register_state(env, state, spi, reg, size);
4585 	} else {
4586 		u8 type = STACK_MISC;
4587 
4588 		/* regular write of data into stack destroys any spilled ptr */
4589 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4590 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4591 		if (is_stack_slot_special(&state->stack[spi]))
4592 			for (i = 0; i < BPF_REG_SIZE; i++)
4593 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4594 
4595 		/* only mark the slot as written if all 8 bytes were written
4596 		 * otherwise read propagation may incorrectly stop too soon
4597 		 * when stack slots are partially written.
4598 		 * This heuristic means that read propagation will be
4599 		 * conservative, since it will add reg_live_read marks
4600 		 * to stack slots all the way to first state when programs
4601 		 * writes+reads less than 8 bytes
4602 		 */
4603 		if (size == BPF_REG_SIZE)
4604 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4605 
4606 		/* when we zero initialize stack slots mark them as such */
4607 		if ((reg && register_is_null(reg)) ||
4608 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4609 			/* STACK_ZERO case happened because register spill
4610 			 * wasn't properly aligned at the stack slot boundary,
4611 			 * so it's not a register spill anymore; force
4612 			 * originating register to be precise to make
4613 			 * STACK_ZERO correct for subsequent states
4614 			 */
4615 			err = mark_chain_precision(env, value_regno);
4616 			if (err)
4617 				return err;
4618 			type = STACK_ZERO;
4619 		}
4620 
4621 		/* Mark slots affected by this stack write. */
4622 		for (i = 0; i < size; i++)
4623 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
4624 		insn_flags = 0; /* not a register spill */
4625 	}
4626 
4627 	if (insn_flags)
4628 		return push_jmp_history(env, env->cur_state, insn_flags);
4629 	return 0;
4630 }
4631 
4632 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4633  * known to contain a variable offset.
4634  * This function checks whether the write is permitted and conservatively
4635  * tracks the effects of the write, considering that each stack slot in the
4636  * dynamic range is potentially written to.
4637  *
4638  * 'off' includes 'regno->off'.
4639  * 'value_regno' can be -1, meaning that an unknown value is being written to
4640  * the stack.
4641  *
4642  * Spilled pointers in range are not marked as written because we don't know
4643  * what's going to be actually written. This means that read propagation for
4644  * future reads cannot be terminated by this write.
4645  *
4646  * For privileged programs, uninitialized stack slots are considered
4647  * initialized by this write (even though we don't know exactly what offsets
4648  * are going to be written to). The idea is that we don't want the verifier to
4649  * reject future reads that access slots written to through variable offsets.
4650  */
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)4651 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4652 				     /* func where register points to */
4653 				     struct bpf_func_state *state,
4654 				     int ptr_regno, int off, int size,
4655 				     int value_regno, int insn_idx)
4656 {
4657 	struct bpf_func_state *cur; /* state of the current function */
4658 	int min_off, max_off;
4659 	int i, err;
4660 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4661 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4662 	bool writing_zero = false;
4663 	/* set if the fact that we're writing a zero is used to let any
4664 	 * stack slots remain STACK_ZERO
4665 	 */
4666 	bool zero_used = false;
4667 
4668 	cur = env->cur_state->frame[env->cur_state->curframe];
4669 	ptr_reg = &cur->regs[ptr_regno];
4670 	min_off = ptr_reg->smin_value + off;
4671 	max_off = ptr_reg->smax_value + off + size;
4672 	if (value_regno >= 0)
4673 		value_reg = &cur->regs[value_regno];
4674 	if ((value_reg && register_is_null(value_reg)) ||
4675 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4676 		writing_zero = true;
4677 
4678 	for (i = min_off; i < max_off; i++) {
4679 		int spi;
4680 
4681 		spi = __get_spi(i);
4682 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4683 		if (err)
4684 			return err;
4685 	}
4686 
4687 	/* Variable offset writes destroy any spilled pointers in range. */
4688 	for (i = min_off; i < max_off; i++) {
4689 		u8 new_type, *stype;
4690 		int slot, spi;
4691 
4692 		slot = -i - 1;
4693 		spi = slot / BPF_REG_SIZE;
4694 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4695 		mark_stack_slot_scratched(env, spi);
4696 
4697 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4698 			/* Reject the write if range we may write to has not
4699 			 * been initialized beforehand. If we didn't reject
4700 			 * here, the ptr status would be erased below (even
4701 			 * though not all slots are actually overwritten),
4702 			 * possibly opening the door to leaks.
4703 			 *
4704 			 * We do however catch STACK_INVALID case below, and
4705 			 * only allow reading possibly uninitialized memory
4706 			 * later for CAP_PERFMON, as the write may not happen to
4707 			 * that slot.
4708 			 */
4709 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4710 				insn_idx, i);
4711 			return -EINVAL;
4712 		}
4713 
4714 		/* If writing_zero and the spi slot contains a spill of value 0,
4715 		 * maintain the spill type.
4716 		 */
4717 		if (writing_zero && *stype == STACK_SPILL &&
4718 		    is_spilled_scalar_reg(&state->stack[spi])) {
4719 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
4720 
4721 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
4722 				zero_used = true;
4723 				continue;
4724 			}
4725 		}
4726 
4727 		/* Erase all other spilled pointers. */
4728 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4729 
4730 		/* Update the slot type. */
4731 		new_type = STACK_MISC;
4732 		if (writing_zero && *stype == STACK_ZERO) {
4733 			new_type = STACK_ZERO;
4734 			zero_used = true;
4735 		}
4736 		/* If the slot is STACK_INVALID, we check whether it's OK to
4737 		 * pretend that it will be initialized by this write. The slot
4738 		 * might not actually be written to, and so if we mark it as
4739 		 * initialized future reads might leak uninitialized memory.
4740 		 * For privileged programs, we will accept such reads to slots
4741 		 * that may or may not be written because, if we're reject
4742 		 * them, the error would be too confusing.
4743 		 */
4744 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4745 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4746 					insn_idx, i);
4747 			return -EINVAL;
4748 		}
4749 		*stype = new_type;
4750 	}
4751 	if (zero_used) {
4752 		/* backtracking doesn't work for STACK_ZERO yet. */
4753 		err = mark_chain_precision(env, value_regno);
4754 		if (err)
4755 			return err;
4756 	}
4757 	return 0;
4758 }
4759 
4760 /* When register 'dst_regno' is assigned some values from stack[min_off,
4761  * max_off), we set the register's type according to the types of the
4762  * respective stack slots. If all the stack values are known to be zeros, then
4763  * so is the destination reg. Otherwise, the register is considered to be
4764  * SCALAR. This function does not deal with register filling; the caller must
4765  * ensure that all spilled registers in the stack range have been marked as
4766  * read.
4767  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)4768 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4769 				/* func where src register points to */
4770 				struct bpf_func_state *ptr_state,
4771 				int min_off, int max_off, int dst_regno)
4772 {
4773 	struct bpf_verifier_state *vstate = env->cur_state;
4774 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4775 	int i, slot, spi;
4776 	u8 *stype;
4777 	int zeros = 0;
4778 
4779 	for (i = min_off; i < max_off; i++) {
4780 		slot = -i - 1;
4781 		spi = slot / BPF_REG_SIZE;
4782 		mark_stack_slot_scratched(env, spi);
4783 		stype = ptr_state->stack[spi].slot_type;
4784 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4785 			break;
4786 		zeros++;
4787 	}
4788 	if (zeros == max_off - min_off) {
4789 		/* Any access_size read into register is zero extended,
4790 		 * so the whole register == const_zero.
4791 		 */
4792 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
4793 	} else {
4794 		/* have read misc data from the stack */
4795 		mark_reg_unknown(env, state->regs, dst_regno);
4796 	}
4797 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4798 }
4799 
4800 /* Read the stack at 'off' and put the results into the register indicated by
4801  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4802  * spilled reg.
4803  *
4804  * 'dst_regno' can be -1, meaning that the read value is not going to a
4805  * register.
4806  *
4807  * The access is assumed to be within the current stack bounds.
4808  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)4809 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4810 				      /* func where src register points to */
4811 				      struct bpf_func_state *reg_state,
4812 				      int off, int size, int dst_regno)
4813 {
4814 	struct bpf_verifier_state *vstate = env->cur_state;
4815 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4816 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4817 	struct bpf_reg_state *reg;
4818 	u8 *stype, type;
4819 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
4820 
4821 	stype = reg_state->stack[spi].slot_type;
4822 	reg = &reg_state->stack[spi].spilled_ptr;
4823 
4824 	mark_stack_slot_scratched(env, spi);
4825 
4826 	if (is_spilled_reg(&reg_state->stack[spi])) {
4827 		u8 spill_size = 1;
4828 
4829 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4830 			spill_size++;
4831 
4832 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4833 			if (reg->type != SCALAR_VALUE) {
4834 				verbose_linfo(env, env->insn_idx, "; ");
4835 				verbose(env, "invalid size of register fill\n");
4836 				return -EACCES;
4837 			}
4838 
4839 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4840 			if (dst_regno < 0)
4841 				return 0;
4842 
4843 			if (size <= spill_size &&
4844 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
4845 				/* The earlier check_reg_arg() has decided the
4846 				 * subreg_def for this insn.  Save it first.
4847 				 */
4848 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4849 
4850 				copy_register_state(&state->regs[dst_regno], reg);
4851 				state->regs[dst_regno].subreg_def = subreg_def;
4852 
4853 				/* Break the relation on a narrowing fill.
4854 				 * coerce_reg_to_size will adjust the boundaries.
4855 				 */
4856 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
4857 					state->regs[dst_regno].id = 0;
4858 			} else {
4859 				int spill_cnt = 0, zero_cnt = 0;
4860 
4861 				for (i = 0; i < size; i++) {
4862 					type = stype[(slot - i) % BPF_REG_SIZE];
4863 					if (type == STACK_SPILL) {
4864 						spill_cnt++;
4865 						continue;
4866 					}
4867 					if (type == STACK_MISC)
4868 						continue;
4869 					if (type == STACK_ZERO) {
4870 						zero_cnt++;
4871 						continue;
4872 					}
4873 					if (type == STACK_INVALID && env->allow_uninit_stack)
4874 						continue;
4875 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4876 						off, i, size);
4877 					return -EACCES;
4878 				}
4879 
4880 				if (spill_cnt == size &&
4881 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
4882 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4883 					/* this IS register fill, so keep insn_flags */
4884 				} else if (zero_cnt == size) {
4885 					/* similarly to mark_reg_stack_read(), preserve zeroes */
4886 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
4887 					insn_flags = 0; /* not restoring original register state */
4888 				} else {
4889 					mark_reg_unknown(env, state->regs, dst_regno);
4890 					insn_flags = 0; /* not restoring original register state */
4891 				}
4892 			}
4893 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4894 		} else if (dst_regno >= 0) {
4895 			/* restore register state from stack */
4896 			copy_register_state(&state->regs[dst_regno], reg);
4897 			/* mark reg as written since spilled pointer state likely
4898 			 * has its liveness marks cleared by is_state_visited()
4899 			 * which resets stack/reg liveness for state transitions
4900 			 */
4901 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4902 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4903 			/* If dst_regno==-1, the caller is asking us whether
4904 			 * it is acceptable to use this value as a SCALAR_VALUE
4905 			 * (e.g. for XADD).
4906 			 * We must not allow unprivileged callers to do that
4907 			 * with spilled pointers.
4908 			 */
4909 			verbose(env, "leaking pointer from stack off %d\n",
4910 				off);
4911 			return -EACCES;
4912 		}
4913 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4914 	} else {
4915 		for (i = 0; i < size; i++) {
4916 			type = stype[(slot - i) % BPF_REG_SIZE];
4917 			if (type == STACK_MISC)
4918 				continue;
4919 			if (type == STACK_ZERO)
4920 				continue;
4921 			if (type == STACK_INVALID && env->allow_uninit_stack)
4922 				continue;
4923 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4924 				off, i, size);
4925 			return -EACCES;
4926 		}
4927 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4928 		if (dst_regno >= 0)
4929 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4930 		insn_flags = 0; /* we are not restoring spilled register */
4931 	}
4932 	if (insn_flags)
4933 		return push_jmp_history(env, env->cur_state, insn_flags);
4934 	return 0;
4935 }
4936 
4937 enum bpf_access_src {
4938 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4939 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4940 };
4941 
4942 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4943 					 int regno, int off, int access_size,
4944 					 bool zero_size_allowed,
4945 					 enum bpf_access_src type,
4946 					 struct bpf_call_arg_meta *meta);
4947 
reg_state(struct bpf_verifier_env * env,int regno)4948 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4949 {
4950 	return cur_regs(env) + regno;
4951 }
4952 
4953 /* Read the stack at 'ptr_regno + off' and put the result into the register
4954  * 'dst_regno'.
4955  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4956  * but not its variable offset.
4957  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4958  *
4959  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4960  * filling registers (i.e. reads of spilled register cannot be detected when
4961  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4962  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4963  * offset; for a fixed offset check_stack_read_fixed_off should be used
4964  * instead.
4965  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)4966 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4967 				    int ptr_regno, int off, int size, int dst_regno)
4968 {
4969 	/* The state of the source register. */
4970 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4971 	struct bpf_func_state *ptr_state = func(env, reg);
4972 	int err;
4973 	int min_off, max_off;
4974 
4975 	/* Note that we pass a NULL meta, so raw access will not be permitted.
4976 	 */
4977 	err = check_stack_range_initialized(env, ptr_regno, off, size,
4978 					    false, ACCESS_DIRECT, NULL);
4979 	if (err)
4980 		return err;
4981 
4982 	min_off = reg->smin_value + off;
4983 	max_off = reg->smax_value + off;
4984 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4985 	return 0;
4986 }
4987 
4988 /* check_stack_read dispatches to check_stack_read_fixed_off or
4989  * check_stack_read_var_off.
4990  *
4991  * The caller must ensure that the offset falls within the allocated stack
4992  * bounds.
4993  *
4994  * 'dst_regno' is a register which will receive the value from the stack. It
4995  * can be -1, meaning that the read value is not going to a register.
4996  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)4997 static int check_stack_read(struct bpf_verifier_env *env,
4998 			    int ptr_regno, int off, int size,
4999 			    int dst_regno)
5000 {
5001 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5002 	struct bpf_func_state *state = func(env, reg);
5003 	int err;
5004 	/* Some accesses are only permitted with a static offset. */
5005 	bool var_off = !tnum_is_const(reg->var_off);
5006 
5007 	/* The offset is required to be static when reads don't go to a
5008 	 * register, in order to not leak pointers (see
5009 	 * check_stack_read_fixed_off).
5010 	 */
5011 	if (dst_regno < 0 && var_off) {
5012 		char tn_buf[48];
5013 
5014 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5015 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5016 			tn_buf, off, size);
5017 		return -EACCES;
5018 	}
5019 	/* Variable offset is prohibited for unprivileged mode for simplicity
5020 	 * since it requires corresponding support in Spectre masking for stack
5021 	 * ALU. See also retrieve_ptr_limit(). The check in
5022 	 * check_stack_access_for_ptr_arithmetic() called by
5023 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5024 	 * with variable offsets, therefore no check is required here. Further,
5025 	 * just checking it here would be insufficient as speculative stack
5026 	 * writes could still lead to unsafe speculative behaviour.
5027 	 */
5028 	if (!var_off) {
5029 		off += reg->var_off.value;
5030 		err = check_stack_read_fixed_off(env, state, off, size,
5031 						 dst_regno);
5032 	} else {
5033 		/* Variable offset stack reads need more conservative handling
5034 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5035 		 * branch.
5036 		 */
5037 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5038 					       dst_regno);
5039 	}
5040 	return err;
5041 }
5042 
5043 
5044 /* check_stack_write dispatches to check_stack_write_fixed_off or
5045  * check_stack_write_var_off.
5046  *
5047  * 'ptr_regno' is the register used as a pointer into the stack.
5048  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5049  * 'value_regno' is the register whose value we're writing to the stack. It can
5050  * be -1, meaning that we're not writing from a register.
5051  *
5052  * The caller must ensure that the offset falls within the maximum stack size.
5053  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5054 static int check_stack_write(struct bpf_verifier_env *env,
5055 			     int ptr_regno, int off, int size,
5056 			     int value_regno, int insn_idx)
5057 {
5058 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5059 	struct bpf_func_state *state = func(env, reg);
5060 	int err;
5061 
5062 	if (tnum_is_const(reg->var_off)) {
5063 		off += reg->var_off.value;
5064 		err = check_stack_write_fixed_off(env, state, off, size,
5065 						  value_regno, insn_idx);
5066 	} else {
5067 		/* Variable offset stack reads need more conservative handling
5068 		 * than fixed offset ones.
5069 		 */
5070 		err = check_stack_write_var_off(env, state,
5071 						ptr_regno, off, size,
5072 						value_regno, insn_idx);
5073 	}
5074 	return err;
5075 }
5076 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5077 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5078 				 int off, int size, enum bpf_access_type type)
5079 {
5080 	struct bpf_reg_state *regs = cur_regs(env);
5081 	struct bpf_map *map = regs[regno].map_ptr;
5082 	u32 cap = bpf_map_flags_to_cap(map);
5083 
5084 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5085 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5086 			map->value_size, off, size);
5087 		return -EACCES;
5088 	}
5089 
5090 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5091 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5092 			map->value_size, off, size);
5093 		return -EACCES;
5094 	}
5095 
5096 	return 0;
5097 }
5098 
5099 /* 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)5100 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5101 			      int off, int size, u32 mem_size,
5102 			      bool zero_size_allowed)
5103 {
5104 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5105 	struct bpf_reg_state *reg;
5106 
5107 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5108 		return 0;
5109 
5110 	reg = &cur_regs(env)[regno];
5111 	switch (reg->type) {
5112 	case PTR_TO_MAP_KEY:
5113 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5114 			mem_size, off, size);
5115 		break;
5116 	case PTR_TO_MAP_VALUE:
5117 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5118 			mem_size, off, size);
5119 		break;
5120 	case PTR_TO_PACKET:
5121 	case PTR_TO_PACKET_META:
5122 	case PTR_TO_PACKET_END:
5123 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5124 			off, size, regno, reg->id, off, mem_size);
5125 		break;
5126 	case PTR_TO_MEM:
5127 	default:
5128 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5129 			mem_size, off, size);
5130 	}
5131 
5132 	return -EACCES;
5133 }
5134 
5135 /* 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)5136 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5137 				   int off, int size, u32 mem_size,
5138 				   bool zero_size_allowed)
5139 {
5140 	struct bpf_verifier_state *vstate = env->cur_state;
5141 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5142 	struct bpf_reg_state *reg = &state->regs[regno];
5143 	int err;
5144 
5145 	/* We may have adjusted the register pointing to memory region, so we
5146 	 * need to try adding each of min_value and max_value to off
5147 	 * to make sure our theoretical access will be safe.
5148 	 *
5149 	 * The minimum value is only important with signed
5150 	 * comparisons where we can't assume the floor of a
5151 	 * value is 0.  If we are using signed variables for our
5152 	 * index'es we need to make sure that whatever we use
5153 	 * will have a set floor within our range.
5154 	 */
5155 	if (reg->smin_value < 0 &&
5156 	    (reg->smin_value == S64_MIN ||
5157 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5158 	      reg->smin_value + off < 0)) {
5159 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5160 			regno);
5161 		return -EACCES;
5162 	}
5163 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5164 				 mem_size, zero_size_allowed);
5165 	if (err) {
5166 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5167 			regno);
5168 		return err;
5169 	}
5170 
5171 	/* If we haven't set a max value then we need to bail since we can't be
5172 	 * sure we won't do bad things.
5173 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5174 	 */
5175 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5176 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5177 			regno);
5178 		return -EACCES;
5179 	}
5180 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5181 				 mem_size, zero_size_allowed);
5182 	if (err) {
5183 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5184 			regno);
5185 		return err;
5186 	}
5187 
5188 	return 0;
5189 }
5190 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5191 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5192 			       const struct bpf_reg_state *reg, int regno,
5193 			       bool fixed_off_ok)
5194 {
5195 	/* Access to this pointer-typed register or passing it to a helper
5196 	 * is only allowed in its original, unmodified form.
5197 	 */
5198 
5199 	if (reg->off < 0) {
5200 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5201 			reg_type_str(env, reg->type), regno, reg->off);
5202 		return -EACCES;
5203 	}
5204 
5205 	if (!fixed_off_ok && reg->off) {
5206 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5207 			reg_type_str(env, reg->type), regno, reg->off);
5208 		return -EACCES;
5209 	}
5210 
5211 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5212 		char tn_buf[48];
5213 
5214 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5215 		verbose(env, "variable %s access var_off=%s disallowed\n",
5216 			reg_type_str(env, reg->type), tn_buf);
5217 		return -EACCES;
5218 	}
5219 
5220 	return 0;
5221 }
5222 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5223 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5224 		             const struct bpf_reg_state *reg, int regno)
5225 {
5226 	return __check_ptr_off_reg(env, reg, regno, false);
5227 }
5228 
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5229 static int map_kptr_match_type(struct bpf_verifier_env *env,
5230 			       struct btf_field *kptr_field,
5231 			       struct bpf_reg_state *reg, u32 regno)
5232 {
5233 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5234 	int perm_flags;
5235 	const char *reg_name = "";
5236 
5237 	if (btf_is_kernel(reg->btf)) {
5238 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5239 
5240 		/* Only unreferenced case accepts untrusted pointers */
5241 		if (kptr_field->type == BPF_KPTR_UNREF)
5242 			perm_flags |= PTR_UNTRUSTED;
5243 	} else {
5244 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5245 		if (kptr_field->type == BPF_KPTR_PERCPU)
5246 			perm_flags |= MEM_PERCPU;
5247 	}
5248 
5249 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5250 		goto bad_type;
5251 
5252 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5253 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5254 
5255 	/* For ref_ptr case, release function check should ensure we get one
5256 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5257 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5258 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5259 	 * reg->off and reg->ref_obj_id are not needed here.
5260 	 */
5261 	if (__check_ptr_off_reg(env, reg, regno, true))
5262 		return -EACCES;
5263 
5264 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5265 	 * we also need to take into account the reg->off.
5266 	 *
5267 	 * We want to support cases like:
5268 	 *
5269 	 * struct foo {
5270 	 *         struct bar br;
5271 	 *         struct baz bz;
5272 	 * };
5273 	 *
5274 	 * struct foo *v;
5275 	 * v = func();	      // PTR_TO_BTF_ID
5276 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5277 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5278 	 *                    // first member type of struct after comparison fails
5279 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5280 	 *                    // to match type
5281 	 *
5282 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5283 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5284 	 * the struct to match type against first member of struct, i.e. reject
5285 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5286 	 * strict mode to true for type match.
5287 	 */
5288 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5289 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5290 				  kptr_field->type != BPF_KPTR_UNREF))
5291 		goto bad_type;
5292 	return 0;
5293 bad_type:
5294 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5295 		reg_type_str(env, reg->type), reg_name);
5296 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5297 	if (kptr_field->type == BPF_KPTR_UNREF)
5298 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5299 			targ_name);
5300 	else
5301 		verbose(env, "\n");
5302 	return -EINVAL;
5303 }
5304 
in_sleepable(struct bpf_verifier_env * env)5305 static bool in_sleepable(struct bpf_verifier_env *env)
5306 {
5307 	return env->prog->sleepable ||
5308 	       (env->cur_state && env->cur_state->in_sleepable);
5309 }
5310 
5311 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5312  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5313  */
in_rcu_cs(struct bpf_verifier_env * env)5314 static bool in_rcu_cs(struct bpf_verifier_env *env)
5315 {
5316 	return env->cur_state->active_rcu_lock ||
5317 	       env->cur_state->active_lock.ptr ||
5318 	       !in_sleepable(env);
5319 }
5320 
5321 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5322 BTF_SET_START(rcu_protected_types)
BTF_ID(struct,prog_test_ref_kfunc)5323 BTF_ID(struct, prog_test_ref_kfunc)
5324 #ifdef CONFIG_CGROUPS
5325 BTF_ID(struct, cgroup)
5326 #endif
5327 #ifdef CONFIG_BPF_JIT
5328 BTF_ID(struct, bpf_cpumask)
5329 #endif
5330 BTF_ID(struct, task_struct)
5331 BTF_ID(struct, bpf_crypto_ctx)
5332 BTF_SET_END(rcu_protected_types)
5333 
5334 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5335 {
5336 	if (!btf_is_kernel(btf))
5337 		return true;
5338 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5339 }
5340 
kptr_pointee_btf_record(struct btf_field * kptr_field)5341 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5342 {
5343 	struct btf_struct_meta *meta;
5344 
5345 	if (btf_is_kernel(kptr_field->kptr.btf))
5346 		return NULL;
5347 
5348 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5349 				    kptr_field->kptr.btf_id);
5350 
5351 	return meta ? meta->record : NULL;
5352 }
5353 
rcu_safe_kptr(const struct btf_field * field)5354 static bool rcu_safe_kptr(const struct btf_field *field)
5355 {
5356 	const struct btf_field_kptr *kptr = &field->kptr;
5357 
5358 	return field->type == BPF_KPTR_PERCPU ||
5359 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5360 }
5361 
btf_ld_kptr_type(struct bpf_verifier_env * env,struct btf_field * kptr_field)5362 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5363 {
5364 	struct btf_record *rec;
5365 	u32 ret;
5366 
5367 	ret = PTR_MAYBE_NULL;
5368 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5369 		ret |= MEM_RCU;
5370 		if (kptr_field->type == BPF_KPTR_PERCPU)
5371 			ret |= MEM_PERCPU;
5372 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5373 			ret |= MEM_ALLOC;
5374 
5375 		rec = kptr_pointee_btf_record(kptr_field);
5376 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5377 			ret |= NON_OWN_REF;
5378 	} else {
5379 		ret |= PTR_UNTRUSTED;
5380 	}
5381 
5382 	return ret;
5383 }
5384 
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)5385 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5386 				 int value_regno, int insn_idx,
5387 				 struct btf_field *kptr_field)
5388 {
5389 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5390 	int class = BPF_CLASS(insn->code);
5391 	struct bpf_reg_state *val_reg;
5392 
5393 	/* Things we already checked for in check_map_access and caller:
5394 	 *  - Reject cases where variable offset may touch kptr
5395 	 *  - size of access (must be BPF_DW)
5396 	 *  - tnum_is_const(reg->var_off)
5397 	 *  - kptr_field->offset == off + reg->var_off.value
5398 	 */
5399 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5400 	if (BPF_MODE(insn->code) != BPF_MEM) {
5401 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5402 		return -EACCES;
5403 	}
5404 
5405 	/* We only allow loading referenced kptr, since it will be marked as
5406 	 * untrusted, similar to unreferenced kptr.
5407 	 */
5408 	if (class != BPF_LDX &&
5409 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5410 		verbose(env, "store to referenced kptr disallowed\n");
5411 		return -EACCES;
5412 	}
5413 
5414 	if (class == BPF_LDX) {
5415 		val_reg = reg_state(env, value_regno);
5416 		/* We can simply mark the value_regno receiving the pointer
5417 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5418 		 */
5419 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5420 				kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5421 	} else if (class == BPF_STX) {
5422 		val_reg = reg_state(env, value_regno);
5423 		if (!register_is_null(val_reg) &&
5424 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5425 			return -EACCES;
5426 	} else if (class == BPF_ST) {
5427 		if (insn->imm) {
5428 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5429 				kptr_field->offset);
5430 			return -EACCES;
5431 		}
5432 	} else {
5433 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5434 		return -EACCES;
5435 	}
5436 	return 0;
5437 }
5438 
5439 /* 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)5440 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5441 			    int off, int size, bool zero_size_allowed,
5442 			    enum bpf_access_src src)
5443 {
5444 	struct bpf_verifier_state *vstate = env->cur_state;
5445 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5446 	struct bpf_reg_state *reg = &state->regs[regno];
5447 	struct bpf_map *map = reg->map_ptr;
5448 	struct btf_record *rec;
5449 	int err, i;
5450 
5451 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5452 				      zero_size_allowed);
5453 	if (err)
5454 		return err;
5455 
5456 	if (IS_ERR_OR_NULL(map->record))
5457 		return 0;
5458 	rec = map->record;
5459 	for (i = 0; i < rec->cnt; i++) {
5460 		struct btf_field *field = &rec->fields[i];
5461 		u32 p = field->offset;
5462 
5463 		/* If any part of a field  can be touched by load/store, reject
5464 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5465 		 * it is sufficient to check x1 < y2 && y1 < x2.
5466 		 */
5467 		if (reg->smin_value + off < p + field->size &&
5468 		    p < reg->umax_value + off + size) {
5469 			switch (field->type) {
5470 			case BPF_KPTR_UNREF:
5471 			case BPF_KPTR_REF:
5472 			case BPF_KPTR_PERCPU:
5473 				if (src != ACCESS_DIRECT) {
5474 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5475 					return -EACCES;
5476 				}
5477 				if (!tnum_is_const(reg->var_off)) {
5478 					verbose(env, "kptr access cannot have variable offset\n");
5479 					return -EACCES;
5480 				}
5481 				if (p != off + reg->var_off.value) {
5482 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5483 						p, off + reg->var_off.value);
5484 					return -EACCES;
5485 				}
5486 				if (size != bpf_size_to_bytes(BPF_DW)) {
5487 					verbose(env, "kptr access size must be BPF_DW\n");
5488 					return -EACCES;
5489 				}
5490 				break;
5491 			default:
5492 				verbose(env, "%s cannot be accessed directly by load/store\n",
5493 					btf_field_type_name(field->type));
5494 				return -EACCES;
5495 			}
5496 		}
5497 	}
5498 	return 0;
5499 }
5500 
5501 #define MAX_PACKET_OFF 0xffff
5502 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)5503 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5504 				       const struct bpf_call_arg_meta *meta,
5505 				       enum bpf_access_type t)
5506 {
5507 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5508 
5509 	switch (prog_type) {
5510 	/* Program types only with direct read access go here! */
5511 	case BPF_PROG_TYPE_LWT_IN:
5512 	case BPF_PROG_TYPE_LWT_OUT:
5513 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5514 	case BPF_PROG_TYPE_SK_REUSEPORT:
5515 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5516 	case BPF_PROG_TYPE_CGROUP_SKB:
5517 		if (t == BPF_WRITE)
5518 			return false;
5519 		fallthrough;
5520 
5521 	/* Program types with direct read + write access go here! */
5522 	case BPF_PROG_TYPE_SCHED_CLS:
5523 	case BPF_PROG_TYPE_SCHED_ACT:
5524 	case BPF_PROG_TYPE_XDP:
5525 	case BPF_PROG_TYPE_LWT_XMIT:
5526 	case BPF_PROG_TYPE_SK_SKB:
5527 	case BPF_PROG_TYPE_SK_MSG:
5528 		if (meta)
5529 			return meta->pkt_access;
5530 
5531 		env->seen_direct_write = true;
5532 		return true;
5533 
5534 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5535 		if (t == BPF_WRITE)
5536 			env->seen_direct_write = true;
5537 
5538 		return true;
5539 
5540 	default:
5541 		return false;
5542 	}
5543 }
5544 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)5545 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5546 			       int size, bool zero_size_allowed)
5547 {
5548 	struct bpf_reg_state *regs = cur_regs(env);
5549 	struct bpf_reg_state *reg = &regs[regno];
5550 	int err;
5551 
5552 	/* We may have added a variable offset to the packet pointer; but any
5553 	 * reg->range we have comes after that.  We are only checking the fixed
5554 	 * offset.
5555 	 */
5556 
5557 	/* We don't allow negative numbers, because we aren't tracking enough
5558 	 * detail to prove they're safe.
5559 	 */
5560 	if (reg->smin_value < 0) {
5561 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5562 			regno);
5563 		return -EACCES;
5564 	}
5565 
5566 	err = reg->range < 0 ? -EINVAL :
5567 	      __check_mem_access(env, regno, off, size, reg->range,
5568 				 zero_size_allowed);
5569 	if (err) {
5570 		verbose(env, "R%d offset is outside of the packet\n", regno);
5571 		return err;
5572 	}
5573 
5574 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5575 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5576 	 * otherwise find_good_pkt_pointers would have refused to set range info
5577 	 * that __check_mem_access would have rejected this pkt access.
5578 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5579 	 */
5580 	env->prog->aux->max_pkt_offset =
5581 		max_t(u32, env->prog->aux->max_pkt_offset,
5582 		      off + reg->umax_value + size - 1);
5583 
5584 	return err;
5585 }
5586 
5587 /* 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,enum bpf_reg_type * reg_type,struct btf ** btf,u32 * btf_id)5588 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5589 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5590 			    struct btf **btf, u32 *btf_id)
5591 {
5592 	struct bpf_insn_access_aux info = {
5593 		.reg_type = *reg_type,
5594 		.log = &env->log,
5595 	};
5596 
5597 	if (env->ops->is_valid_access &&
5598 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5599 		/* A non zero info.ctx_field_size indicates that this field is a
5600 		 * candidate for later verifier transformation to load the whole
5601 		 * field and then apply a mask when accessed with a narrower
5602 		 * access than actual ctx access size. A zero info.ctx_field_size
5603 		 * will only allow for whole field access and rejects any other
5604 		 * type of narrower access.
5605 		 */
5606 		*reg_type = info.reg_type;
5607 
5608 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5609 			*btf = info.btf;
5610 			*btf_id = info.btf_id;
5611 		} else {
5612 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5613 		}
5614 		/* remember the offset of last byte accessed in ctx */
5615 		if (env->prog->aux->max_ctx_offset < off + size)
5616 			env->prog->aux->max_ctx_offset = off + size;
5617 		return 0;
5618 	}
5619 
5620 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5621 	return -EACCES;
5622 }
5623 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)5624 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5625 				  int size)
5626 {
5627 	if (size < 0 || off < 0 ||
5628 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5629 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5630 			off, size);
5631 		return -EACCES;
5632 	}
5633 	return 0;
5634 }
5635 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)5636 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5637 			     u32 regno, int off, int size,
5638 			     enum bpf_access_type t)
5639 {
5640 	struct bpf_reg_state *regs = cur_regs(env);
5641 	struct bpf_reg_state *reg = &regs[regno];
5642 	struct bpf_insn_access_aux info = {};
5643 	bool valid;
5644 
5645 	if (reg->smin_value < 0) {
5646 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5647 			regno);
5648 		return -EACCES;
5649 	}
5650 
5651 	switch (reg->type) {
5652 	case PTR_TO_SOCK_COMMON:
5653 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5654 		break;
5655 	case PTR_TO_SOCKET:
5656 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5657 		break;
5658 	case PTR_TO_TCP_SOCK:
5659 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5660 		break;
5661 	case PTR_TO_XDP_SOCK:
5662 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5663 		break;
5664 	default:
5665 		valid = false;
5666 	}
5667 
5668 
5669 	if (valid) {
5670 		env->insn_aux_data[insn_idx].ctx_field_size =
5671 			info.ctx_field_size;
5672 		return 0;
5673 	}
5674 
5675 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5676 		regno, reg_type_str(env, reg->type), off, size);
5677 
5678 	return -EACCES;
5679 }
5680 
is_pointer_value(struct bpf_verifier_env * env,int regno)5681 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5682 {
5683 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5684 }
5685 
is_ctx_reg(struct bpf_verifier_env * env,int regno)5686 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5687 {
5688 	const struct bpf_reg_state *reg = reg_state(env, regno);
5689 
5690 	return reg->type == PTR_TO_CTX;
5691 }
5692 
is_sk_reg(struct bpf_verifier_env * env,int regno)5693 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5694 {
5695 	const struct bpf_reg_state *reg = reg_state(env, regno);
5696 
5697 	return type_is_sk_pointer(reg->type);
5698 }
5699 
is_pkt_reg(struct bpf_verifier_env * env,int regno)5700 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5701 {
5702 	const struct bpf_reg_state *reg = reg_state(env, regno);
5703 
5704 	return type_is_pkt_pointer(reg->type);
5705 }
5706 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)5707 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5708 {
5709 	const struct bpf_reg_state *reg = reg_state(env, regno);
5710 
5711 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5712 	return reg->type == PTR_TO_FLOW_KEYS;
5713 }
5714 
is_arena_reg(struct bpf_verifier_env * env,int regno)5715 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
5716 {
5717 	const struct bpf_reg_state *reg = reg_state(env, regno);
5718 
5719 	return reg->type == PTR_TO_ARENA;
5720 }
5721 
5722 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5723 #ifdef CONFIG_NET
5724 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5725 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5726 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5727 #endif
5728 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5729 };
5730 
is_trusted_reg(const struct bpf_reg_state * reg)5731 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5732 {
5733 	/* A referenced register is always trusted. */
5734 	if (reg->ref_obj_id)
5735 		return true;
5736 
5737 	/* Types listed in the reg2btf_ids are always trusted */
5738 	if (reg2btf_ids[base_type(reg->type)] &&
5739 	    !bpf_type_has_unsafe_modifiers(reg->type))
5740 		return true;
5741 
5742 	/* If a register is not referenced, it is trusted if it has the
5743 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5744 	 * other type modifiers may be safe, but we elect to take an opt-in
5745 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5746 	 * not.
5747 	 *
5748 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5749 	 * for whether a register is trusted.
5750 	 */
5751 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5752 	       !bpf_type_has_unsafe_modifiers(reg->type);
5753 }
5754 
is_rcu_reg(const struct bpf_reg_state * reg)5755 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5756 {
5757 	return reg->type & MEM_RCU;
5758 }
5759 
clear_trusted_flags(enum bpf_type_flag * flag)5760 static void clear_trusted_flags(enum bpf_type_flag *flag)
5761 {
5762 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5763 }
5764 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)5765 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5766 				   const struct bpf_reg_state *reg,
5767 				   int off, int size, bool strict)
5768 {
5769 	struct tnum reg_off;
5770 	int ip_align;
5771 
5772 	/* Byte size accesses are always allowed. */
5773 	if (!strict || size == 1)
5774 		return 0;
5775 
5776 	/* For platforms that do not have a Kconfig enabling
5777 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5778 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5779 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5780 	 * to this code only in strict mode where we want to emulate
5781 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5782 	 * unconditional IP align value of '2'.
5783 	 */
5784 	ip_align = 2;
5785 
5786 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5787 	if (!tnum_is_aligned(reg_off, size)) {
5788 		char tn_buf[48];
5789 
5790 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5791 		verbose(env,
5792 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5793 			ip_align, tn_buf, reg->off, off, size);
5794 		return -EACCES;
5795 	}
5796 
5797 	return 0;
5798 }
5799 
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)5800 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5801 				       const struct bpf_reg_state *reg,
5802 				       const char *pointer_desc,
5803 				       int off, int size, bool strict)
5804 {
5805 	struct tnum reg_off;
5806 
5807 	/* Byte size accesses are always allowed. */
5808 	if (!strict || size == 1)
5809 		return 0;
5810 
5811 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5812 	if (!tnum_is_aligned(reg_off, size)) {
5813 		char tn_buf[48];
5814 
5815 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5816 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5817 			pointer_desc, tn_buf, reg->off, off, size);
5818 		return -EACCES;
5819 	}
5820 
5821 	return 0;
5822 }
5823 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)5824 static int check_ptr_alignment(struct bpf_verifier_env *env,
5825 			       const struct bpf_reg_state *reg, int off,
5826 			       int size, bool strict_alignment_once)
5827 {
5828 	bool strict = env->strict_alignment || strict_alignment_once;
5829 	const char *pointer_desc = "";
5830 
5831 	switch (reg->type) {
5832 	case PTR_TO_PACKET:
5833 	case PTR_TO_PACKET_META:
5834 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5835 		 * right in front, treat it the very same way.
5836 		 */
5837 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5838 	case PTR_TO_FLOW_KEYS:
5839 		pointer_desc = "flow keys ";
5840 		break;
5841 	case PTR_TO_MAP_KEY:
5842 		pointer_desc = "key ";
5843 		break;
5844 	case PTR_TO_MAP_VALUE:
5845 		pointer_desc = "value ";
5846 		break;
5847 	case PTR_TO_CTX:
5848 		pointer_desc = "context ";
5849 		break;
5850 	case PTR_TO_STACK:
5851 		pointer_desc = "stack ";
5852 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5853 		 * and check_stack_read_fixed_off() relies on stack accesses being
5854 		 * aligned.
5855 		 */
5856 		strict = true;
5857 		break;
5858 	case PTR_TO_SOCKET:
5859 		pointer_desc = "sock ";
5860 		break;
5861 	case PTR_TO_SOCK_COMMON:
5862 		pointer_desc = "sock_common ";
5863 		break;
5864 	case PTR_TO_TCP_SOCK:
5865 		pointer_desc = "tcp_sock ";
5866 		break;
5867 	case PTR_TO_XDP_SOCK:
5868 		pointer_desc = "xdp_sock ";
5869 		break;
5870 	case PTR_TO_ARENA:
5871 		return 0;
5872 	default:
5873 		break;
5874 	}
5875 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5876 					   strict);
5877 }
5878 
round_up_stack_depth(struct bpf_verifier_env * env,int stack_depth)5879 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
5880 {
5881 	if (env->prog->jit_requested)
5882 		return round_up(stack_depth, 16);
5883 
5884 	/* round up to 32-bytes, since this is granularity
5885 	 * of interpreter stack size
5886 	 */
5887 	return round_up(max_t(u32, stack_depth, 1), 32);
5888 }
5889 
5890 /* starting from main bpf function walk all instructions of the function
5891  * and recursively walk all callees that given function can call.
5892  * Ignore jump and exit insns.
5893  * Since recursion is prevented by check_cfg() this algorithm
5894  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5895  */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx)5896 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5897 {
5898 	struct bpf_subprog_info *subprog = env->subprog_info;
5899 	struct bpf_insn *insn = env->prog->insnsi;
5900 	int depth = 0, frame = 0, i, subprog_end;
5901 	bool tail_call_reachable = false;
5902 	int ret_insn[MAX_CALL_FRAMES];
5903 	int ret_prog[MAX_CALL_FRAMES];
5904 	int j;
5905 
5906 	i = subprog[idx].start;
5907 process_func:
5908 	/* protect against potential stack overflow that might happen when
5909 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5910 	 * depth for such case down to 256 so that the worst case scenario
5911 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5912 	 * 8k).
5913 	 *
5914 	 * To get the idea what might happen, see an example:
5915 	 * func1 -> sub rsp, 128
5916 	 *  subfunc1 -> sub rsp, 256
5917 	 *  tailcall1 -> add rsp, 256
5918 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5919 	 *   subfunc2 -> sub rsp, 64
5920 	 *   subfunc22 -> sub rsp, 128
5921 	 *   tailcall2 -> add rsp, 128
5922 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5923 	 *
5924 	 * tailcall will unwind the current stack frame but it will not get rid
5925 	 * of caller's stack as shown on the example above.
5926 	 */
5927 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5928 		verbose(env,
5929 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5930 			depth);
5931 		return -EACCES;
5932 	}
5933 	depth += round_up_stack_depth(env, subprog[idx].stack_depth);
5934 	if (depth > MAX_BPF_STACK) {
5935 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5936 			frame + 1, depth);
5937 		return -EACCES;
5938 	}
5939 continue_func:
5940 	subprog_end = subprog[idx + 1].start;
5941 	for (; i < subprog_end; i++) {
5942 		int next_insn, sidx;
5943 
5944 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5945 			bool err = false;
5946 
5947 			if (!is_bpf_throw_kfunc(insn + i))
5948 				continue;
5949 			if (subprog[idx].is_cb)
5950 				err = true;
5951 			for (int c = 0; c < frame && !err; c++) {
5952 				if (subprog[ret_prog[c]].is_cb) {
5953 					err = true;
5954 					break;
5955 				}
5956 			}
5957 			if (!err)
5958 				continue;
5959 			verbose(env,
5960 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5961 				i, idx);
5962 			return -EINVAL;
5963 		}
5964 
5965 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5966 			continue;
5967 		/* remember insn and function to return to */
5968 		ret_insn[frame] = i + 1;
5969 		ret_prog[frame] = idx;
5970 
5971 		/* find the callee */
5972 		next_insn = i + insn[i].imm + 1;
5973 		sidx = find_subprog(env, next_insn);
5974 		if (sidx < 0) {
5975 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5976 				  next_insn);
5977 			return -EFAULT;
5978 		}
5979 		if (subprog[sidx].is_async_cb) {
5980 			if (subprog[sidx].has_tail_call) {
5981 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5982 				return -EFAULT;
5983 			}
5984 			/* async callbacks don't increase bpf prog stack size unless called directly */
5985 			if (!bpf_pseudo_call(insn + i))
5986 				continue;
5987 			if (subprog[sidx].is_exception_cb) {
5988 				verbose(env, "insn %d cannot call exception cb directly\n", i);
5989 				return -EINVAL;
5990 			}
5991 		}
5992 		i = next_insn;
5993 		idx = sidx;
5994 
5995 		if (subprog[idx].has_tail_call)
5996 			tail_call_reachable = true;
5997 
5998 		frame++;
5999 		if (frame >= MAX_CALL_FRAMES) {
6000 			verbose(env, "the call stack of %d frames is too deep !\n",
6001 				frame);
6002 			return -E2BIG;
6003 		}
6004 		goto process_func;
6005 	}
6006 	/* if tail call got detected across bpf2bpf calls then mark each of the
6007 	 * currently present subprog frames as tail call reachable subprogs;
6008 	 * this info will be utilized by JIT so that we will be preserving the
6009 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6010 	 */
6011 	if (tail_call_reachable)
6012 		for (j = 0; j < frame; j++) {
6013 			if (subprog[ret_prog[j]].is_exception_cb) {
6014 				verbose(env, "cannot tail call within exception cb\n");
6015 				return -EINVAL;
6016 			}
6017 			subprog[ret_prog[j]].tail_call_reachable = true;
6018 		}
6019 	if (subprog[0].tail_call_reachable)
6020 		env->prog->aux->tail_call_reachable = true;
6021 
6022 	/* end of for() loop means the last insn of the 'subprog'
6023 	 * was reached. Doesn't matter whether it was JA or EXIT
6024 	 */
6025 	if (frame == 0)
6026 		return 0;
6027 	depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6028 	frame--;
6029 	i = ret_insn[frame];
6030 	idx = ret_prog[frame];
6031 	goto continue_func;
6032 }
6033 
check_max_stack_depth(struct bpf_verifier_env * env)6034 static int check_max_stack_depth(struct bpf_verifier_env *env)
6035 {
6036 	struct bpf_subprog_info *si = env->subprog_info;
6037 	int ret;
6038 
6039 	for (int i = 0; i < env->subprog_cnt; i++) {
6040 		if (!i || si[i].is_async_cb) {
6041 			ret = check_max_stack_depth_subprog(env, i);
6042 			if (ret < 0)
6043 				return ret;
6044 		}
6045 		continue;
6046 	}
6047 	return 0;
6048 }
6049 
6050 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)6051 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6052 				  const struct bpf_insn *insn, int idx)
6053 {
6054 	int start = idx + insn->imm + 1, subprog;
6055 
6056 	subprog = find_subprog(env, start);
6057 	if (subprog < 0) {
6058 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6059 			  start);
6060 		return -EFAULT;
6061 	}
6062 	return env->subprog_info[subprog].stack_depth;
6063 }
6064 #endif
6065 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)6066 static int __check_buffer_access(struct bpf_verifier_env *env,
6067 				 const char *buf_info,
6068 				 const struct bpf_reg_state *reg,
6069 				 int regno, int off, int size)
6070 {
6071 	if (off < 0) {
6072 		verbose(env,
6073 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6074 			regno, buf_info, off, size);
6075 		return -EACCES;
6076 	}
6077 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6078 		char tn_buf[48];
6079 
6080 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6081 		verbose(env,
6082 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6083 			regno, off, tn_buf);
6084 		return -EACCES;
6085 	}
6086 
6087 	return 0;
6088 }
6089 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)6090 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6091 				  const struct bpf_reg_state *reg,
6092 				  int regno, int off, int size)
6093 {
6094 	int err;
6095 
6096 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6097 	if (err)
6098 		return err;
6099 
6100 	if (off + size > env->prog->aux->max_tp_access)
6101 		env->prog->aux->max_tp_access = off + size;
6102 
6103 	return 0;
6104 }
6105 
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)6106 static int check_buffer_access(struct bpf_verifier_env *env,
6107 			       const struct bpf_reg_state *reg,
6108 			       int regno, int off, int size,
6109 			       bool zero_size_allowed,
6110 			       u32 *max_access)
6111 {
6112 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6113 	int err;
6114 
6115 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6116 	if (err)
6117 		return err;
6118 
6119 	if (off + size > *max_access)
6120 		*max_access = off + size;
6121 
6122 	return 0;
6123 }
6124 
6125 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6126 static void zext_32_to_64(struct bpf_reg_state *reg)
6127 {
6128 	reg->var_off = tnum_subreg(reg->var_off);
6129 	__reg_assign_32_into_64(reg);
6130 }
6131 
6132 /* truncate register to smaller size (in bytes)
6133  * must be called with size < BPF_REG_SIZE
6134  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6135 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6136 {
6137 	u64 mask;
6138 
6139 	/* clear high bits in bit representation */
6140 	reg->var_off = tnum_cast(reg->var_off, size);
6141 
6142 	/* fix arithmetic bounds */
6143 	mask = ((u64)1 << (size * 8)) - 1;
6144 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6145 		reg->umin_value &= mask;
6146 		reg->umax_value &= mask;
6147 	} else {
6148 		reg->umin_value = 0;
6149 		reg->umax_value = mask;
6150 	}
6151 	reg->smin_value = reg->umin_value;
6152 	reg->smax_value = reg->umax_value;
6153 
6154 	/* If size is smaller than 32bit register the 32bit register
6155 	 * values are also truncated so we push 64-bit bounds into
6156 	 * 32-bit bounds. Above were truncated < 32-bits already.
6157 	 */
6158 	if (size < 4)
6159 		__mark_reg32_unbounded(reg);
6160 
6161 	reg_bounds_sync(reg);
6162 }
6163 
set_sext64_default_val(struct bpf_reg_state * reg,int size)6164 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6165 {
6166 	if (size == 1) {
6167 		reg->smin_value = reg->s32_min_value = S8_MIN;
6168 		reg->smax_value = reg->s32_max_value = S8_MAX;
6169 	} else if (size == 2) {
6170 		reg->smin_value = reg->s32_min_value = S16_MIN;
6171 		reg->smax_value = reg->s32_max_value = S16_MAX;
6172 	} else {
6173 		/* size == 4 */
6174 		reg->smin_value = reg->s32_min_value = S32_MIN;
6175 		reg->smax_value = reg->s32_max_value = S32_MAX;
6176 	}
6177 	reg->umin_value = reg->u32_min_value = 0;
6178 	reg->umax_value = U64_MAX;
6179 	reg->u32_max_value = U32_MAX;
6180 	reg->var_off = tnum_unknown;
6181 }
6182 
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6183 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6184 {
6185 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6186 	u64 top_smax_value, top_smin_value;
6187 	u64 num_bits = size * 8;
6188 
6189 	if (tnum_is_const(reg->var_off)) {
6190 		u64_cval = reg->var_off.value;
6191 		if (size == 1)
6192 			reg->var_off = tnum_const((s8)u64_cval);
6193 		else if (size == 2)
6194 			reg->var_off = tnum_const((s16)u64_cval);
6195 		else
6196 			/* size == 4 */
6197 			reg->var_off = tnum_const((s32)u64_cval);
6198 
6199 		u64_cval = reg->var_off.value;
6200 		reg->smax_value = reg->smin_value = u64_cval;
6201 		reg->umax_value = reg->umin_value = u64_cval;
6202 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6203 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6204 		return;
6205 	}
6206 
6207 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6208 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6209 
6210 	if (top_smax_value != top_smin_value)
6211 		goto out;
6212 
6213 	/* find the s64_min and s64_min after sign extension */
6214 	if (size == 1) {
6215 		init_s64_max = (s8)reg->smax_value;
6216 		init_s64_min = (s8)reg->smin_value;
6217 	} else if (size == 2) {
6218 		init_s64_max = (s16)reg->smax_value;
6219 		init_s64_min = (s16)reg->smin_value;
6220 	} else {
6221 		init_s64_max = (s32)reg->smax_value;
6222 		init_s64_min = (s32)reg->smin_value;
6223 	}
6224 
6225 	s64_max = max(init_s64_max, init_s64_min);
6226 	s64_min = min(init_s64_max, init_s64_min);
6227 
6228 	/* both of s64_max/s64_min positive or negative */
6229 	if ((s64_max >= 0) == (s64_min >= 0)) {
6230 		reg->smin_value = reg->s32_min_value = s64_min;
6231 		reg->smax_value = reg->s32_max_value = s64_max;
6232 		reg->umin_value = reg->u32_min_value = s64_min;
6233 		reg->umax_value = reg->u32_max_value = s64_max;
6234 		reg->var_off = tnum_range(s64_min, s64_max);
6235 		return;
6236 	}
6237 
6238 out:
6239 	set_sext64_default_val(reg, size);
6240 }
6241 
set_sext32_default_val(struct bpf_reg_state * reg,int size)6242 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6243 {
6244 	if (size == 1) {
6245 		reg->s32_min_value = S8_MIN;
6246 		reg->s32_max_value = S8_MAX;
6247 	} else {
6248 		/* size == 2 */
6249 		reg->s32_min_value = S16_MIN;
6250 		reg->s32_max_value = S16_MAX;
6251 	}
6252 	reg->u32_min_value = 0;
6253 	reg->u32_max_value = U32_MAX;
6254 	reg->var_off = tnum_subreg(tnum_unknown);
6255 }
6256 
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6257 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6258 {
6259 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6260 	u32 top_smax_value, top_smin_value;
6261 	u32 num_bits = size * 8;
6262 
6263 	if (tnum_is_const(reg->var_off)) {
6264 		u32_val = reg->var_off.value;
6265 		if (size == 1)
6266 			reg->var_off = tnum_const((s8)u32_val);
6267 		else
6268 			reg->var_off = tnum_const((s16)u32_val);
6269 
6270 		u32_val = reg->var_off.value;
6271 		reg->s32_min_value = reg->s32_max_value = u32_val;
6272 		reg->u32_min_value = reg->u32_max_value = u32_val;
6273 		return;
6274 	}
6275 
6276 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6277 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6278 
6279 	if (top_smax_value != top_smin_value)
6280 		goto out;
6281 
6282 	/* find the s32_min and s32_min after sign extension */
6283 	if (size == 1) {
6284 		init_s32_max = (s8)reg->s32_max_value;
6285 		init_s32_min = (s8)reg->s32_min_value;
6286 	} else {
6287 		/* size == 2 */
6288 		init_s32_max = (s16)reg->s32_max_value;
6289 		init_s32_min = (s16)reg->s32_min_value;
6290 	}
6291 	s32_max = max(init_s32_max, init_s32_min);
6292 	s32_min = min(init_s32_max, init_s32_min);
6293 
6294 	if ((s32_min >= 0) == (s32_max >= 0)) {
6295 		reg->s32_min_value = s32_min;
6296 		reg->s32_max_value = s32_max;
6297 		reg->u32_min_value = (u32)s32_min;
6298 		reg->u32_max_value = (u32)s32_max;
6299 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6300 		return;
6301 	}
6302 
6303 out:
6304 	set_sext32_default_val(reg, size);
6305 }
6306 
bpf_map_is_rdonly(const struct bpf_map * map)6307 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6308 {
6309 	/* A map is considered read-only if the following condition are true:
6310 	 *
6311 	 * 1) BPF program side cannot change any of the map content. The
6312 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6313 	 *    and was set at map creation time.
6314 	 * 2) The map value(s) have been initialized from user space by a
6315 	 *    loader and then "frozen", such that no new map update/delete
6316 	 *    operations from syscall side are possible for the rest of
6317 	 *    the map's lifetime from that point onwards.
6318 	 * 3) Any parallel/pending map update/delete operations from syscall
6319 	 *    side have been completed. Only after that point, it's safe to
6320 	 *    assume that map value(s) are immutable.
6321 	 */
6322 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6323 	       READ_ONCE(map->frozen) &&
6324 	       !bpf_map_write_active(map);
6325 }
6326 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)6327 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6328 			       bool is_ldsx)
6329 {
6330 	void *ptr;
6331 	u64 addr;
6332 	int err;
6333 
6334 	err = map->ops->map_direct_value_addr(map, &addr, off);
6335 	if (err)
6336 		return err;
6337 	ptr = (void *)(long)addr + off;
6338 
6339 	switch (size) {
6340 	case sizeof(u8):
6341 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6342 		break;
6343 	case sizeof(u16):
6344 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6345 		break;
6346 	case sizeof(u32):
6347 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6348 		break;
6349 	case sizeof(u64):
6350 		*val = *(u64 *)ptr;
6351 		break;
6352 	default:
6353 		return -EINVAL;
6354 	}
6355 	return 0;
6356 }
6357 
6358 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6359 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6360 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6361 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6362 
6363 /*
6364  * Allow list few fields as RCU trusted or full trusted.
6365  * This logic doesn't allow mix tagging and will be removed once GCC supports
6366  * btf_type_tag.
6367  */
6368 
6369 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)6370 BTF_TYPE_SAFE_RCU(struct task_struct) {
6371 	const cpumask_t *cpus_ptr;
6372 	struct css_set __rcu *cgroups;
6373 	struct task_struct __rcu *real_parent;
6374 	struct task_struct *group_leader;
6375 };
6376 
BTF_TYPE_SAFE_RCU(struct cgroup)6377 BTF_TYPE_SAFE_RCU(struct cgroup) {
6378 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6379 	struct kernfs_node *kn;
6380 };
6381 
BTF_TYPE_SAFE_RCU(struct css_set)6382 BTF_TYPE_SAFE_RCU(struct css_set) {
6383 	struct cgroup *dfl_cgrp;
6384 };
6385 
6386 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)6387 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6388 	struct file __rcu *exe_file;
6389 };
6390 
6391 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6392  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6393  */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)6394 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6395 	struct sock *sk;
6396 };
6397 
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)6398 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6399 	struct sock *sk;
6400 };
6401 
6402 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)6403 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6404 	struct seq_file *seq;
6405 };
6406 
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)6407 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6408 	struct bpf_iter_meta *meta;
6409 	struct task_struct *task;
6410 };
6411 
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)6412 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6413 	struct file *file;
6414 };
6415 
BTF_TYPE_SAFE_TRUSTED(struct file)6416 BTF_TYPE_SAFE_TRUSTED(struct file) {
6417 	struct inode *f_inode;
6418 };
6419 
BTF_TYPE_SAFE_TRUSTED(struct dentry)6420 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6421 	/* no negative dentry-s in places where bpf can see it */
6422 	struct inode *d_inode;
6423 };
6424 
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)6425 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6426 	struct sock *sk;
6427 };
6428 
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6429 static bool type_is_rcu(struct bpf_verifier_env *env,
6430 			struct bpf_reg_state *reg,
6431 			const char *field_name, u32 btf_id)
6432 {
6433 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6434 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6435 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6436 
6437 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6438 }
6439 
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6440 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6441 				struct bpf_reg_state *reg,
6442 				const char *field_name, u32 btf_id)
6443 {
6444 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6445 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6446 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6447 
6448 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6449 }
6450 
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6451 static bool type_is_trusted(struct bpf_verifier_env *env,
6452 			    struct bpf_reg_state *reg,
6453 			    const char *field_name, u32 btf_id)
6454 {
6455 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6456 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6457 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6458 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6459 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6460 
6461 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6462 }
6463 
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6464 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6465 				    struct bpf_reg_state *reg,
6466 				    const char *field_name, u32 btf_id)
6467 {
6468 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6469 
6470 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6471 					  "__safe_trusted_or_null");
6472 }
6473 
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)6474 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6475 				   struct bpf_reg_state *regs,
6476 				   int regno, int off, int size,
6477 				   enum bpf_access_type atype,
6478 				   int value_regno)
6479 {
6480 	struct bpf_reg_state *reg = regs + regno;
6481 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6482 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6483 	const char *field_name = NULL;
6484 	enum bpf_type_flag flag = 0;
6485 	u32 btf_id = 0;
6486 	int ret;
6487 
6488 	if (!env->allow_ptr_leaks) {
6489 		verbose(env,
6490 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6491 			tname);
6492 		return -EPERM;
6493 	}
6494 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6495 		verbose(env,
6496 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6497 			tname);
6498 		return -EINVAL;
6499 	}
6500 	if (off < 0) {
6501 		verbose(env,
6502 			"R%d is ptr_%s invalid negative access: off=%d\n",
6503 			regno, tname, off);
6504 		return -EACCES;
6505 	}
6506 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6507 		char tn_buf[48];
6508 
6509 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6510 		verbose(env,
6511 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6512 			regno, tname, off, tn_buf);
6513 		return -EACCES;
6514 	}
6515 
6516 	if (reg->type & MEM_USER) {
6517 		verbose(env,
6518 			"R%d is ptr_%s access user memory: off=%d\n",
6519 			regno, tname, off);
6520 		return -EACCES;
6521 	}
6522 
6523 	if (reg->type & MEM_PERCPU) {
6524 		verbose(env,
6525 			"R%d is ptr_%s access percpu memory: off=%d\n",
6526 			regno, tname, off);
6527 		return -EACCES;
6528 	}
6529 
6530 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6531 		if (!btf_is_kernel(reg->btf)) {
6532 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6533 			return -EFAULT;
6534 		}
6535 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6536 	} else {
6537 		/* Writes are permitted with default btf_struct_access for
6538 		 * program allocated objects (which always have ref_obj_id > 0),
6539 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6540 		 */
6541 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6542 			verbose(env, "only read is supported\n");
6543 			return -EACCES;
6544 		}
6545 
6546 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6547 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6548 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6549 			return -EFAULT;
6550 		}
6551 
6552 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6553 	}
6554 
6555 	if (ret < 0)
6556 		return ret;
6557 
6558 	if (ret != PTR_TO_BTF_ID) {
6559 		/* just mark; */
6560 
6561 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6562 		/* If this is an untrusted pointer, all pointers formed by walking it
6563 		 * also inherit the untrusted flag.
6564 		 */
6565 		flag = PTR_UNTRUSTED;
6566 
6567 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6568 		/* By default any pointer obtained from walking a trusted pointer is no
6569 		 * longer trusted, unless the field being accessed has explicitly been
6570 		 * marked as inheriting its parent's state of trust (either full or RCU).
6571 		 * For example:
6572 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6573 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6574 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6575 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6576 		 *
6577 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6578 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6579 		 */
6580 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6581 			flag |= PTR_TRUSTED;
6582 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6583 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6584 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6585 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6586 				/* ignore __rcu tag and mark it MEM_RCU */
6587 				flag |= MEM_RCU;
6588 			} else if (flag & MEM_RCU ||
6589 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6590 				/* __rcu tagged pointers can be NULL */
6591 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6592 
6593 				/* We always trust them */
6594 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6595 				    flag & PTR_UNTRUSTED)
6596 					flag &= ~PTR_UNTRUSTED;
6597 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6598 				/* keep as-is */
6599 			} else {
6600 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6601 				clear_trusted_flags(&flag);
6602 			}
6603 		} else {
6604 			/*
6605 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6606 			 * aggressively mark as untrusted otherwise such
6607 			 * pointers will be plain PTR_TO_BTF_ID without flags
6608 			 * and will be allowed to be passed into helpers for
6609 			 * compat reasons.
6610 			 */
6611 			flag = PTR_UNTRUSTED;
6612 		}
6613 	} else {
6614 		/* Old compat. Deprecated */
6615 		clear_trusted_flags(&flag);
6616 	}
6617 
6618 	if (atype == BPF_READ && value_regno >= 0)
6619 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6620 
6621 	return 0;
6622 }
6623 
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)6624 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6625 				   struct bpf_reg_state *regs,
6626 				   int regno, int off, int size,
6627 				   enum bpf_access_type atype,
6628 				   int value_regno)
6629 {
6630 	struct bpf_reg_state *reg = regs + regno;
6631 	struct bpf_map *map = reg->map_ptr;
6632 	struct bpf_reg_state map_reg;
6633 	enum bpf_type_flag flag = 0;
6634 	const struct btf_type *t;
6635 	const char *tname;
6636 	u32 btf_id;
6637 	int ret;
6638 
6639 	if (!btf_vmlinux) {
6640 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6641 		return -ENOTSUPP;
6642 	}
6643 
6644 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6645 		verbose(env, "map_ptr access not supported for map type %d\n",
6646 			map->map_type);
6647 		return -ENOTSUPP;
6648 	}
6649 
6650 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6651 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6652 
6653 	if (!env->allow_ptr_leaks) {
6654 		verbose(env,
6655 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6656 			tname);
6657 		return -EPERM;
6658 	}
6659 
6660 	if (off < 0) {
6661 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6662 			regno, tname, off);
6663 		return -EACCES;
6664 	}
6665 
6666 	if (atype != BPF_READ) {
6667 		verbose(env, "only read from %s is supported\n", tname);
6668 		return -EACCES;
6669 	}
6670 
6671 	/* Simulate access to a PTR_TO_BTF_ID */
6672 	memset(&map_reg, 0, sizeof(map_reg));
6673 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6674 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6675 	if (ret < 0)
6676 		return ret;
6677 
6678 	if (value_regno >= 0)
6679 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6680 
6681 	return 0;
6682 }
6683 
6684 /* Check that the stack access at the given offset is within bounds. The
6685  * maximum valid offset is -1.
6686  *
6687  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6688  * -state->allocated_stack for reads.
6689  */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)6690 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6691                                           s64 off,
6692                                           struct bpf_func_state *state,
6693                                           enum bpf_access_type t)
6694 {
6695 	int min_valid_off;
6696 
6697 	if (t == BPF_WRITE || env->allow_uninit_stack)
6698 		min_valid_off = -MAX_BPF_STACK;
6699 	else
6700 		min_valid_off = -state->allocated_stack;
6701 
6702 	if (off < min_valid_off || off > -1)
6703 		return -EACCES;
6704 	return 0;
6705 }
6706 
6707 /* Check that the stack access at 'regno + off' falls within the maximum stack
6708  * bounds.
6709  *
6710  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6711  */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_src src,enum bpf_access_type type)6712 static int check_stack_access_within_bounds(
6713 		struct bpf_verifier_env *env,
6714 		int regno, int off, int access_size,
6715 		enum bpf_access_src src, enum bpf_access_type type)
6716 {
6717 	struct bpf_reg_state *regs = cur_regs(env);
6718 	struct bpf_reg_state *reg = regs + regno;
6719 	struct bpf_func_state *state = func(env, reg);
6720 	s64 min_off, max_off;
6721 	int err;
6722 	char *err_extra;
6723 
6724 	if (src == ACCESS_HELPER)
6725 		/* We don't know if helpers are reading or writing (or both). */
6726 		err_extra = " indirect access to";
6727 	else if (type == BPF_READ)
6728 		err_extra = " read from";
6729 	else
6730 		err_extra = " write to";
6731 
6732 	if (tnum_is_const(reg->var_off)) {
6733 		min_off = (s64)reg->var_off.value + off;
6734 		max_off = min_off + access_size;
6735 	} else {
6736 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6737 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6738 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6739 				err_extra, regno);
6740 			return -EACCES;
6741 		}
6742 		min_off = reg->smin_value + off;
6743 		max_off = reg->smax_value + off + access_size;
6744 	}
6745 
6746 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6747 	if (!err && max_off > 0)
6748 		err = -EINVAL; /* out of stack access into non-negative offsets */
6749 	if (!err && access_size < 0)
6750 		/* access_size should not be negative (or overflow an int); others checks
6751 		 * along the way should have prevented such an access.
6752 		 */
6753 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6754 
6755 	if (err) {
6756 		if (tnum_is_const(reg->var_off)) {
6757 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6758 				err_extra, regno, off, access_size);
6759 		} else {
6760 			char tn_buf[48];
6761 
6762 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6763 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
6764 				err_extra, regno, tn_buf, off, access_size);
6765 		}
6766 		return err;
6767 	}
6768 
6769 	/* Note that there is no stack access with offset zero, so the needed stack
6770 	 * size is -min_off, not -min_off+1.
6771 	 */
6772 	return grow_stack_state(env, state, -min_off /* size */);
6773 }
6774 
6775 /* check whether memory at (regno + off) is accessible for t = (read | write)
6776  * if t==write, value_regno is a register which value is stored into memory
6777  * if t==read, value_regno is a register which will receive the value from memory
6778  * if t==write && value_regno==-1, some unknown value is stored into memory
6779  * if t==read && value_regno==-1, don't care what we read from memory
6780  */
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)6781 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6782 			    int off, int bpf_size, enum bpf_access_type t,
6783 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6784 {
6785 	struct bpf_reg_state *regs = cur_regs(env);
6786 	struct bpf_reg_state *reg = regs + regno;
6787 	int size, err = 0;
6788 
6789 	size = bpf_size_to_bytes(bpf_size);
6790 	if (size < 0)
6791 		return size;
6792 
6793 	/* alignment checks will add in reg->off themselves */
6794 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6795 	if (err)
6796 		return err;
6797 
6798 	/* for access checks, reg->off is just part of off */
6799 	off += reg->off;
6800 
6801 	if (reg->type == PTR_TO_MAP_KEY) {
6802 		if (t == BPF_WRITE) {
6803 			verbose(env, "write to change key R%d not allowed\n", regno);
6804 			return -EACCES;
6805 		}
6806 
6807 		err = check_mem_region_access(env, regno, off, size,
6808 					      reg->map_ptr->key_size, false);
6809 		if (err)
6810 			return err;
6811 		if (value_regno >= 0)
6812 			mark_reg_unknown(env, regs, value_regno);
6813 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6814 		struct btf_field *kptr_field = NULL;
6815 
6816 		if (t == BPF_WRITE && value_regno >= 0 &&
6817 		    is_pointer_value(env, value_regno)) {
6818 			verbose(env, "R%d leaks addr into map\n", value_regno);
6819 			return -EACCES;
6820 		}
6821 		err = check_map_access_type(env, regno, off, size, t);
6822 		if (err)
6823 			return err;
6824 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6825 		if (err)
6826 			return err;
6827 		if (tnum_is_const(reg->var_off))
6828 			kptr_field = btf_record_find(reg->map_ptr->record,
6829 						     off + reg->var_off.value, BPF_KPTR);
6830 		if (kptr_field) {
6831 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6832 		} else if (t == BPF_READ && value_regno >= 0) {
6833 			struct bpf_map *map = reg->map_ptr;
6834 
6835 			/* if map is read-only, track its contents as scalars */
6836 			if (tnum_is_const(reg->var_off) &&
6837 			    bpf_map_is_rdonly(map) &&
6838 			    map->ops->map_direct_value_addr) {
6839 				int map_off = off + reg->var_off.value;
6840 				u64 val = 0;
6841 
6842 				err = bpf_map_direct_read(map, map_off, size,
6843 							  &val, is_ldsx);
6844 				if (err)
6845 					return err;
6846 
6847 				regs[value_regno].type = SCALAR_VALUE;
6848 				__mark_reg_known(&regs[value_regno], val);
6849 			} else {
6850 				mark_reg_unknown(env, regs, value_regno);
6851 			}
6852 		}
6853 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6854 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6855 
6856 		if (type_may_be_null(reg->type)) {
6857 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6858 				reg_type_str(env, reg->type));
6859 			return -EACCES;
6860 		}
6861 
6862 		if (t == BPF_WRITE && rdonly_mem) {
6863 			verbose(env, "R%d cannot write into %s\n",
6864 				regno, reg_type_str(env, reg->type));
6865 			return -EACCES;
6866 		}
6867 
6868 		if (t == BPF_WRITE && value_regno >= 0 &&
6869 		    is_pointer_value(env, value_regno)) {
6870 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6871 			return -EACCES;
6872 		}
6873 
6874 		err = check_mem_region_access(env, regno, off, size,
6875 					      reg->mem_size, false);
6876 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6877 			mark_reg_unknown(env, regs, value_regno);
6878 	} else if (reg->type == PTR_TO_CTX) {
6879 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6880 		struct btf *btf = NULL;
6881 		u32 btf_id = 0;
6882 
6883 		if (t == BPF_WRITE && value_regno >= 0 &&
6884 		    is_pointer_value(env, value_regno)) {
6885 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6886 			return -EACCES;
6887 		}
6888 
6889 		err = check_ptr_off_reg(env, reg, regno);
6890 		if (err < 0)
6891 			return err;
6892 
6893 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6894 				       &btf_id);
6895 		if (err)
6896 			verbose_linfo(env, insn_idx, "; ");
6897 		if (!err && t == BPF_READ && value_regno >= 0) {
6898 			/* ctx access returns either a scalar, or a
6899 			 * PTR_TO_PACKET[_META,_END]. In the latter
6900 			 * case, we know the offset is zero.
6901 			 */
6902 			if (reg_type == SCALAR_VALUE) {
6903 				mark_reg_unknown(env, regs, value_regno);
6904 			} else {
6905 				mark_reg_known_zero(env, regs,
6906 						    value_regno);
6907 				if (type_may_be_null(reg_type))
6908 					regs[value_regno].id = ++env->id_gen;
6909 				/* A load of ctx field could have different
6910 				 * actual load size with the one encoded in the
6911 				 * insn. When the dst is PTR, it is for sure not
6912 				 * a sub-register.
6913 				 */
6914 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6915 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6916 					regs[value_regno].btf = btf;
6917 					regs[value_regno].btf_id = btf_id;
6918 				}
6919 			}
6920 			regs[value_regno].type = reg_type;
6921 		}
6922 
6923 	} else if (reg->type == PTR_TO_STACK) {
6924 		/* Basic bounds checks. */
6925 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6926 		if (err)
6927 			return err;
6928 
6929 		if (t == BPF_READ)
6930 			err = check_stack_read(env, regno, off, size,
6931 					       value_regno);
6932 		else
6933 			err = check_stack_write(env, regno, off, size,
6934 						value_regno, insn_idx);
6935 	} else if (reg_is_pkt_pointer(reg)) {
6936 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6937 			verbose(env, "cannot write into packet\n");
6938 			return -EACCES;
6939 		}
6940 		if (t == BPF_WRITE && value_regno >= 0 &&
6941 		    is_pointer_value(env, value_regno)) {
6942 			verbose(env, "R%d leaks addr into packet\n",
6943 				value_regno);
6944 			return -EACCES;
6945 		}
6946 		err = check_packet_access(env, regno, off, size, false);
6947 		if (!err && t == BPF_READ && value_regno >= 0)
6948 			mark_reg_unknown(env, regs, value_regno);
6949 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6950 		if (t == BPF_WRITE && value_regno >= 0 &&
6951 		    is_pointer_value(env, value_regno)) {
6952 			verbose(env, "R%d leaks addr into flow keys\n",
6953 				value_regno);
6954 			return -EACCES;
6955 		}
6956 
6957 		err = check_flow_keys_access(env, off, size);
6958 		if (!err && t == BPF_READ && value_regno >= 0)
6959 			mark_reg_unknown(env, regs, value_regno);
6960 	} else if (type_is_sk_pointer(reg->type)) {
6961 		if (t == BPF_WRITE) {
6962 			verbose(env, "R%d cannot write into %s\n",
6963 				regno, reg_type_str(env, reg->type));
6964 			return -EACCES;
6965 		}
6966 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6967 		if (!err && value_regno >= 0)
6968 			mark_reg_unknown(env, regs, value_regno);
6969 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6970 		err = check_tp_buffer_access(env, reg, regno, off, size);
6971 		if (!err && t == BPF_READ && value_regno >= 0)
6972 			mark_reg_unknown(env, regs, value_regno);
6973 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6974 		   !type_may_be_null(reg->type)) {
6975 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6976 					      value_regno);
6977 	} else if (reg->type == CONST_PTR_TO_MAP) {
6978 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6979 					      value_regno);
6980 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6981 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6982 		u32 *max_access;
6983 
6984 		if (rdonly_mem) {
6985 			if (t == BPF_WRITE) {
6986 				verbose(env, "R%d cannot write into %s\n",
6987 					regno, reg_type_str(env, reg->type));
6988 				return -EACCES;
6989 			}
6990 			max_access = &env->prog->aux->max_rdonly_access;
6991 		} else {
6992 			max_access = &env->prog->aux->max_rdwr_access;
6993 		}
6994 
6995 		err = check_buffer_access(env, reg, regno, off, size, false,
6996 					  max_access);
6997 
6998 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6999 			mark_reg_unknown(env, regs, value_regno);
7000 	} else if (reg->type == PTR_TO_ARENA) {
7001 		if (t == BPF_READ && value_regno >= 0)
7002 			mark_reg_unknown(env, regs, value_regno);
7003 	} else {
7004 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7005 			reg_type_str(env, reg->type));
7006 		return -EACCES;
7007 	}
7008 
7009 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7010 	    regs[value_regno].type == SCALAR_VALUE) {
7011 		if (!is_ldsx)
7012 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7013 			coerce_reg_to_size(&regs[value_regno], size);
7014 		else
7015 			coerce_reg_to_size_sx(&regs[value_regno], size);
7016 	}
7017 	return err;
7018 }
7019 
7020 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7021 			     bool allow_trust_mismatch);
7022 
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)7023 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7024 {
7025 	int load_reg;
7026 	int err;
7027 
7028 	switch (insn->imm) {
7029 	case BPF_ADD:
7030 	case BPF_ADD | BPF_FETCH:
7031 	case BPF_AND:
7032 	case BPF_AND | BPF_FETCH:
7033 	case BPF_OR:
7034 	case BPF_OR | BPF_FETCH:
7035 	case BPF_XOR:
7036 	case BPF_XOR | BPF_FETCH:
7037 	case BPF_XCHG:
7038 	case BPF_CMPXCHG:
7039 		break;
7040 	default:
7041 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7042 		return -EINVAL;
7043 	}
7044 
7045 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7046 		verbose(env, "invalid atomic operand size\n");
7047 		return -EINVAL;
7048 	}
7049 
7050 	/* check src1 operand */
7051 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7052 	if (err)
7053 		return err;
7054 
7055 	/* check src2 operand */
7056 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7057 	if (err)
7058 		return err;
7059 
7060 	if (insn->imm == BPF_CMPXCHG) {
7061 		/* Check comparison of R0 with memory location */
7062 		const u32 aux_reg = BPF_REG_0;
7063 
7064 		err = check_reg_arg(env, aux_reg, SRC_OP);
7065 		if (err)
7066 			return err;
7067 
7068 		if (is_pointer_value(env, aux_reg)) {
7069 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7070 			return -EACCES;
7071 		}
7072 	}
7073 
7074 	if (is_pointer_value(env, insn->src_reg)) {
7075 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7076 		return -EACCES;
7077 	}
7078 
7079 	if (is_ctx_reg(env, insn->dst_reg) ||
7080 	    is_pkt_reg(env, insn->dst_reg) ||
7081 	    is_flow_key_reg(env, insn->dst_reg) ||
7082 	    is_sk_reg(env, insn->dst_reg) ||
7083 	    (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) {
7084 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7085 			insn->dst_reg,
7086 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7087 		return -EACCES;
7088 	}
7089 
7090 	if (insn->imm & BPF_FETCH) {
7091 		if (insn->imm == BPF_CMPXCHG)
7092 			load_reg = BPF_REG_0;
7093 		else
7094 			load_reg = insn->src_reg;
7095 
7096 		/* check and record load of old value */
7097 		err = check_reg_arg(env, load_reg, DST_OP);
7098 		if (err)
7099 			return err;
7100 	} else {
7101 		/* This instruction accesses a memory location but doesn't
7102 		 * actually load it into a register.
7103 		 */
7104 		load_reg = -1;
7105 	}
7106 
7107 	/* Check whether we can read the memory, with second call for fetch
7108 	 * case to simulate the register fill.
7109 	 */
7110 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7111 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7112 	if (!err && load_reg >= 0)
7113 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7114 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7115 				       true, false);
7116 	if (err)
7117 		return err;
7118 
7119 	if (is_arena_reg(env, insn->dst_reg)) {
7120 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7121 		if (err)
7122 			return err;
7123 	}
7124 	/* Check whether we can write into the same memory. */
7125 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7126 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7127 	if (err)
7128 		return err;
7129 	return 0;
7130 }
7131 
7132 /* When register 'regno' is used to read the stack (either directly or through
7133  * a helper function) make sure that it's within stack boundary and, depending
7134  * on the access type and privileges, that all elements of the stack are
7135  * initialized.
7136  *
7137  * 'off' includes 'regno->off', but not its dynamic part (if any).
7138  *
7139  * All registers that have been spilled on the stack in the slots within the
7140  * read offsets are marked as read.
7141  */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum bpf_access_src type,struct bpf_call_arg_meta * meta)7142 static int check_stack_range_initialized(
7143 		struct bpf_verifier_env *env, int regno, int off,
7144 		int access_size, bool zero_size_allowed,
7145 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7146 {
7147 	struct bpf_reg_state *reg = reg_state(env, regno);
7148 	struct bpf_func_state *state = func(env, reg);
7149 	int err, min_off, max_off, i, j, slot, spi;
7150 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7151 	enum bpf_access_type bounds_check_type;
7152 	/* Some accesses can write anything into the stack, others are
7153 	 * read-only.
7154 	 */
7155 	bool clobber = false;
7156 
7157 	if (access_size == 0 && !zero_size_allowed) {
7158 		verbose(env, "invalid zero-sized read\n");
7159 		return -EACCES;
7160 	}
7161 
7162 	if (type == ACCESS_HELPER) {
7163 		/* The bounds checks for writes are more permissive than for
7164 		 * reads. However, if raw_mode is not set, we'll do extra
7165 		 * checks below.
7166 		 */
7167 		bounds_check_type = BPF_WRITE;
7168 		clobber = true;
7169 	} else {
7170 		bounds_check_type = BPF_READ;
7171 	}
7172 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7173 					       type, bounds_check_type);
7174 	if (err)
7175 		return err;
7176 
7177 
7178 	if (tnum_is_const(reg->var_off)) {
7179 		min_off = max_off = reg->var_off.value + off;
7180 	} else {
7181 		/* Variable offset is prohibited for unprivileged mode for
7182 		 * simplicity since it requires corresponding support in
7183 		 * Spectre masking for stack ALU.
7184 		 * See also retrieve_ptr_limit().
7185 		 */
7186 		if (!env->bypass_spec_v1) {
7187 			char tn_buf[48];
7188 
7189 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7190 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7191 				regno, err_extra, tn_buf);
7192 			return -EACCES;
7193 		}
7194 		/* Only initialized buffer on stack is allowed to be accessed
7195 		 * with variable offset. With uninitialized buffer it's hard to
7196 		 * guarantee that whole memory is marked as initialized on
7197 		 * helper return since specific bounds are unknown what may
7198 		 * cause uninitialized stack leaking.
7199 		 */
7200 		if (meta && meta->raw_mode)
7201 			meta = NULL;
7202 
7203 		min_off = reg->smin_value + off;
7204 		max_off = reg->smax_value + off;
7205 	}
7206 
7207 	if (meta && meta->raw_mode) {
7208 		/* Ensure we won't be overwriting dynptrs when simulating byte
7209 		 * by byte access in check_helper_call using meta.access_size.
7210 		 * This would be a problem if we have a helper in the future
7211 		 * which takes:
7212 		 *
7213 		 *	helper(uninit_mem, len, dynptr)
7214 		 *
7215 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7216 		 * may end up writing to dynptr itself when touching memory from
7217 		 * arg 1. This can be relaxed on a case by case basis for known
7218 		 * safe cases, but reject due to the possibilitiy of aliasing by
7219 		 * default.
7220 		 */
7221 		for (i = min_off; i < max_off + access_size; i++) {
7222 			int stack_off = -i - 1;
7223 
7224 			spi = __get_spi(i);
7225 			/* raw_mode may write past allocated_stack */
7226 			if (state->allocated_stack <= stack_off)
7227 				continue;
7228 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7229 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7230 				return -EACCES;
7231 			}
7232 		}
7233 		meta->access_size = access_size;
7234 		meta->regno = regno;
7235 		return 0;
7236 	}
7237 
7238 	for (i = min_off; i < max_off + access_size; i++) {
7239 		u8 *stype;
7240 
7241 		slot = -i - 1;
7242 		spi = slot / BPF_REG_SIZE;
7243 		if (state->allocated_stack <= slot) {
7244 			verbose(env, "verifier bug: allocated_stack too small");
7245 			return -EFAULT;
7246 		}
7247 
7248 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7249 		if (*stype == STACK_MISC)
7250 			goto mark;
7251 		if ((*stype == STACK_ZERO) ||
7252 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7253 			if (clobber) {
7254 				/* helper can write anything into the stack */
7255 				*stype = STACK_MISC;
7256 			}
7257 			goto mark;
7258 		}
7259 
7260 		if (is_spilled_reg(&state->stack[spi]) &&
7261 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7262 		     env->allow_ptr_leaks)) {
7263 			if (clobber) {
7264 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7265 				for (j = 0; j < BPF_REG_SIZE; j++)
7266 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7267 			}
7268 			goto mark;
7269 		}
7270 
7271 		if (tnum_is_const(reg->var_off)) {
7272 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7273 				err_extra, regno, min_off, i - min_off, access_size);
7274 		} else {
7275 			char tn_buf[48];
7276 
7277 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7278 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7279 				err_extra, regno, tn_buf, i - min_off, access_size);
7280 		}
7281 		return -EACCES;
7282 mark:
7283 		/* reading any byte out of 8-byte 'spill_slot' will cause
7284 		 * the whole slot to be marked as 'read'
7285 		 */
7286 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7287 			      state->stack[spi].spilled_ptr.parent,
7288 			      REG_LIVE_READ64);
7289 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7290 		 * be sure that whether stack slot is written to or not. Hence,
7291 		 * we must still conservatively propagate reads upwards even if
7292 		 * helper may write to the entire memory range.
7293 		 */
7294 	}
7295 	return 0;
7296 }
7297 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)7298 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7299 				   int access_size, bool zero_size_allowed,
7300 				   struct bpf_call_arg_meta *meta)
7301 {
7302 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7303 	u32 *max_access;
7304 
7305 	switch (base_type(reg->type)) {
7306 	case PTR_TO_PACKET:
7307 	case PTR_TO_PACKET_META:
7308 		return check_packet_access(env, regno, reg->off, access_size,
7309 					   zero_size_allowed);
7310 	case PTR_TO_MAP_KEY:
7311 		if (meta && meta->raw_mode) {
7312 			verbose(env, "R%d cannot write into %s\n", regno,
7313 				reg_type_str(env, reg->type));
7314 			return -EACCES;
7315 		}
7316 		return check_mem_region_access(env, regno, reg->off, access_size,
7317 					       reg->map_ptr->key_size, false);
7318 	case PTR_TO_MAP_VALUE:
7319 		if (check_map_access_type(env, regno, reg->off, access_size,
7320 					  meta && meta->raw_mode ? BPF_WRITE :
7321 					  BPF_READ))
7322 			return -EACCES;
7323 		return check_map_access(env, regno, reg->off, access_size,
7324 					zero_size_allowed, ACCESS_HELPER);
7325 	case PTR_TO_MEM:
7326 		if (type_is_rdonly_mem(reg->type)) {
7327 			if (meta && meta->raw_mode) {
7328 				verbose(env, "R%d cannot write into %s\n", regno,
7329 					reg_type_str(env, reg->type));
7330 				return -EACCES;
7331 			}
7332 		}
7333 		return check_mem_region_access(env, regno, reg->off,
7334 					       access_size, reg->mem_size,
7335 					       zero_size_allowed);
7336 	case PTR_TO_BUF:
7337 		if (type_is_rdonly_mem(reg->type)) {
7338 			if (meta && meta->raw_mode) {
7339 				verbose(env, "R%d cannot write into %s\n", regno,
7340 					reg_type_str(env, reg->type));
7341 				return -EACCES;
7342 			}
7343 
7344 			max_access = &env->prog->aux->max_rdonly_access;
7345 		} else {
7346 			max_access = &env->prog->aux->max_rdwr_access;
7347 		}
7348 		return check_buffer_access(env, reg, regno, reg->off,
7349 					   access_size, zero_size_allowed,
7350 					   max_access);
7351 	case PTR_TO_STACK:
7352 		return check_stack_range_initialized(
7353 				env,
7354 				regno, reg->off, access_size,
7355 				zero_size_allowed, ACCESS_HELPER, meta);
7356 	case PTR_TO_BTF_ID:
7357 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7358 					       access_size, BPF_READ, -1);
7359 	case PTR_TO_CTX:
7360 		/* in case the function doesn't know how to access the context,
7361 		 * (because we are in a program of type SYSCALL for example), we
7362 		 * can not statically check its size.
7363 		 * Dynamically check it now.
7364 		 */
7365 		if (!env->ops->convert_ctx_access) {
7366 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7367 			int offset = access_size - 1;
7368 
7369 			/* Allow zero-byte read from PTR_TO_CTX */
7370 			if (access_size == 0)
7371 				return zero_size_allowed ? 0 : -EACCES;
7372 
7373 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7374 						atype, -1, false, false);
7375 		}
7376 
7377 		fallthrough;
7378 	default: /* scalar_value or invalid ptr */
7379 		/* Allow zero-byte read from NULL, regardless of pointer type */
7380 		if (zero_size_allowed && access_size == 0 &&
7381 		    register_is_null(reg))
7382 			return 0;
7383 
7384 		verbose(env, "R%d type=%s ", regno,
7385 			reg_type_str(env, reg->type));
7386 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7387 		return -EACCES;
7388 	}
7389 }
7390 
7391 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
7392  * size.
7393  *
7394  * @regno is the register containing the access size. regno-1 is the register
7395  * containing the pointer.
7396  */
check_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,bool zero_size_allowed,struct bpf_call_arg_meta * meta)7397 static int check_mem_size_reg(struct bpf_verifier_env *env,
7398 			      struct bpf_reg_state *reg, u32 regno,
7399 			      bool zero_size_allowed,
7400 			      struct bpf_call_arg_meta *meta)
7401 {
7402 	int err;
7403 
7404 	/* This is used to refine r0 return value bounds for helpers
7405 	 * that enforce this value as an upper bound on return values.
7406 	 * See do_refine_retval_range() for helpers that can refine
7407 	 * the return value. C type of helper is u32 so we pull register
7408 	 * bound from umax_value however, if negative verifier errors
7409 	 * out. Only upper bounds can be learned because retval is an
7410 	 * int type and negative retvals are allowed.
7411 	 */
7412 	meta->msize_max_value = reg->umax_value;
7413 
7414 	/* The register is SCALAR_VALUE; the access check
7415 	 * happens using its boundaries.
7416 	 */
7417 	if (!tnum_is_const(reg->var_off))
7418 		/* For unprivileged variable accesses, disable raw
7419 		 * mode so that the program is required to
7420 		 * initialize all the memory that the helper could
7421 		 * just partially fill up.
7422 		 */
7423 		meta = NULL;
7424 
7425 	if (reg->smin_value < 0) {
7426 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7427 			regno);
7428 		return -EACCES;
7429 	}
7430 
7431 	if (reg->umin_value == 0 && !zero_size_allowed) {
7432 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7433 			regno, reg->umin_value, reg->umax_value);
7434 		return -EACCES;
7435 	}
7436 
7437 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7438 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7439 			regno);
7440 		return -EACCES;
7441 	}
7442 	err = check_helper_mem_access(env, regno - 1,
7443 				      reg->umax_value,
7444 				      zero_size_allowed, meta);
7445 	if (!err)
7446 		err = mark_chain_precision(env, regno);
7447 	return err;
7448 }
7449 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)7450 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7451 			 u32 regno, u32 mem_size)
7452 {
7453 	bool may_be_null = type_may_be_null(reg->type);
7454 	struct bpf_reg_state saved_reg;
7455 	struct bpf_call_arg_meta meta;
7456 	int err;
7457 
7458 	if (register_is_null(reg))
7459 		return 0;
7460 
7461 	memset(&meta, 0, sizeof(meta));
7462 	/* Assuming that the register contains a value check if the memory
7463 	 * access is safe. Temporarily save and restore the register's state as
7464 	 * the conversion shouldn't be visible to a caller.
7465 	 */
7466 	if (may_be_null) {
7467 		saved_reg = *reg;
7468 		mark_ptr_not_null_reg(reg);
7469 	}
7470 
7471 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7472 	/* Check access for BPF_WRITE */
7473 	meta.raw_mode = true;
7474 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7475 
7476 	if (may_be_null)
7477 		*reg = saved_reg;
7478 
7479 	return err;
7480 }
7481 
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)7482 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7483 				    u32 regno)
7484 {
7485 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7486 	bool may_be_null = type_may_be_null(mem_reg->type);
7487 	struct bpf_reg_state saved_reg;
7488 	struct bpf_call_arg_meta meta;
7489 	int err;
7490 
7491 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7492 
7493 	memset(&meta, 0, sizeof(meta));
7494 
7495 	if (may_be_null) {
7496 		saved_reg = *mem_reg;
7497 		mark_ptr_not_null_reg(mem_reg);
7498 	}
7499 
7500 	err = check_mem_size_reg(env, reg, regno, true, &meta);
7501 	/* Check access for BPF_WRITE */
7502 	meta.raw_mode = true;
7503 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7504 
7505 	if (may_be_null)
7506 		*mem_reg = saved_reg;
7507 	return err;
7508 }
7509 
7510 /* Implementation details:
7511  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7512  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7513  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7514  * Two separate bpf_obj_new will also have different reg->id.
7515  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7516  * clears reg->id after value_or_null->value transition, since the verifier only
7517  * cares about the range of access to valid map value pointer and doesn't care
7518  * about actual address of the map element.
7519  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7520  * reg->id > 0 after value_or_null->value transition. By doing so
7521  * two bpf_map_lookups will be considered two different pointers that
7522  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7523  * returned from bpf_obj_new.
7524  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7525  * dead-locks.
7526  * Since only one bpf_spin_lock is allowed the checks are simpler than
7527  * reg_is_refcounted() logic. The verifier needs to remember only
7528  * one spin_lock instead of array of acquired_refs.
7529  * cur_state->active_lock remembers which map value element or allocated
7530  * object got locked and clears it after bpf_spin_unlock.
7531  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)7532 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7533 			     bool is_lock)
7534 {
7535 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7536 	struct bpf_verifier_state *cur = env->cur_state;
7537 	bool is_const = tnum_is_const(reg->var_off);
7538 	u64 val = reg->var_off.value;
7539 	struct bpf_map *map = NULL;
7540 	struct btf *btf = NULL;
7541 	struct btf_record *rec;
7542 
7543 	if (!is_const) {
7544 		verbose(env,
7545 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7546 			regno);
7547 		return -EINVAL;
7548 	}
7549 	if (reg->type == PTR_TO_MAP_VALUE) {
7550 		map = reg->map_ptr;
7551 		if (!map->btf) {
7552 			verbose(env,
7553 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7554 				map->name);
7555 			return -EINVAL;
7556 		}
7557 	} else {
7558 		btf = reg->btf;
7559 	}
7560 
7561 	rec = reg_btf_record(reg);
7562 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7563 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7564 			map ? map->name : "kptr");
7565 		return -EINVAL;
7566 	}
7567 	if (rec->spin_lock_off != val + reg->off) {
7568 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7569 			val + reg->off, rec->spin_lock_off);
7570 		return -EINVAL;
7571 	}
7572 	if (is_lock) {
7573 		if (cur->active_lock.ptr) {
7574 			verbose(env,
7575 				"Locking two bpf_spin_locks are not allowed\n");
7576 			return -EINVAL;
7577 		}
7578 		if (map)
7579 			cur->active_lock.ptr = map;
7580 		else
7581 			cur->active_lock.ptr = btf;
7582 		cur->active_lock.id = reg->id;
7583 	} else {
7584 		void *ptr;
7585 
7586 		if (map)
7587 			ptr = map;
7588 		else
7589 			ptr = btf;
7590 
7591 		if (!cur->active_lock.ptr) {
7592 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7593 			return -EINVAL;
7594 		}
7595 		if (cur->active_lock.ptr != ptr ||
7596 		    cur->active_lock.id != reg->id) {
7597 			verbose(env, "bpf_spin_unlock of different lock\n");
7598 			return -EINVAL;
7599 		}
7600 
7601 		invalidate_non_owning_refs(env);
7602 
7603 		cur->active_lock.ptr = NULL;
7604 		cur->active_lock.id = 0;
7605 	}
7606 	return 0;
7607 }
7608 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7609 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7610 			      struct bpf_call_arg_meta *meta)
7611 {
7612 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7613 	bool is_const = tnum_is_const(reg->var_off);
7614 	struct bpf_map *map = reg->map_ptr;
7615 	u64 val = reg->var_off.value;
7616 
7617 	if (!is_const) {
7618 		verbose(env,
7619 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7620 			regno);
7621 		return -EINVAL;
7622 	}
7623 	if (!map->btf) {
7624 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7625 			map->name);
7626 		return -EINVAL;
7627 	}
7628 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7629 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7630 		return -EINVAL;
7631 	}
7632 	if (map->record->timer_off != val + reg->off) {
7633 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7634 			val + reg->off, map->record->timer_off);
7635 		return -EINVAL;
7636 	}
7637 	if (meta->map_ptr) {
7638 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7639 		return -EFAULT;
7640 	}
7641 	meta->map_uid = reg->map_uid;
7642 	meta->map_ptr = map;
7643 	return 0;
7644 }
7645 
process_wq_func(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)7646 static int process_wq_func(struct bpf_verifier_env *env, int regno,
7647 			   struct bpf_kfunc_call_arg_meta *meta)
7648 {
7649 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7650 	struct bpf_map *map = reg->map_ptr;
7651 	u64 val = reg->var_off.value;
7652 
7653 	if (map->record->wq_off != val + reg->off) {
7654 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
7655 			val + reg->off, map->record->wq_off);
7656 		return -EINVAL;
7657 	}
7658 	meta->map.uid = reg->map_uid;
7659 	meta->map.ptr = map;
7660 	return 0;
7661 }
7662 
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7663 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7664 			     struct bpf_call_arg_meta *meta)
7665 {
7666 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7667 	struct bpf_map *map_ptr = reg->map_ptr;
7668 	struct btf_field *kptr_field;
7669 	u32 kptr_off;
7670 
7671 	if (!tnum_is_const(reg->var_off)) {
7672 		verbose(env,
7673 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7674 			regno);
7675 		return -EINVAL;
7676 	}
7677 	if (!map_ptr->btf) {
7678 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7679 			map_ptr->name);
7680 		return -EINVAL;
7681 	}
7682 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7683 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7684 		return -EINVAL;
7685 	}
7686 
7687 	meta->map_ptr = map_ptr;
7688 	kptr_off = reg->off + reg->var_off.value;
7689 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7690 	if (!kptr_field) {
7691 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7692 		return -EACCES;
7693 	}
7694 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7695 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7696 		return -EACCES;
7697 	}
7698 	meta->kptr_field = kptr_field;
7699 	return 0;
7700 }
7701 
7702 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7703  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7704  *
7705  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7706  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7707  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7708  *
7709  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7710  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7711  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7712  * mutate the view of the dynptr and also possibly destroy it. In the latter
7713  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7714  * memory that dynptr points to.
7715  *
7716  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7717  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7718  * readonly dynptr view yet, hence only the first case is tracked and checked.
7719  *
7720  * This is consistent with how C applies the const modifier to a struct object,
7721  * where the pointer itself inside bpf_dynptr becomes const but not what it
7722  * points to.
7723  *
7724  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7725  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7726  */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)7727 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7728 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7729 {
7730 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7731 	int err;
7732 
7733 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
7734 		verbose(env,
7735 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
7736 			regno);
7737 		return -EINVAL;
7738 	}
7739 
7740 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7741 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7742 	 */
7743 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7744 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7745 		return -EFAULT;
7746 	}
7747 
7748 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7749 	 *		 constructing a mutable bpf_dynptr object.
7750 	 *
7751 	 *		 Currently, this is only possible with PTR_TO_STACK
7752 	 *		 pointing to a region of at least 16 bytes which doesn't
7753 	 *		 contain an existing bpf_dynptr.
7754 	 *
7755 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7756 	 *		 mutated or destroyed. However, the memory it points to
7757 	 *		 may be mutated.
7758 	 *
7759 	 *  None       - Points to a initialized dynptr that can be mutated and
7760 	 *		 destroyed, including mutation of the memory it points
7761 	 *		 to.
7762 	 */
7763 	if (arg_type & MEM_UNINIT) {
7764 		int i;
7765 
7766 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7767 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7768 			return -EINVAL;
7769 		}
7770 
7771 		/* we write BPF_DW bits (8 bytes) at a time */
7772 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7773 			err = check_mem_access(env, insn_idx, regno,
7774 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7775 			if (err)
7776 				return err;
7777 		}
7778 
7779 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7780 	} else /* MEM_RDONLY and None case from above */ {
7781 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7782 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7783 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7784 			return -EINVAL;
7785 		}
7786 
7787 		if (!is_dynptr_reg_valid_init(env, reg)) {
7788 			verbose(env,
7789 				"Expected an initialized dynptr as arg #%d\n",
7790 				regno);
7791 			return -EINVAL;
7792 		}
7793 
7794 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7795 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7796 			verbose(env,
7797 				"Expected a dynptr of type %s as arg #%d\n",
7798 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7799 			return -EINVAL;
7800 		}
7801 
7802 		err = mark_dynptr_read(env, reg);
7803 	}
7804 	return err;
7805 }
7806 
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)7807 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7808 {
7809 	struct bpf_func_state *state = func(env, reg);
7810 
7811 	return state->stack[spi].spilled_ptr.ref_obj_id;
7812 }
7813 
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)7814 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7815 {
7816 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7817 }
7818 
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)7819 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7820 {
7821 	return meta->kfunc_flags & KF_ITER_NEW;
7822 }
7823 
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)7824 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7825 {
7826 	return meta->kfunc_flags & KF_ITER_NEXT;
7827 }
7828 
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)7829 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7830 {
7831 	return meta->kfunc_flags & KF_ITER_DESTROY;
7832 }
7833 
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg)7834 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7835 {
7836 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7837 	 * kfunc is iter state pointer
7838 	 */
7839 	return arg == 0 && is_iter_kfunc(meta);
7840 }
7841 
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7842 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7843 			    struct bpf_kfunc_call_arg_meta *meta)
7844 {
7845 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7846 	const struct btf_type *t;
7847 	const struct btf_param *arg;
7848 	int spi, err, i, nr_slots;
7849 	u32 btf_id;
7850 
7851 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7852 	arg = &btf_params(meta->func_proto)[0];
7853 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7854 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7855 	nr_slots = t->size / BPF_REG_SIZE;
7856 
7857 	if (is_iter_new_kfunc(meta)) {
7858 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7859 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7860 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7861 				iter_type_str(meta->btf, btf_id), regno);
7862 			return -EINVAL;
7863 		}
7864 
7865 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7866 			err = check_mem_access(env, insn_idx, regno,
7867 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7868 			if (err)
7869 				return err;
7870 		}
7871 
7872 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7873 		if (err)
7874 			return err;
7875 	} else {
7876 		/* iter_next() or iter_destroy() expect initialized iter state*/
7877 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7878 		switch (err) {
7879 		case 0:
7880 			break;
7881 		case -EINVAL:
7882 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7883 				iter_type_str(meta->btf, btf_id), regno);
7884 			return err;
7885 		case -EPROTO:
7886 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7887 			return err;
7888 		default:
7889 			return err;
7890 		}
7891 
7892 		spi = iter_get_spi(env, reg, nr_slots);
7893 		if (spi < 0)
7894 			return spi;
7895 
7896 		err = mark_iter_read(env, reg, spi, nr_slots);
7897 		if (err)
7898 			return err;
7899 
7900 		/* remember meta->iter info for process_iter_next_call() */
7901 		meta->iter.spi = spi;
7902 		meta->iter.frameno = reg->frameno;
7903 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7904 
7905 		if (is_iter_destroy_kfunc(meta)) {
7906 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7907 			if (err)
7908 				return err;
7909 		}
7910 	}
7911 
7912 	return 0;
7913 }
7914 
7915 /* Look for a previous loop entry at insn_idx: nearest parent state
7916  * stopped at insn_idx with callsites matching those in cur->frame.
7917  */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)7918 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7919 						  struct bpf_verifier_state *cur,
7920 						  int insn_idx)
7921 {
7922 	struct bpf_verifier_state_list *sl;
7923 	struct bpf_verifier_state *st;
7924 
7925 	/* Explored states are pushed in stack order, most recent states come first */
7926 	sl = *explored_state(env, insn_idx);
7927 	for (; sl; sl = sl->next) {
7928 		/* If st->branches != 0 state is a part of current DFS verification path,
7929 		 * hence cur & st for a loop.
7930 		 */
7931 		st = &sl->state;
7932 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7933 		    st->dfs_depth < cur->dfs_depth)
7934 			return st;
7935 	}
7936 
7937 	return NULL;
7938 }
7939 
7940 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7941 static bool regs_exact(const struct bpf_reg_state *rold,
7942 		       const struct bpf_reg_state *rcur,
7943 		       struct bpf_idmap *idmap);
7944 
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)7945 static void maybe_widen_reg(struct bpf_verifier_env *env,
7946 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7947 			    struct bpf_idmap *idmap)
7948 {
7949 	if (rold->type != SCALAR_VALUE)
7950 		return;
7951 	if (rold->type != rcur->type)
7952 		return;
7953 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7954 		return;
7955 	__mark_reg_unknown(env, rcur);
7956 }
7957 
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)7958 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7959 				   struct bpf_verifier_state *old,
7960 				   struct bpf_verifier_state *cur)
7961 {
7962 	struct bpf_func_state *fold, *fcur;
7963 	int i, fr;
7964 
7965 	reset_idmap_scratch(env);
7966 	for (fr = old->curframe; fr >= 0; fr--) {
7967 		fold = old->frame[fr];
7968 		fcur = cur->frame[fr];
7969 
7970 		for (i = 0; i < MAX_BPF_REG; i++)
7971 			maybe_widen_reg(env,
7972 					&fold->regs[i],
7973 					&fcur->regs[i],
7974 					&env->idmap_scratch);
7975 
7976 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7977 			if (!is_spilled_reg(&fold->stack[i]) ||
7978 			    !is_spilled_reg(&fcur->stack[i]))
7979 				continue;
7980 
7981 			maybe_widen_reg(env,
7982 					&fold->stack[i].spilled_ptr,
7983 					&fcur->stack[i].spilled_ptr,
7984 					&env->idmap_scratch);
7985 		}
7986 	}
7987 	return 0;
7988 }
7989 
7990 /* process_iter_next_call() is called when verifier gets to iterator's next
7991  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7992  * to it as just "iter_next()" in comments below.
7993  *
7994  * BPF verifier relies on a crucial contract for any iter_next()
7995  * implementation: it should *eventually* return NULL, and once that happens
7996  * it should keep returning NULL. That is, once iterator exhausts elements to
7997  * iterate, it should never reset or spuriously return new elements.
7998  *
7999  * With the assumption of such contract, process_iter_next_call() simulates
8000  * a fork in the verifier state to validate loop logic correctness and safety
8001  * without having to simulate infinite amount of iterations.
8002  *
8003  * In current state, we first assume that iter_next() returned NULL and
8004  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8005  * conditions we should not form an infinite loop and should eventually reach
8006  * exit.
8007  *
8008  * Besides that, we also fork current state and enqueue it for later
8009  * verification. In a forked state we keep iterator state as ACTIVE
8010  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8011  * also bump iteration depth to prevent erroneous infinite loop detection
8012  * later on (see iter_active_depths_differ() comment for details). In this
8013  * state we assume that we'll eventually loop back to another iter_next()
8014  * calls (it could be in exactly same location or in some other instruction,
8015  * it doesn't matter, we don't make any unnecessary assumptions about this,
8016  * everything revolves around iterator state in a stack slot, not which
8017  * instruction is calling iter_next()). When that happens, we either will come
8018  * to iter_next() with equivalent state and can conclude that next iteration
8019  * will proceed in exactly the same way as we just verified, so it's safe to
8020  * assume that loop converges. If not, we'll go on another iteration
8021  * simulation with a different input state, until all possible starting states
8022  * are validated or we reach maximum number of instructions limit.
8023  *
8024  * This way, we will either exhaustively discover all possible input states
8025  * that iterator loop can start with and eventually will converge, or we'll
8026  * effectively regress into bounded loop simulation logic and either reach
8027  * maximum number of instructions if loop is not provably convergent, or there
8028  * is some statically known limit on number of iterations (e.g., if there is
8029  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8030  *
8031  * Iteration convergence logic in is_state_visited() relies on exact
8032  * states comparison, which ignores read and precision marks.
8033  * This is necessary because read and precision marks are not finalized
8034  * while in the loop. Exact comparison might preclude convergence for
8035  * simple programs like below:
8036  *
8037  *     i = 0;
8038  *     while(iter_next(&it))
8039  *       i++;
8040  *
8041  * At each iteration step i++ would produce a new distinct state and
8042  * eventually instruction processing limit would be reached.
8043  *
8044  * To avoid such behavior speculatively forget (widen) range for
8045  * imprecise scalar registers, if those registers were not precise at the
8046  * end of the previous iteration and do not match exactly.
8047  *
8048  * This is a conservative heuristic that allows to verify wide range of programs,
8049  * however it precludes verification of programs that conjure an
8050  * imprecise value on the first loop iteration and use it as precise on a second.
8051  * For example, the following safe program would fail to verify:
8052  *
8053  *     struct bpf_num_iter it;
8054  *     int arr[10];
8055  *     int i = 0, a = 0;
8056  *     bpf_iter_num_new(&it, 0, 10);
8057  *     while (bpf_iter_num_next(&it)) {
8058  *       if (a == 0) {
8059  *         a = 1;
8060  *         i = 7; // Because i changed verifier would forget
8061  *                // it's range on second loop entry.
8062  *       } else {
8063  *         arr[i] = 42; // This would fail to verify.
8064  *       }
8065  *     }
8066  *     bpf_iter_num_destroy(&it);
8067  */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)8068 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8069 				  struct bpf_kfunc_call_arg_meta *meta)
8070 {
8071 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8072 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8073 	struct bpf_reg_state *cur_iter, *queued_iter;
8074 	int iter_frameno = meta->iter.frameno;
8075 	int iter_spi = meta->iter.spi;
8076 
8077 	BTF_TYPE_EMIT(struct bpf_iter);
8078 
8079 	cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8080 
8081 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8082 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8083 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8084 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8085 		return -EFAULT;
8086 	}
8087 
8088 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8089 		/* Because iter_next() call is a checkpoint is_state_visitied()
8090 		 * should guarantee parent state with same call sites and insn_idx.
8091 		 */
8092 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8093 		    !same_callsites(cur_st->parent, cur_st)) {
8094 			verbose(env, "bug: bad parent state for iter next call");
8095 			return -EFAULT;
8096 		}
8097 		/* Note cur_st->parent in the call below, it is necessary to skip
8098 		 * checkpoint created for cur_st by is_state_visited()
8099 		 * right at this instruction.
8100 		 */
8101 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8102 		/* branch out active iter state */
8103 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8104 		if (!queued_st)
8105 			return -ENOMEM;
8106 
8107 		queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8108 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8109 		queued_iter->iter.depth++;
8110 		if (prev_st)
8111 			widen_imprecise_scalars(env, prev_st, queued_st);
8112 
8113 		queued_fr = queued_st->frame[queued_st->curframe];
8114 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8115 	}
8116 
8117 	/* switch to DRAINED state, but keep the depth unchanged */
8118 	/* mark current iter state as drained and assume returned NULL */
8119 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8120 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
8121 
8122 	return 0;
8123 }
8124 
arg_type_is_mem_size(enum bpf_arg_type type)8125 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8126 {
8127 	return type == ARG_CONST_SIZE ||
8128 	       type == ARG_CONST_SIZE_OR_ZERO;
8129 }
8130 
arg_type_is_release(enum bpf_arg_type type)8131 static bool arg_type_is_release(enum bpf_arg_type type)
8132 {
8133 	return type & OBJ_RELEASE;
8134 }
8135 
arg_type_is_dynptr(enum bpf_arg_type type)8136 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8137 {
8138 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8139 }
8140 
int_ptr_type_to_size(enum bpf_arg_type type)8141 static int int_ptr_type_to_size(enum bpf_arg_type type)
8142 {
8143 	if (type == ARG_PTR_TO_INT)
8144 		return sizeof(u32);
8145 	else if (type == ARG_PTR_TO_LONG)
8146 		return sizeof(u64);
8147 
8148 	return -EINVAL;
8149 }
8150 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)8151 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8152 				 const struct bpf_call_arg_meta *meta,
8153 				 enum bpf_arg_type *arg_type)
8154 {
8155 	if (!meta->map_ptr) {
8156 		/* kernel subsystem misconfigured verifier */
8157 		verbose(env, "invalid map_ptr to access map->type\n");
8158 		return -EACCES;
8159 	}
8160 
8161 	switch (meta->map_ptr->map_type) {
8162 	case BPF_MAP_TYPE_SOCKMAP:
8163 	case BPF_MAP_TYPE_SOCKHASH:
8164 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8165 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8166 		} else {
8167 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8168 			return -EINVAL;
8169 		}
8170 		break;
8171 	case BPF_MAP_TYPE_BLOOM_FILTER:
8172 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8173 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8174 		break;
8175 	default:
8176 		break;
8177 	}
8178 	return 0;
8179 }
8180 
8181 struct bpf_reg_types {
8182 	const enum bpf_reg_type types[10];
8183 	u32 *btf_id;
8184 };
8185 
8186 static const struct bpf_reg_types sock_types = {
8187 	.types = {
8188 		PTR_TO_SOCK_COMMON,
8189 		PTR_TO_SOCKET,
8190 		PTR_TO_TCP_SOCK,
8191 		PTR_TO_XDP_SOCK,
8192 	},
8193 };
8194 
8195 #ifdef CONFIG_NET
8196 static const struct bpf_reg_types btf_id_sock_common_types = {
8197 	.types = {
8198 		PTR_TO_SOCK_COMMON,
8199 		PTR_TO_SOCKET,
8200 		PTR_TO_TCP_SOCK,
8201 		PTR_TO_XDP_SOCK,
8202 		PTR_TO_BTF_ID,
8203 		PTR_TO_BTF_ID | PTR_TRUSTED,
8204 	},
8205 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8206 };
8207 #endif
8208 
8209 static const struct bpf_reg_types mem_types = {
8210 	.types = {
8211 		PTR_TO_STACK,
8212 		PTR_TO_PACKET,
8213 		PTR_TO_PACKET_META,
8214 		PTR_TO_MAP_KEY,
8215 		PTR_TO_MAP_VALUE,
8216 		PTR_TO_MEM,
8217 		PTR_TO_MEM | MEM_RINGBUF,
8218 		PTR_TO_BUF,
8219 		PTR_TO_BTF_ID | PTR_TRUSTED,
8220 	},
8221 };
8222 
8223 static const struct bpf_reg_types int_ptr_types = {
8224 	.types = {
8225 		PTR_TO_STACK,
8226 		PTR_TO_PACKET,
8227 		PTR_TO_PACKET_META,
8228 		PTR_TO_MAP_KEY,
8229 		PTR_TO_MAP_VALUE,
8230 	},
8231 };
8232 
8233 static const struct bpf_reg_types spin_lock_types = {
8234 	.types = {
8235 		PTR_TO_MAP_VALUE,
8236 		PTR_TO_BTF_ID | MEM_ALLOC,
8237 	}
8238 };
8239 
8240 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8241 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8242 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8243 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8244 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8245 static const struct bpf_reg_types btf_ptr_types = {
8246 	.types = {
8247 		PTR_TO_BTF_ID,
8248 		PTR_TO_BTF_ID | PTR_TRUSTED,
8249 		PTR_TO_BTF_ID | MEM_RCU,
8250 	},
8251 };
8252 static const struct bpf_reg_types percpu_btf_ptr_types = {
8253 	.types = {
8254 		PTR_TO_BTF_ID | MEM_PERCPU,
8255 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8256 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8257 	}
8258 };
8259 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8260 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8261 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8262 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8263 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8264 static const struct bpf_reg_types dynptr_types = {
8265 	.types = {
8266 		PTR_TO_STACK,
8267 		CONST_PTR_TO_DYNPTR,
8268 	}
8269 };
8270 
8271 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8272 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8273 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8274 	[ARG_CONST_SIZE]		= &scalar_types,
8275 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8276 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8277 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8278 	[ARG_PTR_TO_CTX]		= &context_types,
8279 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8280 #ifdef CONFIG_NET
8281 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8282 #endif
8283 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8284 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8285 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8286 	[ARG_PTR_TO_MEM]		= &mem_types,
8287 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8288 	[ARG_PTR_TO_INT]		= &int_ptr_types,
8289 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
8290 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8291 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8292 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8293 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8294 	[ARG_PTR_TO_TIMER]		= &timer_types,
8295 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8296 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8297 };
8298 
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)8299 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8300 			  enum bpf_arg_type arg_type,
8301 			  const u32 *arg_btf_id,
8302 			  struct bpf_call_arg_meta *meta)
8303 {
8304 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8305 	enum bpf_reg_type expected, type = reg->type;
8306 	const struct bpf_reg_types *compatible;
8307 	int i, j;
8308 
8309 	compatible = compatible_reg_types[base_type(arg_type)];
8310 	if (!compatible) {
8311 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8312 		return -EFAULT;
8313 	}
8314 
8315 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8316 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8317 	 *
8318 	 * Same for MAYBE_NULL:
8319 	 *
8320 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8321 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8322 	 *
8323 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8324 	 *
8325 	 * Therefore we fold these flags depending on the arg_type before comparison.
8326 	 */
8327 	if (arg_type & MEM_RDONLY)
8328 		type &= ~MEM_RDONLY;
8329 	if (arg_type & PTR_MAYBE_NULL)
8330 		type &= ~PTR_MAYBE_NULL;
8331 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8332 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8333 
8334 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8335 		type &= ~MEM_ALLOC;
8336 		type &= ~MEM_PERCPU;
8337 	}
8338 
8339 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8340 		expected = compatible->types[i];
8341 		if (expected == NOT_INIT)
8342 			break;
8343 
8344 		if (type == expected)
8345 			goto found;
8346 	}
8347 
8348 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8349 	for (j = 0; j + 1 < i; j++)
8350 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8351 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8352 	return -EACCES;
8353 
8354 found:
8355 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8356 		return 0;
8357 
8358 	if (compatible == &mem_types) {
8359 		if (!(arg_type & MEM_RDONLY)) {
8360 			verbose(env,
8361 				"%s() may write into memory pointed by R%d type=%s\n",
8362 				func_id_name(meta->func_id),
8363 				regno, reg_type_str(env, reg->type));
8364 			return -EACCES;
8365 		}
8366 		return 0;
8367 	}
8368 
8369 	switch ((int)reg->type) {
8370 	case PTR_TO_BTF_ID:
8371 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8372 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
8373 	case PTR_TO_BTF_ID | MEM_RCU:
8374 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8375 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8376 	{
8377 		/* For bpf_sk_release, it needs to match against first member
8378 		 * 'struct sock_common', hence make an exception for it. This
8379 		 * allows bpf_sk_release to work for multiple socket types.
8380 		 */
8381 		bool strict_type_match = arg_type_is_release(arg_type) &&
8382 					 meta->func_id != BPF_FUNC_sk_release;
8383 
8384 		if (type_may_be_null(reg->type) &&
8385 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8386 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8387 			return -EACCES;
8388 		}
8389 
8390 		if (!arg_btf_id) {
8391 			if (!compatible->btf_id) {
8392 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8393 				return -EFAULT;
8394 			}
8395 			arg_btf_id = compatible->btf_id;
8396 		}
8397 
8398 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8399 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8400 				return -EACCES;
8401 		} else {
8402 			if (arg_btf_id == BPF_PTR_POISON) {
8403 				verbose(env, "verifier internal error:");
8404 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8405 					regno);
8406 				return -EACCES;
8407 			}
8408 
8409 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8410 						  btf_vmlinux, *arg_btf_id,
8411 						  strict_type_match)) {
8412 				verbose(env, "R%d is of type %s but %s is expected\n",
8413 					regno, btf_type_name(reg->btf, reg->btf_id),
8414 					btf_type_name(btf_vmlinux, *arg_btf_id));
8415 				return -EACCES;
8416 			}
8417 		}
8418 		break;
8419 	}
8420 	case PTR_TO_BTF_ID | MEM_ALLOC:
8421 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8422 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8423 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8424 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8425 			return -EFAULT;
8426 		}
8427 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8428 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8429 				return -EACCES;
8430 		}
8431 		break;
8432 	case PTR_TO_BTF_ID | MEM_PERCPU:
8433 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8434 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8435 		/* Handled by helper specific checks */
8436 		break;
8437 	default:
8438 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8439 		return -EFAULT;
8440 	}
8441 	return 0;
8442 }
8443 
8444 static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)8445 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8446 {
8447 	struct btf_field *field;
8448 	struct btf_record *rec;
8449 
8450 	rec = reg_btf_record(reg);
8451 	if (!rec)
8452 		return NULL;
8453 
8454 	field = btf_record_find(rec, off, fields);
8455 	if (!field)
8456 		return NULL;
8457 
8458 	return field;
8459 }
8460 
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)8461 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
8462 				  const struct bpf_reg_state *reg, int regno,
8463 				  enum bpf_arg_type arg_type)
8464 {
8465 	u32 type = reg->type;
8466 
8467 	/* When referenced register is passed to release function, its fixed
8468 	 * offset must be 0.
8469 	 *
8470 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8471 	 * meta->release_regno.
8472 	 */
8473 	if (arg_type_is_release(arg_type)) {
8474 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8475 		 * may not directly point to the object being released, but to
8476 		 * dynptr pointing to such object, which might be at some offset
8477 		 * on the stack. In that case, we simply to fallback to the
8478 		 * default handling.
8479 		 */
8480 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8481 			return 0;
8482 
8483 		/* Doing check_ptr_off_reg check for the offset will catch this
8484 		 * because fixed_off_ok is false, but checking here allows us
8485 		 * to give the user a better error message.
8486 		 */
8487 		if (reg->off) {
8488 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8489 				regno);
8490 			return -EINVAL;
8491 		}
8492 		return __check_ptr_off_reg(env, reg, regno, false);
8493 	}
8494 
8495 	switch (type) {
8496 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8497 	case PTR_TO_STACK:
8498 	case PTR_TO_PACKET:
8499 	case PTR_TO_PACKET_META:
8500 	case PTR_TO_MAP_KEY:
8501 	case PTR_TO_MAP_VALUE:
8502 	case PTR_TO_MEM:
8503 	case PTR_TO_MEM | MEM_RDONLY:
8504 	case PTR_TO_MEM | MEM_RINGBUF:
8505 	case PTR_TO_BUF:
8506 	case PTR_TO_BUF | MEM_RDONLY:
8507 	case PTR_TO_ARENA:
8508 	case SCALAR_VALUE:
8509 		return 0;
8510 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8511 	 * fixed offset.
8512 	 */
8513 	case PTR_TO_BTF_ID:
8514 	case PTR_TO_BTF_ID | MEM_ALLOC:
8515 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8516 	case PTR_TO_BTF_ID | MEM_RCU:
8517 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8518 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8519 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8520 		 * its fixed offset must be 0. In the other cases, fixed offset
8521 		 * can be non-zero. This was already checked above. So pass
8522 		 * fixed_off_ok as true to allow fixed offset for all other
8523 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8524 		 * still need to do checks instead of returning.
8525 		 */
8526 		return __check_ptr_off_reg(env, reg, regno, true);
8527 	default:
8528 		return __check_ptr_off_reg(env, reg, regno, false);
8529 	}
8530 }
8531 
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)8532 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8533 						const struct bpf_func_proto *fn,
8534 						struct bpf_reg_state *regs)
8535 {
8536 	struct bpf_reg_state *state = NULL;
8537 	int i;
8538 
8539 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8540 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8541 			if (state) {
8542 				verbose(env, "verifier internal error: multiple dynptr args\n");
8543 				return NULL;
8544 			}
8545 			state = &regs[BPF_REG_1 + i];
8546 		}
8547 
8548 	if (!state)
8549 		verbose(env, "verifier internal error: no dynptr arg found\n");
8550 
8551 	return state;
8552 }
8553 
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8554 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8555 {
8556 	struct bpf_func_state *state = func(env, reg);
8557 	int spi;
8558 
8559 	if (reg->type == CONST_PTR_TO_DYNPTR)
8560 		return reg->id;
8561 	spi = dynptr_get_spi(env, reg);
8562 	if (spi < 0)
8563 		return spi;
8564 	return state->stack[spi].spilled_ptr.id;
8565 }
8566 
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8567 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8568 {
8569 	struct bpf_func_state *state = func(env, reg);
8570 	int spi;
8571 
8572 	if (reg->type == CONST_PTR_TO_DYNPTR)
8573 		return reg->ref_obj_id;
8574 	spi = dynptr_get_spi(env, reg);
8575 	if (spi < 0)
8576 		return spi;
8577 	return state->stack[spi].spilled_ptr.ref_obj_id;
8578 }
8579 
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8580 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8581 					    struct bpf_reg_state *reg)
8582 {
8583 	struct bpf_func_state *state = func(env, reg);
8584 	int spi;
8585 
8586 	if (reg->type == CONST_PTR_TO_DYNPTR)
8587 		return reg->dynptr.type;
8588 
8589 	spi = __get_spi(reg->off);
8590 	if (spi < 0) {
8591 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8592 		return BPF_DYNPTR_TYPE_INVALID;
8593 	}
8594 
8595 	return state->stack[spi].spilled_ptr.dynptr.type;
8596 }
8597 
check_reg_const_str(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)8598 static int check_reg_const_str(struct bpf_verifier_env *env,
8599 			       struct bpf_reg_state *reg, u32 regno)
8600 {
8601 	struct bpf_map *map = reg->map_ptr;
8602 	int err;
8603 	int map_off;
8604 	u64 map_addr;
8605 	char *str_ptr;
8606 
8607 	if (reg->type != PTR_TO_MAP_VALUE)
8608 		return -EINVAL;
8609 
8610 	if (!bpf_map_is_rdonly(map)) {
8611 		verbose(env, "R%d does not point to a readonly map'\n", regno);
8612 		return -EACCES;
8613 	}
8614 
8615 	if (!tnum_is_const(reg->var_off)) {
8616 		verbose(env, "R%d is not a constant address'\n", regno);
8617 		return -EACCES;
8618 	}
8619 
8620 	if (!map->ops->map_direct_value_addr) {
8621 		verbose(env, "no direct value access support for this map type\n");
8622 		return -EACCES;
8623 	}
8624 
8625 	err = check_map_access(env, regno, reg->off,
8626 			       map->value_size - reg->off, false,
8627 			       ACCESS_HELPER);
8628 	if (err)
8629 		return err;
8630 
8631 	map_off = reg->off + reg->var_off.value;
8632 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8633 	if (err) {
8634 		verbose(env, "direct value access on string failed\n");
8635 		return err;
8636 	}
8637 
8638 	str_ptr = (char *)(long)(map_addr);
8639 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8640 		verbose(env, "string is not zero-terminated\n");
8641 		return -EINVAL;
8642 	}
8643 	return 0;
8644 }
8645 
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)8646 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8647 			  struct bpf_call_arg_meta *meta,
8648 			  const struct bpf_func_proto *fn,
8649 			  int insn_idx)
8650 {
8651 	u32 regno = BPF_REG_1 + arg;
8652 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8653 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8654 	enum bpf_reg_type type = reg->type;
8655 	u32 *arg_btf_id = NULL;
8656 	int err = 0;
8657 
8658 	if (arg_type == ARG_DONTCARE)
8659 		return 0;
8660 
8661 	err = check_reg_arg(env, regno, SRC_OP);
8662 	if (err)
8663 		return err;
8664 
8665 	if (arg_type == ARG_ANYTHING) {
8666 		if (is_pointer_value(env, regno)) {
8667 			verbose(env, "R%d leaks addr into helper function\n",
8668 				regno);
8669 			return -EACCES;
8670 		}
8671 		return 0;
8672 	}
8673 
8674 	if (type_is_pkt_pointer(type) &&
8675 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8676 		verbose(env, "helper access to the packet is not allowed\n");
8677 		return -EACCES;
8678 	}
8679 
8680 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8681 		err = resolve_map_arg_type(env, meta, &arg_type);
8682 		if (err)
8683 			return err;
8684 	}
8685 
8686 	if (register_is_null(reg) && type_may_be_null(arg_type))
8687 		/* A NULL register has a SCALAR_VALUE type, so skip
8688 		 * type checking.
8689 		 */
8690 		goto skip_type_check;
8691 
8692 	/* arg_btf_id and arg_size are in a union. */
8693 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8694 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8695 		arg_btf_id = fn->arg_btf_id[arg];
8696 
8697 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8698 	if (err)
8699 		return err;
8700 
8701 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8702 	if (err)
8703 		return err;
8704 
8705 skip_type_check:
8706 	if (arg_type_is_release(arg_type)) {
8707 		if (arg_type_is_dynptr(arg_type)) {
8708 			struct bpf_func_state *state = func(env, reg);
8709 			int spi;
8710 
8711 			/* Only dynptr created on stack can be released, thus
8712 			 * the get_spi and stack state checks for spilled_ptr
8713 			 * should only be done before process_dynptr_func for
8714 			 * PTR_TO_STACK.
8715 			 */
8716 			if (reg->type == PTR_TO_STACK) {
8717 				spi = dynptr_get_spi(env, reg);
8718 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8719 					verbose(env, "arg %d is an unacquired reference\n", regno);
8720 					return -EINVAL;
8721 				}
8722 			} else {
8723 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8724 				return -EINVAL;
8725 			}
8726 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8727 			verbose(env, "R%d must be referenced when passed to release function\n",
8728 				regno);
8729 			return -EINVAL;
8730 		}
8731 		if (meta->release_regno) {
8732 			verbose(env, "verifier internal error: more than one release argument\n");
8733 			return -EFAULT;
8734 		}
8735 		meta->release_regno = regno;
8736 	}
8737 
8738 	if (reg->ref_obj_id) {
8739 		if (meta->ref_obj_id) {
8740 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8741 				regno, reg->ref_obj_id,
8742 				meta->ref_obj_id);
8743 			return -EFAULT;
8744 		}
8745 		meta->ref_obj_id = reg->ref_obj_id;
8746 	}
8747 
8748 	switch (base_type(arg_type)) {
8749 	case ARG_CONST_MAP_PTR:
8750 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8751 		if (meta->map_ptr) {
8752 			/* Use map_uid (which is unique id of inner map) to reject:
8753 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8754 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8755 			 * if (inner_map1 && inner_map2) {
8756 			 *     timer = bpf_map_lookup_elem(inner_map1);
8757 			 *     if (timer)
8758 			 *         // mismatch would have been allowed
8759 			 *         bpf_timer_init(timer, inner_map2);
8760 			 * }
8761 			 *
8762 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8763 			 */
8764 			if (meta->map_ptr != reg->map_ptr ||
8765 			    meta->map_uid != reg->map_uid) {
8766 				verbose(env,
8767 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8768 					meta->map_uid, reg->map_uid);
8769 				return -EINVAL;
8770 			}
8771 		}
8772 		meta->map_ptr = reg->map_ptr;
8773 		meta->map_uid = reg->map_uid;
8774 		break;
8775 	case ARG_PTR_TO_MAP_KEY:
8776 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8777 		 * check that [key, key + map->key_size) are within
8778 		 * stack limits and initialized
8779 		 */
8780 		if (!meta->map_ptr) {
8781 			/* in function declaration map_ptr must come before
8782 			 * map_key, so that it's verified and known before
8783 			 * we have to check map_key here. Otherwise it means
8784 			 * that kernel subsystem misconfigured verifier
8785 			 */
8786 			verbose(env, "invalid map_ptr to access map->key\n");
8787 			return -EACCES;
8788 		}
8789 		err = check_helper_mem_access(env, regno,
8790 					      meta->map_ptr->key_size, false,
8791 					      NULL);
8792 		break;
8793 	case ARG_PTR_TO_MAP_VALUE:
8794 		if (type_may_be_null(arg_type) && register_is_null(reg))
8795 			return 0;
8796 
8797 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8798 		 * check [value, value + map->value_size) validity
8799 		 */
8800 		if (!meta->map_ptr) {
8801 			/* kernel subsystem misconfigured verifier */
8802 			verbose(env, "invalid map_ptr to access map->value\n");
8803 			return -EACCES;
8804 		}
8805 		meta->raw_mode = arg_type & MEM_UNINIT;
8806 		err = check_helper_mem_access(env, regno,
8807 					      meta->map_ptr->value_size, false,
8808 					      meta);
8809 		break;
8810 	case ARG_PTR_TO_PERCPU_BTF_ID:
8811 		if (!reg->btf_id) {
8812 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8813 			return -EACCES;
8814 		}
8815 		meta->ret_btf = reg->btf;
8816 		meta->ret_btf_id = reg->btf_id;
8817 		break;
8818 	case ARG_PTR_TO_SPIN_LOCK:
8819 		if (in_rbtree_lock_required_cb(env)) {
8820 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8821 			return -EACCES;
8822 		}
8823 		if (meta->func_id == BPF_FUNC_spin_lock) {
8824 			err = process_spin_lock(env, regno, true);
8825 			if (err)
8826 				return err;
8827 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8828 			err = process_spin_lock(env, regno, false);
8829 			if (err)
8830 				return err;
8831 		} else {
8832 			verbose(env, "verifier internal error\n");
8833 			return -EFAULT;
8834 		}
8835 		break;
8836 	case ARG_PTR_TO_TIMER:
8837 		err = process_timer_func(env, regno, meta);
8838 		if (err)
8839 			return err;
8840 		break;
8841 	case ARG_PTR_TO_FUNC:
8842 		meta->subprogno = reg->subprogno;
8843 		break;
8844 	case ARG_PTR_TO_MEM:
8845 		/* The access to this pointer is only checked when we hit the
8846 		 * next is_mem_size argument below.
8847 		 */
8848 		meta->raw_mode = arg_type & MEM_UNINIT;
8849 		if (arg_type & MEM_FIXED_SIZE) {
8850 			err = check_helper_mem_access(env, regno,
8851 						      fn->arg_size[arg], false,
8852 						      meta);
8853 		}
8854 		break;
8855 	case ARG_CONST_SIZE:
8856 		err = check_mem_size_reg(env, reg, regno, false, meta);
8857 		break;
8858 	case ARG_CONST_SIZE_OR_ZERO:
8859 		err = check_mem_size_reg(env, reg, regno, true, meta);
8860 		break;
8861 	case ARG_PTR_TO_DYNPTR:
8862 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8863 		if (err)
8864 			return err;
8865 		break;
8866 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8867 		if (!tnum_is_const(reg->var_off)) {
8868 			verbose(env, "R%d is not a known constant'\n",
8869 				regno);
8870 			return -EACCES;
8871 		}
8872 		meta->mem_size = reg->var_off.value;
8873 		err = mark_chain_precision(env, regno);
8874 		if (err)
8875 			return err;
8876 		break;
8877 	case ARG_PTR_TO_INT:
8878 	case ARG_PTR_TO_LONG:
8879 	{
8880 		int size = int_ptr_type_to_size(arg_type);
8881 
8882 		err = check_helper_mem_access(env, regno, size, false, meta);
8883 		if (err)
8884 			return err;
8885 		err = check_ptr_alignment(env, reg, 0, size, true);
8886 		break;
8887 	}
8888 	case ARG_PTR_TO_CONST_STR:
8889 	{
8890 		err = check_reg_const_str(env, reg, regno);
8891 		if (err)
8892 			return err;
8893 		break;
8894 	}
8895 	case ARG_PTR_TO_KPTR:
8896 		err = process_kptr_func(env, regno, meta);
8897 		if (err)
8898 			return err;
8899 		break;
8900 	}
8901 
8902 	return err;
8903 }
8904 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)8905 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8906 {
8907 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8908 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8909 
8910 	if (func_id != BPF_FUNC_map_update_elem &&
8911 	    func_id != BPF_FUNC_map_delete_elem)
8912 		return false;
8913 
8914 	/* It's not possible to get access to a locked struct sock in these
8915 	 * contexts, so updating is safe.
8916 	 */
8917 	switch (type) {
8918 	case BPF_PROG_TYPE_TRACING:
8919 		if (eatype == BPF_TRACE_ITER)
8920 			return true;
8921 		break;
8922 	case BPF_PROG_TYPE_SOCK_OPS:
8923 		/* map_update allowed only via dedicated helpers with event type checks */
8924 		if (func_id == BPF_FUNC_map_delete_elem)
8925 			return true;
8926 		break;
8927 	case BPF_PROG_TYPE_SOCKET_FILTER:
8928 	case BPF_PROG_TYPE_SCHED_CLS:
8929 	case BPF_PROG_TYPE_SCHED_ACT:
8930 	case BPF_PROG_TYPE_XDP:
8931 	case BPF_PROG_TYPE_SK_REUSEPORT:
8932 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8933 	case BPF_PROG_TYPE_SK_LOOKUP:
8934 		return true;
8935 	default:
8936 		break;
8937 	}
8938 
8939 	verbose(env, "cannot update sockmap in this context\n");
8940 	return false;
8941 }
8942 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)8943 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8944 {
8945 	return env->prog->jit_requested &&
8946 	       bpf_jit_supports_subprog_tailcalls();
8947 }
8948 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)8949 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8950 					struct bpf_map *map, int func_id)
8951 {
8952 	if (!map)
8953 		return 0;
8954 
8955 	/* We need a two way check, first is from map perspective ... */
8956 	switch (map->map_type) {
8957 	case BPF_MAP_TYPE_PROG_ARRAY:
8958 		if (func_id != BPF_FUNC_tail_call)
8959 			goto error;
8960 		break;
8961 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8962 		if (func_id != BPF_FUNC_perf_event_read &&
8963 		    func_id != BPF_FUNC_perf_event_output &&
8964 		    func_id != BPF_FUNC_skb_output &&
8965 		    func_id != BPF_FUNC_perf_event_read_value &&
8966 		    func_id != BPF_FUNC_xdp_output)
8967 			goto error;
8968 		break;
8969 	case BPF_MAP_TYPE_RINGBUF:
8970 		if (func_id != BPF_FUNC_ringbuf_output &&
8971 		    func_id != BPF_FUNC_ringbuf_reserve &&
8972 		    func_id != BPF_FUNC_ringbuf_query &&
8973 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8974 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8975 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8976 			goto error;
8977 		break;
8978 	case BPF_MAP_TYPE_USER_RINGBUF:
8979 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8980 			goto error;
8981 		break;
8982 	case BPF_MAP_TYPE_STACK_TRACE:
8983 		if (func_id != BPF_FUNC_get_stackid)
8984 			goto error;
8985 		break;
8986 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8987 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8988 		    func_id != BPF_FUNC_current_task_under_cgroup)
8989 			goto error;
8990 		break;
8991 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8992 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8993 		if (func_id != BPF_FUNC_get_local_storage)
8994 			goto error;
8995 		break;
8996 	case BPF_MAP_TYPE_DEVMAP:
8997 	case BPF_MAP_TYPE_DEVMAP_HASH:
8998 		if (func_id != BPF_FUNC_redirect_map &&
8999 		    func_id != BPF_FUNC_map_lookup_elem)
9000 			goto error;
9001 		break;
9002 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9003 	 * appear.
9004 	 */
9005 	case BPF_MAP_TYPE_CPUMAP:
9006 		if (func_id != BPF_FUNC_redirect_map)
9007 			goto error;
9008 		break;
9009 	case BPF_MAP_TYPE_XSKMAP:
9010 		if (func_id != BPF_FUNC_redirect_map &&
9011 		    func_id != BPF_FUNC_map_lookup_elem)
9012 			goto error;
9013 		break;
9014 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9015 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9016 		if (func_id != BPF_FUNC_map_lookup_elem)
9017 			goto error;
9018 		break;
9019 	case BPF_MAP_TYPE_SOCKMAP:
9020 		if (func_id != BPF_FUNC_sk_redirect_map &&
9021 		    func_id != BPF_FUNC_sock_map_update &&
9022 		    func_id != BPF_FUNC_msg_redirect_map &&
9023 		    func_id != BPF_FUNC_sk_select_reuseport &&
9024 		    func_id != BPF_FUNC_map_lookup_elem &&
9025 		    !may_update_sockmap(env, func_id))
9026 			goto error;
9027 		break;
9028 	case BPF_MAP_TYPE_SOCKHASH:
9029 		if (func_id != BPF_FUNC_sk_redirect_hash &&
9030 		    func_id != BPF_FUNC_sock_hash_update &&
9031 		    func_id != BPF_FUNC_msg_redirect_hash &&
9032 		    func_id != BPF_FUNC_sk_select_reuseport &&
9033 		    func_id != BPF_FUNC_map_lookup_elem &&
9034 		    !may_update_sockmap(env, func_id))
9035 			goto error;
9036 		break;
9037 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
9038 		if (func_id != BPF_FUNC_sk_select_reuseport)
9039 			goto error;
9040 		break;
9041 	case BPF_MAP_TYPE_QUEUE:
9042 	case BPF_MAP_TYPE_STACK:
9043 		if (func_id != BPF_FUNC_map_peek_elem &&
9044 		    func_id != BPF_FUNC_map_pop_elem &&
9045 		    func_id != BPF_FUNC_map_push_elem)
9046 			goto error;
9047 		break;
9048 	case BPF_MAP_TYPE_SK_STORAGE:
9049 		if (func_id != BPF_FUNC_sk_storage_get &&
9050 		    func_id != BPF_FUNC_sk_storage_delete &&
9051 		    func_id != BPF_FUNC_kptr_xchg)
9052 			goto error;
9053 		break;
9054 	case BPF_MAP_TYPE_INODE_STORAGE:
9055 		if (func_id != BPF_FUNC_inode_storage_get &&
9056 		    func_id != BPF_FUNC_inode_storage_delete &&
9057 		    func_id != BPF_FUNC_kptr_xchg)
9058 			goto error;
9059 		break;
9060 	case BPF_MAP_TYPE_TASK_STORAGE:
9061 		if (func_id != BPF_FUNC_task_storage_get &&
9062 		    func_id != BPF_FUNC_task_storage_delete &&
9063 		    func_id != BPF_FUNC_kptr_xchg)
9064 			goto error;
9065 		break;
9066 	case BPF_MAP_TYPE_CGRP_STORAGE:
9067 		if (func_id != BPF_FUNC_cgrp_storage_get &&
9068 		    func_id != BPF_FUNC_cgrp_storage_delete &&
9069 		    func_id != BPF_FUNC_kptr_xchg)
9070 			goto error;
9071 		break;
9072 	case BPF_MAP_TYPE_BLOOM_FILTER:
9073 		if (func_id != BPF_FUNC_map_peek_elem &&
9074 		    func_id != BPF_FUNC_map_push_elem)
9075 			goto error;
9076 		break;
9077 	default:
9078 		break;
9079 	}
9080 
9081 	/* ... and second from the function itself. */
9082 	switch (func_id) {
9083 	case BPF_FUNC_tail_call:
9084 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9085 			goto error;
9086 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9087 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9088 			return -EINVAL;
9089 		}
9090 		break;
9091 	case BPF_FUNC_perf_event_read:
9092 	case BPF_FUNC_perf_event_output:
9093 	case BPF_FUNC_perf_event_read_value:
9094 	case BPF_FUNC_skb_output:
9095 	case BPF_FUNC_xdp_output:
9096 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9097 			goto error;
9098 		break;
9099 	case BPF_FUNC_ringbuf_output:
9100 	case BPF_FUNC_ringbuf_reserve:
9101 	case BPF_FUNC_ringbuf_query:
9102 	case BPF_FUNC_ringbuf_reserve_dynptr:
9103 	case BPF_FUNC_ringbuf_submit_dynptr:
9104 	case BPF_FUNC_ringbuf_discard_dynptr:
9105 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9106 			goto error;
9107 		break;
9108 	case BPF_FUNC_user_ringbuf_drain:
9109 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9110 			goto error;
9111 		break;
9112 	case BPF_FUNC_get_stackid:
9113 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9114 			goto error;
9115 		break;
9116 	case BPF_FUNC_current_task_under_cgroup:
9117 	case BPF_FUNC_skb_under_cgroup:
9118 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9119 			goto error;
9120 		break;
9121 	case BPF_FUNC_redirect_map:
9122 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9123 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9124 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
9125 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
9126 			goto error;
9127 		break;
9128 	case BPF_FUNC_sk_redirect_map:
9129 	case BPF_FUNC_msg_redirect_map:
9130 	case BPF_FUNC_sock_map_update:
9131 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9132 			goto error;
9133 		break;
9134 	case BPF_FUNC_sk_redirect_hash:
9135 	case BPF_FUNC_msg_redirect_hash:
9136 	case BPF_FUNC_sock_hash_update:
9137 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9138 			goto error;
9139 		break;
9140 	case BPF_FUNC_get_local_storage:
9141 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9142 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9143 			goto error;
9144 		break;
9145 	case BPF_FUNC_sk_select_reuseport:
9146 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9147 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9148 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
9149 			goto error;
9150 		break;
9151 	case BPF_FUNC_map_pop_elem:
9152 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9153 		    map->map_type != BPF_MAP_TYPE_STACK)
9154 			goto error;
9155 		break;
9156 	case BPF_FUNC_map_peek_elem:
9157 	case BPF_FUNC_map_push_elem:
9158 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9159 		    map->map_type != BPF_MAP_TYPE_STACK &&
9160 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9161 			goto error;
9162 		break;
9163 	case BPF_FUNC_map_lookup_percpu_elem:
9164 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9165 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9166 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9167 			goto error;
9168 		break;
9169 	case BPF_FUNC_sk_storage_get:
9170 	case BPF_FUNC_sk_storage_delete:
9171 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9172 			goto error;
9173 		break;
9174 	case BPF_FUNC_inode_storage_get:
9175 	case BPF_FUNC_inode_storage_delete:
9176 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9177 			goto error;
9178 		break;
9179 	case BPF_FUNC_task_storage_get:
9180 	case BPF_FUNC_task_storage_delete:
9181 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9182 			goto error;
9183 		break;
9184 	case BPF_FUNC_cgrp_storage_get:
9185 	case BPF_FUNC_cgrp_storage_delete:
9186 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9187 			goto error;
9188 		break;
9189 	default:
9190 		break;
9191 	}
9192 
9193 	return 0;
9194 error:
9195 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9196 		map->map_type, func_id_name(func_id), func_id);
9197 	return -EINVAL;
9198 }
9199 
check_raw_mode_ok(const struct bpf_func_proto * fn)9200 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9201 {
9202 	int count = 0;
9203 
9204 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9205 		count++;
9206 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9207 		count++;
9208 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9209 		count++;
9210 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9211 		count++;
9212 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9213 		count++;
9214 
9215 	/* We only support one arg being in raw mode at the moment,
9216 	 * which is sufficient for the helper functions we have
9217 	 * right now.
9218 	 */
9219 	return count <= 1;
9220 }
9221 
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)9222 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9223 {
9224 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9225 	bool has_size = fn->arg_size[arg] != 0;
9226 	bool is_next_size = false;
9227 
9228 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9229 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9230 
9231 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9232 		return is_next_size;
9233 
9234 	return has_size == is_next_size || is_next_size == is_fixed;
9235 }
9236 
check_arg_pair_ok(const struct bpf_func_proto * fn)9237 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9238 {
9239 	/* bpf_xxx(..., buf, len) call will access 'len'
9240 	 * bytes from memory 'buf'. Both arg types need
9241 	 * to be paired, so make sure there's no buggy
9242 	 * helper function specification.
9243 	 */
9244 	if (arg_type_is_mem_size(fn->arg1_type) ||
9245 	    check_args_pair_invalid(fn, 0) ||
9246 	    check_args_pair_invalid(fn, 1) ||
9247 	    check_args_pair_invalid(fn, 2) ||
9248 	    check_args_pair_invalid(fn, 3) ||
9249 	    check_args_pair_invalid(fn, 4))
9250 		return false;
9251 
9252 	return true;
9253 }
9254 
check_btf_id_ok(const struct bpf_func_proto * fn)9255 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9256 {
9257 	int i;
9258 
9259 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9260 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9261 			return !!fn->arg_btf_id[i];
9262 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9263 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9264 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9265 		    /* arg_btf_id and arg_size are in a union. */
9266 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9267 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9268 			return false;
9269 	}
9270 
9271 	return true;
9272 }
9273 
check_func_proto(const struct bpf_func_proto * fn,int func_id)9274 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9275 {
9276 	return check_raw_mode_ok(fn) &&
9277 	       check_arg_pair_ok(fn) &&
9278 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9279 }
9280 
9281 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9282  * are now invalid, so turn them into unknown SCALAR_VALUE.
9283  *
9284  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9285  * since these slices point to packet data.
9286  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)9287 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9288 {
9289 	struct bpf_func_state *state;
9290 	struct bpf_reg_state *reg;
9291 
9292 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9293 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9294 			mark_reg_invalid(env, reg);
9295 	}));
9296 }
9297 
9298 enum {
9299 	AT_PKT_END = -1,
9300 	BEYOND_PKT_END = -2,
9301 };
9302 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)9303 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9304 {
9305 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9306 	struct bpf_reg_state *reg = &state->regs[regn];
9307 
9308 	if (reg->type != PTR_TO_PACKET)
9309 		/* PTR_TO_PACKET_META is not supported yet */
9310 		return;
9311 
9312 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9313 	 * How far beyond pkt_end it goes is unknown.
9314 	 * if (!range_open) it's the case of pkt >= pkt_end
9315 	 * if (range_open) it's the case of pkt > pkt_end
9316 	 * hence this pointer is at least 1 byte bigger than pkt_end
9317 	 */
9318 	if (range_open)
9319 		reg->range = BEYOND_PKT_END;
9320 	else
9321 		reg->range = AT_PKT_END;
9322 }
9323 
9324 /* The pointer with the specified id has released its reference to kernel
9325  * resources. Identify all copies of the same pointer and clear the reference.
9326  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)9327 static int release_reference(struct bpf_verifier_env *env,
9328 			     int ref_obj_id)
9329 {
9330 	struct bpf_func_state *state;
9331 	struct bpf_reg_state *reg;
9332 	int err;
9333 
9334 	err = release_reference_state(cur_func(env), ref_obj_id);
9335 	if (err)
9336 		return err;
9337 
9338 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9339 		if (reg->ref_obj_id == ref_obj_id)
9340 			mark_reg_invalid(env, reg);
9341 	}));
9342 
9343 	return 0;
9344 }
9345 
invalidate_non_owning_refs(struct bpf_verifier_env * env)9346 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9347 {
9348 	struct bpf_func_state *unused;
9349 	struct bpf_reg_state *reg;
9350 
9351 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9352 		if (type_is_non_owning_ref(reg->type))
9353 			mark_reg_invalid(env, reg);
9354 	}));
9355 }
9356 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9357 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9358 				    struct bpf_reg_state *regs)
9359 {
9360 	int i;
9361 
9362 	/* after the call registers r0 - r5 were scratched */
9363 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9364 		mark_reg_not_init(env, regs, caller_saved[i]);
9365 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9366 	}
9367 }
9368 
9369 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9370 				   struct bpf_func_state *caller,
9371 				   struct bpf_func_state *callee,
9372 				   int insn_idx);
9373 
9374 static int set_callee_state(struct bpf_verifier_env *env,
9375 			    struct bpf_func_state *caller,
9376 			    struct bpf_func_state *callee, int insn_idx);
9377 
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)9378 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9379 			    set_callee_state_fn set_callee_state_cb,
9380 			    struct bpf_verifier_state *state)
9381 {
9382 	struct bpf_func_state *caller, *callee;
9383 	int err;
9384 
9385 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9386 		verbose(env, "the call stack of %d frames is too deep\n",
9387 			state->curframe + 2);
9388 		return -E2BIG;
9389 	}
9390 
9391 	if (state->frame[state->curframe + 1]) {
9392 		verbose(env, "verifier bug. Frame %d already allocated\n",
9393 			state->curframe + 1);
9394 		return -EFAULT;
9395 	}
9396 
9397 	caller = state->frame[state->curframe];
9398 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9399 	if (!callee)
9400 		return -ENOMEM;
9401 	state->frame[state->curframe + 1] = callee;
9402 
9403 	/* callee cannot access r0, r6 - r9 for reading and has to write
9404 	 * into its own stack before reading from it.
9405 	 * callee can read/write into caller's stack
9406 	 */
9407 	init_func_state(env, callee,
9408 			/* remember the callsite, it will be used by bpf_exit */
9409 			callsite,
9410 			state->curframe + 1 /* frameno within this callchain */,
9411 			subprog /* subprog number within this prog */);
9412 	/* Transfer references to the callee */
9413 	err = copy_reference_state(callee, caller);
9414 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9415 	if (err)
9416 		goto err_out;
9417 
9418 	/* only increment it after check_reg_arg() finished */
9419 	state->curframe++;
9420 
9421 	return 0;
9422 
9423 err_out:
9424 	free_func_state(callee);
9425 	state->frame[state->curframe + 1] = NULL;
9426 	return err;
9427 }
9428 
btf_check_func_arg_match(struct bpf_verifier_env * env,int subprog,const struct btf * btf,struct bpf_reg_state * regs)9429 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
9430 				    const struct btf *btf,
9431 				    struct bpf_reg_state *regs)
9432 {
9433 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
9434 	struct bpf_verifier_log *log = &env->log;
9435 	u32 i;
9436 	int ret;
9437 
9438 	ret = btf_prepare_func_args(env, subprog);
9439 	if (ret)
9440 		return ret;
9441 
9442 	/* check that BTF function arguments match actual types that the
9443 	 * verifier sees.
9444 	 */
9445 	for (i = 0; i < sub->arg_cnt; i++) {
9446 		u32 regno = i + 1;
9447 		struct bpf_reg_state *reg = &regs[regno];
9448 		struct bpf_subprog_arg_info *arg = &sub->args[i];
9449 
9450 		if (arg->arg_type == ARG_ANYTHING) {
9451 			if (reg->type != SCALAR_VALUE) {
9452 				bpf_log(log, "R%d is not a scalar\n", regno);
9453 				return -EINVAL;
9454 			}
9455 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
9456 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9457 			if (ret < 0)
9458 				return ret;
9459 			/* If function expects ctx type in BTF check that caller
9460 			 * is passing PTR_TO_CTX.
9461 			 */
9462 			if (reg->type != PTR_TO_CTX) {
9463 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
9464 				return -EINVAL;
9465 			}
9466 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
9467 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
9468 			if (ret < 0)
9469 				return ret;
9470 			if (check_mem_reg(env, reg, regno, arg->mem_size))
9471 				return -EINVAL;
9472 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
9473 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
9474 				return -EINVAL;
9475 			}
9476 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
9477 			/*
9478 			 * Can pass any value and the kernel won't crash, but
9479 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
9480 			 * else is a bug in the bpf program. Point it out to
9481 			 * the user at the verification time instead of
9482 			 * run-time debug nightmare.
9483 			 */
9484 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
9485 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
9486 				return -EINVAL;
9487 			}
9488 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
9489 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
9490 			if (ret)
9491 				return ret;
9492 
9493 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
9494 			if (ret)
9495 				return ret;
9496 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
9497 			struct bpf_call_arg_meta meta;
9498 			int err;
9499 
9500 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
9501 				continue;
9502 
9503 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
9504 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
9505 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
9506 			if (err)
9507 				return err;
9508 		} else {
9509 			bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n",
9510 				i, arg->arg_type);
9511 			return -EFAULT;
9512 		}
9513 	}
9514 
9515 	return 0;
9516 }
9517 
9518 /* Compare BTF of a function call with given bpf_reg_state.
9519  * Returns:
9520  * EFAULT - there is a verifier bug. Abort verification.
9521  * EINVAL - there is a type mismatch or BTF is not available.
9522  * 0 - BTF matches with what bpf_reg_state expects.
9523  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
9524  */
btf_check_subprog_call(struct bpf_verifier_env * env,int subprog,struct bpf_reg_state * regs)9525 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
9526 				  struct bpf_reg_state *regs)
9527 {
9528 	struct bpf_prog *prog = env->prog;
9529 	struct btf *btf = prog->aux->btf;
9530 	u32 btf_id;
9531 	int err;
9532 
9533 	if (!prog->aux->func_info)
9534 		return -EINVAL;
9535 
9536 	btf_id = prog->aux->func_info[subprog].type_id;
9537 	if (!btf_id)
9538 		return -EFAULT;
9539 
9540 	if (prog->aux->func_info_aux[subprog].unreliable)
9541 		return -EINVAL;
9542 
9543 	err = btf_check_func_arg_match(env, subprog, btf, regs);
9544 	/* Compiler optimizations can remove arguments from static functions
9545 	 * or mismatched type can be passed into a global function.
9546 	 * In such cases mark the function as unreliable from BTF point of view.
9547 	 */
9548 	if (err)
9549 		prog->aux->func_info_aux[subprog].unreliable = true;
9550 	return err;
9551 }
9552 
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)9553 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9554 			      int insn_idx, int subprog,
9555 			      set_callee_state_fn set_callee_state_cb)
9556 {
9557 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9558 	struct bpf_func_state *caller, *callee;
9559 	int err;
9560 
9561 	caller = state->frame[state->curframe];
9562 	err = btf_check_subprog_call(env, subprog, caller->regs);
9563 	if (err == -EFAULT)
9564 		return err;
9565 
9566 	/* set_callee_state is used for direct subprog calls, but we are
9567 	 * interested in validating only BPF helpers that can call subprogs as
9568 	 * callbacks
9569 	 */
9570 	env->subprog_info[subprog].is_cb = true;
9571 	if (bpf_pseudo_kfunc_call(insn) &&
9572 	    !is_callback_calling_kfunc(insn->imm)) {
9573 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9574 			func_id_name(insn->imm), insn->imm);
9575 		return -EFAULT;
9576 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9577 		   !is_callback_calling_function(insn->imm)) { /* helper */
9578 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9579 			func_id_name(insn->imm), insn->imm);
9580 		return -EFAULT;
9581 	}
9582 
9583 	if (is_async_callback_calling_insn(insn)) {
9584 		struct bpf_verifier_state *async_cb;
9585 
9586 		/* there is no real recursion here. timer and workqueue callbacks are async */
9587 		env->subprog_info[subprog].is_async_cb = true;
9588 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9589 					 insn_idx, subprog,
9590 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
9591 		if (!async_cb)
9592 			return -EFAULT;
9593 		callee = async_cb->frame[0];
9594 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9595 
9596 		/* Convert bpf_timer_set_callback() args into timer callback args */
9597 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9598 		if (err)
9599 			return err;
9600 
9601 		return 0;
9602 	}
9603 
9604 	/* for callback functions enqueue entry to callback and
9605 	 * proceed with next instruction within current frame.
9606 	 */
9607 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9608 	if (!callback_state)
9609 		return -ENOMEM;
9610 
9611 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9612 			       callback_state);
9613 	if (err)
9614 		return err;
9615 
9616 	callback_state->callback_unroll_depth++;
9617 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9618 	caller->callback_depth = 0;
9619 	return 0;
9620 }
9621 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)9622 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9623 			   int *insn_idx)
9624 {
9625 	struct bpf_verifier_state *state = env->cur_state;
9626 	struct bpf_func_state *caller;
9627 	int err, subprog, target_insn;
9628 
9629 	target_insn = *insn_idx + insn->imm + 1;
9630 	subprog = find_subprog(env, target_insn);
9631 	if (subprog < 0) {
9632 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9633 		return -EFAULT;
9634 	}
9635 
9636 	caller = state->frame[state->curframe];
9637 	err = btf_check_subprog_call(env, subprog, caller->regs);
9638 	if (err == -EFAULT)
9639 		return err;
9640 	if (subprog_is_global(env, subprog)) {
9641 		const char *sub_name = subprog_name(env, subprog);
9642 
9643 		/* Only global subprogs cannot be called with a lock held. */
9644 		if (env->cur_state->active_lock.ptr) {
9645 			verbose(env, "global function calls are not allowed while holding a lock,\n"
9646 				     "use static function instead\n");
9647 			return -EINVAL;
9648 		}
9649 
9650 		/* Only global subprogs cannot be called with preemption disabled. */
9651 		if (env->cur_state->active_preempt_lock) {
9652 			verbose(env, "global function calls are not allowed with preemption disabled,\n"
9653 				     "use static function instead\n");
9654 			return -EINVAL;
9655 		}
9656 
9657 		if (err) {
9658 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
9659 				subprog, sub_name);
9660 			return err;
9661 		}
9662 
9663 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
9664 			subprog, sub_name);
9665 		/* mark global subprog for verifying after main prog */
9666 		subprog_aux(env, subprog)->called = true;
9667 		clear_caller_saved_regs(env, caller->regs);
9668 
9669 		/* All global functions return a 64-bit SCALAR_VALUE */
9670 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9671 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9672 
9673 		/* continue with next insn after call */
9674 		return 0;
9675 	}
9676 
9677 	/* for regular function entry setup new frame and continue
9678 	 * from that frame.
9679 	 */
9680 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9681 	if (err)
9682 		return err;
9683 
9684 	clear_caller_saved_regs(env, caller->regs);
9685 
9686 	/* and go analyze first insn of the callee */
9687 	*insn_idx = env->subprog_info[subprog].start - 1;
9688 
9689 	if (env->log.level & BPF_LOG_LEVEL) {
9690 		verbose(env, "caller:\n");
9691 		print_verifier_state(env, caller, true);
9692 		verbose(env, "callee:\n");
9693 		print_verifier_state(env, state->frame[state->curframe], true);
9694 	}
9695 
9696 	return 0;
9697 }
9698 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)9699 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9700 				   struct bpf_func_state *caller,
9701 				   struct bpf_func_state *callee)
9702 {
9703 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9704 	 *      void *callback_ctx, u64 flags);
9705 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9706 	 *      void *callback_ctx);
9707 	 */
9708 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9709 
9710 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9711 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9712 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9713 
9714 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9715 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9716 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9717 
9718 	/* pointer to stack or null */
9719 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9720 
9721 	/* unused */
9722 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9723 	return 0;
9724 }
9725 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9726 static int set_callee_state(struct bpf_verifier_env *env,
9727 			    struct bpf_func_state *caller,
9728 			    struct bpf_func_state *callee, int insn_idx)
9729 {
9730 	int i;
9731 
9732 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9733 	 * pointers, which connects us up to the liveness chain
9734 	 */
9735 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9736 		callee->regs[i] = caller->regs[i];
9737 	return 0;
9738 }
9739 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9740 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9741 				       struct bpf_func_state *caller,
9742 				       struct bpf_func_state *callee,
9743 				       int insn_idx)
9744 {
9745 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9746 	struct bpf_map *map;
9747 	int err;
9748 
9749 	/* valid map_ptr and poison value does not matter */
9750 	map = insn_aux->map_ptr_state.map_ptr;
9751 	if (!map->ops->map_set_for_each_callback_args ||
9752 	    !map->ops->map_for_each_callback) {
9753 		verbose(env, "callback function not allowed for map\n");
9754 		return -ENOTSUPP;
9755 	}
9756 
9757 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9758 	if (err)
9759 		return err;
9760 
9761 	callee->in_callback_fn = true;
9762 	callee->callback_ret_range = retval_range(0, 1);
9763 	return 0;
9764 }
9765 
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9766 static int set_loop_callback_state(struct bpf_verifier_env *env,
9767 				   struct bpf_func_state *caller,
9768 				   struct bpf_func_state *callee,
9769 				   int insn_idx)
9770 {
9771 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9772 	 *	    u64 flags);
9773 	 * callback_fn(u32 index, void *callback_ctx);
9774 	 */
9775 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9776 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9777 
9778 	/* unused */
9779 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9780 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9781 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9782 
9783 	callee->in_callback_fn = true;
9784 	callee->callback_ret_range = retval_range(0, 1);
9785 	return 0;
9786 }
9787 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9788 static int set_timer_callback_state(struct bpf_verifier_env *env,
9789 				    struct bpf_func_state *caller,
9790 				    struct bpf_func_state *callee,
9791 				    int insn_idx)
9792 {
9793 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9794 
9795 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9796 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9797 	 */
9798 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9799 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9800 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9801 
9802 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9803 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9804 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9805 
9806 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9807 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9808 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9809 
9810 	/* unused */
9811 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9812 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9813 	callee->in_async_callback_fn = true;
9814 	callee->callback_ret_range = retval_range(0, 1);
9815 	return 0;
9816 }
9817 
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9818 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9819 				       struct bpf_func_state *caller,
9820 				       struct bpf_func_state *callee,
9821 				       int insn_idx)
9822 {
9823 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9824 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9825 	 * (callback_fn)(struct task_struct *task,
9826 	 *               struct vm_area_struct *vma, void *callback_ctx);
9827 	 */
9828 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9829 
9830 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9831 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9832 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9833 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
9834 
9835 	/* pointer to stack or null */
9836 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9837 
9838 	/* unused */
9839 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9840 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9841 	callee->in_callback_fn = true;
9842 	callee->callback_ret_range = retval_range(0, 1);
9843 	return 0;
9844 }
9845 
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9846 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9847 					   struct bpf_func_state *caller,
9848 					   struct bpf_func_state *callee,
9849 					   int insn_idx)
9850 {
9851 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9852 	 *			  callback_ctx, u64 flags);
9853 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9854 	 */
9855 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9856 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9857 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9858 
9859 	/* unused */
9860 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9861 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9862 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9863 
9864 	callee->in_callback_fn = true;
9865 	callee->callback_ret_range = retval_range(0, 1);
9866 	return 0;
9867 }
9868 
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9869 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9870 					 struct bpf_func_state *caller,
9871 					 struct bpf_func_state *callee,
9872 					 int insn_idx)
9873 {
9874 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9875 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9876 	 *
9877 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9878 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9879 	 * by this point, so look at 'root'
9880 	 */
9881 	struct btf_field *field;
9882 
9883 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9884 				      BPF_RB_ROOT);
9885 	if (!field || !field->graph_root.value_btf_id)
9886 		return -EFAULT;
9887 
9888 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9889 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9890 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9891 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9892 
9893 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9894 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9895 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9896 	callee->in_callback_fn = true;
9897 	callee->callback_ret_range = retval_range(0, 1);
9898 	return 0;
9899 }
9900 
9901 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9902 
9903 /* Are we currently verifying the callback for a rbtree helper that must
9904  * be called with lock held? If so, no need to complain about unreleased
9905  * lock
9906  */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)9907 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9908 {
9909 	struct bpf_verifier_state *state = env->cur_state;
9910 	struct bpf_insn *insn = env->prog->insnsi;
9911 	struct bpf_func_state *callee;
9912 	int kfunc_btf_id;
9913 
9914 	if (!state->curframe)
9915 		return false;
9916 
9917 	callee = state->frame[state->curframe];
9918 
9919 	if (!callee->in_callback_fn)
9920 		return false;
9921 
9922 	kfunc_btf_id = insn[callee->callsite].imm;
9923 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9924 }
9925 
retval_range_within(struct bpf_retval_range range,const struct bpf_reg_state * reg)9926 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg)
9927 {
9928 	return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
9929 }
9930 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)9931 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9932 {
9933 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9934 	struct bpf_func_state *caller, *callee;
9935 	struct bpf_reg_state *r0;
9936 	bool in_callback_fn;
9937 	int err;
9938 
9939 	callee = state->frame[state->curframe];
9940 	r0 = &callee->regs[BPF_REG_0];
9941 	if (r0->type == PTR_TO_STACK) {
9942 		/* technically it's ok to return caller's stack pointer
9943 		 * (or caller's caller's pointer) back to the caller,
9944 		 * since these pointers are valid. Only current stack
9945 		 * pointer will be invalid as soon as function exits,
9946 		 * but let's be conservative
9947 		 */
9948 		verbose(env, "cannot return stack pointer to the caller\n");
9949 		return -EINVAL;
9950 	}
9951 
9952 	caller = state->frame[state->curframe - 1];
9953 	if (callee->in_callback_fn) {
9954 		if (r0->type != SCALAR_VALUE) {
9955 			verbose(env, "R0 not a scalar value\n");
9956 			return -EACCES;
9957 		}
9958 
9959 		/* we are going to rely on register's precise value */
9960 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9961 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9962 		if (err)
9963 			return err;
9964 
9965 		/* enforce R0 return value range */
9966 		if (!retval_range_within(callee->callback_ret_range, r0)) {
9967 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
9968 					       "At callback return", "R0");
9969 			return -EINVAL;
9970 		}
9971 		if (!calls_callback(env, callee->callsite)) {
9972 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9973 				*insn_idx, callee->callsite);
9974 			return -EFAULT;
9975 		}
9976 	} else {
9977 		/* return to the caller whatever r0 had in the callee */
9978 		caller->regs[BPF_REG_0] = *r0;
9979 	}
9980 
9981 	/* callback_fn frame should have released its own additions to parent's
9982 	 * reference state at this point, or check_reference_leak would
9983 	 * complain, hence it must be the same as the caller. There is no need
9984 	 * to copy it back.
9985 	 */
9986 	if (!callee->in_callback_fn) {
9987 		/* Transfer references to the caller */
9988 		err = copy_reference_state(caller, callee);
9989 		if (err)
9990 			return err;
9991 	}
9992 
9993 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9994 	 * there function call logic would reschedule callback visit. If iteration
9995 	 * converges is_state_visited() would prune that visit eventually.
9996 	 */
9997 	in_callback_fn = callee->in_callback_fn;
9998 	if (in_callback_fn)
9999 		*insn_idx = callee->callsite;
10000 	else
10001 		*insn_idx = callee->callsite + 1;
10002 
10003 	if (env->log.level & BPF_LOG_LEVEL) {
10004 		verbose(env, "returning from callee:\n");
10005 		print_verifier_state(env, callee, true);
10006 		verbose(env, "to caller at %d:\n", *insn_idx);
10007 		print_verifier_state(env, caller, true);
10008 	}
10009 	/* clear everything in the callee. In case of exceptional exits using
10010 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
10011 	free_func_state(callee);
10012 	state->frame[state->curframe--] = NULL;
10013 
10014 	/* for callbacks widen imprecise scalars to make programs like below verify:
10015 	 *
10016 	 *   struct ctx { int i; }
10017 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
10018 	 *   ...
10019 	 *   struct ctx = { .i = 0; }
10020 	 *   bpf_loop(100, cb, &ctx, 0);
10021 	 *
10022 	 * This is similar to what is done in process_iter_next_call() for open
10023 	 * coded iterators.
10024 	 */
10025 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
10026 	if (prev_st) {
10027 		err = widen_imprecise_scalars(env, prev_st, state);
10028 		if (err)
10029 			return err;
10030 	}
10031 	return 0;
10032 }
10033 
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)10034 static int do_refine_retval_range(struct bpf_verifier_env *env,
10035 				  struct bpf_reg_state *regs, int ret_type,
10036 				  int func_id,
10037 				  struct bpf_call_arg_meta *meta)
10038 {
10039 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
10040 
10041 	if (ret_type != RET_INTEGER)
10042 		return 0;
10043 
10044 	switch (func_id) {
10045 	case BPF_FUNC_get_stack:
10046 	case BPF_FUNC_get_task_stack:
10047 	case BPF_FUNC_probe_read_str:
10048 	case BPF_FUNC_probe_read_kernel_str:
10049 	case BPF_FUNC_probe_read_user_str:
10050 		ret_reg->smax_value = meta->msize_max_value;
10051 		ret_reg->s32_max_value = meta->msize_max_value;
10052 		ret_reg->smin_value = -MAX_ERRNO;
10053 		ret_reg->s32_min_value = -MAX_ERRNO;
10054 		reg_bounds_sync(ret_reg);
10055 		break;
10056 	case BPF_FUNC_get_smp_processor_id:
10057 		ret_reg->umax_value = nr_cpu_ids - 1;
10058 		ret_reg->u32_max_value = nr_cpu_ids - 1;
10059 		ret_reg->smax_value = nr_cpu_ids - 1;
10060 		ret_reg->s32_max_value = nr_cpu_ids - 1;
10061 		ret_reg->umin_value = 0;
10062 		ret_reg->u32_min_value = 0;
10063 		ret_reg->smin_value = 0;
10064 		ret_reg->s32_min_value = 0;
10065 		reg_bounds_sync(ret_reg);
10066 		break;
10067 	}
10068 
10069 	return reg_bounds_sanity_check(env, ret_reg, "retval");
10070 }
10071 
10072 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)10073 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10074 		int func_id, int insn_idx)
10075 {
10076 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10077 	struct bpf_map *map = meta->map_ptr;
10078 
10079 	if (func_id != BPF_FUNC_tail_call &&
10080 	    func_id != BPF_FUNC_map_lookup_elem &&
10081 	    func_id != BPF_FUNC_map_update_elem &&
10082 	    func_id != BPF_FUNC_map_delete_elem &&
10083 	    func_id != BPF_FUNC_map_push_elem &&
10084 	    func_id != BPF_FUNC_map_pop_elem &&
10085 	    func_id != BPF_FUNC_map_peek_elem &&
10086 	    func_id != BPF_FUNC_for_each_map_elem &&
10087 	    func_id != BPF_FUNC_redirect_map &&
10088 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
10089 		return 0;
10090 
10091 	if (map == NULL) {
10092 		verbose(env, "kernel subsystem misconfigured verifier\n");
10093 		return -EINVAL;
10094 	}
10095 
10096 	/* In case of read-only, some additional restrictions
10097 	 * need to be applied in order to prevent altering the
10098 	 * state of the map from program side.
10099 	 */
10100 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
10101 	    (func_id == BPF_FUNC_map_delete_elem ||
10102 	     func_id == BPF_FUNC_map_update_elem ||
10103 	     func_id == BPF_FUNC_map_push_elem ||
10104 	     func_id == BPF_FUNC_map_pop_elem)) {
10105 		verbose(env, "write into map forbidden\n");
10106 		return -EACCES;
10107 	}
10108 
10109 	if (!aux->map_ptr_state.map_ptr)
10110 		bpf_map_ptr_store(aux, meta->map_ptr,
10111 				  !meta->map_ptr->bypass_spec_v1, false);
10112 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
10113 		bpf_map_ptr_store(aux, meta->map_ptr,
10114 				  !meta->map_ptr->bypass_spec_v1, true);
10115 	return 0;
10116 }
10117 
10118 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)10119 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
10120 		int func_id, int insn_idx)
10121 {
10122 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
10123 	struct bpf_reg_state *regs = cur_regs(env), *reg;
10124 	struct bpf_map *map = meta->map_ptr;
10125 	u64 val, max;
10126 	int err;
10127 
10128 	if (func_id != BPF_FUNC_tail_call)
10129 		return 0;
10130 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
10131 		verbose(env, "kernel subsystem misconfigured verifier\n");
10132 		return -EINVAL;
10133 	}
10134 
10135 	reg = &regs[BPF_REG_3];
10136 	val = reg->var_off.value;
10137 	max = map->max_entries;
10138 
10139 	if (!(is_reg_const(reg, false) && val < max)) {
10140 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10141 		return 0;
10142 	}
10143 
10144 	err = mark_chain_precision(env, BPF_REG_3);
10145 	if (err)
10146 		return err;
10147 	if (bpf_map_key_unseen(aux))
10148 		bpf_map_key_store(aux, val);
10149 	else if (!bpf_map_key_poisoned(aux) &&
10150 		  bpf_map_key_immediate(aux) != val)
10151 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
10152 	return 0;
10153 }
10154 
check_reference_leak(struct bpf_verifier_env * env,bool exception_exit)10155 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
10156 {
10157 	struct bpf_func_state *state = cur_func(env);
10158 	bool refs_lingering = false;
10159 	int i;
10160 
10161 	if (!exception_exit && state->frameno && !state->in_callback_fn)
10162 		return 0;
10163 
10164 	for (i = 0; i < state->acquired_refs; i++) {
10165 		if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
10166 			continue;
10167 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
10168 			state->refs[i].id, state->refs[i].insn_idx);
10169 		refs_lingering = true;
10170 	}
10171 	return refs_lingering ? -EINVAL : 0;
10172 }
10173 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)10174 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
10175 				   struct bpf_reg_state *regs)
10176 {
10177 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
10178 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
10179 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
10180 	struct bpf_bprintf_data data = {};
10181 	int err, fmt_map_off, num_args;
10182 	u64 fmt_addr;
10183 	char *fmt;
10184 
10185 	/* data must be an array of u64 */
10186 	if (data_len_reg->var_off.value % 8)
10187 		return -EINVAL;
10188 	num_args = data_len_reg->var_off.value / 8;
10189 
10190 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
10191 	 * and map_direct_value_addr is set.
10192 	 */
10193 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
10194 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
10195 						  fmt_map_off);
10196 	if (err) {
10197 		verbose(env, "verifier bug\n");
10198 		return -EFAULT;
10199 	}
10200 	fmt = (char *)(long)fmt_addr + fmt_map_off;
10201 
10202 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
10203 	 * can focus on validating the format specifiers.
10204 	 */
10205 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
10206 	if (err < 0)
10207 		verbose(env, "Invalid format string\n");
10208 
10209 	return err;
10210 }
10211 
check_get_func_ip(struct bpf_verifier_env * env)10212 static int check_get_func_ip(struct bpf_verifier_env *env)
10213 {
10214 	enum bpf_prog_type type = resolve_prog_type(env->prog);
10215 	int func_id = BPF_FUNC_get_func_ip;
10216 
10217 	if (type == BPF_PROG_TYPE_TRACING) {
10218 		if (!bpf_prog_has_trampoline(env->prog)) {
10219 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
10220 				func_id_name(func_id), func_id);
10221 			return -ENOTSUPP;
10222 		}
10223 		return 0;
10224 	} else if (type == BPF_PROG_TYPE_KPROBE) {
10225 		return 0;
10226 	}
10227 
10228 	verbose(env, "func %s#%d not supported for program type %d\n",
10229 		func_id_name(func_id), func_id, type);
10230 	return -ENOTSUPP;
10231 }
10232 
cur_aux(struct bpf_verifier_env * env)10233 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
10234 {
10235 	return &env->insn_aux_data[env->insn_idx];
10236 }
10237 
loop_flag_is_zero(struct bpf_verifier_env * env)10238 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
10239 {
10240 	struct bpf_reg_state *regs = cur_regs(env);
10241 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
10242 	bool reg_is_null = register_is_null(reg);
10243 
10244 	if (reg_is_null)
10245 		mark_chain_precision(env, BPF_REG_4);
10246 
10247 	return reg_is_null;
10248 }
10249 
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)10250 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10251 {
10252 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10253 
10254 	if (!state->initialized) {
10255 		state->initialized = 1;
10256 		state->fit_for_inline = loop_flag_is_zero(env);
10257 		state->callback_subprogno = subprogno;
10258 		return;
10259 	}
10260 
10261 	if (!state->fit_for_inline)
10262 		return;
10263 
10264 	state->fit_for_inline = (loop_flag_is_zero(env) &&
10265 				 state->callback_subprogno == subprogno);
10266 }
10267 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)10268 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10269 			     int *insn_idx_p)
10270 {
10271 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10272 	bool returns_cpu_specific_alloc_ptr = false;
10273 	const struct bpf_func_proto *fn = NULL;
10274 	enum bpf_return_type ret_type;
10275 	enum bpf_type_flag ret_flag;
10276 	struct bpf_reg_state *regs;
10277 	struct bpf_call_arg_meta meta;
10278 	int insn_idx = *insn_idx_p;
10279 	bool changes_data;
10280 	int i, err, func_id;
10281 
10282 	/* find function prototype */
10283 	func_id = insn->imm;
10284 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10285 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10286 			func_id);
10287 		return -EINVAL;
10288 	}
10289 
10290 	if (env->ops->get_func_proto)
10291 		fn = env->ops->get_func_proto(func_id, env->prog);
10292 	if (!fn) {
10293 		verbose(env, "program of this type cannot use helper %s#%d\n",
10294 			func_id_name(func_id), func_id);
10295 		return -EINVAL;
10296 	}
10297 
10298 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
10299 	if (!env->prog->gpl_compatible && fn->gpl_only) {
10300 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10301 		return -EINVAL;
10302 	}
10303 
10304 	if (fn->allowed && !fn->allowed(env->prog)) {
10305 		verbose(env, "helper call is not allowed in probe\n");
10306 		return -EINVAL;
10307 	}
10308 
10309 	if (!in_sleepable(env) && fn->might_sleep) {
10310 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10311 		return -EINVAL;
10312 	}
10313 
10314 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10315 	changes_data = bpf_helper_changes_pkt_data(fn->func);
10316 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10317 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10318 			func_id_name(func_id), func_id);
10319 		return -EINVAL;
10320 	}
10321 
10322 	memset(&meta, 0, sizeof(meta));
10323 	meta.pkt_access = fn->pkt_access;
10324 
10325 	err = check_func_proto(fn, func_id);
10326 	if (err) {
10327 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10328 			func_id_name(func_id), func_id);
10329 		return err;
10330 	}
10331 
10332 	if (env->cur_state->active_rcu_lock) {
10333 		if (fn->might_sleep) {
10334 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10335 				func_id_name(func_id), func_id);
10336 			return -EINVAL;
10337 		}
10338 
10339 		if (in_sleepable(env) && is_storage_get_function(func_id))
10340 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10341 	}
10342 
10343 	if (env->cur_state->active_preempt_lock) {
10344 		if (fn->might_sleep) {
10345 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
10346 				func_id_name(func_id), func_id);
10347 			return -EINVAL;
10348 		}
10349 
10350 		if (in_sleepable(env) && is_storage_get_function(func_id))
10351 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10352 	}
10353 
10354 	meta.func_id = func_id;
10355 	/* check args */
10356 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10357 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10358 		if (err)
10359 			return err;
10360 	}
10361 
10362 	err = record_func_map(env, &meta, func_id, insn_idx);
10363 	if (err)
10364 		return err;
10365 
10366 	err = record_func_key(env, &meta, func_id, insn_idx);
10367 	if (err)
10368 		return err;
10369 
10370 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10371 	 * is inferred from register state.
10372 	 */
10373 	for (i = 0; i < meta.access_size; i++) {
10374 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10375 				       BPF_WRITE, -1, false, false);
10376 		if (err)
10377 			return err;
10378 	}
10379 
10380 	regs = cur_regs(env);
10381 
10382 	if (meta.release_regno) {
10383 		err = -EINVAL;
10384 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10385 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10386 		 * is safe to do directly.
10387 		 */
10388 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10389 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10390 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10391 				return -EFAULT;
10392 			}
10393 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10394 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10395 			u32 ref_obj_id = meta.ref_obj_id;
10396 			bool in_rcu = in_rcu_cs(env);
10397 			struct bpf_func_state *state;
10398 			struct bpf_reg_state *reg;
10399 
10400 			err = release_reference_state(cur_func(env), ref_obj_id);
10401 			if (!err) {
10402 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10403 					if (reg->ref_obj_id == ref_obj_id) {
10404 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10405 							reg->ref_obj_id = 0;
10406 							reg->type &= ~MEM_ALLOC;
10407 							reg->type |= MEM_RCU;
10408 						} else {
10409 							mark_reg_invalid(env, reg);
10410 						}
10411 					}
10412 				}));
10413 			}
10414 		} else if (meta.ref_obj_id) {
10415 			err = release_reference(env, meta.ref_obj_id);
10416 		} else if (register_is_null(&regs[meta.release_regno])) {
10417 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10418 			 * released is NULL, which must be > R0.
10419 			 */
10420 			err = 0;
10421 		}
10422 		if (err) {
10423 			verbose(env, "func %s#%d reference has not been acquired before\n",
10424 				func_id_name(func_id), func_id);
10425 			return err;
10426 		}
10427 	}
10428 
10429 	switch (func_id) {
10430 	case BPF_FUNC_tail_call:
10431 		err = check_reference_leak(env, false);
10432 		if (err) {
10433 			verbose(env, "tail_call would lead to reference leak\n");
10434 			return err;
10435 		}
10436 		break;
10437 	case BPF_FUNC_get_local_storage:
10438 		/* check that flags argument in get_local_storage(map, flags) is 0,
10439 		 * this is required because get_local_storage() can't return an error.
10440 		 */
10441 		if (!register_is_null(&regs[BPF_REG_2])) {
10442 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10443 			return -EINVAL;
10444 		}
10445 		break;
10446 	case BPF_FUNC_for_each_map_elem:
10447 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10448 					 set_map_elem_callback_state);
10449 		break;
10450 	case BPF_FUNC_timer_set_callback:
10451 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10452 					 set_timer_callback_state);
10453 		break;
10454 	case BPF_FUNC_find_vma:
10455 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10456 					 set_find_vma_callback_state);
10457 		break;
10458 	case BPF_FUNC_snprintf:
10459 		err = check_bpf_snprintf_call(env, regs);
10460 		break;
10461 	case BPF_FUNC_loop:
10462 		update_loop_inline_state(env, meta.subprogno);
10463 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10464 		 * is finished, thus mark it precise.
10465 		 */
10466 		err = mark_chain_precision(env, BPF_REG_1);
10467 		if (err)
10468 			return err;
10469 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10470 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10471 						 set_loop_callback_state);
10472 		} else {
10473 			cur_func(env)->callback_depth = 0;
10474 			if (env->log.level & BPF_LOG_LEVEL2)
10475 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10476 					env->cur_state->curframe);
10477 		}
10478 		break;
10479 	case BPF_FUNC_dynptr_from_mem:
10480 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10481 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10482 				reg_type_str(env, regs[BPF_REG_1].type));
10483 			return -EACCES;
10484 		}
10485 		break;
10486 	case BPF_FUNC_set_retval:
10487 		if (prog_type == BPF_PROG_TYPE_LSM &&
10488 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10489 			if (!env->prog->aux->attach_func_proto->type) {
10490 				/* Make sure programs that attach to void
10491 				 * hooks don't try to modify return value.
10492 				 */
10493 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10494 				return -EINVAL;
10495 			}
10496 		}
10497 		break;
10498 	case BPF_FUNC_dynptr_data:
10499 	{
10500 		struct bpf_reg_state *reg;
10501 		int id, ref_obj_id;
10502 
10503 		reg = get_dynptr_arg_reg(env, fn, regs);
10504 		if (!reg)
10505 			return -EFAULT;
10506 
10507 
10508 		if (meta.dynptr_id) {
10509 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10510 			return -EFAULT;
10511 		}
10512 		if (meta.ref_obj_id) {
10513 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10514 			return -EFAULT;
10515 		}
10516 
10517 		id = dynptr_id(env, reg);
10518 		if (id < 0) {
10519 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10520 			return id;
10521 		}
10522 
10523 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10524 		if (ref_obj_id < 0) {
10525 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10526 			return ref_obj_id;
10527 		}
10528 
10529 		meta.dynptr_id = id;
10530 		meta.ref_obj_id = ref_obj_id;
10531 
10532 		break;
10533 	}
10534 	case BPF_FUNC_dynptr_write:
10535 	{
10536 		enum bpf_dynptr_type dynptr_type;
10537 		struct bpf_reg_state *reg;
10538 
10539 		reg = get_dynptr_arg_reg(env, fn, regs);
10540 		if (!reg)
10541 			return -EFAULT;
10542 
10543 		dynptr_type = dynptr_get_type(env, reg);
10544 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10545 			return -EFAULT;
10546 
10547 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10548 			/* this will trigger clear_all_pkt_pointers(), which will
10549 			 * invalidate all dynptr slices associated with the skb
10550 			 */
10551 			changes_data = true;
10552 
10553 		break;
10554 	}
10555 	case BPF_FUNC_per_cpu_ptr:
10556 	case BPF_FUNC_this_cpu_ptr:
10557 	{
10558 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
10559 		const struct btf_type *type;
10560 
10561 		if (reg->type & MEM_RCU) {
10562 			type = btf_type_by_id(reg->btf, reg->btf_id);
10563 			if (!type || !btf_type_is_struct(type)) {
10564 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
10565 				return -EFAULT;
10566 			}
10567 			returns_cpu_specific_alloc_ptr = true;
10568 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10569 		}
10570 		break;
10571 	}
10572 	case BPF_FUNC_user_ringbuf_drain:
10573 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10574 					 set_user_ringbuf_callback_state);
10575 		break;
10576 	}
10577 
10578 	if (err)
10579 		return err;
10580 
10581 	/* reset caller saved regs */
10582 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10583 		mark_reg_not_init(env, regs, caller_saved[i]);
10584 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10585 	}
10586 
10587 	/* helper call returns 64-bit value. */
10588 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10589 
10590 	/* update return register (already marked as written above) */
10591 	ret_type = fn->ret_type;
10592 	ret_flag = type_flag(ret_type);
10593 
10594 	switch (base_type(ret_type)) {
10595 	case RET_INTEGER:
10596 		/* sets type to SCALAR_VALUE */
10597 		mark_reg_unknown(env, regs, BPF_REG_0);
10598 		break;
10599 	case RET_VOID:
10600 		regs[BPF_REG_0].type = NOT_INIT;
10601 		break;
10602 	case RET_PTR_TO_MAP_VALUE:
10603 		/* There is no offset yet applied, variable or fixed */
10604 		mark_reg_known_zero(env, regs, BPF_REG_0);
10605 		/* remember map_ptr, so that check_map_access()
10606 		 * can check 'value_size' boundary of memory access
10607 		 * to map element returned from bpf_map_lookup_elem()
10608 		 */
10609 		if (meta.map_ptr == NULL) {
10610 			verbose(env,
10611 				"kernel subsystem misconfigured verifier\n");
10612 			return -EINVAL;
10613 		}
10614 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10615 		regs[BPF_REG_0].map_uid = meta.map_uid;
10616 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10617 		if (!type_may_be_null(ret_type) &&
10618 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10619 			regs[BPF_REG_0].id = ++env->id_gen;
10620 		}
10621 		break;
10622 	case RET_PTR_TO_SOCKET:
10623 		mark_reg_known_zero(env, regs, BPF_REG_0);
10624 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10625 		break;
10626 	case RET_PTR_TO_SOCK_COMMON:
10627 		mark_reg_known_zero(env, regs, BPF_REG_0);
10628 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10629 		break;
10630 	case RET_PTR_TO_TCP_SOCK:
10631 		mark_reg_known_zero(env, regs, BPF_REG_0);
10632 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10633 		break;
10634 	case RET_PTR_TO_MEM:
10635 		mark_reg_known_zero(env, regs, BPF_REG_0);
10636 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10637 		regs[BPF_REG_0].mem_size = meta.mem_size;
10638 		break;
10639 	case RET_PTR_TO_MEM_OR_BTF_ID:
10640 	{
10641 		const struct btf_type *t;
10642 
10643 		mark_reg_known_zero(env, regs, BPF_REG_0);
10644 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10645 		if (!btf_type_is_struct(t)) {
10646 			u32 tsize;
10647 			const struct btf_type *ret;
10648 			const char *tname;
10649 
10650 			/* resolve the type size of ksym. */
10651 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10652 			if (IS_ERR(ret)) {
10653 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10654 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10655 					tname, PTR_ERR(ret));
10656 				return -EINVAL;
10657 			}
10658 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10659 			regs[BPF_REG_0].mem_size = tsize;
10660 		} else {
10661 			if (returns_cpu_specific_alloc_ptr) {
10662 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10663 			} else {
10664 				/* MEM_RDONLY may be carried from ret_flag, but it
10665 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10666 				 * it will confuse the check of PTR_TO_BTF_ID in
10667 				 * check_mem_access().
10668 				 */
10669 				ret_flag &= ~MEM_RDONLY;
10670 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10671 			}
10672 
10673 			regs[BPF_REG_0].btf = meta.ret_btf;
10674 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10675 		}
10676 		break;
10677 	}
10678 	case RET_PTR_TO_BTF_ID:
10679 	{
10680 		struct btf *ret_btf;
10681 		int ret_btf_id;
10682 
10683 		mark_reg_known_zero(env, regs, BPF_REG_0);
10684 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10685 		if (func_id == BPF_FUNC_kptr_xchg) {
10686 			ret_btf = meta.kptr_field->kptr.btf;
10687 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10688 			if (!btf_is_kernel(ret_btf)) {
10689 				regs[BPF_REG_0].type |= MEM_ALLOC;
10690 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10691 					regs[BPF_REG_0].type |= MEM_PERCPU;
10692 			}
10693 		} else {
10694 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10695 				verbose(env, "verifier internal error:");
10696 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10697 					func_id_name(func_id));
10698 				return -EINVAL;
10699 			}
10700 			ret_btf = btf_vmlinux;
10701 			ret_btf_id = *fn->ret_btf_id;
10702 		}
10703 		if (ret_btf_id == 0) {
10704 			verbose(env, "invalid return type %u of func %s#%d\n",
10705 				base_type(ret_type), func_id_name(func_id),
10706 				func_id);
10707 			return -EINVAL;
10708 		}
10709 		regs[BPF_REG_0].btf = ret_btf;
10710 		regs[BPF_REG_0].btf_id = ret_btf_id;
10711 		break;
10712 	}
10713 	default:
10714 		verbose(env, "unknown return type %u of func %s#%d\n",
10715 			base_type(ret_type), func_id_name(func_id), func_id);
10716 		return -EINVAL;
10717 	}
10718 
10719 	if (type_may_be_null(regs[BPF_REG_0].type))
10720 		regs[BPF_REG_0].id = ++env->id_gen;
10721 
10722 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10723 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10724 			func_id_name(func_id), func_id);
10725 		return -EFAULT;
10726 	}
10727 
10728 	if (is_dynptr_ref_function(func_id))
10729 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10730 
10731 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10732 		/* For release_reference() */
10733 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10734 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10735 		int id = acquire_reference_state(env, insn_idx);
10736 
10737 		if (id < 0)
10738 			return id;
10739 		/* For mark_ptr_or_null_reg() */
10740 		regs[BPF_REG_0].id = id;
10741 		/* For release_reference() */
10742 		regs[BPF_REG_0].ref_obj_id = id;
10743 	}
10744 
10745 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
10746 	if (err)
10747 		return err;
10748 
10749 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10750 	if (err)
10751 		return err;
10752 
10753 	if ((func_id == BPF_FUNC_get_stack ||
10754 	     func_id == BPF_FUNC_get_task_stack) &&
10755 	    !env->prog->has_callchain_buf) {
10756 		const char *err_str;
10757 
10758 #ifdef CONFIG_PERF_EVENTS
10759 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10760 		err_str = "cannot get callchain buffer for func %s#%d\n";
10761 #else
10762 		err = -ENOTSUPP;
10763 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10764 #endif
10765 		if (err) {
10766 			verbose(env, err_str, func_id_name(func_id), func_id);
10767 			return err;
10768 		}
10769 
10770 		env->prog->has_callchain_buf = true;
10771 	}
10772 
10773 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10774 		env->prog->call_get_stack = true;
10775 
10776 	if (func_id == BPF_FUNC_get_func_ip) {
10777 		if (check_get_func_ip(env))
10778 			return -ENOTSUPP;
10779 		env->prog->call_get_func_ip = true;
10780 	}
10781 
10782 	if (changes_data)
10783 		clear_all_pkt_pointers(env);
10784 	return 0;
10785 }
10786 
10787 /* mark_btf_func_reg_size() is used when the reg size is determined by
10788  * the BTF func_proto's return value size and argument.
10789  */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)10790 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10791 				   size_t reg_size)
10792 {
10793 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10794 
10795 	if (regno == BPF_REG_0) {
10796 		/* Function return value */
10797 		reg->live |= REG_LIVE_WRITTEN;
10798 		reg->subreg_def = reg_size == sizeof(u64) ?
10799 			DEF_NOT_SUBREG : env->insn_idx + 1;
10800 	} else {
10801 		/* Function argument */
10802 		if (reg_size == sizeof(u64)) {
10803 			mark_insn_zext(env, reg);
10804 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10805 		} else {
10806 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10807 		}
10808 	}
10809 }
10810 
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)10811 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10812 {
10813 	return meta->kfunc_flags & KF_ACQUIRE;
10814 }
10815 
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)10816 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10817 {
10818 	return meta->kfunc_flags & KF_RELEASE;
10819 }
10820 
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)10821 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10822 {
10823 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10824 }
10825 
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)10826 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10827 {
10828 	return meta->kfunc_flags & KF_SLEEPABLE;
10829 }
10830 
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)10831 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10832 {
10833 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10834 }
10835 
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)10836 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10837 {
10838 	return meta->kfunc_flags & KF_RCU;
10839 }
10840 
is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta * meta)10841 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10842 {
10843 	return meta->kfunc_flags & KF_RCU_PROTECTED;
10844 }
10845 
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10846 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10847 				  const struct btf_param *arg,
10848 				  const struct bpf_reg_state *reg)
10849 {
10850 	const struct btf_type *t;
10851 
10852 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10853 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10854 		return false;
10855 
10856 	return btf_param_match_suffix(btf, arg, "__sz");
10857 }
10858 
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10859 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10860 					const struct btf_param *arg,
10861 					const struct bpf_reg_state *reg)
10862 {
10863 	const struct btf_type *t;
10864 
10865 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10866 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10867 		return false;
10868 
10869 	return btf_param_match_suffix(btf, arg, "__szk");
10870 }
10871 
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)10872 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10873 {
10874 	return btf_param_match_suffix(btf, arg, "__opt");
10875 }
10876 
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)10877 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10878 {
10879 	return btf_param_match_suffix(btf, arg, "__k");
10880 }
10881 
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)10882 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10883 {
10884 	return btf_param_match_suffix(btf, arg, "__ign");
10885 }
10886 
is_kfunc_arg_map(const struct btf * btf,const struct btf_param * arg)10887 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
10888 {
10889 	return btf_param_match_suffix(btf, arg, "__map");
10890 }
10891 
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)10892 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10893 {
10894 	return btf_param_match_suffix(btf, arg, "__alloc");
10895 }
10896 
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)10897 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10898 {
10899 	return btf_param_match_suffix(btf, arg, "__uninit");
10900 }
10901 
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)10902 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10903 {
10904 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
10905 }
10906 
is_kfunc_arg_nullable(const struct btf * btf,const struct btf_param * arg)10907 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10908 {
10909 	return btf_param_match_suffix(btf, arg, "__nullable");
10910 }
10911 
is_kfunc_arg_const_str(const struct btf * btf,const struct btf_param * arg)10912 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
10913 {
10914 	return btf_param_match_suffix(btf, arg, "__str");
10915 }
10916 
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)10917 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10918 					  const struct btf_param *arg,
10919 					  const char *name)
10920 {
10921 	int len, target_len = strlen(name);
10922 	const char *param_name;
10923 
10924 	param_name = btf_name_by_offset(btf, arg->name_off);
10925 	if (str_is_empty(param_name))
10926 		return false;
10927 	len = strlen(param_name);
10928 	if (len != target_len)
10929 		return false;
10930 	if (strcmp(param_name, name))
10931 		return false;
10932 
10933 	return true;
10934 }
10935 
10936 enum {
10937 	KF_ARG_DYNPTR_ID,
10938 	KF_ARG_LIST_HEAD_ID,
10939 	KF_ARG_LIST_NODE_ID,
10940 	KF_ARG_RB_ROOT_ID,
10941 	KF_ARG_RB_NODE_ID,
10942 	KF_ARG_WORKQUEUE_ID,
10943 };
10944 
10945 BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr)10946 BTF_ID(struct, bpf_dynptr)
10947 BTF_ID(struct, bpf_list_head)
10948 BTF_ID(struct, bpf_list_node)
10949 BTF_ID(struct, bpf_rb_root)
10950 BTF_ID(struct, bpf_rb_node)
10951 BTF_ID(struct, bpf_wq)
10952 
10953 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10954 				    const struct btf_param *arg, int type)
10955 {
10956 	const struct btf_type *t;
10957 	u32 res_id;
10958 
10959 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10960 	if (!t)
10961 		return false;
10962 	if (!btf_type_is_ptr(t))
10963 		return false;
10964 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10965 	if (!t)
10966 		return false;
10967 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10968 }
10969 
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)10970 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10971 {
10972 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10973 }
10974 
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)10975 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10976 {
10977 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10978 }
10979 
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)10980 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10981 {
10982 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10983 }
10984 
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)10985 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10986 {
10987 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10988 }
10989 
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)10990 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10991 {
10992 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10993 }
10994 
is_kfunc_arg_wq(const struct btf * btf,const struct btf_param * arg)10995 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
10996 {
10997 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
10998 }
10999 
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)11000 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
11001 				  const struct btf_param *arg)
11002 {
11003 	const struct btf_type *t;
11004 
11005 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
11006 	if (!t)
11007 		return false;
11008 
11009 	return true;
11010 }
11011 
11012 /* 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)11013 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
11014 					const struct btf *btf,
11015 					const struct btf_type *t, int rec)
11016 {
11017 	const struct btf_type *member_type;
11018 	const struct btf_member *member;
11019 	u32 i;
11020 
11021 	if (!btf_type_is_struct(t))
11022 		return false;
11023 
11024 	for_each_member(i, t, member) {
11025 		const struct btf_array *array;
11026 
11027 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
11028 		if (btf_type_is_struct(member_type)) {
11029 			if (rec >= 3) {
11030 				verbose(env, "max struct nesting depth exceeded\n");
11031 				return false;
11032 			}
11033 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
11034 				return false;
11035 			continue;
11036 		}
11037 		if (btf_type_is_array(member_type)) {
11038 			array = btf_array(member_type);
11039 			if (!array->nelems)
11040 				return false;
11041 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
11042 			if (!btf_type_is_scalar(member_type))
11043 				return false;
11044 			continue;
11045 		}
11046 		if (!btf_type_is_scalar(member_type))
11047 			return false;
11048 	}
11049 	return true;
11050 }
11051 
11052 enum kfunc_ptr_arg_type {
11053 	KF_ARG_PTR_TO_CTX,
11054 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
11055 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
11056 	KF_ARG_PTR_TO_DYNPTR,
11057 	KF_ARG_PTR_TO_ITER,
11058 	KF_ARG_PTR_TO_LIST_HEAD,
11059 	KF_ARG_PTR_TO_LIST_NODE,
11060 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
11061 	KF_ARG_PTR_TO_MEM,
11062 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
11063 	KF_ARG_PTR_TO_CALLBACK,
11064 	KF_ARG_PTR_TO_RB_ROOT,
11065 	KF_ARG_PTR_TO_RB_NODE,
11066 	KF_ARG_PTR_TO_NULL,
11067 	KF_ARG_PTR_TO_CONST_STR,
11068 	KF_ARG_PTR_TO_MAP,
11069 	KF_ARG_PTR_TO_WORKQUEUE,
11070 };
11071 
11072 enum special_kfunc_type {
11073 	KF_bpf_obj_new_impl,
11074 	KF_bpf_obj_drop_impl,
11075 	KF_bpf_refcount_acquire_impl,
11076 	KF_bpf_list_push_front_impl,
11077 	KF_bpf_list_push_back_impl,
11078 	KF_bpf_list_pop_front,
11079 	KF_bpf_list_pop_back,
11080 	KF_bpf_cast_to_kern_ctx,
11081 	KF_bpf_rdonly_cast,
11082 	KF_bpf_rcu_read_lock,
11083 	KF_bpf_rcu_read_unlock,
11084 	KF_bpf_rbtree_remove,
11085 	KF_bpf_rbtree_add_impl,
11086 	KF_bpf_rbtree_first,
11087 	KF_bpf_dynptr_from_skb,
11088 	KF_bpf_dynptr_from_xdp,
11089 	KF_bpf_dynptr_slice,
11090 	KF_bpf_dynptr_slice_rdwr,
11091 	KF_bpf_dynptr_clone,
11092 	KF_bpf_percpu_obj_new_impl,
11093 	KF_bpf_percpu_obj_drop_impl,
11094 	KF_bpf_throw,
11095 	KF_bpf_wq_set_callback_impl,
11096 	KF_bpf_preempt_disable,
11097 	KF_bpf_preempt_enable,
11098 	KF_bpf_iter_css_task_new,
11099 	KF_bpf_session_cookie,
11100 };
11101 
11102 BTF_SET_START(special_kfunc_set)
BTF_ID(func,bpf_obj_new_impl)11103 BTF_ID(func, bpf_obj_new_impl)
11104 BTF_ID(func, bpf_obj_drop_impl)
11105 BTF_ID(func, bpf_refcount_acquire_impl)
11106 BTF_ID(func, bpf_list_push_front_impl)
11107 BTF_ID(func, bpf_list_push_back_impl)
11108 BTF_ID(func, bpf_list_pop_front)
11109 BTF_ID(func, bpf_list_pop_back)
11110 BTF_ID(func, bpf_cast_to_kern_ctx)
11111 BTF_ID(func, bpf_rdonly_cast)
11112 BTF_ID(func, bpf_rbtree_remove)
11113 BTF_ID(func, bpf_rbtree_add_impl)
11114 BTF_ID(func, bpf_rbtree_first)
11115 BTF_ID(func, bpf_dynptr_from_skb)
11116 BTF_ID(func, bpf_dynptr_from_xdp)
11117 BTF_ID(func, bpf_dynptr_slice)
11118 BTF_ID(func, bpf_dynptr_slice_rdwr)
11119 BTF_ID(func, bpf_dynptr_clone)
11120 BTF_ID(func, bpf_percpu_obj_new_impl)
11121 BTF_ID(func, bpf_percpu_obj_drop_impl)
11122 BTF_ID(func, bpf_throw)
11123 BTF_ID(func, bpf_wq_set_callback_impl)
11124 #ifdef CONFIG_CGROUPS
11125 BTF_ID(func, bpf_iter_css_task_new)
11126 #endif
11127 BTF_SET_END(special_kfunc_set)
11128 
11129 BTF_ID_LIST(special_kfunc_list)
11130 BTF_ID(func, bpf_obj_new_impl)
11131 BTF_ID(func, bpf_obj_drop_impl)
11132 BTF_ID(func, bpf_refcount_acquire_impl)
11133 BTF_ID(func, bpf_list_push_front_impl)
11134 BTF_ID(func, bpf_list_push_back_impl)
11135 BTF_ID(func, bpf_list_pop_front)
11136 BTF_ID(func, bpf_list_pop_back)
11137 BTF_ID(func, bpf_cast_to_kern_ctx)
11138 BTF_ID(func, bpf_rdonly_cast)
11139 BTF_ID(func, bpf_rcu_read_lock)
11140 BTF_ID(func, bpf_rcu_read_unlock)
11141 BTF_ID(func, bpf_rbtree_remove)
11142 BTF_ID(func, bpf_rbtree_add_impl)
11143 BTF_ID(func, bpf_rbtree_first)
11144 BTF_ID(func, bpf_dynptr_from_skb)
11145 BTF_ID(func, bpf_dynptr_from_xdp)
11146 BTF_ID(func, bpf_dynptr_slice)
11147 BTF_ID(func, bpf_dynptr_slice_rdwr)
11148 BTF_ID(func, bpf_dynptr_clone)
11149 BTF_ID(func, bpf_percpu_obj_new_impl)
11150 BTF_ID(func, bpf_percpu_obj_drop_impl)
11151 BTF_ID(func, bpf_throw)
11152 BTF_ID(func, bpf_wq_set_callback_impl)
11153 BTF_ID(func, bpf_preempt_disable)
11154 BTF_ID(func, bpf_preempt_enable)
11155 #ifdef CONFIG_CGROUPS
11156 BTF_ID(func, bpf_iter_css_task_new)
11157 #else
11158 BTF_ID_UNUSED
11159 #endif
11160 #ifdef CONFIG_BPF_EVENTS
11161 BTF_ID(func, bpf_session_cookie)
11162 #else
11163 BTF_ID_UNUSED
11164 #endif
11165 
11166 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
11167 {
11168 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
11169 	    meta->arg_owning_ref) {
11170 		return false;
11171 	}
11172 
11173 	return meta->kfunc_flags & KF_RET_NULL;
11174 }
11175 
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)11176 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
11177 {
11178 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
11179 }
11180 
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)11181 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
11182 {
11183 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
11184 }
11185 
is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta * meta)11186 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
11187 {
11188 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
11189 }
11190 
is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta * meta)11191 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
11192 {
11193 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
11194 }
11195 
11196 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)11197 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
11198 		       struct bpf_kfunc_call_arg_meta *meta,
11199 		       const struct btf_type *t, const struct btf_type *ref_t,
11200 		       const char *ref_tname, const struct btf_param *args,
11201 		       int argno, int nargs)
11202 {
11203 	u32 regno = argno + 1;
11204 	struct bpf_reg_state *regs = cur_regs(env);
11205 	struct bpf_reg_state *reg = &regs[regno];
11206 	bool arg_mem_size = false;
11207 
11208 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
11209 		return KF_ARG_PTR_TO_CTX;
11210 
11211 	/* In this function, we verify the kfunc's BTF as per the argument type,
11212 	 * leaving the rest of the verification with respect to the register
11213 	 * type to our caller. When a set of conditions hold in the BTF type of
11214 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
11215 	 */
11216 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
11217 		return KF_ARG_PTR_TO_CTX;
11218 
11219 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
11220 		return KF_ARG_PTR_TO_NULL;
11221 
11222 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
11223 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
11224 
11225 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
11226 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
11227 
11228 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
11229 		return KF_ARG_PTR_TO_DYNPTR;
11230 
11231 	if (is_kfunc_arg_iter(meta, argno))
11232 		return KF_ARG_PTR_TO_ITER;
11233 
11234 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
11235 		return KF_ARG_PTR_TO_LIST_HEAD;
11236 
11237 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
11238 		return KF_ARG_PTR_TO_LIST_NODE;
11239 
11240 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
11241 		return KF_ARG_PTR_TO_RB_ROOT;
11242 
11243 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
11244 		return KF_ARG_PTR_TO_RB_NODE;
11245 
11246 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
11247 		return KF_ARG_PTR_TO_CONST_STR;
11248 
11249 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
11250 		return KF_ARG_PTR_TO_MAP;
11251 
11252 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
11253 		return KF_ARG_PTR_TO_WORKQUEUE;
11254 
11255 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
11256 		if (!btf_type_is_struct(ref_t)) {
11257 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
11258 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
11259 			return -EINVAL;
11260 		}
11261 		return KF_ARG_PTR_TO_BTF_ID;
11262 	}
11263 
11264 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
11265 		return KF_ARG_PTR_TO_CALLBACK;
11266 
11267 	if (argno + 1 < nargs &&
11268 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
11269 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
11270 		arg_mem_size = true;
11271 
11272 	/* This is the catch all argument type of register types supported by
11273 	 * check_helper_mem_access. However, we only allow when argument type is
11274 	 * pointer to scalar, or struct composed (recursively) of scalars. When
11275 	 * arg_mem_size is true, the pointer can be void *.
11276 	 */
11277 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
11278 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
11279 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
11280 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
11281 		return -EINVAL;
11282 	}
11283 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
11284 }
11285 
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)11286 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
11287 					struct bpf_reg_state *reg,
11288 					const struct btf_type *ref_t,
11289 					const char *ref_tname, u32 ref_id,
11290 					struct bpf_kfunc_call_arg_meta *meta,
11291 					int argno)
11292 {
11293 	const struct btf_type *reg_ref_t;
11294 	bool strict_type_match = false;
11295 	const struct btf *reg_btf;
11296 	const char *reg_ref_tname;
11297 	bool taking_projection;
11298 	bool struct_same;
11299 	u32 reg_ref_id;
11300 
11301 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
11302 		reg_btf = reg->btf;
11303 		reg_ref_id = reg->btf_id;
11304 	} else {
11305 		reg_btf = btf_vmlinux;
11306 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
11307 	}
11308 
11309 	/* Enforce strict type matching for calls to kfuncs that are acquiring
11310 	 * or releasing a reference, or are no-cast aliases. We do _not_
11311 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
11312 	 * as we want to enable BPF programs to pass types that are bitwise
11313 	 * equivalent without forcing them to explicitly cast with something
11314 	 * like bpf_cast_to_kern_ctx().
11315 	 *
11316 	 * For example, say we had a type like the following:
11317 	 *
11318 	 * struct bpf_cpumask {
11319 	 *	cpumask_t cpumask;
11320 	 *	refcount_t usage;
11321 	 * };
11322 	 *
11323 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11324 	 * to a struct cpumask, so it would be safe to pass a struct
11325 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11326 	 *
11327 	 * The philosophy here is similar to how we allow scalars of different
11328 	 * types to be passed to kfuncs as long as the size is the same. The
11329 	 * only difference here is that we're simply allowing
11330 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
11331 	 * resolve types.
11332 	 */
11333 	if (is_kfunc_acquire(meta) ||
11334 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
11335 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11336 		strict_type_match = true;
11337 
11338 	WARN_ON_ONCE(is_kfunc_release(meta) &&
11339 		     (reg->off || !tnum_is_const(reg->var_off) ||
11340 		      reg->var_off.value));
11341 
11342 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11343 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11344 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
11345 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
11346 	 * actually use it -- it must cast to the underlying type. So we allow
11347 	 * caller to pass in the underlying type.
11348 	 */
11349 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
11350 	if (!taking_projection && !struct_same) {
11351 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11352 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11353 			btf_type_str(reg_ref_t), reg_ref_tname);
11354 		return -EINVAL;
11355 	}
11356 	return 0;
11357 }
11358 
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)11359 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11360 {
11361 	struct bpf_verifier_state *state = env->cur_state;
11362 	struct btf_record *rec = reg_btf_record(reg);
11363 
11364 	if (!state->active_lock.ptr) {
11365 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11366 		return -EFAULT;
11367 	}
11368 
11369 	if (type_flag(reg->type) & NON_OWN_REF) {
11370 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11371 		return -EFAULT;
11372 	}
11373 
11374 	reg->type |= NON_OWN_REF;
11375 	if (rec->refcount_off >= 0)
11376 		reg->type |= MEM_RCU;
11377 
11378 	return 0;
11379 }
11380 
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)11381 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11382 {
11383 	struct bpf_func_state *state, *unused;
11384 	struct bpf_reg_state *reg;
11385 	int i;
11386 
11387 	state = cur_func(env);
11388 
11389 	if (!ref_obj_id) {
11390 		verbose(env, "verifier internal error: ref_obj_id is zero for "
11391 			     "owning -> non-owning conversion\n");
11392 		return -EFAULT;
11393 	}
11394 
11395 	for (i = 0; i < state->acquired_refs; i++) {
11396 		if (state->refs[i].id != ref_obj_id)
11397 			continue;
11398 
11399 		/* Clear ref_obj_id here so release_reference doesn't clobber
11400 		 * the whole reg
11401 		 */
11402 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11403 			if (reg->ref_obj_id == ref_obj_id) {
11404 				reg->ref_obj_id = 0;
11405 				ref_set_non_owning(env, reg);
11406 			}
11407 		}));
11408 		return 0;
11409 	}
11410 
11411 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11412 	return -EFAULT;
11413 }
11414 
11415 /* Implementation details:
11416  *
11417  * Each register points to some region of memory, which we define as an
11418  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11419  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11420  * allocation. The lock and the data it protects are colocated in the same
11421  * memory region.
11422  *
11423  * Hence, everytime a register holds a pointer value pointing to such
11424  * allocation, the verifier preserves a unique reg->id for it.
11425  *
11426  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11427  * bpf_spin_lock is called.
11428  *
11429  * To enable this, lock state in the verifier captures two values:
11430  *	active_lock.ptr = Register's type specific pointer
11431  *	active_lock.id  = A unique ID for each register pointer value
11432  *
11433  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11434  * supported register types.
11435  *
11436  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11437  * allocated objects is the reg->btf pointer.
11438  *
11439  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11440  * can establish the provenance of the map value statically for each distinct
11441  * lookup into such maps. They always contain a single map value hence unique
11442  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11443  *
11444  * So, in case of global variables, they use array maps with max_entries = 1,
11445  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11446  * into the same map value as max_entries is 1, as described above).
11447  *
11448  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11449  * outer map pointer (in verifier context), but each lookup into an inner map
11450  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11451  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11452  * will get different reg->id assigned to each lookup, hence different
11453  * active_lock.id.
11454  *
11455  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11456  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11457  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11458  */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)11459 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11460 {
11461 	void *ptr;
11462 	u32 id;
11463 
11464 	switch ((int)reg->type) {
11465 	case PTR_TO_MAP_VALUE:
11466 		ptr = reg->map_ptr;
11467 		break;
11468 	case PTR_TO_BTF_ID | MEM_ALLOC:
11469 		ptr = reg->btf;
11470 		break;
11471 	default:
11472 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11473 		return -EFAULT;
11474 	}
11475 	id = reg->id;
11476 
11477 	if (!env->cur_state->active_lock.ptr)
11478 		return -EINVAL;
11479 	if (env->cur_state->active_lock.ptr != ptr ||
11480 	    env->cur_state->active_lock.id != id) {
11481 		verbose(env, "held lock and object are not in the same allocation\n");
11482 		return -EINVAL;
11483 	}
11484 	return 0;
11485 }
11486 
is_bpf_list_api_kfunc(u32 btf_id)11487 static bool is_bpf_list_api_kfunc(u32 btf_id)
11488 {
11489 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11490 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11491 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11492 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11493 }
11494 
is_bpf_rbtree_api_kfunc(u32 btf_id)11495 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11496 {
11497 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11498 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11499 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11500 }
11501 
is_bpf_graph_api_kfunc(u32 btf_id)11502 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11503 {
11504 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11505 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11506 }
11507 
is_sync_callback_calling_kfunc(u32 btf_id)11508 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11509 {
11510 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11511 }
11512 
is_async_callback_calling_kfunc(u32 btf_id)11513 static bool is_async_callback_calling_kfunc(u32 btf_id)
11514 {
11515 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11516 }
11517 
is_bpf_throw_kfunc(struct bpf_insn * insn)11518 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11519 {
11520 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11521 	       insn->imm == special_kfunc_list[KF_bpf_throw];
11522 }
11523 
is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)11524 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
11525 {
11526 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
11527 }
11528 
is_callback_calling_kfunc(u32 btf_id)11529 static bool is_callback_calling_kfunc(u32 btf_id)
11530 {
11531 	return is_sync_callback_calling_kfunc(btf_id) ||
11532 	       is_async_callback_calling_kfunc(btf_id);
11533 }
11534 
is_rbtree_lock_required_kfunc(u32 btf_id)11535 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11536 {
11537 	return is_bpf_rbtree_api_kfunc(btf_id);
11538 }
11539 
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)11540 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11541 					  enum btf_field_type head_field_type,
11542 					  u32 kfunc_btf_id)
11543 {
11544 	bool ret;
11545 
11546 	switch (head_field_type) {
11547 	case BPF_LIST_HEAD:
11548 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11549 		break;
11550 	case BPF_RB_ROOT:
11551 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11552 		break;
11553 	default:
11554 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11555 			btf_field_type_name(head_field_type));
11556 		return false;
11557 	}
11558 
11559 	if (!ret)
11560 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11561 			btf_field_type_name(head_field_type));
11562 	return ret;
11563 }
11564 
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)11565 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11566 					  enum btf_field_type node_field_type,
11567 					  u32 kfunc_btf_id)
11568 {
11569 	bool ret;
11570 
11571 	switch (node_field_type) {
11572 	case BPF_LIST_NODE:
11573 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11574 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11575 		break;
11576 	case BPF_RB_NODE:
11577 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11578 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11579 		break;
11580 	default:
11581 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11582 			btf_field_type_name(node_field_type));
11583 		return false;
11584 	}
11585 
11586 	if (!ret)
11587 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11588 			btf_field_type_name(node_field_type));
11589 	return ret;
11590 }
11591 
11592 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)11593 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11594 				   struct bpf_reg_state *reg, u32 regno,
11595 				   struct bpf_kfunc_call_arg_meta *meta,
11596 				   enum btf_field_type head_field_type,
11597 				   struct btf_field **head_field)
11598 {
11599 	const char *head_type_name;
11600 	struct btf_field *field;
11601 	struct btf_record *rec;
11602 	u32 head_off;
11603 
11604 	if (meta->btf != btf_vmlinux) {
11605 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11606 		return -EFAULT;
11607 	}
11608 
11609 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11610 		return -EFAULT;
11611 
11612 	head_type_name = btf_field_type_name(head_field_type);
11613 	if (!tnum_is_const(reg->var_off)) {
11614 		verbose(env,
11615 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11616 			regno, head_type_name);
11617 		return -EINVAL;
11618 	}
11619 
11620 	rec = reg_btf_record(reg);
11621 	head_off = reg->off + reg->var_off.value;
11622 	field = btf_record_find(rec, head_off, head_field_type);
11623 	if (!field) {
11624 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11625 		return -EINVAL;
11626 	}
11627 
11628 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11629 	if (check_reg_allocation_locked(env, reg)) {
11630 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11631 			rec->spin_lock_off, head_type_name);
11632 		return -EINVAL;
11633 	}
11634 
11635 	if (*head_field) {
11636 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11637 		return -EFAULT;
11638 	}
11639 	*head_field = field;
11640 	return 0;
11641 }
11642 
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)11643 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11644 					   struct bpf_reg_state *reg, u32 regno,
11645 					   struct bpf_kfunc_call_arg_meta *meta)
11646 {
11647 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11648 							  &meta->arg_list_head.field);
11649 }
11650 
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)11651 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11652 					     struct bpf_reg_state *reg, u32 regno,
11653 					     struct bpf_kfunc_call_arg_meta *meta)
11654 {
11655 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11656 							  &meta->arg_rbtree_root.field);
11657 }
11658 
11659 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)11660 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11661 				   struct bpf_reg_state *reg, u32 regno,
11662 				   struct bpf_kfunc_call_arg_meta *meta,
11663 				   enum btf_field_type head_field_type,
11664 				   enum btf_field_type node_field_type,
11665 				   struct btf_field **node_field)
11666 {
11667 	const char *node_type_name;
11668 	const struct btf_type *et, *t;
11669 	struct btf_field *field;
11670 	u32 node_off;
11671 
11672 	if (meta->btf != btf_vmlinux) {
11673 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11674 		return -EFAULT;
11675 	}
11676 
11677 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11678 		return -EFAULT;
11679 
11680 	node_type_name = btf_field_type_name(node_field_type);
11681 	if (!tnum_is_const(reg->var_off)) {
11682 		verbose(env,
11683 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11684 			regno, node_type_name);
11685 		return -EINVAL;
11686 	}
11687 
11688 	node_off = reg->off + reg->var_off.value;
11689 	field = reg_find_field_offset(reg, node_off, node_field_type);
11690 	if (!field) {
11691 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11692 		return -EINVAL;
11693 	}
11694 
11695 	field = *node_field;
11696 
11697 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11698 	t = btf_type_by_id(reg->btf, reg->btf_id);
11699 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11700 				  field->graph_root.value_btf_id, true)) {
11701 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11702 			"in struct %s, but arg is at offset=%d in struct %s\n",
11703 			btf_field_type_name(head_field_type),
11704 			btf_field_type_name(node_field_type),
11705 			field->graph_root.node_offset,
11706 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11707 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11708 		return -EINVAL;
11709 	}
11710 	meta->arg_btf = reg->btf;
11711 	meta->arg_btf_id = reg->btf_id;
11712 
11713 	if (node_off != field->graph_root.node_offset) {
11714 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11715 			node_off, btf_field_type_name(node_field_type),
11716 			field->graph_root.node_offset,
11717 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11718 		return -EINVAL;
11719 	}
11720 
11721 	return 0;
11722 }
11723 
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)11724 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11725 					   struct bpf_reg_state *reg, u32 regno,
11726 					   struct bpf_kfunc_call_arg_meta *meta)
11727 {
11728 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11729 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11730 						  &meta->arg_list_head.field);
11731 }
11732 
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)11733 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11734 					     struct bpf_reg_state *reg, u32 regno,
11735 					     struct bpf_kfunc_call_arg_meta *meta)
11736 {
11737 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11738 						  BPF_RB_ROOT, BPF_RB_NODE,
11739 						  &meta->arg_rbtree_root.field);
11740 }
11741 
11742 /*
11743  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
11744  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
11745  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
11746  * them can only be attached to some specific hook points.
11747  */
check_css_task_iter_allowlist(struct bpf_verifier_env * env)11748 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11749 {
11750 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11751 
11752 	switch (prog_type) {
11753 	case BPF_PROG_TYPE_LSM:
11754 		return true;
11755 	case BPF_PROG_TYPE_TRACING:
11756 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
11757 			return true;
11758 		fallthrough;
11759 	default:
11760 		return in_sleepable(env);
11761 	}
11762 }
11763 
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)11764 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11765 			    int insn_idx)
11766 {
11767 	const char *func_name = meta->func_name, *ref_tname;
11768 	const struct btf *btf = meta->btf;
11769 	const struct btf_param *args;
11770 	struct btf_record *rec;
11771 	u32 i, nargs;
11772 	int ret;
11773 
11774 	args = (const struct btf_param *)(meta->func_proto + 1);
11775 	nargs = btf_type_vlen(meta->func_proto);
11776 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11777 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11778 			MAX_BPF_FUNC_REG_ARGS);
11779 		return -EINVAL;
11780 	}
11781 
11782 	/* Check that BTF function arguments match actual types that the
11783 	 * verifier sees.
11784 	 */
11785 	for (i = 0; i < nargs; i++) {
11786 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11787 		const struct btf_type *t, *ref_t, *resolve_ret;
11788 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11789 		u32 regno = i + 1, ref_id, type_size;
11790 		bool is_ret_buf_sz = false;
11791 		int kf_arg_type;
11792 
11793 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11794 
11795 		if (is_kfunc_arg_ignore(btf, &args[i]))
11796 			continue;
11797 
11798 		if (btf_type_is_scalar(t)) {
11799 			if (reg->type != SCALAR_VALUE) {
11800 				verbose(env, "R%d is not a scalar\n", regno);
11801 				return -EINVAL;
11802 			}
11803 
11804 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11805 				if (meta->arg_constant.found) {
11806 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11807 					return -EFAULT;
11808 				}
11809 				if (!tnum_is_const(reg->var_off)) {
11810 					verbose(env, "R%d must be a known constant\n", regno);
11811 					return -EINVAL;
11812 				}
11813 				ret = mark_chain_precision(env, regno);
11814 				if (ret < 0)
11815 					return ret;
11816 				meta->arg_constant.found = true;
11817 				meta->arg_constant.value = reg->var_off.value;
11818 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11819 				meta->r0_rdonly = true;
11820 				is_ret_buf_sz = true;
11821 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11822 				is_ret_buf_sz = true;
11823 			}
11824 
11825 			if (is_ret_buf_sz) {
11826 				if (meta->r0_size) {
11827 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11828 					return -EINVAL;
11829 				}
11830 
11831 				if (!tnum_is_const(reg->var_off)) {
11832 					verbose(env, "R%d is not a const\n", regno);
11833 					return -EINVAL;
11834 				}
11835 
11836 				meta->r0_size = reg->var_off.value;
11837 				ret = mark_chain_precision(env, regno);
11838 				if (ret)
11839 					return ret;
11840 			}
11841 			continue;
11842 		}
11843 
11844 		if (!btf_type_is_ptr(t)) {
11845 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11846 			return -EINVAL;
11847 		}
11848 
11849 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11850 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
11851 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
11852 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11853 			return -EACCES;
11854 		}
11855 
11856 		if (reg->ref_obj_id) {
11857 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11858 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11859 					regno, reg->ref_obj_id,
11860 					meta->ref_obj_id);
11861 				return -EFAULT;
11862 			}
11863 			meta->ref_obj_id = reg->ref_obj_id;
11864 			if (is_kfunc_release(meta))
11865 				meta->release_regno = regno;
11866 		}
11867 
11868 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11869 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11870 
11871 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11872 		if (kf_arg_type < 0)
11873 			return kf_arg_type;
11874 
11875 		switch (kf_arg_type) {
11876 		case KF_ARG_PTR_TO_NULL:
11877 			continue;
11878 		case KF_ARG_PTR_TO_MAP:
11879 			if (!reg->map_ptr) {
11880 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
11881 				return -EINVAL;
11882 			}
11883 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
11884 				/* Use map_uid (which is unique id of inner map) to reject:
11885 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
11886 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
11887 				 * if (inner_map1 && inner_map2) {
11888 				 *     wq = bpf_map_lookup_elem(inner_map1);
11889 				 *     if (wq)
11890 				 *         // mismatch would have been allowed
11891 				 *         bpf_wq_init(wq, inner_map2);
11892 				 * }
11893 				 *
11894 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
11895 				 */
11896 				if (meta->map.ptr != reg->map_ptr ||
11897 				    meta->map.uid != reg->map_uid) {
11898 					verbose(env,
11899 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
11900 						meta->map.uid, reg->map_uid);
11901 					return -EINVAL;
11902 				}
11903 			}
11904 			meta->map.ptr = reg->map_ptr;
11905 			meta->map.uid = reg->map_uid;
11906 			fallthrough;
11907 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11908 		case KF_ARG_PTR_TO_BTF_ID:
11909 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11910 				break;
11911 
11912 			if (!is_trusted_reg(reg)) {
11913 				if (!is_kfunc_rcu(meta)) {
11914 					verbose(env, "R%d must be referenced or trusted\n", regno);
11915 					return -EINVAL;
11916 				}
11917 				if (!is_rcu_reg(reg)) {
11918 					verbose(env, "R%d must be a rcu pointer\n", regno);
11919 					return -EINVAL;
11920 				}
11921 			}
11922 			fallthrough;
11923 		case KF_ARG_PTR_TO_CTX:
11924 		case KF_ARG_PTR_TO_DYNPTR:
11925 		case KF_ARG_PTR_TO_ITER:
11926 		case KF_ARG_PTR_TO_LIST_HEAD:
11927 		case KF_ARG_PTR_TO_LIST_NODE:
11928 		case KF_ARG_PTR_TO_RB_ROOT:
11929 		case KF_ARG_PTR_TO_RB_NODE:
11930 		case KF_ARG_PTR_TO_MEM:
11931 		case KF_ARG_PTR_TO_MEM_SIZE:
11932 		case KF_ARG_PTR_TO_CALLBACK:
11933 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11934 		case KF_ARG_PTR_TO_CONST_STR:
11935 		case KF_ARG_PTR_TO_WORKQUEUE:
11936 			break;
11937 		default:
11938 			WARN_ON_ONCE(1);
11939 			return -EFAULT;
11940 		}
11941 
11942 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11943 			arg_type |= OBJ_RELEASE;
11944 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11945 		if (ret < 0)
11946 			return ret;
11947 
11948 		switch (kf_arg_type) {
11949 		case KF_ARG_PTR_TO_CTX:
11950 			if (reg->type != PTR_TO_CTX) {
11951 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11952 				return -EINVAL;
11953 			}
11954 
11955 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11956 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11957 				if (ret < 0)
11958 					return -EINVAL;
11959 				meta->ret_btf_id  = ret;
11960 			}
11961 			break;
11962 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11963 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11964 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11965 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11966 					return -EINVAL;
11967 				}
11968 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11969 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11970 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11971 					return -EINVAL;
11972 				}
11973 			} else {
11974 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11975 				return -EINVAL;
11976 			}
11977 			if (!reg->ref_obj_id) {
11978 				verbose(env, "allocated object must be referenced\n");
11979 				return -EINVAL;
11980 			}
11981 			if (meta->btf == btf_vmlinux) {
11982 				meta->arg_btf = reg->btf;
11983 				meta->arg_btf_id = reg->btf_id;
11984 			}
11985 			break;
11986 		case KF_ARG_PTR_TO_DYNPTR:
11987 		{
11988 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11989 			int clone_ref_obj_id = 0;
11990 
11991 			if (reg->type == CONST_PTR_TO_DYNPTR)
11992 				dynptr_arg_type |= MEM_RDONLY;
11993 
11994 			if (is_kfunc_arg_uninit(btf, &args[i]))
11995 				dynptr_arg_type |= MEM_UNINIT;
11996 
11997 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11998 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11999 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
12000 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
12001 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
12002 				   (dynptr_arg_type & MEM_UNINIT)) {
12003 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
12004 
12005 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
12006 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
12007 					return -EFAULT;
12008 				}
12009 
12010 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
12011 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
12012 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
12013 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
12014 					return -EFAULT;
12015 				}
12016 			}
12017 
12018 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
12019 			if (ret < 0)
12020 				return ret;
12021 
12022 			if (!(dynptr_arg_type & MEM_UNINIT)) {
12023 				int id = dynptr_id(env, reg);
12024 
12025 				if (id < 0) {
12026 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
12027 					return id;
12028 				}
12029 				meta->initialized_dynptr.id = id;
12030 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
12031 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
12032 			}
12033 
12034 			break;
12035 		}
12036 		case KF_ARG_PTR_TO_ITER:
12037 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
12038 				if (!check_css_task_iter_allowlist(env)) {
12039 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
12040 					return -EINVAL;
12041 				}
12042 			}
12043 			ret = process_iter_arg(env, regno, insn_idx, meta);
12044 			if (ret < 0)
12045 				return ret;
12046 			break;
12047 		case KF_ARG_PTR_TO_LIST_HEAD:
12048 			if (reg->type != PTR_TO_MAP_VALUE &&
12049 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12050 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12051 				return -EINVAL;
12052 			}
12053 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12054 				verbose(env, "allocated object must be referenced\n");
12055 				return -EINVAL;
12056 			}
12057 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
12058 			if (ret < 0)
12059 				return ret;
12060 			break;
12061 		case KF_ARG_PTR_TO_RB_ROOT:
12062 			if (reg->type != PTR_TO_MAP_VALUE &&
12063 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12064 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
12065 				return -EINVAL;
12066 			}
12067 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
12068 				verbose(env, "allocated object must be referenced\n");
12069 				return -EINVAL;
12070 			}
12071 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
12072 			if (ret < 0)
12073 				return ret;
12074 			break;
12075 		case KF_ARG_PTR_TO_LIST_NODE:
12076 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12077 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
12078 				return -EINVAL;
12079 			}
12080 			if (!reg->ref_obj_id) {
12081 				verbose(env, "allocated object must be referenced\n");
12082 				return -EINVAL;
12083 			}
12084 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
12085 			if (ret < 0)
12086 				return ret;
12087 			break;
12088 		case KF_ARG_PTR_TO_RB_NODE:
12089 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
12090 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
12091 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
12092 					return -EINVAL;
12093 				}
12094 				if (in_rbtree_lock_required_cb(env)) {
12095 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
12096 					return -EINVAL;
12097 				}
12098 			} else {
12099 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
12100 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
12101 					return -EINVAL;
12102 				}
12103 				if (!reg->ref_obj_id) {
12104 					verbose(env, "allocated object must be referenced\n");
12105 					return -EINVAL;
12106 				}
12107 			}
12108 
12109 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
12110 			if (ret < 0)
12111 				return ret;
12112 			break;
12113 		case KF_ARG_PTR_TO_MAP:
12114 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
12115 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
12116 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
12117 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
12118 			fallthrough;
12119 		case KF_ARG_PTR_TO_BTF_ID:
12120 			/* Only base_type is checked, further checks are done here */
12121 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
12122 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
12123 			    !reg2btf_ids[base_type(reg->type)]) {
12124 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
12125 				verbose(env, "expected %s or socket\n",
12126 					reg_type_str(env, base_type(reg->type) |
12127 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
12128 				return -EINVAL;
12129 			}
12130 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
12131 			if (ret < 0)
12132 				return ret;
12133 			break;
12134 		case KF_ARG_PTR_TO_MEM:
12135 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
12136 			if (IS_ERR(resolve_ret)) {
12137 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
12138 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
12139 				return -EINVAL;
12140 			}
12141 			ret = check_mem_reg(env, reg, regno, type_size);
12142 			if (ret < 0)
12143 				return ret;
12144 			break;
12145 		case KF_ARG_PTR_TO_MEM_SIZE:
12146 		{
12147 			struct bpf_reg_state *buff_reg = &regs[regno];
12148 			const struct btf_param *buff_arg = &args[i];
12149 			struct bpf_reg_state *size_reg = &regs[regno + 1];
12150 			const struct btf_param *size_arg = &args[i + 1];
12151 
12152 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
12153 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
12154 				if (ret < 0) {
12155 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
12156 					return ret;
12157 				}
12158 			}
12159 
12160 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
12161 				if (meta->arg_constant.found) {
12162 					verbose(env, "verifier internal error: only one constant argument permitted\n");
12163 					return -EFAULT;
12164 				}
12165 				if (!tnum_is_const(size_reg->var_off)) {
12166 					verbose(env, "R%d must be a known constant\n", regno + 1);
12167 					return -EINVAL;
12168 				}
12169 				meta->arg_constant.found = true;
12170 				meta->arg_constant.value = size_reg->var_off.value;
12171 			}
12172 
12173 			/* Skip next '__sz' or '__szk' argument */
12174 			i++;
12175 			break;
12176 		}
12177 		case KF_ARG_PTR_TO_CALLBACK:
12178 			if (reg->type != PTR_TO_FUNC) {
12179 				verbose(env, "arg%d expected pointer to func\n", i);
12180 				return -EINVAL;
12181 			}
12182 			meta->subprogno = reg->subprogno;
12183 			break;
12184 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
12185 			if (!type_is_ptr_alloc_obj(reg->type)) {
12186 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
12187 				return -EINVAL;
12188 			}
12189 			if (!type_is_non_owning_ref(reg->type))
12190 				meta->arg_owning_ref = true;
12191 
12192 			rec = reg_btf_record(reg);
12193 			if (!rec) {
12194 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
12195 				return -EFAULT;
12196 			}
12197 
12198 			if (rec->refcount_off < 0) {
12199 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
12200 				return -EINVAL;
12201 			}
12202 
12203 			meta->arg_btf = reg->btf;
12204 			meta->arg_btf_id = reg->btf_id;
12205 			break;
12206 		case KF_ARG_PTR_TO_CONST_STR:
12207 			if (reg->type != PTR_TO_MAP_VALUE) {
12208 				verbose(env, "arg#%d doesn't point to a const string\n", i);
12209 				return -EINVAL;
12210 			}
12211 			ret = check_reg_const_str(env, reg, regno);
12212 			if (ret)
12213 				return ret;
12214 			break;
12215 		case KF_ARG_PTR_TO_WORKQUEUE:
12216 			if (reg->type != PTR_TO_MAP_VALUE) {
12217 				verbose(env, "arg#%d doesn't point to a map value\n", i);
12218 				return -EINVAL;
12219 			}
12220 			ret = process_wq_func(env, regno, meta);
12221 			if (ret < 0)
12222 				return ret;
12223 			break;
12224 		}
12225 	}
12226 
12227 	if (is_kfunc_release(meta) && !meta->release_regno) {
12228 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
12229 			func_name);
12230 		return -EINVAL;
12231 	}
12232 
12233 	return 0;
12234 }
12235 
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)12236 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
12237 			    struct bpf_insn *insn,
12238 			    struct bpf_kfunc_call_arg_meta *meta,
12239 			    const char **kfunc_name)
12240 {
12241 	const struct btf_type *func, *func_proto;
12242 	u32 func_id, *kfunc_flags;
12243 	const char *func_name;
12244 	struct btf *desc_btf;
12245 
12246 	if (kfunc_name)
12247 		*kfunc_name = NULL;
12248 
12249 	if (!insn->imm)
12250 		return -EINVAL;
12251 
12252 	desc_btf = find_kfunc_desc_btf(env, insn->off);
12253 	if (IS_ERR(desc_btf))
12254 		return PTR_ERR(desc_btf);
12255 
12256 	func_id = insn->imm;
12257 	func = btf_type_by_id(desc_btf, func_id);
12258 	func_name = btf_name_by_offset(desc_btf, func->name_off);
12259 	if (kfunc_name)
12260 		*kfunc_name = func_name;
12261 	func_proto = btf_type_by_id(desc_btf, func->type);
12262 
12263 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
12264 	if (!kfunc_flags) {
12265 		return -EACCES;
12266 	}
12267 
12268 	memset(meta, 0, sizeof(*meta));
12269 	meta->btf = desc_btf;
12270 	meta->func_id = func_id;
12271 	meta->kfunc_flags = *kfunc_flags;
12272 	meta->func_proto = func_proto;
12273 	meta->func_name = func_name;
12274 
12275 	return 0;
12276 }
12277 
12278 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
12279 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)12280 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
12281 			    int *insn_idx_p)
12282 {
12283 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
12284 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
12285 	struct bpf_reg_state *regs = cur_regs(env);
12286 	const char *func_name, *ptr_type_name;
12287 	const struct btf_type *t, *ptr_type;
12288 	struct bpf_kfunc_call_arg_meta meta;
12289 	struct bpf_insn_aux_data *insn_aux;
12290 	int err, insn_idx = *insn_idx_p;
12291 	const struct btf_param *args;
12292 	const struct btf_type *ret_t;
12293 	struct btf *desc_btf;
12294 
12295 	/* skip for now, but return error when we find this in fixup_kfunc_call */
12296 	if (!insn->imm)
12297 		return 0;
12298 
12299 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
12300 	if (err == -EACCES && func_name)
12301 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
12302 	if (err)
12303 		return err;
12304 	desc_btf = meta.btf;
12305 	insn_aux = &env->insn_aux_data[insn_idx];
12306 
12307 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
12308 
12309 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
12310 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
12311 		return -EACCES;
12312 	}
12313 
12314 	sleepable = is_kfunc_sleepable(&meta);
12315 	if (sleepable && !in_sleepable(env)) {
12316 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
12317 		return -EACCES;
12318 	}
12319 
12320 	/* Check the arguments */
12321 	err = check_kfunc_args(env, &meta, insn_idx);
12322 	if (err < 0)
12323 		return err;
12324 
12325 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12326 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12327 					 set_rbtree_add_callback_state);
12328 		if (err) {
12329 			verbose(env, "kfunc %s#%d failed callback verification\n",
12330 				func_name, meta.func_id);
12331 			return err;
12332 		}
12333 	}
12334 
12335 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
12336 		meta.r0_size = sizeof(u64);
12337 		meta.r0_rdonly = false;
12338 	}
12339 
12340 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
12341 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
12342 					 set_timer_callback_state);
12343 		if (err) {
12344 			verbose(env, "kfunc %s#%d failed callback verification\n",
12345 				func_name, meta.func_id);
12346 			return err;
12347 		}
12348 	}
12349 
12350 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
12351 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
12352 
12353 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
12354 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
12355 
12356 	if (env->cur_state->active_rcu_lock) {
12357 		struct bpf_func_state *state;
12358 		struct bpf_reg_state *reg;
12359 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
12360 
12361 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
12362 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
12363 			return -EACCES;
12364 		}
12365 
12366 		if (rcu_lock) {
12367 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
12368 			return -EINVAL;
12369 		} else if (rcu_unlock) {
12370 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
12371 				if (reg->type & MEM_RCU) {
12372 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
12373 					reg->type |= PTR_UNTRUSTED;
12374 				}
12375 			}));
12376 			env->cur_state->active_rcu_lock = false;
12377 		} else if (sleepable) {
12378 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
12379 			return -EACCES;
12380 		}
12381 	} else if (rcu_lock) {
12382 		env->cur_state->active_rcu_lock = true;
12383 	} else if (rcu_unlock) {
12384 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
12385 		return -EINVAL;
12386 	}
12387 
12388 	if (env->cur_state->active_preempt_lock) {
12389 		if (preempt_disable) {
12390 			env->cur_state->active_preempt_lock++;
12391 		} else if (preempt_enable) {
12392 			env->cur_state->active_preempt_lock--;
12393 		} else if (sleepable) {
12394 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
12395 			return -EACCES;
12396 		}
12397 	} else if (preempt_disable) {
12398 		env->cur_state->active_preempt_lock++;
12399 	} else if (preempt_enable) {
12400 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
12401 		return -EINVAL;
12402 	}
12403 
12404 	/* In case of release function, we get register number of refcounted
12405 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
12406 	 */
12407 	if (meta.release_regno) {
12408 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
12409 		if (err) {
12410 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12411 				func_name, meta.func_id);
12412 			return err;
12413 		}
12414 	}
12415 
12416 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12417 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12418 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12419 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
12420 		insn_aux->insert_off = regs[BPF_REG_2].off;
12421 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
12422 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
12423 		if (err) {
12424 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
12425 				func_name, meta.func_id);
12426 			return err;
12427 		}
12428 
12429 		err = release_reference(env, release_ref_obj_id);
12430 		if (err) {
12431 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
12432 				func_name, meta.func_id);
12433 			return err;
12434 		}
12435 	}
12436 
12437 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12438 		if (!bpf_jit_supports_exceptions()) {
12439 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
12440 				func_name, meta.func_id);
12441 			return -ENOTSUPP;
12442 		}
12443 		env->seen_exception = true;
12444 
12445 		/* In the case of the default callback, the cookie value passed
12446 		 * to bpf_throw becomes the return value of the program.
12447 		 */
12448 		if (!env->exception_callback_subprog) {
12449 			err = check_return_code(env, BPF_REG_1, "R1");
12450 			if (err < 0)
12451 				return err;
12452 		}
12453 	}
12454 
12455 	for (i = 0; i < CALLER_SAVED_REGS; i++)
12456 		mark_reg_not_init(env, regs, caller_saved[i]);
12457 
12458 	/* Check return type */
12459 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12460 
12461 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12462 		/* Only exception is bpf_obj_new_impl */
12463 		if (meta.btf != btf_vmlinux ||
12464 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12465 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12466 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12467 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12468 			return -EINVAL;
12469 		}
12470 	}
12471 
12472 	if (btf_type_is_scalar(t)) {
12473 		mark_reg_unknown(env, regs, BPF_REG_0);
12474 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12475 	} else if (btf_type_is_ptr(t)) {
12476 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12477 
12478 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12479 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12480 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12481 				struct btf_struct_meta *struct_meta;
12482 				struct btf *ret_btf;
12483 				u32 ret_btf_id;
12484 
12485 				if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12486 					return -ENOMEM;
12487 
12488 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12489 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12490 					return -EINVAL;
12491 				}
12492 
12493 				ret_btf = env->prog->aux->btf;
12494 				ret_btf_id = meta.arg_constant.value;
12495 
12496 				/* This may be NULL due to user not supplying a BTF */
12497 				if (!ret_btf) {
12498 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12499 					return -EINVAL;
12500 				}
12501 
12502 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12503 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
12504 					verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12505 					return -EINVAL;
12506 				}
12507 
12508 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12509 					if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
12510 						verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
12511 							ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
12512 						return -EINVAL;
12513 					}
12514 
12515 					if (!bpf_global_percpu_ma_set) {
12516 						mutex_lock(&bpf_percpu_ma_lock);
12517 						if (!bpf_global_percpu_ma_set) {
12518 							/* Charge memory allocated with bpf_global_percpu_ma to
12519 							 * root memcg. The obj_cgroup for root memcg is NULL.
12520 							 */
12521 							err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
12522 							if (!err)
12523 								bpf_global_percpu_ma_set = true;
12524 						}
12525 						mutex_unlock(&bpf_percpu_ma_lock);
12526 						if (err)
12527 							return err;
12528 					}
12529 
12530 					mutex_lock(&bpf_percpu_ma_lock);
12531 					err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
12532 					mutex_unlock(&bpf_percpu_ma_lock);
12533 					if (err)
12534 						return err;
12535 				}
12536 
12537 				struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12538 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12539 					if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12540 						verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12541 						return -EINVAL;
12542 					}
12543 
12544 					if (struct_meta) {
12545 						verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12546 						return -EINVAL;
12547 					}
12548 				}
12549 
12550 				mark_reg_known_zero(env, regs, BPF_REG_0);
12551 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12552 				regs[BPF_REG_0].btf = ret_btf;
12553 				regs[BPF_REG_0].btf_id = ret_btf_id;
12554 				if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12555 					regs[BPF_REG_0].type |= MEM_PERCPU;
12556 
12557 				insn_aux->obj_new_size = ret_t->size;
12558 				insn_aux->kptr_struct_meta = struct_meta;
12559 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12560 				mark_reg_known_zero(env, regs, BPF_REG_0);
12561 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12562 				regs[BPF_REG_0].btf = meta.arg_btf;
12563 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12564 
12565 				insn_aux->kptr_struct_meta =
12566 					btf_find_struct_meta(meta.arg_btf,
12567 							     meta.arg_btf_id);
12568 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12569 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12570 				struct btf_field *field = meta.arg_list_head.field;
12571 
12572 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12573 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12574 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12575 				struct btf_field *field = meta.arg_rbtree_root.field;
12576 
12577 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12578 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12579 				mark_reg_known_zero(env, regs, BPF_REG_0);
12580 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12581 				regs[BPF_REG_0].btf = desc_btf;
12582 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12583 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12584 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12585 				if (!ret_t || !btf_type_is_struct(ret_t)) {
12586 					verbose(env,
12587 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12588 					return -EINVAL;
12589 				}
12590 
12591 				mark_reg_known_zero(env, regs, BPF_REG_0);
12592 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12593 				regs[BPF_REG_0].btf = desc_btf;
12594 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12595 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12596 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12597 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12598 
12599 				mark_reg_known_zero(env, regs, BPF_REG_0);
12600 
12601 				if (!meta.arg_constant.found) {
12602 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12603 					return -EFAULT;
12604 				}
12605 
12606 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12607 
12608 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12609 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12610 
12611 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12612 					regs[BPF_REG_0].type |= MEM_RDONLY;
12613 				} else {
12614 					/* this will set env->seen_direct_write to true */
12615 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12616 						verbose(env, "the prog does not allow writes to packet data\n");
12617 						return -EINVAL;
12618 					}
12619 				}
12620 
12621 				if (!meta.initialized_dynptr.id) {
12622 					verbose(env, "verifier internal error: no dynptr id\n");
12623 					return -EFAULT;
12624 				}
12625 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12626 
12627 				/* we don't need to set BPF_REG_0's ref obj id
12628 				 * because packet slices are not refcounted (see
12629 				 * dynptr_type_refcounted)
12630 				 */
12631 			} else {
12632 				verbose(env, "kernel function %s unhandled dynamic return type\n",
12633 					meta.func_name);
12634 				return -EFAULT;
12635 			}
12636 		} else if (btf_type_is_void(ptr_type)) {
12637 			/* kfunc returning 'void *' is equivalent to returning scalar */
12638 			mark_reg_unknown(env, regs, BPF_REG_0);
12639 		} else if (!__btf_type_is_struct(ptr_type)) {
12640 			if (!meta.r0_size) {
12641 				__u32 sz;
12642 
12643 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12644 					meta.r0_size = sz;
12645 					meta.r0_rdonly = true;
12646 				}
12647 			}
12648 			if (!meta.r0_size) {
12649 				ptr_type_name = btf_name_by_offset(desc_btf,
12650 								   ptr_type->name_off);
12651 				verbose(env,
12652 					"kernel function %s returns pointer type %s %s is not supported\n",
12653 					func_name,
12654 					btf_type_str(ptr_type),
12655 					ptr_type_name);
12656 				return -EINVAL;
12657 			}
12658 
12659 			mark_reg_known_zero(env, regs, BPF_REG_0);
12660 			regs[BPF_REG_0].type = PTR_TO_MEM;
12661 			regs[BPF_REG_0].mem_size = meta.r0_size;
12662 
12663 			if (meta.r0_rdonly)
12664 				regs[BPF_REG_0].type |= MEM_RDONLY;
12665 
12666 			/* Ensures we don't access the memory after a release_reference() */
12667 			if (meta.ref_obj_id)
12668 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12669 		} else {
12670 			mark_reg_known_zero(env, regs, BPF_REG_0);
12671 			regs[BPF_REG_0].btf = desc_btf;
12672 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12673 			regs[BPF_REG_0].btf_id = ptr_type_id;
12674 		}
12675 
12676 		if (is_kfunc_ret_null(&meta)) {
12677 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12678 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12679 			regs[BPF_REG_0].id = ++env->id_gen;
12680 		}
12681 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12682 		if (is_kfunc_acquire(&meta)) {
12683 			int id = acquire_reference_state(env, insn_idx);
12684 
12685 			if (id < 0)
12686 				return id;
12687 			if (is_kfunc_ret_null(&meta))
12688 				regs[BPF_REG_0].id = id;
12689 			regs[BPF_REG_0].ref_obj_id = id;
12690 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12691 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12692 		}
12693 
12694 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12695 			regs[BPF_REG_0].id = ++env->id_gen;
12696 	} else if (btf_type_is_void(t)) {
12697 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12698 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12699 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12700 				insn_aux->kptr_struct_meta =
12701 					btf_find_struct_meta(meta.arg_btf,
12702 							     meta.arg_btf_id);
12703 			}
12704 		}
12705 	}
12706 
12707 	nargs = btf_type_vlen(meta.func_proto);
12708 	args = (const struct btf_param *)(meta.func_proto + 1);
12709 	for (i = 0; i < nargs; i++) {
12710 		u32 regno = i + 1;
12711 
12712 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12713 		if (btf_type_is_ptr(t))
12714 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12715 		else
12716 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12717 			mark_btf_func_reg_size(env, regno, t->size);
12718 	}
12719 
12720 	if (is_iter_next_kfunc(&meta)) {
12721 		err = process_iter_next_call(env, insn_idx, &meta);
12722 		if (err)
12723 			return err;
12724 	}
12725 
12726 	return 0;
12727 }
12728 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)12729 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12730 				  const struct bpf_reg_state *reg,
12731 				  enum bpf_reg_type type)
12732 {
12733 	bool known = tnum_is_const(reg->var_off);
12734 	s64 val = reg->var_off.value;
12735 	s64 smin = reg->smin_value;
12736 
12737 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12738 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12739 			reg_type_str(env, type), val);
12740 		return false;
12741 	}
12742 
12743 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12744 		verbose(env, "%s pointer offset %d is not allowed\n",
12745 			reg_type_str(env, type), reg->off);
12746 		return false;
12747 	}
12748 
12749 	if (smin == S64_MIN) {
12750 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12751 			reg_type_str(env, type));
12752 		return false;
12753 	}
12754 
12755 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12756 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12757 			smin, reg_type_str(env, type));
12758 		return false;
12759 	}
12760 
12761 	return true;
12762 }
12763 
12764 enum {
12765 	REASON_BOUNDS	= -1,
12766 	REASON_TYPE	= -2,
12767 	REASON_PATHS	= -3,
12768 	REASON_LIMIT	= -4,
12769 	REASON_STACK	= -5,
12770 };
12771 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)12772 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12773 			      u32 *alu_limit, bool mask_to_left)
12774 {
12775 	u32 max = 0, ptr_limit = 0;
12776 
12777 	switch (ptr_reg->type) {
12778 	case PTR_TO_STACK:
12779 		/* Offset 0 is out-of-bounds, but acceptable start for the
12780 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12781 		 * offset where we would need to deal with min/max bounds is
12782 		 * currently prohibited for unprivileged.
12783 		 */
12784 		max = MAX_BPF_STACK + mask_to_left;
12785 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12786 		break;
12787 	case PTR_TO_MAP_VALUE:
12788 		max = ptr_reg->map_ptr->value_size;
12789 		ptr_limit = (mask_to_left ?
12790 			     ptr_reg->smin_value :
12791 			     ptr_reg->umax_value) + ptr_reg->off;
12792 		break;
12793 	default:
12794 		return REASON_TYPE;
12795 	}
12796 
12797 	if (ptr_limit >= max)
12798 		return REASON_LIMIT;
12799 	*alu_limit = ptr_limit;
12800 	return 0;
12801 }
12802 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)12803 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12804 				    const struct bpf_insn *insn)
12805 {
12806 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12807 }
12808 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)12809 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12810 				       u32 alu_state, u32 alu_limit)
12811 {
12812 	/* If we arrived here from different branches with different
12813 	 * state or limits to sanitize, then this won't work.
12814 	 */
12815 	if (aux->alu_state &&
12816 	    (aux->alu_state != alu_state ||
12817 	     aux->alu_limit != alu_limit))
12818 		return REASON_PATHS;
12819 
12820 	/* Corresponding fixup done in do_misc_fixups(). */
12821 	aux->alu_state = alu_state;
12822 	aux->alu_limit = alu_limit;
12823 	return 0;
12824 }
12825 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)12826 static int sanitize_val_alu(struct bpf_verifier_env *env,
12827 			    struct bpf_insn *insn)
12828 {
12829 	struct bpf_insn_aux_data *aux = cur_aux(env);
12830 
12831 	if (can_skip_alu_sanitation(env, insn))
12832 		return 0;
12833 
12834 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12835 }
12836 
sanitize_needed(u8 opcode)12837 static bool sanitize_needed(u8 opcode)
12838 {
12839 	return opcode == BPF_ADD || opcode == BPF_SUB;
12840 }
12841 
12842 struct bpf_sanitize_info {
12843 	struct bpf_insn_aux_data aux;
12844 	bool mask_to_left;
12845 };
12846 
12847 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)12848 sanitize_speculative_path(struct bpf_verifier_env *env,
12849 			  const struct bpf_insn *insn,
12850 			  u32 next_idx, u32 curr_idx)
12851 {
12852 	struct bpf_verifier_state *branch;
12853 	struct bpf_reg_state *regs;
12854 
12855 	branch = push_stack(env, next_idx, curr_idx, true);
12856 	if (branch && insn) {
12857 		regs = branch->frame[branch->curframe]->regs;
12858 		if (BPF_SRC(insn->code) == BPF_K) {
12859 			mark_reg_unknown(env, regs, insn->dst_reg);
12860 		} else if (BPF_SRC(insn->code) == BPF_X) {
12861 			mark_reg_unknown(env, regs, insn->dst_reg);
12862 			mark_reg_unknown(env, regs, insn->src_reg);
12863 		}
12864 	}
12865 	return branch;
12866 }
12867 
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)12868 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12869 			    struct bpf_insn *insn,
12870 			    const struct bpf_reg_state *ptr_reg,
12871 			    const struct bpf_reg_state *off_reg,
12872 			    struct bpf_reg_state *dst_reg,
12873 			    struct bpf_sanitize_info *info,
12874 			    const bool commit_window)
12875 {
12876 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12877 	struct bpf_verifier_state *vstate = env->cur_state;
12878 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12879 	bool off_is_neg = off_reg->smin_value < 0;
12880 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12881 	u8 opcode = BPF_OP(insn->code);
12882 	u32 alu_state, alu_limit;
12883 	struct bpf_reg_state tmp;
12884 	bool ret;
12885 	int err;
12886 
12887 	if (can_skip_alu_sanitation(env, insn))
12888 		return 0;
12889 
12890 	/* We already marked aux for masking from non-speculative
12891 	 * paths, thus we got here in the first place. We only care
12892 	 * to explore bad access from here.
12893 	 */
12894 	if (vstate->speculative)
12895 		goto do_sim;
12896 
12897 	if (!commit_window) {
12898 		if (!tnum_is_const(off_reg->var_off) &&
12899 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12900 			return REASON_BOUNDS;
12901 
12902 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12903 				     (opcode == BPF_SUB && !off_is_neg);
12904 	}
12905 
12906 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12907 	if (err < 0)
12908 		return err;
12909 
12910 	if (commit_window) {
12911 		/* In commit phase we narrow the masking window based on
12912 		 * the observed pointer move after the simulated operation.
12913 		 */
12914 		alu_state = info->aux.alu_state;
12915 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12916 	} else {
12917 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12918 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12919 		alu_state |= ptr_is_dst_reg ?
12920 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12921 
12922 		/* Limit pruning on unknown scalars to enable deep search for
12923 		 * potential masking differences from other program paths.
12924 		 */
12925 		if (!off_is_imm)
12926 			env->explore_alu_limits = true;
12927 	}
12928 
12929 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12930 	if (err < 0)
12931 		return err;
12932 do_sim:
12933 	/* If we're in commit phase, we're done here given we already
12934 	 * pushed the truncated dst_reg into the speculative verification
12935 	 * stack.
12936 	 *
12937 	 * Also, when register is a known constant, we rewrite register-based
12938 	 * operation to immediate-based, and thus do not need masking (and as
12939 	 * a consequence, do not need to simulate the zero-truncation either).
12940 	 */
12941 	if (commit_window || off_is_imm)
12942 		return 0;
12943 
12944 	/* Simulate and find potential out-of-bounds access under
12945 	 * speculative execution from truncation as a result of
12946 	 * masking when off was not within expected range. If off
12947 	 * sits in dst, then we temporarily need to move ptr there
12948 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12949 	 * for cases where we use K-based arithmetic in one direction
12950 	 * and truncated reg-based in the other in order to explore
12951 	 * bad access.
12952 	 */
12953 	if (!ptr_is_dst_reg) {
12954 		tmp = *dst_reg;
12955 		copy_register_state(dst_reg, ptr_reg);
12956 	}
12957 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12958 					env->insn_idx);
12959 	if (!ptr_is_dst_reg && ret)
12960 		*dst_reg = tmp;
12961 	return !ret ? REASON_STACK : 0;
12962 }
12963 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)12964 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12965 {
12966 	struct bpf_verifier_state *vstate = env->cur_state;
12967 
12968 	/* If we simulate paths under speculation, we don't update the
12969 	 * insn as 'seen' such that when we verify unreachable paths in
12970 	 * the non-speculative domain, sanitize_dead_code() can still
12971 	 * rewrite/sanitize them.
12972 	 */
12973 	if (!vstate->speculative)
12974 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12975 }
12976 
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)12977 static int sanitize_err(struct bpf_verifier_env *env,
12978 			const struct bpf_insn *insn, int reason,
12979 			const struct bpf_reg_state *off_reg,
12980 			const struct bpf_reg_state *dst_reg)
12981 {
12982 	static const char *err = "pointer arithmetic with it prohibited for !root";
12983 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12984 	u32 dst = insn->dst_reg, src = insn->src_reg;
12985 
12986 	switch (reason) {
12987 	case REASON_BOUNDS:
12988 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12989 			off_reg == dst_reg ? dst : src, err);
12990 		break;
12991 	case REASON_TYPE:
12992 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12993 			off_reg == dst_reg ? src : dst, err);
12994 		break;
12995 	case REASON_PATHS:
12996 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12997 			dst, op, err);
12998 		break;
12999 	case REASON_LIMIT:
13000 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
13001 			dst, op, err);
13002 		break;
13003 	case REASON_STACK:
13004 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
13005 			dst, err);
13006 		break;
13007 	default:
13008 		verbose(env, "verifier internal error: unknown reason (%d)\n",
13009 			reason);
13010 		break;
13011 	}
13012 
13013 	return -EACCES;
13014 }
13015 
13016 /* check that stack access falls within stack limits and that 'reg' doesn't
13017  * have a variable offset.
13018  *
13019  * Variable offset is prohibited for unprivileged mode for simplicity since it
13020  * requires corresponding support in Spectre masking for stack ALU.  See also
13021  * retrieve_ptr_limit().
13022  *
13023  *
13024  * 'off' includes 'reg->off'.
13025  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)13026 static int check_stack_access_for_ptr_arithmetic(
13027 				struct bpf_verifier_env *env,
13028 				int regno,
13029 				const struct bpf_reg_state *reg,
13030 				int off)
13031 {
13032 	if (!tnum_is_const(reg->var_off)) {
13033 		char tn_buf[48];
13034 
13035 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
13036 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
13037 			regno, tn_buf, off);
13038 		return -EACCES;
13039 	}
13040 
13041 	if (off >= 0 || off < -MAX_BPF_STACK) {
13042 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
13043 			"prohibited for !root; off=%d\n", regno, off);
13044 		return -EACCES;
13045 	}
13046 
13047 	return 0;
13048 }
13049 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)13050 static int sanitize_check_bounds(struct bpf_verifier_env *env,
13051 				 const struct bpf_insn *insn,
13052 				 const struct bpf_reg_state *dst_reg)
13053 {
13054 	u32 dst = insn->dst_reg;
13055 
13056 	/* For unprivileged we require that resulting offset must be in bounds
13057 	 * in order to be able to sanitize access later on.
13058 	 */
13059 	if (env->bypass_spec_v1)
13060 		return 0;
13061 
13062 	switch (dst_reg->type) {
13063 	case PTR_TO_STACK:
13064 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
13065 					dst_reg->off + dst_reg->var_off.value))
13066 			return -EACCES;
13067 		break;
13068 	case PTR_TO_MAP_VALUE:
13069 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
13070 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
13071 				"prohibited for !root\n", dst);
13072 			return -EACCES;
13073 		}
13074 		break;
13075 	default:
13076 		break;
13077 	}
13078 
13079 	return 0;
13080 }
13081 
13082 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
13083  * Caller should also handle BPF_MOV case separately.
13084  * If we return -EACCES, caller may want to try again treating pointer as a
13085  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
13086  */
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)13087 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
13088 				   struct bpf_insn *insn,
13089 				   const struct bpf_reg_state *ptr_reg,
13090 				   const struct bpf_reg_state *off_reg)
13091 {
13092 	struct bpf_verifier_state *vstate = env->cur_state;
13093 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13094 	struct bpf_reg_state *regs = state->regs, *dst_reg;
13095 	bool known = tnum_is_const(off_reg->var_off);
13096 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
13097 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
13098 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
13099 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
13100 	struct bpf_sanitize_info info = {};
13101 	u8 opcode = BPF_OP(insn->code);
13102 	u32 dst = insn->dst_reg;
13103 	int ret;
13104 
13105 	dst_reg = &regs[dst];
13106 
13107 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
13108 	    smin_val > smax_val || umin_val > umax_val) {
13109 		/* Taint dst register if offset had invalid bounds derived from
13110 		 * e.g. dead branches.
13111 		 */
13112 		__mark_reg_unknown(env, dst_reg);
13113 		return 0;
13114 	}
13115 
13116 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
13117 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
13118 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13119 			__mark_reg_unknown(env, dst_reg);
13120 			return 0;
13121 		}
13122 
13123 		verbose(env,
13124 			"R%d 32-bit pointer arithmetic prohibited\n",
13125 			dst);
13126 		return -EACCES;
13127 	}
13128 
13129 	if (ptr_reg->type & PTR_MAYBE_NULL) {
13130 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
13131 			dst, reg_type_str(env, ptr_reg->type));
13132 		return -EACCES;
13133 	}
13134 
13135 	switch (base_type(ptr_reg->type)) {
13136 	case PTR_TO_CTX:
13137 	case PTR_TO_MAP_VALUE:
13138 	case PTR_TO_MAP_KEY:
13139 	case PTR_TO_STACK:
13140 	case PTR_TO_PACKET_META:
13141 	case PTR_TO_PACKET:
13142 	case PTR_TO_TP_BUFFER:
13143 	case PTR_TO_BTF_ID:
13144 	case PTR_TO_MEM:
13145 	case PTR_TO_BUF:
13146 	case PTR_TO_FUNC:
13147 	case CONST_PTR_TO_DYNPTR:
13148 		break;
13149 	case PTR_TO_FLOW_KEYS:
13150 		if (known)
13151 			break;
13152 		fallthrough;
13153 	case CONST_PTR_TO_MAP:
13154 		/* smin_val represents the known value */
13155 		if (known && smin_val == 0 && opcode == BPF_ADD)
13156 			break;
13157 		fallthrough;
13158 	default:
13159 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
13160 			dst, reg_type_str(env, ptr_reg->type));
13161 		return -EACCES;
13162 	}
13163 
13164 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
13165 	 * The id may be overwritten later if we create a new variable offset.
13166 	 */
13167 	dst_reg->type = ptr_reg->type;
13168 	dst_reg->id = ptr_reg->id;
13169 
13170 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
13171 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
13172 		return -EINVAL;
13173 
13174 	/* pointer types do not carry 32-bit bounds at the moment. */
13175 	__mark_reg32_unbounded(dst_reg);
13176 
13177 	if (sanitize_needed(opcode)) {
13178 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
13179 				       &info, false);
13180 		if (ret < 0)
13181 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13182 	}
13183 
13184 	switch (opcode) {
13185 	case BPF_ADD:
13186 		/* We can take a fixed offset as long as it doesn't overflow
13187 		 * the s32 'off' field
13188 		 */
13189 		if (known && (ptr_reg->off + smin_val ==
13190 			      (s64)(s32)(ptr_reg->off + smin_val))) {
13191 			/* pointer += K.  Accumulate it into fixed offset */
13192 			dst_reg->smin_value = smin_ptr;
13193 			dst_reg->smax_value = smax_ptr;
13194 			dst_reg->umin_value = umin_ptr;
13195 			dst_reg->umax_value = umax_ptr;
13196 			dst_reg->var_off = ptr_reg->var_off;
13197 			dst_reg->off = ptr_reg->off + smin_val;
13198 			dst_reg->raw = ptr_reg->raw;
13199 			break;
13200 		}
13201 		/* A new variable offset is created.  Note that off_reg->off
13202 		 * == 0, since it's a scalar.
13203 		 * dst_reg gets the pointer type and since some positive
13204 		 * integer value was added to the pointer, give it a new 'id'
13205 		 * if it's a PTR_TO_PACKET.
13206 		 * this creates a new 'base' pointer, off_reg (variable) gets
13207 		 * added into the variable offset, and we copy the fixed offset
13208 		 * from ptr_reg.
13209 		 */
13210 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
13211 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
13212 			dst_reg->smin_value = S64_MIN;
13213 			dst_reg->smax_value = S64_MAX;
13214 		}
13215 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
13216 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
13217 			dst_reg->umin_value = 0;
13218 			dst_reg->umax_value = U64_MAX;
13219 		}
13220 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
13221 		dst_reg->off = ptr_reg->off;
13222 		dst_reg->raw = ptr_reg->raw;
13223 		if (reg_is_pkt_pointer(ptr_reg)) {
13224 			dst_reg->id = ++env->id_gen;
13225 			/* something was added to pkt_ptr, set range to zero */
13226 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13227 		}
13228 		break;
13229 	case BPF_SUB:
13230 		if (dst_reg == off_reg) {
13231 			/* scalar -= pointer.  Creates an unknown scalar */
13232 			verbose(env, "R%d tried to subtract pointer from scalar\n",
13233 				dst);
13234 			return -EACCES;
13235 		}
13236 		/* We don't allow subtraction from FP, because (according to
13237 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
13238 		 * be able to deal with it.
13239 		 */
13240 		if (ptr_reg->type == PTR_TO_STACK) {
13241 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
13242 				dst);
13243 			return -EACCES;
13244 		}
13245 		if (known && (ptr_reg->off - smin_val ==
13246 			      (s64)(s32)(ptr_reg->off - smin_val))) {
13247 			/* pointer -= K.  Subtract it from fixed offset */
13248 			dst_reg->smin_value = smin_ptr;
13249 			dst_reg->smax_value = smax_ptr;
13250 			dst_reg->umin_value = umin_ptr;
13251 			dst_reg->umax_value = umax_ptr;
13252 			dst_reg->var_off = ptr_reg->var_off;
13253 			dst_reg->id = ptr_reg->id;
13254 			dst_reg->off = ptr_reg->off - smin_val;
13255 			dst_reg->raw = ptr_reg->raw;
13256 			break;
13257 		}
13258 		/* A new variable offset is created.  If the subtrahend is known
13259 		 * nonnegative, then any reg->range we had before is still good.
13260 		 */
13261 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
13262 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
13263 			/* Overflow possible, we know nothing */
13264 			dst_reg->smin_value = S64_MIN;
13265 			dst_reg->smax_value = S64_MAX;
13266 		}
13267 		if (umin_ptr < umax_val) {
13268 			/* Overflow possible, we know nothing */
13269 			dst_reg->umin_value = 0;
13270 			dst_reg->umax_value = U64_MAX;
13271 		} else {
13272 			/* Cannot overflow (as long as bounds are consistent) */
13273 			dst_reg->umin_value = umin_ptr - umax_val;
13274 			dst_reg->umax_value = umax_ptr - umin_val;
13275 		}
13276 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
13277 		dst_reg->off = ptr_reg->off;
13278 		dst_reg->raw = ptr_reg->raw;
13279 		if (reg_is_pkt_pointer(ptr_reg)) {
13280 			dst_reg->id = ++env->id_gen;
13281 			/* something was added to pkt_ptr, set range to zero */
13282 			if (smin_val < 0)
13283 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
13284 		}
13285 		break;
13286 	case BPF_AND:
13287 	case BPF_OR:
13288 	case BPF_XOR:
13289 		/* bitwise ops on pointers are troublesome, prohibit. */
13290 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
13291 			dst, bpf_alu_string[opcode >> 4]);
13292 		return -EACCES;
13293 	default:
13294 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
13295 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
13296 			dst, bpf_alu_string[opcode >> 4]);
13297 		return -EACCES;
13298 	}
13299 
13300 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
13301 		return -EINVAL;
13302 	reg_bounds_sync(dst_reg);
13303 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
13304 		return -EACCES;
13305 	if (sanitize_needed(opcode)) {
13306 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
13307 				       &info, true);
13308 		if (ret < 0)
13309 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
13310 	}
13311 
13312 	return 0;
13313 }
13314 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13315 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
13316 				 struct bpf_reg_state *src_reg)
13317 {
13318 	s32 *dst_smin = &dst_reg->s32_min_value;
13319 	s32 *dst_smax = &dst_reg->s32_max_value;
13320 	u32 *dst_umin = &dst_reg->u32_min_value;
13321 	u32 *dst_umax = &dst_reg->u32_max_value;
13322 
13323 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
13324 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
13325 		*dst_smin = S32_MIN;
13326 		*dst_smax = S32_MAX;
13327 	}
13328 	if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) ||
13329 	    check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) {
13330 		*dst_umin = 0;
13331 		*dst_umax = U32_MAX;
13332 	}
13333 }
13334 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13335 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
13336 			       struct bpf_reg_state *src_reg)
13337 {
13338 	s64 *dst_smin = &dst_reg->smin_value;
13339 	s64 *dst_smax = &dst_reg->smax_value;
13340 	u64 *dst_umin = &dst_reg->umin_value;
13341 	u64 *dst_umax = &dst_reg->umax_value;
13342 
13343 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
13344 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
13345 		*dst_smin = S64_MIN;
13346 		*dst_smax = S64_MAX;
13347 	}
13348 	if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) ||
13349 	    check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) {
13350 		*dst_umin = 0;
13351 		*dst_umax = U64_MAX;
13352 	}
13353 }
13354 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13355 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
13356 				 struct bpf_reg_state *src_reg)
13357 {
13358 	s32 *dst_smin = &dst_reg->s32_min_value;
13359 	s32 *dst_smax = &dst_reg->s32_max_value;
13360 	u32 umin_val = src_reg->u32_min_value;
13361 	u32 umax_val = src_reg->u32_max_value;
13362 
13363 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
13364 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
13365 		/* Overflow possible, we know nothing */
13366 		*dst_smin = S32_MIN;
13367 		*dst_smax = S32_MAX;
13368 	}
13369 	if (dst_reg->u32_min_value < umax_val) {
13370 		/* Overflow possible, we know nothing */
13371 		dst_reg->u32_min_value = 0;
13372 		dst_reg->u32_max_value = U32_MAX;
13373 	} else {
13374 		/* Cannot overflow (as long as bounds are consistent) */
13375 		dst_reg->u32_min_value -= umax_val;
13376 		dst_reg->u32_max_value -= umin_val;
13377 	}
13378 }
13379 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13380 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
13381 			       struct bpf_reg_state *src_reg)
13382 {
13383 	s64 *dst_smin = &dst_reg->smin_value;
13384 	s64 *dst_smax = &dst_reg->smax_value;
13385 	u64 umin_val = src_reg->umin_value;
13386 	u64 umax_val = src_reg->umax_value;
13387 
13388 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
13389 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
13390 		/* Overflow possible, we know nothing */
13391 		*dst_smin = S64_MIN;
13392 		*dst_smax = S64_MAX;
13393 	}
13394 	if (dst_reg->umin_value < umax_val) {
13395 		/* Overflow possible, we know nothing */
13396 		dst_reg->umin_value = 0;
13397 		dst_reg->umax_value = U64_MAX;
13398 	} else {
13399 		/* Cannot overflow (as long as bounds are consistent) */
13400 		dst_reg->umin_value -= umax_val;
13401 		dst_reg->umax_value -= umin_val;
13402 	}
13403 }
13404 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13405 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13406 				 struct bpf_reg_state *src_reg)
13407 {
13408 	s32 smin_val = src_reg->s32_min_value;
13409 	u32 umin_val = src_reg->u32_min_value;
13410 	u32 umax_val = src_reg->u32_max_value;
13411 
13412 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13413 		/* Ain't nobody got time to multiply that sign */
13414 		__mark_reg32_unbounded(dst_reg);
13415 		return;
13416 	}
13417 	/* Both values are positive, so we can work with unsigned and
13418 	 * copy the result to signed (unless it exceeds S32_MAX).
13419 	 */
13420 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13421 		/* Potential overflow, we know nothing */
13422 		__mark_reg32_unbounded(dst_reg);
13423 		return;
13424 	}
13425 	dst_reg->u32_min_value *= umin_val;
13426 	dst_reg->u32_max_value *= umax_val;
13427 	if (dst_reg->u32_max_value > S32_MAX) {
13428 		/* Overflow possible, we know nothing */
13429 		dst_reg->s32_min_value = S32_MIN;
13430 		dst_reg->s32_max_value = S32_MAX;
13431 	} else {
13432 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13433 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13434 	}
13435 }
13436 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13437 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13438 			       struct bpf_reg_state *src_reg)
13439 {
13440 	s64 smin_val = src_reg->smin_value;
13441 	u64 umin_val = src_reg->umin_value;
13442 	u64 umax_val = src_reg->umax_value;
13443 
13444 	if (smin_val < 0 || dst_reg->smin_value < 0) {
13445 		/* Ain't nobody got time to multiply that sign */
13446 		__mark_reg64_unbounded(dst_reg);
13447 		return;
13448 	}
13449 	/* Both values are positive, so we can work with unsigned and
13450 	 * copy the result to signed (unless it exceeds S64_MAX).
13451 	 */
13452 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13453 		/* Potential overflow, we know nothing */
13454 		__mark_reg64_unbounded(dst_reg);
13455 		return;
13456 	}
13457 	dst_reg->umin_value *= umin_val;
13458 	dst_reg->umax_value *= umax_val;
13459 	if (dst_reg->umax_value > S64_MAX) {
13460 		/* Overflow possible, we know nothing */
13461 		dst_reg->smin_value = S64_MIN;
13462 		dst_reg->smax_value = S64_MAX;
13463 	} else {
13464 		dst_reg->smin_value = dst_reg->umin_value;
13465 		dst_reg->smax_value = dst_reg->umax_value;
13466 	}
13467 }
13468 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13469 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13470 				 struct bpf_reg_state *src_reg)
13471 {
13472 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13473 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13474 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13475 	u32 umax_val = src_reg->u32_max_value;
13476 
13477 	if (src_known && dst_known) {
13478 		__mark_reg32_known(dst_reg, var32_off.value);
13479 		return;
13480 	}
13481 
13482 	/* We get our minimum from the var_off, since that's inherently
13483 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13484 	 */
13485 	dst_reg->u32_min_value = var32_off.value;
13486 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13487 
13488 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13489 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13490 	 */
13491 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13492 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13493 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13494 	} else {
13495 		dst_reg->s32_min_value = S32_MIN;
13496 		dst_reg->s32_max_value = S32_MAX;
13497 	}
13498 }
13499 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13500 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13501 			       struct bpf_reg_state *src_reg)
13502 {
13503 	bool src_known = tnum_is_const(src_reg->var_off);
13504 	bool dst_known = tnum_is_const(dst_reg->var_off);
13505 	u64 umax_val = src_reg->umax_value;
13506 
13507 	if (src_known && dst_known) {
13508 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13509 		return;
13510 	}
13511 
13512 	/* We get our minimum from the var_off, since that's inherently
13513 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
13514 	 */
13515 	dst_reg->umin_value = dst_reg->var_off.value;
13516 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13517 
13518 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13519 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13520 	 */
13521 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13522 		dst_reg->smin_value = dst_reg->umin_value;
13523 		dst_reg->smax_value = dst_reg->umax_value;
13524 	} else {
13525 		dst_reg->smin_value = S64_MIN;
13526 		dst_reg->smax_value = S64_MAX;
13527 	}
13528 	/* We may learn something more from the var_off */
13529 	__update_reg_bounds(dst_reg);
13530 }
13531 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13532 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13533 				struct bpf_reg_state *src_reg)
13534 {
13535 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13536 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13537 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13538 	u32 umin_val = src_reg->u32_min_value;
13539 
13540 	if (src_known && dst_known) {
13541 		__mark_reg32_known(dst_reg, var32_off.value);
13542 		return;
13543 	}
13544 
13545 	/* We get our maximum from the var_off, and our minimum is the
13546 	 * maximum of the operands' minima
13547 	 */
13548 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13549 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13550 
13551 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13552 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13553 	 */
13554 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13555 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13556 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13557 	} else {
13558 		dst_reg->s32_min_value = S32_MIN;
13559 		dst_reg->s32_max_value = S32_MAX;
13560 	}
13561 }
13562 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13563 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13564 			      struct bpf_reg_state *src_reg)
13565 {
13566 	bool src_known = tnum_is_const(src_reg->var_off);
13567 	bool dst_known = tnum_is_const(dst_reg->var_off);
13568 	u64 umin_val = src_reg->umin_value;
13569 
13570 	if (src_known && dst_known) {
13571 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13572 		return;
13573 	}
13574 
13575 	/* We get our maximum from the var_off, and our minimum is the
13576 	 * maximum of the operands' minima
13577 	 */
13578 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13579 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13580 
13581 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13582 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13583 	 */
13584 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13585 		dst_reg->smin_value = dst_reg->umin_value;
13586 		dst_reg->smax_value = dst_reg->umax_value;
13587 	} else {
13588 		dst_reg->smin_value = S64_MIN;
13589 		dst_reg->smax_value = S64_MAX;
13590 	}
13591 	/* We may learn something more from the var_off */
13592 	__update_reg_bounds(dst_reg);
13593 }
13594 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13595 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13596 				 struct bpf_reg_state *src_reg)
13597 {
13598 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13599 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13600 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13601 
13602 	if (src_known && dst_known) {
13603 		__mark_reg32_known(dst_reg, var32_off.value);
13604 		return;
13605 	}
13606 
13607 	/* We get both minimum and maximum from the var32_off. */
13608 	dst_reg->u32_min_value = var32_off.value;
13609 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13610 
13611 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
13612 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
13613 	 */
13614 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
13615 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13616 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13617 	} else {
13618 		dst_reg->s32_min_value = S32_MIN;
13619 		dst_reg->s32_max_value = S32_MAX;
13620 	}
13621 }
13622 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13623 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13624 			       struct bpf_reg_state *src_reg)
13625 {
13626 	bool src_known = tnum_is_const(src_reg->var_off);
13627 	bool dst_known = tnum_is_const(dst_reg->var_off);
13628 
13629 	if (src_known && dst_known) {
13630 		/* dst_reg->var_off.value has been updated earlier */
13631 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13632 		return;
13633 	}
13634 
13635 	/* We get both minimum and maximum from the var_off. */
13636 	dst_reg->umin_value = dst_reg->var_off.value;
13637 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13638 
13639 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
13640 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
13641 	 */
13642 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
13643 		dst_reg->smin_value = dst_reg->umin_value;
13644 		dst_reg->smax_value = dst_reg->umax_value;
13645 	} else {
13646 		dst_reg->smin_value = S64_MIN;
13647 		dst_reg->smax_value = S64_MAX;
13648 	}
13649 
13650 	__update_reg_bounds(dst_reg);
13651 }
13652 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13653 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13654 				   u64 umin_val, u64 umax_val)
13655 {
13656 	/* We lose all sign bit information (except what we can pick
13657 	 * up from var_off)
13658 	 */
13659 	dst_reg->s32_min_value = S32_MIN;
13660 	dst_reg->s32_max_value = S32_MAX;
13661 	/* If we might shift our top bit out, then we know nothing */
13662 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13663 		dst_reg->u32_min_value = 0;
13664 		dst_reg->u32_max_value = U32_MAX;
13665 	} else {
13666 		dst_reg->u32_min_value <<= umin_val;
13667 		dst_reg->u32_max_value <<= umax_val;
13668 	}
13669 }
13670 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13671 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13672 				 struct bpf_reg_state *src_reg)
13673 {
13674 	u32 umax_val = src_reg->u32_max_value;
13675 	u32 umin_val = src_reg->u32_min_value;
13676 	/* u32 alu operation will zext upper bits */
13677 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13678 
13679 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13680 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13681 	/* Not required but being careful mark reg64 bounds as unknown so
13682 	 * that we are forced to pick them up from tnum and zext later and
13683 	 * if some path skips this step we are still safe.
13684 	 */
13685 	__mark_reg64_unbounded(dst_reg);
13686 	__update_reg32_bounds(dst_reg);
13687 }
13688 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13689 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13690 				   u64 umin_val, u64 umax_val)
13691 {
13692 	/* Special case <<32 because it is a common compiler pattern to sign
13693 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13694 	 * positive we know this shift will also be positive so we can track
13695 	 * bounds correctly. Otherwise we lose all sign bit information except
13696 	 * what we can pick up from var_off. Perhaps we can generalize this
13697 	 * later to shifts of any length.
13698 	 */
13699 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13700 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13701 	else
13702 		dst_reg->smax_value = S64_MAX;
13703 
13704 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13705 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13706 	else
13707 		dst_reg->smin_value = S64_MIN;
13708 
13709 	/* If we might shift our top bit out, then we know nothing */
13710 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13711 		dst_reg->umin_value = 0;
13712 		dst_reg->umax_value = U64_MAX;
13713 	} else {
13714 		dst_reg->umin_value <<= umin_val;
13715 		dst_reg->umax_value <<= umax_val;
13716 	}
13717 }
13718 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13719 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13720 			       struct bpf_reg_state *src_reg)
13721 {
13722 	u64 umax_val = src_reg->umax_value;
13723 	u64 umin_val = src_reg->umin_value;
13724 
13725 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13726 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13727 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13728 
13729 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13730 	/* We may learn something more from the var_off */
13731 	__update_reg_bounds(dst_reg);
13732 }
13733 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13734 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13735 				 struct bpf_reg_state *src_reg)
13736 {
13737 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13738 	u32 umax_val = src_reg->u32_max_value;
13739 	u32 umin_val = src_reg->u32_min_value;
13740 
13741 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13742 	 * be negative, then either:
13743 	 * 1) src_reg might be zero, so the sign bit of the result is
13744 	 *    unknown, so we lose our signed bounds
13745 	 * 2) it's known negative, thus the unsigned bounds capture the
13746 	 *    signed bounds
13747 	 * 3) the signed bounds cross zero, so they tell us nothing
13748 	 *    about the result
13749 	 * If the value in dst_reg is known nonnegative, then again the
13750 	 * unsigned bounds capture the signed bounds.
13751 	 * Thus, in all cases it suffices to blow away our signed bounds
13752 	 * and rely on inferring new ones from the unsigned bounds and
13753 	 * var_off of the result.
13754 	 */
13755 	dst_reg->s32_min_value = S32_MIN;
13756 	dst_reg->s32_max_value = S32_MAX;
13757 
13758 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13759 	dst_reg->u32_min_value >>= umax_val;
13760 	dst_reg->u32_max_value >>= umin_val;
13761 
13762 	__mark_reg64_unbounded(dst_reg);
13763 	__update_reg32_bounds(dst_reg);
13764 }
13765 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13766 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13767 			       struct bpf_reg_state *src_reg)
13768 {
13769 	u64 umax_val = src_reg->umax_value;
13770 	u64 umin_val = src_reg->umin_value;
13771 
13772 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13773 	 * be negative, then either:
13774 	 * 1) src_reg might be zero, so the sign bit of the result is
13775 	 *    unknown, so we lose our signed bounds
13776 	 * 2) it's known negative, thus the unsigned bounds capture the
13777 	 *    signed bounds
13778 	 * 3) the signed bounds cross zero, so they tell us nothing
13779 	 *    about the result
13780 	 * If the value in dst_reg is known nonnegative, then again the
13781 	 * unsigned bounds capture the signed bounds.
13782 	 * Thus, in all cases it suffices to blow away our signed bounds
13783 	 * and rely on inferring new ones from the unsigned bounds and
13784 	 * var_off of the result.
13785 	 */
13786 	dst_reg->smin_value = S64_MIN;
13787 	dst_reg->smax_value = S64_MAX;
13788 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13789 	dst_reg->umin_value >>= umax_val;
13790 	dst_reg->umax_value >>= umin_val;
13791 
13792 	/* Its not easy to operate on alu32 bounds here because it depends
13793 	 * on bits being shifted in. Take easy way out and mark unbounded
13794 	 * so we can recalculate later from tnum.
13795 	 */
13796 	__mark_reg32_unbounded(dst_reg);
13797 	__update_reg_bounds(dst_reg);
13798 }
13799 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13800 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13801 				  struct bpf_reg_state *src_reg)
13802 {
13803 	u64 umin_val = src_reg->u32_min_value;
13804 
13805 	/* Upon reaching here, src_known is true and
13806 	 * umax_val is equal to umin_val.
13807 	 */
13808 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13809 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13810 
13811 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13812 
13813 	/* blow away the dst_reg umin_value/umax_value and rely on
13814 	 * dst_reg var_off to refine the result.
13815 	 */
13816 	dst_reg->u32_min_value = 0;
13817 	dst_reg->u32_max_value = U32_MAX;
13818 
13819 	__mark_reg64_unbounded(dst_reg);
13820 	__update_reg32_bounds(dst_reg);
13821 }
13822 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13823 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13824 				struct bpf_reg_state *src_reg)
13825 {
13826 	u64 umin_val = src_reg->umin_value;
13827 
13828 	/* Upon reaching here, src_known is true and umax_val is equal
13829 	 * to umin_val.
13830 	 */
13831 	dst_reg->smin_value >>= umin_val;
13832 	dst_reg->smax_value >>= umin_val;
13833 
13834 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13835 
13836 	/* blow away the dst_reg umin_value/umax_value and rely on
13837 	 * dst_reg var_off to refine the result.
13838 	 */
13839 	dst_reg->umin_value = 0;
13840 	dst_reg->umax_value = U64_MAX;
13841 
13842 	/* Its not easy to operate on alu32 bounds here because it depends
13843 	 * on bits being shifted in from upper 32-bits. Take easy way out
13844 	 * and mark unbounded so we can recalculate later from tnum.
13845 	 */
13846 	__mark_reg32_unbounded(dst_reg);
13847 	__update_reg_bounds(dst_reg);
13848 }
13849 
is_safe_to_compute_dst_reg_range(struct bpf_insn * insn,const struct bpf_reg_state * src_reg)13850 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
13851 					     const struct bpf_reg_state *src_reg)
13852 {
13853 	bool src_is_const = false;
13854 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13855 
13856 	if (insn_bitness == 32) {
13857 		if (tnum_subreg_is_const(src_reg->var_off)
13858 		    && src_reg->s32_min_value == src_reg->s32_max_value
13859 		    && src_reg->u32_min_value == src_reg->u32_max_value)
13860 			src_is_const = true;
13861 	} else {
13862 		if (tnum_is_const(src_reg->var_off)
13863 		    && src_reg->smin_value == src_reg->smax_value
13864 		    && src_reg->umin_value == src_reg->umax_value)
13865 			src_is_const = true;
13866 	}
13867 
13868 	switch (BPF_OP(insn->code)) {
13869 	case BPF_ADD:
13870 	case BPF_SUB:
13871 	case BPF_AND:
13872 	case BPF_XOR:
13873 	case BPF_OR:
13874 	case BPF_MUL:
13875 		return true;
13876 
13877 	/* Shift operators range is only computable if shift dimension operand
13878 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
13879 	 * includes shifts by a negative number.
13880 	 */
13881 	case BPF_LSH:
13882 	case BPF_RSH:
13883 	case BPF_ARSH:
13884 		return (src_is_const && src_reg->umax_value < insn_bitness);
13885 	default:
13886 		return false;
13887 	}
13888 }
13889 
13890 /* WARNING: This function does calculations on 64-bit values, but the actual
13891  * execution may occur on 32-bit values. Therefore, things like bitshifts
13892  * need extra checks in the 32-bit case.
13893  */
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)13894 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13895 				      struct bpf_insn *insn,
13896 				      struct bpf_reg_state *dst_reg,
13897 				      struct bpf_reg_state src_reg)
13898 {
13899 	u8 opcode = BPF_OP(insn->code);
13900 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13901 	int ret;
13902 
13903 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
13904 		__mark_reg_unknown(env, dst_reg);
13905 		return 0;
13906 	}
13907 
13908 	if (sanitize_needed(opcode)) {
13909 		ret = sanitize_val_alu(env, insn);
13910 		if (ret < 0)
13911 			return sanitize_err(env, insn, ret, NULL, NULL);
13912 	}
13913 
13914 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13915 	 * There are two classes of instructions: The first class we track both
13916 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13917 	 * greatest amount of precision when alu operations are mixed with jmp32
13918 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13919 	 * and BPF_OR. This is possible because these ops have fairly easy to
13920 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13921 	 * See alu32 verifier tests for examples. The second class of
13922 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13923 	 * with regards to tracking sign/unsigned bounds because the bits may
13924 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13925 	 * the reg unbounded in the subreg bound space and use the resulting
13926 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13927 	 */
13928 	switch (opcode) {
13929 	case BPF_ADD:
13930 		scalar32_min_max_add(dst_reg, &src_reg);
13931 		scalar_min_max_add(dst_reg, &src_reg);
13932 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13933 		break;
13934 	case BPF_SUB:
13935 		scalar32_min_max_sub(dst_reg, &src_reg);
13936 		scalar_min_max_sub(dst_reg, &src_reg);
13937 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13938 		break;
13939 	case BPF_MUL:
13940 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13941 		scalar32_min_max_mul(dst_reg, &src_reg);
13942 		scalar_min_max_mul(dst_reg, &src_reg);
13943 		break;
13944 	case BPF_AND:
13945 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13946 		scalar32_min_max_and(dst_reg, &src_reg);
13947 		scalar_min_max_and(dst_reg, &src_reg);
13948 		break;
13949 	case BPF_OR:
13950 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13951 		scalar32_min_max_or(dst_reg, &src_reg);
13952 		scalar_min_max_or(dst_reg, &src_reg);
13953 		break;
13954 	case BPF_XOR:
13955 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13956 		scalar32_min_max_xor(dst_reg, &src_reg);
13957 		scalar_min_max_xor(dst_reg, &src_reg);
13958 		break;
13959 	case BPF_LSH:
13960 		if (alu32)
13961 			scalar32_min_max_lsh(dst_reg, &src_reg);
13962 		else
13963 			scalar_min_max_lsh(dst_reg, &src_reg);
13964 		break;
13965 	case BPF_RSH:
13966 		if (alu32)
13967 			scalar32_min_max_rsh(dst_reg, &src_reg);
13968 		else
13969 			scalar_min_max_rsh(dst_reg, &src_reg);
13970 		break;
13971 	case BPF_ARSH:
13972 		if (alu32)
13973 			scalar32_min_max_arsh(dst_reg, &src_reg);
13974 		else
13975 			scalar_min_max_arsh(dst_reg, &src_reg);
13976 		break;
13977 	default:
13978 		break;
13979 	}
13980 
13981 	/* ALU32 ops are zero extended into 64bit register */
13982 	if (alu32)
13983 		zext_32_to_64(dst_reg);
13984 	reg_bounds_sync(dst_reg);
13985 	return 0;
13986 }
13987 
13988 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13989  * and var_off.
13990  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)13991 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13992 				   struct bpf_insn *insn)
13993 {
13994 	struct bpf_verifier_state *vstate = env->cur_state;
13995 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13996 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13997 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13998 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13999 	u8 opcode = BPF_OP(insn->code);
14000 	int err;
14001 
14002 	dst_reg = &regs[insn->dst_reg];
14003 	src_reg = NULL;
14004 
14005 	if (dst_reg->type == PTR_TO_ARENA) {
14006 		struct bpf_insn_aux_data *aux = cur_aux(env);
14007 
14008 		if (BPF_CLASS(insn->code) == BPF_ALU64)
14009 			/*
14010 			 * 32-bit operations zero upper bits automatically.
14011 			 * 64-bit operations need to be converted to 32.
14012 			 */
14013 			aux->needs_zext = true;
14014 
14015 		/* Any arithmetic operations are allowed on arena pointers */
14016 		return 0;
14017 	}
14018 
14019 	if (dst_reg->type != SCALAR_VALUE)
14020 		ptr_reg = dst_reg;
14021 
14022 	if (BPF_SRC(insn->code) == BPF_X) {
14023 		src_reg = &regs[insn->src_reg];
14024 		if (src_reg->type != SCALAR_VALUE) {
14025 			if (dst_reg->type != SCALAR_VALUE) {
14026 				/* Combining two pointers by any ALU op yields
14027 				 * an arbitrary scalar. Disallow all math except
14028 				 * pointer subtraction
14029 				 */
14030 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14031 					mark_reg_unknown(env, regs, insn->dst_reg);
14032 					return 0;
14033 				}
14034 				verbose(env, "R%d pointer %s pointer prohibited\n",
14035 					insn->dst_reg,
14036 					bpf_alu_string[opcode >> 4]);
14037 				return -EACCES;
14038 			} else {
14039 				/* scalar += pointer
14040 				 * This is legal, but we have to reverse our
14041 				 * src/dest handling in computing the range
14042 				 */
14043 				err = mark_chain_precision(env, insn->dst_reg);
14044 				if (err)
14045 					return err;
14046 				return adjust_ptr_min_max_vals(env, insn,
14047 							       src_reg, dst_reg);
14048 			}
14049 		} else if (ptr_reg) {
14050 			/* pointer += scalar */
14051 			err = mark_chain_precision(env, insn->src_reg);
14052 			if (err)
14053 				return err;
14054 			return adjust_ptr_min_max_vals(env, insn,
14055 						       dst_reg, src_reg);
14056 		} else if (dst_reg->precise) {
14057 			/* if dst_reg is precise, src_reg should be precise as well */
14058 			err = mark_chain_precision(env, insn->src_reg);
14059 			if (err)
14060 				return err;
14061 		}
14062 	} else {
14063 		/* Pretend the src is a reg with a known value, since we only
14064 		 * need to be able to read from this state.
14065 		 */
14066 		off_reg.type = SCALAR_VALUE;
14067 		__mark_reg_known(&off_reg, insn->imm);
14068 		src_reg = &off_reg;
14069 		if (ptr_reg) /* pointer += K */
14070 			return adjust_ptr_min_max_vals(env, insn,
14071 						       ptr_reg, src_reg);
14072 	}
14073 
14074 	/* Got here implies adding two SCALAR_VALUEs */
14075 	if (WARN_ON_ONCE(ptr_reg)) {
14076 		print_verifier_state(env, state, true);
14077 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
14078 		return -EINVAL;
14079 	}
14080 	if (WARN_ON(!src_reg)) {
14081 		print_verifier_state(env, state, true);
14082 		verbose(env, "verifier internal error: no src_reg\n");
14083 		return -EINVAL;
14084 	}
14085 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
14086 	if (err)
14087 		return err;
14088 	/*
14089 	 * Compilers can generate the code
14090 	 * r1 = r2
14091 	 * r1 += 0x1
14092 	 * if r2 < 1000 goto ...
14093 	 * use r1 in memory access
14094 	 * So remember constant delta between r2 and r1 and update r1 after
14095 	 * 'if' condition.
14096 	 */
14097 	if (env->bpf_capable && BPF_OP(insn->code) == BPF_ADD &&
14098 	    dst_reg->id && is_reg_const(src_reg, alu32)) {
14099 		u64 val = reg_const_value(src_reg, alu32);
14100 
14101 		if ((dst_reg->id & BPF_ADD_CONST) ||
14102 		    /* prevent overflow in find_equal_scalars() later */
14103 		    val > (u32)S32_MAX) {
14104 			/*
14105 			 * If the register already went through rX += val
14106 			 * we cannot accumulate another val into rx->off.
14107 			 */
14108 			dst_reg->off = 0;
14109 			dst_reg->id = 0;
14110 		} else {
14111 			dst_reg->id |= BPF_ADD_CONST;
14112 			dst_reg->off = val;
14113 		}
14114 	} else {
14115 		/*
14116 		 * Make sure ID is cleared otherwise dst_reg min/max could be
14117 		 * incorrectly propagated into other registers by find_equal_scalars()
14118 		 */
14119 		dst_reg->id = 0;
14120 	}
14121 	return 0;
14122 }
14123 
14124 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)14125 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
14126 {
14127 	struct bpf_reg_state *regs = cur_regs(env);
14128 	u8 opcode = BPF_OP(insn->code);
14129 	int err;
14130 
14131 	if (opcode == BPF_END || opcode == BPF_NEG) {
14132 		if (opcode == BPF_NEG) {
14133 			if (BPF_SRC(insn->code) != BPF_K ||
14134 			    insn->src_reg != BPF_REG_0 ||
14135 			    insn->off != 0 || insn->imm != 0) {
14136 				verbose(env, "BPF_NEG uses reserved fields\n");
14137 				return -EINVAL;
14138 			}
14139 		} else {
14140 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
14141 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
14142 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
14143 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
14144 				verbose(env, "BPF_END uses reserved fields\n");
14145 				return -EINVAL;
14146 			}
14147 		}
14148 
14149 		/* check src operand */
14150 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14151 		if (err)
14152 			return err;
14153 
14154 		if (is_pointer_value(env, insn->dst_reg)) {
14155 			verbose(env, "R%d pointer arithmetic prohibited\n",
14156 				insn->dst_reg);
14157 			return -EACCES;
14158 		}
14159 
14160 		/* check dest operand */
14161 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
14162 		if (err)
14163 			return err;
14164 
14165 	} else if (opcode == BPF_MOV) {
14166 
14167 		if (BPF_SRC(insn->code) == BPF_X) {
14168 			if (BPF_CLASS(insn->code) == BPF_ALU) {
14169 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
14170 				    insn->imm) {
14171 					verbose(env, "BPF_MOV uses reserved fields\n");
14172 					return -EINVAL;
14173 				}
14174 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
14175 				if (insn->imm != 1 && insn->imm != 1u << 16) {
14176 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
14177 					return -EINVAL;
14178 				}
14179 				if (!env->prog->aux->arena) {
14180 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
14181 					return -EINVAL;
14182 				}
14183 			} else {
14184 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
14185 				     insn->off != 32) || insn->imm) {
14186 					verbose(env, "BPF_MOV uses reserved fields\n");
14187 					return -EINVAL;
14188 				}
14189 			}
14190 
14191 			/* check src operand */
14192 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14193 			if (err)
14194 				return err;
14195 		} else {
14196 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
14197 				verbose(env, "BPF_MOV uses reserved fields\n");
14198 				return -EINVAL;
14199 			}
14200 		}
14201 
14202 		/* check dest operand, mark as required later */
14203 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14204 		if (err)
14205 			return err;
14206 
14207 		if (BPF_SRC(insn->code) == BPF_X) {
14208 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
14209 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
14210 
14211 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14212 				if (insn->imm) {
14213 					/* off == BPF_ADDR_SPACE_CAST */
14214 					mark_reg_unknown(env, regs, insn->dst_reg);
14215 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
14216 						dst_reg->type = PTR_TO_ARENA;
14217 						/* PTR_TO_ARENA is 32-bit */
14218 						dst_reg->subreg_def = env->insn_idx + 1;
14219 					}
14220 				} else if (insn->off == 0) {
14221 					/* case: R1 = R2
14222 					 * copy register state to dest reg
14223 					 */
14224 					assign_scalar_id_before_mov(env, src_reg);
14225 					copy_register_state(dst_reg, src_reg);
14226 					dst_reg->live |= REG_LIVE_WRITTEN;
14227 					dst_reg->subreg_def = DEF_NOT_SUBREG;
14228 				} else {
14229 					/* case: R1 = (s8, s16 s32)R2 */
14230 					if (is_pointer_value(env, insn->src_reg)) {
14231 						verbose(env,
14232 							"R%d sign-extension part of pointer\n",
14233 							insn->src_reg);
14234 						return -EACCES;
14235 					} else if (src_reg->type == SCALAR_VALUE) {
14236 						bool no_sext;
14237 
14238 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14239 						if (no_sext)
14240 							assign_scalar_id_before_mov(env, src_reg);
14241 						copy_register_state(dst_reg, src_reg);
14242 						if (!no_sext)
14243 							dst_reg->id = 0;
14244 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
14245 						dst_reg->live |= REG_LIVE_WRITTEN;
14246 						dst_reg->subreg_def = DEF_NOT_SUBREG;
14247 					} else {
14248 						mark_reg_unknown(env, regs, insn->dst_reg);
14249 					}
14250 				}
14251 			} else {
14252 				/* R1 = (u32) R2 */
14253 				if (is_pointer_value(env, insn->src_reg)) {
14254 					verbose(env,
14255 						"R%d partial copy of pointer\n",
14256 						insn->src_reg);
14257 					return -EACCES;
14258 				} else if (src_reg->type == SCALAR_VALUE) {
14259 					if (insn->off == 0) {
14260 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
14261 
14262 						if (is_src_reg_u32)
14263 							assign_scalar_id_before_mov(env, src_reg);
14264 						copy_register_state(dst_reg, src_reg);
14265 						/* Make sure ID is cleared if src_reg is not in u32
14266 						 * range otherwise dst_reg min/max could be incorrectly
14267 						 * propagated into src_reg by find_equal_scalars()
14268 						 */
14269 						if (!is_src_reg_u32)
14270 							dst_reg->id = 0;
14271 						dst_reg->live |= REG_LIVE_WRITTEN;
14272 						dst_reg->subreg_def = env->insn_idx + 1;
14273 					} else {
14274 						/* case: W1 = (s8, s16)W2 */
14275 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
14276 
14277 						if (no_sext)
14278 							assign_scalar_id_before_mov(env, src_reg);
14279 						copy_register_state(dst_reg, src_reg);
14280 						if (!no_sext)
14281 							dst_reg->id = 0;
14282 						dst_reg->live |= REG_LIVE_WRITTEN;
14283 						dst_reg->subreg_def = env->insn_idx + 1;
14284 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
14285 					}
14286 				} else {
14287 					mark_reg_unknown(env, regs,
14288 							 insn->dst_reg);
14289 				}
14290 				zext_32_to_64(dst_reg);
14291 				reg_bounds_sync(dst_reg);
14292 			}
14293 		} else {
14294 			/* case: R = imm
14295 			 * remember the value we stored into this reg
14296 			 */
14297 			/* clear any state __mark_reg_known doesn't set */
14298 			mark_reg_unknown(env, regs, insn->dst_reg);
14299 			regs[insn->dst_reg].type = SCALAR_VALUE;
14300 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
14301 				__mark_reg_known(regs + insn->dst_reg,
14302 						 insn->imm);
14303 			} else {
14304 				__mark_reg_known(regs + insn->dst_reg,
14305 						 (u32)insn->imm);
14306 			}
14307 		}
14308 
14309 	} else if (opcode > BPF_END) {
14310 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
14311 		return -EINVAL;
14312 
14313 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
14314 
14315 		if (BPF_SRC(insn->code) == BPF_X) {
14316 			if (insn->imm != 0 || insn->off > 1 ||
14317 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14318 				verbose(env, "BPF_ALU uses reserved fields\n");
14319 				return -EINVAL;
14320 			}
14321 			/* check src1 operand */
14322 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
14323 			if (err)
14324 				return err;
14325 		} else {
14326 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
14327 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
14328 				verbose(env, "BPF_ALU uses reserved fields\n");
14329 				return -EINVAL;
14330 			}
14331 		}
14332 
14333 		/* check src2 operand */
14334 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14335 		if (err)
14336 			return err;
14337 
14338 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
14339 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
14340 			verbose(env, "div by zero\n");
14341 			return -EINVAL;
14342 		}
14343 
14344 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
14345 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
14346 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
14347 
14348 			if (insn->imm < 0 || insn->imm >= size) {
14349 				verbose(env, "invalid shift %d\n", insn->imm);
14350 				return -EINVAL;
14351 			}
14352 		}
14353 
14354 		/* check dest operand */
14355 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
14356 		err = err ?: adjust_reg_min_max_vals(env, insn);
14357 		if (err)
14358 			return err;
14359 	}
14360 
14361 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
14362 }
14363 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)14364 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
14365 				   struct bpf_reg_state *dst_reg,
14366 				   enum bpf_reg_type type,
14367 				   bool range_right_open)
14368 {
14369 	struct bpf_func_state *state;
14370 	struct bpf_reg_state *reg;
14371 	int new_range;
14372 
14373 	if (dst_reg->off < 0 ||
14374 	    (dst_reg->off == 0 && range_right_open))
14375 		/* This doesn't give us any range */
14376 		return;
14377 
14378 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
14379 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
14380 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
14381 		 * than pkt_end, but that's because it's also less than pkt.
14382 		 */
14383 		return;
14384 
14385 	new_range = dst_reg->off;
14386 	if (range_right_open)
14387 		new_range++;
14388 
14389 	/* Examples for register markings:
14390 	 *
14391 	 * pkt_data in dst register:
14392 	 *
14393 	 *   r2 = r3;
14394 	 *   r2 += 8;
14395 	 *   if (r2 > pkt_end) goto <handle exception>
14396 	 *   <access okay>
14397 	 *
14398 	 *   r2 = r3;
14399 	 *   r2 += 8;
14400 	 *   if (r2 < pkt_end) goto <access okay>
14401 	 *   <handle exception>
14402 	 *
14403 	 *   Where:
14404 	 *     r2 == dst_reg, pkt_end == src_reg
14405 	 *     r2=pkt(id=n,off=8,r=0)
14406 	 *     r3=pkt(id=n,off=0,r=0)
14407 	 *
14408 	 * pkt_data in src register:
14409 	 *
14410 	 *   r2 = r3;
14411 	 *   r2 += 8;
14412 	 *   if (pkt_end >= r2) goto <access okay>
14413 	 *   <handle exception>
14414 	 *
14415 	 *   r2 = r3;
14416 	 *   r2 += 8;
14417 	 *   if (pkt_end <= r2) goto <handle exception>
14418 	 *   <access okay>
14419 	 *
14420 	 *   Where:
14421 	 *     pkt_end == dst_reg, r2 == src_reg
14422 	 *     r2=pkt(id=n,off=8,r=0)
14423 	 *     r3=pkt(id=n,off=0,r=0)
14424 	 *
14425 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14426 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14427 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
14428 	 * the check.
14429 	 */
14430 
14431 	/* If our ids match, then we must have the same max_value.  And we
14432 	 * don't care about the other reg's fixed offset, since if it's too big
14433 	 * the range won't allow anything.
14434 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14435 	 */
14436 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14437 		if (reg->type == type && reg->id == dst_reg->id)
14438 			/* keep the maximum range already checked */
14439 			reg->range = max(reg->range, new_range);
14440 	}));
14441 }
14442 
14443 /*
14444  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
14445  */
is_scalar_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)14446 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14447 				  u8 opcode, bool is_jmp32)
14448 {
14449 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
14450 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
14451 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
14452 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
14453 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
14454 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
14455 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
14456 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
14457 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
14458 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
14459 
14460 	switch (opcode) {
14461 	case BPF_JEQ:
14462 		/* constants, umin/umax and smin/smax checks would be
14463 		 * redundant in this case because they all should match
14464 		 */
14465 		if (tnum_is_const(t1) && tnum_is_const(t2))
14466 			return t1.value == t2.value;
14467 		/* non-overlapping ranges */
14468 		if (umin1 > umax2 || umax1 < umin2)
14469 			return 0;
14470 		if (smin1 > smax2 || smax1 < smin2)
14471 			return 0;
14472 		if (!is_jmp32) {
14473 			/* if 64-bit ranges are inconclusive, see if we can
14474 			 * utilize 32-bit subrange knowledge to eliminate
14475 			 * branches that can't be taken a priori
14476 			 */
14477 			if (reg1->u32_min_value > reg2->u32_max_value ||
14478 			    reg1->u32_max_value < reg2->u32_min_value)
14479 				return 0;
14480 			if (reg1->s32_min_value > reg2->s32_max_value ||
14481 			    reg1->s32_max_value < reg2->s32_min_value)
14482 				return 0;
14483 		}
14484 		break;
14485 	case BPF_JNE:
14486 		/* constants, umin/umax and smin/smax checks would be
14487 		 * redundant in this case because they all should match
14488 		 */
14489 		if (tnum_is_const(t1) && tnum_is_const(t2))
14490 			return t1.value != t2.value;
14491 		/* non-overlapping ranges */
14492 		if (umin1 > umax2 || umax1 < umin2)
14493 			return 1;
14494 		if (smin1 > smax2 || smax1 < smin2)
14495 			return 1;
14496 		if (!is_jmp32) {
14497 			/* if 64-bit ranges are inconclusive, see if we can
14498 			 * utilize 32-bit subrange knowledge to eliminate
14499 			 * branches that can't be taken a priori
14500 			 */
14501 			if (reg1->u32_min_value > reg2->u32_max_value ||
14502 			    reg1->u32_max_value < reg2->u32_min_value)
14503 				return 1;
14504 			if (reg1->s32_min_value > reg2->s32_max_value ||
14505 			    reg1->s32_max_value < reg2->s32_min_value)
14506 				return 1;
14507 		}
14508 		break;
14509 	case BPF_JSET:
14510 		if (!is_reg_const(reg2, is_jmp32)) {
14511 			swap(reg1, reg2);
14512 			swap(t1, t2);
14513 		}
14514 		if (!is_reg_const(reg2, is_jmp32))
14515 			return -1;
14516 		if ((~t1.mask & t1.value) & t2.value)
14517 			return 1;
14518 		if (!((t1.mask | t1.value) & t2.value))
14519 			return 0;
14520 		break;
14521 	case BPF_JGT:
14522 		if (umin1 > umax2)
14523 			return 1;
14524 		else if (umax1 <= umin2)
14525 			return 0;
14526 		break;
14527 	case BPF_JSGT:
14528 		if (smin1 > smax2)
14529 			return 1;
14530 		else if (smax1 <= smin2)
14531 			return 0;
14532 		break;
14533 	case BPF_JLT:
14534 		if (umax1 < umin2)
14535 			return 1;
14536 		else if (umin1 >= umax2)
14537 			return 0;
14538 		break;
14539 	case BPF_JSLT:
14540 		if (smax1 < smin2)
14541 			return 1;
14542 		else if (smin1 >= smax2)
14543 			return 0;
14544 		break;
14545 	case BPF_JGE:
14546 		if (umin1 >= umax2)
14547 			return 1;
14548 		else if (umax1 < umin2)
14549 			return 0;
14550 		break;
14551 	case BPF_JSGE:
14552 		if (smin1 >= smax2)
14553 			return 1;
14554 		else if (smax1 < smin2)
14555 			return 0;
14556 		break;
14557 	case BPF_JLE:
14558 		if (umax1 <= umin2)
14559 			return 1;
14560 		else if (umin1 > umax2)
14561 			return 0;
14562 		break;
14563 	case BPF_JSLE:
14564 		if (smax1 <= smin2)
14565 			return 1;
14566 		else if (smin1 > smax2)
14567 			return 0;
14568 		break;
14569 	}
14570 
14571 	return -1;
14572 }
14573 
flip_opcode(u32 opcode)14574 static int flip_opcode(u32 opcode)
14575 {
14576 	/* How can we transform "a <op> b" into "b <op> a"? */
14577 	static const u8 opcode_flip[16] = {
14578 		/* these stay the same */
14579 		[BPF_JEQ  >> 4] = BPF_JEQ,
14580 		[BPF_JNE  >> 4] = BPF_JNE,
14581 		[BPF_JSET >> 4] = BPF_JSET,
14582 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14583 		[BPF_JGE  >> 4] = BPF_JLE,
14584 		[BPF_JGT  >> 4] = BPF_JLT,
14585 		[BPF_JLE  >> 4] = BPF_JGE,
14586 		[BPF_JLT  >> 4] = BPF_JGT,
14587 		[BPF_JSGE >> 4] = BPF_JSLE,
14588 		[BPF_JSGT >> 4] = BPF_JSLT,
14589 		[BPF_JSLE >> 4] = BPF_JSGE,
14590 		[BPF_JSLT >> 4] = BPF_JSGT
14591 	};
14592 	return opcode_flip[opcode >> 4];
14593 }
14594 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)14595 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14596 				   struct bpf_reg_state *src_reg,
14597 				   u8 opcode)
14598 {
14599 	struct bpf_reg_state *pkt;
14600 
14601 	if (src_reg->type == PTR_TO_PACKET_END) {
14602 		pkt = dst_reg;
14603 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14604 		pkt = src_reg;
14605 		opcode = flip_opcode(opcode);
14606 	} else {
14607 		return -1;
14608 	}
14609 
14610 	if (pkt->range >= 0)
14611 		return -1;
14612 
14613 	switch (opcode) {
14614 	case BPF_JLE:
14615 		/* pkt <= pkt_end */
14616 		fallthrough;
14617 	case BPF_JGT:
14618 		/* pkt > pkt_end */
14619 		if (pkt->range == BEYOND_PKT_END)
14620 			/* pkt has at last one extra byte beyond pkt_end */
14621 			return opcode == BPF_JGT;
14622 		break;
14623 	case BPF_JLT:
14624 		/* pkt < pkt_end */
14625 		fallthrough;
14626 	case BPF_JGE:
14627 		/* pkt >= pkt_end */
14628 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14629 			return opcode == BPF_JGE;
14630 		break;
14631 	}
14632 	return -1;
14633 }
14634 
14635 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
14636  * and return:
14637  *  1 - branch will be taken and "goto target" will be executed
14638  *  0 - branch will not be taken and fall-through to next insn
14639  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
14640  *      range [0,10]
14641  */
is_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)14642 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14643 			   u8 opcode, bool is_jmp32)
14644 {
14645 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
14646 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
14647 
14648 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
14649 		u64 val;
14650 
14651 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
14652 		if (!is_reg_const(reg2, is_jmp32)) {
14653 			opcode = flip_opcode(opcode);
14654 			swap(reg1, reg2);
14655 		}
14656 		/* and ensure that reg2 is a constant */
14657 		if (!is_reg_const(reg2, is_jmp32))
14658 			return -1;
14659 
14660 		if (!reg_not_null(reg1))
14661 			return -1;
14662 
14663 		/* If pointer is valid tests against zero will fail so we can
14664 		 * use this to direct branch taken.
14665 		 */
14666 		val = reg_const_value(reg2, is_jmp32);
14667 		if (val != 0)
14668 			return -1;
14669 
14670 		switch (opcode) {
14671 		case BPF_JEQ:
14672 			return 0;
14673 		case BPF_JNE:
14674 			return 1;
14675 		default:
14676 			return -1;
14677 		}
14678 	}
14679 
14680 	/* now deal with two scalars, but not necessarily constants */
14681 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
14682 }
14683 
14684 /* Opcode that corresponds to a *false* branch condition.
14685  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
14686  */
rev_opcode(u8 opcode)14687 static u8 rev_opcode(u8 opcode)
14688 {
14689 	switch (opcode) {
14690 	case BPF_JEQ:		return BPF_JNE;
14691 	case BPF_JNE:		return BPF_JEQ;
14692 	/* JSET doesn't have it's reverse opcode in BPF, so add
14693 	 * BPF_X flag to denote the reverse of that operation
14694 	 */
14695 	case BPF_JSET:		return BPF_JSET | BPF_X;
14696 	case BPF_JSET | BPF_X:	return BPF_JSET;
14697 	case BPF_JGE:		return BPF_JLT;
14698 	case BPF_JGT:		return BPF_JLE;
14699 	case BPF_JLE:		return BPF_JGT;
14700 	case BPF_JLT:		return BPF_JGE;
14701 	case BPF_JSGE:		return BPF_JSLT;
14702 	case BPF_JSGT:		return BPF_JSLE;
14703 	case BPF_JSLE:		return BPF_JSGT;
14704 	case BPF_JSLT:		return BPF_JSGE;
14705 	default:		return 0;
14706 	}
14707 }
14708 
14709 /* 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)14710 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
14711 				u8 opcode, bool is_jmp32)
14712 {
14713 	struct tnum t;
14714 	u64 val;
14715 
14716 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
14717 	switch (opcode) {
14718 	case BPF_JGE:
14719 	case BPF_JGT:
14720 	case BPF_JSGE:
14721 	case BPF_JSGT:
14722 		opcode = flip_opcode(opcode);
14723 		swap(reg1, reg2);
14724 		break;
14725 	default:
14726 		break;
14727 	}
14728 
14729 	switch (opcode) {
14730 	case BPF_JEQ:
14731 		if (is_jmp32) {
14732 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14733 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14734 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14735 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14736 			reg2->u32_min_value = reg1->u32_min_value;
14737 			reg2->u32_max_value = reg1->u32_max_value;
14738 			reg2->s32_min_value = reg1->s32_min_value;
14739 			reg2->s32_max_value = reg1->s32_max_value;
14740 
14741 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
14742 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14743 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
14744 		} else {
14745 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
14746 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14747 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
14748 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14749 			reg2->umin_value = reg1->umin_value;
14750 			reg2->umax_value = reg1->umax_value;
14751 			reg2->smin_value = reg1->smin_value;
14752 			reg2->smax_value = reg1->smax_value;
14753 
14754 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
14755 			reg2->var_off = reg1->var_off;
14756 		}
14757 		break;
14758 	case BPF_JNE:
14759 		if (!is_reg_const(reg2, is_jmp32))
14760 			swap(reg1, reg2);
14761 		if (!is_reg_const(reg2, is_jmp32))
14762 			break;
14763 
14764 		/* try to recompute the bound of reg1 if reg2 is a const and
14765 		 * is exactly the edge of reg1.
14766 		 */
14767 		val = reg_const_value(reg2, is_jmp32);
14768 		if (is_jmp32) {
14769 			/* u32_min_value is not equal to 0xffffffff at this point,
14770 			 * because otherwise u32_max_value is 0xffffffff as well,
14771 			 * in such a case both reg1 and reg2 would be constants,
14772 			 * jump would be predicted and reg_set_min_max() won't
14773 			 * be called.
14774 			 *
14775 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
14776 			 * below.
14777 			 */
14778 			if (reg1->u32_min_value == (u32)val)
14779 				reg1->u32_min_value++;
14780 			if (reg1->u32_max_value == (u32)val)
14781 				reg1->u32_max_value--;
14782 			if (reg1->s32_min_value == (s32)val)
14783 				reg1->s32_min_value++;
14784 			if (reg1->s32_max_value == (s32)val)
14785 				reg1->s32_max_value--;
14786 		} else {
14787 			if (reg1->umin_value == (u64)val)
14788 				reg1->umin_value++;
14789 			if (reg1->umax_value == (u64)val)
14790 				reg1->umax_value--;
14791 			if (reg1->smin_value == (s64)val)
14792 				reg1->smin_value++;
14793 			if (reg1->smax_value == (s64)val)
14794 				reg1->smax_value--;
14795 		}
14796 		break;
14797 	case BPF_JSET:
14798 		if (!is_reg_const(reg2, is_jmp32))
14799 			swap(reg1, reg2);
14800 		if (!is_reg_const(reg2, is_jmp32))
14801 			break;
14802 		val = reg_const_value(reg2, is_jmp32);
14803 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
14804 		 * requires single bit to learn something useful. E.g., if we
14805 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
14806 		 * are actually set? We can learn something definite only if
14807 		 * it's a single-bit value to begin with.
14808 		 *
14809 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
14810 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
14811 		 * bit 1 is set, which we can readily use in adjustments.
14812 		 */
14813 		if (!is_power_of_2(val))
14814 			break;
14815 		if (is_jmp32) {
14816 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
14817 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14818 		} else {
14819 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
14820 		}
14821 		break;
14822 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
14823 		if (!is_reg_const(reg2, is_jmp32))
14824 			swap(reg1, reg2);
14825 		if (!is_reg_const(reg2, is_jmp32))
14826 			break;
14827 		val = reg_const_value(reg2, is_jmp32);
14828 		if (is_jmp32) {
14829 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
14830 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
14831 		} else {
14832 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
14833 		}
14834 		break;
14835 	case BPF_JLE:
14836 		if (is_jmp32) {
14837 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
14838 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
14839 		} else {
14840 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
14841 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
14842 		}
14843 		break;
14844 	case BPF_JLT:
14845 		if (is_jmp32) {
14846 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
14847 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
14848 		} else {
14849 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
14850 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
14851 		}
14852 		break;
14853 	case BPF_JSLE:
14854 		if (is_jmp32) {
14855 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
14856 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
14857 		} else {
14858 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
14859 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
14860 		}
14861 		break;
14862 	case BPF_JSLT:
14863 		if (is_jmp32) {
14864 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
14865 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
14866 		} else {
14867 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
14868 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
14869 		}
14870 		break;
14871 	default:
14872 		return;
14873 	}
14874 }
14875 
14876 /* Adjusts the register min/max values in the case that the dst_reg and
14877  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
14878  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
14879  * Technically we can do similar adjustments for pointers to the same object,
14880  * but we don't support that right now.
14881  */
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)14882 static int reg_set_min_max(struct bpf_verifier_env *env,
14883 			   struct bpf_reg_state *true_reg1,
14884 			   struct bpf_reg_state *true_reg2,
14885 			   struct bpf_reg_state *false_reg1,
14886 			   struct bpf_reg_state *false_reg2,
14887 			   u8 opcode, bool is_jmp32)
14888 {
14889 	int err;
14890 
14891 	/* If either register is a pointer, we can't learn anything about its
14892 	 * variable offset from the compare (unless they were a pointer into
14893 	 * the same object, but we don't bother with that).
14894 	 */
14895 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
14896 		return 0;
14897 
14898 	/* fallthrough (FALSE) branch */
14899 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
14900 	reg_bounds_sync(false_reg1);
14901 	reg_bounds_sync(false_reg2);
14902 
14903 	/* jump (TRUE) branch */
14904 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
14905 	reg_bounds_sync(true_reg1);
14906 	reg_bounds_sync(true_reg2);
14907 
14908 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
14909 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
14910 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
14911 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
14912 	return err;
14913 }
14914 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)14915 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14916 				 struct bpf_reg_state *reg, u32 id,
14917 				 bool is_null)
14918 {
14919 	if (type_may_be_null(reg->type) && reg->id == id &&
14920 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14921 		/* Old offset (both fixed and variable parts) should have been
14922 		 * known-zero, because we don't allow pointer arithmetic on
14923 		 * pointers that might be NULL. If we see this happening, don't
14924 		 * convert the register.
14925 		 *
14926 		 * But in some cases, some helpers that return local kptrs
14927 		 * advance offset for the returned pointer. In those cases, it
14928 		 * is fine to expect to see reg->off.
14929 		 */
14930 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14931 			return;
14932 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14933 		    WARN_ON_ONCE(reg->off))
14934 			return;
14935 
14936 		if (is_null) {
14937 			reg->type = SCALAR_VALUE;
14938 			/* We don't need id and ref_obj_id from this point
14939 			 * onwards anymore, thus we should better reset it,
14940 			 * so that state pruning has chances to take effect.
14941 			 */
14942 			reg->id = 0;
14943 			reg->ref_obj_id = 0;
14944 
14945 			return;
14946 		}
14947 
14948 		mark_ptr_not_null_reg(reg);
14949 
14950 		if (!reg_may_point_to_spin_lock(reg)) {
14951 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14952 			 * in release_reference().
14953 			 *
14954 			 * reg->id is still used by spin_lock ptr. Other
14955 			 * than spin_lock ptr type, reg->id can be reset.
14956 			 */
14957 			reg->id = 0;
14958 		}
14959 	}
14960 }
14961 
14962 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14963  * be folded together at some point.
14964  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)14965 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14966 				  bool is_null)
14967 {
14968 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14969 	struct bpf_reg_state *regs = state->regs, *reg;
14970 	u32 ref_obj_id = regs[regno].ref_obj_id;
14971 	u32 id = regs[regno].id;
14972 
14973 	if (ref_obj_id && ref_obj_id == id && is_null)
14974 		/* regs[regno] is in the " == NULL" branch.
14975 		 * No one could have freed the reference state before
14976 		 * doing the NULL check.
14977 		 */
14978 		WARN_ON_ONCE(release_reference_state(state, id));
14979 
14980 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14981 		mark_ptr_or_null_reg(state, reg, id, is_null);
14982 	}));
14983 }
14984 
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)14985 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14986 				   struct bpf_reg_state *dst_reg,
14987 				   struct bpf_reg_state *src_reg,
14988 				   struct bpf_verifier_state *this_branch,
14989 				   struct bpf_verifier_state *other_branch)
14990 {
14991 	if (BPF_SRC(insn->code) != BPF_X)
14992 		return false;
14993 
14994 	/* Pointers are always 64-bit. */
14995 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14996 		return false;
14997 
14998 	switch (BPF_OP(insn->code)) {
14999 	case BPF_JGT:
15000 		if ((dst_reg->type == PTR_TO_PACKET &&
15001 		     src_reg->type == PTR_TO_PACKET_END) ||
15002 		    (dst_reg->type == PTR_TO_PACKET_META &&
15003 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15004 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
15005 			find_good_pkt_pointers(this_branch, dst_reg,
15006 					       dst_reg->type, false);
15007 			mark_pkt_end(other_branch, insn->dst_reg, true);
15008 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15009 			    src_reg->type == PTR_TO_PACKET) ||
15010 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15011 			    src_reg->type == PTR_TO_PACKET_META)) {
15012 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
15013 			find_good_pkt_pointers(other_branch, src_reg,
15014 					       src_reg->type, true);
15015 			mark_pkt_end(this_branch, insn->src_reg, false);
15016 		} else {
15017 			return false;
15018 		}
15019 		break;
15020 	case BPF_JLT:
15021 		if ((dst_reg->type == PTR_TO_PACKET &&
15022 		     src_reg->type == PTR_TO_PACKET_END) ||
15023 		    (dst_reg->type == PTR_TO_PACKET_META &&
15024 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15025 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
15026 			find_good_pkt_pointers(other_branch, dst_reg,
15027 					       dst_reg->type, true);
15028 			mark_pkt_end(this_branch, insn->dst_reg, false);
15029 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15030 			    src_reg->type == PTR_TO_PACKET) ||
15031 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15032 			    src_reg->type == PTR_TO_PACKET_META)) {
15033 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
15034 			find_good_pkt_pointers(this_branch, src_reg,
15035 					       src_reg->type, false);
15036 			mark_pkt_end(other_branch, insn->src_reg, true);
15037 		} else {
15038 			return false;
15039 		}
15040 		break;
15041 	case BPF_JGE:
15042 		if ((dst_reg->type == PTR_TO_PACKET &&
15043 		     src_reg->type == PTR_TO_PACKET_END) ||
15044 		    (dst_reg->type == PTR_TO_PACKET_META &&
15045 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15046 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
15047 			find_good_pkt_pointers(this_branch, dst_reg,
15048 					       dst_reg->type, true);
15049 			mark_pkt_end(other_branch, insn->dst_reg, false);
15050 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15051 			    src_reg->type == PTR_TO_PACKET) ||
15052 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15053 			    src_reg->type == PTR_TO_PACKET_META)) {
15054 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
15055 			find_good_pkt_pointers(other_branch, src_reg,
15056 					       src_reg->type, false);
15057 			mark_pkt_end(this_branch, insn->src_reg, true);
15058 		} else {
15059 			return false;
15060 		}
15061 		break;
15062 	case BPF_JLE:
15063 		if ((dst_reg->type == PTR_TO_PACKET &&
15064 		     src_reg->type == PTR_TO_PACKET_END) ||
15065 		    (dst_reg->type == PTR_TO_PACKET_META &&
15066 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
15067 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
15068 			find_good_pkt_pointers(other_branch, dst_reg,
15069 					       dst_reg->type, false);
15070 			mark_pkt_end(this_branch, insn->dst_reg, true);
15071 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
15072 			    src_reg->type == PTR_TO_PACKET) ||
15073 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
15074 			    src_reg->type == PTR_TO_PACKET_META)) {
15075 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
15076 			find_good_pkt_pointers(this_branch, src_reg,
15077 					       src_reg->type, true);
15078 			mark_pkt_end(other_branch, insn->src_reg, false);
15079 		} else {
15080 			return false;
15081 		}
15082 		break;
15083 	default:
15084 		return false;
15085 	}
15086 
15087 	return true;
15088 }
15089 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)15090 static void find_equal_scalars(struct bpf_verifier_state *vstate,
15091 			       struct bpf_reg_state *known_reg)
15092 {
15093 	struct bpf_reg_state fake_reg;
15094 	struct bpf_func_state *state;
15095 	struct bpf_reg_state *reg;
15096 
15097 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15098 		if (reg->type != SCALAR_VALUE || reg == known_reg)
15099 			continue;
15100 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
15101 			continue;
15102 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
15103 		    reg->off == known_reg->off) {
15104 			copy_register_state(reg, known_reg);
15105 		} else {
15106 			s32 saved_off = reg->off;
15107 
15108 			fake_reg.type = SCALAR_VALUE;
15109 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
15110 
15111 			/* reg = known_reg; reg += delta */
15112 			copy_register_state(reg, known_reg);
15113 			/*
15114 			 * Must preserve off, id and add_const flag,
15115 			 * otherwise another find_equal_scalars() will be incorrect.
15116 			 */
15117 			reg->off = saved_off;
15118 
15119 			scalar32_min_max_add(reg, &fake_reg);
15120 			scalar_min_max_add(reg, &fake_reg);
15121 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
15122 		}
15123 	}));
15124 }
15125 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)15126 static int check_cond_jmp_op(struct bpf_verifier_env *env,
15127 			     struct bpf_insn *insn, int *insn_idx)
15128 {
15129 	struct bpf_verifier_state *this_branch = env->cur_state;
15130 	struct bpf_verifier_state *other_branch;
15131 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
15132 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
15133 	struct bpf_reg_state *eq_branch_regs;
15134 	u8 opcode = BPF_OP(insn->code);
15135 	bool is_jmp32;
15136 	int pred = -1;
15137 	int err;
15138 
15139 	/* Only conditional jumps are expected to reach here. */
15140 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
15141 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
15142 		return -EINVAL;
15143 	}
15144 
15145 	if (opcode == BPF_JCOND) {
15146 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
15147 		int idx = *insn_idx;
15148 
15149 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
15150 		    insn->src_reg != BPF_MAY_GOTO ||
15151 		    insn->dst_reg || insn->imm || insn->off == 0) {
15152 			verbose(env, "invalid may_goto off %d imm %d\n",
15153 				insn->off, insn->imm);
15154 			return -EINVAL;
15155 		}
15156 		prev_st = find_prev_entry(env, cur_st->parent, idx);
15157 
15158 		/* branch out 'fallthrough' insn as a new state to explore */
15159 		queued_st = push_stack(env, idx + 1, idx, false);
15160 		if (!queued_st)
15161 			return -ENOMEM;
15162 
15163 		queued_st->may_goto_depth++;
15164 		if (prev_st)
15165 			widen_imprecise_scalars(env, prev_st, queued_st);
15166 		*insn_idx += insn->off;
15167 		return 0;
15168 	}
15169 
15170 	/* check src2 operand */
15171 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15172 	if (err)
15173 		return err;
15174 
15175 	dst_reg = &regs[insn->dst_reg];
15176 	if (BPF_SRC(insn->code) == BPF_X) {
15177 		if (insn->imm != 0) {
15178 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15179 			return -EINVAL;
15180 		}
15181 
15182 		/* check src1 operand */
15183 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15184 		if (err)
15185 			return err;
15186 
15187 		src_reg = &regs[insn->src_reg];
15188 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
15189 		    is_pointer_value(env, insn->src_reg)) {
15190 			verbose(env, "R%d pointer comparison prohibited\n",
15191 				insn->src_reg);
15192 			return -EACCES;
15193 		}
15194 	} else {
15195 		if (insn->src_reg != BPF_REG_0) {
15196 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
15197 			return -EINVAL;
15198 		}
15199 		src_reg = &env->fake_reg[0];
15200 		memset(src_reg, 0, sizeof(*src_reg));
15201 		src_reg->type = SCALAR_VALUE;
15202 		__mark_reg_known(src_reg, insn->imm);
15203 	}
15204 
15205 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
15206 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
15207 	if (pred >= 0) {
15208 		/* If we get here with a dst_reg pointer type it is because
15209 		 * above is_branch_taken() special cased the 0 comparison.
15210 		 */
15211 		if (!__is_pointer_value(false, dst_reg))
15212 			err = mark_chain_precision(env, insn->dst_reg);
15213 		if (BPF_SRC(insn->code) == BPF_X && !err &&
15214 		    !__is_pointer_value(false, src_reg))
15215 			err = mark_chain_precision(env, insn->src_reg);
15216 		if (err)
15217 			return err;
15218 	}
15219 
15220 	if (pred == 1) {
15221 		/* Only follow the goto, ignore fall-through. If needed, push
15222 		 * the fall-through branch for simulation under speculative
15223 		 * execution.
15224 		 */
15225 		if (!env->bypass_spec_v1 &&
15226 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
15227 					       *insn_idx))
15228 			return -EFAULT;
15229 		if (env->log.level & BPF_LOG_LEVEL)
15230 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15231 		*insn_idx += insn->off;
15232 		return 0;
15233 	} else if (pred == 0) {
15234 		/* Only follow the fall-through branch, since that's where the
15235 		 * program will go. If needed, push the goto branch for
15236 		 * simulation under speculative execution.
15237 		 */
15238 		if (!env->bypass_spec_v1 &&
15239 		    !sanitize_speculative_path(env, insn,
15240 					       *insn_idx + insn->off + 1,
15241 					       *insn_idx))
15242 			return -EFAULT;
15243 		if (env->log.level & BPF_LOG_LEVEL)
15244 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
15245 		return 0;
15246 	}
15247 
15248 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
15249 				  false);
15250 	if (!other_branch)
15251 		return -EFAULT;
15252 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
15253 
15254 	if (BPF_SRC(insn->code) == BPF_X) {
15255 		err = reg_set_min_max(env,
15256 				      &other_branch_regs[insn->dst_reg],
15257 				      &other_branch_regs[insn->src_reg],
15258 				      dst_reg, src_reg, opcode, is_jmp32);
15259 	} else /* BPF_SRC(insn->code) == BPF_K */ {
15260 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
15261 		 * so that these are two different memory locations. The
15262 		 * src_reg is not used beyond here in context of K.
15263 		 */
15264 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
15265 		       sizeof(env->fake_reg[0]));
15266 		err = reg_set_min_max(env,
15267 				      &other_branch_regs[insn->dst_reg],
15268 				      &env->fake_reg[0],
15269 				      dst_reg, &env->fake_reg[1],
15270 				      opcode, is_jmp32);
15271 	}
15272 	if (err)
15273 		return err;
15274 
15275 	if (BPF_SRC(insn->code) == BPF_X &&
15276 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
15277 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
15278 		find_equal_scalars(this_branch, src_reg);
15279 		find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
15280 	}
15281 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
15282 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
15283 		find_equal_scalars(this_branch, dst_reg);
15284 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
15285 	}
15286 
15287 	/* if one pointer register is compared to another pointer
15288 	 * register check if PTR_MAYBE_NULL could be lifted.
15289 	 * E.g. register A - maybe null
15290 	 *      register B - not null
15291 	 * for JNE A, B, ... - A is not null in the false branch;
15292 	 * for JEQ A, B, ... - A is not null in the true branch.
15293 	 *
15294 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
15295 	 * not need to be null checked by the BPF program, i.e.,
15296 	 * could be null even without PTR_MAYBE_NULL marking, so
15297 	 * only propagate nullness when neither reg is that type.
15298 	 */
15299 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
15300 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
15301 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
15302 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
15303 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
15304 		eq_branch_regs = NULL;
15305 		switch (opcode) {
15306 		case BPF_JEQ:
15307 			eq_branch_regs = other_branch_regs;
15308 			break;
15309 		case BPF_JNE:
15310 			eq_branch_regs = regs;
15311 			break;
15312 		default:
15313 			/* do nothing */
15314 			break;
15315 		}
15316 		if (eq_branch_regs) {
15317 			if (type_may_be_null(src_reg->type))
15318 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
15319 			else
15320 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
15321 		}
15322 	}
15323 
15324 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
15325 	 * NOTE: these optimizations below are related with pointer comparison
15326 	 *       which will never be JMP32.
15327 	 */
15328 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
15329 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
15330 	    type_may_be_null(dst_reg->type)) {
15331 		/* Mark all identical registers in each branch as either
15332 		 * safe or unknown depending R == 0 or R != 0 conditional.
15333 		 */
15334 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
15335 				      opcode == BPF_JNE);
15336 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
15337 				      opcode == BPF_JEQ);
15338 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
15339 					   this_branch, other_branch) &&
15340 		   is_pointer_value(env, insn->dst_reg)) {
15341 		verbose(env, "R%d pointer comparison prohibited\n",
15342 			insn->dst_reg);
15343 		return -EACCES;
15344 	}
15345 	if (env->log.level & BPF_LOG_LEVEL)
15346 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
15347 	return 0;
15348 }
15349 
15350 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)15351 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
15352 {
15353 	struct bpf_insn_aux_data *aux = cur_aux(env);
15354 	struct bpf_reg_state *regs = cur_regs(env);
15355 	struct bpf_reg_state *dst_reg;
15356 	struct bpf_map *map;
15357 	int err;
15358 
15359 	if (BPF_SIZE(insn->code) != BPF_DW) {
15360 		verbose(env, "invalid BPF_LD_IMM insn\n");
15361 		return -EINVAL;
15362 	}
15363 	if (insn->off != 0) {
15364 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
15365 		return -EINVAL;
15366 	}
15367 
15368 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
15369 	if (err)
15370 		return err;
15371 
15372 	dst_reg = &regs[insn->dst_reg];
15373 	if (insn->src_reg == 0) {
15374 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
15375 
15376 		dst_reg->type = SCALAR_VALUE;
15377 		__mark_reg_known(&regs[insn->dst_reg], imm);
15378 		return 0;
15379 	}
15380 
15381 	/* All special src_reg cases are listed below. From this point onwards
15382 	 * we either succeed and assign a corresponding dst_reg->type after
15383 	 * zeroing the offset, or fail and reject the program.
15384 	 */
15385 	mark_reg_known_zero(env, regs, insn->dst_reg);
15386 
15387 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
15388 		dst_reg->type = aux->btf_var.reg_type;
15389 		switch (base_type(dst_reg->type)) {
15390 		case PTR_TO_MEM:
15391 			dst_reg->mem_size = aux->btf_var.mem_size;
15392 			break;
15393 		case PTR_TO_BTF_ID:
15394 			dst_reg->btf = aux->btf_var.btf;
15395 			dst_reg->btf_id = aux->btf_var.btf_id;
15396 			break;
15397 		default:
15398 			verbose(env, "bpf verifier is misconfigured\n");
15399 			return -EFAULT;
15400 		}
15401 		return 0;
15402 	}
15403 
15404 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
15405 		struct bpf_prog_aux *aux = env->prog->aux;
15406 		u32 subprogno = find_subprog(env,
15407 					     env->insn_idx + insn->imm + 1);
15408 
15409 		if (!aux->func_info) {
15410 			verbose(env, "missing btf func_info\n");
15411 			return -EINVAL;
15412 		}
15413 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
15414 			verbose(env, "callback function not static\n");
15415 			return -EINVAL;
15416 		}
15417 
15418 		dst_reg->type = PTR_TO_FUNC;
15419 		dst_reg->subprogno = subprogno;
15420 		return 0;
15421 	}
15422 
15423 	map = env->used_maps[aux->map_index];
15424 	dst_reg->map_ptr = map;
15425 
15426 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15427 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15428 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
15429 			__mark_reg_unknown(env, dst_reg);
15430 			return 0;
15431 		}
15432 		dst_reg->type = PTR_TO_MAP_VALUE;
15433 		dst_reg->off = aux->map_off;
15434 		WARN_ON_ONCE(map->max_entries != 1);
15435 		/* We want reg->id to be same (0) as map_value is not distinct */
15436 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15437 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15438 		dst_reg->type = CONST_PTR_TO_MAP;
15439 	} else {
15440 		verbose(env, "bpf verifier is misconfigured\n");
15441 		return -EINVAL;
15442 	}
15443 
15444 	return 0;
15445 }
15446 
may_access_skb(enum bpf_prog_type type)15447 static bool may_access_skb(enum bpf_prog_type type)
15448 {
15449 	switch (type) {
15450 	case BPF_PROG_TYPE_SOCKET_FILTER:
15451 	case BPF_PROG_TYPE_SCHED_CLS:
15452 	case BPF_PROG_TYPE_SCHED_ACT:
15453 		return true;
15454 	default:
15455 		return false;
15456 	}
15457 }
15458 
15459 /* verify safety of LD_ABS|LD_IND instructions:
15460  * - they can only appear in the programs where ctx == skb
15461  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15462  *   preserve R6-R9, and store return value into R0
15463  *
15464  * Implicit input:
15465  *   ctx == skb == R6 == CTX
15466  *
15467  * Explicit input:
15468  *   SRC == any register
15469  *   IMM == 32-bit immediate
15470  *
15471  * Output:
15472  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15473  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)15474 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15475 {
15476 	struct bpf_reg_state *regs = cur_regs(env);
15477 	static const int ctx_reg = BPF_REG_6;
15478 	u8 mode = BPF_MODE(insn->code);
15479 	int i, err;
15480 
15481 	if (!may_access_skb(resolve_prog_type(env->prog))) {
15482 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15483 		return -EINVAL;
15484 	}
15485 
15486 	if (!env->ops->gen_ld_abs) {
15487 		verbose(env, "bpf verifier is misconfigured\n");
15488 		return -EINVAL;
15489 	}
15490 
15491 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15492 	    BPF_SIZE(insn->code) == BPF_DW ||
15493 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15494 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15495 		return -EINVAL;
15496 	}
15497 
15498 	/* check whether implicit source operand (register R6) is readable */
15499 	err = check_reg_arg(env, ctx_reg, SRC_OP);
15500 	if (err)
15501 		return err;
15502 
15503 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15504 	 * gen_ld_abs() may terminate the program at runtime, leading to
15505 	 * reference leak.
15506 	 */
15507 	err = check_reference_leak(env, false);
15508 	if (err) {
15509 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15510 		return err;
15511 	}
15512 
15513 	if (env->cur_state->active_lock.ptr) {
15514 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15515 		return -EINVAL;
15516 	}
15517 
15518 	if (env->cur_state->active_rcu_lock) {
15519 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15520 		return -EINVAL;
15521 	}
15522 
15523 	if (env->cur_state->active_preempt_lock) {
15524 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n");
15525 		return -EINVAL;
15526 	}
15527 
15528 	if (regs[ctx_reg].type != PTR_TO_CTX) {
15529 		verbose(env,
15530 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15531 		return -EINVAL;
15532 	}
15533 
15534 	if (mode == BPF_IND) {
15535 		/* check explicit source operand */
15536 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
15537 		if (err)
15538 			return err;
15539 	}
15540 
15541 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15542 	if (err < 0)
15543 		return err;
15544 
15545 	/* reset caller saved regs to unreadable */
15546 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
15547 		mark_reg_not_init(env, regs, caller_saved[i]);
15548 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15549 	}
15550 
15551 	/* mark destination R0 register as readable, since it contains
15552 	 * the value fetched from the packet.
15553 	 * Already marked as written above.
15554 	 */
15555 	mark_reg_unknown(env, regs, BPF_REG_0);
15556 	/* ld_abs load up to 32-bit skb data. */
15557 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15558 	return 0;
15559 }
15560 
check_return_code(struct bpf_verifier_env * env,int regno,const char * reg_name)15561 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
15562 {
15563 	const char *exit_ctx = "At program exit";
15564 	struct tnum enforce_attach_type_range = tnum_unknown;
15565 	const struct bpf_prog *prog = env->prog;
15566 	struct bpf_reg_state *reg;
15567 	struct bpf_retval_range range = retval_range(0, 1);
15568 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15569 	int err;
15570 	struct bpf_func_state *frame = env->cur_state->frame[0];
15571 	const bool is_subprog = frame->subprogno;
15572 
15573 	/* LSM and struct_ops func-ptr's return type could be "void" */
15574 	if (!is_subprog || frame->in_exception_callback_fn) {
15575 		switch (prog_type) {
15576 		case BPF_PROG_TYPE_LSM:
15577 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
15578 				/* See below, can be 0 or 0-1 depending on hook. */
15579 				break;
15580 			fallthrough;
15581 		case BPF_PROG_TYPE_STRUCT_OPS:
15582 			if (!prog->aux->attach_func_proto->type)
15583 				return 0;
15584 			break;
15585 		default:
15586 			break;
15587 		}
15588 	}
15589 
15590 	/* eBPF calling convention is such that R0 is used
15591 	 * to return the value from eBPF program.
15592 	 * Make sure that it's readable at this time
15593 	 * of bpf_exit, which means that program wrote
15594 	 * something into it earlier
15595 	 */
15596 	err = check_reg_arg(env, regno, SRC_OP);
15597 	if (err)
15598 		return err;
15599 
15600 	if (is_pointer_value(env, regno)) {
15601 		verbose(env, "R%d leaks addr as return value\n", regno);
15602 		return -EACCES;
15603 	}
15604 
15605 	reg = cur_regs(env) + regno;
15606 
15607 	if (frame->in_async_callback_fn) {
15608 		/* enforce return zero from async callbacks like timer */
15609 		exit_ctx = "At async callback return";
15610 		range = retval_range(0, 0);
15611 		goto enforce_retval;
15612 	}
15613 
15614 	if (is_subprog && !frame->in_exception_callback_fn) {
15615 		if (reg->type != SCALAR_VALUE) {
15616 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15617 				regno, reg_type_str(env, reg->type));
15618 			return -EINVAL;
15619 		}
15620 		return 0;
15621 	}
15622 
15623 	switch (prog_type) {
15624 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15625 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15626 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15627 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15628 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15629 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15630 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15631 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15632 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15633 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15634 			range = retval_range(1, 1);
15635 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15636 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15637 			range = retval_range(0, 3);
15638 		break;
15639 	case BPF_PROG_TYPE_CGROUP_SKB:
15640 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15641 			range = retval_range(0, 3);
15642 			enforce_attach_type_range = tnum_range(2, 3);
15643 		}
15644 		break;
15645 	case BPF_PROG_TYPE_CGROUP_SOCK:
15646 	case BPF_PROG_TYPE_SOCK_OPS:
15647 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15648 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15649 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15650 		break;
15651 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15652 		if (!env->prog->aux->attach_btf_id)
15653 			return 0;
15654 		range = retval_range(0, 0);
15655 		break;
15656 	case BPF_PROG_TYPE_TRACING:
15657 		switch (env->prog->expected_attach_type) {
15658 		case BPF_TRACE_FENTRY:
15659 		case BPF_TRACE_FEXIT:
15660 			range = retval_range(0, 0);
15661 			break;
15662 		case BPF_TRACE_RAW_TP:
15663 		case BPF_MODIFY_RETURN:
15664 			return 0;
15665 		case BPF_TRACE_ITER:
15666 			break;
15667 		default:
15668 			return -ENOTSUPP;
15669 		}
15670 		break;
15671 	case BPF_PROG_TYPE_SK_LOOKUP:
15672 		range = retval_range(SK_DROP, SK_PASS);
15673 		break;
15674 
15675 	case BPF_PROG_TYPE_LSM:
15676 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15677 			/* Regular BPF_PROG_TYPE_LSM programs can return
15678 			 * any value.
15679 			 */
15680 			return 0;
15681 		}
15682 		if (!env->prog->aux->attach_func_proto->type) {
15683 			/* Make sure programs that attach to void
15684 			 * hooks don't try to modify return value.
15685 			 */
15686 			range = retval_range(1, 1);
15687 		}
15688 		break;
15689 
15690 	case BPF_PROG_TYPE_NETFILTER:
15691 		range = retval_range(NF_DROP, NF_ACCEPT);
15692 		break;
15693 	case BPF_PROG_TYPE_EXT:
15694 		/* freplace program can return anything as its return value
15695 		 * depends on the to-be-replaced kernel func or bpf program.
15696 		 */
15697 	default:
15698 		return 0;
15699 	}
15700 
15701 enforce_retval:
15702 	if (reg->type != SCALAR_VALUE) {
15703 		verbose(env, "%s the register R%d is not a known value (%s)\n",
15704 			exit_ctx, regno, reg_type_str(env, reg->type));
15705 		return -EINVAL;
15706 	}
15707 
15708 	err = mark_chain_precision(env, regno);
15709 	if (err)
15710 		return err;
15711 
15712 	if (!retval_range_within(range, reg)) {
15713 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
15714 		if (!is_subprog &&
15715 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
15716 		    prog_type == BPF_PROG_TYPE_LSM &&
15717 		    !prog->aux->attach_func_proto->type)
15718 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15719 		return -EINVAL;
15720 	}
15721 
15722 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15723 	    tnum_in(enforce_attach_type_range, reg->var_off))
15724 		env->prog->enforce_expected_attach_type = 1;
15725 	return 0;
15726 }
15727 
15728 /* non-recursive DFS pseudo code
15729  * 1  procedure DFS-iterative(G,v):
15730  * 2      label v as discovered
15731  * 3      let S be a stack
15732  * 4      S.push(v)
15733  * 5      while S is not empty
15734  * 6            t <- S.peek()
15735  * 7            if t is what we're looking for:
15736  * 8                return t
15737  * 9            for all edges e in G.adjacentEdges(t) do
15738  * 10               if edge e is already labelled
15739  * 11                   continue with the next edge
15740  * 12               w <- G.adjacentVertex(t,e)
15741  * 13               if vertex w is not discovered and not explored
15742  * 14                   label e as tree-edge
15743  * 15                   label w as discovered
15744  * 16                   S.push(w)
15745  * 17                   continue at 5
15746  * 18               else if vertex w is discovered
15747  * 19                   label e as back-edge
15748  * 20               else
15749  * 21                   // vertex w is explored
15750  * 22                   label e as forward- or cross-edge
15751  * 23           label t as explored
15752  * 24           S.pop()
15753  *
15754  * convention:
15755  * 0x10 - discovered
15756  * 0x11 - discovered and fall-through edge labelled
15757  * 0x12 - discovered and fall-through and branch edges labelled
15758  * 0x20 - explored
15759  */
15760 
15761 enum {
15762 	DISCOVERED = 0x10,
15763 	EXPLORED = 0x20,
15764 	FALLTHROUGH = 1,
15765 	BRANCH = 2,
15766 };
15767 
mark_prune_point(struct bpf_verifier_env * env,int idx)15768 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15769 {
15770 	env->insn_aux_data[idx].prune_point = true;
15771 }
15772 
is_prune_point(struct bpf_verifier_env * env,int insn_idx)15773 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15774 {
15775 	return env->insn_aux_data[insn_idx].prune_point;
15776 }
15777 
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)15778 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15779 {
15780 	env->insn_aux_data[idx].force_checkpoint = true;
15781 }
15782 
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)15783 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15784 {
15785 	return env->insn_aux_data[insn_idx].force_checkpoint;
15786 }
15787 
mark_calls_callback(struct bpf_verifier_env * env,int idx)15788 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15789 {
15790 	env->insn_aux_data[idx].calls_callback = true;
15791 }
15792 
calls_callback(struct bpf_verifier_env * env,int insn_idx)15793 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15794 {
15795 	return env->insn_aux_data[insn_idx].calls_callback;
15796 }
15797 
15798 enum {
15799 	DONE_EXPLORING = 0,
15800 	KEEP_EXPLORING = 1,
15801 };
15802 
15803 /* t, w, e - match pseudo-code above:
15804  * t - index of current instruction
15805  * w - next instruction
15806  * e - edge
15807  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)15808 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15809 {
15810 	int *insn_stack = env->cfg.insn_stack;
15811 	int *insn_state = env->cfg.insn_state;
15812 
15813 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15814 		return DONE_EXPLORING;
15815 
15816 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15817 		return DONE_EXPLORING;
15818 
15819 	if (w < 0 || w >= env->prog->len) {
15820 		verbose_linfo(env, t, "%d: ", t);
15821 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15822 		return -EINVAL;
15823 	}
15824 
15825 	if (e == BRANCH) {
15826 		/* mark branch target for state pruning */
15827 		mark_prune_point(env, w);
15828 		mark_jmp_point(env, w);
15829 	}
15830 
15831 	if (insn_state[w] == 0) {
15832 		/* tree-edge */
15833 		insn_state[t] = DISCOVERED | e;
15834 		insn_state[w] = DISCOVERED;
15835 		if (env->cfg.cur_stack >= env->prog->len)
15836 			return -E2BIG;
15837 		insn_stack[env->cfg.cur_stack++] = w;
15838 		return KEEP_EXPLORING;
15839 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15840 		if (env->bpf_capable)
15841 			return DONE_EXPLORING;
15842 		verbose_linfo(env, t, "%d: ", t);
15843 		verbose_linfo(env, w, "%d: ", w);
15844 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15845 		return -EINVAL;
15846 	} else if (insn_state[w] == EXPLORED) {
15847 		/* forward- or cross-edge */
15848 		insn_state[t] = DISCOVERED | e;
15849 	} else {
15850 		verbose(env, "insn state internal bug\n");
15851 		return -EFAULT;
15852 	}
15853 	return DONE_EXPLORING;
15854 }
15855 
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)15856 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15857 				struct bpf_verifier_env *env,
15858 				bool visit_callee)
15859 {
15860 	int ret, insn_sz;
15861 
15862 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15863 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15864 	if (ret)
15865 		return ret;
15866 
15867 	mark_prune_point(env, t + insn_sz);
15868 	/* when we exit from subprog, we need to record non-linear history */
15869 	mark_jmp_point(env, t + insn_sz);
15870 
15871 	if (visit_callee) {
15872 		mark_prune_point(env, t);
15873 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15874 	}
15875 	return ret;
15876 }
15877 
15878 /* Visits the instruction at index t and returns one of the following:
15879  *  < 0 - an error occurred
15880  *  DONE_EXPLORING - the instruction was fully explored
15881  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15882  */
visit_insn(int t,struct bpf_verifier_env * env)15883 static int visit_insn(int t, struct bpf_verifier_env *env)
15884 {
15885 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15886 	int ret, off, insn_sz;
15887 
15888 	if (bpf_pseudo_func(insn))
15889 		return visit_func_call_insn(t, insns, env, true);
15890 
15891 	/* All non-branch instructions have a single fall-through edge. */
15892 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15893 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15894 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15895 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15896 	}
15897 
15898 	switch (BPF_OP(insn->code)) {
15899 	case BPF_EXIT:
15900 		return DONE_EXPLORING;
15901 
15902 	case BPF_CALL:
15903 		if (is_async_callback_calling_insn(insn))
15904 			/* Mark this call insn as a prune point to trigger
15905 			 * is_state_visited() check before call itself is
15906 			 * processed by __check_func_call(). Otherwise new
15907 			 * async state will be pushed for further exploration.
15908 			 */
15909 			mark_prune_point(env, t);
15910 		/* For functions that invoke callbacks it is not known how many times
15911 		 * callback would be called. Verifier models callback calling functions
15912 		 * by repeatedly visiting callback bodies and returning to origin call
15913 		 * instruction.
15914 		 * In order to stop such iteration verifier needs to identify when a
15915 		 * state identical some state from a previous iteration is reached.
15916 		 * Check below forces creation of checkpoint before callback calling
15917 		 * instruction to allow search for such identical states.
15918 		 */
15919 		if (is_sync_callback_calling_insn(insn)) {
15920 			mark_calls_callback(env, t);
15921 			mark_force_checkpoint(env, t);
15922 			mark_prune_point(env, t);
15923 			mark_jmp_point(env, t);
15924 		}
15925 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15926 			struct bpf_kfunc_call_arg_meta meta;
15927 
15928 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15929 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15930 				mark_prune_point(env, t);
15931 				/* Checking and saving state checkpoints at iter_next() call
15932 				 * is crucial for fast convergence of open-coded iterator loop
15933 				 * logic, so we need to force it. If we don't do that,
15934 				 * is_state_visited() might skip saving a checkpoint, causing
15935 				 * unnecessarily long sequence of not checkpointed
15936 				 * instructions and jumps, leading to exhaustion of jump
15937 				 * history buffer, and potentially other undesired outcomes.
15938 				 * It is expected that with correct open-coded iterators
15939 				 * convergence will happen quickly, so we don't run a risk of
15940 				 * exhausting memory.
15941 				 */
15942 				mark_force_checkpoint(env, t);
15943 			}
15944 		}
15945 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15946 
15947 	case BPF_JA:
15948 		if (BPF_SRC(insn->code) != BPF_K)
15949 			return -EINVAL;
15950 
15951 		if (BPF_CLASS(insn->code) == BPF_JMP)
15952 			off = insn->off;
15953 		else
15954 			off = insn->imm;
15955 
15956 		/* unconditional jump with single edge */
15957 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15958 		if (ret)
15959 			return ret;
15960 
15961 		mark_prune_point(env, t + off + 1);
15962 		mark_jmp_point(env, t + off + 1);
15963 
15964 		return ret;
15965 
15966 	default:
15967 		/* conditional jump with two edges */
15968 		mark_prune_point(env, t);
15969 		if (is_may_goto_insn(insn))
15970 			mark_force_checkpoint(env, t);
15971 
15972 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15973 		if (ret)
15974 			return ret;
15975 
15976 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15977 	}
15978 }
15979 
15980 /* non-recursive depth-first-search to detect loops in BPF program
15981  * loop == back-edge in directed graph
15982  */
check_cfg(struct bpf_verifier_env * env)15983 static int check_cfg(struct bpf_verifier_env *env)
15984 {
15985 	int insn_cnt = env->prog->len;
15986 	int *insn_stack, *insn_state;
15987 	int ex_insn_beg, i, ret = 0;
15988 	bool ex_done = false;
15989 
15990 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15991 	if (!insn_state)
15992 		return -ENOMEM;
15993 
15994 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15995 	if (!insn_stack) {
15996 		kvfree(insn_state);
15997 		return -ENOMEM;
15998 	}
15999 
16000 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
16001 	insn_stack[0] = 0; /* 0 is the first instruction */
16002 	env->cfg.cur_stack = 1;
16003 
16004 walk_cfg:
16005 	while (env->cfg.cur_stack > 0) {
16006 		int t = insn_stack[env->cfg.cur_stack - 1];
16007 
16008 		ret = visit_insn(t, env);
16009 		switch (ret) {
16010 		case DONE_EXPLORING:
16011 			insn_state[t] = EXPLORED;
16012 			env->cfg.cur_stack--;
16013 			break;
16014 		case KEEP_EXPLORING:
16015 			break;
16016 		default:
16017 			if (ret > 0) {
16018 				verbose(env, "visit_insn internal bug\n");
16019 				ret = -EFAULT;
16020 			}
16021 			goto err_free;
16022 		}
16023 	}
16024 
16025 	if (env->cfg.cur_stack < 0) {
16026 		verbose(env, "pop stack internal bug\n");
16027 		ret = -EFAULT;
16028 		goto err_free;
16029 	}
16030 
16031 	if (env->exception_callback_subprog && !ex_done) {
16032 		ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
16033 
16034 		insn_state[ex_insn_beg] = DISCOVERED;
16035 		insn_stack[0] = ex_insn_beg;
16036 		env->cfg.cur_stack = 1;
16037 		ex_done = true;
16038 		goto walk_cfg;
16039 	}
16040 
16041 	for (i = 0; i < insn_cnt; i++) {
16042 		struct bpf_insn *insn = &env->prog->insnsi[i];
16043 
16044 		if (insn_state[i] != EXPLORED) {
16045 			verbose(env, "unreachable insn %d\n", i);
16046 			ret = -EINVAL;
16047 			goto err_free;
16048 		}
16049 		if (bpf_is_ldimm64(insn)) {
16050 			if (insn_state[i + 1] != 0) {
16051 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
16052 				ret = -EINVAL;
16053 				goto err_free;
16054 			}
16055 			i++; /* skip second half of ldimm64 */
16056 		}
16057 	}
16058 	ret = 0; /* cfg looks good */
16059 
16060 err_free:
16061 	kvfree(insn_state);
16062 	kvfree(insn_stack);
16063 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
16064 	return ret;
16065 }
16066 
check_abnormal_return(struct bpf_verifier_env * env)16067 static int check_abnormal_return(struct bpf_verifier_env *env)
16068 {
16069 	int i;
16070 
16071 	for (i = 1; i < env->subprog_cnt; i++) {
16072 		if (env->subprog_info[i].has_ld_abs) {
16073 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
16074 			return -EINVAL;
16075 		}
16076 		if (env->subprog_info[i].has_tail_call) {
16077 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
16078 			return -EINVAL;
16079 		}
16080 	}
16081 	return 0;
16082 }
16083 
16084 /* The minimum supported BTF func info size */
16085 #define MIN_BPF_FUNCINFO_SIZE	8
16086 #define MAX_FUNCINFO_REC_SIZE	252
16087 
check_btf_func_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)16088 static int check_btf_func_early(struct bpf_verifier_env *env,
16089 				const union bpf_attr *attr,
16090 				bpfptr_t uattr)
16091 {
16092 	u32 krec_size = sizeof(struct bpf_func_info);
16093 	const struct btf_type *type, *func_proto;
16094 	u32 i, nfuncs, urec_size, min_size;
16095 	struct bpf_func_info *krecord;
16096 	struct bpf_prog *prog;
16097 	const struct btf *btf;
16098 	u32 prev_offset = 0;
16099 	bpfptr_t urecord;
16100 	int ret = -ENOMEM;
16101 
16102 	nfuncs = attr->func_info_cnt;
16103 	if (!nfuncs) {
16104 		if (check_abnormal_return(env))
16105 			return -EINVAL;
16106 		return 0;
16107 	}
16108 
16109 	urec_size = attr->func_info_rec_size;
16110 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
16111 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
16112 	    urec_size % sizeof(u32)) {
16113 		verbose(env, "invalid func info rec size %u\n", urec_size);
16114 		return -EINVAL;
16115 	}
16116 
16117 	prog = env->prog;
16118 	btf = prog->aux->btf;
16119 
16120 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16121 	min_size = min_t(u32, krec_size, urec_size);
16122 
16123 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
16124 	if (!krecord)
16125 		return -ENOMEM;
16126 
16127 	for (i = 0; i < nfuncs; i++) {
16128 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
16129 		if (ret) {
16130 			if (ret == -E2BIG) {
16131 				verbose(env, "nonzero tailing record in func info");
16132 				/* set the size kernel expects so loader can zero
16133 				 * out the rest of the record.
16134 				 */
16135 				if (copy_to_bpfptr_offset(uattr,
16136 							  offsetof(union bpf_attr, func_info_rec_size),
16137 							  &min_size, sizeof(min_size)))
16138 					ret = -EFAULT;
16139 			}
16140 			goto err_free;
16141 		}
16142 
16143 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
16144 			ret = -EFAULT;
16145 			goto err_free;
16146 		}
16147 
16148 		/* check insn_off */
16149 		ret = -EINVAL;
16150 		if (i == 0) {
16151 			if (krecord[i].insn_off) {
16152 				verbose(env,
16153 					"nonzero insn_off %u for the first func info record",
16154 					krecord[i].insn_off);
16155 				goto err_free;
16156 			}
16157 		} else if (krecord[i].insn_off <= prev_offset) {
16158 			verbose(env,
16159 				"same or smaller insn offset (%u) than previous func info record (%u)",
16160 				krecord[i].insn_off, prev_offset);
16161 			goto err_free;
16162 		}
16163 
16164 		/* check type_id */
16165 		type = btf_type_by_id(btf, krecord[i].type_id);
16166 		if (!type || !btf_type_is_func(type)) {
16167 			verbose(env, "invalid type id %d in func info",
16168 				krecord[i].type_id);
16169 			goto err_free;
16170 		}
16171 
16172 		func_proto = btf_type_by_id(btf, type->type);
16173 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
16174 			/* btf_func_check() already verified it during BTF load */
16175 			goto err_free;
16176 
16177 		prev_offset = krecord[i].insn_off;
16178 		bpfptr_add(&urecord, urec_size);
16179 	}
16180 
16181 	prog->aux->func_info = krecord;
16182 	prog->aux->func_info_cnt = nfuncs;
16183 	return 0;
16184 
16185 err_free:
16186 	kvfree(krecord);
16187 	return ret;
16188 }
16189 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)16190 static int check_btf_func(struct bpf_verifier_env *env,
16191 			  const union bpf_attr *attr,
16192 			  bpfptr_t uattr)
16193 {
16194 	const struct btf_type *type, *func_proto, *ret_type;
16195 	u32 i, nfuncs, urec_size;
16196 	struct bpf_func_info *krecord;
16197 	struct bpf_func_info_aux *info_aux = NULL;
16198 	struct bpf_prog *prog;
16199 	const struct btf *btf;
16200 	bpfptr_t urecord;
16201 	bool scalar_return;
16202 	int ret = -ENOMEM;
16203 
16204 	nfuncs = attr->func_info_cnt;
16205 	if (!nfuncs) {
16206 		if (check_abnormal_return(env))
16207 			return -EINVAL;
16208 		return 0;
16209 	}
16210 	if (nfuncs != env->subprog_cnt) {
16211 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
16212 		return -EINVAL;
16213 	}
16214 
16215 	urec_size = attr->func_info_rec_size;
16216 
16217 	prog = env->prog;
16218 	btf = prog->aux->btf;
16219 
16220 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
16221 
16222 	krecord = prog->aux->func_info;
16223 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
16224 	if (!info_aux)
16225 		return -ENOMEM;
16226 
16227 	for (i = 0; i < nfuncs; i++) {
16228 		/* check insn_off */
16229 		ret = -EINVAL;
16230 
16231 		if (env->subprog_info[i].start != krecord[i].insn_off) {
16232 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
16233 			goto err_free;
16234 		}
16235 
16236 		/* Already checked type_id */
16237 		type = btf_type_by_id(btf, krecord[i].type_id);
16238 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
16239 		/* Already checked func_proto */
16240 		func_proto = btf_type_by_id(btf, type->type);
16241 
16242 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
16243 		scalar_return =
16244 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
16245 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
16246 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
16247 			goto err_free;
16248 		}
16249 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
16250 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
16251 			goto err_free;
16252 		}
16253 
16254 		bpfptr_add(&urecord, urec_size);
16255 	}
16256 
16257 	prog->aux->func_info_aux = info_aux;
16258 	return 0;
16259 
16260 err_free:
16261 	kfree(info_aux);
16262 	return ret;
16263 }
16264 
adjust_btf_func(struct bpf_verifier_env * env)16265 static void adjust_btf_func(struct bpf_verifier_env *env)
16266 {
16267 	struct bpf_prog_aux *aux = env->prog->aux;
16268 	int i;
16269 
16270 	if (!aux->func_info)
16271 		return;
16272 
16273 	/* func_info is not available for hidden subprogs */
16274 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
16275 		aux->func_info[i].insn_off = env->subprog_info[i].start;
16276 }
16277 
16278 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
16279 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
16280 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)16281 static int check_btf_line(struct bpf_verifier_env *env,
16282 			  const union bpf_attr *attr,
16283 			  bpfptr_t uattr)
16284 {
16285 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
16286 	struct bpf_subprog_info *sub;
16287 	struct bpf_line_info *linfo;
16288 	struct bpf_prog *prog;
16289 	const struct btf *btf;
16290 	bpfptr_t ulinfo;
16291 	int err;
16292 
16293 	nr_linfo = attr->line_info_cnt;
16294 	if (!nr_linfo)
16295 		return 0;
16296 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
16297 		return -EINVAL;
16298 
16299 	rec_size = attr->line_info_rec_size;
16300 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
16301 	    rec_size > MAX_LINEINFO_REC_SIZE ||
16302 	    rec_size & (sizeof(u32) - 1))
16303 		return -EINVAL;
16304 
16305 	/* Need to zero it in case the userspace may
16306 	 * pass in a smaller bpf_line_info object.
16307 	 */
16308 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
16309 			 GFP_KERNEL | __GFP_NOWARN);
16310 	if (!linfo)
16311 		return -ENOMEM;
16312 
16313 	prog = env->prog;
16314 	btf = prog->aux->btf;
16315 
16316 	s = 0;
16317 	sub = env->subprog_info;
16318 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
16319 	expected_size = sizeof(struct bpf_line_info);
16320 	ncopy = min_t(u32, expected_size, rec_size);
16321 	for (i = 0; i < nr_linfo; i++) {
16322 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
16323 		if (err) {
16324 			if (err == -E2BIG) {
16325 				verbose(env, "nonzero tailing record in line_info");
16326 				if (copy_to_bpfptr_offset(uattr,
16327 							  offsetof(union bpf_attr, line_info_rec_size),
16328 							  &expected_size, sizeof(expected_size)))
16329 					err = -EFAULT;
16330 			}
16331 			goto err_free;
16332 		}
16333 
16334 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
16335 			err = -EFAULT;
16336 			goto err_free;
16337 		}
16338 
16339 		/*
16340 		 * Check insn_off to ensure
16341 		 * 1) strictly increasing AND
16342 		 * 2) bounded by prog->len
16343 		 *
16344 		 * The linfo[0].insn_off == 0 check logically falls into
16345 		 * the later "missing bpf_line_info for func..." case
16346 		 * because the first linfo[0].insn_off must be the
16347 		 * first sub also and the first sub must have
16348 		 * subprog_info[0].start == 0.
16349 		 */
16350 		if ((i && linfo[i].insn_off <= prev_offset) ||
16351 		    linfo[i].insn_off >= prog->len) {
16352 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
16353 				i, linfo[i].insn_off, prev_offset,
16354 				prog->len);
16355 			err = -EINVAL;
16356 			goto err_free;
16357 		}
16358 
16359 		if (!prog->insnsi[linfo[i].insn_off].code) {
16360 			verbose(env,
16361 				"Invalid insn code at line_info[%u].insn_off\n",
16362 				i);
16363 			err = -EINVAL;
16364 			goto err_free;
16365 		}
16366 
16367 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
16368 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
16369 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
16370 			err = -EINVAL;
16371 			goto err_free;
16372 		}
16373 
16374 		if (s != env->subprog_cnt) {
16375 			if (linfo[i].insn_off == sub[s].start) {
16376 				sub[s].linfo_idx = i;
16377 				s++;
16378 			} else if (sub[s].start < linfo[i].insn_off) {
16379 				verbose(env, "missing bpf_line_info for func#%u\n", s);
16380 				err = -EINVAL;
16381 				goto err_free;
16382 			}
16383 		}
16384 
16385 		prev_offset = linfo[i].insn_off;
16386 		bpfptr_add(&ulinfo, rec_size);
16387 	}
16388 
16389 	if (s != env->subprog_cnt) {
16390 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
16391 			env->subprog_cnt - s, s);
16392 		err = -EINVAL;
16393 		goto err_free;
16394 	}
16395 
16396 	prog->aux->linfo = linfo;
16397 	prog->aux->nr_linfo = nr_linfo;
16398 
16399 	return 0;
16400 
16401 err_free:
16402 	kvfree(linfo);
16403 	return err;
16404 }
16405 
16406 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
16407 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
16408 
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)16409 static int check_core_relo(struct bpf_verifier_env *env,
16410 			   const union bpf_attr *attr,
16411 			   bpfptr_t uattr)
16412 {
16413 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
16414 	struct bpf_core_relo core_relo = {};
16415 	struct bpf_prog *prog = env->prog;
16416 	const struct btf *btf = prog->aux->btf;
16417 	struct bpf_core_ctx ctx = {
16418 		.log = &env->log,
16419 		.btf = btf,
16420 	};
16421 	bpfptr_t u_core_relo;
16422 	int err;
16423 
16424 	nr_core_relo = attr->core_relo_cnt;
16425 	if (!nr_core_relo)
16426 		return 0;
16427 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
16428 		return -EINVAL;
16429 
16430 	rec_size = attr->core_relo_rec_size;
16431 	if (rec_size < MIN_CORE_RELO_SIZE ||
16432 	    rec_size > MAX_CORE_RELO_SIZE ||
16433 	    rec_size % sizeof(u32))
16434 		return -EINVAL;
16435 
16436 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
16437 	expected_size = sizeof(struct bpf_core_relo);
16438 	ncopy = min_t(u32, expected_size, rec_size);
16439 
16440 	/* Unlike func_info and line_info, copy and apply each CO-RE
16441 	 * relocation record one at a time.
16442 	 */
16443 	for (i = 0; i < nr_core_relo; i++) {
16444 		/* future proofing when sizeof(bpf_core_relo) changes */
16445 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
16446 		if (err) {
16447 			if (err == -E2BIG) {
16448 				verbose(env, "nonzero tailing record in core_relo");
16449 				if (copy_to_bpfptr_offset(uattr,
16450 							  offsetof(union bpf_attr, core_relo_rec_size),
16451 							  &expected_size, sizeof(expected_size)))
16452 					err = -EFAULT;
16453 			}
16454 			break;
16455 		}
16456 
16457 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16458 			err = -EFAULT;
16459 			break;
16460 		}
16461 
16462 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16463 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16464 				i, core_relo.insn_off, prog->len);
16465 			err = -EINVAL;
16466 			break;
16467 		}
16468 
16469 		err = bpf_core_apply(&ctx, &core_relo, i,
16470 				     &prog->insnsi[core_relo.insn_off / 8]);
16471 		if (err)
16472 			break;
16473 		bpfptr_add(&u_core_relo, rec_size);
16474 	}
16475 	return err;
16476 }
16477 
check_btf_info_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)16478 static int check_btf_info_early(struct bpf_verifier_env *env,
16479 				const union bpf_attr *attr,
16480 				bpfptr_t uattr)
16481 {
16482 	struct btf *btf;
16483 	int err;
16484 
16485 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16486 		if (check_abnormal_return(env))
16487 			return -EINVAL;
16488 		return 0;
16489 	}
16490 
16491 	btf = btf_get_by_fd(attr->prog_btf_fd);
16492 	if (IS_ERR(btf))
16493 		return PTR_ERR(btf);
16494 	if (btf_is_kernel(btf)) {
16495 		btf_put(btf);
16496 		return -EACCES;
16497 	}
16498 	env->prog->aux->btf = btf;
16499 
16500 	err = check_btf_func_early(env, attr, uattr);
16501 	if (err)
16502 		return err;
16503 	return 0;
16504 }
16505 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)16506 static int check_btf_info(struct bpf_verifier_env *env,
16507 			  const union bpf_attr *attr,
16508 			  bpfptr_t uattr)
16509 {
16510 	int err;
16511 
16512 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
16513 		if (check_abnormal_return(env))
16514 			return -EINVAL;
16515 		return 0;
16516 	}
16517 
16518 	err = check_btf_func(env, attr, uattr);
16519 	if (err)
16520 		return err;
16521 
16522 	err = check_btf_line(env, attr, uattr);
16523 	if (err)
16524 		return err;
16525 
16526 	err = check_core_relo(env, attr, uattr);
16527 	if (err)
16528 		return err;
16529 
16530 	return 0;
16531 }
16532 
16533 /* check %cur's range satisfies %old's */
range_within(const struct bpf_reg_state * old,const struct bpf_reg_state * cur)16534 static bool range_within(const struct bpf_reg_state *old,
16535 			 const struct bpf_reg_state *cur)
16536 {
16537 	return old->umin_value <= cur->umin_value &&
16538 	       old->umax_value >= cur->umax_value &&
16539 	       old->smin_value <= cur->smin_value &&
16540 	       old->smax_value >= cur->smax_value &&
16541 	       old->u32_min_value <= cur->u32_min_value &&
16542 	       old->u32_max_value >= cur->u32_max_value &&
16543 	       old->s32_min_value <= cur->s32_min_value &&
16544 	       old->s32_max_value >= cur->s32_max_value;
16545 }
16546 
16547 /* If in the old state two registers had the same id, then they need to have
16548  * the same id in the new state as well.  But that id could be different from
16549  * the old state, so we need to track the mapping from old to new ids.
16550  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16551  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16552  * regs with a different old id could still have new id 9, we don't care about
16553  * that.
16554  * So we look through our idmap to see if this old id has been seen before.  If
16555  * so, we require the new id to match; otherwise, we add the id pair to the map.
16556  */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)16557 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16558 {
16559 	struct bpf_id_pair *map = idmap->map;
16560 	unsigned int i;
16561 
16562 	/* either both IDs should be set or both should be zero */
16563 	if (!!old_id != !!cur_id)
16564 		return false;
16565 
16566 	if (old_id == 0) /* cur_id == 0 as well */
16567 		return true;
16568 
16569 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16570 		if (!map[i].old) {
16571 			/* Reached an empty slot; haven't seen this id before */
16572 			map[i].old = old_id;
16573 			map[i].cur = cur_id;
16574 			return true;
16575 		}
16576 		if (map[i].old == old_id)
16577 			return map[i].cur == cur_id;
16578 		if (map[i].cur == cur_id)
16579 			return false;
16580 	}
16581 	/* We ran out of idmap slots, which should be impossible */
16582 	WARN_ON_ONCE(1);
16583 	return false;
16584 }
16585 
16586 /* Similar to check_ids(), but allocate a unique temporary ID
16587  * for 'old_id' or 'cur_id' of zero.
16588  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16589  */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)16590 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16591 {
16592 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16593 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16594 
16595 	return check_ids(old_id, cur_id, idmap);
16596 }
16597 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)16598 static void clean_func_state(struct bpf_verifier_env *env,
16599 			     struct bpf_func_state *st)
16600 {
16601 	enum bpf_reg_liveness live;
16602 	int i, j;
16603 
16604 	for (i = 0; i < BPF_REG_FP; i++) {
16605 		live = st->regs[i].live;
16606 		/* liveness must not touch this register anymore */
16607 		st->regs[i].live |= REG_LIVE_DONE;
16608 		if (!(live & REG_LIVE_READ))
16609 			/* since the register is unused, clear its state
16610 			 * to make further comparison simpler
16611 			 */
16612 			__mark_reg_not_init(env, &st->regs[i]);
16613 	}
16614 
16615 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16616 		live = st->stack[i].spilled_ptr.live;
16617 		/* liveness must not touch this stack slot anymore */
16618 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16619 		if (!(live & REG_LIVE_READ)) {
16620 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16621 			for (j = 0; j < BPF_REG_SIZE; j++)
16622 				st->stack[i].slot_type[j] = STACK_INVALID;
16623 		}
16624 	}
16625 }
16626 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)16627 static void clean_verifier_state(struct bpf_verifier_env *env,
16628 				 struct bpf_verifier_state *st)
16629 {
16630 	int i;
16631 
16632 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16633 		/* all regs in this state in all frames were already marked */
16634 		return;
16635 
16636 	for (i = 0; i <= st->curframe; i++)
16637 		clean_func_state(env, st->frame[i]);
16638 }
16639 
16640 /* the parentage chains form a tree.
16641  * the verifier states are added to state lists at given insn and
16642  * pushed into state stack for future exploration.
16643  * when the verifier reaches bpf_exit insn some of the verifer states
16644  * stored in the state lists have their final liveness state already,
16645  * but a lot of states will get revised from liveness point of view when
16646  * the verifier explores other branches.
16647  * Example:
16648  * 1: r0 = 1
16649  * 2: if r1 == 100 goto pc+1
16650  * 3: r0 = 2
16651  * 4: exit
16652  * when the verifier reaches exit insn the register r0 in the state list of
16653  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16654  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16655  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16656  *
16657  * Since the verifier pushes the branch states as it sees them while exploring
16658  * the program the condition of walking the branch instruction for the second
16659  * time means that all states below this branch were already explored and
16660  * their final liveness marks are already propagated.
16661  * Hence when the verifier completes the search of state list in is_state_visited()
16662  * we can call this clean_live_states() function to mark all liveness states
16663  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16664  * will not be used.
16665  * This function also clears the registers and stack for states that !READ
16666  * to simplify state merging.
16667  *
16668  * Important note here that walking the same branch instruction in the callee
16669  * doesn't meant that the states are DONE. The verifier has to compare
16670  * the callsites
16671  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)16672 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16673 			      struct bpf_verifier_state *cur)
16674 {
16675 	struct bpf_verifier_state_list *sl;
16676 
16677 	sl = *explored_state(env, insn);
16678 	while (sl) {
16679 		if (sl->state.branches)
16680 			goto next;
16681 		if (sl->state.insn_idx != insn ||
16682 		    !same_callsites(&sl->state, cur))
16683 			goto next;
16684 		clean_verifier_state(env, &sl->state);
16685 next:
16686 		sl = sl->next;
16687 	}
16688 }
16689 
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)16690 static bool regs_exact(const struct bpf_reg_state *rold,
16691 		       const struct bpf_reg_state *rcur,
16692 		       struct bpf_idmap *idmap)
16693 {
16694 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16695 	       check_ids(rold->id, rcur->id, idmap) &&
16696 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16697 }
16698 
16699 enum exact_level {
16700 	NOT_EXACT,
16701 	EXACT,
16702 	RANGE_WITHIN
16703 };
16704 
16705 /* 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)16706 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16707 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
16708 		    enum exact_level exact)
16709 {
16710 	if (exact == EXACT)
16711 		return regs_exact(rold, rcur, idmap);
16712 
16713 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
16714 		/* explored state didn't use this */
16715 		return true;
16716 	if (rold->type == NOT_INIT) {
16717 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
16718 			/* explored state can't have used this */
16719 			return true;
16720 	}
16721 
16722 	/* Enforce that register types have to match exactly, including their
16723 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16724 	 * rule.
16725 	 *
16726 	 * One can make a point that using a pointer register as unbounded
16727 	 * SCALAR would be technically acceptable, but this could lead to
16728 	 * pointer leaks because scalars are allowed to leak while pointers
16729 	 * are not. We could make this safe in special cases if root is
16730 	 * calling us, but it's probably not worth the hassle.
16731 	 *
16732 	 * Also, register types that are *not* MAYBE_NULL could technically be
16733 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16734 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16735 	 * to the same map).
16736 	 * However, if the old MAYBE_NULL register then got NULL checked,
16737 	 * doing so could have affected others with the same id, and we can't
16738 	 * check for that because we lost the id when we converted to
16739 	 * a non-MAYBE_NULL variant.
16740 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16741 	 * non-MAYBE_NULL registers as well.
16742 	 */
16743 	if (rold->type != rcur->type)
16744 		return false;
16745 
16746 	switch (base_type(rold->type)) {
16747 	case SCALAR_VALUE:
16748 		if (env->explore_alu_limits) {
16749 			/* explore_alu_limits disables tnum_in() and range_within()
16750 			 * logic and requires everything to be strict
16751 			 */
16752 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16753 			       check_scalar_ids(rold->id, rcur->id, idmap);
16754 		}
16755 		if (!rold->precise && exact == NOT_EXACT)
16756 			return true;
16757 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
16758 			return false;
16759 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
16760 			return false;
16761 		/* Why check_ids() for scalar registers?
16762 		 *
16763 		 * Consider the following BPF code:
16764 		 *   1: r6 = ... unbound scalar, ID=a ...
16765 		 *   2: r7 = ... unbound scalar, ID=b ...
16766 		 *   3: if (r6 > r7) goto +1
16767 		 *   4: r6 = r7
16768 		 *   5: if (r6 > X) goto ...
16769 		 *   6: ... memory operation using r7 ...
16770 		 *
16771 		 * First verification path is [1-6]:
16772 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16773 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16774 		 *   r7 <= X, because r6 and r7 share same id.
16775 		 * Next verification path is [1-4, 6].
16776 		 *
16777 		 * Instruction (6) would be reached in two states:
16778 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16779 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16780 		 *
16781 		 * Use check_ids() to distinguish these states.
16782 		 * ---
16783 		 * Also verify that new value satisfies old value range knowledge.
16784 		 */
16785 		return range_within(rold, rcur) &&
16786 		       tnum_in(rold->var_off, rcur->var_off) &&
16787 		       check_scalar_ids(rold->id, rcur->id, idmap);
16788 	case PTR_TO_MAP_KEY:
16789 	case PTR_TO_MAP_VALUE:
16790 	case PTR_TO_MEM:
16791 	case PTR_TO_BUF:
16792 	case PTR_TO_TP_BUFFER:
16793 		/* If the new min/max/var_off satisfy the old ones and
16794 		 * everything else matches, we are OK.
16795 		 */
16796 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16797 		       range_within(rold, rcur) &&
16798 		       tnum_in(rold->var_off, rcur->var_off) &&
16799 		       check_ids(rold->id, rcur->id, idmap) &&
16800 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16801 	case PTR_TO_PACKET_META:
16802 	case PTR_TO_PACKET:
16803 		/* We must have at least as much range as the old ptr
16804 		 * did, so that any accesses which were safe before are
16805 		 * still safe.  This is true even if old range < old off,
16806 		 * since someone could have accessed through (ptr - k), or
16807 		 * even done ptr -= k in a register, to get a safe access.
16808 		 */
16809 		if (rold->range > rcur->range)
16810 			return false;
16811 		/* If the offsets don't match, we can't trust our alignment;
16812 		 * nor can we be sure that we won't fall out of range.
16813 		 */
16814 		if (rold->off != rcur->off)
16815 			return false;
16816 		/* id relations must be preserved */
16817 		if (!check_ids(rold->id, rcur->id, idmap))
16818 			return false;
16819 		/* new val must satisfy old val knowledge */
16820 		return range_within(rold, rcur) &&
16821 		       tnum_in(rold->var_off, rcur->var_off);
16822 	case PTR_TO_STACK:
16823 		/* two stack pointers are equal only if they're pointing to
16824 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16825 		 */
16826 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16827 	case PTR_TO_ARENA:
16828 		return true;
16829 	default:
16830 		return regs_exact(rold, rcur, idmap);
16831 	}
16832 }
16833 
16834 static struct bpf_reg_state unbound_reg;
16835 
unbound_reg_init(void)16836 static __init int unbound_reg_init(void)
16837 {
16838 	__mark_reg_unknown_imprecise(&unbound_reg);
16839 	unbound_reg.live |= REG_LIVE_READ;
16840 	return 0;
16841 }
16842 late_initcall(unbound_reg_init);
16843 
is_stack_all_misc(struct bpf_verifier_env * env,struct bpf_stack_state * stack)16844 static bool is_stack_all_misc(struct bpf_verifier_env *env,
16845 			      struct bpf_stack_state *stack)
16846 {
16847 	u32 i;
16848 
16849 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
16850 		if ((stack->slot_type[i] == STACK_MISC) ||
16851 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
16852 			continue;
16853 		return false;
16854 	}
16855 
16856 	return true;
16857 }
16858 
scalar_reg_for_stack(struct bpf_verifier_env * env,struct bpf_stack_state * stack)16859 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
16860 						  struct bpf_stack_state *stack)
16861 {
16862 	if (is_spilled_scalar_reg64(stack))
16863 		return &stack->spilled_ptr;
16864 
16865 	if (is_stack_all_misc(env, stack))
16866 		return &unbound_reg;
16867 
16868 	return NULL;
16869 }
16870 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,enum exact_level exact)16871 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16872 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
16873 		      enum exact_level exact)
16874 {
16875 	int i, spi;
16876 
16877 	/* walk slots of the explored stack and ignore any additional
16878 	 * slots in the current stack, since explored(safe) state
16879 	 * didn't use them
16880 	 */
16881 	for (i = 0; i < old->allocated_stack; i++) {
16882 		struct bpf_reg_state *old_reg, *cur_reg;
16883 
16884 		spi = i / BPF_REG_SIZE;
16885 
16886 		if (exact != NOT_EXACT &&
16887 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16888 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16889 			return false;
16890 
16891 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
16892 		    && exact == NOT_EXACT) {
16893 			i += BPF_REG_SIZE - 1;
16894 			/* explored state didn't use this */
16895 			continue;
16896 		}
16897 
16898 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16899 			continue;
16900 
16901 		if (env->allow_uninit_stack &&
16902 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16903 			continue;
16904 
16905 		/* explored stack has more populated slots than current stack
16906 		 * and these slots were used
16907 		 */
16908 		if (i >= cur->allocated_stack)
16909 			return false;
16910 
16911 		/* 64-bit scalar spill vs all slots MISC and vice versa.
16912 		 * Load from all slots MISC produces unbound scalar.
16913 		 * Construct a fake register for such stack and call
16914 		 * regsafe() to ensure scalar ids are compared.
16915 		 */
16916 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
16917 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
16918 		if (old_reg && cur_reg) {
16919 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
16920 				return false;
16921 			i += BPF_REG_SIZE - 1;
16922 			continue;
16923 		}
16924 
16925 		/* if old state was safe with misc data in the stack
16926 		 * it will be safe with zero-initialized stack.
16927 		 * The opposite is not true
16928 		 */
16929 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16930 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16931 			continue;
16932 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16933 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16934 			/* Ex: old explored (safe) state has STACK_SPILL in
16935 			 * this stack slot, but current has STACK_MISC ->
16936 			 * this verifier states are not equivalent,
16937 			 * return false to continue verification of this path
16938 			 */
16939 			return false;
16940 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16941 			continue;
16942 		/* Both old and cur are having same slot_type */
16943 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16944 		case STACK_SPILL:
16945 			/* when explored and current stack slot are both storing
16946 			 * spilled registers, check that stored pointers types
16947 			 * are the same as well.
16948 			 * Ex: explored safe path could have stored
16949 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16950 			 * but current path has stored:
16951 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16952 			 * such verifier states are not equivalent.
16953 			 * return false to continue verification of this path
16954 			 */
16955 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16956 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16957 				return false;
16958 			break;
16959 		case STACK_DYNPTR:
16960 			old_reg = &old->stack[spi].spilled_ptr;
16961 			cur_reg = &cur->stack[spi].spilled_ptr;
16962 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16963 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16964 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16965 				return false;
16966 			break;
16967 		case STACK_ITER:
16968 			old_reg = &old->stack[spi].spilled_ptr;
16969 			cur_reg = &cur->stack[spi].spilled_ptr;
16970 			/* iter.depth is not compared between states as it
16971 			 * doesn't matter for correctness and would otherwise
16972 			 * prevent convergence; we maintain it only to prevent
16973 			 * infinite loop check triggering, see
16974 			 * iter_active_depths_differ()
16975 			 */
16976 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16977 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16978 			    old_reg->iter.state != cur_reg->iter.state ||
16979 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16980 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16981 				return false;
16982 			break;
16983 		case STACK_MISC:
16984 		case STACK_ZERO:
16985 		case STACK_INVALID:
16986 			continue;
16987 		/* Ensure that new unhandled slot types return false by default */
16988 		default:
16989 			return false;
16990 		}
16991 	}
16992 	return true;
16993 }
16994 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap)16995 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16996 		    struct bpf_idmap *idmap)
16997 {
16998 	int i;
16999 
17000 	if (old->acquired_refs != cur->acquired_refs)
17001 		return false;
17002 
17003 	for (i = 0; i < old->acquired_refs; i++) {
17004 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
17005 			return false;
17006 	}
17007 
17008 	return true;
17009 }
17010 
17011 /* compare two verifier states
17012  *
17013  * all states stored in state_list are known to be valid, since
17014  * verifier reached 'bpf_exit' instruction through them
17015  *
17016  * this function is called when verifier exploring different branches of
17017  * execution popped from the state stack. If it sees an old state that has
17018  * more strict register state and more strict stack state then this execution
17019  * branch doesn't need to be explored further, since verifier already
17020  * concluded that more strict state leads to valid finish.
17021  *
17022  * Therefore two states are equivalent if register state is more conservative
17023  * and explored stack state is more conservative than the current one.
17024  * Example:
17025  *       explored                   current
17026  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
17027  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
17028  *
17029  * In other words if current stack state (one being explored) has more
17030  * valid slots than old one that already passed validation, it means
17031  * the verifier can stop exploring and conclude that current state is valid too
17032  *
17033  * Similarly with registers. If explored state has register type as invalid
17034  * whereas register type in current state is meaningful, it means that
17035  * the current state will reach 'bpf_exit' instruction safely
17036  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,enum exact_level exact)17037 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
17038 			      struct bpf_func_state *cur, enum exact_level exact)
17039 {
17040 	int i;
17041 
17042 	if (old->callback_depth > cur->callback_depth)
17043 		return false;
17044 
17045 	for (i = 0; i < MAX_BPF_REG; i++)
17046 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
17047 			     &env->idmap_scratch, exact))
17048 			return false;
17049 
17050 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
17051 		return false;
17052 
17053 	if (!refsafe(old, cur, &env->idmap_scratch))
17054 		return false;
17055 
17056 	return true;
17057 }
17058 
reset_idmap_scratch(struct bpf_verifier_env * env)17059 static void reset_idmap_scratch(struct bpf_verifier_env *env)
17060 {
17061 	env->idmap_scratch.tmp_id_gen = env->id_gen;
17062 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
17063 }
17064 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,enum exact_level exact)17065 static bool states_equal(struct bpf_verifier_env *env,
17066 			 struct bpf_verifier_state *old,
17067 			 struct bpf_verifier_state *cur,
17068 			 enum exact_level exact)
17069 {
17070 	int i;
17071 
17072 	if (old->curframe != cur->curframe)
17073 		return false;
17074 
17075 	reset_idmap_scratch(env);
17076 
17077 	/* Verification state from speculative execution simulation
17078 	 * must never prune a non-speculative execution one.
17079 	 */
17080 	if (old->speculative && !cur->speculative)
17081 		return false;
17082 
17083 	if (old->active_lock.ptr != cur->active_lock.ptr)
17084 		return false;
17085 
17086 	/* Old and cur active_lock's have to be either both present
17087 	 * or both absent.
17088 	 */
17089 	if (!!old->active_lock.id != !!cur->active_lock.id)
17090 		return false;
17091 
17092 	if (old->active_lock.id &&
17093 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
17094 		return false;
17095 
17096 	if (old->active_rcu_lock != cur->active_rcu_lock)
17097 		return false;
17098 
17099 	if (old->active_preempt_lock != cur->active_preempt_lock)
17100 		return false;
17101 
17102 	if (old->in_sleepable != cur->in_sleepable)
17103 		return false;
17104 
17105 	/* for states to be equal callsites have to be the same
17106 	 * and all frame states need to be equivalent
17107 	 */
17108 	for (i = 0; i <= old->curframe; i++) {
17109 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
17110 			return false;
17111 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
17112 			return false;
17113 	}
17114 	return true;
17115 }
17116 
17117 /* Return 0 if no propagation happened. Return negative error code if error
17118  * happened. Otherwise, return the propagated bit.
17119  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)17120 static int propagate_liveness_reg(struct bpf_verifier_env *env,
17121 				  struct bpf_reg_state *reg,
17122 				  struct bpf_reg_state *parent_reg)
17123 {
17124 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
17125 	u8 flag = reg->live & REG_LIVE_READ;
17126 	int err;
17127 
17128 	/* When comes here, read flags of PARENT_REG or REG could be any of
17129 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
17130 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
17131 	 */
17132 	if (parent_flag == REG_LIVE_READ64 ||
17133 	    /* Or if there is no read flag from REG. */
17134 	    !flag ||
17135 	    /* Or if the read flag from REG is the same as PARENT_REG. */
17136 	    parent_flag == flag)
17137 		return 0;
17138 
17139 	err = mark_reg_read(env, reg, parent_reg, flag);
17140 	if (err)
17141 		return err;
17142 
17143 	return flag;
17144 }
17145 
17146 /* A write screens off any subsequent reads; but write marks come from the
17147  * straight-line code between a state and its parent.  When we arrive at an
17148  * equivalent state (jump target or such) we didn't arrive by the straight-line
17149  * code, so read marks in the state must propagate to the parent regardless
17150  * of the state's write marks. That's what 'parent == state->parent' comparison
17151  * in mark_reg_read() is for.
17152  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)17153 static int propagate_liveness(struct bpf_verifier_env *env,
17154 			      const struct bpf_verifier_state *vstate,
17155 			      struct bpf_verifier_state *vparent)
17156 {
17157 	struct bpf_reg_state *state_reg, *parent_reg;
17158 	struct bpf_func_state *state, *parent;
17159 	int i, frame, err = 0;
17160 
17161 	if (vparent->curframe != vstate->curframe) {
17162 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
17163 		     vparent->curframe, vstate->curframe);
17164 		return -EFAULT;
17165 	}
17166 	/* Propagate read liveness of registers... */
17167 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
17168 	for (frame = 0; frame <= vstate->curframe; frame++) {
17169 		parent = vparent->frame[frame];
17170 		state = vstate->frame[frame];
17171 		parent_reg = parent->regs;
17172 		state_reg = state->regs;
17173 		/* We don't need to worry about FP liveness, it's read-only */
17174 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
17175 			err = propagate_liveness_reg(env, &state_reg[i],
17176 						     &parent_reg[i]);
17177 			if (err < 0)
17178 				return err;
17179 			if (err == REG_LIVE_READ64)
17180 				mark_insn_zext(env, &parent_reg[i]);
17181 		}
17182 
17183 		/* Propagate stack slots. */
17184 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
17185 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
17186 			parent_reg = &parent->stack[i].spilled_ptr;
17187 			state_reg = &state->stack[i].spilled_ptr;
17188 			err = propagate_liveness_reg(env, state_reg,
17189 						     parent_reg);
17190 			if (err < 0)
17191 				return err;
17192 		}
17193 	}
17194 	return 0;
17195 }
17196 
17197 /* find precise scalars in the previous equivalent state and
17198  * propagate them into the current state
17199  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)17200 static int propagate_precision(struct bpf_verifier_env *env,
17201 			       const struct bpf_verifier_state *old)
17202 {
17203 	struct bpf_reg_state *state_reg;
17204 	struct bpf_func_state *state;
17205 	int i, err = 0, fr;
17206 	bool first;
17207 
17208 	for (fr = old->curframe; fr >= 0; fr--) {
17209 		state = old->frame[fr];
17210 		state_reg = state->regs;
17211 		first = true;
17212 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
17213 			if (state_reg->type != SCALAR_VALUE ||
17214 			    !state_reg->precise ||
17215 			    !(state_reg->live & REG_LIVE_READ))
17216 				continue;
17217 			if (env->log.level & BPF_LOG_LEVEL2) {
17218 				if (first)
17219 					verbose(env, "frame %d: propagating r%d", fr, i);
17220 				else
17221 					verbose(env, ",r%d", i);
17222 			}
17223 			bt_set_frame_reg(&env->bt, fr, i);
17224 			first = false;
17225 		}
17226 
17227 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17228 			if (!is_spilled_reg(&state->stack[i]))
17229 				continue;
17230 			state_reg = &state->stack[i].spilled_ptr;
17231 			if (state_reg->type != SCALAR_VALUE ||
17232 			    !state_reg->precise ||
17233 			    !(state_reg->live & REG_LIVE_READ))
17234 				continue;
17235 			if (env->log.level & BPF_LOG_LEVEL2) {
17236 				if (first)
17237 					verbose(env, "frame %d: propagating fp%d",
17238 						fr, (-i - 1) * BPF_REG_SIZE);
17239 				else
17240 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
17241 			}
17242 			bt_set_frame_slot(&env->bt, fr, i);
17243 			first = false;
17244 		}
17245 		if (!first)
17246 			verbose(env, "\n");
17247 	}
17248 
17249 	err = mark_chain_precision_batch(env);
17250 	if (err < 0)
17251 		return err;
17252 
17253 	return 0;
17254 }
17255 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)17256 static bool states_maybe_looping(struct bpf_verifier_state *old,
17257 				 struct bpf_verifier_state *cur)
17258 {
17259 	struct bpf_func_state *fold, *fcur;
17260 	int i, fr = cur->curframe;
17261 
17262 	if (old->curframe != fr)
17263 		return false;
17264 
17265 	fold = old->frame[fr];
17266 	fcur = cur->frame[fr];
17267 	for (i = 0; i < MAX_BPF_REG; i++)
17268 		if (memcmp(&fold->regs[i], &fcur->regs[i],
17269 			   offsetof(struct bpf_reg_state, parent)))
17270 			return false;
17271 	return true;
17272 }
17273 
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)17274 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
17275 {
17276 	return env->insn_aux_data[insn_idx].is_iter_next;
17277 }
17278 
17279 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
17280  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
17281  * states to match, which otherwise would look like an infinite loop. So while
17282  * iter_next() calls are taken care of, we still need to be careful and
17283  * prevent erroneous and too eager declaration of "ininite loop", when
17284  * iterators are involved.
17285  *
17286  * Here's a situation in pseudo-BPF assembly form:
17287  *
17288  *   0: again:                          ; set up iter_next() call args
17289  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
17290  *   2:   call bpf_iter_num_next        ; this is iter_next() call
17291  *   3:   if r0 == 0 goto done
17292  *   4:   ... something useful here ...
17293  *   5:   goto again                    ; another iteration
17294  *   6: done:
17295  *   7:   r1 = &it
17296  *   8:   call bpf_iter_num_destroy     ; clean up iter state
17297  *   9:   exit
17298  *
17299  * This is a typical loop. Let's assume that we have a prune point at 1:,
17300  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
17301  * again`, assuming other heuristics don't get in a way).
17302  *
17303  * When we first time come to 1:, let's say we have some state X. We proceed
17304  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
17305  * Now we come back to validate that forked ACTIVE state. We proceed through
17306  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
17307  * are converging. But the problem is that we don't know that yet, as this
17308  * convergence has to happen at iter_next() call site only. So if nothing is
17309  * done, at 1: verifier will use bounded loop logic and declare infinite
17310  * looping (and would be *technically* correct, if not for iterator's
17311  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
17312  * don't want that. So what we do in process_iter_next_call() when we go on
17313  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
17314  * a different iteration. So when we suspect an infinite loop, we additionally
17315  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
17316  * pretend we are not looping and wait for next iter_next() call.
17317  *
17318  * This only applies to ACTIVE state. In DRAINED state we don't expect to
17319  * loop, because that would actually mean infinite loop, as DRAINED state is
17320  * "sticky", and so we'll keep returning into the same instruction with the
17321  * same state (at least in one of possible code paths).
17322  *
17323  * This approach allows to keep infinite loop heuristic even in the face of
17324  * active iterator. E.g., C snippet below is and will be detected as
17325  * inifintely looping:
17326  *
17327  *   struct bpf_iter_num it;
17328  *   int *p, x;
17329  *
17330  *   bpf_iter_num_new(&it, 0, 10);
17331  *   while ((p = bpf_iter_num_next(&t))) {
17332  *       x = p;
17333  *       while (x--) {} // <<-- infinite loop here
17334  *   }
17335  *
17336  */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)17337 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
17338 {
17339 	struct bpf_reg_state *slot, *cur_slot;
17340 	struct bpf_func_state *state;
17341 	int i, fr;
17342 
17343 	for (fr = old->curframe; fr >= 0; fr--) {
17344 		state = old->frame[fr];
17345 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
17346 			if (state->stack[i].slot_type[0] != STACK_ITER)
17347 				continue;
17348 
17349 			slot = &state->stack[i].spilled_ptr;
17350 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
17351 				continue;
17352 
17353 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
17354 			if (cur_slot->iter.depth != slot->iter.depth)
17355 				return true;
17356 		}
17357 	}
17358 	return false;
17359 }
17360 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)17361 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
17362 {
17363 	struct bpf_verifier_state_list *new_sl;
17364 	struct bpf_verifier_state_list *sl, **pprev;
17365 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
17366 	int i, j, n, err, states_cnt = 0;
17367 	bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
17368 	bool add_new_state = force_new_state;
17369 	bool force_exact;
17370 
17371 	/* bpf progs typically have pruning point every 4 instructions
17372 	 * http://vger.kernel.org/bpfconf2019.html#session-1
17373 	 * Do not add new state for future pruning if the verifier hasn't seen
17374 	 * at least 2 jumps and at least 8 instructions.
17375 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
17376 	 * In tests that amounts to up to 50% reduction into total verifier
17377 	 * memory consumption and 20% verifier time speedup.
17378 	 */
17379 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
17380 	    env->insn_processed - env->prev_insn_processed >= 8)
17381 		add_new_state = true;
17382 
17383 	pprev = explored_state(env, insn_idx);
17384 	sl = *pprev;
17385 
17386 	clean_live_states(env, insn_idx, cur);
17387 
17388 	while (sl) {
17389 		states_cnt++;
17390 		if (sl->state.insn_idx != insn_idx)
17391 			goto next;
17392 
17393 		if (sl->state.branches) {
17394 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
17395 
17396 			if (frame->in_async_callback_fn &&
17397 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
17398 				/* Different async_entry_cnt means that the verifier is
17399 				 * processing another entry into async callback.
17400 				 * Seeing the same state is not an indication of infinite
17401 				 * loop or infinite recursion.
17402 				 * But finding the same state doesn't mean that it's safe
17403 				 * to stop processing the current state. The previous state
17404 				 * hasn't yet reached bpf_exit, since state.branches > 0.
17405 				 * Checking in_async_callback_fn alone is not enough either.
17406 				 * Since the verifier still needs to catch infinite loops
17407 				 * inside async callbacks.
17408 				 */
17409 				goto skip_inf_loop_check;
17410 			}
17411 			/* BPF open-coded iterators loop detection is special.
17412 			 * states_maybe_looping() logic is too simplistic in detecting
17413 			 * states that *might* be equivalent, because it doesn't know
17414 			 * about ID remapping, so don't even perform it.
17415 			 * See process_iter_next_call() and iter_active_depths_differ()
17416 			 * for overview of the logic. When current and one of parent
17417 			 * states are detected as equivalent, it's a good thing: we prove
17418 			 * convergence and can stop simulating further iterations.
17419 			 * It's safe to assume that iterator loop will finish, taking into
17420 			 * account iter_next() contract of eventually returning
17421 			 * sticky NULL result.
17422 			 *
17423 			 * Note, that states have to be compared exactly in this case because
17424 			 * read and precision marks might not be finalized inside the loop.
17425 			 * E.g. as in the program below:
17426 			 *
17427 			 *     1. r7 = -16
17428 			 *     2. r6 = bpf_get_prandom_u32()
17429 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
17430 			 *     4.   if (r6 != 42) {
17431 			 *     5.     r7 = -32
17432 			 *     6.     r6 = bpf_get_prandom_u32()
17433 			 *     7.     continue
17434 			 *     8.   }
17435 			 *     9.   r0 = r10
17436 			 *    10.   r0 += r7
17437 			 *    11.   r8 = *(u64 *)(r0 + 0)
17438 			 *    12.   r6 = bpf_get_prandom_u32()
17439 			 *    13. }
17440 			 *
17441 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
17442 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
17443 			 * not have read or precision mark for r7 yet, thus inexact states
17444 			 * comparison would discard current state with r7=-32
17445 			 * => unsafe memory access at 11 would not be caught.
17446 			 */
17447 			if (is_iter_next_insn(env, insn_idx)) {
17448 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17449 					struct bpf_func_state *cur_frame;
17450 					struct bpf_reg_state *iter_state, *iter_reg;
17451 					int spi;
17452 
17453 					cur_frame = cur->frame[cur->curframe];
17454 					/* btf_check_iter_kfuncs() enforces that
17455 					 * iter state pointer is always the first arg
17456 					 */
17457 					iter_reg = &cur_frame->regs[BPF_REG_1];
17458 					/* current state is valid due to states_equal(),
17459 					 * so we can assume valid iter and reg state,
17460 					 * no need for extra (re-)validations
17461 					 */
17462 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
17463 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
17464 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
17465 						update_loop_entry(cur, &sl->state);
17466 						goto hit;
17467 					}
17468 				}
17469 				goto skip_inf_loop_check;
17470 			}
17471 			if (is_may_goto_insn_at(env, insn_idx)) {
17472 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
17473 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
17474 					update_loop_entry(cur, &sl->state);
17475 					goto hit;
17476 				}
17477 			}
17478 			if (calls_callback(env, insn_idx)) {
17479 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
17480 					goto hit;
17481 				goto skip_inf_loop_check;
17482 			}
17483 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
17484 			if (states_maybe_looping(&sl->state, cur) &&
17485 			    states_equal(env, &sl->state, cur, EXACT) &&
17486 			    !iter_active_depths_differ(&sl->state, cur) &&
17487 			    sl->state.may_goto_depth == cur->may_goto_depth &&
17488 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
17489 				verbose_linfo(env, insn_idx, "; ");
17490 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
17491 				verbose(env, "cur state:");
17492 				print_verifier_state(env, cur->frame[cur->curframe], true);
17493 				verbose(env, "old state:");
17494 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
17495 				return -EINVAL;
17496 			}
17497 			/* if the verifier is processing a loop, avoid adding new state
17498 			 * too often, since different loop iterations have distinct
17499 			 * states and may not help future pruning.
17500 			 * This threshold shouldn't be too low to make sure that
17501 			 * a loop with large bound will be rejected quickly.
17502 			 * The most abusive loop will be:
17503 			 * r1 += 1
17504 			 * if r1 < 1000000 goto pc-2
17505 			 * 1M insn_procssed limit / 100 == 10k peak states.
17506 			 * This threshold shouldn't be too high either, since states
17507 			 * at the end of the loop are likely to be useful in pruning.
17508 			 */
17509 skip_inf_loop_check:
17510 			if (!force_new_state &&
17511 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
17512 			    env->insn_processed - env->prev_insn_processed < 100)
17513 				add_new_state = false;
17514 			goto miss;
17515 		}
17516 		/* If sl->state is a part of a loop and this loop's entry is a part of
17517 		 * current verification path then states have to be compared exactly.
17518 		 * 'force_exact' is needed to catch the following case:
17519 		 *
17520 		 *                initial     Here state 'succ' was processed first,
17521 		 *                  |         it was eventually tracked to produce a
17522 		 *                  V         state identical to 'hdr'.
17523 		 *     .---------> hdr        All branches from 'succ' had been explored
17524 		 *     |            |         and thus 'succ' has its .branches == 0.
17525 		 *     |            V
17526 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
17527 		 *     |    |       |         to the same instruction + callsites.
17528 		 *     |    V       V         In such case it is necessary to check
17529 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
17530 		 *     |    |       |         If 'succ' and 'cur' are a part of the
17531 		 *     |    V       V         same loop exact flag has to be set.
17532 		 *     |   succ <- cur        To check if that is the case, verify
17533 		 *     |    |                 if loop entry of 'succ' is in current
17534 		 *     |    V                 DFS path.
17535 		 *     |   ...
17536 		 *     |    |
17537 		 *     '----'
17538 		 *
17539 		 * Additional details are in the comment before get_loop_entry().
17540 		 */
17541 		loop_entry = get_loop_entry(&sl->state);
17542 		force_exact = loop_entry && loop_entry->branches > 0;
17543 		if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) {
17544 			if (force_exact)
17545 				update_loop_entry(cur, loop_entry);
17546 hit:
17547 			sl->hit_cnt++;
17548 			/* reached equivalent register/stack state,
17549 			 * prune the search.
17550 			 * Registers read by the continuation are read by us.
17551 			 * If we have any write marks in env->cur_state, they
17552 			 * will prevent corresponding reads in the continuation
17553 			 * from reaching our parent (an explored_state).  Our
17554 			 * own state will get the read marks recorded, but
17555 			 * they'll be immediately forgotten as we're pruning
17556 			 * this state and will pop a new one.
17557 			 */
17558 			err = propagate_liveness(env, &sl->state, cur);
17559 
17560 			/* if previous state reached the exit with precision and
17561 			 * current state is equivalent to it (except precision marks)
17562 			 * the precision needs to be propagated back in
17563 			 * the current state.
17564 			 */
17565 			if (is_jmp_point(env, env->insn_idx))
17566 				err = err ? : push_jmp_history(env, cur, 0);
17567 			err = err ? : propagate_precision(env, &sl->state);
17568 			if (err)
17569 				return err;
17570 			return 1;
17571 		}
17572 miss:
17573 		/* when new state is not going to be added do not increase miss count.
17574 		 * Otherwise several loop iterations will remove the state
17575 		 * recorded earlier. The goal of these heuristics is to have
17576 		 * states from some iterations of the loop (some in the beginning
17577 		 * and some at the end) to help pruning.
17578 		 */
17579 		if (add_new_state)
17580 			sl->miss_cnt++;
17581 		/* heuristic to determine whether this state is beneficial
17582 		 * to keep checking from state equivalence point of view.
17583 		 * Higher numbers increase max_states_per_insn and verification time,
17584 		 * but do not meaningfully decrease insn_processed.
17585 		 * 'n' controls how many times state could miss before eviction.
17586 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
17587 		 * too early would hinder iterator convergence.
17588 		 */
17589 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17590 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
17591 			/* the state is unlikely to be useful. Remove it to
17592 			 * speed up verification
17593 			 */
17594 			*pprev = sl->next;
17595 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17596 			    !sl->state.used_as_loop_entry) {
17597 				u32 br = sl->state.branches;
17598 
17599 				WARN_ONCE(br,
17600 					  "BUG live_done but branches_to_explore %d\n",
17601 					  br);
17602 				free_verifier_state(&sl->state, false);
17603 				kfree(sl);
17604 				env->peak_states--;
17605 			} else {
17606 				/* cannot free this state, since parentage chain may
17607 				 * walk it later. Add it for free_list instead to
17608 				 * be freed at the end of verification
17609 				 */
17610 				sl->next = env->free_list;
17611 				env->free_list = sl;
17612 			}
17613 			sl = *pprev;
17614 			continue;
17615 		}
17616 next:
17617 		pprev = &sl->next;
17618 		sl = *pprev;
17619 	}
17620 
17621 	if (env->max_states_per_insn < states_cnt)
17622 		env->max_states_per_insn = states_cnt;
17623 
17624 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17625 		return 0;
17626 
17627 	if (!add_new_state)
17628 		return 0;
17629 
17630 	/* There were no equivalent states, remember the current one.
17631 	 * Technically the current state is not proven to be safe yet,
17632 	 * but it will either reach outer most bpf_exit (which means it's safe)
17633 	 * or it will be rejected. When there are no loops the verifier won't be
17634 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17635 	 * again on the way to bpf_exit.
17636 	 * When looping the sl->state.branches will be > 0 and this state
17637 	 * will not be considered for equivalence until branches == 0.
17638 	 */
17639 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17640 	if (!new_sl)
17641 		return -ENOMEM;
17642 	env->total_states++;
17643 	env->peak_states++;
17644 	env->prev_jmps_processed = env->jmps_processed;
17645 	env->prev_insn_processed = env->insn_processed;
17646 
17647 	/* forget precise markings we inherited, see __mark_chain_precision */
17648 	if (env->bpf_capable)
17649 		mark_all_scalars_imprecise(env, cur);
17650 
17651 	/* add new state to the head of linked list */
17652 	new = &new_sl->state;
17653 	err = copy_verifier_state(new, cur);
17654 	if (err) {
17655 		free_verifier_state(new, false);
17656 		kfree(new_sl);
17657 		return err;
17658 	}
17659 	new->insn_idx = insn_idx;
17660 	WARN_ONCE(new->branches != 1,
17661 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17662 
17663 	cur->parent = new;
17664 	cur->first_insn_idx = insn_idx;
17665 	cur->dfs_depth = new->dfs_depth + 1;
17666 	clear_jmp_history(cur);
17667 	new_sl->next = *explored_state(env, insn_idx);
17668 	*explored_state(env, insn_idx) = new_sl;
17669 	/* connect new state to parentage chain. Current frame needs all
17670 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
17671 	 * to the stack implicitly by JITs) so in callers' frames connect just
17672 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17673 	 * the state of the call instruction (with WRITTEN set), and r0 comes
17674 	 * from callee with its full parentage chain, anyway.
17675 	 */
17676 	/* clear write marks in current state: the writes we did are not writes
17677 	 * our child did, so they don't screen off its reads from us.
17678 	 * (There are no read marks in current state, because reads always mark
17679 	 * their parent and current state never has children yet.  Only
17680 	 * explored_states can get read marks.)
17681 	 */
17682 	for (j = 0; j <= cur->curframe; j++) {
17683 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17684 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17685 		for (i = 0; i < BPF_REG_FP; i++)
17686 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17687 	}
17688 
17689 	/* all stack frames are accessible from callee, clear them all */
17690 	for (j = 0; j <= cur->curframe; j++) {
17691 		struct bpf_func_state *frame = cur->frame[j];
17692 		struct bpf_func_state *newframe = new->frame[j];
17693 
17694 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17695 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17696 			frame->stack[i].spilled_ptr.parent =
17697 						&newframe->stack[i].spilled_ptr;
17698 		}
17699 	}
17700 	return 0;
17701 }
17702 
17703 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)17704 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17705 {
17706 	switch (base_type(type)) {
17707 	case PTR_TO_CTX:
17708 	case PTR_TO_SOCKET:
17709 	case PTR_TO_SOCK_COMMON:
17710 	case PTR_TO_TCP_SOCK:
17711 	case PTR_TO_XDP_SOCK:
17712 	case PTR_TO_BTF_ID:
17713 	case PTR_TO_ARENA:
17714 		return false;
17715 	default:
17716 		return true;
17717 	}
17718 }
17719 
17720 /* If an instruction was previously used with particular pointer types, then we
17721  * need to be careful to avoid cases such as the below, where it may be ok
17722  * for one branch accessing the pointer, but not ok for the other branch:
17723  *
17724  * R1 = sock_ptr
17725  * goto X;
17726  * ...
17727  * R1 = some_other_valid_ptr;
17728  * goto X;
17729  * ...
17730  * R2 = *(u32 *)(R1 + 0);
17731  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)17732 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17733 {
17734 	return src != prev && (!reg_type_mismatch_ok(src) ||
17735 			       !reg_type_mismatch_ok(prev));
17736 }
17737 
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_mismatch)17738 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17739 			     bool allow_trust_mismatch)
17740 {
17741 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17742 
17743 	if (*prev_type == NOT_INIT) {
17744 		/* Saw a valid insn
17745 		 * dst_reg = *(u32 *)(src_reg + off)
17746 		 * save type to validate intersecting paths
17747 		 */
17748 		*prev_type = type;
17749 	} else if (reg_type_mismatch(type, *prev_type)) {
17750 		/* Abuser program is trying to use the same insn
17751 		 * dst_reg = *(u32*) (src_reg + off)
17752 		 * with different pointer types:
17753 		 * src_reg == ctx in one branch and
17754 		 * src_reg == stack|map in some other branch.
17755 		 * Reject it.
17756 		 */
17757 		if (allow_trust_mismatch &&
17758 		    base_type(type) == PTR_TO_BTF_ID &&
17759 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17760 			/*
17761 			 * Have to support a use case when one path through
17762 			 * the program yields TRUSTED pointer while another
17763 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17764 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17765 			 */
17766 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17767 		} else {
17768 			verbose(env, "same insn cannot be used with different pointers\n");
17769 			return -EINVAL;
17770 		}
17771 	}
17772 
17773 	return 0;
17774 }
17775 
do_check(struct bpf_verifier_env * env)17776 static int do_check(struct bpf_verifier_env *env)
17777 {
17778 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17779 	struct bpf_verifier_state *state = env->cur_state;
17780 	struct bpf_insn *insns = env->prog->insnsi;
17781 	struct bpf_reg_state *regs;
17782 	int insn_cnt = env->prog->len;
17783 	bool do_print_state = false;
17784 	int prev_insn_idx = -1;
17785 
17786 	for (;;) {
17787 		bool exception_exit = false;
17788 		struct bpf_insn *insn;
17789 		u8 class;
17790 		int err;
17791 
17792 		/* reset current history entry on each new instruction */
17793 		env->cur_hist_ent = NULL;
17794 
17795 		env->prev_insn_idx = prev_insn_idx;
17796 		if (env->insn_idx >= insn_cnt) {
17797 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17798 				env->insn_idx, insn_cnt);
17799 			return -EFAULT;
17800 		}
17801 
17802 		insn = &insns[env->insn_idx];
17803 		class = BPF_CLASS(insn->code);
17804 
17805 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17806 			verbose(env,
17807 				"BPF program is too large. Processed %d insn\n",
17808 				env->insn_processed);
17809 			return -E2BIG;
17810 		}
17811 
17812 		state->last_insn_idx = env->prev_insn_idx;
17813 
17814 		if (is_prune_point(env, env->insn_idx)) {
17815 			err = is_state_visited(env, env->insn_idx);
17816 			if (err < 0)
17817 				return err;
17818 			if (err == 1) {
17819 				/* found equivalent state, can prune the search */
17820 				if (env->log.level & BPF_LOG_LEVEL) {
17821 					if (do_print_state)
17822 						verbose(env, "\nfrom %d to %d%s: safe\n",
17823 							env->prev_insn_idx, env->insn_idx,
17824 							env->cur_state->speculative ?
17825 							" (speculative execution)" : "");
17826 					else
17827 						verbose(env, "%d: safe\n", env->insn_idx);
17828 				}
17829 				goto process_bpf_exit;
17830 			}
17831 		}
17832 
17833 		if (is_jmp_point(env, env->insn_idx)) {
17834 			err = push_jmp_history(env, state, 0);
17835 			if (err)
17836 				return err;
17837 		}
17838 
17839 		if (signal_pending(current))
17840 			return -EAGAIN;
17841 
17842 		if (need_resched())
17843 			cond_resched();
17844 
17845 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17846 			verbose(env, "\nfrom %d to %d%s:",
17847 				env->prev_insn_idx, env->insn_idx,
17848 				env->cur_state->speculative ?
17849 				" (speculative execution)" : "");
17850 			print_verifier_state(env, state->frame[state->curframe], true);
17851 			do_print_state = false;
17852 		}
17853 
17854 		if (env->log.level & BPF_LOG_LEVEL) {
17855 			const struct bpf_insn_cbs cbs = {
17856 				.cb_call	= disasm_kfunc_name,
17857 				.cb_print	= verbose,
17858 				.private_data	= env,
17859 			};
17860 
17861 			if (verifier_state_scratched(env))
17862 				print_insn_state(env, state->frame[state->curframe]);
17863 
17864 			verbose_linfo(env, env->insn_idx, "; ");
17865 			env->prev_log_pos = env->log.end_pos;
17866 			verbose(env, "%d: ", env->insn_idx);
17867 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17868 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17869 			env->prev_log_pos = env->log.end_pos;
17870 		}
17871 
17872 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17873 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17874 							   env->prev_insn_idx);
17875 			if (err)
17876 				return err;
17877 		}
17878 
17879 		regs = cur_regs(env);
17880 		sanitize_mark_insn_seen(env);
17881 		prev_insn_idx = env->insn_idx;
17882 
17883 		if (class == BPF_ALU || class == BPF_ALU64) {
17884 			err = check_alu_op(env, insn);
17885 			if (err)
17886 				return err;
17887 
17888 		} else if (class == BPF_LDX) {
17889 			enum bpf_reg_type src_reg_type;
17890 
17891 			/* check for reserved fields is already done */
17892 
17893 			/* check src operand */
17894 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17895 			if (err)
17896 				return err;
17897 
17898 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17899 			if (err)
17900 				return err;
17901 
17902 			src_reg_type = regs[insn->src_reg].type;
17903 
17904 			/* check that memory (src_reg + off) is readable,
17905 			 * the state of dst_reg will be updated by this func
17906 			 */
17907 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17908 					       insn->off, BPF_SIZE(insn->code),
17909 					       BPF_READ, insn->dst_reg, false,
17910 					       BPF_MODE(insn->code) == BPF_MEMSX);
17911 			err = err ?: save_aux_ptr_type(env, src_reg_type, true);
17912 			err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], "ldx");
17913 			if (err)
17914 				return err;
17915 		} else if (class == BPF_STX) {
17916 			enum bpf_reg_type dst_reg_type;
17917 
17918 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17919 				err = check_atomic(env, env->insn_idx, insn);
17920 				if (err)
17921 					return err;
17922 				env->insn_idx++;
17923 				continue;
17924 			}
17925 
17926 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17927 				verbose(env, "BPF_STX uses reserved fields\n");
17928 				return -EINVAL;
17929 			}
17930 
17931 			/* check src1 operand */
17932 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17933 			if (err)
17934 				return err;
17935 			/* check src2 operand */
17936 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17937 			if (err)
17938 				return err;
17939 
17940 			dst_reg_type = regs[insn->dst_reg].type;
17941 
17942 			/* check that memory (dst_reg + off) is writeable */
17943 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17944 					       insn->off, BPF_SIZE(insn->code),
17945 					       BPF_WRITE, insn->src_reg, false, false);
17946 			if (err)
17947 				return err;
17948 
17949 			err = save_aux_ptr_type(env, dst_reg_type, false);
17950 			if (err)
17951 				return err;
17952 		} else if (class == BPF_ST) {
17953 			enum bpf_reg_type dst_reg_type;
17954 
17955 			if (BPF_MODE(insn->code) != BPF_MEM ||
17956 			    insn->src_reg != BPF_REG_0) {
17957 				verbose(env, "BPF_ST uses reserved fields\n");
17958 				return -EINVAL;
17959 			}
17960 			/* check src operand */
17961 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17962 			if (err)
17963 				return err;
17964 
17965 			dst_reg_type = regs[insn->dst_reg].type;
17966 
17967 			/* check that memory (dst_reg + off) is writeable */
17968 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17969 					       insn->off, BPF_SIZE(insn->code),
17970 					       BPF_WRITE, -1, false, false);
17971 			if (err)
17972 				return err;
17973 
17974 			err = save_aux_ptr_type(env, dst_reg_type, false);
17975 			if (err)
17976 				return err;
17977 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17978 			u8 opcode = BPF_OP(insn->code);
17979 
17980 			env->jmps_processed++;
17981 			if (opcode == BPF_CALL) {
17982 				if (BPF_SRC(insn->code) != BPF_K ||
17983 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17984 				     && insn->off != 0) ||
17985 				    (insn->src_reg != BPF_REG_0 &&
17986 				     insn->src_reg != BPF_PSEUDO_CALL &&
17987 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17988 				    insn->dst_reg != BPF_REG_0 ||
17989 				    class == BPF_JMP32) {
17990 					verbose(env, "BPF_CALL uses reserved fields\n");
17991 					return -EINVAL;
17992 				}
17993 
17994 				if (env->cur_state->active_lock.ptr) {
17995 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17996 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17997 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17998 						verbose(env, "function calls are not allowed while holding a lock\n");
17999 						return -EINVAL;
18000 					}
18001 				}
18002 				if (insn->src_reg == BPF_PSEUDO_CALL) {
18003 					err = check_func_call(env, insn, &env->insn_idx);
18004 				} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18005 					err = check_kfunc_call(env, insn, &env->insn_idx);
18006 					if (!err && is_bpf_throw_kfunc(insn)) {
18007 						exception_exit = true;
18008 						goto process_bpf_exit_full;
18009 					}
18010 				} else {
18011 					err = check_helper_call(env, insn, &env->insn_idx);
18012 				}
18013 				if (err)
18014 					return err;
18015 
18016 				mark_reg_scratched(env, BPF_REG_0);
18017 			} else if (opcode == BPF_JA) {
18018 				if (BPF_SRC(insn->code) != BPF_K ||
18019 				    insn->src_reg != BPF_REG_0 ||
18020 				    insn->dst_reg != BPF_REG_0 ||
18021 				    (class == BPF_JMP && insn->imm != 0) ||
18022 				    (class == BPF_JMP32 && insn->off != 0)) {
18023 					verbose(env, "BPF_JA uses reserved fields\n");
18024 					return -EINVAL;
18025 				}
18026 
18027 				if (class == BPF_JMP)
18028 					env->insn_idx += insn->off + 1;
18029 				else
18030 					env->insn_idx += insn->imm + 1;
18031 				continue;
18032 
18033 			} else if (opcode == BPF_EXIT) {
18034 				if (BPF_SRC(insn->code) != BPF_K ||
18035 				    insn->imm != 0 ||
18036 				    insn->src_reg != BPF_REG_0 ||
18037 				    insn->dst_reg != BPF_REG_0 ||
18038 				    class == BPF_JMP32) {
18039 					verbose(env, "BPF_EXIT uses reserved fields\n");
18040 					return -EINVAL;
18041 				}
18042 process_bpf_exit_full:
18043 				if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) {
18044 					verbose(env, "bpf_spin_unlock is missing\n");
18045 					return -EINVAL;
18046 				}
18047 
18048 				if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) {
18049 					verbose(env, "bpf_rcu_read_unlock is missing\n");
18050 					return -EINVAL;
18051 				}
18052 
18053 				if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) {
18054 					verbose(env, "%d bpf_preempt_enable%s missing\n",
18055 						env->cur_state->active_preempt_lock,
18056 						env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are");
18057 					return -EINVAL;
18058 				}
18059 
18060 				/* We must do check_reference_leak here before
18061 				 * prepare_func_exit to handle the case when
18062 				 * state->curframe > 0, it may be a callback
18063 				 * function, for which reference_state must
18064 				 * match caller reference state when it exits.
18065 				 */
18066 				err = check_reference_leak(env, exception_exit);
18067 				if (err)
18068 					return err;
18069 
18070 				/* The side effect of the prepare_func_exit
18071 				 * which is being skipped is that it frees
18072 				 * bpf_func_state. Typically, process_bpf_exit
18073 				 * will only be hit with outermost exit.
18074 				 * copy_verifier_state in pop_stack will handle
18075 				 * freeing of any extra bpf_func_state left over
18076 				 * from not processing all nested function
18077 				 * exits. We also skip return code checks as
18078 				 * they are not needed for exceptional exits.
18079 				 */
18080 				if (exception_exit)
18081 					goto process_bpf_exit;
18082 
18083 				if (state->curframe) {
18084 					/* exit from nested function */
18085 					err = prepare_func_exit(env, &env->insn_idx);
18086 					if (err)
18087 						return err;
18088 					do_print_state = true;
18089 					continue;
18090 				}
18091 
18092 				err = check_return_code(env, BPF_REG_0, "R0");
18093 				if (err)
18094 					return err;
18095 process_bpf_exit:
18096 				mark_verifier_state_scratched(env);
18097 				update_branch_counts(env, env->cur_state);
18098 				err = pop_stack(env, &prev_insn_idx,
18099 						&env->insn_idx, pop_log);
18100 				if (err < 0) {
18101 					if (err != -ENOENT)
18102 						return err;
18103 					break;
18104 				} else {
18105 					do_print_state = true;
18106 					continue;
18107 				}
18108 			} else {
18109 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
18110 				if (err)
18111 					return err;
18112 			}
18113 		} else if (class == BPF_LD) {
18114 			u8 mode = BPF_MODE(insn->code);
18115 
18116 			if (mode == BPF_ABS || mode == BPF_IND) {
18117 				err = check_ld_abs(env, insn);
18118 				if (err)
18119 					return err;
18120 
18121 			} else if (mode == BPF_IMM) {
18122 				err = check_ld_imm(env, insn);
18123 				if (err)
18124 					return err;
18125 
18126 				env->insn_idx++;
18127 				sanitize_mark_insn_seen(env);
18128 			} else {
18129 				verbose(env, "invalid BPF_LD mode\n");
18130 				return -EINVAL;
18131 			}
18132 		} else {
18133 			verbose(env, "unknown insn class %d\n", class);
18134 			return -EINVAL;
18135 		}
18136 
18137 		env->insn_idx++;
18138 	}
18139 
18140 	return 0;
18141 }
18142 
find_btf_percpu_datasec(struct btf * btf)18143 static int find_btf_percpu_datasec(struct btf *btf)
18144 {
18145 	const struct btf_type *t;
18146 	const char *tname;
18147 	int i, n;
18148 
18149 	/*
18150 	 * Both vmlinux and module each have their own ".data..percpu"
18151 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
18152 	 * types to look at only module's own BTF types.
18153 	 */
18154 	n = btf_nr_types(btf);
18155 	if (btf_is_module(btf))
18156 		i = btf_nr_types(btf_vmlinux);
18157 	else
18158 		i = 1;
18159 
18160 	for(; i < n; i++) {
18161 		t = btf_type_by_id(btf, i);
18162 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
18163 			continue;
18164 
18165 		tname = btf_name_by_offset(btf, t->name_off);
18166 		if (!strcmp(tname, ".data..percpu"))
18167 			return i;
18168 	}
18169 
18170 	return -ENOENT;
18171 }
18172 
18173 /* 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)18174 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
18175 			       struct bpf_insn *insn,
18176 			       struct bpf_insn_aux_data *aux)
18177 {
18178 	const struct btf_var_secinfo *vsi;
18179 	const struct btf_type *datasec;
18180 	struct btf_mod_pair *btf_mod;
18181 	const struct btf_type *t;
18182 	const char *sym_name;
18183 	bool percpu = false;
18184 	u32 type, id = insn->imm;
18185 	struct btf *btf;
18186 	s32 datasec_id;
18187 	u64 addr;
18188 	int i, btf_fd, err;
18189 
18190 	btf_fd = insn[1].imm;
18191 	if (btf_fd) {
18192 		btf = btf_get_by_fd(btf_fd);
18193 		if (IS_ERR(btf)) {
18194 			verbose(env, "invalid module BTF object FD specified.\n");
18195 			return -EINVAL;
18196 		}
18197 	} else {
18198 		if (!btf_vmlinux) {
18199 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
18200 			return -EINVAL;
18201 		}
18202 		btf = btf_vmlinux;
18203 		btf_get(btf);
18204 	}
18205 
18206 	t = btf_type_by_id(btf, id);
18207 	if (!t) {
18208 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
18209 		err = -ENOENT;
18210 		goto err_put;
18211 	}
18212 
18213 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
18214 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
18215 		err = -EINVAL;
18216 		goto err_put;
18217 	}
18218 
18219 	sym_name = btf_name_by_offset(btf, t->name_off);
18220 	addr = kallsyms_lookup_name(sym_name);
18221 	if (!addr) {
18222 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
18223 			sym_name);
18224 		err = -ENOENT;
18225 		goto err_put;
18226 	}
18227 	insn[0].imm = (u32)addr;
18228 	insn[1].imm = addr >> 32;
18229 
18230 	if (btf_type_is_func(t)) {
18231 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18232 		aux->btf_var.mem_size = 0;
18233 		goto check_btf;
18234 	}
18235 
18236 	datasec_id = find_btf_percpu_datasec(btf);
18237 	if (datasec_id > 0) {
18238 		datasec = btf_type_by_id(btf, datasec_id);
18239 		for_each_vsi(i, datasec, vsi) {
18240 			if (vsi->type == id) {
18241 				percpu = true;
18242 				break;
18243 			}
18244 		}
18245 	}
18246 
18247 	type = t->type;
18248 	t = btf_type_skip_modifiers(btf, type, NULL);
18249 	if (percpu) {
18250 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
18251 		aux->btf_var.btf = btf;
18252 		aux->btf_var.btf_id = type;
18253 	} else if (!btf_type_is_struct(t)) {
18254 		const struct btf_type *ret;
18255 		const char *tname;
18256 		u32 tsize;
18257 
18258 		/* resolve the type size of ksym. */
18259 		ret = btf_resolve_size(btf, t, &tsize);
18260 		if (IS_ERR(ret)) {
18261 			tname = btf_name_by_offset(btf, t->name_off);
18262 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
18263 				tname, PTR_ERR(ret));
18264 			err = -EINVAL;
18265 			goto err_put;
18266 		}
18267 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
18268 		aux->btf_var.mem_size = tsize;
18269 	} else {
18270 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
18271 		aux->btf_var.btf = btf;
18272 		aux->btf_var.btf_id = type;
18273 	}
18274 check_btf:
18275 	/* check whether we recorded this BTF (and maybe module) already */
18276 	for (i = 0; i < env->used_btf_cnt; i++) {
18277 		if (env->used_btfs[i].btf == btf) {
18278 			btf_put(btf);
18279 			return 0;
18280 		}
18281 	}
18282 
18283 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
18284 		err = -E2BIG;
18285 		goto err_put;
18286 	}
18287 
18288 	btf_mod = &env->used_btfs[env->used_btf_cnt];
18289 	btf_mod->btf = btf;
18290 	btf_mod->module = NULL;
18291 
18292 	/* if we reference variables from kernel module, bump its refcount */
18293 	if (btf_is_module(btf)) {
18294 		btf_mod->module = btf_try_get_module(btf);
18295 		if (!btf_mod->module) {
18296 			err = -ENXIO;
18297 			goto err_put;
18298 		}
18299 	}
18300 
18301 	env->used_btf_cnt++;
18302 
18303 	return 0;
18304 err_put:
18305 	btf_put(btf);
18306 	return err;
18307 }
18308 
is_tracing_prog_type(enum bpf_prog_type type)18309 static bool is_tracing_prog_type(enum bpf_prog_type type)
18310 {
18311 	switch (type) {
18312 	case BPF_PROG_TYPE_KPROBE:
18313 	case BPF_PROG_TYPE_TRACEPOINT:
18314 	case BPF_PROG_TYPE_PERF_EVENT:
18315 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
18316 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
18317 		return true;
18318 	default:
18319 		return false;
18320 	}
18321 }
18322 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)18323 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
18324 					struct bpf_map *map,
18325 					struct bpf_prog *prog)
18326 
18327 {
18328 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18329 
18330 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
18331 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
18332 		if (is_tracing_prog_type(prog_type)) {
18333 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
18334 			return -EINVAL;
18335 		}
18336 	}
18337 
18338 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
18339 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
18340 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
18341 			return -EINVAL;
18342 		}
18343 
18344 		if (is_tracing_prog_type(prog_type)) {
18345 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
18346 			return -EINVAL;
18347 		}
18348 	}
18349 
18350 	if (btf_record_has_field(map->record, BPF_TIMER)) {
18351 		if (is_tracing_prog_type(prog_type)) {
18352 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
18353 			return -EINVAL;
18354 		}
18355 	}
18356 
18357 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
18358 		if (is_tracing_prog_type(prog_type)) {
18359 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
18360 			return -EINVAL;
18361 		}
18362 	}
18363 
18364 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
18365 	    !bpf_offload_prog_map_match(prog, map)) {
18366 		verbose(env, "offload device mismatch between prog and map\n");
18367 		return -EINVAL;
18368 	}
18369 
18370 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
18371 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
18372 		return -EINVAL;
18373 	}
18374 
18375 	if (prog->sleepable)
18376 		switch (map->map_type) {
18377 		case BPF_MAP_TYPE_HASH:
18378 		case BPF_MAP_TYPE_LRU_HASH:
18379 		case BPF_MAP_TYPE_ARRAY:
18380 		case BPF_MAP_TYPE_PERCPU_HASH:
18381 		case BPF_MAP_TYPE_PERCPU_ARRAY:
18382 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
18383 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
18384 		case BPF_MAP_TYPE_HASH_OF_MAPS:
18385 		case BPF_MAP_TYPE_RINGBUF:
18386 		case BPF_MAP_TYPE_USER_RINGBUF:
18387 		case BPF_MAP_TYPE_INODE_STORAGE:
18388 		case BPF_MAP_TYPE_SK_STORAGE:
18389 		case BPF_MAP_TYPE_TASK_STORAGE:
18390 		case BPF_MAP_TYPE_CGRP_STORAGE:
18391 		case BPF_MAP_TYPE_QUEUE:
18392 		case BPF_MAP_TYPE_STACK:
18393 		case BPF_MAP_TYPE_ARENA:
18394 			break;
18395 		default:
18396 			verbose(env,
18397 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
18398 			return -EINVAL;
18399 		}
18400 
18401 	return 0;
18402 }
18403 
bpf_map_is_cgroup_storage(struct bpf_map * map)18404 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
18405 {
18406 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
18407 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
18408 }
18409 
18410 /* find and rewrite pseudo imm in ld_imm64 instructions:
18411  *
18412  * 1. if it accesses map FD, replace it with actual map pointer.
18413  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
18414  *
18415  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
18416  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)18417 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
18418 {
18419 	struct bpf_insn *insn = env->prog->insnsi;
18420 	int insn_cnt = env->prog->len;
18421 	int i, j, err;
18422 
18423 	err = bpf_prog_calc_tag(env->prog);
18424 	if (err)
18425 		return err;
18426 
18427 	for (i = 0; i < insn_cnt; i++, insn++) {
18428 		if (BPF_CLASS(insn->code) == BPF_LDX &&
18429 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
18430 		    insn->imm != 0)) {
18431 			verbose(env, "BPF_LDX uses reserved fields\n");
18432 			return -EINVAL;
18433 		}
18434 
18435 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
18436 			struct bpf_insn_aux_data *aux;
18437 			struct bpf_map *map;
18438 			struct fd f;
18439 			u64 addr;
18440 			u32 fd;
18441 
18442 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
18443 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
18444 			    insn[1].off != 0) {
18445 				verbose(env, "invalid bpf_ld_imm64 insn\n");
18446 				return -EINVAL;
18447 			}
18448 
18449 			if (insn[0].src_reg == 0)
18450 				/* valid generic load 64-bit imm */
18451 				goto next_insn;
18452 
18453 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
18454 				aux = &env->insn_aux_data[i];
18455 				err = check_pseudo_btf_id(env, insn, aux);
18456 				if (err)
18457 					return err;
18458 				goto next_insn;
18459 			}
18460 
18461 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
18462 				aux = &env->insn_aux_data[i];
18463 				aux->ptr_type = PTR_TO_FUNC;
18464 				goto next_insn;
18465 			}
18466 
18467 			/* In final convert_pseudo_ld_imm64() step, this is
18468 			 * converted into regular 64-bit imm load insn.
18469 			 */
18470 			switch (insn[0].src_reg) {
18471 			case BPF_PSEUDO_MAP_VALUE:
18472 			case BPF_PSEUDO_MAP_IDX_VALUE:
18473 				break;
18474 			case BPF_PSEUDO_MAP_FD:
18475 			case BPF_PSEUDO_MAP_IDX:
18476 				if (insn[1].imm == 0)
18477 					break;
18478 				fallthrough;
18479 			default:
18480 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
18481 				return -EINVAL;
18482 			}
18483 
18484 			switch (insn[0].src_reg) {
18485 			case BPF_PSEUDO_MAP_IDX_VALUE:
18486 			case BPF_PSEUDO_MAP_IDX:
18487 				if (bpfptr_is_null(env->fd_array)) {
18488 					verbose(env, "fd_idx without fd_array is invalid\n");
18489 					return -EPROTO;
18490 				}
18491 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
18492 							    insn[0].imm * sizeof(fd),
18493 							    sizeof(fd)))
18494 					return -EFAULT;
18495 				break;
18496 			default:
18497 				fd = insn[0].imm;
18498 				break;
18499 			}
18500 
18501 			f = fdget(fd);
18502 			map = __bpf_map_get(f);
18503 			if (IS_ERR(map)) {
18504 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
18505 				return PTR_ERR(map);
18506 			}
18507 
18508 			err = check_map_prog_compatibility(env, map, env->prog);
18509 			if (err) {
18510 				fdput(f);
18511 				return err;
18512 			}
18513 
18514 			aux = &env->insn_aux_data[i];
18515 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
18516 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
18517 				addr = (unsigned long)map;
18518 			} else {
18519 				u32 off = insn[1].imm;
18520 
18521 				if (off >= BPF_MAX_VAR_OFF) {
18522 					verbose(env, "direct value offset of %u is not allowed\n", off);
18523 					fdput(f);
18524 					return -EINVAL;
18525 				}
18526 
18527 				if (!map->ops->map_direct_value_addr) {
18528 					verbose(env, "no direct value access support for this map type\n");
18529 					fdput(f);
18530 					return -EINVAL;
18531 				}
18532 
18533 				err = map->ops->map_direct_value_addr(map, &addr, off);
18534 				if (err) {
18535 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
18536 						map->value_size, off);
18537 					fdput(f);
18538 					return err;
18539 				}
18540 
18541 				aux->map_off = off;
18542 				addr += off;
18543 			}
18544 
18545 			insn[0].imm = (u32)addr;
18546 			insn[1].imm = addr >> 32;
18547 
18548 			/* check whether we recorded this map already */
18549 			for (j = 0; j < env->used_map_cnt; j++) {
18550 				if (env->used_maps[j] == map) {
18551 					aux->map_index = j;
18552 					fdput(f);
18553 					goto next_insn;
18554 				}
18555 			}
18556 
18557 			if (env->used_map_cnt >= MAX_USED_MAPS) {
18558 				verbose(env, "The total number of maps per program has reached the limit of %u\n",
18559 					MAX_USED_MAPS);
18560 				fdput(f);
18561 				return -E2BIG;
18562 			}
18563 
18564 			if (env->prog->sleepable)
18565 				atomic64_inc(&map->sleepable_refcnt);
18566 			/* hold the map. If the program is rejected by verifier,
18567 			 * the map will be released by release_maps() or it
18568 			 * will be used by the valid program until it's unloaded
18569 			 * and all maps are released in bpf_free_used_maps()
18570 			 */
18571 			bpf_map_inc(map);
18572 
18573 			aux->map_index = env->used_map_cnt;
18574 			env->used_maps[env->used_map_cnt++] = map;
18575 
18576 			if (bpf_map_is_cgroup_storage(map) &&
18577 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
18578 				verbose(env, "only one cgroup storage of each type is allowed\n");
18579 				fdput(f);
18580 				return -EBUSY;
18581 			}
18582 			if (map->map_type == BPF_MAP_TYPE_ARENA) {
18583 				if (env->prog->aux->arena) {
18584 					verbose(env, "Only one arena per program\n");
18585 					fdput(f);
18586 					return -EBUSY;
18587 				}
18588 				if (!env->allow_ptr_leaks || !env->bpf_capable) {
18589 					verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
18590 					fdput(f);
18591 					return -EPERM;
18592 				}
18593 				if (!env->prog->jit_requested) {
18594 					verbose(env, "JIT is required to use arena\n");
18595 					fdput(f);
18596 					return -EOPNOTSUPP;
18597 				}
18598 				if (!bpf_jit_supports_arena()) {
18599 					verbose(env, "JIT doesn't support arena\n");
18600 					fdput(f);
18601 					return -EOPNOTSUPP;
18602 				}
18603 				env->prog->aux->arena = (void *)map;
18604 				if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
18605 					verbose(env, "arena's user address must be set via map_extra or mmap()\n");
18606 					fdput(f);
18607 					return -EINVAL;
18608 				}
18609 			}
18610 
18611 			fdput(f);
18612 next_insn:
18613 			insn++;
18614 			i++;
18615 			continue;
18616 		}
18617 
18618 		/* Basic sanity check before we invest more work here. */
18619 		if (!bpf_opcode_in_insntable(insn->code)) {
18620 			verbose(env, "unknown opcode %02x\n", insn->code);
18621 			return -EINVAL;
18622 		}
18623 	}
18624 
18625 	/* now all pseudo BPF_LD_IMM64 instructions load valid
18626 	 * 'struct bpf_map *' into a register instead of user map_fd.
18627 	 * These pointers will be used later by verifier to validate map access.
18628 	 */
18629 	return 0;
18630 }
18631 
18632 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)18633 static void release_maps(struct bpf_verifier_env *env)
18634 {
18635 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
18636 			     env->used_map_cnt);
18637 }
18638 
18639 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)18640 static void release_btfs(struct bpf_verifier_env *env)
18641 {
18642 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
18643 }
18644 
18645 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)18646 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18647 {
18648 	struct bpf_insn *insn = env->prog->insnsi;
18649 	int insn_cnt = env->prog->len;
18650 	int i;
18651 
18652 	for (i = 0; i < insn_cnt; i++, insn++) {
18653 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18654 			continue;
18655 		if (insn->src_reg == BPF_PSEUDO_FUNC)
18656 			continue;
18657 		insn->src_reg = 0;
18658 	}
18659 }
18660 
18661 /* single env->prog->insni[off] instruction was replaced with the range
18662  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18663  * [0, off) and [off, end) to new locations, so the patched range stays zero
18664  */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_insn_aux_data * new_data,struct bpf_prog * new_prog,u32 off,u32 cnt)18665 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18666 				 struct bpf_insn_aux_data *new_data,
18667 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
18668 {
18669 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18670 	struct bpf_insn *insn = new_prog->insnsi;
18671 	u32 old_seen = old_data[off].seen;
18672 	u32 prog_len;
18673 	int i;
18674 
18675 	/* aux info at OFF always needs adjustment, no matter fast path
18676 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18677 	 * original insn at old prog.
18678 	 */
18679 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18680 
18681 	if (cnt == 1)
18682 		return;
18683 	prog_len = new_prog->len;
18684 
18685 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18686 	memcpy(new_data + off + cnt - 1, old_data + off,
18687 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18688 	for (i = off; i < off + cnt - 1; i++) {
18689 		/* Expand insni[off]'s seen count to the patched range. */
18690 		new_data[i].seen = old_seen;
18691 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
18692 	}
18693 	env->insn_aux_data = new_data;
18694 	vfree(old_data);
18695 }
18696 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)18697 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18698 {
18699 	int i;
18700 
18701 	if (len == 1)
18702 		return;
18703 	/* NOTE: fake 'exit' subprog should be updated as well. */
18704 	for (i = 0; i <= env->subprog_cnt; i++) {
18705 		if (env->subprog_info[i].start <= off)
18706 			continue;
18707 		env->subprog_info[i].start += len - 1;
18708 	}
18709 }
18710 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)18711 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18712 {
18713 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18714 	int i, sz = prog->aux->size_poke_tab;
18715 	struct bpf_jit_poke_descriptor *desc;
18716 
18717 	for (i = 0; i < sz; i++) {
18718 		desc = &tab[i];
18719 		if (desc->insn_idx <= off)
18720 			continue;
18721 		desc->insn_idx += len - 1;
18722 	}
18723 }
18724 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)18725 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18726 					    const struct bpf_insn *patch, u32 len)
18727 {
18728 	struct bpf_prog *new_prog;
18729 	struct bpf_insn_aux_data *new_data = NULL;
18730 
18731 	if (len > 1) {
18732 		new_data = vzalloc(array_size(env->prog->len + len - 1,
18733 					      sizeof(struct bpf_insn_aux_data)));
18734 		if (!new_data)
18735 			return NULL;
18736 	}
18737 
18738 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18739 	if (IS_ERR(new_prog)) {
18740 		if (PTR_ERR(new_prog) == -ERANGE)
18741 			verbose(env,
18742 				"insn %d cannot be patched due to 16-bit range\n",
18743 				env->insn_aux_data[off].orig_idx);
18744 		vfree(new_data);
18745 		return NULL;
18746 	}
18747 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
18748 	adjust_subprog_starts(env, off, len);
18749 	adjust_poke_descs(new_prog, off, len);
18750 	return new_prog;
18751 }
18752 
18753 /*
18754  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
18755  * jump offset by 'delta'.
18756  */
adjust_jmp_off(struct bpf_prog * prog,u32 tgt_idx,u32 delta)18757 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
18758 {
18759 	struct bpf_insn *insn = prog->insnsi;
18760 	u32 insn_cnt = prog->len, i;
18761 	s32 imm;
18762 	s16 off;
18763 
18764 	for (i = 0; i < insn_cnt; i++, insn++) {
18765 		u8 code = insn->code;
18766 
18767 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
18768 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
18769 			continue;
18770 
18771 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
18772 			if (i + 1 + insn->imm != tgt_idx)
18773 				continue;
18774 			if (check_add_overflow(insn->imm, delta, &imm))
18775 				return -ERANGE;
18776 			insn->imm = imm;
18777 		} else {
18778 			if (i + 1 + insn->off != tgt_idx)
18779 				continue;
18780 			if (check_add_overflow(insn->off, delta, &off))
18781 				return -ERANGE;
18782 			insn->off = off;
18783 		}
18784 	}
18785 	return 0;
18786 }
18787 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)18788 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18789 					      u32 off, u32 cnt)
18790 {
18791 	int i, j;
18792 
18793 	/* find first prog starting at or after off (first to remove) */
18794 	for (i = 0; i < env->subprog_cnt; i++)
18795 		if (env->subprog_info[i].start >= off)
18796 			break;
18797 	/* find first prog starting at or after off + cnt (first to stay) */
18798 	for (j = i; j < env->subprog_cnt; j++)
18799 		if (env->subprog_info[j].start >= off + cnt)
18800 			break;
18801 	/* if j doesn't start exactly at off + cnt, we are just removing
18802 	 * the front of previous prog
18803 	 */
18804 	if (env->subprog_info[j].start != off + cnt)
18805 		j--;
18806 
18807 	if (j > i) {
18808 		struct bpf_prog_aux *aux = env->prog->aux;
18809 		int move;
18810 
18811 		/* move fake 'exit' subprog as well */
18812 		move = env->subprog_cnt + 1 - j;
18813 
18814 		memmove(env->subprog_info + i,
18815 			env->subprog_info + j,
18816 			sizeof(*env->subprog_info) * move);
18817 		env->subprog_cnt -= j - i;
18818 
18819 		/* remove func_info */
18820 		if (aux->func_info) {
18821 			move = aux->func_info_cnt - j;
18822 
18823 			memmove(aux->func_info + i,
18824 				aux->func_info + j,
18825 				sizeof(*aux->func_info) * move);
18826 			aux->func_info_cnt -= j - i;
18827 			/* func_info->insn_off is set after all code rewrites,
18828 			 * in adjust_btf_func() - no need to adjust
18829 			 */
18830 		}
18831 	} else {
18832 		/* convert i from "first prog to remove" to "first to adjust" */
18833 		if (env->subprog_info[i].start == off)
18834 			i++;
18835 	}
18836 
18837 	/* update fake 'exit' subprog as well */
18838 	for (; i <= env->subprog_cnt; i++)
18839 		env->subprog_info[i].start -= cnt;
18840 
18841 	return 0;
18842 }
18843 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)18844 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18845 				      u32 cnt)
18846 {
18847 	struct bpf_prog *prog = env->prog;
18848 	u32 i, l_off, l_cnt, nr_linfo;
18849 	struct bpf_line_info *linfo;
18850 
18851 	nr_linfo = prog->aux->nr_linfo;
18852 	if (!nr_linfo)
18853 		return 0;
18854 
18855 	linfo = prog->aux->linfo;
18856 
18857 	/* find first line info to remove, count lines to be removed */
18858 	for (i = 0; i < nr_linfo; i++)
18859 		if (linfo[i].insn_off >= off)
18860 			break;
18861 
18862 	l_off = i;
18863 	l_cnt = 0;
18864 	for (; i < nr_linfo; i++)
18865 		if (linfo[i].insn_off < off + cnt)
18866 			l_cnt++;
18867 		else
18868 			break;
18869 
18870 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18871 	 * last removed linfo.  prog is already modified, so prog->len == off
18872 	 * means no live instructions after (tail of the program was removed).
18873 	 */
18874 	if (prog->len != off && l_cnt &&
18875 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18876 		l_cnt--;
18877 		linfo[--i].insn_off = off + cnt;
18878 	}
18879 
18880 	/* remove the line info which refer to the removed instructions */
18881 	if (l_cnt) {
18882 		memmove(linfo + l_off, linfo + i,
18883 			sizeof(*linfo) * (nr_linfo - i));
18884 
18885 		prog->aux->nr_linfo -= l_cnt;
18886 		nr_linfo = prog->aux->nr_linfo;
18887 	}
18888 
18889 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18890 	for (i = l_off; i < nr_linfo; i++)
18891 		linfo[i].insn_off -= cnt;
18892 
18893 	/* fix up all subprogs (incl. 'exit') which start >= off */
18894 	for (i = 0; i <= env->subprog_cnt; i++)
18895 		if (env->subprog_info[i].linfo_idx > l_off) {
18896 			/* program may have started in the removed region but
18897 			 * may not be fully removed
18898 			 */
18899 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18900 				env->subprog_info[i].linfo_idx -= l_cnt;
18901 			else
18902 				env->subprog_info[i].linfo_idx = l_off;
18903 		}
18904 
18905 	return 0;
18906 }
18907 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)18908 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18909 {
18910 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18911 	unsigned int orig_prog_len = env->prog->len;
18912 	int err;
18913 
18914 	if (bpf_prog_is_offloaded(env->prog->aux))
18915 		bpf_prog_offload_remove_insns(env, off, cnt);
18916 
18917 	err = bpf_remove_insns(env->prog, off, cnt);
18918 	if (err)
18919 		return err;
18920 
18921 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18922 	if (err)
18923 		return err;
18924 
18925 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18926 	if (err)
18927 		return err;
18928 
18929 	memmove(aux_data + off,	aux_data + off + cnt,
18930 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18931 
18932 	return 0;
18933 }
18934 
18935 /* The verifier does more data flow analysis than llvm and will not
18936  * explore branches that are dead at run time. Malicious programs can
18937  * have dead code too. Therefore replace all dead at-run-time code
18938  * with 'ja -1'.
18939  *
18940  * Just nops are not optimal, e.g. if they would sit at the end of the
18941  * program and through another bug we would manage to jump there, then
18942  * we'd execute beyond program memory otherwise. Returning exception
18943  * code also wouldn't work since we can have subprogs where the dead
18944  * code could be located.
18945  */
sanitize_dead_code(struct bpf_verifier_env * env)18946 static void sanitize_dead_code(struct bpf_verifier_env *env)
18947 {
18948 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18949 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18950 	struct bpf_insn *insn = env->prog->insnsi;
18951 	const int insn_cnt = env->prog->len;
18952 	int i;
18953 
18954 	for (i = 0; i < insn_cnt; i++) {
18955 		if (aux_data[i].seen)
18956 			continue;
18957 		memcpy(insn + i, &trap, sizeof(trap));
18958 		aux_data[i].zext_dst = false;
18959 	}
18960 }
18961 
insn_is_cond_jump(u8 code)18962 static bool insn_is_cond_jump(u8 code)
18963 {
18964 	u8 op;
18965 
18966 	op = BPF_OP(code);
18967 	if (BPF_CLASS(code) == BPF_JMP32)
18968 		return op != BPF_JA;
18969 
18970 	if (BPF_CLASS(code) != BPF_JMP)
18971 		return false;
18972 
18973 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18974 }
18975 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)18976 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18977 {
18978 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18979 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18980 	struct bpf_insn *insn = env->prog->insnsi;
18981 	const int insn_cnt = env->prog->len;
18982 	int i;
18983 
18984 	for (i = 0; i < insn_cnt; i++, insn++) {
18985 		if (!insn_is_cond_jump(insn->code))
18986 			continue;
18987 
18988 		if (!aux_data[i + 1].seen)
18989 			ja.off = insn->off;
18990 		else if (!aux_data[i + 1 + insn->off].seen)
18991 			ja.off = 0;
18992 		else
18993 			continue;
18994 
18995 		if (bpf_prog_is_offloaded(env->prog->aux))
18996 			bpf_prog_offload_replace_insn(env, i, &ja);
18997 
18998 		memcpy(insn, &ja, sizeof(ja));
18999 	}
19000 }
19001 
opt_remove_dead_code(struct bpf_verifier_env * env)19002 static int opt_remove_dead_code(struct bpf_verifier_env *env)
19003 {
19004 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
19005 	int insn_cnt = env->prog->len;
19006 	int i, err;
19007 
19008 	for (i = 0; i < insn_cnt; i++) {
19009 		int j;
19010 
19011 		j = 0;
19012 		while (i + j < insn_cnt && !aux_data[i + j].seen)
19013 			j++;
19014 		if (!j)
19015 			continue;
19016 
19017 		err = verifier_remove_insns(env, i, j);
19018 		if (err)
19019 			return err;
19020 		insn_cnt = env->prog->len;
19021 	}
19022 
19023 	return 0;
19024 }
19025 
opt_remove_nops(struct bpf_verifier_env * env)19026 static int opt_remove_nops(struct bpf_verifier_env *env)
19027 {
19028 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
19029 	struct bpf_insn *insn = env->prog->insnsi;
19030 	int insn_cnt = env->prog->len;
19031 	int i, err;
19032 
19033 	for (i = 0; i < insn_cnt; i++) {
19034 		if (memcmp(&insn[i], &ja, sizeof(ja)))
19035 			continue;
19036 
19037 		err = verifier_remove_insns(env, i, 1);
19038 		if (err)
19039 			return err;
19040 		insn_cnt--;
19041 		i--;
19042 	}
19043 
19044 	return 0;
19045 }
19046 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)19047 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
19048 					 const union bpf_attr *attr)
19049 {
19050 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
19051 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
19052 	int i, patch_len, delta = 0, len = env->prog->len;
19053 	struct bpf_insn *insns = env->prog->insnsi;
19054 	struct bpf_prog *new_prog;
19055 	bool rnd_hi32;
19056 
19057 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
19058 	zext_patch[1] = BPF_ZEXT_REG(0);
19059 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
19060 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
19061 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
19062 	for (i = 0; i < len; i++) {
19063 		int adj_idx = i + delta;
19064 		struct bpf_insn insn;
19065 		int load_reg;
19066 
19067 		insn = insns[adj_idx];
19068 		load_reg = insn_def_regno(&insn);
19069 		if (!aux[adj_idx].zext_dst) {
19070 			u8 code, class;
19071 			u32 imm_rnd;
19072 
19073 			if (!rnd_hi32)
19074 				continue;
19075 
19076 			code = insn.code;
19077 			class = BPF_CLASS(code);
19078 			if (load_reg == -1)
19079 				continue;
19080 
19081 			/* NOTE: arg "reg" (the fourth one) is only used for
19082 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
19083 			 *       here.
19084 			 */
19085 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
19086 				if (class == BPF_LD &&
19087 				    BPF_MODE(code) == BPF_IMM)
19088 					i++;
19089 				continue;
19090 			}
19091 
19092 			/* ctx load could be transformed into wider load. */
19093 			if (class == BPF_LDX &&
19094 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
19095 				continue;
19096 
19097 			imm_rnd = get_random_u32();
19098 			rnd_hi32_patch[0] = insn;
19099 			rnd_hi32_patch[1].imm = imm_rnd;
19100 			rnd_hi32_patch[3].dst_reg = load_reg;
19101 			patch = rnd_hi32_patch;
19102 			patch_len = 4;
19103 			goto apply_patch_buffer;
19104 		}
19105 
19106 		/* Add in an zero-extend instruction if a) the JIT has requested
19107 		 * it or b) it's a CMPXCHG.
19108 		 *
19109 		 * The latter is because: BPF_CMPXCHG always loads a value into
19110 		 * R0, therefore always zero-extends. However some archs'
19111 		 * equivalent instruction only does this load when the
19112 		 * comparison is successful. This detail of CMPXCHG is
19113 		 * orthogonal to the general zero-extension behaviour of the
19114 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
19115 		 */
19116 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
19117 			continue;
19118 
19119 		/* Zero-extension is done by the caller. */
19120 		if (bpf_pseudo_kfunc_call(&insn))
19121 			continue;
19122 
19123 		if (WARN_ON(load_reg == -1)) {
19124 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
19125 			return -EFAULT;
19126 		}
19127 
19128 		zext_patch[0] = insn;
19129 		zext_patch[1].dst_reg = load_reg;
19130 		zext_patch[1].src_reg = load_reg;
19131 		patch = zext_patch;
19132 		patch_len = 2;
19133 apply_patch_buffer:
19134 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
19135 		if (!new_prog)
19136 			return -ENOMEM;
19137 		env->prog = new_prog;
19138 		insns = new_prog->insnsi;
19139 		aux = env->insn_aux_data;
19140 		delta += patch_len - 1;
19141 	}
19142 
19143 	return 0;
19144 }
19145 
19146 /* convert load instructions that access fields of a context type into a
19147  * sequence of instructions that access fields of the underlying structure:
19148  *     struct __sk_buff    -> struct sk_buff
19149  *     struct bpf_sock_ops -> struct sock
19150  */
convert_ctx_accesses(struct bpf_verifier_env * env)19151 static int convert_ctx_accesses(struct bpf_verifier_env *env)
19152 {
19153 	const struct bpf_verifier_ops *ops = env->ops;
19154 	int i, cnt, size, ctx_field_size, delta = 0;
19155 	const int insn_cnt = env->prog->len;
19156 	struct bpf_insn insn_buf[16], *insn;
19157 	u32 target_size, size_default, off;
19158 	struct bpf_prog *new_prog;
19159 	enum bpf_access_type type;
19160 	bool is_narrower_load;
19161 
19162 	if (ops->gen_prologue || env->seen_direct_write) {
19163 		if (!ops->gen_prologue) {
19164 			verbose(env, "bpf verifier is misconfigured\n");
19165 			return -EINVAL;
19166 		}
19167 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
19168 					env->prog);
19169 		if (cnt >= ARRAY_SIZE(insn_buf)) {
19170 			verbose(env, "bpf verifier is misconfigured\n");
19171 			return -EINVAL;
19172 		} else if (cnt) {
19173 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
19174 			if (!new_prog)
19175 				return -ENOMEM;
19176 
19177 			env->prog = new_prog;
19178 			delta += cnt - 1;
19179 		}
19180 	}
19181 
19182 	if (bpf_prog_is_offloaded(env->prog->aux))
19183 		return 0;
19184 
19185 	insn = env->prog->insnsi + delta;
19186 
19187 	for (i = 0; i < insn_cnt; i++, insn++) {
19188 		bpf_convert_ctx_access_t convert_ctx_access;
19189 		u8 mode;
19190 
19191 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
19192 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
19193 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
19194 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
19195 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
19196 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
19197 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
19198 			type = BPF_READ;
19199 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
19200 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
19201 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
19202 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
19203 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
19204 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
19205 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
19206 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
19207 			type = BPF_WRITE;
19208 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
19209 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
19210 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
19211 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
19212 			env->prog->aux->num_exentries++;
19213 			continue;
19214 		} else {
19215 			continue;
19216 		}
19217 
19218 		if (type == BPF_WRITE &&
19219 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
19220 			struct bpf_insn patch[] = {
19221 				*insn,
19222 				BPF_ST_NOSPEC(),
19223 			};
19224 
19225 			cnt = ARRAY_SIZE(patch);
19226 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
19227 			if (!new_prog)
19228 				return -ENOMEM;
19229 
19230 			delta    += cnt - 1;
19231 			env->prog = new_prog;
19232 			insn      = new_prog->insnsi + i + delta;
19233 			continue;
19234 		}
19235 
19236 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
19237 		case PTR_TO_CTX:
19238 			if (!ops->convert_ctx_access)
19239 				continue;
19240 			convert_ctx_access = ops->convert_ctx_access;
19241 			break;
19242 		case PTR_TO_SOCKET:
19243 		case PTR_TO_SOCK_COMMON:
19244 			convert_ctx_access = bpf_sock_convert_ctx_access;
19245 			break;
19246 		case PTR_TO_TCP_SOCK:
19247 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
19248 			break;
19249 		case PTR_TO_XDP_SOCK:
19250 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
19251 			break;
19252 		case PTR_TO_BTF_ID:
19253 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
19254 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
19255 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
19256 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
19257 		 * any faults for loads into such types. BPF_WRITE is disallowed
19258 		 * for this case.
19259 		 */
19260 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
19261 			if (type == BPF_READ) {
19262 				if (BPF_MODE(insn->code) == BPF_MEM)
19263 					insn->code = BPF_LDX | BPF_PROBE_MEM |
19264 						     BPF_SIZE((insn)->code);
19265 				else
19266 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
19267 						     BPF_SIZE((insn)->code);
19268 				env->prog->aux->num_exentries++;
19269 			}
19270 			continue;
19271 		case PTR_TO_ARENA:
19272 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
19273 				verbose(env, "sign extending loads from arena are not supported yet\n");
19274 				return -EOPNOTSUPP;
19275 			}
19276 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
19277 			env->prog->aux->num_exentries++;
19278 			continue;
19279 		default:
19280 			continue;
19281 		}
19282 
19283 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
19284 		size = BPF_LDST_BYTES(insn);
19285 		mode = BPF_MODE(insn->code);
19286 
19287 		/* If the read access is a narrower load of the field,
19288 		 * convert to a 4/8-byte load, to minimum program type specific
19289 		 * convert_ctx_access changes. If conversion is successful,
19290 		 * we will apply proper mask to the result.
19291 		 */
19292 		is_narrower_load = size < ctx_field_size;
19293 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
19294 		off = insn->off;
19295 		if (is_narrower_load) {
19296 			u8 size_code;
19297 
19298 			if (type == BPF_WRITE) {
19299 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
19300 				return -EINVAL;
19301 			}
19302 
19303 			size_code = BPF_H;
19304 			if (ctx_field_size == 4)
19305 				size_code = BPF_W;
19306 			else if (ctx_field_size == 8)
19307 				size_code = BPF_DW;
19308 
19309 			insn->off = off & ~(size_default - 1);
19310 			insn->code = BPF_LDX | BPF_MEM | size_code;
19311 		}
19312 
19313 		target_size = 0;
19314 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
19315 					 &target_size);
19316 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
19317 		    (ctx_field_size && !target_size)) {
19318 			verbose(env, "bpf verifier is misconfigured\n");
19319 			return -EINVAL;
19320 		}
19321 
19322 		if (is_narrower_load && size < target_size) {
19323 			u8 shift = bpf_ctx_narrow_access_offset(
19324 				off, size, size_default) * 8;
19325 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
19326 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
19327 				return -EINVAL;
19328 			}
19329 			if (ctx_field_size <= 4) {
19330 				if (shift)
19331 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
19332 									insn->dst_reg,
19333 									shift);
19334 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19335 								(1 << size * 8) - 1);
19336 			} else {
19337 				if (shift)
19338 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
19339 									insn->dst_reg,
19340 									shift);
19341 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
19342 								(1ULL << size * 8) - 1);
19343 			}
19344 		}
19345 		if (mode == BPF_MEMSX)
19346 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
19347 						       insn->dst_reg, insn->dst_reg,
19348 						       size * 8, 0);
19349 
19350 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19351 		if (!new_prog)
19352 			return -ENOMEM;
19353 
19354 		delta += cnt - 1;
19355 
19356 		/* keep walking new program and skip insns we just inserted */
19357 		env->prog = new_prog;
19358 		insn      = new_prog->insnsi + i + delta;
19359 	}
19360 
19361 	return 0;
19362 }
19363 
jit_subprogs(struct bpf_verifier_env * env)19364 static int jit_subprogs(struct bpf_verifier_env *env)
19365 {
19366 	struct bpf_prog *prog = env->prog, **func, *tmp;
19367 	int i, j, subprog_start, subprog_end = 0, len, subprog;
19368 	struct bpf_map *map_ptr;
19369 	struct bpf_insn *insn;
19370 	void *old_bpf_func;
19371 	int err, num_exentries;
19372 
19373 	if (env->subprog_cnt <= 1)
19374 		return 0;
19375 
19376 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19377 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
19378 			continue;
19379 
19380 		/* Upon error here we cannot fall back to interpreter but
19381 		 * need a hard reject of the program. Thus -EFAULT is
19382 		 * propagated in any case.
19383 		 */
19384 		subprog = find_subprog(env, i + insn->imm + 1);
19385 		if (subprog < 0) {
19386 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
19387 				  i + insn->imm + 1);
19388 			return -EFAULT;
19389 		}
19390 		/* temporarily remember subprog id inside insn instead of
19391 		 * aux_data, since next loop will split up all insns into funcs
19392 		 */
19393 		insn->off = subprog;
19394 		/* remember original imm in case JIT fails and fallback
19395 		 * to interpreter will be needed
19396 		 */
19397 		env->insn_aux_data[i].call_imm = insn->imm;
19398 		/* point imm to __bpf_call_base+1 from JITs point of view */
19399 		insn->imm = 1;
19400 		if (bpf_pseudo_func(insn)) {
19401 #if defined(MODULES_VADDR)
19402 			u64 addr = MODULES_VADDR;
19403 #else
19404 			u64 addr = VMALLOC_START;
19405 #endif
19406 			/* jit (e.g. x86_64) may emit fewer instructions
19407 			 * if it learns a u32 imm is the same as a u64 imm.
19408 			 * Set close enough to possible prog address.
19409 			 */
19410 			insn[0].imm = (u32)addr;
19411 			insn[1].imm = addr >> 32;
19412 		}
19413 	}
19414 
19415 	err = bpf_prog_alloc_jited_linfo(prog);
19416 	if (err)
19417 		goto out_undo_insn;
19418 
19419 	err = -ENOMEM;
19420 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
19421 	if (!func)
19422 		goto out_undo_insn;
19423 
19424 	for (i = 0; i < env->subprog_cnt; i++) {
19425 		subprog_start = subprog_end;
19426 		subprog_end = env->subprog_info[i + 1].start;
19427 
19428 		len = subprog_end - subprog_start;
19429 		/* bpf_prog_run() doesn't call subprogs directly,
19430 		 * hence main prog stats include the runtime of subprogs.
19431 		 * subprogs don't have IDs and not reachable via prog_get_next_id
19432 		 * func[i]->stats will never be accessed and stays NULL
19433 		 */
19434 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
19435 		if (!func[i])
19436 			goto out_free;
19437 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
19438 		       len * sizeof(struct bpf_insn));
19439 		func[i]->type = prog->type;
19440 		func[i]->len = len;
19441 		if (bpf_prog_calc_tag(func[i]))
19442 			goto out_free;
19443 		func[i]->is_func = 1;
19444 		func[i]->sleepable = prog->sleepable;
19445 		func[i]->aux->func_idx = i;
19446 		/* Below members will be freed only at prog->aux */
19447 		func[i]->aux->btf = prog->aux->btf;
19448 		func[i]->aux->func_info = prog->aux->func_info;
19449 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
19450 		func[i]->aux->poke_tab = prog->aux->poke_tab;
19451 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
19452 
19453 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
19454 			struct bpf_jit_poke_descriptor *poke;
19455 
19456 			poke = &prog->aux->poke_tab[j];
19457 			if (poke->insn_idx < subprog_end &&
19458 			    poke->insn_idx >= subprog_start)
19459 				poke->aux = func[i]->aux;
19460 		}
19461 
19462 		func[i]->aux->name[0] = 'F';
19463 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
19464 		func[i]->jit_requested = 1;
19465 		func[i]->blinding_requested = prog->blinding_requested;
19466 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
19467 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
19468 		func[i]->aux->linfo = prog->aux->linfo;
19469 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
19470 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
19471 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
19472 		func[i]->aux->arena = prog->aux->arena;
19473 		num_exentries = 0;
19474 		insn = func[i]->insnsi;
19475 		for (j = 0; j < func[i]->len; j++, insn++) {
19476 			if (BPF_CLASS(insn->code) == BPF_LDX &&
19477 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19478 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
19479 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
19480 				num_exentries++;
19481 			if ((BPF_CLASS(insn->code) == BPF_STX ||
19482 			     BPF_CLASS(insn->code) == BPF_ST) &&
19483 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
19484 				num_exentries++;
19485 			if (BPF_CLASS(insn->code) == BPF_STX &&
19486 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
19487 				num_exentries++;
19488 		}
19489 		func[i]->aux->num_exentries = num_exentries;
19490 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
19491 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
19492 		if (!i)
19493 			func[i]->aux->exception_boundary = env->seen_exception;
19494 		func[i] = bpf_int_jit_compile(func[i]);
19495 		if (!func[i]->jited) {
19496 			err = -ENOTSUPP;
19497 			goto out_free;
19498 		}
19499 		cond_resched();
19500 	}
19501 
19502 	/* at this point all bpf functions were successfully JITed
19503 	 * now populate all bpf_calls with correct addresses and
19504 	 * run last pass of JIT
19505 	 */
19506 	for (i = 0; i < env->subprog_cnt; i++) {
19507 		insn = func[i]->insnsi;
19508 		for (j = 0; j < func[i]->len; j++, insn++) {
19509 			if (bpf_pseudo_func(insn)) {
19510 				subprog = insn->off;
19511 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
19512 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
19513 				continue;
19514 			}
19515 			if (!bpf_pseudo_call(insn))
19516 				continue;
19517 			subprog = insn->off;
19518 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
19519 		}
19520 
19521 		/* we use the aux data to keep a list of the start addresses
19522 		 * of the JITed images for each function in the program
19523 		 *
19524 		 * for some architectures, such as powerpc64, the imm field
19525 		 * might not be large enough to hold the offset of the start
19526 		 * address of the callee's JITed image from __bpf_call_base
19527 		 *
19528 		 * in such cases, we can lookup the start address of a callee
19529 		 * by using its subprog id, available from the off field of
19530 		 * the call instruction, as an index for this list
19531 		 */
19532 		func[i]->aux->func = func;
19533 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19534 		func[i]->aux->real_func_cnt = env->subprog_cnt;
19535 	}
19536 	for (i = 0; i < env->subprog_cnt; i++) {
19537 		old_bpf_func = func[i]->bpf_func;
19538 		tmp = bpf_int_jit_compile(func[i]);
19539 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
19540 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
19541 			err = -ENOTSUPP;
19542 			goto out_free;
19543 		}
19544 		cond_resched();
19545 	}
19546 
19547 	/* finally lock prog and jit images for all functions and
19548 	 * populate kallsysm. Begin at the first subprogram, since
19549 	 * bpf_prog_load will add the kallsyms for the main program.
19550 	 */
19551 	for (i = 1; i < env->subprog_cnt; i++) {
19552 		err = bpf_prog_lock_ro(func[i]);
19553 		if (err)
19554 			goto out_free;
19555 	}
19556 
19557 	for (i = 1; i < env->subprog_cnt; i++)
19558 		bpf_prog_kallsyms_add(func[i]);
19559 
19560 	/* Last step: make now unused interpreter insns from main
19561 	 * prog consistent for later dump requests, so they can
19562 	 * later look the same as if they were interpreted only.
19563 	 */
19564 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19565 		if (bpf_pseudo_func(insn)) {
19566 			insn[0].imm = env->insn_aux_data[i].call_imm;
19567 			insn[1].imm = insn->off;
19568 			insn->off = 0;
19569 			continue;
19570 		}
19571 		if (!bpf_pseudo_call(insn))
19572 			continue;
19573 		insn->off = env->insn_aux_data[i].call_imm;
19574 		subprog = find_subprog(env, i + insn->off + 1);
19575 		insn->imm = subprog;
19576 	}
19577 
19578 	prog->jited = 1;
19579 	prog->bpf_func = func[0]->bpf_func;
19580 	prog->jited_len = func[0]->jited_len;
19581 	prog->aux->extable = func[0]->aux->extable;
19582 	prog->aux->num_exentries = func[0]->aux->num_exentries;
19583 	prog->aux->func = func;
19584 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
19585 	prog->aux->real_func_cnt = env->subprog_cnt;
19586 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
19587 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
19588 	bpf_prog_jit_attempt_done(prog);
19589 	return 0;
19590 out_free:
19591 	/* We failed JIT'ing, so at this point we need to unregister poke
19592 	 * descriptors from subprogs, so that kernel is not attempting to
19593 	 * patch it anymore as we're freeing the subprog JIT memory.
19594 	 */
19595 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19596 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19597 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
19598 	}
19599 	/* At this point we're guaranteed that poke descriptors are not
19600 	 * live anymore. We can just unlink its descriptor table as it's
19601 	 * released with the main prog.
19602 	 */
19603 	for (i = 0; i < env->subprog_cnt; i++) {
19604 		if (!func[i])
19605 			continue;
19606 		func[i]->aux->poke_tab = NULL;
19607 		bpf_jit_free(func[i]);
19608 	}
19609 	kfree(func);
19610 out_undo_insn:
19611 	/* cleanup main prog to be interpreted */
19612 	prog->jit_requested = 0;
19613 	prog->blinding_requested = 0;
19614 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
19615 		if (!bpf_pseudo_call(insn))
19616 			continue;
19617 		insn->off = 0;
19618 		insn->imm = env->insn_aux_data[i].call_imm;
19619 	}
19620 	bpf_prog_jit_attempt_done(prog);
19621 	return err;
19622 }
19623 
fixup_call_args(struct bpf_verifier_env * env)19624 static int fixup_call_args(struct bpf_verifier_env *env)
19625 {
19626 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19627 	struct bpf_prog *prog = env->prog;
19628 	struct bpf_insn *insn = prog->insnsi;
19629 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
19630 	int i, depth;
19631 #endif
19632 	int err = 0;
19633 
19634 	if (env->prog->jit_requested &&
19635 	    !bpf_prog_is_offloaded(env->prog->aux)) {
19636 		err = jit_subprogs(env);
19637 		if (err == 0)
19638 			return 0;
19639 		if (err == -EFAULT)
19640 			return err;
19641 	}
19642 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
19643 	if (has_kfunc_call) {
19644 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
19645 		return -EINVAL;
19646 	}
19647 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
19648 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
19649 		 * have to be rejected, since interpreter doesn't support them yet.
19650 		 */
19651 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
19652 		return -EINVAL;
19653 	}
19654 	for (i = 0; i < prog->len; i++, insn++) {
19655 		if (bpf_pseudo_func(insn)) {
19656 			/* When JIT fails the progs with callback calls
19657 			 * have to be rejected, since interpreter doesn't support them yet.
19658 			 */
19659 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
19660 			return -EINVAL;
19661 		}
19662 
19663 		if (!bpf_pseudo_call(insn))
19664 			continue;
19665 		depth = get_callee_stack_depth(env, insn, i);
19666 		if (depth < 0)
19667 			return depth;
19668 		bpf_patch_call_args(insn, depth);
19669 	}
19670 	err = 0;
19671 #endif
19672 	return err;
19673 }
19674 
19675 /* replace a generic kfunc with a specialized version if necessary */
specialize_kfunc(struct bpf_verifier_env * env,u32 func_id,u16 offset,unsigned long * addr)19676 static void specialize_kfunc(struct bpf_verifier_env *env,
19677 			     u32 func_id, u16 offset, unsigned long *addr)
19678 {
19679 	struct bpf_prog *prog = env->prog;
19680 	bool seen_direct_write;
19681 	void *xdp_kfunc;
19682 	bool is_rdonly;
19683 
19684 	if (bpf_dev_bound_kfunc_id(func_id)) {
19685 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19686 		if (xdp_kfunc) {
19687 			*addr = (unsigned long)xdp_kfunc;
19688 			return;
19689 		}
19690 		/* fallback to default kfunc when not supported by netdev */
19691 	}
19692 
19693 	if (offset)
19694 		return;
19695 
19696 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19697 		seen_direct_write = env->seen_direct_write;
19698 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19699 
19700 		if (is_rdonly)
19701 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19702 
19703 		/* restore env->seen_direct_write to its original value, since
19704 		 * may_access_direct_pkt_data mutates it
19705 		 */
19706 		env->seen_direct_write = seen_direct_write;
19707 	}
19708 }
19709 
__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)19710 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19711 					    u16 struct_meta_reg,
19712 					    u16 node_offset_reg,
19713 					    struct bpf_insn *insn,
19714 					    struct bpf_insn *insn_buf,
19715 					    int *cnt)
19716 {
19717 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19718 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19719 
19720 	insn_buf[0] = addr[0];
19721 	insn_buf[1] = addr[1];
19722 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19723 	insn_buf[3] = *insn;
19724 	*cnt = 4;
19725 }
19726 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)19727 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19728 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19729 {
19730 	const struct bpf_kfunc_desc *desc;
19731 
19732 	if (!insn->imm) {
19733 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19734 		return -EINVAL;
19735 	}
19736 
19737 	*cnt = 0;
19738 
19739 	/* insn->imm has the btf func_id. Replace it with an offset relative to
19740 	 * __bpf_call_base, unless the JIT needs to call functions that are
19741 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19742 	 */
19743 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19744 	if (!desc) {
19745 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19746 			insn->imm);
19747 		return -EFAULT;
19748 	}
19749 
19750 	if (!bpf_jit_supports_far_kfunc_call())
19751 		insn->imm = BPF_CALL_IMM(desc->addr);
19752 	if (insn->off)
19753 		return 0;
19754 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19755 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19756 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19757 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19758 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19759 
19760 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19761 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19762 				insn_idx);
19763 			return -EFAULT;
19764 		}
19765 
19766 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19767 		insn_buf[1] = addr[0];
19768 		insn_buf[2] = addr[1];
19769 		insn_buf[3] = *insn;
19770 		*cnt = 4;
19771 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19772 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19773 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19774 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19775 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19776 
19777 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19778 			verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19779 				insn_idx);
19780 			return -EFAULT;
19781 		}
19782 
19783 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19784 		    !kptr_struct_meta) {
19785 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19786 				insn_idx);
19787 			return -EFAULT;
19788 		}
19789 
19790 		insn_buf[0] = addr[0];
19791 		insn_buf[1] = addr[1];
19792 		insn_buf[2] = *insn;
19793 		*cnt = 3;
19794 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19795 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19796 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19797 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19798 		int struct_meta_reg = BPF_REG_3;
19799 		int node_offset_reg = BPF_REG_4;
19800 
19801 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19802 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19803 			struct_meta_reg = BPF_REG_4;
19804 			node_offset_reg = BPF_REG_5;
19805 		}
19806 
19807 		if (!kptr_struct_meta) {
19808 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19809 				insn_idx);
19810 			return -EFAULT;
19811 		}
19812 
19813 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19814 						node_offset_reg, insn, insn_buf, cnt);
19815 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19816 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19817 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19818 		*cnt = 1;
19819 	} else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) {
19820 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) };
19821 
19822 		insn_buf[0] = ld_addrs[0];
19823 		insn_buf[1] = ld_addrs[1];
19824 		insn_buf[2] = *insn;
19825 		*cnt = 3;
19826 	}
19827 	return 0;
19828 }
19829 
19830 /* 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)19831 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19832 {
19833 	struct bpf_subprog_info *info = env->subprog_info;
19834 	int cnt = env->subprog_cnt;
19835 	struct bpf_prog *prog;
19836 
19837 	/* We only reserve one slot for hidden subprogs in subprog_info. */
19838 	if (env->hidden_subprog_cnt) {
19839 		verbose(env, "verifier internal error: only one hidden subprog supported\n");
19840 		return -EFAULT;
19841 	}
19842 	/* We're not patching any existing instruction, just appending the new
19843 	 * ones for the hidden subprog. Hence all of the adjustment operations
19844 	 * in bpf_patch_insn_data are no-ops.
19845 	 */
19846 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19847 	if (!prog)
19848 		return -ENOMEM;
19849 	env->prog = prog;
19850 	info[cnt + 1].start = info[cnt].start;
19851 	info[cnt].start = prog->len - len + 1;
19852 	env->subprog_cnt++;
19853 	env->hidden_subprog_cnt++;
19854 	return 0;
19855 }
19856 
19857 /* Do various post-verification rewrites in a single program pass.
19858  * These rewrites simplify JIT and interpreter implementations.
19859  */
do_misc_fixups(struct bpf_verifier_env * env)19860 static int do_misc_fixups(struct bpf_verifier_env *env)
19861 {
19862 	struct bpf_prog *prog = env->prog;
19863 	enum bpf_attach_type eatype = prog->expected_attach_type;
19864 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
19865 	struct bpf_insn *insn = prog->insnsi;
19866 	const struct bpf_func_proto *fn;
19867 	const int insn_cnt = prog->len;
19868 	const struct bpf_map_ops *ops;
19869 	struct bpf_insn_aux_data *aux;
19870 	struct bpf_insn insn_buf[16];
19871 	struct bpf_prog *new_prog;
19872 	struct bpf_map *map_ptr;
19873 	int i, ret, cnt, delta = 0, cur_subprog = 0;
19874 	struct bpf_subprog_info *subprogs = env->subprog_info;
19875 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19876 	u16 stack_depth_extra = 0;
19877 
19878 	if (env->seen_exception && !env->exception_callback_subprog) {
19879 		struct bpf_insn patch[] = {
19880 			env->prog->insnsi[insn_cnt - 1],
19881 			BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19882 			BPF_EXIT_INSN(),
19883 		};
19884 
19885 		ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19886 		if (ret < 0)
19887 			return ret;
19888 		prog = env->prog;
19889 		insn = prog->insnsi;
19890 
19891 		env->exception_callback_subprog = env->subprog_cnt - 1;
19892 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19893 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
19894 	}
19895 
19896 	for (i = 0; i < insn_cnt;) {
19897 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
19898 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
19899 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
19900 				/* convert to 32-bit mov that clears upper 32-bit */
19901 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
19902 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
19903 				insn->off = 0;
19904 				insn->imm = 0;
19905 			} /* cast from as(0) to as(1) should be handled by JIT */
19906 			goto next_insn;
19907 		}
19908 
19909 		if (env->insn_aux_data[i + delta].needs_zext)
19910 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
19911 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
19912 
19913 		/* Make divide-by-zero exceptions impossible. */
19914 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19915 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19916 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19917 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19918 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19919 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19920 			struct bpf_insn *patchlet;
19921 			struct bpf_insn chk_and_div[] = {
19922 				/* [R,W]x div 0 -> 0 */
19923 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19924 					     BPF_JNE | BPF_K, insn->src_reg,
19925 					     0, 2, 0),
19926 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19927 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19928 				*insn,
19929 			};
19930 			struct bpf_insn chk_and_mod[] = {
19931 				/* [R,W]x mod 0 -> [R,W]x */
19932 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19933 					     BPF_JEQ | BPF_K, insn->src_reg,
19934 					     0, 1 + (is64 ? 0 : 1), 0),
19935 				*insn,
19936 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19937 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19938 			};
19939 
19940 			patchlet = isdiv ? chk_and_div : chk_and_mod;
19941 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19942 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19943 
19944 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19945 			if (!new_prog)
19946 				return -ENOMEM;
19947 
19948 			delta    += cnt - 1;
19949 			env->prog = prog = new_prog;
19950 			insn      = new_prog->insnsi + i + delta;
19951 			goto next_insn;
19952 		}
19953 
19954 		/* Make it impossible to de-reference a userspace address */
19955 		if (BPF_CLASS(insn->code) == BPF_LDX &&
19956 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
19957 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
19958 			struct bpf_insn *patch = &insn_buf[0];
19959 			u64 uaddress_limit = bpf_arch_uaddress_limit();
19960 
19961 			if (!uaddress_limit)
19962 				goto next_insn;
19963 
19964 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
19965 			if (insn->off)
19966 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
19967 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
19968 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
19969 			*patch++ = *insn;
19970 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
19971 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
19972 
19973 			cnt = patch - insn_buf;
19974 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19975 			if (!new_prog)
19976 				return -ENOMEM;
19977 
19978 			delta    += cnt - 1;
19979 			env->prog = prog = new_prog;
19980 			insn      = new_prog->insnsi + i + delta;
19981 			goto next_insn;
19982 		}
19983 
19984 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19985 		if (BPF_CLASS(insn->code) == BPF_LD &&
19986 		    (BPF_MODE(insn->code) == BPF_ABS ||
19987 		     BPF_MODE(insn->code) == BPF_IND)) {
19988 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19989 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19990 				verbose(env, "bpf verifier is misconfigured\n");
19991 				return -EINVAL;
19992 			}
19993 
19994 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19995 			if (!new_prog)
19996 				return -ENOMEM;
19997 
19998 			delta    += cnt - 1;
19999 			env->prog = prog = new_prog;
20000 			insn      = new_prog->insnsi + i + delta;
20001 			goto next_insn;
20002 		}
20003 
20004 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
20005 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
20006 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
20007 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
20008 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
20009 			struct bpf_insn *patch = &insn_buf[0];
20010 			bool issrc, isneg, isimm;
20011 			u32 off_reg;
20012 
20013 			aux = &env->insn_aux_data[i + delta];
20014 			if (!aux->alu_state ||
20015 			    aux->alu_state == BPF_ALU_NON_POINTER)
20016 				goto next_insn;
20017 
20018 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
20019 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
20020 				BPF_ALU_SANITIZE_SRC;
20021 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
20022 
20023 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
20024 			if (isimm) {
20025 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20026 			} else {
20027 				if (isneg)
20028 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20029 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
20030 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
20031 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
20032 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
20033 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
20034 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
20035 			}
20036 			if (!issrc)
20037 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
20038 			insn->src_reg = BPF_REG_AX;
20039 			if (isneg)
20040 				insn->code = insn->code == code_add ?
20041 					     code_sub : code_add;
20042 			*patch++ = *insn;
20043 			if (issrc && isneg && !isimm)
20044 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
20045 			cnt = patch - insn_buf;
20046 
20047 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20048 			if (!new_prog)
20049 				return -ENOMEM;
20050 
20051 			delta    += cnt - 1;
20052 			env->prog = prog = new_prog;
20053 			insn      = new_prog->insnsi + i + delta;
20054 			goto next_insn;
20055 		}
20056 
20057 		if (is_may_goto_insn(insn)) {
20058 			int stack_off = -stack_depth - 8;
20059 
20060 			stack_depth_extra = 8;
20061 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
20062 			if (insn->off >= 0)
20063 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
20064 			else
20065 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
20066 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
20067 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
20068 			cnt = 4;
20069 
20070 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20071 			if (!new_prog)
20072 				return -ENOMEM;
20073 
20074 			delta += cnt - 1;
20075 			env->prog = prog = new_prog;
20076 			insn = new_prog->insnsi + i + delta;
20077 			goto next_insn;
20078 		}
20079 
20080 		if (insn->code != (BPF_JMP | BPF_CALL))
20081 			goto next_insn;
20082 		if (insn->src_reg == BPF_PSEUDO_CALL)
20083 			goto next_insn;
20084 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20085 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
20086 			if (ret)
20087 				return ret;
20088 			if (cnt == 0)
20089 				goto next_insn;
20090 
20091 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20092 			if (!new_prog)
20093 				return -ENOMEM;
20094 
20095 			delta	 += cnt - 1;
20096 			env->prog = prog = new_prog;
20097 			insn	  = new_prog->insnsi + i + delta;
20098 			goto next_insn;
20099 		}
20100 
20101 		/* Skip inlining the helper call if the JIT does it. */
20102 		if (bpf_jit_inlines_helper_call(insn->imm))
20103 			goto next_insn;
20104 
20105 		if (insn->imm == BPF_FUNC_get_route_realm)
20106 			prog->dst_needed = 1;
20107 		if (insn->imm == BPF_FUNC_get_prandom_u32)
20108 			bpf_user_rnd_init_once();
20109 		if (insn->imm == BPF_FUNC_override_return)
20110 			prog->kprobe_override = 1;
20111 		if (insn->imm == BPF_FUNC_tail_call) {
20112 			/* If we tail call into other programs, we
20113 			 * cannot make any assumptions since they can
20114 			 * be replaced dynamically during runtime in
20115 			 * the program array.
20116 			 */
20117 			prog->cb_access = 1;
20118 			if (!allow_tail_call_in_subprogs(env))
20119 				prog->aux->stack_depth = MAX_BPF_STACK;
20120 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
20121 
20122 			/* mark bpf_tail_call as different opcode to avoid
20123 			 * conditional branch in the interpreter for every normal
20124 			 * call and to prevent accidental JITing by JIT compiler
20125 			 * that doesn't support bpf_tail_call yet
20126 			 */
20127 			insn->imm = 0;
20128 			insn->code = BPF_JMP | BPF_TAIL_CALL;
20129 
20130 			aux = &env->insn_aux_data[i + delta];
20131 			if (env->bpf_capable && !prog->blinding_requested &&
20132 			    prog->jit_requested &&
20133 			    !bpf_map_key_poisoned(aux) &&
20134 			    !bpf_map_ptr_poisoned(aux) &&
20135 			    !bpf_map_ptr_unpriv(aux)) {
20136 				struct bpf_jit_poke_descriptor desc = {
20137 					.reason = BPF_POKE_REASON_TAIL_CALL,
20138 					.tail_call.map = aux->map_ptr_state.map_ptr,
20139 					.tail_call.key = bpf_map_key_immediate(aux),
20140 					.insn_idx = i + delta,
20141 				};
20142 
20143 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
20144 				if (ret < 0) {
20145 					verbose(env, "adding tail call poke descriptor failed\n");
20146 					return ret;
20147 				}
20148 
20149 				insn->imm = ret + 1;
20150 				goto next_insn;
20151 			}
20152 
20153 			if (!bpf_map_ptr_unpriv(aux))
20154 				goto next_insn;
20155 
20156 			/* instead of changing every JIT dealing with tail_call
20157 			 * emit two extra insns:
20158 			 * if (index >= max_entries) goto out;
20159 			 * index &= array->index_mask;
20160 			 * to avoid out-of-bounds cpu speculation
20161 			 */
20162 			if (bpf_map_ptr_poisoned(aux)) {
20163 				verbose(env, "tail_call abusing map_ptr\n");
20164 				return -EINVAL;
20165 			}
20166 
20167 			map_ptr = aux->map_ptr_state.map_ptr;
20168 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
20169 						  map_ptr->max_entries, 2);
20170 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
20171 						    container_of(map_ptr,
20172 								 struct bpf_array,
20173 								 map)->index_mask);
20174 			insn_buf[2] = *insn;
20175 			cnt = 3;
20176 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20177 			if (!new_prog)
20178 				return -ENOMEM;
20179 
20180 			delta    += cnt - 1;
20181 			env->prog = prog = new_prog;
20182 			insn      = new_prog->insnsi + i + delta;
20183 			goto next_insn;
20184 		}
20185 
20186 		if (insn->imm == BPF_FUNC_timer_set_callback) {
20187 			/* The verifier will process callback_fn as many times as necessary
20188 			 * with different maps and the register states prepared by
20189 			 * set_timer_callback_state will be accurate.
20190 			 *
20191 			 * The following use case is valid:
20192 			 *   map1 is shared by prog1, prog2, prog3.
20193 			 *   prog1 calls bpf_timer_init for some map1 elements
20194 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
20195 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
20196 			 *   prog3 calls bpf_timer_start for some map1 elements.
20197 			 *     Those that were not both bpf_timer_init-ed and
20198 			 *     bpf_timer_set_callback-ed will return -EINVAL.
20199 			 */
20200 			struct bpf_insn ld_addrs[2] = {
20201 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
20202 			};
20203 
20204 			insn_buf[0] = ld_addrs[0];
20205 			insn_buf[1] = ld_addrs[1];
20206 			insn_buf[2] = *insn;
20207 			cnt = 3;
20208 
20209 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20210 			if (!new_prog)
20211 				return -ENOMEM;
20212 
20213 			delta    += cnt - 1;
20214 			env->prog = prog = new_prog;
20215 			insn      = new_prog->insnsi + i + delta;
20216 			goto patch_call_imm;
20217 		}
20218 
20219 		if (is_storage_get_function(insn->imm)) {
20220 			if (!in_sleepable(env) ||
20221 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
20222 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
20223 			else
20224 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
20225 			insn_buf[1] = *insn;
20226 			cnt = 2;
20227 
20228 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20229 			if (!new_prog)
20230 				return -ENOMEM;
20231 
20232 			delta += cnt - 1;
20233 			env->prog = prog = new_prog;
20234 			insn = new_prog->insnsi + i + delta;
20235 			goto patch_call_imm;
20236 		}
20237 
20238 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
20239 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
20240 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
20241 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
20242 			 */
20243 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
20244 			insn_buf[1] = *insn;
20245 			cnt = 2;
20246 
20247 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20248 			if (!new_prog)
20249 				return -ENOMEM;
20250 
20251 			delta += cnt - 1;
20252 			env->prog = prog = new_prog;
20253 			insn = new_prog->insnsi + i + delta;
20254 			goto patch_call_imm;
20255 		}
20256 
20257 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
20258 		 * and other inlining handlers are currently limited to 64 bit
20259 		 * only.
20260 		 */
20261 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20262 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
20263 		     insn->imm == BPF_FUNC_map_update_elem ||
20264 		     insn->imm == BPF_FUNC_map_delete_elem ||
20265 		     insn->imm == BPF_FUNC_map_push_elem   ||
20266 		     insn->imm == BPF_FUNC_map_pop_elem    ||
20267 		     insn->imm == BPF_FUNC_map_peek_elem   ||
20268 		     insn->imm == BPF_FUNC_redirect_map    ||
20269 		     insn->imm == BPF_FUNC_for_each_map_elem ||
20270 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
20271 			aux = &env->insn_aux_data[i + delta];
20272 			if (bpf_map_ptr_poisoned(aux))
20273 				goto patch_call_imm;
20274 
20275 			map_ptr = aux->map_ptr_state.map_ptr;
20276 			ops = map_ptr->ops;
20277 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
20278 			    ops->map_gen_lookup) {
20279 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
20280 				if (cnt == -EOPNOTSUPP)
20281 					goto patch_map_ops_generic;
20282 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
20283 					verbose(env, "bpf verifier is misconfigured\n");
20284 					return -EINVAL;
20285 				}
20286 
20287 				new_prog = bpf_patch_insn_data(env, i + delta,
20288 							       insn_buf, cnt);
20289 				if (!new_prog)
20290 					return -ENOMEM;
20291 
20292 				delta    += cnt - 1;
20293 				env->prog = prog = new_prog;
20294 				insn      = new_prog->insnsi + i + delta;
20295 				goto next_insn;
20296 			}
20297 
20298 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
20299 				     (void *(*)(struct bpf_map *map, void *key))NULL));
20300 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
20301 				     (long (*)(struct bpf_map *map, void *key))NULL));
20302 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
20303 				     (long (*)(struct bpf_map *map, void *key, void *value,
20304 					      u64 flags))NULL));
20305 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
20306 				     (long (*)(struct bpf_map *map, void *value,
20307 					      u64 flags))NULL));
20308 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
20309 				     (long (*)(struct bpf_map *map, void *value))NULL));
20310 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
20311 				     (long (*)(struct bpf_map *map, void *value))NULL));
20312 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
20313 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
20314 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
20315 				     (long (*)(struct bpf_map *map,
20316 					      bpf_callback_t callback_fn,
20317 					      void *callback_ctx,
20318 					      u64 flags))NULL));
20319 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
20320 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
20321 
20322 patch_map_ops_generic:
20323 			switch (insn->imm) {
20324 			case BPF_FUNC_map_lookup_elem:
20325 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
20326 				goto next_insn;
20327 			case BPF_FUNC_map_update_elem:
20328 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
20329 				goto next_insn;
20330 			case BPF_FUNC_map_delete_elem:
20331 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
20332 				goto next_insn;
20333 			case BPF_FUNC_map_push_elem:
20334 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
20335 				goto next_insn;
20336 			case BPF_FUNC_map_pop_elem:
20337 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
20338 				goto next_insn;
20339 			case BPF_FUNC_map_peek_elem:
20340 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
20341 				goto next_insn;
20342 			case BPF_FUNC_redirect_map:
20343 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
20344 				goto next_insn;
20345 			case BPF_FUNC_for_each_map_elem:
20346 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
20347 				goto next_insn;
20348 			case BPF_FUNC_map_lookup_percpu_elem:
20349 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
20350 				goto next_insn;
20351 			}
20352 
20353 			goto patch_call_imm;
20354 		}
20355 
20356 		/* Implement bpf_jiffies64 inline. */
20357 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20358 		    insn->imm == BPF_FUNC_jiffies64) {
20359 			struct bpf_insn ld_jiffies_addr[2] = {
20360 				BPF_LD_IMM64(BPF_REG_0,
20361 					     (unsigned long)&jiffies),
20362 			};
20363 
20364 			insn_buf[0] = ld_jiffies_addr[0];
20365 			insn_buf[1] = ld_jiffies_addr[1];
20366 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
20367 						  BPF_REG_0, 0);
20368 			cnt = 3;
20369 
20370 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
20371 						       cnt);
20372 			if (!new_prog)
20373 				return -ENOMEM;
20374 
20375 			delta    += cnt - 1;
20376 			env->prog = prog = new_prog;
20377 			insn      = new_prog->insnsi + i + delta;
20378 			goto next_insn;
20379 		}
20380 
20381 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
20382 		/* Implement bpf_get_smp_processor_id() inline. */
20383 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
20384 		    prog->jit_requested && bpf_jit_supports_percpu_insn()) {
20385 			/* BPF_FUNC_get_smp_processor_id inlining is an
20386 			 * optimization, so if pcpu_hot.cpu_number is ever
20387 			 * changed in some incompatible and hard to support
20388 			 * way, it's fine to back out this inlining logic
20389 			 */
20390 			insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number);
20391 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
20392 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
20393 			cnt = 3;
20394 
20395 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20396 			if (!new_prog)
20397 				return -ENOMEM;
20398 
20399 			delta    += cnt - 1;
20400 			env->prog = prog = new_prog;
20401 			insn      = new_prog->insnsi + i + delta;
20402 			goto next_insn;
20403 		}
20404 #endif
20405 		/* Implement bpf_get_func_arg inline. */
20406 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20407 		    insn->imm == BPF_FUNC_get_func_arg) {
20408 			/* Load nr_args from ctx - 8 */
20409 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20410 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
20411 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
20412 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
20413 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
20414 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20415 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
20416 			insn_buf[7] = BPF_JMP_A(1);
20417 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20418 			cnt = 9;
20419 
20420 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20421 			if (!new_prog)
20422 				return -ENOMEM;
20423 
20424 			delta    += cnt - 1;
20425 			env->prog = prog = new_prog;
20426 			insn      = new_prog->insnsi + i + delta;
20427 			goto next_insn;
20428 		}
20429 
20430 		/* Implement bpf_get_func_ret inline. */
20431 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20432 		    insn->imm == BPF_FUNC_get_func_ret) {
20433 			if (eatype == BPF_TRACE_FEXIT ||
20434 			    eatype == BPF_MODIFY_RETURN) {
20435 				/* Load nr_args from ctx - 8 */
20436 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20437 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
20438 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
20439 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
20440 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
20441 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
20442 				cnt = 6;
20443 			} else {
20444 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
20445 				cnt = 1;
20446 			}
20447 
20448 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20449 			if (!new_prog)
20450 				return -ENOMEM;
20451 
20452 			delta    += cnt - 1;
20453 			env->prog = prog = new_prog;
20454 			insn      = new_prog->insnsi + i + delta;
20455 			goto next_insn;
20456 		}
20457 
20458 		/* Implement get_func_arg_cnt inline. */
20459 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20460 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
20461 			/* Load nr_args from ctx - 8 */
20462 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
20463 
20464 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20465 			if (!new_prog)
20466 				return -ENOMEM;
20467 
20468 			env->prog = prog = new_prog;
20469 			insn      = new_prog->insnsi + i + delta;
20470 			goto next_insn;
20471 		}
20472 
20473 		/* Implement bpf_get_func_ip inline. */
20474 		if (prog_type == BPF_PROG_TYPE_TRACING &&
20475 		    insn->imm == BPF_FUNC_get_func_ip) {
20476 			/* Load IP address from ctx - 16 */
20477 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
20478 
20479 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
20480 			if (!new_prog)
20481 				return -ENOMEM;
20482 
20483 			env->prog = prog = new_prog;
20484 			insn      = new_prog->insnsi + i + delta;
20485 			goto next_insn;
20486 		}
20487 
20488 		/* Implement bpf_get_branch_snapshot inline. */
20489 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
20490 		    prog->jit_requested && BITS_PER_LONG == 64 &&
20491 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
20492 			/* We are dealing with the following func protos:
20493 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
20494 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
20495 			 */
20496 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
20497 
20498 			/* struct perf_branch_entry is part of UAPI and is
20499 			 * used as an array element, so extremely unlikely to
20500 			 * ever grow or shrink
20501 			 */
20502 			BUILD_BUG_ON(br_entry_size != 24);
20503 
20504 			/* if (unlikely(flags)) return -EINVAL */
20505 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
20506 
20507 			/* Transform size (bytes) into number of entries (cnt = size / 24).
20508 			 * But to avoid expensive division instruction, we implement
20509 			 * divide-by-3 through multiplication, followed by further
20510 			 * division by 8 through 3-bit right shift.
20511 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
20512 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
20513 			 *
20514 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
20515 			 */
20516 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
20517 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
20518 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
20519 
20520 			/* call perf_snapshot_branch_stack implementation */
20521 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
20522 			/* if (entry_cnt == 0) return -ENOENT */
20523 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
20524 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
20525 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
20526 			insn_buf[7] = BPF_JMP_A(3);
20527 			/* return -EINVAL; */
20528 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
20529 			insn_buf[9] = BPF_JMP_A(1);
20530 			/* return -ENOENT; */
20531 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
20532 			cnt = 11;
20533 
20534 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20535 			if (!new_prog)
20536 				return -ENOMEM;
20537 
20538 			delta    += cnt - 1;
20539 			env->prog = prog = new_prog;
20540 			insn      = new_prog->insnsi + i + delta;
20541 			continue;
20542 		}
20543 
20544 		/* Implement bpf_kptr_xchg inline */
20545 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
20546 		    insn->imm == BPF_FUNC_kptr_xchg &&
20547 		    bpf_jit_supports_ptr_xchg()) {
20548 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
20549 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
20550 			cnt = 2;
20551 
20552 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
20553 			if (!new_prog)
20554 				return -ENOMEM;
20555 
20556 			delta    += cnt - 1;
20557 			env->prog = prog = new_prog;
20558 			insn      = new_prog->insnsi + i + delta;
20559 			goto next_insn;
20560 		}
20561 patch_call_imm:
20562 		fn = env->ops->get_func_proto(insn->imm, env->prog);
20563 		/* all functions that have prototype and verifier allowed
20564 		 * programs to call them, must be real in-kernel functions
20565 		 */
20566 		if (!fn->func) {
20567 			verbose(env,
20568 				"kernel subsystem misconfigured func %s#%d\n",
20569 				func_id_name(insn->imm), insn->imm);
20570 			return -EFAULT;
20571 		}
20572 		insn->imm = fn->func - __bpf_call_base;
20573 next_insn:
20574 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20575 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20576 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
20577 			cur_subprog++;
20578 			stack_depth = subprogs[cur_subprog].stack_depth;
20579 			stack_depth_extra = 0;
20580 		}
20581 		i++;
20582 		insn++;
20583 	}
20584 
20585 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
20586 	for (i = 0; i < env->subprog_cnt; i++) {
20587 		int subprog_start = subprogs[i].start;
20588 		int stack_slots = subprogs[i].stack_extra / 8;
20589 
20590 		if (!stack_slots)
20591 			continue;
20592 		if (stack_slots > 1) {
20593 			verbose(env, "verifier bug: stack_slots supports may_goto only\n");
20594 			return -EFAULT;
20595 		}
20596 
20597 		/* Add ST insn to subprog prologue to init extra stack */
20598 		insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
20599 					 -subprogs[i].stack_depth, BPF_MAX_LOOPS);
20600 		/* Copy first actual insn to preserve it */
20601 		insn_buf[1] = env->prog->insnsi[subprog_start];
20602 
20603 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2);
20604 		if (!new_prog)
20605 			return -ENOMEM;
20606 		env->prog = prog = new_prog;
20607 		/*
20608 		 * If may_goto is a first insn of a prog there could be a jmp
20609 		 * insn that points to it, hence adjust all such jmps to point
20610 		 * to insn after BPF_ST that inits may_goto count.
20611 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
20612 		 */
20613 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, 1));
20614 	}
20615 
20616 	/* Since poke tab is now finalized, publish aux to tracker. */
20617 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
20618 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
20619 		if (!map_ptr->ops->map_poke_track ||
20620 		    !map_ptr->ops->map_poke_untrack ||
20621 		    !map_ptr->ops->map_poke_run) {
20622 			verbose(env, "bpf verifier is misconfigured\n");
20623 			return -EINVAL;
20624 		}
20625 
20626 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
20627 		if (ret < 0) {
20628 			verbose(env, "tracking tail call prog failed\n");
20629 			return ret;
20630 		}
20631 	}
20632 
20633 	sort_kfunc_descs_by_imm_off(env->prog);
20634 
20635 	return 0;
20636 }
20637 
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * cnt)20638 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
20639 					int position,
20640 					s32 stack_base,
20641 					u32 callback_subprogno,
20642 					u32 *cnt)
20643 {
20644 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
20645 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
20646 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
20647 	int reg_loop_max = BPF_REG_6;
20648 	int reg_loop_cnt = BPF_REG_7;
20649 	int reg_loop_ctx = BPF_REG_8;
20650 
20651 	struct bpf_prog *new_prog;
20652 	u32 callback_start;
20653 	u32 call_insn_offset;
20654 	s32 callback_offset;
20655 
20656 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
20657 	 * be careful to modify this code in sync.
20658 	 */
20659 	struct bpf_insn insn_buf[] = {
20660 		/* Return error and jump to the end of the patch if
20661 		 * expected number of iterations is too big.
20662 		 */
20663 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
20664 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
20665 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
20666 		/* spill R6, R7, R8 to use these as loop vars */
20667 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
20668 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
20669 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
20670 		/* initialize loop vars */
20671 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
20672 		BPF_MOV32_IMM(reg_loop_cnt, 0),
20673 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
20674 		/* loop header,
20675 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
20676 		 */
20677 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
20678 		/* callback call,
20679 		 * correct callback offset would be set after patching
20680 		 */
20681 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
20682 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
20683 		BPF_CALL_REL(0),
20684 		/* increment loop counter */
20685 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
20686 		/* jump to loop header if callback returned 0 */
20687 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
20688 		/* return value of bpf_loop,
20689 		 * set R0 to the number of iterations
20690 		 */
20691 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
20692 		/* restore original values of R6, R7, R8 */
20693 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
20694 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
20695 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
20696 	};
20697 
20698 	*cnt = ARRAY_SIZE(insn_buf);
20699 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
20700 	if (!new_prog)
20701 		return new_prog;
20702 
20703 	/* callback start is known only after patching */
20704 	callback_start = env->subprog_info[callback_subprogno].start;
20705 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
20706 	call_insn_offset = position + 12;
20707 	callback_offset = callback_start - call_insn_offset - 1;
20708 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
20709 
20710 	return new_prog;
20711 }
20712 
is_bpf_loop_call(struct bpf_insn * insn)20713 static bool is_bpf_loop_call(struct bpf_insn *insn)
20714 {
20715 	return insn->code == (BPF_JMP | BPF_CALL) &&
20716 		insn->src_reg == 0 &&
20717 		insn->imm == BPF_FUNC_loop;
20718 }
20719 
20720 /* For all sub-programs in the program (including main) check
20721  * insn_aux_data to see if there are bpf_loop calls that require
20722  * inlining. If such calls are found the calls are replaced with a
20723  * sequence of instructions produced by `inline_bpf_loop` function and
20724  * subprog stack_depth is increased by the size of 3 registers.
20725  * This stack space is used to spill values of the R6, R7, R8.  These
20726  * registers are used to store the loop bound, counter and context
20727  * variables.
20728  */
optimize_bpf_loop(struct bpf_verifier_env * env)20729 static int optimize_bpf_loop(struct bpf_verifier_env *env)
20730 {
20731 	struct bpf_subprog_info *subprogs = env->subprog_info;
20732 	int i, cur_subprog = 0, cnt, delta = 0;
20733 	struct bpf_insn *insn = env->prog->insnsi;
20734 	int insn_cnt = env->prog->len;
20735 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
20736 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20737 	u16 stack_depth_extra = 0;
20738 
20739 	for (i = 0; i < insn_cnt; i++, insn++) {
20740 		struct bpf_loop_inline_state *inline_state =
20741 			&env->insn_aux_data[i + delta].loop_inline_state;
20742 
20743 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
20744 			struct bpf_prog *new_prog;
20745 
20746 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
20747 			new_prog = inline_bpf_loop(env,
20748 						   i + delta,
20749 						   -(stack_depth + stack_depth_extra),
20750 						   inline_state->callback_subprogno,
20751 						   &cnt);
20752 			if (!new_prog)
20753 				return -ENOMEM;
20754 
20755 			delta     += cnt - 1;
20756 			env->prog  = new_prog;
20757 			insn       = new_prog->insnsi + i + delta;
20758 		}
20759 
20760 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
20761 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
20762 			cur_subprog++;
20763 			stack_depth = subprogs[cur_subprog].stack_depth;
20764 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
20765 			stack_depth_extra = 0;
20766 		}
20767 	}
20768 
20769 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20770 
20771 	return 0;
20772 }
20773 
free_states(struct bpf_verifier_env * env)20774 static void free_states(struct bpf_verifier_env *env)
20775 {
20776 	struct bpf_verifier_state_list *sl, *sln;
20777 	int i;
20778 
20779 	sl = env->free_list;
20780 	while (sl) {
20781 		sln = sl->next;
20782 		free_verifier_state(&sl->state, false);
20783 		kfree(sl);
20784 		sl = sln;
20785 	}
20786 	env->free_list = NULL;
20787 
20788 	if (!env->explored_states)
20789 		return;
20790 
20791 	for (i = 0; i < state_htab_size(env); i++) {
20792 		sl = env->explored_states[i];
20793 
20794 		while (sl) {
20795 			sln = sl->next;
20796 			free_verifier_state(&sl->state, false);
20797 			kfree(sl);
20798 			sl = sln;
20799 		}
20800 		env->explored_states[i] = NULL;
20801 	}
20802 }
20803 
do_check_common(struct bpf_verifier_env * env,int subprog)20804 static int do_check_common(struct bpf_verifier_env *env, int subprog)
20805 {
20806 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20807 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
20808 	struct bpf_verifier_state *state;
20809 	struct bpf_reg_state *regs;
20810 	int ret, i;
20811 
20812 	env->prev_linfo = NULL;
20813 	env->pass_cnt++;
20814 
20815 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
20816 	if (!state)
20817 		return -ENOMEM;
20818 	state->curframe = 0;
20819 	state->speculative = false;
20820 	state->branches = 1;
20821 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
20822 	if (!state->frame[0]) {
20823 		kfree(state);
20824 		return -ENOMEM;
20825 	}
20826 	env->cur_state = state;
20827 	init_func_state(env, state->frame[0],
20828 			BPF_MAIN_FUNC /* callsite */,
20829 			0 /* frameno */,
20830 			subprog);
20831 	state->first_insn_idx = env->subprog_info[subprog].start;
20832 	state->last_insn_idx = -1;
20833 
20834 	regs = state->frame[state->curframe]->regs;
20835 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
20836 		const char *sub_name = subprog_name(env, subprog);
20837 		struct bpf_subprog_arg_info *arg;
20838 		struct bpf_reg_state *reg;
20839 
20840 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
20841 		ret = btf_prepare_func_args(env, subprog);
20842 		if (ret)
20843 			goto out;
20844 
20845 		if (subprog_is_exc_cb(env, subprog)) {
20846 			state->frame[0]->in_exception_callback_fn = true;
20847 			/* We have already ensured that the callback returns an integer, just
20848 			 * like all global subprogs. We need to determine it only has a single
20849 			 * scalar argument.
20850 			 */
20851 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
20852 				verbose(env, "exception cb only supports single integer argument\n");
20853 				ret = -EINVAL;
20854 				goto out;
20855 			}
20856 		}
20857 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
20858 			arg = &sub->args[i - BPF_REG_1];
20859 			reg = &regs[i];
20860 
20861 			if (arg->arg_type == ARG_PTR_TO_CTX) {
20862 				reg->type = PTR_TO_CTX;
20863 				mark_reg_known_zero(env, regs, i);
20864 			} else if (arg->arg_type == ARG_ANYTHING) {
20865 				reg->type = SCALAR_VALUE;
20866 				mark_reg_unknown(env, regs, i);
20867 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
20868 				/* assume unspecial LOCAL dynptr type */
20869 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
20870 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
20871 				reg->type = PTR_TO_MEM;
20872 				if (arg->arg_type & PTR_MAYBE_NULL)
20873 					reg->type |= PTR_MAYBE_NULL;
20874 				mark_reg_known_zero(env, regs, i);
20875 				reg->mem_size = arg->mem_size;
20876 				reg->id = ++env->id_gen;
20877 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
20878 				reg->type = PTR_TO_BTF_ID;
20879 				if (arg->arg_type & PTR_MAYBE_NULL)
20880 					reg->type |= PTR_MAYBE_NULL;
20881 				if (arg->arg_type & PTR_UNTRUSTED)
20882 					reg->type |= PTR_UNTRUSTED;
20883 				if (arg->arg_type & PTR_TRUSTED)
20884 					reg->type |= PTR_TRUSTED;
20885 				mark_reg_known_zero(env, regs, i);
20886 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
20887 				reg->btf_id = arg->btf_id;
20888 				reg->id = ++env->id_gen;
20889 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
20890 				/* caller can pass either PTR_TO_ARENA or SCALAR */
20891 				mark_reg_unknown(env, regs, i);
20892 			} else {
20893 				WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n",
20894 					  i - BPF_REG_1, arg->arg_type);
20895 				ret = -EFAULT;
20896 				goto out;
20897 			}
20898 		}
20899 	} else {
20900 		/* if main BPF program has associated BTF info, validate that
20901 		 * it's matching expected signature, and otherwise mark BTF
20902 		 * info for main program as unreliable
20903 		 */
20904 		if (env->prog->aux->func_info_aux) {
20905 			ret = btf_prepare_func_args(env, 0);
20906 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
20907 				env->prog->aux->func_info_aux[0].unreliable = true;
20908 		}
20909 
20910 		/* 1st arg to a function */
20911 		regs[BPF_REG_1].type = PTR_TO_CTX;
20912 		mark_reg_known_zero(env, regs, BPF_REG_1);
20913 	}
20914 
20915 	ret = do_check(env);
20916 out:
20917 	/* check for NULL is necessary, since cur_state can be freed inside
20918 	 * do_check() under memory pressure.
20919 	 */
20920 	if (env->cur_state) {
20921 		free_verifier_state(env->cur_state, true);
20922 		env->cur_state = NULL;
20923 	}
20924 	while (!pop_stack(env, NULL, NULL, false));
20925 	if (!ret && pop_log)
20926 		bpf_vlog_reset(&env->log, 0);
20927 	free_states(env);
20928 	return ret;
20929 }
20930 
20931 /* Lazily verify all global functions based on their BTF, if they are called
20932  * from main BPF program or any of subprograms transitively.
20933  * BPF global subprogs called from dead code are not validated.
20934  * All callable global functions must pass verification.
20935  * Otherwise the whole program is rejected.
20936  * Consider:
20937  * int bar(int);
20938  * int foo(int f)
20939  * {
20940  *    return bar(f);
20941  * }
20942  * int bar(int b)
20943  * {
20944  *    ...
20945  * }
20946  * foo() will be verified first for R1=any_scalar_value. During verification it
20947  * will be assumed that bar() already verified successfully and call to bar()
20948  * from foo() will be checked for type match only. Later bar() will be verified
20949  * independently to check that it's safe for R1=any_scalar_value.
20950  */
do_check_subprogs(struct bpf_verifier_env * env)20951 static int do_check_subprogs(struct bpf_verifier_env *env)
20952 {
20953 	struct bpf_prog_aux *aux = env->prog->aux;
20954 	struct bpf_func_info_aux *sub_aux;
20955 	int i, ret, new_cnt;
20956 
20957 	if (!aux->func_info)
20958 		return 0;
20959 
20960 	/* exception callback is presumed to be always called */
20961 	if (env->exception_callback_subprog)
20962 		subprog_aux(env, env->exception_callback_subprog)->called = true;
20963 
20964 again:
20965 	new_cnt = 0;
20966 	for (i = 1; i < env->subprog_cnt; i++) {
20967 		if (!subprog_is_global(env, i))
20968 			continue;
20969 
20970 		sub_aux = subprog_aux(env, i);
20971 		if (!sub_aux->called || sub_aux->verified)
20972 			continue;
20973 
20974 		env->insn_idx = env->subprog_info[i].start;
20975 		WARN_ON_ONCE(env->insn_idx == 0);
20976 		ret = do_check_common(env, i);
20977 		if (ret) {
20978 			return ret;
20979 		} else if (env->log.level & BPF_LOG_LEVEL) {
20980 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
20981 				i, subprog_name(env, i));
20982 		}
20983 
20984 		/* We verified new global subprog, it might have called some
20985 		 * more global subprogs that we haven't verified yet, so we
20986 		 * need to do another pass over subprogs to verify those.
20987 		 */
20988 		sub_aux->verified = true;
20989 		new_cnt++;
20990 	}
20991 
20992 	/* We can't loop forever as we verify at least one global subprog on
20993 	 * each pass.
20994 	 */
20995 	if (new_cnt)
20996 		goto again;
20997 
20998 	return 0;
20999 }
21000 
do_check_main(struct bpf_verifier_env * env)21001 static int do_check_main(struct bpf_verifier_env *env)
21002 {
21003 	int ret;
21004 
21005 	env->insn_idx = 0;
21006 	ret = do_check_common(env, 0);
21007 	if (!ret)
21008 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
21009 	return ret;
21010 }
21011 
21012 
print_verification_stats(struct bpf_verifier_env * env)21013 static void print_verification_stats(struct bpf_verifier_env *env)
21014 {
21015 	int i;
21016 
21017 	if (env->log.level & BPF_LOG_STATS) {
21018 		verbose(env, "verification time %lld usec\n",
21019 			div_u64(env->verification_time, 1000));
21020 		verbose(env, "stack depth ");
21021 		for (i = 0; i < env->subprog_cnt; i++) {
21022 			u32 depth = env->subprog_info[i].stack_depth;
21023 
21024 			verbose(env, "%d", depth);
21025 			if (i + 1 < env->subprog_cnt)
21026 				verbose(env, "+");
21027 		}
21028 		verbose(env, "\n");
21029 	}
21030 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
21031 		"total_states %d peak_states %d mark_read %d\n",
21032 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
21033 		env->max_states_per_insn, env->total_states,
21034 		env->peak_states, env->longest_mark_read_walk);
21035 }
21036 
check_struct_ops_btf_id(struct bpf_verifier_env * env)21037 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
21038 {
21039 	const struct btf_type *t, *func_proto;
21040 	const struct bpf_struct_ops_desc *st_ops_desc;
21041 	const struct bpf_struct_ops *st_ops;
21042 	const struct btf_member *member;
21043 	struct bpf_prog *prog = env->prog;
21044 	u32 btf_id, member_idx;
21045 	struct btf *btf;
21046 	const char *mname;
21047 
21048 	if (!prog->gpl_compatible) {
21049 		verbose(env, "struct ops programs must have a GPL compatible license\n");
21050 		return -EINVAL;
21051 	}
21052 
21053 	if (!prog->aux->attach_btf_id)
21054 		return -ENOTSUPP;
21055 
21056 	btf = prog->aux->attach_btf;
21057 	if (btf_is_module(btf)) {
21058 		/* Make sure st_ops is valid through the lifetime of env */
21059 		env->attach_btf_mod = btf_try_get_module(btf);
21060 		if (!env->attach_btf_mod) {
21061 			verbose(env, "struct_ops module %s is not found\n",
21062 				btf_get_name(btf));
21063 			return -ENOTSUPP;
21064 		}
21065 	}
21066 
21067 	btf_id = prog->aux->attach_btf_id;
21068 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
21069 	if (!st_ops_desc) {
21070 		verbose(env, "attach_btf_id %u is not a supported struct\n",
21071 			btf_id);
21072 		return -ENOTSUPP;
21073 	}
21074 	st_ops = st_ops_desc->st_ops;
21075 
21076 	t = st_ops_desc->type;
21077 	member_idx = prog->expected_attach_type;
21078 	if (member_idx >= btf_type_vlen(t)) {
21079 		verbose(env, "attach to invalid member idx %u of struct %s\n",
21080 			member_idx, st_ops->name);
21081 		return -EINVAL;
21082 	}
21083 
21084 	member = &btf_type_member(t)[member_idx];
21085 	mname = btf_name_by_offset(btf, member->name_off);
21086 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
21087 					       NULL);
21088 	if (!func_proto) {
21089 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
21090 			mname, member_idx, st_ops->name);
21091 		return -EINVAL;
21092 	}
21093 
21094 	if (st_ops->check_member) {
21095 		int err = st_ops->check_member(t, member, prog);
21096 
21097 		if (err) {
21098 			verbose(env, "attach to unsupported member %s of struct %s\n",
21099 				mname, st_ops->name);
21100 			return err;
21101 		}
21102 	}
21103 
21104 	/* btf_ctx_access() used this to provide argument type info */
21105 	prog->aux->ctx_arg_info =
21106 		st_ops_desc->arg_info[member_idx].info;
21107 	prog->aux->ctx_arg_info_size =
21108 		st_ops_desc->arg_info[member_idx].cnt;
21109 
21110 	prog->aux->attach_func_proto = func_proto;
21111 	prog->aux->attach_func_name = mname;
21112 	env->ops = st_ops->verifier_ops;
21113 
21114 	return 0;
21115 }
21116 #define SECURITY_PREFIX "security_"
21117 
check_attach_modify_return(unsigned long addr,const char * func_name)21118 static int check_attach_modify_return(unsigned long addr, const char *func_name)
21119 {
21120 	if (within_error_injection_list(addr) ||
21121 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
21122 		return 0;
21123 
21124 	return -EINVAL;
21125 }
21126 
21127 /* list of non-sleepable functions that are otherwise on
21128  * ALLOW_ERROR_INJECTION list
21129  */
21130 BTF_SET_START(btf_non_sleepable_error_inject)
21131 /* Three functions below can be called from sleepable and non-sleepable context.
21132  * Assume non-sleepable from bpf safety point of view.
21133  */
BTF_ID(func,__filemap_add_folio)21134 BTF_ID(func, __filemap_add_folio)
21135 #ifdef CONFIG_FAIL_PAGE_ALLOC
21136 BTF_ID(func, should_fail_alloc_page)
21137 #endif
21138 #ifdef CONFIG_FAILSLAB
21139 BTF_ID(func, should_failslab)
21140 #endif
21141 BTF_SET_END(btf_non_sleepable_error_inject)
21142 
21143 static int check_non_sleepable_error_inject(u32 btf_id)
21144 {
21145 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
21146 }
21147 
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)21148 int bpf_check_attach_target(struct bpf_verifier_log *log,
21149 			    const struct bpf_prog *prog,
21150 			    const struct bpf_prog *tgt_prog,
21151 			    u32 btf_id,
21152 			    struct bpf_attach_target_info *tgt_info)
21153 {
21154 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
21155 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
21156 	const char prefix[] = "btf_trace_";
21157 	int ret = 0, subprog = -1, i;
21158 	const struct btf_type *t;
21159 	bool conservative = true;
21160 	const char *tname;
21161 	struct btf *btf;
21162 	long addr = 0;
21163 	struct module *mod = NULL;
21164 
21165 	if (!btf_id) {
21166 		bpf_log(log, "Tracing programs must provide btf_id\n");
21167 		return -EINVAL;
21168 	}
21169 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
21170 	if (!btf) {
21171 		bpf_log(log,
21172 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
21173 		return -EINVAL;
21174 	}
21175 	t = btf_type_by_id(btf, btf_id);
21176 	if (!t) {
21177 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
21178 		return -EINVAL;
21179 	}
21180 	tname = btf_name_by_offset(btf, t->name_off);
21181 	if (!tname) {
21182 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
21183 		return -EINVAL;
21184 	}
21185 	if (tgt_prog) {
21186 		struct bpf_prog_aux *aux = tgt_prog->aux;
21187 
21188 		if (bpf_prog_is_dev_bound(prog->aux) &&
21189 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
21190 			bpf_log(log, "Target program bound device mismatch");
21191 			return -EINVAL;
21192 		}
21193 
21194 		for (i = 0; i < aux->func_info_cnt; i++)
21195 			if (aux->func_info[i].type_id == btf_id) {
21196 				subprog = i;
21197 				break;
21198 			}
21199 		if (subprog == -1) {
21200 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
21201 			return -EINVAL;
21202 		}
21203 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
21204 			bpf_log(log,
21205 				"%s programs cannot attach to exception callback\n",
21206 				prog_extension ? "Extension" : "FENTRY/FEXIT");
21207 			return -EINVAL;
21208 		}
21209 		conservative = aux->func_info_aux[subprog].unreliable;
21210 		if (prog_extension) {
21211 			if (conservative) {
21212 				bpf_log(log,
21213 					"Cannot replace static functions\n");
21214 				return -EINVAL;
21215 			}
21216 			if (!prog->jit_requested) {
21217 				bpf_log(log,
21218 					"Extension programs should be JITed\n");
21219 				return -EINVAL;
21220 			}
21221 		}
21222 		if (!tgt_prog->jited) {
21223 			bpf_log(log, "Can attach to only JITed progs\n");
21224 			return -EINVAL;
21225 		}
21226 		if (prog_tracing) {
21227 			if (aux->attach_tracing_prog) {
21228 				/*
21229 				 * Target program is an fentry/fexit which is already attached
21230 				 * to another tracing program. More levels of nesting
21231 				 * attachment are not allowed.
21232 				 */
21233 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
21234 				return -EINVAL;
21235 			}
21236 		} else if (tgt_prog->type == prog->type) {
21237 			/*
21238 			 * To avoid potential call chain cycles, prevent attaching of a
21239 			 * program extension to another extension. It's ok to attach
21240 			 * fentry/fexit to extension program.
21241 			 */
21242 			bpf_log(log, "Cannot recursively attach\n");
21243 			return -EINVAL;
21244 		}
21245 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
21246 		    prog_extension &&
21247 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
21248 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
21249 			/* Program extensions can extend all program types
21250 			 * except fentry/fexit. The reason is the following.
21251 			 * The fentry/fexit programs are used for performance
21252 			 * analysis, stats and can be attached to any program
21253 			 * type. When extension program is replacing XDP function
21254 			 * it is necessary to allow performance analysis of all
21255 			 * functions. Both original XDP program and its program
21256 			 * extension. Hence attaching fentry/fexit to
21257 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
21258 			 * fentry/fexit was allowed it would be possible to create
21259 			 * long call chain fentry->extension->fentry->extension
21260 			 * beyond reasonable stack size. Hence extending fentry
21261 			 * is not allowed.
21262 			 */
21263 			bpf_log(log, "Cannot extend fentry/fexit\n");
21264 			return -EINVAL;
21265 		}
21266 	} else {
21267 		if (prog_extension) {
21268 			bpf_log(log, "Cannot replace kernel functions\n");
21269 			return -EINVAL;
21270 		}
21271 	}
21272 
21273 	switch (prog->expected_attach_type) {
21274 	case BPF_TRACE_RAW_TP:
21275 		if (tgt_prog) {
21276 			bpf_log(log,
21277 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
21278 			return -EINVAL;
21279 		}
21280 		if (!btf_type_is_typedef(t)) {
21281 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
21282 				btf_id);
21283 			return -EINVAL;
21284 		}
21285 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
21286 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
21287 				btf_id, tname);
21288 			return -EINVAL;
21289 		}
21290 		tname += sizeof(prefix) - 1;
21291 		t = btf_type_by_id(btf, t->type);
21292 		if (!btf_type_is_ptr(t))
21293 			/* should never happen in valid vmlinux build */
21294 			return -EINVAL;
21295 		t = btf_type_by_id(btf, t->type);
21296 		if (!btf_type_is_func_proto(t))
21297 			/* should never happen in valid vmlinux build */
21298 			return -EINVAL;
21299 
21300 		break;
21301 	case BPF_TRACE_ITER:
21302 		if (!btf_type_is_func(t)) {
21303 			bpf_log(log, "attach_btf_id %u is not a function\n",
21304 				btf_id);
21305 			return -EINVAL;
21306 		}
21307 		t = btf_type_by_id(btf, t->type);
21308 		if (!btf_type_is_func_proto(t))
21309 			return -EINVAL;
21310 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
21311 		if (ret)
21312 			return ret;
21313 		break;
21314 	default:
21315 		if (!prog_extension)
21316 			return -EINVAL;
21317 		fallthrough;
21318 	case BPF_MODIFY_RETURN:
21319 	case BPF_LSM_MAC:
21320 	case BPF_LSM_CGROUP:
21321 	case BPF_TRACE_FENTRY:
21322 	case BPF_TRACE_FEXIT:
21323 		if (!btf_type_is_func(t)) {
21324 			bpf_log(log, "attach_btf_id %u is not a function\n",
21325 				btf_id);
21326 			return -EINVAL;
21327 		}
21328 		if (prog_extension &&
21329 		    btf_check_type_match(log, prog, btf, t))
21330 			return -EINVAL;
21331 		t = btf_type_by_id(btf, t->type);
21332 		if (!btf_type_is_func_proto(t))
21333 			return -EINVAL;
21334 
21335 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
21336 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
21337 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
21338 			return -EINVAL;
21339 
21340 		if (tgt_prog && conservative)
21341 			t = NULL;
21342 
21343 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
21344 		if (ret < 0)
21345 			return ret;
21346 
21347 		if (tgt_prog) {
21348 			if (subprog == 0)
21349 				addr = (long) tgt_prog->bpf_func;
21350 			else
21351 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
21352 		} else {
21353 			if (btf_is_module(btf)) {
21354 				mod = btf_try_get_module(btf);
21355 				if (mod)
21356 					addr = find_kallsyms_symbol_value(mod, tname);
21357 				else
21358 					addr = 0;
21359 			} else {
21360 				addr = kallsyms_lookup_name(tname);
21361 			}
21362 			if (!addr) {
21363 				module_put(mod);
21364 				bpf_log(log,
21365 					"The address of function %s cannot be found\n",
21366 					tname);
21367 				return -ENOENT;
21368 			}
21369 		}
21370 
21371 		if (prog->sleepable) {
21372 			ret = -EINVAL;
21373 			switch (prog->type) {
21374 			case BPF_PROG_TYPE_TRACING:
21375 
21376 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
21377 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
21378 				 */
21379 				if (!check_non_sleepable_error_inject(btf_id) &&
21380 				    within_error_injection_list(addr))
21381 					ret = 0;
21382 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
21383 				 * in the fmodret id set with the KF_SLEEPABLE flag.
21384 				 */
21385 				else {
21386 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
21387 										prog);
21388 
21389 					if (flags && (*flags & KF_SLEEPABLE))
21390 						ret = 0;
21391 				}
21392 				break;
21393 			case BPF_PROG_TYPE_LSM:
21394 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
21395 				 * Only some of them are sleepable.
21396 				 */
21397 				if (bpf_lsm_is_sleepable_hook(btf_id))
21398 					ret = 0;
21399 				break;
21400 			default:
21401 				break;
21402 			}
21403 			if (ret) {
21404 				module_put(mod);
21405 				bpf_log(log, "%s is not sleepable\n", tname);
21406 				return ret;
21407 			}
21408 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
21409 			if (tgt_prog) {
21410 				module_put(mod);
21411 				bpf_log(log, "can't modify return codes of BPF programs\n");
21412 				return -EINVAL;
21413 			}
21414 			ret = -EINVAL;
21415 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
21416 			    !check_attach_modify_return(addr, tname))
21417 				ret = 0;
21418 			if (ret) {
21419 				module_put(mod);
21420 				bpf_log(log, "%s() is not modifiable\n", tname);
21421 				return ret;
21422 			}
21423 		}
21424 
21425 		break;
21426 	}
21427 	tgt_info->tgt_addr = addr;
21428 	tgt_info->tgt_name = tname;
21429 	tgt_info->tgt_type = t;
21430 	tgt_info->tgt_mod = mod;
21431 	return 0;
21432 }
21433 
BTF_SET_START(btf_id_deny)21434 BTF_SET_START(btf_id_deny)
21435 BTF_ID_UNUSED
21436 #ifdef CONFIG_SMP
21437 BTF_ID(func, migrate_disable)
21438 BTF_ID(func, migrate_enable)
21439 #endif
21440 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
21441 BTF_ID(func, rcu_read_unlock_strict)
21442 #endif
21443 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
21444 BTF_ID(func, preempt_count_add)
21445 BTF_ID(func, preempt_count_sub)
21446 #endif
21447 #ifdef CONFIG_PREEMPT_RCU
21448 BTF_ID(func, __rcu_read_lock)
21449 BTF_ID(func, __rcu_read_unlock)
21450 #endif
21451 BTF_SET_END(btf_id_deny)
21452 
21453 static bool can_be_sleepable(struct bpf_prog *prog)
21454 {
21455 	if (prog->type == BPF_PROG_TYPE_TRACING) {
21456 		switch (prog->expected_attach_type) {
21457 		case BPF_TRACE_FENTRY:
21458 		case BPF_TRACE_FEXIT:
21459 		case BPF_MODIFY_RETURN:
21460 		case BPF_TRACE_ITER:
21461 			return true;
21462 		default:
21463 			return false;
21464 		}
21465 	}
21466 	return prog->type == BPF_PROG_TYPE_LSM ||
21467 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
21468 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
21469 }
21470 
check_attach_btf_id(struct bpf_verifier_env * env)21471 static int check_attach_btf_id(struct bpf_verifier_env *env)
21472 {
21473 	struct bpf_prog *prog = env->prog;
21474 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
21475 	struct bpf_attach_target_info tgt_info = {};
21476 	u32 btf_id = prog->aux->attach_btf_id;
21477 	struct bpf_trampoline *tr;
21478 	int ret;
21479 	u64 key;
21480 
21481 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
21482 		if (prog->sleepable)
21483 			/* attach_btf_id checked to be zero already */
21484 			return 0;
21485 		verbose(env, "Syscall programs can only be sleepable\n");
21486 		return -EINVAL;
21487 	}
21488 
21489 	if (prog->sleepable && !can_be_sleepable(prog)) {
21490 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
21491 		return -EINVAL;
21492 	}
21493 
21494 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
21495 		return check_struct_ops_btf_id(env);
21496 
21497 	if (prog->type != BPF_PROG_TYPE_TRACING &&
21498 	    prog->type != BPF_PROG_TYPE_LSM &&
21499 	    prog->type != BPF_PROG_TYPE_EXT)
21500 		return 0;
21501 
21502 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
21503 	if (ret)
21504 		return ret;
21505 
21506 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
21507 		/* to make freplace equivalent to their targets, they need to
21508 		 * inherit env->ops and expected_attach_type for the rest of the
21509 		 * verification
21510 		 */
21511 		env->ops = bpf_verifier_ops[tgt_prog->type];
21512 		prog->expected_attach_type = tgt_prog->expected_attach_type;
21513 	}
21514 
21515 	/* store info about the attachment target that will be used later */
21516 	prog->aux->attach_func_proto = tgt_info.tgt_type;
21517 	prog->aux->attach_func_name = tgt_info.tgt_name;
21518 	prog->aux->mod = tgt_info.tgt_mod;
21519 
21520 	if (tgt_prog) {
21521 		prog->aux->saved_dst_prog_type = tgt_prog->type;
21522 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
21523 	}
21524 
21525 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
21526 		prog->aux->attach_btf_trace = true;
21527 		return 0;
21528 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
21529 		if (!bpf_iter_prog_supported(prog))
21530 			return -EINVAL;
21531 		return 0;
21532 	}
21533 
21534 	if (prog->type == BPF_PROG_TYPE_LSM) {
21535 		ret = bpf_lsm_verify_prog(&env->log, prog);
21536 		if (ret < 0)
21537 			return ret;
21538 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
21539 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
21540 		return -EINVAL;
21541 	}
21542 
21543 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
21544 	tr = bpf_trampoline_get(key, &tgt_info);
21545 	if (!tr)
21546 		return -ENOMEM;
21547 
21548 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
21549 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
21550 
21551 	prog->aux->dst_trampoline = tr;
21552 	return 0;
21553 }
21554 
bpf_get_btf_vmlinux(void)21555 struct btf *bpf_get_btf_vmlinux(void)
21556 {
21557 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
21558 		mutex_lock(&bpf_verifier_lock);
21559 		if (!btf_vmlinux)
21560 			btf_vmlinux = btf_parse_vmlinux();
21561 		mutex_unlock(&bpf_verifier_lock);
21562 	}
21563 	return btf_vmlinux;
21564 }
21565 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)21566 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
21567 {
21568 	u64 start_time = ktime_get_ns();
21569 	struct bpf_verifier_env *env;
21570 	int i, len, ret = -EINVAL, err;
21571 	u32 log_true_size;
21572 	bool is_priv;
21573 
21574 	/* no program is valid */
21575 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
21576 		return -EINVAL;
21577 
21578 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
21579 	 * allocate/free it every time bpf_check() is called
21580 	 */
21581 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
21582 	if (!env)
21583 		return -ENOMEM;
21584 
21585 	env->bt.env = env;
21586 
21587 	len = (*prog)->len;
21588 	env->insn_aux_data =
21589 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
21590 	ret = -ENOMEM;
21591 	if (!env->insn_aux_data)
21592 		goto err_free_env;
21593 	for (i = 0; i < len; i++)
21594 		env->insn_aux_data[i].orig_idx = i;
21595 	env->prog = *prog;
21596 	env->ops = bpf_verifier_ops[env->prog->type];
21597 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
21598 
21599 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
21600 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
21601 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
21602 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
21603 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
21604 
21605 	bpf_get_btf_vmlinux();
21606 
21607 	/* grab the mutex to protect few globals used by verifier */
21608 	if (!is_priv)
21609 		mutex_lock(&bpf_verifier_lock);
21610 
21611 	/* user could have requested verbose verifier output
21612 	 * and supplied buffer to store the verification trace
21613 	 */
21614 	ret = bpf_vlog_init(&env->log, attr->log_level,
21615 			    (char __user *) (unsigned long) attr->log_buf,
21616 			    attr->log_size);
21617 	if (ret)
21618 		goto err_unlock;
21619 
21620 	mark_verifier_state_clean(env);
21621 
21622 	if (IS_ERR(btf_vmlinux)) {
21623 		/* Either gcc or pahole or kernel are broken. */
21624 		verbose(env, "in-kernel BTF is malformed\n");
21625 		ret = PTR_ERR(btf_vmlinux);
21626 		goto skip_full_check;
21627 	}
21628 
21629 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
21630 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
21631 		env->strict_alignment = true;
21632 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
21633 		env->strict_alignment = false;
21634 
21635 	if (is_priv)
21636 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
21637 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
21638 
21639 	env->explored_states = kvcalloc(state_htab_size(env),
21640 				       sizeof(struct bpf_verifier_state_list *),
21641 				       GFP_USER);
21642 	ret = -ENOMEM;
21643 	if (!env->explored_states)
21644 		goto skip_full_check;
21645 
21646 	ret = check_btf_info_early(env, attr, uattr);
21647 	if (ret < 0)
21648 		goto skip_full_check;
21649 
21650 	ret = add_subprog_and_kfunc(env);
21651 	if (ret < 0)
21652 		goto skip_full_check;
21653 
21654 	ret = check_subprogs(env);
21655 	if (ret < 0)
21656 		goto skip_full_check;
21657 
21658 	ret = check_btf_info(env, attr, uattr);
21659 	if (ret < 0)
21660 		goto skip_full_check;
21661 
21662 	ret = check_attach_btf_id(env);
21663 	if (ret)
21664 		goto skip_full_check;
21665 
21666 	ret = resolve_pseudo_ldimm64(env);
21667 	if (ret < 0)
21668 		goto skip_full_check;
21669 
21670 	if (bpf_prog_is_offloaded(env->prog->aux)) {
21671 		ret = bpf_prog_offload_verifier_prep(env->prog);
21672 		if (ret)
21673 			goto skip_full_check;
21674 	}
21675 
21676 	ret = check_cfg(env);
21677 	if (ret < 0)
21678 		goto skip_full_check;
21679 
21680 	ret = do_check_main(env);
21681 	ret = ret ?: do_check_subprogs(env);
21682 
21683 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
21684 		ret = bpf_prog_offload_finalize(env);
21685 
21686 skip_full_check:
21687 	kvfree(env->explored_states);
21688 
21689 	if (ret == 0)
21690 		ret = check_max_stack_depth(env);
21691 
21692 	/* instruction rewrites happen after this point */
21693 	if (ret == 0)
21694 		ret = optimize_bpf_loop(env);
21695 
21696 	if (is_priv) {
21697 		if (ret == 0)
21698 			opt_hard_wire_dead_code_branches(env);
21699 		if (ret == 0)
21700 			ret = opt_remove_dead_code(env);
21701 		if (ret == 0)
21702 			ret = opt_remove_nops(env);
21703 	} else {
21704 		if (ret == 0)
21705 			sanitize_dead_code(env);
21706 	}
21707 
21708 	if (ret == 0)
21709 		/* program is valid, convert *(u32*)(ctx + off) accesses */
21710 		ret = convert_ctx_accesses(env);
21711 
21712 	if (ret == 0)
21713 		ret = do_misc_fixups(env);
21714 
21715 	/* do 32-bit optimization after insn patching has done so those patched
21716 	 * insns could be handled correctly.
21717 	 */
21718 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
21719 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
21720 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
21721 								     : false;
21722 	}
21723 
21724 	if (ret == 0)
21725 		ret = fixup_call_args(env);
21726 
21727 	env->verification_time = ktime_get_ns() - start_time;
21728 	print_verification_stats(env);
21729 	env->prog->aux->verified_insns = env->insn_processed;
21730 
21731 	/* preserve original error even if log finalization is successful */
21732 	err = bpf_vlog_finalize(&env->log, &log_true_size);
21733 	if (err)
21734 		ret = err;
21735 
21736 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
21737 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
21738 				  &log_true_size, sizeof(log_true_size))) {
21739 		ret = -EFAULT;
21740 		goto err_release_maps;
21741 	}
21742 
21743 	if (ret)
21744 		goto err_release_maps;
21745 
21746 	if (env->used_map_cnt) {
21747 		/* if program passed verifier, update used_maps in bpf_prog_info */
21748 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
21749 							  sizeof(env->used_maps[0]),
21750 							  GFP_KERNEL);
21751 
21752 		if (!env->prog->aux->used_maps) {
21753 			ret = -ENOMEM;
21754 			goto err_release_maps;
21755 		}
21756 
21757 		memcpy(env->prog->aux->used_maps, env->used_maps,
21758 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
21759 		env->prog->aux->used_map_cnt = env->used_map_cnt;
21760 	}
21761 	if (env->used_btf_cnt) {
21762 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
21763 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
21764 							  sizeof(env->used_btfs[0]),
21765 							  GFP_KERNEL);
21766 		if (!env->prog->aux->used_btfs) {
21767 			ret = -ENOMEM;
21768 			goto err_release_maps;
21769 		}
21770 
21771 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
21772 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
21773 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
21774 	}
21775 	if (env->used_map_cnt || env->used_btf_cnt) {
21776 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
21777 		 * bpf_ld_imm64 instructions
21778 		 */
21779 		convert_pseudo_ld_imm64(env);
21780 	}
21781 
21782 	adjust_btf_func(env);
21783 
21784 err_release_maps:
21785 	if (!env->prog->aux->used_maps)
21786 		/* if we didn't copy map pointers into bpf_prog_info, release
21787 		 * them now. Otherwise free_used_maps() will release them.
21788 		 */
21789 		release_maps(env);
21790 	if (!env->prog->aux->used_btfs)
21791 		release_btfs(env);
21792 
21793 	/* extension progs temporarily inherit the attach_type of their targets
21794 	   for verification purposes, so set it back to zero before returning
21795 	 */
21796 	if (env->prog->type == BPF_PROG_TYPE_EXT)
21797 		env->prog->expected_attach_type = 0;
21798 
21799 	*prog = env->prog;
21800 
21801 	module_put(env->attach_btf_mod);
21802 err_unlock:
21803 	if (!is_priv)
21804 		mutex_unlock(&bpf_verifier_lock);
21805 	vfree(env->insn_aux_data);
21806 err_free_env:
21807 	kfree(env);
21808 	return ret;
21809 }
21810