xref: /linux/kernel/bpf/verifier.c (revision c30a13538d9f8b2a60b2f6b26abe046dea10aa12)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33 
34 #include "disasm.h"
35 
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 	[_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46 
47 enum bpf_features {
48 	BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 	BPF_FEAT_STREAMS	     = 1,
50 	__MAX_BPF_FEAT,
51 };
52 
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55 
56 /* bpf_check() is a static code analyzer that walks eBPF program
57  * instruction by instruction and updates register/stack state.
58  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59  *
60  * The first pass is depth-first-search to check that the program is a DAG.
61  * It rejects the following programs:
62  * - larger than BPF_MAXINSNS insns
63  * - if loop is present (detected via back-edge)
64  * - unreachable insns exist (shouldn't be a forest. program = one function)
65  * - out of bounds or malformed jumps
66  * The second pass is all possible path descent from the 1st insn.
67  * Since it's analyzing all paths through the program, the length of the
68  * analysis is limited to 64k insn, which may be hit even if total number of
69  * insn is less then 4K, but there are too many branches that change stack/regs.
70  * Number of 'branches to be analyzed' is limited to 1k
71  *
72  * On entry to each instruction, each register has a type, and the instruction
73  * changes the types of the registers depending on instruction semantics.
74  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75  * copied to R1.
76  *
77  * All registers are 64-bit.
78  * R0 - return register
79  * R1-R5 argument passing registers
80  * R6-R9 callee saved registers
81  * R10 - frame pointer read-only
82  *
83  * At the start of BPF program the register R1 contains a pointer to bpf_context
84  * and has type PTR_TO_CTX.
85  *
86  * Verifier tracks arithmetic operations on pointers in case:
87  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89  * 1st insn copies R10 (which has FRAME_PTR) type into R1
90  * and 2nd arithmetic instruction is pattern matched to recognize
91  * that it wants to construct a pointer to some element within stack.
92  * So after 2nd insn, the register R1 has type PTR_TO_STACK
93  * (and -20 constant is saved for further stack bounds checking).
94  * Meaning that this reg is a pointer to stack plus known immediate constant.
95  *
96  * Most of the time the registers have SCALAR_VALUE type, which
97  * means the register has some value, but it's not a valid pointer.
98  * (like pointer plus pointer becomes SCALAR_VALUE type)
99  *
100  * When verifier sees load or store instructions the type of base register
101  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102  * four pointer types recognized by check_mem_access() function.
103  *
104  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105  * and the range of [ptr, ptr + map's value_size) is accessible.
106  *
107  * registers used to pass values to function calls are checked against
108  * function argument constraints.
109  *
110  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111  * It means that the register type passed to this function must be
112  * PTR_TO_STACK and it will be used inside the function as
113  * 'pointer to map element key'
114  *
115  * For example the argument constraints for bpf_map_lookup_elem():
116  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117  *   .arg1_type = ARG_CONST_MAP_PTR,
118  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
119  *
120  * ret_type says that this function returns 'pointer to map elem value or null'
121  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122  * 2nd argument should be a pointer to stack, which will be used inside
123  * the helper function as a pointer to map element key.
124  *
125  * On the kernel side the helper function looks like:
126  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127  * {
128  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129  *    void *key = (void *) (unsigned long) r2;
130  *    void *value;
131  *
132  *    here kernel can access 'key' and 'map' pointers safely, knowing that
133  *    [key, key + map->key_size) bytes are valid and were initialized on
134  *    the stack of eBPF program.
135  * }
136  *
137  * Corresponding eBPF program may look like:
138  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
139  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
141  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142  * here verifier looks at prototype of map_lookup_elem() and sees:
143  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145  *
146  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148  * and were initialized prior to this call.
149  * If it's ok, then verifier allows this BPF_CALL insn and looks at
150  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152  * returns either pointer to map value or NULL.
153  *
154  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155  * insn, the register holding that pointer in the true branch changes state to
156  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157  * branch. See check_cond_jmp_op().
158  *
159  * After the call R0 is set to return type of the function and registers R1-R5
160  * are set to NOT_INIT to indicate that they are no longer readable.
161  *
162  * The following reference types represent a potential reference to a kernel
163  * resource which, after first being allocated, must be checked and freed by
164  * the BPF program:
165  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166  *
167  * When the verifier sees a helper call return a reference type, it allocates a
168  * pointer id for the reference and stores it in the current function state.
169  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171  * passes through a NULL-check conditional. For the branch wherein the state is
172  * changed to CONST_IMM, the verifier releases the reference.
173  *
174  * For each helper function that allocates a reference, such as
175  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176  * bpf_sk_release(). When a reference type passes into the release function,
177  * the verifier also releases the reference. If any unchecked or unreleased
178  * reference remains at the end of the program, the verifier rejects it.
179  */
180 
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 	/* verifier state is 'st'
184 	 * before processing instruction 'insn_idx'
185 	 * and after processing instruction 'prev_insn_idx'
186 	 */
187 	struct bpf_verifier_state st;
188 	int insn_idx;
189 	int prev_insn_idx;
190 	struct bpf_verifier_stack_elem *next;
191 	/* length of verifier log at the time this state was pushed on stack */
192 	u32 log_pos;
193 };
194 
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
196 #define BPF_COMPLEXITY_LIMIT_STATES	64
197 
198 #define BPF_MAP_KEY_POISON	(1ULL << 63)
199 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
200 
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE  512
202 
203 #define BPF_PRIV_STACK_MIN_SIZE		64
204 
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 			      struct bpf_reg_state *reg);
212 static void specialize_kfunc(struct bpf_verifier_env *env,
213 			     u32 func_id, u16 offset, unsigned long *addr);
214 static bool is_trusted_reg(const struct bpf_reg_state *reg);
215 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)216 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
217 {
218 	return aux->map_ptr_state.poison;
219 }
220 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)221 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
222 {
223 	return aux->map_ptr_state.unpriv;
224 }
225 
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,struct bpf_map * map,bool unpriv,bool poison)226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
227 			      struct bpf_map *map,
228 			      bool unpriv, bool poison)
229 {
230 	unpriv |= bpf_map_ptr_unpriv(aux);
231 	aux->map_ptr_state.unpriv = unpriv;
232 	aux->map_ptr_state.poison = poison;
233 	aux->map_ptr_state.map_ptr = map;
234 }
235 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)236 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
237 {
238 	return aux->map_key_state & BPF_MAP_KEY_POISON;
239 }
240 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)241 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
242 {
243 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
244 }
245 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)246 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
247 {
248 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
249 }
250 
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)251 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
252 {
253 	bool poisoned = bpf_map_key_poisoned(aux);
254 
255 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
256 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
257 }
258 
bpf_helper_call(const struct bpf_insn * insn)259 static bool bpf_helper_call(const struct bpf_insn *insn)
260 {
261 	return insn->code == (BPF_JMP | BPF_CALL) &&
262 	       insn->src_reg == 0;
263 }
264 
bpf_pseudo_call(const struct bpf_insn * insn)265 static bool bpf_pseudo_call(const struct bpf_insn *insn)
266 {
267 	return insn->code == (BPF_JMP | BPF_CALL) &&
268 	       insn->src_reg == BPF_PSEUDO_CALL;
269 }
270 
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)271 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
272 {
273 	return insn->code == (BPF_JMP | BPF_CALL) &&
274 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
275 }
276 
277 struct bpf_call_arg_meta {
278 	struct bpf_map *map_ptr;
279 	bool raw_mode;
280 	bool pkt_access;
281 	u8 release_regno;
282 	int regno;
283 	int access_size;
284 	int mem_size;
285 	u64 msize_max_value;
286 	int ref_obj_id;
287 	int dynptr_id;
288 	int map_uid;
289 	int func_id;
290 	struct btf *btf;
291 	u32 btf_id;
292 	struct btf *ret_btf;
293 	u32 ret_btf_id;
294 	u32 subprogno;
295 	struct btf_field *kptr_field;
296 	s64 const_map_key;
297 };
298 
299 struct bpf_kfunc_call_arg_meta {
300 	/* In parameters */
301 	struct btf *btf;
302 	u32 func_id;
303 	u32 kfunc_flags;
304 	const struct btf_type *func_proto;
305 	const char *func_name;
306 	/* Out parameters */
307 	u32 ref_obj_id;
308 	u8 release_regno;
309 	bool r0_rdonly;
310 	u32 ret_btf_id;
311 	u64 r0_size;
312 	u32 subprogno;
313 	struct {
314 		u64 value;
315 		bool found;
316 	} arg_constant;
317 
318 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
319 	 * generally to pass info about user-defined local kptr types to later
320 	 * verification logic
321 	 *   bpf_obj_drop/bpf_percpu_obj_drop
322 	 *     Record the local kptr type to be drop'd
323 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
324 	 *     Record the local kptr type to be refcount_incr'd and use
325 	 *     arg_owning_ref to determine whether refcount_acquire should be
326 	 *     fallible
327 	 */
328 	struct btf *arg_btf;
329 	u32 arg_btf_id;
330 	bool arg_owning_ref;
331 	bool arg_prog;
332 
333 	struct {
334 		struct btf_field *field;
335 	} arg_list_head;
336 	struct {
337 		struct btf_field *field;
338 	} arg_rbtree_root;
339 	struct {
340 		enum bpf_dynptr_type type;
341 		u32 id;
342 		u32 ref_obj_id;
343 	} initialized_dynptr;
344 	struct {
345 		u8 spi;
346 		u8 frameno;
347 	} iter;
348 	struct {
349 		struct bpf_map *ptr;
350 		int uid;
351 	} map;
352 	u64 mem_size;
353 };
354 
355 struct btf *btf_vmlinux;
356 
btf_type_name(const struct btf * btf,u32 id)357 static const char *btf_type_name(const struct btf *btf, u32 id)
358 {
359 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
360 }
361 
362 static DEFINE_MUTEX(bpf_verifier_lock);
363 static DEFINE_MUTEX(bpf_percpu_ma_lock);
364 
verbose(void * private_data,const char * fmt,...)365 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
366 {
367 	struct bpf_verifier_env *env = private_data;
368 	va_list args;
369 
370 	if (!bpf_verifier_log_needed(&env->log))
371 		return;
372 
373 	va_start(args, fmt);
374 	bpf_verifier_vlog(&env->log, fmt, args);
375 	va_end(args);
376 }
377 
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)378 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
379 				   struct bpf_reg_state *reg,
380 				   struct bpf_retval_range range, const char *ctx,
381 				   const char *reg_name)
382 {
383 	bool unknown = true;
384 
385 	verbose(env, "%s the register %s has", ctx, reg_name);
386 	if (reg->smin_value > S64_MIN) {
387 		verbose(env, " smin=%lld", reg->smin_value);
388 		unknown = false;
389 	}
390 	if (reg->smax_value < S64_MAX) {
391 		verbose(env, " smax=%lld", reg->smax_value);
392 		unknown = false;
393 	}
394 	if (unknown)
395 		verbose(env, " unknown scalar value");
396 	verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
397 }
398 
reg_not_null(const struct bpf_reg_state * reg)399 static bool reg_not_null(const struct bpf_reg_state *reg)
400 {
401 	enum bpf_reg_type type;
402 
403 	type = reg->type;
404 	if (type_may_be_null(type))
405 		return false;
406 
407 	type = base_type(type);
408 	return type == PTR_TO_SOCKET ||
409 		type == PTR_TO_TCP_SOCK ||
410 		type == PTR_TO_MAP_VALUE ||
411 		type == PTR_TO_MAP_KEY ||
412 		type == PTR_TO_SOCK_COMMON ||
413 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
414 		(type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
415 		type == CONST_PTR_TO_MAP;
416 }
417 
reg_btf_record(const struct bpf_reg_state * reg)418 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
419 {
420 	struct btf_record *rec = NULL;
421 	struct btf_struct_meta *meta;
422 
423 	if (reg->type == PTR_TO_MAP_VALUE) {
424 		rec = reg->map_ptr->record;
425 	} else if (type_is_ptr_alloc_obj(reg->type)) {
426 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
427 		if (meta)
428 			rec = meta->record;
429 	}
430 	return rec;
431 }
432 
subprog_is_global(const struct bpf_verifier_env * env,int subprog)433 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
434 {
435 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
436 
437 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
438 }
439 
subprog_name(const struct bpf_verifier_env * env,int subprog)440 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
441 {
442 	struct bpf_func_info *info;
443 
444 	if (!env->prog->aux->func_info)
445 		return "";
446 
447 	info = &env->prog->aux->func_info[subprog];
448 	return btf_type_name(env->prog->aux->btf, info->type_id);
449 }
450 
mark_subprog_exc_cb(struct bpf_verifier_env * env,int subprog)451 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
452 {
453 	struct bpf_subprog_info *info = subprog_info(env, subprog);
454 
455 	info->is_cb = true;
456 	info->is_async_cb = true;
457 	info->is_exception_cb = true;
458 }
459 
subprog_is_exc_cb(struct bpf_verifier_env * env,int subprog)460 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
461 {
462 	return subprog_info(env, subprog)->is_exception_cb;
463 }
464 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)465 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
466 {
467 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
468 }
469 
type_is_rdonly_mem(u32 type)470 static bool type_is_rdonly_mem(u32 type)
471 {
472 	return type & MEM_RDONLY;
473 }
474 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)475 static bool is_acquire_function(enum bpf_func_id func_id,
476 				const struct bpf_map *map)
477 {
478 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
479 
480 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
481 	    func_id == BPF_FUNC_sk_lookup_udp ||
482 	    func_id == BPF_FUNC_skc_lookup_tcp ||
483 	    func_id == BPF_FUNC_ringbuf_reserve ||
484 	    func_id == BPF_FUNC_kptr_xchg)
485 		return true;
486 
487 	if (func_id == BPF_FUNC_map_lookup_elem &&
488 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
489 	     map_type == BPF_MAP_TYPE_SOCKHASH))
490 		return true;
491 
492 	return false;
493 }
494 
is_ptr_cast_function(enum bpf_func_id func_id)495 static bool is_ptr_cast_function(enum bpf_func_id func_id)
496 {
497 	return func_id == BPF_FUNC_tcp_sock ||
498 		func_id == BPF_FUNC_sk_fullsock ||
499 		func_id == BPF_FUNC_skc_to_tcp_sock ||
500 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
501 		func_id == BPF_FUNC_skc_to_udp6_sock ||
502 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
503 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
505 }
506 
is_dynptr_ref_function(enum bpf_func_id func_id)507 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
508 {
509 	return func_id == BPF_FUNC_dynptr_data;
510 }
511 
512 static bool is_sync_callback_calling_kfunc(u32 btf_id);
513 static bool is_async_callback_calling_kfunc(u32 btf_id);
514 static bool is_callback_calling_kfunc(u32 btf_id);
515 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
516 
517 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
518 
is_sync_callback_calling_function(enum bpf_func_id func_id)519 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
520 {
521 	return func_id == BPF_FUNC_for_each_map_elem ||
522 	       func_id == BPF_FUNC_find_vma ||
523 	       func_id == BPF_FUNC_loop ||
524 	       func_id == BPF_FUNC_user_ringbuf_drain;
525 }
526 
is_async_callback_calling_function(enum bpf_func_id func_id)527 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
528 {
529 	return func_id == BPF_FUNC_timer_set_callback;
530 }
531 
is_callback_calling_function(enum bpf_func_id func_id)532 static bool is_callback_calling_function(enum bpf_func_id func_id)
533 {
534 	return is_sync_callback_calling_function(func_id) ||
535 	       is_async_callback_calling_function(func_id);
536 }
537 
is_sync_callback_calling_insn(struct bpf_insn * insn)538 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
539 {
540 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
541 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
542 }
543 
is_async_callback_calling_insn(struct bpf_insn * insn)544 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
545 {
546 	return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
547 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
548 }
549 
is_may_goto_insn(struct bpf_insn * insn)550 static bool is_may_goto_insn(struct bpf_insn *insn)
551 {
552 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
553 }
554 
is_may_goto_insn_at(struct bpf_verifier_env * env,int insn_idx)555 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
556 {
557 	return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
558 }
559 
is_storage_get_function(enum bpf_func_id func_id)560 static bool is_storage_get_function(enum bpf_func_id func_id)
561 {
562 	return func_id == BPF_FUNC_sk_storage_get ||
563 	       func_id == BPF_FUNC_inode_storage_get ||
564 	       func_id == BPF_FUNC_task_storage_get ||
565 	       func_id == BPF_FUNC_cgrp_storage_get;
566 }
567 
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569 					const struct bpf_map *map)
570 {
571 	int ref_obj_uses = 0;
572 
573 	if (is_ptr_cast_function(func_id))
574 		ref_obj_uses++;
575 	if (is_acquire_function(func_id, map))
576 		ref_obj_uses++;
577 	if (is_dynptr_ref_function(func_id))
578 		ref_obj_uses++;
579 
580 	return ref_obj_uses > 1;
581 }
582 
is_cmpxchg_insn(const struct bpf_insn * insn)583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585 	return BPF_CLASS(insn->code) == BPF_STX &&
586 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
587 	       insn->imm == BPF_CMPXCHG;
588 }
589 
is_atomic_load_insn(const struct bpf_insn * insn)590 static bool is_atomic_load_insn(const struct bpf_insn *insn)
591 {
592 	return BPF_CLASS(insn->code) == BPF_STX &&
593 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
594 	       insn->imm == BPF_LOAD_ACQ;
595 }
596 
__get_spi(s32 off)597 static int __get_spi(s32 off)
598 {
599 	return (-off - 1) / BPF_REG_SIZE;
600 }
601 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)610 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
611 {
612        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
613 
614        /* We need to check that slots between [spi - nr_slots + 1, spi] are
615 	* within [0, allocated_stack).
616 	*
617 	* Please note that the spi grows downwards. For example, a dynptr
618 	* takes the size of two stack slots; the first slot will be at
619 	* spi and the second slot will be at spi - 1.
620 	*/
621        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
622 }
623 
stack_slot_obj_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * obj_kind,int nr_slots)624 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
625 			          const char *obj_kind, int nr_slots)
626 {
627 	int off, spi;
628 
629 	if (!tnum_is_const(reg->var_off)) {
630 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
631 		return -EINVAL;
632 	}
633 
634 	off = reg->off + reg->var_off.value;
635 	if (off % BPF_REG_SIZE) {
636 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
637 		return -EINVAL;
638 	}
639 
640 	spi = __get_spi(off);
641 	if (spi + 1 < nr_slots) {
642 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
643 		return -EINVAL;
644 	}
645 
646 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
647 		return -ERANGE;
648 	return spi;
649 }
650 
dynptr_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)651 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
652 {
653 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
654 }
655 
iter_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)656 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
657 {
658 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
659 }
660 
irq_flag_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)661 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
662 {
663 	return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
664 }
665 
arg_to_dynptr_type(enum bpf_arg_type arg_type)666 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
667 {
668 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
669 	case DYNPTR_TYPE_LOCAL:
670 		return BPF_DYNPTR_TYPE_LOCAL;
671 	case DYNPTR_TYPE_RINGBUF:
672 		return BPF_DYNPTR_TYPE_RINGBUF;
673 	case DYNPTR_TYPE_SKB:
674 		return BPF_DYNPTR_TYPE_SKB;
675 	case DYNPTR_TYPE_XDP:
676 		return BPF_DYNPTR_TYPE_XDP;
677 	default:
678 		return BPF_DYNPTR_TYPE_INVALID;
679 	}
680 }
681 
get_dynptr_type_flag(enum bpf_dynptr_type type)682 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
683 {
684 	switch (type) {
685 	case BPF_DYNPTR_TYPE_LOCAL:
686 		return DYNPTR_TYPE_LOCAL;
687 	case BPF_DYNPTR_TYPE_RINGBUF:
688 		return DYNPTR_TYPE_RINGBUF;
689 	case BPF_DYNPTR_TYPE_SKB:
690 		return DYNPTR_TYPE_SKB;
691 	case BPF_DYNPTR_TYPE_XDP:
692 		return DYNPTR_TYPE_XDP;
693 	default:
694 		return 0;
695 	}
696 }
697 
dynptr_type_refcounted(enum bpf_dynptr_type type)698 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
699 {
700 	return type == BPF_DYNPTR_TYPE_RINGBUF;
701 }
702 
703 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
704 			      enum bpf_dynptr_type type,
705 			      bool first_slot, int dynptr_id);
706 
707 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
708 				struct bpf_reg_state *reg);
709 
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)710 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
711 				   struct bpf_reg_state *sreg1,
712 				   struct bpf_reg_state *sreg2,
713 				   enum bpf_dynptr_type type)
714 {
715 	int id = ++env->id_gen;
716 
717 	__mark_dynptr_reg(sreg1, type, true, id);
718 	__mark_dynptr_reg(sreg2, type, false, id);
719 }
720 
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)721 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
722 			       struct bpf_reg_state *reg,
723 			       enum bpf_dynptr_type type)
724 {
725 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
726 }
727 
728 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
729 				        struct bpf_func_state *state, int spi);
730 
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)731 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
732 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
733 {
734 	struct bpf_func_state *state = func(env, reg);
735 	enum bpf_dynptr_type type;
736 	int spi, i, err;
737 
738 	spi = dynptr_get_spi(env, reg);
739 	if (spi < 0)
740 		return spi;
741 
742 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
743 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
744 	 * to ensure that for the following example:
745 	 *	[d1][d1][d2][d2]
746 	 * spi    3   2   1   0
747 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
748 	 * case they do belong to same dynptr, second call won't see slot_type
749 	 * as STACK_DYNPTR and will simply skip destruction.
750 	 */
751 	err = destroy_if_dynptr_stack_slot(env, state, spi);
752 	if (err)
753 		return err;
754 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
755 	if (err)
756 		return err;
757 
758 	for (i = 0; i < BPF_REG_SIZE; i++) {
759 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
760 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
761 	}
762 
763 	type = arg_to_dynptr_type(arg_type);
764 	if (type == BPF_DYNPTR_TYPE_INVALID)
765 		return -EINVAL;
766 
767 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
768 			       &state->stack[spi - 1].spilled_ptr, type);
769 
770 	if (dynptr_type_refcounted(type)) {
771 		/* The id is used to track proper releasing */
772 		int id;
773 
774 		if (clone_ref_obj_id)
775 			id = clone_ref_obj_id;
776 		else
777 			id = acquire_reference(env, insn_idx);
778 
779 		if (id < 0)
780 			return id;
781 
782 		state->stack[spi].spilled_ptr.ref_obj_id = id;
783 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
784 	}
785 
786 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
787 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
788 
789 	return 0;
790 }
791 
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)792 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
793 {
794 	int i;
795 
796 	for (i = 0; i < BPF_REG_SIZE; i++) {
797 		state->stack[spi].slot_type[i] = STACK_INVALID;
798 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
799 	}
800 
801 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
802 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
803 
804 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
805 	 *
806 	 * While we don't allow reading STACK_INVALID, it is still possible to
807 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
808 	 * helpers or insns can do partial read of that part without failing,
809 	 * but check_stack_range_initialized, check_stack_read_var_off, and
810 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
811 	 * the slot conservatively. Hence we need to prevent those liveness
812 	 * marking walks.
813 	 *
814 	 * This was not a problem before because STACK_INVALID is only set by
815 	 * default (where the default reg state has its reg->parent as NULL), or
816 	 * in clean_live_states after REG_LIVE_DONE (at which point
817 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
818 	 * verifier state exploration (like we did above). Hence, for our case
819 	 * parentage chain will still be live (i.e. reg->parent may be
820 	 * non-NULL), while earlier reg->parent was NULL, so we need
821 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
822 	 * done later on reads or by mark_dynptr_read as well to unnecessary
823 	 * mark registers in verifier state.
824 	 */
825 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
826 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
827 }
828 
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)829 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
830 {
831 	struct bpf_func_state *state = func(env, reg);
832 	int spi, ref_obj_id, i;
833 
834 	spi = dynptr_get_spi(env, reg);
835 	if (spi < 0)
836 		return spi;
837 
838 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
839 		invalidate_dynptr(env, state, spi);
840 		return 0;
841 	}
842 
843 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
844 
845 	/* If the dynptr has a ref_obj_id, then we need to invalidate
846 	 * two things:
847 	 *
848 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
849 	 * 2) Any slices derived from this dynptr.
850 	 */
851 
852 	/* Invalidate any slices associated with this dynptr */
853 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
854 
855 	/* Invalidate any dynptr clones */
856 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
857 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
858 			continue;
859 
860 		/* it should always be the case that if the ref obj id
861 		 * matches then the stack slot also belongs to a
862 		 * dynptr
863 		 */
864 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
865 			verifier_bug(env, "misconfigured ref_obj_id");
866 			return -EFAULT;
867 		}
868 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
869 			invalidate_dynptr(env, state, i);
870 	}
871 
872 	return 0;
873 }
874 
875 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
876 			       struct bpf_reg_state *reg);
877 
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)878 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
879 {
880 	if (!env->allow_ptr_leaks)
881 		__mark_reg_not_init(env, reg);
882 	else
883 		__mark_reg_unknown(env, reg);
884 }
885 
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)886 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
887 				        struct bpf_func_state *state, int spi)
888 {
889 	struct bpf_func_state *fstate;
890 	struct bpf_reg_state *dreg;
891 	int i, dynptr_id;
892 
893 	/* We always ensure that STACK_DYNPTR is never set partially,
894 	 * hence just checking for slot_type[0] is enough. This is
895 	 * different for STACK_SPILL, where it may be only set for
896 	 * 1 byte, so code has to use is_spilled_reg.
897 	 */
898 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
899 		return 0;
900 
901 	/* Reposition spi to first slot */
902 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
903 		spi = spi + 1;
904 
905 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
906 		verbose(env, "cannot overwrite referenced dynptr\n");
907 		return -EINVAL;
908 	}
909 
910 	mark_stack_slot_scratched(env, spi);
911 	mark_stack_slot_scratched(env, spi - 1);
912 
913 	/* Writing partially to one dynptr stack slot destroys both. */
914 	for (i = 0; i < BPF_REG_SIZE; i++) {
915 		state->stack[spi].slot_type[i] = STACK_INVALID;
916 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
917 	}
918 
919 	dynptr_id = state->stack[spi].spilled_ptr.id;
920 	/* Invalidate any slices associated with this dynptr */
921 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
922 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
923 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
924 			continue;
925 		if (dreg->dynptr_id == dynptr_id)
926 			mark_reg_invalid(env, dreg);
927 	}));
928 
929 	/* Do not release reference state, we are destroying dynptr on stack,
930 	 * not using some helper to release it. Just reset register.
931 	 */
932 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
933 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
934 
935 	/* Same reason as unmark_stack_slots_dynptr above */
936 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
937 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
938 
939 	return 0;
940 }
941 
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)942 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
943 {
944 	int spi;
945 
946 	if (reg->type == CONST_PTR_TO_DYNPTR)
947 		return false;
948 
949 	spi = dynptr_get_spi(env, reg);
950 
951 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
952 	 * error because this just means the stack state hasn't been updated yet.
953 	 * We will do check_mem_access to check and update stack bounds later.
954 	 */
955 	if (spi < 0 && spi != -ERANGE)
956 		return false;
957 
958 	/* We don't need to check if the stack slots are marked by previous
959 	 * dynptr initializations because we allow overwriting existing unreferenced
960 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
961 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
962 	 * touching are completely destructed before we reinitialize them for a new
963 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
964 	 * instead of delaying it until the end where the user will get "Unreleased
965 	 * reference" error.
966 	 */
967 	return true;
968 }
969 
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)970 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
971 {
972 	struct bpf_func_state *state = func(env, reg);
973 	int i, spi;
974 
975 	/* This already represents first slot of initialized bpf_dynptr.
976 	 *
977 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
978 	 * check_func_arg_reg_off's logic, so we don't need to check its
979 	 * offset and alignment.
980 	 */
981 	if (reg->type == CONST_PTR_TO_DYNPTR)
982 		return true;
983 
984 	spi = dynptr_get_spi(env, reg);
985 	if (spi < 0)
986 		return false;
987 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
988 		return false;
989 
990 	for (i = 0; i < BPF_REG_SIZE; i++) {
991 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
992 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
993 			return false;
994 	}
995 
996 	return true;
997 }
998 
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)999 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1000 				    enum bpf_arg_type arg_type)
1001 {
1002 	struct bpf_func_state *state = func(env, reg);
1003 	enum bpf_dynptr_type dynptr_type;
1004 	int spi;
1005 
1006 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1007 	if (arg_type == ARG_PTR_TO_DYNPTR)
1008 		return true;
1009 
1010 	dynptr_type = arg_to_dynptr_type(arg_type);
1011 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1012 		return reg->dynptr.type == dynptr_type;
1013 	} else {
1014 		spi = dynptr_get_spi(env, reg);
1015 		if (spi < 0)
1016 			return false;
1017 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1018 	}
1019 }
1020 
1021 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1022 
1023 static bool in_rcu_cs(struct bpf_verifier_env *env);
1024 
1025 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1026 
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)1027 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1028 				 struct bpf_kfunc_call_arg_meta *meta,
1029 				 struct bpf_reg_state *reg, int insn_idx,
1030 				 struct btf *btf, u32 btf_id, int nr_slots)
1031 {
1032 	struct bpf_func_state *state = func(env, reg);
1033 	int spi, i, j, id;
1034 
1035 	spi = iter_get_spi(env, reg, nr_slots);
1036 	if (spi < 0)
1037 		return spi;
1038 
1039 	id = acquire_reference(env, insn_idx);
1040 	if (id < 0)
1041 		return id;
1042 
1043 	for (i = 0; i < nr_slots; i++) {
1044 		struct bpf_stack_state *slot = &state->stack[spi - i];
1045 		struct bpf_reg_state *st = &slot->spilled_ptr;
1046 
1047 		__mark_reg_known_zero(st);
1048 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1049 		if (is_kfunc_rcu_protected(meta)) {
1050 			if (in_rcu_cs(env))
1051 				st->type |= MEM_RCU;
1052 			else
1053 				st->type |= PTR_UNTRUSTED;
1054 		}
1055 		st->live |= REG_LIVE_WRITTEN;
1056 		st->ref_obj_id = i == 0 ? id : 0;
1057 		st->iter.btf = btf;
1058 		st->iter.btf_id = btf_id;
1059 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1060 		st->iter.depth = 0;
1061 
1062 		for (j = 0; j < BPF_REG_SIZE; j++)
1063 			slot->slot_type[j] = STACK_ITER;
1064 
1065 		mark_stack_slot_scratched(env, spi - i);
1066 	}
1067 
1068 	return 0;
1069 }
1070 
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1071 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1072 				   struct bpf_reg_state *reg, int nr_slots)
1073 {
1074 	struct bpf_func_state *state = func(env, reg);
1075 	int spi, i, j;
1076 
1077 	spi = iter_get_spi(env, reg, nr_slots);
1078 	if (spi < 0)
1079 		return spi;
1080 
1081 	for (i = 0; i < nr_slots; i++) {
1082 		struct bpf_stack_state *slot = &state->stack[spi - i];
1083 		struct bpf_reg_state *st = &slot->spilled_ptr;
1084 
1085 		if (i == 0)
1086 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1087 
1088 		__mark_reg_not_init(env, st);
1089 
1090 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1091 		st->live |= REG_LIVE_WRITTEN;
1092 
1093 		for (j = 0; j < BPF_REG_SIZE; j++)
1094 			slot->slot_type[j] = STACK_INVALID;
1095 
1096 		mark_stack_slot_scratched(env, spi - i);
1097 	}
1098 
1099 	return 0;
1100 }
1101 
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1102 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1103 				     struct bpf_reg_state *reg, int nr_slots)
1104 {
1105 	struct bpf_func_state *state = func(env, reg);
1106 	int spi, i, j;
1107 
1108 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1109 	 * will do check_mem_access to check and update stack bounds later, so
1110 	 * return true for that case.
1111 	 */
1112 	spi = iter_get_spi(env, reg, nr_slots);
1113 	if (spi == -ERANGE)
1114 		return true;
1115 	if (spi < 0)
1116 		return false;
1117 
1118 	for (i = 0; i < nr_slots; i++) {
1119 		struct bpf_stack_state *slot = &state->stack[spi - i];
1120 
1121 		for (j = 0; j < BPF_REG_SIZE; j++)
1122 			if (slot->slot_type[j] == STACK_ITER)
1123 				return false;
1124 	}
1125 
1126 	return true;
1127 }
1128 
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1129 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1130 				   struct btf *btf, u32 btf_id, int nr_slots)
1131 {
1132 	struct bpf_func_state *state = func(env, reg);
1133 	int spi, i, j;
1134 
1135 	spi = iter_get_spi(env, reg, nr_slots);
1136 	if (spi < 0)
1137 		return -EINVAL;
1138 
1139 	for (i = 0; i < nr_slots; i++) {
1140 		struct bpf_stack_state *slot = &state->stack[spi - i];
1141 		struct bpf_reg_state *st = &slot->spilled_ptr;
1142 
1143 		if (st->type & PTR_UNTRUSTED)
1144 			return -EPROTO;
1145 		/* only main (first) slot has ref_obj_id set */
1146 		if (i == 0 && !st->ref_obj_id)
1147 			return -EINVAL;
1148 		if (i != 0 && st->ref_obj_id)
1149 			return -EINVAL;
1150 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1151 			return -EINVAL;
1152 
1153 		for (j = 0; j < BPF_REG_SIZE; j++)
1154 			if (slot->slot_type[j] != STACK_ITER)
1155 				return -EINVAL;
1156 	}
1157 
1158 	return 0;
1159 }
1160 
1161 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1162 static int release_irq_state(struct bpf_verifier_state *state, int id);
1163 
mark_stack_slot_irq_flag(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,struct bpf_reg_state * reg,int insn_idx,int kfunc_class)1164 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1165 				     struct bpf_kfunc_call_arg_meta *meta,
1166 				     struct bpf_reg_state *reg, int insn_idx,
1167 				     int kfunc_class)
1168 {
1169 	struct bpf_func_state *state = func(env, reg);
1170 	struct bpf_stack_state *slot;
1171 	struct bpf_reg_state *st;
1172 	int spi, i, id;
1173 
1174 	spi = irq_flag_get_spi(env, reg);
1175 	if (spi < 0)
1176 		return spi;
1177 
1178 	id = acquire_irq_state(env, insn_idx);
1179 	if (id < 0)
1180 		return id;
1181 
1182 	slot = &state->stack[spi];
1183 	st = &slot->spilled_ptr;
1184 
1185 	__mark_reg_known_zero(st);
1186 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1187 	st->live |= REG_LIVE_WRITTEN;
1188 	st->ref_obj_id = id;
1189 	st->irq.kfunc_class = kfunc_class;
1190 
1191 	for (i = 0; i < BPF_REG_SIZE; i++)
1192 		slot->slot_type[i] = STACK_IRQ_FLAG;
1193 
1194 	mark_stack_slot_scratched(env, spi);
1195 	return 0;
1196 }
1197 
unmark_stack_slot_irq_flag(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int kfunc_class)1198 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1199 				      int kfunc_class)
1200 {
1201 	struct bpf_func_state *state = func(env, reg);
1202 	struct bpf_stack_state *slot;
1203 	struct bpf_reg_state *st;
1204 	int spi, i, err;
1205 
1206 	spi = irq_flag_get_spi(env, reg);
1207 	if (spi < 0)
1208 		return spi;
1209 
1210 	slot = &state->stack[spi];
1211 	st = &slot->spilled_ptr;
1212 
1213 	if (st->irq.kfunc_class != kfunc_class) {
1214 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1215 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1216 
1217 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1218 			flag_kfunc, used_kfunc);
1219 		return -EINVAL;
1220 	}
1221 
1222 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1223 	WARN_ON_ONCE(err && err != -EACCES);
1224 	if (err) {
1225 		int insn_idx = 0;
1226 
1227 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1228 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1229 				insn_idx = env->cur_state->refs[i].insn_idx;
1230 				break;
1231 			}
1232 		}
1233 
1234 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1235 			env->cur_state->active_irq_id, insn_idx);
1236 		return err;
1237 	}
1238 
1239 	__mark_reg_not_init(env, st);
1240 
1241 	/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1242 	st->live |= REG_LIVE_WRITTEN;
1243 
1244 	for (i = 0; i < BPF_REG_SIZE; i++)
1245 		slot->slot_type[i] = STACK_INVALID;
1246 
1247 	mark_stack_slot_scratched(env, spi);
1248 	return 0;
1249 }
1250 
is_irq_flag_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1251 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1252 {
1253 	struct bpf_func_state *state = func(env, reg);
1254 	struct bpf_stack_state *slot;
1255 	int spi, i;
1256 
1257 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1258 	 * will do check_mem_access to check and update stack bounds later, so
1259 	 * return true for that case.
1260 	 */
1261 	spi = irq_flag_get_spi(env, reg);
1262 	if (spi == -ERANGE)
1263 		return true;
1264 	if (spi < 0)
1265 		return false;
1266 
1267 	slot = &state->stack[spi];
1268 
1269 	for (i = 0; i < BPF_REG_SIZE; i++)
1270 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1271 			return false;
1272 	return true;
1273 }
1274 
is_irq_flag_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1275 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1276 {
1277 	struct bpf_func_state *state = func(env, reg);
1278 	struct bpf_stack_state *slot;
1279 	struct bpf_reg_state *st;
1280 	int spi, i;
1281 
1282 	spi = irq_flag_get_spi(env, reg);
1283 	if (spi < 0)
1284 		return -EINVAL;
1285 
1286 	slot = &state->stack[spi];
1287 	st = &slot->spilled_ptr;
1288 
1289 	if (!st->ref_obj_id)
1290 		return -EINVAL;
1291 
1292 	for (i = 0; i < BPF_REG_SIZE; i++)
1293 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1294 			return -EINVAL;
1295 	return 0;
1296 }
1297 
1298 /* Check if given stack slot is "special":
1299  *   - spilled register state (STACK_SPILL);
1300  *   - dynptr state (STACK_DYNPTR);
1301  *   - iter state (STACK_ITER).
1302  *   - irq flag state (STACK_IRQ_FLAG)
1303  */
is_stack_slot_special(const struct bpf_stack_state * stack)1304 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1305 {
1306 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1307 
1308 	switch (type) {
1309 	case STACK_SPILL:
1310 	case STACK_DYNPTR:
1311 	case STACK_ITER:
1312 	case STACK_IRQ_FLAG:
1313 		return true;
1314 	case STACK_INVALID:
1315 	case STACK_MISC:
1316 	case STACK_ZERO:
1317 		return false;
1318 	default:
1319 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1320 		return true;
1321 	}
1322 }
1323 
1324 /* The reg state of a pointer or a bounded scalar was saved when
1325  * it was spilled to the stack.
1326  */
is_spilled_reg(const struct bpf_stack_state * stack)1327 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1328 {
1329 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1330 }
1331 
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1333 {
1334 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1335 	       stack->spilled_ptr.type == SCALAR_VALUE;
1336 }
1337 
is_spilled_scalar_reg64(const struct bpf_stack_state * stack)1338 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[0] == STACK_SPILL &&
1341 	       stack->spilled_ptr.type == SCALAR_VALUE;
1342 }
1343 
1344 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1345  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1346  * more precise STACK_ZERO.
1347  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1348  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1349  * unnecessary as both are considered equivalent when loading data and pruning,
1350  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1351  * slots.
1352  */
mark_stack_slot_misc(struct bpf_verifier_env * env,u8 * stype)1353 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1354 {
1355 	if (*stype == STACK_ZERO)
1356 		return;
1357 	if (*stype == STACK_INVALID)
1358 		return;
1359 	*stype = STACK_MISC;
1360 }
1361 
scrub_spilled_slot(u8 * stype)1362 static void scrub_spilled_slot(u8 *stype)
1363 {
1364 	if (*stype != STACK_INVALID)
1365 		*stype = STACK_MISC;
1366 }
1367 
1368 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1369  * small to hold src. This is different from krealloc since we don't want to preserve
1370  * the contents of dst.
1371  *
1372  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1373  * not be allocated.
1374  */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1375 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1376 {
1377 	size_t alloc_bytes;
1378 	void *orig = dst;
1379 	size_t bytes;
1380 
1381 	if (ZERO_OR_NULL_PTR(src))
1382 		goto out;
1383 
1384 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1385 		return NULL;
1386 
1387 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1388 	dst = krealloc(orig, alloc_bytes, flags);
1389 	if (!dst) {
1390 		kfree(orig);
1391 		return NULL;
1392 	}
1393 
1394 	memcpy(dst, src, bytes);
1395 out:
1396 	return dst ? dst : ZERO_SIZE_PTR;
1397 }
1398 
1399 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1400  * small to hold new_n items. new items are zeroed out if the array grows.
1401  *
1402  * Contrary to krealloc_array, does not free arr if new_n is zero.
1403  */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1404 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1405 {
1406 	size_t alloc_size;
1407 	void *new_arr;
1408 
1409 	if (!new_n || old_n == new_n)
1410 		goto out;
1411 
1412 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1413 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1414 	if (!new_arr) {
1415 		kfree(arr);
1416 		return NULL;
1417 	}
1418 	arr = new_arr;
1419 
1420 	if (new_n > old_n)
1421 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1422 
1423 out:
1424 	return arr ? arr : ZERO_SIZE_PTR;
1425 }
1426 
copy_reference_state(struct bpf_verifier_state * dst,const struct bpf_verifier_state * src)1427 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1428 {
1429 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1430 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1431 	if (!dst->refs)
1432 		return -ENOMEM;
1433 
1434 	dst->acquired_refs = src->acquired_refs;
1435 	dst->active_locks = src->active_locks;
1436 	dst->active_preempt_locks = src->active_preempt_locks;
1437 	dst->active_rcu_lock = src->active_rcu_lock;
1438 	dst->active_irq_id = src->active_irq_id;
1439 	dst->active_lock_id = src->active_lock_id;
1440 	dst->active_lock_ptr = src->active_lock_ptr;
1441 	return 0;
1442 }
1443 
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1444 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1445 {
1446 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1447 
1448 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1449 				GFP_KERNEL_ACCOUNT);
1450 	if (!dst->stack)
1451 		return -ENOMEM;
1452 
1453 	dst->allocated_stack = src->allocated_stack;
1454 	return 0;
1455 }
1456 
resize_reference_state(struct bpf_verifier_state * state,size_t n)1457 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1458 {
1459 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1460 				    sizeof(struct bpf_reference_state));
1461 	if (!state->refs)
1462 		return -ENOMEM;
1463 
1464 	state->acquired_refs = n;
1465 	return 0;
1466 }
1467 
1468 /* Possibly update state->allocated_stack to be at least size bytes. Also
1469  * possibly update the function's high-water mark in its bpf_subprog_info.
1470  */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1471 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1472 {
1473 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1474 
1475 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1476 	size = round_up(size, BPF_REG_SIZE);
1477 	n = size / BPF_REG_SIZE;
1478 
1479 	if (old_n >= n)
1480 		return 0;
1481 
1482 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1483 	if (!state->stack)
1484 		return -ENOMEM;
1485 
1486 	state->allocated_stack = size;
1487 
1488 	/* update known max for given subprogram */
1489 	if (env->subprog_info[state->subprogno].stack_depth < size)
1490 		env->subprog_info[state->subprogno].stack_depth = size;
1491 
1492 	return 0;
1493 }
1494 
1495 /* Acquire a pointer id from the env and update the state->refs to include
1496  * this new pointer reference.
1497  * On success, returns a valid pointer id to associate with the register
1498  * On failure, returns a negative errno.
1499  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1500 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1501 {
1502 	struct bpf_verifier_state *state = env->cur_state;
1503 	int new_ofs = state->acquired_refs;
1504 	int err;
1505 
1506 	err = resize_reference_state(state, state->acquired_refs + 1);
1507 	if (err)
1508 		return NULL;
1509 	state->refs[new_ofs].insn_idx = insn_idx;
1510 
1511 	return &state->refs[new_ofs];
1512 }
1513 
acquire_reference(struct bpf_verifier_env * env,int insn_idx)1514 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1515 {
1516 	struct bpf_reference_state *s;
1517 
1518 	s = acquire_reference_state(env, insn_idx);
1519 	if (!s)
1520 		return -ENOMEM;
1521 	s->type = REF_TYPE_PTR;
1522 	s->id = ++env->id_gen;
1523 	return s->id;
1524 }
1525 
acquire_lock_state(struct bpf_verifier_env * env,int insn_idx,enum ref_state_type type,int id,void * ptr)1526 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1527 			      int id, void *ptr)
1528 {
1529 	struct bpf_verifier_state *state = env->cur_state;
1530 	struct bpf_reference_state *s;
1531 
1532 	s = acquire_reference_state(env, insn_idx);
1533 	if (!s)
1534 		return -ENOMEM;
1535 	s->type = type;
1536 	s->id = id;
1537 	s->ptr = ptr;
1538 
1539 	state->active_locks++;
1540 	state->active_lock_id = id;
1541 	state->active_lock_ptr = ptr;
1542 	return 0;
1543 }
1544 
acquire_irq_state(struct bpf_verifier_env * env,int insn_idx)1545 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1546 {
1547 	struct bpf_verifier_state *state = env->cur_state;
1548 	struct bpf_reference_state *s;
1549 
1550 	s = acquire_reference_state(env, insn_idx);
1551 	if (!s)
1552 		return -ENOMEM;
1553 	s->type = REF_TYPE_IRQ;
1554 	s->id = ++env->id_gen;
1555 
1556 	state->active_irq_id = s->id;
1557 	return s->id;
1558 }
1559 
release_reference_state(struct bpf_verifier_state * state,int idx)1560 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1561 {
1562 	int last_idx;
1563 	size_t rem;
1564 
1565 	/* IRQ state requires the relative ordering of elements remaining the
1566 	 * same, since it relies on the refs array to behave as a stack, so that
1567 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1568 	 * the array instead of swapping the final element into the deleted idx.
1569 	 */
1570 	last_idx = state->acquired_refs - 1;
1571 	rem = state->acquired_refs - idx - 1;
1572 	if (last_idx && idx != last_idx)
1573 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1574 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1575 	state->acquired_refs--;
1576 	return;
1577 }
1578 
find_reference_state(struct bpf_verifier_state * state,int ptr_id)1579 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1580 {
1581 	int i;
1582 
1583 	for (i = 0; i < state->acquired_refs; i++)
1584 		if (state->refs[i].id == ptr_id)
1585 			return true;
1586 
1587 	return false;
1588 }
1589 
release_lock_state(struct bpf_verifier_state * state,int type,int id,void * ptr)1590 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1591 {
1592 	void *prev_ptr = NULL;
1593 	u32 prev_id = 0;
1594 	int i;
1595 
1596 	for (i = 0; i < state->acquired_refs; i++) {
1597 		if (state->refs[i].type == type && state->refs[i].id == id &&
1598 		    state->refs[i].ptr == ptr) {
1599 			release_reference_state(state, i);
1600 			state->active_locks--;
1601 			/* Reassign active lock (id, ptr). */
1602 			state->active_lock_id = prev_id;
1603 			state->active_lock_ptr = prev_ptr;
1604 			return 0;
1605 		}
1606 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1607 			prev_id = state->refs[i].id;
1608 			prev_ptr = state->refs[i].ptr;
1609 		}
1610 	}
1611 	return -EINVAL;
1612 }
1613 
release_irq_state(struct bpf_verifier_state * state,int id)1614 static int release_irq_state(struct bpf_verifier_state *state, int id)
1615 {
1616 	u32 prev_id = 0;
1617 	int i;
1618 
1619 	if (id != state->active_irq_id)
1620 		return -EACCES;
1621 
1622 	for (i = 0; i < state->acquired_refs; i++) {
1623 		if (state->refs[i].type != REF_TYPE_IRQ)
1624 			continue;
1625 		if (state->refs[i].id == id) {
1626 			release_reference_state(state, i);
1627 			state->active_irq_id = prev_id;
1628 			return 0;
1629 		} else {
1630 			prev_id = state->refs[i].id;
1631 		}
1632 	}
1633 	return -EINVAL;
1634 }
1635 
find_lock_state(struct bpf_verifier_state * state,enum ref_state_type type,int id,void * ptr)1636 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1637 						   int id, void *ptr)
1638 {
1639 	int i;
1640 
1641 	for (i = 0; i < state->acquired_refs; i++) {
1642 		struct bpf_reference_state *s = &state->refs[i];
1643 
1644 		if (!(s->type & type))
1645 			continue;
1646 
1647 		if (s->id == id && s->ptr == ptr)
1648 			return s;
1649 	}
1650 	return NULL;
1651 }
1652 
update_peak_states(struct bpf_verifier_env * env)1653 static void update_peak_states(struct bpf_verifier_env *env)
1654 {
1655 	u32 cur_states;
1656 
1657 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1658 	env->peak_states = max(env->peak_states, cur_states);
1659 }
1660 
free_func_state(struct bpf_func_state * state)1661 static void free_func_state(struct bpf_func_state *state)
1662 {
1663 	if (!state)
1664 		return;
1665 	kfree(state->stack);
1666 	kfree(state);
1667 }
1668 
clear_jmp_history(struct bpf_verifier_state * state)1669 static void clear_jmp_history(struct bpf_verifier_state *state)
1670 {
1671 	kfree(state->jmp_history);
1672 	state->jmp_history = NULL;
1673 	state->jmp_history_cnt = 0;
1674 }
1675 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1676 static void free_verifier_state(struct bpf_verifier_state *state,
1677 				bool free_self)
1678 {
1679 	int i;
1680 
1681 	for (i = 0; i <= state->curframe; i++) {
1682 		free_func_state(state->frame[i]);
1683 		state->frame[i] = NULL;
1684 	}
1685 	kfree(state->refs);
1686 	clear_jmp_history(state);
1687 	if (free_self)
1688 		kfree(state);
1689 }
1690 
1691 /* struct bpf_verifier_state->parent refers to states
1692  * that are in either of env->{expored_states,free_list}.
1693  * In both cases the state is contained in struct bpf_verifier_state_list.
1694  */
state_parent_as_list(struct bpf_verifier_state * st)1695 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1696 {
1697 	if (st->parent)
1698 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1699 	return NULL;
1700 }
1701 
1702 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1703 				  struct bpf_verifier_state *st);
1704 
1705 /* A state can be freed if it is no longer referenced:
1706  * - is in the env->free_list;
1707  * - has no children states;
1708  */
maybe_free_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state_list * sl)1709 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1710 				      struct bpf_verifier_state_list *sl)
1711 {
1712 	if (!sl->in_free_list
1713 	    || sl->state.branches != 0
1714 	    || incomplete_read_marks(env, &sl->state))
1715 		return;
1716 	list_del(&sl->node);
1717 	free_verifier_state(&sl->state, false);
1718 	kfree(sl);
1719 	env->free_list_size--;
1720 }
1721 
1722 /* copy verifier state from src to dst growing dst stack space
1723  * when necessary to accommodate larger src stack
1724  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1725 static int copy_func_state(struct bpf_func_state *dst,
1726 			   const struct bpf_func_state *src)
1727 {
1728 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1729 	return copy_stack_state(dst, src);
1730 }
1731 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1732 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1733 			       const struct bpf_verifier_state *src)
1734 {
1735 	struct bpf_func_state *dst;
1736 	int i, err;
1737 
1738 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1739 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1740 					  GFP_KERNEL_ACCOUNT);
1741 	if (!dst_state->jmp_history)
1742 		return -ENOMEM;
1743 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1744 
1745 	/* if dst has more stack frames then src frame, free them, this is also
1746 	 * necessary in case of exceptional exits using bpf_throw.
1747 	 */
1748 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1749 		free_func_state(dst_state->frame[i]);
1750 		dst_state->frame[i] = NULL;
1751 	}
1752 	err = copy_reference_state(dst_state, src);
1753 	if (err)
1754 		return err;
1755 	dst_state->speculative = src->speculative;
1756 	dst_state->in_sleepable = src->in_sleepable;
1757 	dst_state->curframe = src->curframe;
1758 	dst_state->branches = src->branches;
1759 	dst_state->parent = src->parent;
1760 	dst_state->first_insn_idx = src->first_insn_idx;
1761 	dst_state->last_insn_idx = src->last_insn_idx;
1762 	dst_state->dfs_depth = src->dfs_depth;
1763 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1764 	dst_state->may_goto_depth = src->may_goto_depth;
1765 	dst_state->equal_state = src->equal_state;
1766 	for (i = 0; i <= src->curframe; i++) {
1767 		dst = dst_state->frame[i];
1768 		if (!dst) {
1769 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1770 			if (!dst)
1771 				return -ENOMEM;
1772 			dst_state->frame[i] = dst;
1773 		}
1774 		err = copy_func_state(dst, src->frame[i]);
1775 		if (err)
1776 			return err;
1777 	}
1778 	return 0;
1779 }
1780 
state_htab_size(struct bpf_verifier_env * env)1781 static u32 state_htab_size(struct bpf_verifier_env *env)
1782 {
1783 	return env->prog->len;
1784 }
1785 
explored_state(struct bpf_verifier_env * env,int idx)1786 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1787 {
1788 	struct bpf_verifier_state *cur = env->cur_state;
1789 	struct bpf_func_state *state = cur->frame[cur->curframe];
1790 
1791 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1792 }
1793 
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1794 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1795 {
1796 	int fr;
1797 
1798 	if (a->curframe != b->curframe)
1799 		return false;
1800 
1801 	for (fr = a->curframe; fr >= 0; fr--)
1802 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1803 			return false;
1804 
1805 	return true;
1806 }
1807 
1808 /* Return IP for a given frame in a call stack */
frame_insn_idx(struct bpf_verifier_state * st,u32 frame)1809 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1810 {
1811 	return frame == st->curframe
1812 	       ? st->insn_idx
1813 	       : st->frame[frame + 1]->callsite;
1814 }
1815 
1816 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1817  * if such frame exists form a corresponding @callchain as an array of
1818  * call sites leading to this frame and SCC id.
1819  * E.g.:
1820  *
1821  *    void foo()  { A: loop {... SCC#1 ...}; }
1822  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1823  *                  D: loop { E: foo(); ... SCC#3 ... } }
1824  *    void main() { F: bar(); }
1825  *
1826  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1827  * on @st frame call sites being (F,C,A) or (F,E,A).
1828  */
compute_scc_callchain(struct bpf_verifier_env * env,struct bpf_verifier_state * st,struct bpf_scc_callchain * callchain)1829 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1830 				  struct bpf_verifier_state *st,
1831 				  struct bpf_scc_callchain *callchain)
1832 {
1833 	u32 i, scc, insn_idx;
1834 
1835 	memset(callchain, 0, sizeof(*callchain));
1836 	for (i = 0; i <= st->curframe; i++) {
1837 		insn_idx = frame_insn_idx(st, i);
1838 		scc = env->insn_aux_data[insn_idx].scc;
1839 		if (scc) {
1840 			callchain->scc = scc;
1841 			break;
1842 		} else if (i < st->curframe) {
1843 			callchain->callsites[i] = insn_idx;
1844 		} else {
1845 			return false;
1846 		}
1847 	}
1848 	return true;
1849 }
1850 
1851 /* Check if bpf_scc_visit instance for @callchain exists. */
scc_visit_lookup(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1852 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1853 					      struct bpf_scc_callchain *callchain)
1854 {
1855 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1856 	struct bpf_scc_visit *visits = info->visits;
1857 	u32 i;
1858 
1859 	if (!info)
1860 		return NULL;
1861 	for (i = 0; i < info->num_visits; i++)
1862 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1863 			return &visits[i];
1864 	return NULL;
1865 }
1866 
1867 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1868  * Allocated instances are alive for a duration of the do_check_common()
1869  * call and are freed by free_states().
1870  */
scc_visit_alloc(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1871 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1872 					     struct bpf_scc_callchain *callchain)
1873 {
1874 	struct bpf_scc_visit *visit;
1875 	struct bpf_scc_info *info;
1876 	u32 scc, num_visits;
1877 	u64 new_sz;
1878 
1879 	scc = callchain->scc;
1880 	info = env->scc_info[scc];
1881 	num_visits = info ? info->num_visits : 0;
1882 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1883 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1884 	if (!info)
1885 		return NULL;
1886 	env->scc_info[scc] = info;
1887 	info->num_visits = num_visits + 1;
1888 	visit = &info->visits[num_visits];
1889 	memset(visit, 0, sizeof(*visit));
1890 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1891 	return visit;
1892 }
1893 
1894 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
format_callchain(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1895 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1896 {
1897 	char *buf = env->tmp_str_buf;
1898 	int i, delta = 0;
1899 
1900 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1901 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1902 		if (!callchain->callsites[i])
1903 			break;
1904 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1905 				  callchain->callsites[i]);
1906 	}
1907 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1908 	return env->tmp_str_buf;
1909 }
1910 
1911 /* If callchain for @st exists (@st is in some SCC), ensure that
1912  * bpf_scc_visit instance for this callchain exists.
1913  * If instance does not exist or is empty, assign visit->entry_state to @st.
1914  */
maybe_enter_scc(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1915 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1916 {
1917 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1918 	struct bpf_scc_visit *visit;
1919 
1920 	if (!compute_scc_callchain(env, st, callchain))
1921 		return 0;
1922 	visit = scc_visit_lookup(env, callchain);
1923 	visit = visit ?: scc_visit_alloc(env, callchain);
1924 	if (!visit)
1925 		return -ENOMEM;
1926 	if (!visit->entry_state) {
1927 		visit->entry_state = st;
1928 		if (env->log.level & BPF_LOG_LEVEL2)
1929 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1930 	}
1931 	return 0;
1932 }
1933 
1934 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1935 
1936 /* If callchain for @st exists (@st is in some SCC), make it empty:
1937  * - set visit->entry_state to NULL;
1938  * - flush accumulated backedges.
1939  */
maybe_exit_scc(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1940 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1941 {
1942 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1943 	struct bpf_scc_visit *visit;
1944 
1945 	if (!compute_scc_callchain(env, st, callchain))
1946 		return 0;
1947 	visit = scc_visit_lookup(env, callchain);
1948 	if (!visit) {
1949 		verifier_bug(env, "scc exit: no visit info for call chain %s",
1950 			     format_callchain(env, callchain));
1951 		return -EFAULT;
1952 	}
1953 	if (visit->entry_state != st)
1954 		return 0;
1955 	if (env->log.level & BPF_LOG_LEVEL2)
1956 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1957 	visit->entry_state = NULL;
1958 	env->num_backedges -= visit->num_backedges;
1959 	visit->num_backedges = 0;
1960 	update_peak_states(env);
1961 	return propagate_backedges(env, visit);
1962 }
1963 
1964 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1965  * and add @backedge to visit->backedges. @st callchain must exist.
1966  */
add_scc_backedge(struct bpf_verifier_env * env,struct bpf_verifier_state * st,struct bpf_scc_backedge * backedge)1967 static int add_scc_backedge(struct bpf_verifier_env *env,
1968 			    struct bpf_verifier_state *st,
1969 			    struct bpf_scc_backedge *backedge)
1970 {
1971 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1972 	struct bpf_scc_visit *visit;
1973 
1974 	if (!compute_scc_callchain(env, st, callchain)) {
1975 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1976 			     st->insn_idx);
1977 		return -EFAULT;
1978 	}
1979 	visit = scc_visit_lookup(env, callchain);
1980 	if (!visit) {
1981 		verifier_bug(env, "add backedge: no visit info for call chain %s",
1982 			     format_callchain(env, callchain));
1983 		return -EFAULT;
1984 	}
1985 	if (env->log.level & BPF_LOG_LEVEL2)
1986 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
1987 	backedge->next = visit->backedges;
1988 	visit->backedges = backedge;
1989 	visit->num_backedges++;
1990 	env->num_backedges++;
1991 	update_peak_states(env);
1992 	return 0;
1993 }
1994 
1995 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
1996  * if state @st is in some SCC and not all execution paths starting at this
1997  * SCC are fully explored.
1998  */
incomplete_read_marks(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1999 static bool incomplete_read_marks(struct bpf_verifier_env *env,
2000 				  struct bpf_verifier_state *st)
2001 {
2002 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
2003 	struct bpf_scc_visit *visit;
2004 
2005 	if (!compute_scc_callchain(env, st, callchain))
2006 		return false;
2007 	visit = scc_visit_lookup(env, callchain);
2008 	if (!visit)
2009 		return false;
2010 	return !!visit->backedges;
2011 }
2012 
free_backedges(struct bpf_scc_visit * visit)2013 static void free_backedges(struct bpf_scc_visit *visit)
2014 {
2015 	struct bpf_scc_backedge *backedge, *next;
2016 
2017 	for (backedge = visit->backedges; backedge; backedge = next) {
2018 		free_verifier_state(&backedge->state, false);
2019 		next = backedge->next;
2020 		kvfree(backedge);
2021 	}
2022 	visit->backedges = NULL;
2023 }
2024 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2025 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2026 {
2027 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2028 	struct bpf_verifier_state *parent;
2029 	int err;
2030 
2031 	while (st) {
2032 		u32 br = --st->branches;
2033 
2034 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2035 		 * but see comment in push_stack(), hence:
2036 		 */
2037 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2038 		if (br)
2039 			break;
2040 		err = maybe_exit_scc(env, st);
2041 		if (err)
2042 			return err;
2043 		parent = st->parent;
2044 		parent_sl = state_parent_as_list(st);
2045 		if (sl)
2046 			maybe_free_verifier_state(env, sl);
2047 		st = parent;
2048 		sl = parent_sl;
2049 	}
2050 	return 0;
2051 }
2052 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)2053 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2054 		     int *insn_idx, bool pop_log)
2055 {
2056 	struct bpf_verifier_state *cur = env->cur_state;
2057 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2058 	int err;
2059 
2060 	if (env->head == NULL)
2061 		return -ENOENT;
2062 
2063 	if (cur) {
2064 		err = copy_verifier_state(cur, &head->st);
2065 		if (err)
2066 			return err;
2067 	}
2068 	if (pop_log)
2069 		bpf_vlog_reset(&env->log, head->log_pos);
2070 	if (insn_idx)
2071 		*insn_idx = head->insn_idx;
2072 	if (prev_insn_idx)
2073 		*prev_insn_idx = head->prev_insn_idx;
2074 	elem = head->next;
2075 	free_verifier_state(&head->st, false);
2076 	kfree(head);
2077 	env->head = elem;
2078 	env->stack_size--;
2079 	return 0;
2080 }
2081 
error_recoverable_with_nospec(int err)2082 static bool error_recoverable_with_nospec(int err)
2083 {
2084 	/* Should only return true for non-fatal errors that are allowed to
2085 	 * occur during speculative verification. For these we can insert a
2086 	 * nospec and the program might still be accepted. Do not include
2087 	 * something like ENOMEM because it is likely to re-occur for the next
2088 	 * architectural path once it has been recovered-from in all speculative
2089 	 * paths.
2090 	 */
2091 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2092 }
2093 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)2094 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2095 					     int insn_idx, int prev_insn_idx,
2096 					     bool speculative)
2097 {
2098 	struct bpf_verifier_state *cur = env->cur_state;
2099 	struct bpf_verifier_stack_elem *elem;
2100 	int err;
2101 
2102 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2103 	if (!elem)
2104 		return NULL;
2105 
2106 	elem->insn_idx = insn_idx;
2107 	elem->prev_insn_idx = prev_insn_idx;
2108 	elem->next = env->head;
2109 	elem->log_pos = env->log.end_pos;
2110 	env->head = elem;
2111 	env->stack_size++;
2112 	err = copy_verifier_state(&elem->st, cur);
2113 	if (err)
2114 		return NULL;
2115 	elem->st.speculative |= speculative;
2116 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2117 		verbose(env, "The sequence of %d jumps is too complex.\n",
2118 			env->stack_size);
2119 		return NULL;
2120 	}
2121 	if (elem->st.parent) {
2122 		++elem->st.parent->branches;
2123 		/* WARN_ON(branches > 2) technically makes sense here,
2124 		 * but
2125 		 * 1. speculative states will bump 'branches' for non-branch
2126 		 * instructions
2127 		 * 2. is_state_visited() heuristics may decide not to create
2128 		 * a new state for a sequence of branches and all such current
2129 		 * and cloned states will be pointing to a single parent state
2130 		 * which might have large 'branches' count.
2131 		 */
2132 	}
2133 	return &elem->st;
2134 }
2135 
2136 #define CALLER_SAVED_REGS 6
2137 static const int caller_saved[CALLER_SAVED_REGS] = {
2138 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2139 };
2140 
2141 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)2142 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2143 {
2144 	reg->var_off = tnum_const(imm);
2145 	reg->smin_value = (s64)imm;
2146 	reg->smax_value = (s64)imm;
2147 	reg->umin_value = imm;
2148 	reg->umax_value = imm;
2149 
2150 	reg->s32_min_value = (s32)imm;
2151 	reg->s32_max_value = (s32)imm;
2152 	reg->u32_min_value = (u32)imm;
2153 	reg->u32_max_value = (u32)imm;
2154 }
2155 
2156 /* Mark the unknown part of a register (variable offset or scalar value) as
2157  * known to have the value @imm.
2158  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)2159 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2160 {
2161 	/* Clear off and union(map_ptr, range) */
2162 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2163 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2164 	reg->id = 0;
2165 	reg->ref_obj_id = 0;
2166 	___mark_reg_known(reg, imm);
2167 }
2168 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)2169 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2170 {
2171 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2172 	reg->s32_min_value = (s32)imm;
2173 	reg->s32_max_value = (s32)imm;
2174 	reg->u32_min_value = (u32)imm;
2175 	reg->u32_max_value = (u32)imm;
2176 }
2177 
2178 /* Mark the 'variable offset' part of a register as zero.  This should be
2179  * used only on registers holding a pointer type.
2180  */
__mark_reg_known_zero(struct bpf_reg_state * reg)2181 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2182 {
2183 	__mark_reg_known(reg, 0);
2184 }
2185 
__mark_reg_const_zero(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2186 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2187 {
2188 	__mark_reg_known(reg, 0);
2189 	reg->type = SCALAR_VALUE;
2190 	/* all scalars are assumed imprecise initially (unless unprivileged,
2191 	 * in which case everything is forced to be precise)
2192 	 */
2193 	reg->precise = !env->bpf_capable;
2194 }
2195 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2196 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2197 				struct bpf_reg_state *regs, u32 regno)
2198 {
2199 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2200 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2201 		/* Something bad happened, let's kill all regs */
2202 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2203 			__mark_reg_not_init(env, regs + regno);
2204 		return;
2205 	}
2206 	__mark_reg_known_zero(regs + regno);
2207 }
2208 
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)2209 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2210 			      bool first_slot, int dynptr_id)
2211 {
2212 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2213 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2214 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2215 	 */
2216 	__mark_reg_known_zero(reg);
2217 	reg->type = CONST_PTR_TO_DYNPTR;
2218 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2219 	reg->id = dynptr_id;
2220 	reg->dynptr.type = type;
2221 	reg->dynptr.first_slot = first_slot;
2222 }
2223 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)2224 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2225 {
2226 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2227 		const struct bpf_map *map = reg->map_ptr;
2228 
2229 		if (map->inner_map_meta) {
2230 			reg->type = CONST_PTR_TO_MAP;
2231 			reg->map_ptr = map->inner_map_meta;
2232 			/* transfer reg's id which is unique for every map_lookup_elem
2233 			 * as UID of the inner map.
2234 			 */
2235 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2236 				reg->map_uid = reg->id;
2237 			if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE))
2238 				reg->map_uid = reg->id;
2239 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2240 			reg->type = PTR_TO_XDP_SOCK;
2241 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2242 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2243 			reg->type = PTR_TO_SOCKET;
2244 		} else {
2245 			reg->type = PTR_TO_MAP_VALUE;
2246 		}
2247 		return;
2248 	}
2249 
2250 	reg->type &= ~PTR_MAYBE_NULL;
2251 }
2252 
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)2253 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2254 				struct btf_field_graph_root *ds_head)
2255 {
2256 	__mark_reg_known_zero(&regs[regno]);
2257 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2258 	regs[regno].btf = ds_head->btf;
2259 	regs[regno].btf_id = ds_head->value_btf_id;
2260 	regs[regno].off = ds_head->node_offset;
2261 }
2262 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)2263 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2264 {
2265 	return type_is_pkt_pointer(reg->type);
2266 }
2267 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)2268 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2269 {
2270 	return reg_is_pkt_pointer(reg) ||
2271 	       reg->type == PTR_TO_PACKET_END;
2272 }
2273 
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)2274 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2275 {
2276 	return base_type(reg->type) == PTR_TO_MEM &&
2277 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2278 }
2279 
2280 /* 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)2281 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2282 				    enum bpf_reg_type which)
2283 {
2284 	/* The register can already have a range from prior markings.
2285 	 * This is fine as long as it hasn't been advanced from its
2286 	 * origin.
2287 	 */
2288 	return reg->type == which &&
2289 	       reg->id == 0 &&
2290 	       reg->off == 0 &&
2291 	       tnum_equals_const(reg->var_off, 0);
2292 }
2293 
2294 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)2295 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2296 {
2297 	reg->smin_value = S64_MIN;
2298 	reg->smax_value = S64_MAX;
2299 	reg->umin_value = 0;
2300 	reg->umax_value = U64_MAX;
2301 
2302 	reg->s32_min_value = S32_MIN;
2303 	reg->s32_max_value = S32_MAX;
2304 	reg->u32_min_value = 0;
2305 	reg->u32_max_value = U32_MAX;
2306 }
2307 
__mark_reg64_unbounded(struct bpf_reg_state * reg)2308 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2309 {
2310 	reg->smin_value = S64_MIN;
2311 	reg->smax_value = S64_MAX;
2312 	reg->umin_value = 0;
2313 	reg->umax_value = U64_MAX;
2314 }
2315 
__mark_reg32_unbounded(struct bpf_reg_state * reg)2316 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2317 {
2318 	reg->s32_min_value = S32_MIN;
2319 	reg->s32_max_value = S32_MAX;
2320 	reg->u32_min_value = 0;
2321 	reg->u32_max_value = U32_MAX;
2322 }
2323 
__update_reg32_bounds(struct bpf_reg_state * reg)2324 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2325 {
2326 	struct tnum var32_off = tnum_subreg(reg->var_off);
2327 
2328 	/* min signed is max(sign bit) | min(other bits) */
2329 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2330 			var32_off.value | (var32_off.mask & S32_MIN));
2331 	/* max signed is min(sign bit) | max(other bits) */
2332 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2333 			var32_off.value | (var32_off.mask & S32_MAX));
2334 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2335 	reg->u32_max_value = min(reg->u32_max_value,
2336 				 (u32)(var32_off.value | var32_off.mask));
2337 }
2338 
__update_reg64_bounds(struct bpf_reg_state * reg)2339 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2340 {
2341 	/* min signed is max(sign bit) | min(other bits) */
2342 	reg->smin_value = max_t(s64, reg->smin_value,
2343 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2344 	/* max signed is min(sign bit) | max(other bits) */
2345 	reg->smax_value = min_t(s64, reg->smax_value,
2346 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2347 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2348 	reg->umax_value = min(reg->umax_value,
2349 			      reg->var_off.value | reg->var_off.mask);
2350 }
2351 
__update_reg_bounds(struct bpf_reg_state * reg)2352 static void __update_reg_bounds(struct bpf_reg_state *reg)
2353 {
2354 	__update_reg32_bounds(reg);
2355 	__update_reg64_bounds(reg);
2356 }
2357 
2358 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)2359 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2360 {
2361 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2362 	 * bits to improve our u32/s32 boundaries.
2363 	 *
2364 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2365 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2366 	 * [10, 20] range. But this property holds for any 64-bit range as
2367 	 * long as upper 32 bits in that entire range of values stay the same.
2368 	 *
2369 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2370 	 * in decimal) has the same upper 32 bits throughout all the values in
2371 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2372 	 * range.
2373 	 *
2374 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2375 	 * following the rules outlined below about u64/s64 correspondence
2376 	 * (which equally applies to u32 vs s32 correspondence). In general it
2377 	 * depends on actual hexadecimal values of 32-bit range. They can form
2378 	 * only valid u32, or only valid s32 ranges in some cases.
2379 	 *
2380 	 * So we use all these insights to derive bounds for subregisters here.
2381 	 */
2382 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2383 		/* u64 to u32 casting preserves validity of low 32 bits as
2384 		 * a range, if upper 32 bits are the same
2385 		 */
2386 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2387 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2388 
2389 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2390 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2391 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2392 		}
2393 	}
2394 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2395 		/* low 32 bits should form a proper u32 range */
2396 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2397 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2398 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2399 		}
2400 		/* low 32 bits should form a proper s32 range */
2401 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2402 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2403 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2404 		}
2405 	}
2406 	/* Special case where upper bits form a small sequence of two
2407 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2408 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2409 	 * going from negative numbers to positive numbers. E.g., let's say we
2410 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2411 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2412 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2413 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2414 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2415 	 * upper 32 bits. As a random example, s64 range
2416 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2417 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2418 	 */
2419 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2420 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2421 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2422 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2423 	}
2424 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2425 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2426 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2427 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2428 	}
2429 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2430 	 * try to learn from that
2431 	 */
2432 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2433 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2434 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2435 	}
2436 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2437 	 * are the same, so combine.  This works even in the negative case, e.g.
2438 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2439 	 */
2440 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2441 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2442 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2443 	}
2444 }
2445 
__reg64_deduce_bounds(struct bpf_reg_state * reg)2446 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2447 {
2448 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2449 	 * try to learn from that. Let's do a bit of ASCII art to see when
2450 	 * this is happening. Let's take u64 range first:
2451 	 *
2452 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2453 	 * |-------------------------------|--------------------------------|
2454 	 *
2455 	 * Valid u64 range is formed when umin and umax are anywhere in the
2456 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2457 	 * straightforward. Let's see how s64 range maps onto the same range
2458 	 * of values, annotated below the line for comparison:
2459 	 *
2460 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2461 	 * |-------------------------------|--------------------------------|
2462 	 * 0                        S64_MAX S64_MIN                        -1
2463 	 *
2464 	 * So s64 values basically start in the middle and they are logically
2465 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2466 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2467 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2468 	 * more visually as mapped to sign-agnostic range of hex values.
2469 	 *
2470 	 *  u64 start                                               u64 end
2471 	 *  _______________________________________________________________
2472 	 * /                                                               \
2473 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2474 	 * |-------------------------------|--------------------------------|
2475 	 * 0                        S64_MAX S64_MIN                        -1
2476 	 *                                / \
2477 	 * >------------------------------   ------------------------------->
2478 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2479 	 *
2480 	 * What this means is that, in general, we can't always derive
2481 	 * something new about u64 from any random s64 range, and vice versa.
2482 	 *
2483 	 * But we can do that in two particular cases. One is when entire
2484 	 * u64/s64 range is *entirely* contained within left half of the above
2485 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2486 	 *
2487 	 * |-------------------------------|--------------------------------|
2488 	 *     ^                   ^            ^                 ^
2489 	 *     A                   B            C                 D
2490 	 *
2491 	 * [A, B] and [C, D] are contained entirely in their respective halves
2492 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2493 	 * will be non-negative both as u64 and s64 (and in fact it will be
2494 	 * identical ranges no matter the signedness). [C, D] treated as s64
2495 	 * will be a range of negative values, while in u64 it will be
2496 	 * non-negative range of values larger than 0x8000000000000000.
2497 	 *
2498 	 * Now, any other range here can't be represented in both u64 and s64
2499 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2500 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2501 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2502 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2503 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2504 	 * ranges as u64. Currently reg_state can't represent two segments per
2505 	 * numeric domain, so in such situations we can only derive maximal
2506 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2507 	 *
2508 	 * So we use these facts to derive umin/umax from smin/smax and vice
2509 	 * versa only if they stay within the same "half". This is equivalent
2510 	 * to checking sign bit: lower half will have sign bit as zero, upper
2511 	 * half have sign bit 1. Below in code we simplify this by just
2512 	 * casting umin/umax as smin/smax and checking if they form valid
2513 	 * range, and vice versa. Those are equivalent checks.
2514 	 */
2515 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2516 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2517 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2518 	}
2519 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2520 	 * are the same, so combine.  This works even in the negative case, e.g.
2521 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2522 	 */
2523 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2524 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2525 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2526 	} else {
2527 		/* If the s64 range crosses the sign boundary, then it's split
2528 		 * between the beginning and end of the U64 domain. In that
2529 		 * case, we can derive new bounds if the u64 range overlaps
2530 		 * with only one end of the s64 range.
2531 		 *
2532 		 * In the following example, the u64 range overlaps only with
2533 		 * positive portion of the s64 range.
2534 		 *
2535 		 * 0                                                   U64_MAX
2536 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2537 		 * |----------------------------|----------------------------|
2538 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2539 		 * 0                     S64_MAX S64_MIN                    -1
2540 		 *
2541 		 * We can thus derive the following new s64 and u64 ranges.
2542 		 *
2543 		 * 0                                                   U64_MAX
2544 		 * |  [xxxxxx u64 range xxxxx]                               |
2545 		 * |----------------------------|----------------------------|
2546 		 * |  [xxxxxx s64 range xxxxx]                               |
2547 		 * 0                     S64_MAX S64_MIN                    -1
2548 		 *
2549 		 * If they overlap in two places, we can't derive anything
2550 		 * because reg_state can't represent two ranges per numeric
2551 		 * domain.
2552 		 *
2553 		 * 0                                                   U64_MAX
2554 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2555 		 * |----------------------------|----------------------------|
2556 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2557 		 * 0                     S64_MAX S64_MIN                    -1
2558 		 *
2559 		 * The first condition below corresponds to the first diagram
2560 		 * above.
2561 		 */
2562 		if (reg->umax_value < (u64)reg->smin_value) {
2563 			reg->smin_value = (s64)reg->umin_value;
2564 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2565 		} else if ((u64)reg->smax_value < reg->umin_value) {
2566 			/* This second condition considers the case where the u64 range
2567 			 * overlaps with the negative portion of the s64 range:
2568 			 *
2569 			 * 0                                                   U64_MAX
2570 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2571 			 * |----------------------------|----------------------------|
2572 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2573 			 * 0                     S64_MAX S64_MIN                    -1
2574 			 */
2575 			reg->smax_value = (s64)reg->umax_value;
2576 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2577 		}
2578 	}
2579 }
2580 
__reg_deduce_mixed_bounds(struct bpf_reg_state * reg)2581 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2582 {
2583 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2584 	 * values on both sides of 64-bit range in hope to have tighter range.
2585 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2586 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2587 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2588 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2589 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2590 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2591 	 * We just need to make sure that derived bounds we are intersecting
2592 	 * with are well-formed ranges in respective s64 or u64 domain, just
2593 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2594 	 */
2595 	__u64 new_umin, new_umax;
2596 	__s64 new_smin, new_smax;
2597 
2598 	/* u32 -> u64 tightening, it's always well-formed */
2599 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2600 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2601 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2602 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2603 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2604 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2605 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2606 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2607 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2608 
2609 	/* Here we would like to handle a special case after sign extending load,
2610 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2611 	 *
2612 	 * Upper bits are all 1s when register is in a range:
2613 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2614 	 * Upper bits are all 0s when register is in a range:
2615 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2616 	 * Together this forms are continuous range:
2617 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2618 	 *
2619 	 * Now, suppose that register range is in fact tighter:
2620 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2621 	 * Also suppose that it's 32-bit range is positive,
2622 	 * meaning that lower 32-bits of the full 64-bit register
2623 	 * are in the range:
2624 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2625 	 *
2626 	 * If this happens, then any value in a range:
2627 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2628 	 * is smaller than a lowest bound of the range (R):
2629 	 *   0xffff_ffff_8000_0000
2630 	 * which means that upper bits of the full 64-bit register
2631 	 * can't be all 1s, when lower bits are in range (W).
2632 	 *
2633 	 * Note that:
2634 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2635 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2636 	 * These relations are used in the conditions below.
2637 	 */
2638 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2639 		reg->smin_value = reg->s32_min_value;
2640 		reg->smax_value = reg->s32_max_value;
2641 		reg->umin_value = reg->s32_min_value;
2642 		reg->umax_value = reg->s32_max_value;
2643 		reg->var_off = tnum_intersect(reg->var_off,
2644 					      tnum_range(reg->smin_value, reg->smax_value));
2645 	}
2646 }
2647 
__reg_deduce_bounds(struct bpf_reg_state * reg)2648 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2649 {
2650 	__reg32_deduce_bounds(reg);
2651 	__reg64_deduce_bounds(reg);
2652 	__reg_deduce_mixed_bounds(reg);
2653 }
2654 
2655 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2656 static void __reg_bound_offset(struct bpf_reg_state *reg)
2657 {
2658 	struct tnum var64_off = tnum_intersect(reg->var_off,
2659 					       tnum_range(reg->umin_value,
2660 							  reg->umax_value));
2661 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2662 					       tnum_range(reg->u32_min_value,
2663 							  reg->u32_max_value));
2664 
2665 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2666 }
2667 
reg_bounds_sync(struct bpf_reg_state * reg)2668 static void reg_bounds_sync(struct bpf_reg_state *reg)
2669 {
2670 	/* We might have learned new bounds from the var_off. */
2671 	__update_reg_bounds(reg);
2672 	/* We might have learned something about the sign bit. */
2673 	__reg_deduce_bounds(reg);
2674 	__reg_deduce_bounds(reg);
2675 	__reg_deduce_bounds(reg);
2676 	/* We might have learned some bits from the bounds. */
2677 	__reg_bound_offset(reg);
2678 	/* Intersecting with the old var_off might have improved our bounds
2679 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2680 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2681 	 */
2682 	__update_reg_bounds(reg);
2683 }
2684 
reg_bounds_sanity_check(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * ctx)2685 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2686 				   struct bpf_reg_state *reg, const char *ctx)
2687 {
2688 	const char *msg;
2689 
2690 	if (reg->umin_value > reg->umax_value ||
2691 	    reg->smin_value > reg->smax_value ||
2692 	    reg->u32_min_value > reg->u32_max_value ||
2693 	    reg->s32_min_value > reg->s32_max_value) {
2694 		    msg = "range bounds violation";
2695 		    goto out;
2696 	}
2697 
2698 	if (tnum_is_const(reg->var_off)) {
2699 		u64 uval = reg->var_off.value;
2700 		s64 sval = (s64)uval;
2701 
2702 		if (reg->umin_value != uval || reg->umax_value != uval ||
2703 		    reg->smin_value != sval || reg->smax_value != sval) {
2704 			msg = "const tnum out of sync with range bounds";
2705 			goto out;
2706 		}
2707 	}
2708 
2709 	if (tnum_subreg_is_const(reg->var_off)) {
2710 		u32 uval32 = tnum_subreg(reg->var_off).value;
2711 		s32 sval32 = (s32)uval32;
2712 
2713 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2714 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2715 			msg = "const subreg tnum out of sync with range bounds";
2716 			goto out;
2717 		}
2718 	}
2719 
2720 	return 0;
2721 out:
2722 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2723 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2724 		     ctx, msg, reg->umin_value, reg->umax_value,
2725 		     reg->smin_value, reg->smax_value,
2726 		     reg->u32_min_value, reg->u32_max_value,
2727 		     reg->s32_min_value, reg->s32_max_value,
2728 		     reg->var_off.value, reg->var_off.mask);
2729 	if (env->test_reg_invariants)
2730 		return -EFAULT;
2731 	__mark_reg_unbounded(reg);
2732 	return 0;
2733 }
2734 
__reg32_bound_s64(s32 a)2735 static bool __reg32_bound_s64(s32 a)
2736 {
2737 	return a >= 0 && a <= S32_MAX;
2738 }
2739 
__reg_assign_32_into_64(struct bpf_reg_state * reg)2740 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2741 {
2742 	reg->umin_value = reg->u32_min_value;
2743 	reg->umax_value = reg->u32_max_value;
2744 
2745 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2746 	 * be positive otherwise set to worse case bounds and refine later
2747 	 * from tnum.
2748 	 */
2749 	if (__reg32_bound_s64(reg->s32_min_value) &&
2750 	    __reg32_bound_s64(reg->s32_max_value)) {
2751 		reg->smin_value = reg->s32_min_value;
2752 		reg->smax_value = reg->s32_max_value;
2753 	} else {
2754 		reg->smin_value = 0;
2755 		reg->smax_value = U32_MAX;
2756 	}
2757 }
2758 
2759 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown_imprecise(struct bpf_reg_state * reg)2760 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2761 {
2762 	/*
2763 	 * Clear type, off, and union(map_ptr, range) and
2764 	 * padding between 'type' and union
2765 	 */
2766 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2767 	reg->type = SCALAR_VALUE;
2768 	reg->id = 0;
2769 	reg->ref_obj_id = 0;
2770 	reg->var_off = tnum_unknown;
2771 	reg->frameno = 0;
2772 	reg->precise = false;
2773 	__mark_reg_unbounded(reg);
2774 }
2775 
2776 /* Mark a register as having a completely unknown (scalar) value,
2777  * initialize .precise as true when not bpf capable.
2778  */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2779 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2780 			       struct bpf_reg_state *reg)
2781 {
2782 	__mark_reg_unknown_imprecise(reg);
2783 	reg->precise = !env->bpf_capable;
2784 }
2785 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2786 static void mark_reg_unknown(struct bpf_verifier_env *env,
2787 			     struct bpf_reg_state *regs, u32 regno)
2788 {
2789 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2790 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2791 		/* Something bad happened, let's kill all regs except FP */
2792 		for (regno = 0; regno < BPF_REG_FP; regno++)
2793 			__mark_reg_not_init(env, regs + regno);
2794 		return;
2795 	}
2796 	__mark_reg_unknown(env, regs + regno);
2797 }
2798 
__mark_reg_s32_range(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,s32 s32_min,s32 s32_max)2799 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2800 				struct bpf_reg_state *regs,
2801 				u32 regno,
2802 				s32 s32_min,
2803 				s32 s32_max)
2804 {
2805 	struct bpf_reg_state *reg = regs + regno;
2806 
2807 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2808 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2809 
2810 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2811 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2812 
2813 	reg_bounds_sync(reg);
2814 
2815 	return reg_bounds_sanity_check(env, reg, "s32_range");
2816 }
2817 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2818 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2819 				struct bpf_reg_state *reg)
2820 {
2821 	__mark_reg_unknown(env, reg);
2822 	reg->type = NOT_INIT;
2823 }
2824 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2825 static void mark_reg_not_init(struct bpf_verifier_env *env,
2826 			      struct bpf_reg_state *regs, u32 regno)
2827 {
2828 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2829 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2830 		/* Something bad happened, let's kill all regs except FP */
2831 		for (regno = 0; regno < BPF_REG_FP; regno++)
2832 			__mark_reg_not_init(env, regs + regno);
2833 		return;
2834 	}
2835 	__mark_reg_not_init(env, regs + regno);
2836 }
2837 
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)2838 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2839 			   struct bpf_reg_state *regs, u32 regno,
2840 			   enum bpf_reg_type reg_type,
2841 			   struct btf *btf, u32 btf_id,
2842 			   enum bpf_type_flag flag)
2843 {
2844 	switch (reg_type) {
2845 	case SCALAR_VALUE:
2846 		mark_reg_unknown(env, regs, regno);
2847 		return 0;
2848 	case PTR_TO_BTF_ID:
2849 		mark_reg_known_zero(env, regs, regno);
2850 		regs[regno].type = PTR_TO_BTF_ID | flag;
2851 		regs[regno].btf = btf;
2852 		regs[regno].btf_id = btf_id;
2853 		if (type_may_be_null(flag))
2854 			regs[regno].id = ++env->id_gen;
2855 		return 0;
2856 	case PTR_TO_MEM:
2857 		mark_reg_known_zero(env, regs, regno);
2858 		regs[regno].type = PTR_TO_MEM | flag;
2859 		regs[regno].mem_size = 0;
2860 		return 0;
2861 	default:
2862 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2863 		return -EFAULT;
2864 	}
2865 }
2866 
2867 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2868 static void init_reg_state(struct bpf_verifier_env *env,
2869 			   struct bpf_func_state *state)
2870 {
2871 	struct bpf_reg_state *regs = state->regs;
2872 	int i;
2873 
2874 	for (i = 0; i < MAX_BPF_REG; i++) {
2875 		mark_reg_not_init(env, regs, i);
2876 		regs[i].live = REG_LIVE_NONE;
2877 		regs[i].parent = NULL;
2878 		regs[i].subreg_def = DEF_NOT_SUBREG;
2879 	}
2880 
2881 	/* frame pointer */
2882 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2883 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2884 	regs[BPF_REG_FP].frameno = state->frameno;
2885 }
2886 
retval_range(s32 minval,s32 maxval)2887 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2888 {
2889 	return (struct bpf_retval_range){ minval, maxval };
2890 }
2891 
2892 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2893 static void init_func_state(struct bpf_verifier_env *env,
2894 			    struct bpf_func_state *state,
2895 			    int callsite, int frameno, int subprogno)
2896 {
2897 	state->callsite = callsite;
2898 	state->frameno = frameno;
2899 	state->subprogno = subprogno;
2900 	state->callback_ret_range = retval_range(0, 0);
2901 	init_reg_state(env, state);
2902 	mark_verifier_state_scratched(env);
2903 }
2904 
2905 /* 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)2906 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2907 						int insn_idx, int prev_insn_idx,
2908 						int subprog, bool is_sleepable)
2909 {
2910 	struct bpf_verifier_stack_elem *elem;
2911 	struct bpf_func_state *frame;
2912 
2913 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2914 	if (!elem)
2915 		return NULL;
2916 
2917 	elem->insn_idx = insn_idx;
2918 	elem->prev_insn_idx = prev_insn_idx;
2919 	elem->next = env->head;
2920 	elem->log_pos = env->log.end_pos;
2921 	env->head = elem;
2922 	env->stack_size++;
2923 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2924 		verbose(env,
2925 			"The sequence of %d jumps is too complex for async cb.\n",
2926 			env->stack_size);
2927 		return NULL;
2928 	}
2929 	/* Unlike push_stack() do not copy_verifier_state().
2930 	 * The caller state doesn't matter.
2931 	 * This is async callback. It starts in a fresh stack.
2932 	 * Initialize it similar to do_check_common().
2933 	 */
2934 	elem->st.branches = 1;
2935 	elem->st.in_sleepable = is_sleepable;
2936 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2937 	if (!frame)
2938 		return NULL;
2939 	init_func_state(env, frame,
2940 			BPF_MAIN_FUNC /* callsite */,
2941 			0 /* frameno within this callchain */,
2942 			subprog /* subprog number within this prog */);
2943 	elem->st.frame[0] = frame;
2944 	return &elem->st;
2945 }
2946 
2947 
2948 enum reg_arg_type {
2949 	SRC_OP,		/* register is used as source operand */
2950 	DST_OP,		/* register is used as destination operand */
2951 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2952 };
2953 
cmp_subprogs(const void * a,const void * b)2954 static int cmp_subprogs(const void *a, const void *b)
2955 {
2956 	return ((struct bpf_subprog_info *)a)->start -
2957 	       ((struct bpf_subprog_info *)b)->start;
2958 }
2959 
2960 /* Find subprogram that contains instruction at 'off' */
find_containing_subprog(struct bpf_verifier_env * env,int off)2961 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
2962 {
2963 	struct bpf_subprog_info *vals = env->subprog_info;
2964 	int l, r, m;
2965 
2966 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2967 		return NULL;
2968 
2969 	l = 0;
2970 	r = env->subprog_cnt - 1;
2971 	while (l < r) {
2972 		m = l + (r - l + 1) / 2;
2973 		if (vals[m].start <= off)
2974 			l = m;
2975 		else
2976 			r = m - 1;
2977 	}
2978 	return &vals[l];
2979 }
2980 
2981 /* Find subprogram that starts exactly at 'off' */
find_subprog(struct bpf_verifier_env * env,int off)2982 static int find_subprog(struct bpf_verifier_env *env, int off)
2983 {
2984 	struct bpf_subprog_info *p;
2985 
2986 	p = find_containing_subprog(env, off);
2987 	if (!p || p->start != off)
2988 		return -ENOENT;
2989 	return p - env->subprog_info;
2990 }
2991 
add_subprog(struct bpf_verifier_env * env,int off)2992 static int add_subprog(struct bpf_verifier_env *env, int off)
2993 {
2994 	int insn_cnt = env->prog->len;
2995 	int ret;
2996 
2997 	if (off >= insn_cnt || off < 0) {
2998 		verbose(env, "call to invalid destination\n");
2999 		return -EINVAL;
3000 	}
3001 	ret = find_subprog(env, off);
3002 	if (ret >= 0)
3003 		return ret;
3004 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3005 		verbose(env, "too many subprograms\n");
3006 		return -E2BIG;
3007 	}
3008 	/* determine subprog starts. The end is one before the next starts */
3009 	env->subprog_info[env->subprog_cnt++].start = off;
3010 	sort(env->subprog_info, env->subprog_cnt,
3011 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3012 	return env->subprog_cnt - 1;
3013 }
3014 
bpf_find_exception_callback_insn_off(struct bpf_verifier_env * env)3015 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3016 {
3017 	struct bpf_prog_aux *aux = env->prog->aux;
3018 	struct btf *btf = aux->btf;
3019 	const struct btf_type *t;
3020 	u32 main_btf_id, id;
3021 	const char *name;
3022 	int ret, i;
3023 
3024 	/* Non-zero func_info_cnt implies valid btf */
3025 	if (!aux->func_info_cnt)
3026 		return 0;
3027 	main_btf_id = aux->func_info[0].type_id;
3028 
3029 	t = btf_type_by_id(btf, main_btf_id);
3030 	if (!t) {
3031 		verbose(env, "invalid btf id for main subprog in func_info\n");
3032 		return -EINVAL;
3033 	}
3034 
3035 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3036 	if (IS_ERR(name)) {
3037 		ret = PTR_ERR(name);
3038 		/* If there is no tag present, there is no exception callback */
3039 		if (ret == -ENOENT)
3040 			ret = 0;
3041 		else if (ret == -EEXIST)
3042 			verbose(env, "multiple exception callback tags for main subprog\n");
3043 		return ret;
3044 	}
3045 
3046 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3047 	if (ret < 0) {
3048 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3049 		return ret;
3050 	}
3051 	id = ret;
3052 	t = btf_type_by_id(btf, id);
3053 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3054 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3055 		return -EINVAL;
3056 	}
3057 	ret = 0;
3058 	for (i = 0; i < aux->func_info_cnt; i++) {
3059 		if (aux->func_info[i].type_id != id)
3060 			continue;
3061 		ret = aux->func_info[i].insn_off;
3062 		/* Further func_info and subprog checks will also happen
3063 		 * later, so assume this is the right insn_off for now.
3064 		 */
3065 		if (!ret) {
3066 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3067 			ret = -EINVAL;
3068 		}
3069 	}
3070 	if (!ret) {
3071 		verbose(env, "exception callback type id not found in func_info\n");
3072 		ret = -EINVAL;
3073 	}
3074 	return ret;
3075 }
3076 
3077 #define MAX_KFUNC_DESCS 256
3078 #define MAX_KFUNC_BTFS	256
3079 
3080 struct bpf_kfunc_desc {
3081 	struct btf_func_model func_model;
3082 	u32 func_id;
3083 	s32 imm;
3084 	u16 offset;
3085 	unsigned long addr;
3086 };
3087 
3088 struct bpf_kfunc_btf {
3089 	struct btf *btf;
3090 	struct module *module;
3091 	u16 offset;
3092 };
3093 
3094 struct bpf_kfunc_desc_tab {
3095 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3096 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3097 	 * available, therefore at the end of verification do_misc_fixups()
3098 	 * sorts this by imm and offset.
3099 	 */
3100 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3101 	u32 nr_descs;
3102 };
3103 
3104 struct bpf_kfunc_btf_tab {
3105 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3106 	u32 nr_descs;
3107 };
3108 
kfunc_desc_cmp_by_id_off(const void * a,const void * b)3109 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3110 {
3111 	const struct bpf_kfunc_desc *d0 = a;
3112 	const struct bpf_kfunc_desc *d1 = b;
3113 
3114 	/* func_id is not greater than BTF_MAX_TYPE */
3115 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3116 }
3117 
kfunc_btf_cmp_by_off(const void * a,const void * b)3118 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3119 {
3120 	const struct bpf_kfunc_btf *d0 = a;
3121 	const struct bpf_kfunc_btf *d1 = b;
3122 
3123 	return d0->offset - d1->offset;
3124 }
3125 
3126 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)3127 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3128 {
3129 	struct bpf_kfunc_desc desc = {
3130 		.func_id = func_id,
3131 		.offset = offset,
3132 	};
3133 	struct bpf_kfunc_desc_tab *tab;
3134 
3135 	tab = prog->aux->kfunc_tab;
3136 	return bsearch(&desc, tab->descs, tab->nr_descs,
3137 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3138 }
3139 
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)3140 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3141 		       u16 btf_fd_idx, u8 **func_addr)
3142 {
3143 	const struct bpf_kfunc_desc *desc;
3144 
3145 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3146 	if (!desc)
3147 		return -EFAULT;
3148 
3149 	*func_addr = (u8 *)desc->addr;
3150 	return 0;
3151 }
3152 
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)3153 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3154 					 s16 offset)
3155 {
3156 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3157 	struct bpf_kfunc_btf_tab *tab;
3158 	struct bpf_kfunc_btf *b;
3159 	struct module *mod;
3160 	struct btf *btf;
3161 	int btf_fd;
3162 
3163 	tab = env->prog->aux->kfunc_btf_tab;
3164 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3165 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3166 	if (!b) {
3167 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3168 			verbose(env, "too many different module BTFs\n");
3169 			return ERR_PTR(-E2BIG);
3170 		}
3171 
3172 		if (bpfptr_is_null(env->fd_array)) {
3173 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3174 			return ERR_PTR(-EPROTO);
3175 		}
3176 
3177 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3178 					    offset * sizeof(btf_fd),
3179 					    sizeof(btf_fd)))
3180 			return ERR_PTR(-EFAULT);
3181 
3182 		btf = btf_get_by_fd(btf_fd);
3183 		if (IS_ERR(btf)) {
3184 			verbose(env, "invalid module BTF fd specified\n");
3185 			return btf;
3186 		}
3187 
3188 		if (!btf_is_module(btf)) {
3189 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3190 			btf_put(btf);
3191 			return ERR_PTR(-EINVAL);
3192 		}
3193 
3194 		mod = btf_try_get_module(btf);
3195 		if (!mod) {
3196 			btf_put(btf);
3197 			return ERR_PTR(-ENXIO);
3198 		}
3199 
3200 		b = &tab->descs[tab->nr_descs++];
3201 		b->btf = btf;
3202 		b->module = mod;
3203 		b->offset = offset;
3204 
3205 		/* sort() reorders entries by value, so b may no longer point
3206 		 * to the right entry after this
3207 		 */
3208 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3209 		     kfunc_btf_cmp_by_off, NULL);
3210 	} else {
3211 		btf = b->btf;
3212 	}
3213 
3214 	return btf;
3215 }
3216 
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)3217 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3218 {
3219 	if (!tab)
3220 		return;
3221 
3222 	while (tab->nr_descs--) {
3223 		module_put(tab->descs[tab->nr_descs].module);
3224 		btf_put(tab->descs[tab->nr_descs].btf);
3225 	}
3226 	kfree(tab);
3227 }
3228 
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)3229 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3230 {
3231 	if (offset) {
3232 		if (offset < 0) {
3233 			/* In the future, this can be allowed to increase limit
3234 			 * of fd index into fd_array, interpreted as u16.
3235 			 */
3236 			verbose(env, "negative offset disallowed for kernel module function call\n");
3237 			return ERR_PTR(-EINVAL);
3238 		}
3239 
3240 		return __find_kfunc_desc_btf(env, offset);
3241 	}
3242 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3243 }
3244 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)3245 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3246 {
3247 	const struct btf_type *func, *func_proto;
3248 	struct bpf_kfunc_btf_tab *btf_tab;
3249 	struct bpf_kfunc_desc_tab *tab;
3250 	struct bpf_prog_aux *prog_aux;
3251 	struct bpf_kfunc_desc *desc;
3252 	const char *func_name;
3253 	struct btf *desc_btf;
3254 	unsigned long call_imm;
3255 	unsigned long addr;
3256 	int err;
3257 
3258 	prog_aux = env->prog->aux;
3259 	tab = prog_aux->kfunc_tab;
3260 	btf_tab = prog_aux->kfunc_btf_tab;
3261 	if (!tab) {
3262 		if (!btf_vmlinux) {
3263 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3264 			return -ENOTSUPP;
3265 		}
3266 
3267 		if (!env->prog->jit_requested) {
3268 			verbose(env, "JIT is required for calling kernel function\n");
3269 			return -ENOTSUPP;
3270 		}
3271 
3272 		if (!bpf_jit_supports_kfunc_call()) {
3273 			verbose(env, "JIT does not support calling kernel function\n");
3274 			return -ENOTSUPP;
3275 		}
3276 
3277 		if (!env->prog->gpl_compatible) {
3278 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3279 			return -EINVAL;
3280 		}
3281 
3282 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3283 		if (!tab)
3284 			return -ENOMEM;
3285 		prog_aux->kfunc_tab = tab;
3286 	}
3287 
3288 	/* func_id == 0 is always invalid, but instead of returning an error, be
3289 	 * conservative and wait until the code elimination pass before returning
3290 	 * error, so that invalid calls that get pruned out can be in BPF programs
3291 	 * loaded from userspace.  It is also required that offset be untouched
3292 	 * for such calls.
3293 	 */
3294 	if (!func_id && !offset)
3295 		return 0;
3296 
3297 	if (!btf_tab && offset) {
3298 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3299 		if (!btf_tab)
3300 			return -ENOMEM;
3301 		prog_aux->kfunc_btf_tab = btf_tab;
3302 	}
3303 
3304 	desc_btf = find_kfunc_desc_btf(env, offset);
3305 	if (IS_ERR(desc_btf)) {
3306 		verbose(env, "failed to find BTF for kernel function\n");
3307 		return PTR_ERR(desc_btf);
3308 	}
3309 
3310 	if (find_kfunc_desc(env->prog, func_id, offset))
3311 		return 0;
3312 
3313 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3314 		verbose(env, "too many different kernel function calls\n");
3315 		return -E2BIG;
3316 	}
3317 
3318 	func = btf_type_by_id(desc_btf, func_id);
3319 	if (!func || !btf_type_is_func(func)) {
3320 		verbose(env, "kernel btf_id %u is not a function\n",
3321 			func_id);
3322 		return -EINVAL;
3323 	}
3324 	func_proto = btf_type_by_id(desc_btf, func->type);
3325 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3326 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3327 			func_id);
3328 		return -EINVAL;
3329 	}
3330 
3331 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3332 	addr = kallsyms_lookup_name(func_name);
3333 	if (!addr) {
3334 		verbose(env, "cannot find address for kernel function %s\n",
3335 			func_name);
3336 		return -EINVAL;
3337 	}
3338 	specialize_kfunc(env, func_id, offset, &addr);
3339 
3340 	if (bpf_jit_supports_far_kfunc_call()) {
3341 		call_imm = func_id;
3342 	} else {
3343 		call_imm = BPF_CALL_IMM(addr);
3344 		/* Check whether the relative offset overflows desc->imm */
3345 		if ((unsigned long)(s32)call_imm != call_imm) {
3346 			verbose(env, "address of kernel function %s is out of range\n",
3347 				func_name);
3348 			return -EINVAL;
3349 		}
3350 	}
3351 
3352 	if (bpf_dev_bound_kfunc_id(func_id)) {
3353 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3354 		if (err)
3355 			return err;
3356 	}
3357 
3358 	desc = &tab->descs[tab->nr_descs++];
3359 	desc->func_id = func_id;
3360 	desc->imm = call_imm;
3361 	desc->offset = offset;
3362 	desc->addr = addr;
3363 	err = btf_distill_func_proto(&env->log, desc_btf,
3364 				     func_proto, func_name,
3365 				     &desc->func_model);
3366 	if (!err)
3367 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3368 		     kfunc_desc_cmp_by_id_off, NULL);
3369 	return err;
3370 }
3371 
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)3372 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3373 {
3374 	const struct bpf_kfunc_desc *d0 = a;
3375 	const struct bpf_kfunc_desc *d1 = b;
3376 
3377 	if (d0->imm != d1->imm)
3378 		return d0->imm < d1->imm ? -1 : 1;
3379 	if (d0->offset != d1->offset)
3380 		return d0->offset < d1->offset ? -1 : 1;
3381 	return 0;
3382 }
3383 
sort_kfunc_descs_by_imm_off(struct bpf_prog * prog)3384 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3385 {
3386 	struct bpf_kfunc_desc_tab *tab;
3387 
3388 	tab = prog->aux->kfunc_tab;
3389 	if (!tab)
3390 		return;
3391 
3392 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3393 	     kfunc_desc_cmp_by_imm_off, NULL);
3394 }
3395 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)3396 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3397 {
3398 	return !!prog->aux->kfunc_tab;
3399 }
3400 
3401 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)3402 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3403 			 const struct bpf_insn *insn)
3404 {
3405 	const struct bpf_kfunc_desc desc = {
3406 		.imm = insn->imm,
3407 		.offset = insn->off,
3408 	};
3409 	const struct bpf_kfunc_desc *res;
3410 	struct bpf_kfunc_desc_tab *tab;
3411 
3412 	tab = prog->aux->kfunc_tab;
3413 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3414 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3415 
3416 	return res ? &res->func_model : NULL;
3417 }
3418 
add_kfunc_in_insns(struct bpf_verifier_env * env,struct bpf_insn * insn,int cnt)3419 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3420 			      struct bpf_insn *insn, int cnt)
3421 {
3422 	int i, ret;
3423 
3424 	for (i = 0; i < cnt; i++, insn++) {
3425 		if (bpf_pseudo_kfunc_call(insn)) {
3426 			ret = add_kfunc_call(env, insn->imm, insn->off);
3427 			if (ret < 0)
3428 				return ret;
3429 		}
3430 	}
3431 	return 0;
3432 }
3433 
add_subprog_and_kfunc(struct bpf_verifier_env * env)3434 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3435 {
3436 	struct bpf_subprog_info *subprog = env->subprog_info;
3437 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3438 	struct bpf_insn *insn = env->prog->insnsi;
3439 
3440 	/* Add entry function. */
3441 	ret = add_subprog(env, 0);
3442 	if (ret)
3443 		return ret;
3444 
3445 	for (i = 0; i < insn_cnt; i++, insn++) {
3446 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3447 		    !bpf_pseudo_kfunc_call(insn))
3448 			continue;
3449 
3450 		if (!env->bpf_capable) {
3451 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3452 			return -EPERM;
3453 		}
3454 
3455 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3456 			ret = add_subprog(env, i + insn->imm + 1);
3457 		else
3458 			ret = add_kfunc_call(env, insn->imm, insn->off);
3459 
3460 		if (ret < 0)
3461 			return ret;
3462 	}
3463 
3464 	ret = bpf_find_exception_callback_insn_off(env);
3465 	if (ret < 0)
3466 		return ret;
3467 	ex_cb_insn = ret;
3468 
3469 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3470 	 * marked using BTF decl tag to serve as the exception callback.
3471 	 */
3472 	if (ex_cb_insn) {
3473 		ret = add_subprog(env, ex_cb_insn);
3474 		if (ret < 0)
3475 			return ret;
3476 		for (i = 1; i < env->subprog_cnt; i++) {
3477 			if (env->subprog_info[i].start != ex_cb_insn)
3478 				continue;
3479 			env->exception_callback_subprog = i;
3480 			mark_subprog_exc_cb(env, i);
3481 			break;
3482 		}
3483 	}
3484 
3485 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3486 	 * logic. 'subprog_cnt' should not be increased.
3487 	 */
3488 	subprog[env->subprog_cnt].start = insn_cnt;
3489 
3490 	if (env->log.level & BPF_LOG_LEVEL2)
3491 		for (i = 0; i < env->subprog_cnt; i++)
3492 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3493 
3494 	return 0;
3495 }
3496 
jmp_offset(struct bpf_insn * insn)3497 static int jmp_offset(struct bpf_insn *insn)
3498 {
3499 	u8 code = insn->code;
3500 
3501 	if (code == (BPF_JMP32 | BPF_JA))
3502 		return insn->imm;
3503 	return insn->off;
3504 }
3505 
check_subprogs(struct bpf_verifier_env * env)3506 static int check_subprogs(struct bpf_verifier_env *env)
3507 {
3508 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3509 	struct bpf_subprog_info *subprog = env->subprog_info;
3510 	struct bpf_insn *insn = env->prog->insnsi;
3511 	int insn_cnt = env->prog->len;
3512 
3513 	/* now check that all jumps are within the same subprog */
3514 	subprog_start = subprog[cur_subprog].start;
3515 	subprog_end = subprog[cur_subprog + 1].start;
3516 	for (i = 0; i < insn_cnt; i++) {
3517 		u8 code = insn[i].code;
3518 
3519 		if (code == (BPF_JMP | BPF_CALL) &&
3520 		    insn[i].src_reg == 0 &&
3521 		    insn[i].imm == BPF_FUNC_tail_call) {
3522 			subprog[cur_subprog].has_tail_call = true;
3523 			subprog[cur_subprog].tail_call_reachable = true;
3524 		}
3525 		if (BPF_CLASS(code) == BPF_LD &&
3526 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3527 			subprog[cur_subprog].has_ld_abs = true;
3528 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3529 			goto next;
3530 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3531 			goto next;
3532 		off = i + jmp_offset(&insn[i]) + 1;
3533 		if (off < subprog_start || off >= subprog_end) {
3534 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3535 			return -EINVAL;
3536 		}
3537 next:
3538 		if (i == subprog_end - 1) {
3539 			/* to avoid fall-through from one subprog into another
3540 			 * the last insn of the subprog should be either exit
3541 			 * or unconditional jump back or bpf_throw call
3542 			 */
3543 			if (code != (BPF_JMP | BPF_EXIT) &&
3544 			    code != (BPF_JMP32 | BPF_JA) &&
3545 			    code != (BPF_JMP | BPF_JA)) {
3546 				verbose(env, "last insn is not an exit or jmp\n");
3547 				return -EINVAL;
3548 			}
3549 			subprog_start = subprog_end;
3550 			cur_subprog++;
3551 			if (cur_subprog < env->subprog_cnt)
3552 				subprog_end = subprog[cur_subprog + 1].start;
3553 		}
3554 	}
3555 	return 0;
3556 }
3557 
3558 /* Parentage chain of this register (or stack slot) should take care of all
3559  * issues like callee-saved registers, stack slot allocation time, etc.
3560  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)3561 static int mark_reg_read(struct bpf_verifier_env *env,
3562 			 const struct bpf_reg_state *state,
3563 			 struct bpf_reg_state *parent, u8 flag)
3564 {
3565 	bool writes = parent == state->parent; /* Observe write marks */
3566 	int cnt = 0;
3567 
3568 	while (parent) {
3569 		/* if read wasn't screened by an earlier write ... */
3570 		if (writes && state->live & REG_LIVE_WRITTEN)
3571 			break;
3572 		if (verifier_bug_if(parent->live & REG_LIVE_DONE, env,
3573 				    "type %s var_off %lld off %d",
3574 				    reg_type_str(env, parent->type),
3575 				    parent->var_off.value, parent->off))
3576 			return -EFAULT;
3577 		/* The first condition is more likely to be true than the
3578 		 * second, checked it first.
3579 		 */
3580 		if ((parent->live & REG_LIVE_READ) == flag ||
3581 		    parent->live & REG_LIVE_READ64)
3582 			/* The parentage chain never changes and
3583 			 * this parent was already marked as LIVE_READ.
3584 			 * There is no need to keep walking the chain again and
3585 			 * keep re-marking all parents as LIVE_READ.
3586 			 * This case happens when the same register is read
3587 			 * multiple times without writes into it in-between.
3588 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3589 			 * then no need to set the weak REG_LIVE_READ32.
3590 			 */
3591 			break;
3592 		/* ... then we depend on parent's value */
3593 		parent->live |= flag;
3594 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3595 		if (flag == REG_LIVE_READ64)
3596 			parent->live &= ~REG_LIVE_READ32;
3597 		state = parent;
3598 		parent = state->parent;
3599 		writes = true;
3600 		cnt++;
3601 	}
3602 
3603 	if (env->longest_mark_read_walk < cnt)
3604 		env->longest_mark_read_walk = cnt;
3605 	return 0;
3606 }
3607 
mark_stack_slot_obj_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3608 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3609 				    int spi, int nr_slots)
3610 {
3611 	struct bpf_func_state *state = func(env, reg);
3612 	int err, i;
3613 
3614 	for (i = 0; i < nr_slots; i++) {
3615 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3616 
3617 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3618 		if (err)
3619 			return err;
3620 
3621 		mark_stack_slot_scratched(env, spi - i);
3622 	}
3623 	return 0;
3624 }
3625 
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3626 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3627 {
3628 	int spi;
3629 
3630 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3631 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3632 	 * check_kfunc_call.
3633 	 */
3634 	if (reg->type == CONST_PTR_TO_DYNPTR)
3635 		return 0;
3636 	spi = dynptr_get_spi(env, reg);
3637 	if (spi < 0)
3638 		return spi;
3639 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3640 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3641 	 * read.
3642 	 */
3643 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3644 }
3645 
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3646 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3647 			  int spi, int nr_slots)
3648 {
3649 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3650 }
3651 
mark_irq_flag_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3652 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3653 {
3654 	int spi;
3655 
3656 	spi = irq_flag_get_spi(env, reg);
3657 	if (spi < 0)
3658 		return spi;
3659 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3660 }
3661 
3662 /* This function is supposed to be used by the following 32-bit optimization
3663  * code only. It returns TRUE if the source or destination register operates
3664  * on 64-bit, otherwise return FALSE.
3665  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3666 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3667 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3668 {
3669 	u8 code, class, op;
3670 
3671 	code = insn->code;
3672 	class = BPF_CLASS(code);
3673 	op = BPF_OP(code);
3674 	if (class == BPF_JMP) {
3675 		/* BPF_EXIT for "main" will reach here. Return TRUE
3676 		 * conservatively.
3677 		 */
3678 		if (op == BPF_EXIT)
3679 			return true;
3680 		if (op == BPF_CALL) {
3681 			/* BPF to BPF call will reach here because of marking
3682 			 * caller saved clobber with DST_OP_NO_MARK for which we
3683 			 * don't care the register def because they are anyway
3684 			 * marked as NOT_INIT already.
3685 			 */
3686 			if (insn->src_reg == BPF_PSEUDO_CALL)
3687 				return false;
3688 			/* Helper call will reach here because of arg type
3689 			 * check, conservatively return TRUE.
3690 			 */
3691 			if (t == SRC_OP)
3692 				return true;
3693 
3694 			return false;
3695 		}
3696 	}
3697 
3698 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3699 		return false;
3700 
3701 	if (class == BPF_ALU64 || class == BPF_JMP ||
3702 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3703 		return true;
3704 
3705 	if (class == BPF_ALU || class == BPF_JMP32)
3706 		return false;
3707 
3708 	if (class == BPF_LDX) {
3709 		if (t != SRC_OP)
3710 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3711 		/* LDX source must be ptr. */
3712 		return true;
3713 	}
3714 
3715 	if (class == BPF_STX) {
3716 		/* BPF_STX (including atomic variants) has one or more source
3717 		 * operands, one of which is a ptr. Check whether the caller is
3718 		 * asking about it.
3719 		 */
3720 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3721 			return true;
3722 		return BPF_SIZE(code) == BPF_DW;
3723 	}
3724 
3725 	if (class == BPF_LD) {
3726 		u8 mode = BPF_MODE(code);
3727 
3728 		/* LD_IMM64 */
3729 		if (mode == BPF_IMM)
3730 			return true;
3731 
3732 		/* Both LD_IND and LD_ABS return 32-bit data. */
3733 		if (t != SRC_OP)
3734 			return  false;
3735 
3736 		/* Implicit ctx ptr. */
3737 		if (regno == BPF_REG_6)
3738 			return true;
3739 
3740 		/* Explicit source could be any width. */
3741 		return true;
3742 	}
3743 
3744 	if (class == BPF_ST)
3745 		/* The only source register for BPF_ST is a ptr. */
3746 		return true;
3747 
3748 	/* Conservatively return true at default. */
3749 	return true;
3750 }
3751 
3752 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3753 static int insn_def_regno(const struct bpf_insn *insn)
3754 {
3755 	switch (BPF_CLASS(insn->code)) {
3756 	case BPF_JMP:
3757 	case BPF_JMP32:
3758 	case BPF_ST:
3759 		return -1;
3760 	case BPF_STX:
3761 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3762 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3763 			if (insn->imm == BPF_CMPXCHG)
3764 				return BPF_REG_0;
3765 			else if (insn->imm == BPF_LOAD_ACQ)
3766 				return insn->dst_reg;
3767 			else if (insn->imm & BPF_FETCH)
3768 				return insn->src_reg;
3769 		}
3770 		return -1;
3771 	default:
3772 		return insn->dst_reg;
3773 	}
3774 }
3775 
3776 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)3777 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3778 {
3779 	int dst_reg = insn_def_regno(insn);
3780 
3781 	if (dst_reg == -1)
3782 		return false;
3783 
3784 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3785 }
3786 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3787 static void mark_insn_zext(struct bpf_verifier_env *env,
3788 			   struct bpf_reg_state *reg)
3789 {
3790 	s32 def_idx = reg->subreg_def;
3791 
3792 	if (def_idx == DEF_NOT_SUBREG)
3793 		return;
3794 
3795 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3796 	/* The dst will be zero extended, so won't be sub-register anymore. */
3797 	reg->subreg_def = DEF_NOT_SUBREG;
3798 }
3799 
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3800 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3801 			   enum reg_arg_type t)
3802 {
3803 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3804 	struct bpf_reg_state *reg;
3805 	bool rw64;
3806 
3807 	if (regno >= MAX_BPF_REG) {
3808 		verbose(env, "R%d is invalid\n", regno);
3809 		return -EINVAL;
3810 	}
3811 
3812 	mark_reg_scratched(env, regno);
3813 
3814 	reg = &regs[regno];
3815 	rw64 = is_reg64(env, insn, regno, reg, t);
3816 	if (t == SRC_OP) {
3817 		/* check whether register used as source operand can be read */
3818 		if (reg->type == NOT_INIT) {
3819 			verbose(env, "R%d !read_ok\n", regno);
3820 			return -EACCES;
3821 		}
3822 		/* We don't need to worry about FP liveness because it's read-only */
3823 		if (regno == BPF_REG_FP)
3824 			return 0;
3825 
3826 		if (rw64)
3827 			mark_insn_zext(env, reg);
3828 
3829 		return mark_reg_read(env, reg, reg->parent,
3830 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3831 	} else {
3832 		/* check whether register used as dest operand can be written to */
3833 		if (regno == BPF_REG_FP) {
3834 			verbose(env, "frame pointer is read only\n");
3835 			return -EACCES;
3836 		}
3837 		reg->live |= REG_LIVE_WRITTEN;
3838 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3839 		if (t == DST_OP)
3840 			mark_reg_unknown(env, regs, regno);
3841 	}
3842 	return 0;
3843 }
3844 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3845 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3846 			 enum reg_arg_type t)
3847 {
3848 	struct bpf_verifier_state *vstate = env->cur_state;
3849 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3850 
3851 	return __check_reg_arg(env, state->regs, regno, t);
3852 }
3853 
insn_stack_access_flags(int frameno,int spi)3854 static int insn_stack_access_flags(int frameno, int spi)
3855 {
3856 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3857 }
3858 
insn_stack_access_spi(int insn_flags)3859 static int insn_stack_access_spi(int insn_flags)
3860 {
3861 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3862 }
3863 
insn_stack_access_frameno(int insn_flags)3864 static int insn_stack_access_frameno(int insn_flags)
3865 {
3866 	return insn_flags & INSN_F_FRAMENO_MASK;
3867 }
3868 
mark_jmp_point(struct bpf_verifier_env * env,int idx)3869 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3870 {
3871 	env->insn_aux_data[idx].jmp_point = true;
3872 }
3873 
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3874 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3875 {
3876 	return env->insn_aux_data[insn_idx].jmp_point;
3877 }
3878 
3879 #define LR_FRAMENO_BITS	3
3880 #define LR_SPI_BITS	6
3881 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3882 #define LR_SIZE_BITS	4
3883 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3884 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3885 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3886 #define LR_SPI_OFF	LR_FRAMENO_BITS
3887 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3888 #define LINKED_REGS_MAX	6
3889 
3890 struct linked_reg {
3891 	u8 frameno;
3892 	union {
3893 		u8 spi;
3894 		u8 regno;
3895 	};
3896 	bool is_reg;
3897 };
3898 
3899 struct linked_regs {
3900 	int cnt;
3901 	struct linked_reg entries[LINKED_REGS_MAX];
3902 };
3903 
linked_regs_push(struct linked_regs * s)3904 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3905 {
3906 	if (s->cnt < LINKED_REGS_MAX)
3907 		return &s->entries[s->cnt++];
3908 
3909 	return NULL;
3910 }
3911 
3912 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3913  * number of elements currently in stack.
3914  * Pack one history entry for linked registers as 10 bits in the following format:
3915  * - 3-bits frameno
3916  * - 6-bits spi_or_reg
3917  * - 1-bit  is_reg
3918  */
linked_regs_pack(struct linked_regs * s)3919 static u64 linked_regs_pack(struct linked_regs *s)
3920 {
3921 	u64 val = 0;
3922 	int i;
3923 
3924 	for (i = 0; i < s->cnt; ++i) {
3925 		struct linked_reg *e = &s->entries[i];
3926 		u64 tmp = 0;
3927 
3928 		tmp |= e->frameno;
3929 		tmp |= e->spi << LR_SPI_OFF;
3930 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3931 
3932 		val <<= LR_ENTRY_BITS;
3933 		val |= tmp;
3934 	}
3935 	val <<= LR_SIZE_BITS;
3936 	val |= s->cnt;
3937 	return val;
3938 }
3939 
linked_regs_unpack(u64 val,struct linked_regs * s)3940 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3941 {
3942 	int i;
3943 
3944 	s->cnt = val & LR_SIZE_MASK;
3945 	val >>= LR_SIZE_BITS;
3946 
3947 	for (i = 0; i < s->cnt; ++i) {
3948 		struct linked_reg *e = &s->entries[i];
3949 
3950 		e->frameno =  val & LR_FRAMENO_MASK;
3951 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3952 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3953 		val >>= LR_ENTRY_BITS;
3954 	}
3955 }
3956 
3957 /* for any branch, call, exit record the history of jmps in the given state */
push_jmp_history(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_flags,u64 linked_regs)3958 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3959 			    int insn_flags, u64 linked_regs)
3960 {
3961 	u32 cnt = cur->jmp_history_cnt;
3962 	struct bpf_jmp_history_entry *p;
3963 	size_t alloc_size;
3964 
3965 	/* combine instruction flags if we already recorded this instruction */
3966 	if (env->cur_hist_ent) {
3967 		/* atomic instructions push insn_flags twice, for READ and
3968 		 * WRITE sides, but they should agree on stack slot
3969 		 */
3970 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3971 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3972 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3973 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3974 		env->cur_hist_ent->flags |= insn_flags;
3975 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3976 				"insn history: insn_idx %d linked_regs: %#llx",
3977 				env->insn_idx, env->cur_hist_ent->linked_regs);
3978 		env->cur_hist_ent->linked_regs = linked_regs;
3979 		return 0;
3980 	}
3981 
3982 	cnt++;
3983 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3984 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3985 	if (!p)
3986 		return -ENOMEM;
3987 	cur->jmp_history = p;
3988 
3989 	p = &cur->jmp_history[cnt - 1];
3990 	p->idx = env->insn_idx;
3991 	p->prev_idx = env->prev_insn_idx;
3992 	p->flags = insn_flags;
3993 	p->linked_regs = linked_regs;
3994 	cur->jmp_history_cnt = cnt;
3995 	env->cur_hist_ent = p;
3996 
3997 	return 0;
3998 }
3999 
get_jmp_hist_entry(struct bpf_verifier_state * st,u32 hist_end,int insn_idx)4000 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
4001 						        u32 hist_end, int insn_idx)
4002 {
4003 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
4004 		return &st->jmp_history[hist_end - 1];
4005 	return NULL;
4006 }
4007 
4008 /* Backtrack one insn at a time. If idx is not at the top of recorded
4009  * history then previous instruction came from straight line execution.
4010  * Return -ENOENT if we exhausted all instructions within given state.
4011  *
4012  * It's legal to have a bit of a looping with the same starting and ending
4013  * insn index within the same state, e.g.: 3->4->5->3, so just because current
4014  * instruction index is the same as state's first_idx doesn't mean we are
4015  * done. If there is still some jump history left, we should keep going. We
4016  * need to take into account that we might have a jump history between given
4017  * state's parent and itself, due to checkpointing. In this case, we'll have
4018  * history entry recording a jump from last instruction of parent state and
4019  * first instruction of given state.
4020  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)4021 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
4022 			     u32 *history)
4023 {
4024 	u32 cnt = *history;
4025 
4026 	if (i == st->first_insn_idx) {
4027 		if (cnt == 0)
4028 			return -ENOENT;
4029 		if (cnt == 1 && st->jmp_history[0].idx == i)
4030 			return -ENOENT;
4031 	}
4032 
4033 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
4034 		i = st->jmp_history[cnt - 1].prev_idx;
4035 		(*history)--;
4036 	} else {
4037 		i--;
4038 	}
4039 	return i;
4040 }
4041 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)4042 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4043 {
4044 	const struct btf_type *func;
4045 	struct btf *desc_btf;
4046 
4047 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4048 		return NULL;
4049 
4050 	desc_btf = find_kfunc_desc_btf(data, insn->off);
4051 	if (IS_ERR(desc_btf))
4052 		return "<error>";
4053 
4054 	func = btf_type_by_id(desc_btf, insn->imm);
4055 	return btf_name_by_offset(desc_btf, func->name_off);
4056 }
4057 
verbose_insn(struct bpf_verifier_env * env,struct bpf_insn * insn)4058 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4059 {
4060 	const struct bpf_insn_cbs cbs = {
4061 		.cb_call	= disasm_kfunc_name,
4062 		.cb_print	= verbose,
4063 		.private_data	= env,
4064 	};
4065 
4066 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4067 }
4068 
bt_init(struct backtrack_state * bt,u32 frame)4069 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4070 {
4071 	bt->frame = frame;
4072 }
4073 
bt_reset(struct backtrack_state * bt)4074 static inline void bt_reset(struct backtrack_state *bt)
4075 {
4076 	struct bpf_verifier_env *env = bt->env;
4077 
4078 	memset(bt, 0, sizeof(*bt));
4079 	bt->env = env;
4080 }
4081 
bt_empty(struct backtrack_state * bt)4082 static inline u32 bt_empty(struct backtrack_state *bt)
4083 {
4084 	u64 mask = 0;
4085 	int i;
4086 
4087 	for (i = 0; i <= bt->frame; i++)
4088 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4089 
4090 	return mask == 0;
4091 }
4092 
bt_subprog_enter(struct backtrack_state * bt)4093 static inline int bt_subprog_enter(struct backtrack_state *bt)
4094 {
4095 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4096 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4097 		return -EFAULT;
4098 	}
4099 	bt->frame++;
4100 	return 0;
4101 }
4102 
bt_subprog_exit(struct backtrack_state * bt)4103 static inline int bt_subprog_exit(struct backtrack_state *bt)
4104 {
4105 	if (bt->frame == 0) {
4106 		verifier_bug(bt->env, "subprog exit from frame 0");
4107 		return -EFAULT;
4108 	}
4109 	bt->frame--;
4110 	return 0;
4111 }
4112 
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)4113 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4114 {
4115 	bt->reg_masks[frame] |= 1 << reg;
4116 }
4117 
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)4118 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4119 {
4120 	bt->reg_masks[frame] &= ~(1 << reg);
4121 }
4122 
bt_set_reg(struct backtrack_state * bt,u32 reg)4123 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4124 {
4125 	bt_set_frame_reg(bt, bt->frame, reg);
4126 }
4127 
bt_clear_reg(struct backtrack_state * bt,u32 reg)4128 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4129 {
4130 	bt_clear_frame_reg(bt, bt->frame, reg);
4131 }
4132 
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)4133 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4134 {
4135 	bt->stack_masks[frame] |= 1ull << slot;
4136 }
4137 
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)4138 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4139 {
4140 	bt->stack_masks[frame] &= ~(1ull << slot);
4141 }
4142 
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)4143 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4144 {
4145 	return bt->reg_masks[frame];
4146 }
4147 
bt_reg_mask(struct backtrack_state * bt)4148 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4149 {
4150 	return bt->reg_masks[bt->frame];
4151 }
4152 
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)4153 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4154 {
4155 	return bt->stack_masks[frame];
4156 }
4157 
bt_stack_mask(struct backtrack_state * bt)4158 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4159 {
4160 	return bt->stack_masks[bt->frame];
4161 }
4162 
bt_is_reg_set(struct backtrack_state * bt,u32 reg)4163 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4164 {
4165 	return bt->reg_masks[bt->frame] & (1 << reg);
4166 }
4167 
bt_is_frame_reg_set(struct backtrack_state * bt,u32 frame,u32 reg)4168 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4169 {
4170 	return bt->reg_masks[frame] & (1 << reg);
4171 }
4172 
bt_is_frame_slot_set(struct backtrack_state * bt,u32 frame,u32 slot)4173 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4174 {
4175 	return bt->stack_masks[frame] & (1ull << slot);
4176 }
4177 
4178 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)4179 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4180 {
4181 	DECLARE_BITMAP(mask, 64);
4182 	bool first = true;
4183 	int i, n;
4184 
4185 	buf[0] = '\0';
4186 
4187 	bitmap_from_u64(mask, reg_mask);
4188 	for_each_set_bit(i, mask, 32) {
4189 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4190 		first = false;
4191 		buf += n;
4192 		buf_sz -= n;
4193 		if (buf_sz < 0)
4194 			break;
4195 	}
4196 }
4197 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)4198 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4199 {
4200 	DECLARE_BITMAP(mask, 64);
4201 	bool first = true;
4202 	int i, n;
4203 
4204 	buf[0] = '\0';
4205 
4206 	bitmap_from_u64(mask, stack_mask);
4207 	for_each_set_bit(i, mask, 64) {
4208 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4209 		first = false;
4210 		buf += n;
4211 		buf_sz -= n;
4212 		if (buf_sz < 0)
4213 			break;
4214 	}
4215 }
4216 
4217 /* If any register R in hist->linked_regs is marked as precise in bt,
4218  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4219  */
bt_sync_linked_regs(struct backtrack_state * bt,struct bpf_jmp_history_entry * hist)4220 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4221 {
4222 	struct linked_regs linked_regs;
4223 	bool some_precise = false;
4224 	int i;
4225 
4226 	if (!hist || hist->linked_regs == 0)
4227 		return;
4228 
4229 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4230 	for (i = 0; i < linked_regs.cnt; ++i) {
4231 		struct linked_reg *e = &linked_regs.entries[i];
4232 
4233 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4234 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4235 			some_precise = true;
4236 			break;
4237 		}
4238 	}
4239 
4240 	if (!some_precise)
4241 		return;
4242 
4243 	for (i = 0; i < linked_regs.cnt; ++i) {
4244 		struct linked_reg *e = &linked_regs.entries[i];
4245 
4246 		if (e->is_reg)
4247 			bt_set_frame_reg(bt, e->frameno, e->regno);
4248 		else
4249 			bt_set_frame_slot(bt, e->frameno, e->spi);
4250 	}
4251 }
4252 
4253 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
4254 
4255 /* For given verifier state backtrack_insn() is called from the last insn to
4256  * the first insn. Its purpose is to compute a bitmask of registers and
4257  * stack slots that needs precision in the parent verifier state.
4258  *
4259  * @idx is an index of the instruction we are currently processing;
4260  * @subseq_idx is an index of the subsequent instruction that:
4261  *   - *would be* executed next, if jump history is viewed in forward order;
4262  *   - *was* processed previously during backtracking.
4263  */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct bpf_jmp_history_entry * hist,struct backtrack_state * bt)4264 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4265 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4266 {
4267 	struct bpf_insn *insn = env->prog->insnsi + idx;
4268 	u8 class = BPF_CLASS(insn->code);
4269 	u8 opcode = BPF_OP(insn->code);
4270 	u8 mode = BPF_MODE(insn->code);
4271 	u32 dreg = insn->dst_reg;
4272 	u32 sreg = insn->src_reg;
4273 	u32 spi, i, fr;
4274 
4275 	if (insn->code == 0)
4276 		return 0;
4277 	if (env->log.level & BPF_LOG_LEVEL2) {
4278 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4279 		verbose(env, "mark_precise: frame%d: regs=%s ",
4280 			bt->frame, env->tmp_str_buf);
4281 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4282 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4283 		verbose(env, "%d: ", idx);
4284 		verbose_insn(env, insn);
4285 	}
4286 
4287 	/* If there is a history record that some registers gained range at this insn,
4288 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4289 	 * accounts for these registers.
4290 	 */
4291 	bt_sync_linked_regs(bt, hist);
4292 
4293 	if (class == BPF_ALU || class == BPF_ALU64) {
4294 		if (!bt_is_reg_set(bt, dreg))
4295 			return 0;
4296 		if (opcode == BPF_END || opcode == BPF_NEG) {
4297 			/* sreg is reserved and unused
4298 			 * dreg still need precision before this insn
4299 			 */
4300 			return 0;
4301 		} else if (opcode == BPF_MOV) {
4302 			if (BPF_SRC(insn->code) == BPF_X) {
4303 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4304 				 * dreg needs precision after this insn
4305 				 * sreg needs precision before this insn
4306 				 */
4307 				bt_clear_reg(bt, dreg);
4308 				if (sreg != BPF_REG_FP)
4309 					bt_set_reg(bt, sreg);
4310 			} else {
4311 				/* dreg = K
4312 				 * dreg needs precision after this insn.
4313 				 * Corresponding register is already marked
4314 				 * as precise=true in this verifier state.
4315 				 * No further markings in parent are necessary
4316 				 */
4317 				bt_clear_reg(bt, dreg);
4318 			}
4319 		} else {
4320 			if (BPF_SRC(insn->code) == BPF_X) {
4321 				/* dreg += sreg
4322 				 * both dreg and sreg need precision
4323 				 * before this insn
4324 				 */
4325 				if (sreg != BPF_REG_FP)
4326 					bt_set_reg(bt, sreg);
4327 			} /* else dreg += K
4328 			   * dreg still needs precision before this insn
4329 			   */
4330 		}
4331 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4332 		if (!bt_is_reg_set(bt, dreg))
4333 			return 0;
4334 		bt_clear_reg(bt, dreg);
4335 
4336 		/* scalars can only be spilled into stack w/o losing precision.
4337 		 * Load from any other memory can be zero extended.
4338 		 * The desire to keep that precision is already indicated
4339 		 * by 'precise' mark in corresponding register of this state.
4340 		 * No further tracking necessary.
4341 		 */
4342 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4343 			return 0;
4344 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4345 		 * that [fp - off] slot contains scalar that needs to be
4346 		 * tracked with precision
4347 		 */
4348 		spi = insn_stack_access_spi(hist->flags);
4349 		fr = insn_stack_access_frameno(hist->flags);
4350 		bt_set_frame_slot(bt, fr, spi);
4351 	} else if (class == BPF_STX || class == BPF_ST) {
4352 		if (bt_is_reg_set(bt, dreg))
4353 			/* stx & st shouldn't be using _scalar_ dst_reg
4354 			 * to access memory. It means backtracking
4355 			 * encountered a case of pointer subtraction.
4356 			 */
4357 			return -ENOTSUPP;
4358 		/* scalars can only be spilled into stack */
4359 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4360 			return 0;
4361 		spi = insn_stack_access_spi(hist->flags);
4362 		fr = insn_stack_access_frameno(hist->flags);
4363 		if (!bt_is_frame_slot_set(bt, fr, spi))
4364 			return 0;
4365 		bt_clear_frame_slot(bt, fr, spi);
4366 		if (class == BPF_STX)
4367 			bt_set_reg(bt, sreg);
4368 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4369 		if (bpf_pseudo_call(insn)) {
4370 			int subprog_insn_idx, subprog;
4371 
4372 			subprog_insn_idx = idx + insn->imm + 1;
4373 			subprog = find_subprog(env, subprog_insn_idx);
4374 			if (subprog < 0)
4375 				return -EFAULT;
4376 
4377 			if (subprog_is_global(env, subprog)) {
4378 				/* check that jump history doesn't have any
4379 				 * extra instructions from subprog; the next
4380 				 * instruction after call to global subprog
4381 				 * should be literally next instruction in
4382 				 * caller program
4383 				 */
4384 				verifier_bug_if(idx + 1 != subseq_idx, env,
4385 						"extra insn from subprog");
4386 				/* r1-r5 are invalidated after subprog call,
4387 				 * so for global func call it shouldn't be set
4388 				 * anymore
4389 				 */
4390 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4391 					verifier_bug(env, "global subprog unexpected regs %x",
4392 						     bt_reg_mask(bt));
4393 					return -EFAULT;
4394 				}
4395 				/* global subprog always sets R0 */
4396 				bt_clear_reg(bt, BPF_REG_0);
4397 				return 0;
4398 			} else {
4399 				/* static subprog call instruction, which
4400 				 * means that we are exiting current subprog,
4401 				 * so only r1-r5 could be still requested as
4402 				 * precise, r0 and r6-r10 or any stack slot in
4403 				 * the current frame should be zero by now
4404 				 */
4405 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4406 					verifier_bug(env, "static subprog unexpected regs %x",
4407 						     bt_reg_mask(bt));
4408 					return -EFAULT;
4409 				}
4410 				/* we are now tracking register spills correctly,
4411 				 * so any instance of leftover slots is a bug
4412 				 */
4413 				if (bt_stack_mask(bt) != 0) {
4414 					verifier_bug(env,
4415 						     "static subprog leftover stack slots %llx",
4416 						     bt_stack_mask(bt));
4417 					return -EFAULT;
4418 				}
4419 				/* propagate r1-r5 to the caller */
4420 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4421 					if (bt_is_reg_set(bt, i)) {
4422 						bt_clear_reg(bt, i);
4423 						bt_set_frame_reg(bt, bt->frame - 1, i);
4424 					}
4425 				}
4426 				if (bt_subprog_exit(bt))
4427 					return -EFAULT;
4428 				return 0;
4429 			}
4430 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4431 			/* exit from callback subprog to callback-calling helper or
4432 			 * kfunc call. Use idx/subseq_idx check to discern it from
4433 			 * straight line code backtracking.
4434 			 * Unlike the subprog call handling above, we shouldn't
4435 			 * propagate precision of r1-r5 (if any requested), as they are
4436 			 * not actually arguments passed directly to callback subprogs
4437 			 */
4438 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4439 				verifier_bug(env, "callback unexpected regs %x",
4440 					     bt_reg_mask(bt));
4441 				return -EFAULT;
4442 			}
4443 			if (bt_stack_mask(bt) != 0) {
4444 				verifier_bug(env, "callback leftover stack slots %llx",
4445 					     bt_stack_mask(bt));
4446 				return -EFAULT;
4447 			}
4448 			/* clear r1-r5 in callback subprog's mask */
4449 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4450 				bt_clear_reg(bt, i);
4451 			if (bt_subprog_exit(bt))
4452 				return -EFAULT;
4453 			return 0;
4454 		} else if (opcode == BPF_CALL) {
4455 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4456 			 * catch this error later. Make backtracking conservative
4457 			 * with ENOTSUPP.
4458 			 */
4459 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4460 				return -ENOTSUPP;
4461 			/* regular helper call sets R0 */
4462 			bt_clear_reg(bt, BPF_REG_0);
4463 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4464 				/* if backtracking was looking for registers R1-R5
4465 				 * they should have been found already.
4466 				 */
4467 				verifier_bug(env, "backtracking call unexpected regs %x",
4468 					     bt_reg_mask(bt));
4469 				return -EFAULT;
4470 			}
4471 		} else if (opcode == BPF_EXIT) {
4472 			bool r0_precise;
4473 
4474 			/* Backtracking to a nested function call, 'idx' is a part of
4475 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4476 			 * In case of a regular function call, instructions giving
4477 			 * precision to registers R1-R5 should have been found already.
4478 			 * In case of a callback, it is ok to have R1-R5 marked for
4479 			 * backtracking, as these registers are set by the function
4480 			 * invoking callback.
4481 			 */
4482 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
4483 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4484 					bt_clear_reg(bt, i);
4485 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4486 				verifier_bug(env, "backtracking exit unexpected regs %x",
4487 					     bt_reg_mask(bt));
4488 				return -EFAULT;
4489 			}
4490 
4491 			/* BPF_EXIT in subprog or callback always returns
4492 			 * right after the call instruction, so by checking
4493 			 * whether the instruction at subseq_idx-1 is subprog
4494 			 * call or not we can distinguish actual exit from
4495 			 * *subprog* from exit from *callback*. In the former
4496 			 * case, we need to propagate r0 precision, if
4497 			 * necessary. In the former we never do that.
4498 			 */
4499 			r0_precise = subseq_idx - 1 >= 0 &&
4500 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4501 				     bt_is_reg_set(bt, BPF_REG_0);
4502 
4503 			bt_clear_reg(bt, BPF_REG_0);
4504 			if (bt_subprog_enter(bt))
4505 				return -EFAULT;
4506 
4507 			if (r0_precise)
4508 				bt_set_reg(bt, BPF_REG_0);
4509 			/* r6-r9 and stack slots will stay set in caller frame
4510 			 * bitmasks until we return back from callee(s)
4511 			 */
4512 			return 0;
4513 		} else if (BPF_SRC(insn->code) == BPF_X) {
4514 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4515 				return 0;
4516 			/* dreg <cond> sreg
4517 			 * Both dreg and sreg need precision before
4518 			 * this insn. If only sreg was marked precise
4519 			 * before it would be equally necessary to
4520 			 * propagate it to dreg.
4521 			 */
4522 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4523 				bt_set_reg(bt, sreg);
4524 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4525 				bt_set_reg(bt, dreg);
4526 		} else if (BPF_SRC(insn->code) == BPF_K) {
4527 			 /* dreg <cond> K
4528 			  * Only dreg still needs precision before
4529 			  * this insn, so for the K-based conditional
4530 			  * there is nothing new to be marked.
4531 			  */
4532 		}
4533 	} else if (class == BPF_LD) {
4534 		if (!bt_is_reg_set(bt, dreg))
4535 			return 0;
4536 		bt_clear_reg(bt, dreg);
4537 		/* It's ld_imm64 or ld_abs or ld_ind.
4538 		 * For ld_imm64 no further tracking of precision
4539 		 * into parent is necessary
4540 		 */
4541 		if (mode == BPF_IND || mode == BPF_ABS)
4542 			/* to be analyzed */
4543 			return -ENOTSUPP;
4544 	}
4545 	/* Propagate precision marks to linked registers, to account for
4546 	 * registers marked as precise in this function.
4547 	 */
4548 	bt_sync_linked_regs(bt, hist);
4549 	return 0;
4550 }
4551 
4552 /* the scalar precision tracking algorithm:
4553  * . at the start all registers have precise=false.
4554  * . scalar ranges are tracked as normal through alu and jmp insns.
4555  * . once precise value of the scalar register is used in:
4556  *   .  ptr + scalar alu
4557  *   . if (scalar cond K|scalar)
4558  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4559  *   backtrack through the verifier states and mark all registers and
4560  *   stack slots with spilled constants that these scalar registers
4561  *   should be precise.
4562  * . during state pruning two registers (or spilled stack slots)
4563  *   are equivalent if both are not precise.
4564  *
4565  * Note the verifier cannot simply walk register parentage chain,
4566  * since many different registers and stack slots could have been
4567  * used to compute single precise scalar.
4568  *
4569  * The approach of starting with precise=true for all registers and then
4570  * backtrack to mark a register as not precise when the verifier detects
4571  * that program doesn't care about specific value (e.g., when helper
4572  * takes register as ARG_ANYTHING parameter) is not safe.
4573  *
4574  * It's ok to walk single parentage chain of the verifier states.
4575  * It's possible that this backtracking will go all the way till 1st insn.
4576  * All other branches will be explored for needing precision later.
4577  *
4578  * The backtracking needs to deal with cases like:
4579  *   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)
4580  * r9 -= r8
4581  * r5 = r9
4582  * if r5 > 0x79f goto pc+7
4583  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4584  * r5 += 1
4585  * ...
4586  * call bpf_perf_event_output#25
4587  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4588  *
4589  * and this case:
4590  * r6 = 1
4591  * call foo // uses callee's r6 inside to compute r0
4592  * r0 += r6
4593  * if r0 == 0 goto
4594  *
4595  * to track above reg_mask/stack_mask needs to be independent for each frame.
4596  *
4597  * Also if parent's curframe > frame where backtracking started,
4598  * the verifier need to mark registers in both frames, otherwise callees
4599  * may incorrectly prune callers. This is similar to
4600  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4601  *
4602  * For now backtracking falls back into conservative marking.
4603  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4604 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4605 				     struct bpf_verifier_state *st)
4606 {
4607 	struct bpf_func_state *func;
4608 	struct bpf_reg_state *reg;
4609 	int i, j;
4610 
4611 	if (env->log.level & BPF_LOG_LEVEL2) {
4612 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4613 			st->curframe);
4614 	}
4615 
4616 	/* big hammer: mark all scalars precise in this path.
4617 	 * pop_stack may still get !precise scalars.
4618 	 * We also skip current state and go straight to first parent state,
4619 	 * because precision markings in current non-checkpointed state are
4620 	 * not needed. See why in the comment in __mark_chain_precision below.
4621 	 */
4622 	for (st = st->parent; st; st = st->parent) {
4623 		for (i = 0; i <= st->curframe; i++) {
4624 			func = st->frame[i];
4625 			for (j = 0; j < BPF_REG_FP; j++) {
4626 				reg = &func->regs[j];
4627 				if (reg->type != SCALAR_VALUE || reg->precise)
4628 					continue;
4629 				reg->precise = true;
4630 				if (env->log.level & BPF_LOG_LEVEL2) {
4631 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4632 						i, j);
4633 				}
4634 			}
4635 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4636 				if (!is_spilled_reg(&func->stack[j]))
4637 					continue;
4638 				reg = &func->stack[j].spilled_ptr;
4639 				if (reg->type != SCALAR_VALUE || reg->precise)
4640 					continue;
4641 				reg->precise = true;
4642 				if (env->log.level & BPF_LOG_LEVEL2) {
4643 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4644 						i, -(j + 1) * 8);
4645 				}
4646 			}
4647 		}
4648 	}
4649 }
4650 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4651 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4652 {
4653 	struct bpf_func_state *func;
4654 	struct bpf_reg_state *reg;
4655 	int i, j;
4656 
4657 	for (i = 0; i <= st->curframe; i++) {
4658 		func = st->frame[i];
4659 		for (j = 0; j < BPF_REG_FP; j++) {
4660 			reg = &func->regs[j];
4661 			if (reg->type != SCALAR_VALUE)
4662 				continue;
4663 			reg->precise = false;
4664 		}
4665 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4666 			if (!is_spilled_reg(&func->stack[j]))
4667 				continue;
4668 			reg = &func->stack[j].spilled_ptr;
4669 			if (reg->type != SCALAR_VALUE)
4670 				continue;
4671 			reg->precise = false;
4672 		}
4673 	}
4674 }
4675 
4676 /*
4677  * __mark_chain_precision() backtracks BPF program instruction sequence and
4678  * chain of verifier states making sure that register *regno* (if regno >= 0)
4679  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4680  * SCALARS, as well as any other registers and slots that contribute to
4681  * a tracked state of given registers/stack slots, depending on specific BPF
4682  * assembly instructions (see backtrack_insns() for exact instruction handling
4683  * logic). This backtracking relies on recorded jmp_history and is able to
4684  * traverse entire chain of parent states. This process ends only when all the
4685  * necessary registers/slots and their transitive dependencies are marked as
4686  * precise.
4687  *
4688  * One important and subtle aspect is that precise marks *do not matter* in
4689  * the currently verified state (current state). It is important to understand
4690  * why this is the case.
4691  *
4692  * First, note that current state is the state that is not yet "checkpointed",
4693  * i.e., it is not yet put into env->explored_states, and it has no children
4694  * states as well. It's ephemeral, and can end up either a) being discarded if
4695  * compatible explored state is found at some point or BPF_EXIT instruction is
4696  * reached or b) checkpointed and put into env->explored_states, branching out
4697  * into one or more children states.
4698  *
4699  * In the former case, precise markings in current state are completely
4700  * ignored by state comparison code (see regsafe() for details). Only
4701  * checkpointed ("old") state precise markings are important, and if old
4702  * state's register/slot is precise, regsafe() assumes current state's
4703  * register/slot as precise and checks value ranges exactly and precisely. If
4704  * states turn out to be compatible, current state's necessary precise
4705  * markings and any required parent states' precise markings are enforced
4706  * after the fact with propagate_precision() logic, after the fact. But it's
4707  * important to realize that in this case, even after marking current state
4708  * registers/slots as precise, we immediately discard current state. So what
4709  * actually matters is any of the precise markings propagated into current
4710  * state's parent states, which are always checkpointed (due to b) case above).
4711  * As such, for scenario a) it doesn't matter if current state has precise
4712  * markings set or not.
4713  *
4714  * Now, for the scenario b), checkpointing and forking into child(ren)
4715  * state(s). Note that before current state gets to checkpointing step, any
4716  * processed instruction always assumes precise SCALAR register/slot
4717  * knowledge: if precise value or range is useful to prune jump branch, BPF
4718  * verifier takes this opportunity enthusiastically. Similarly, when
4719  * register's value is used to calculate offset or memory address, exact
4720  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4721  * what we mentioned above about state comparison ignoring precise markings
4722  * during state comparison, BPF verifier ignores and also assumes precise
4723  * markings *at will* during instruction verification process. But as verifier
4724  * assumes precision, it also propagates any precision dependencies across
4725  * parent states, which are not yet finalized, so can be further restricted
4726  * based on new knowledge gained from restrictions enforced by their children
4727  * states. This is so that once those parent states are finalized, i.e., when
4728  * they have no more active children state, state comparison logic in
4729  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4730  * required for correctness.
4731  *
4732  * To build a bit more intuition, note also that once a state is checkpointed,
4733  * the path we took to get to that state is not important. This is crucial
4734  * property for state pruning. When state is checkpointed and finalized at
4735  * some instruction index, it can be correctly and safely used to "short
4736  * circuit" any *compatible* state that reaches exactly the same instruction
4737  * index. I.e., if we jumped to that instruction from a completely different
4738  * code path than original finalized state was derived from, it doesn't
4739  * matter, current state can be discarded because from that instruction
4740  * forward having a compatible state will ensure we will safely reach the
4741  * exit. States describe preconditions for further exploration, but completely
4742  * forget the history of how we got here.
4743  *
4744  * This also means that even if we needed precise SCALAR range to get to
4745  * finalized state, but from that point forward *that same* SCALAR register is
4746  * never used in a precise context (i.e., it's precise value is not needed for
4747  * correctness), it's correct and safe to mark such register as "imprecise"
4748  * (i.e., precise marking set to false). This is what we rely on when we do
4749  * not set precise marking in current state. If no child state requires
4750  * precision for any given SCALAR register, it's safe to dictate that it can
4751  * be imprecise. If any child state does require this register to be precise,
4752  * we'll mark it precise later retroactively during precise markings
4753  * propagation from child state to parent states.
4754  *
4755  * Skipping precise marking setting in current state is a mild version of
4756  * relying on the above observation. But we can utilize this property even
4757  * more aggressively by proactively forgetting any precise marking in the
4758  * current state (which we inherited from the parent state), right before we
4759  * checkpoint it and branch off into new child state. This is done by
4760  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4761  * finalized states which help in short circuiting more future states.
4762  */
__mark_chain_precision(struct bpf_verifier_env * env,struct bpf_verifier_state * starting_state,int regno,bool * changed)4763 static int __mark_chain_precision(struct bpf_verifier_env *env,
4764 				  struct bpf_verifier_state *starting_state,
4765 				  int regno,
4766 				  bool *changed)
4767 {
4768 	struct bpf_verifier_state *st = starting_state;
4769 	struct backtrack_state *bt = &env->bt;
4770 	int first_idx = st->first_insn_idx;
4771 	int last_idx = starting_state->insn_idx;
4772 	int subseq_idx = -1;
4773 	struct bpf_func_state *func;
4774 	bool tmp, skip_first = true;
4775 	struct bpf_reg_state *reg;
4776 	int i, fr, err;
4777 
4778 	if (!env->bpf_capable)
4779 		return 0;
4780 
4781 	changed = changed ?: &tmp;
4782 	/* set frame number from which we are starting to backtrack */
4783 	bt_init(bt, starting_state->curframe);
4784 
4785 	/* Do sanity checks against current state of register and/or stack
4786 	 * slot, but don't set precise flag in current state, as precision
4787 	 * tracking in the current state is unnecessary.
4788 	 */
4789 	func = st->frame[bt->frame];
4790 	if (regno >= 0) {
4791 		reg = &func->regs[regno];
4792 		if (reg->type != SCALAR_VALUE) {
4793 			verifier_bug(env, "backtracking misuse");
4794 			return -EFAULT;
4795 		}
4796 		bt_set_reg(bt, regno);
4797 	}
4798 
4799 	if (bt_empty(bt))
4800 		return 0;
4801 
4802 	for (;;) {
4803 		DECLARE_BITMAP(mask, 64);
4804 		u32 history = st->jmp_history_cnt;
4805 		struct bpf_jmp_history_entry *hist;
4806 
4807 		if (env->log.level & BPF_LOG_LEVEL2) {
4808 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4809 				bt->frame, last_idx, first_idx, subseq_idx);
4810 		}
4811 
4812 		if (last_idx < 0) {
4813 			/* we are at the entry into subprog, which
4814 			 * is expected for global funcs, but only if
4815 			 * requested precise registers are R1-R5
4816 			 * (which are global func's input arguments)
4817 			 */
4818 			if (st->curframe == 0 &&
4819 			    st->frame[0]->subprogno > 0 &&
4820 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4821 			    bt_stack_mask(bt) == 0 &&
4822 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4823 				bitmap_from_u64(mask, bt_reg_mask(bt));
4824 				for_each_set_bit(i, mask, 32) {
4825 					reg = &st->frame[0]->regs[i];
4826 					bt_clear_reg(bt, i);
4827 					if (reg->type == SCALAR_VALUE) {
4828 						reg->precise = true;
4829 						*changed = true;
4830 					}
4831 				}
4832 				return 0;
4833 			}
4834 
4835 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4836 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4837 			return -EFAULT;
4838 		}
4839 
4840 		for (i = last_idx;;) {
4841 			if (skip_first) {
4842 				err = 0;
4843 				skip_first = false;
4844 			} else {
4845 				hist = get_jmp_hist_entry(st, history, i);
4846 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4847 			}
4848 			if (err == -ENOTSUPP) {
4849 				mark_all_scalars_precise(env, starting_state);
4850 				bt_reset(bt);
4851 				return 0;
4852 			} else if (err) {
4853 				return err;
4854 			}
4855 			if (bt_empty(bt))
4856 				/* Found assignment(s) into tracked register in this state.
4857 				 * Since this state is already marked, just return.
4858 				 * Nothing to be tracked further in the parent state.
4859 				 */
4860 				return 0;
4861 			subseq_idx = i;
4862 			i = get_prev_insn_idx(st, i, &history);
4863 			if (i == -ENOENT)
4864 				break;
4865 			if (i >= env->prog->len) {
4866 				/* This can happen if backtracking reached insn 0
4867 				 * and there are still reg_mask or stack_mask
4868 				 * to backtrack.
4869 				 * It means the backtracking missed the spot where
4870 				 * particular register was initialized with a constant.
4871 				 */
4872 				verifier_bug(env, "backtracking idx %d", i);
4873 				return -EFAULT;
4874 			}
4875 		}
4876 		st = st->parent;
4877 		if (!st)
4878 			break;
4879 
4880 		for (fr = bt->frame; fr >= 0; fr--) {
4881 			func = st->frame[fr];
4882 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4883 			for_each_set_bit(i, mask, 32) {
4884 				reg = &func->regs[i];
4885 				if (reg->type != SCALAR_VALUE) {
4886 					bt_clear_frame_reg(bt, fr, i);
4887 					continue;
4888 				}
4889 				if (reg->precise) {
4890 					bt_clear_frame_reg(bt, fr, i);
4891 				} else {
4892 					reg->precise = true;
4893 					*changed = true;
4894 				}
4895 			}
4896 
4897 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4898 			for_each_set_bit(i, mask, 64) {
4899 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4900 						    env, "stack slot %d, total slots %d",
4901 						    i, func->allocated_stack / BPF_REG_SIZE))
4902 					return -EFAULT;
4903 
4904 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4905 					bt_clear_frame_slot(bt, fr, i);
4906 					continue;
4907 				}
4908 				reg = &func->stack[i].spilled_ptr;
4909 				if (reg->precise) {
4910 					bt_clear_frame_slot(bt, fr, i);
4911 				} else {
4912 					reg->precise = true;
4913 					*changed = true;
4914 				}
4915 			}
4916 			if (env->log.level & BPF_LOG_LEVEL2) {
4917 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4918 					     bt_frame_reg_mask(bt, fr));
4919 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4920 					fr, env->tmp_str_buf);
4921 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4922 					       bt_frame_stack_mask(bt, fr));
4923 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4924 				print_verifier_state(env, st, fr, true);
4925 			}
4926 		}
4927 
4928 		if (bt_empty(bt))
4929 			return 0;
4930 
4931 		subseq_idx = first_idx;
4932 		last_idx = st->last_insn_idx;
4933 		first_idx = st->first_insn_idx;
4934 	}
4935 
4936 	/* if we still have requested precise regs or slots, we missed
4937 	 * something (e.g., stack access through non-r10 register), so
4938 	 * fallback to marking all precise
4939 	 */
4940 	if (!bt_empty(bt)) {
4941 		mark_all_scalars_precise(env, starting_state);
4942 		bt_reset(bt);
4943 	}
4944 
4945 	return 0;
4946 }
4947 
mark_chain_precision(struct bpf_verifier_env * env,int regno)4948 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4949 {
4950 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4951 }
4952 
4953 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4954  * desired reg and stack masks across all relevant frames
4955  */
mark_chain_precision_batch(struct bpf_verifier_env * env,struct bpf_verifier_state * starting_state)4956 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4957 				      struct bpf_verifier_state *starting_state)
4958 {
4959 	return __mark_chain_precision(env, starting_state, -1, NULL);
4960 }
4961 
is_spillable_regtype(enum bpf_reg_type type)4962 static bool is_spillable_regtype(enum bpf_reg_type type)
4963 {
4964 	switch (base_type(type)) {
4965 	case PTR_TO_MAP_VALUE:
4966 	case PTR_TO_STACK:
4967 	case PTR_TO_CTX:
4968 	case PTR_TO_PACKET:
4969 	case PTR_TO_PACKET_META:
4970 	case PTR_TO_PACKET_END:
4971 	case PTR_TO_FLOW_KEYS:
4972 	case CONST_PTR_TO_MAP:
4973 	case PTR_TO_SOCKET:
4974 	case PTR_TO_SOCK_COMMON:
4975 	case PTR_TO_TCP_SOCK:
4976 	case PTR_TO_XDP_SOCK:
4977 	case PTR_TO_BTF_ID:
4978 	case PTR_TO_BUF:
4979 	case PTR_TO_MEM:
4980 	case PTR_TO_FUNC:
4981 	case PTR_TO_MAP_KEY:
4982 	case PTR_TO_ARENA:
4983 		return true;
4984 	default:
4985 		return false;
4986 	}
4987 }
4988 
4989 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4990 static bool register_is_null(struct bpf_reg_state *reg)
4991 {
4992 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4993 }
4994 
4995 /* check if register is a constant scalar value */
is_reg_const(struct bpf_reg_state * reg,bool subreg32)4996 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4997 {
4998 	return reg->type == SCALAR_VALUE &&
4999 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
5000 }
5001 
5002 /* assuming is_reg_const() is true, return constant value of a register */
reg_const_value(struct bpf_reg_state * reg,bool subreg32)5003 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
5004 {
5005 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
5006 }
5007 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)5008 static bool __is_pointer_value(bool allow_ptr_leaks,
5009 			       const struct bpf_reg_state *reg)
5010 {
5011 	if (allow_ptr_leaks)
5012 		return false;
5013 
5014 	return reg->type != SCALAR_VALUE;
5015 }
5016 
assign_scalar_id_before_mov(struct bpf_verifier_env * env,struct bpf_reg_state * src_reg)5017 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
5018 					struct bpf_reg_state *src_reg)
5019 {
5020 	if (src_reg->type != SCALAR_VALUE)
5021 		return;
5022 
5023 	if (src_reg->id & BPF_ADD_CONST) {
5024 		/*
5025 		 * The verifier is processing rX = rY insn and
5026 		 * rY->id has special linked register already.
5027 		 * Cleared it, since multiple rX += const are not supported.
5028 		 */
5029 		src_reg->id = 0;
5030 		src_reg->off = 0;
5031 	}
5032 
5033 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5034 		/* Ensure that src_reg has a valid ID that will be copied to
5035 		 * dst_reg and then will be used by sync_linked_regs() to
5036 		 * propagate min/max range.
5037 		 */
5038 		src_reg->id = ++env->id_gen;
5039 }
5040 
5041 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)5042 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5043 {
5044 	struct bpf_reg_state *parent = dst->parent;
5045 	enum bpf_reg_liveness live = dst->live;
5046 
5047 	*dst = *src;
5048 	dst->parent = parent;
5049 	dst->live = live;
5050 }
5051 
save_register_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)5052 static void save_register_state(struct bpf_verifier_env *env,
5053 				struct bpf_func_state *state,
5054 				int spi, struct bpf_reg_state *reg,
5055 				int size)
5056 {
5057 	int i;
5058 
5059 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
5060 	if (size == BPF_REG_SIZE)
5061 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
5062 
5063 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5064 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5065 
5066 	/* size < 8 bytes spill */
5067 	for (; i; i--)
5068 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5069 }
5070 
is_bpf_st_mem(struct bpf_insn * insn)5071 static bool is_bpf_st_mem(struct bpf_insn *insn)
5072 {
5073 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5074 }
5075 
get_reg_width(struct bpf_reg_state * reg)5076 static int get_reg_width(struct bpf_reg_state *reg)
5077 {
5078 	return fls64(reg->umax_value);
5079 }
5080 
5081 /* See comment for mark_fastcall_pattern_for_call() */
check_fastcall_stack_contract(struct bpf_verifier_env * env,struct bpf_func_state * state,int insn_idx,int off)5082 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5083 					  struct bpf_func_state *state, int insn_idx, int off)
5084 {
5085 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5086 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5087 	int i;
5088 
5089 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5090 		return;
5091 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5092 	 * from something that is not a part of the fastcall pattern,
5093 	 * disable fastcall rewrites for current subprogram by setting
5094 	 * fastcall_stack_off to a value smaller than any possible offset.
5095 	 */
5096 	subprog->fastcall_stack_off = S16_MIN;
5097 	/* reset fastcall aux flags within subprogram,
5098 	 * happens at most once per subprogram
5099 	 */
5100 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5101 		aux[i].fastcall_spills_num = 0;
5102 		aux[i].fastcall_pattern = 0;
5103 	}
5104 }
5105 
5106 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5107  * stack boundary and alignment are checked in check_mem_access()
5108  */
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)5109 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5110 				       /* stack frame we're writing to */
5111 				       struct bpf_func_state *state,
5112 				       int off, int size, int value_regno,
5113 				       int insn_idx)
5114 {
5115 	struct bpf_func_state *cur; /* state of the current function */
5116 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5117 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5118 	struct bpf_reg_state *reg = NULL;
5119 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5120 
5121 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5122 	 * so it's aligned access and [off, off + size) are within stack limits
5123 	 */
5124 	if (!env->allow_ptr_leaks &&
5125 	    is_spilled_reg(&state->stack[spi]) &&
5126 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5127 	    size != BPF_REG_SIZE) {
5128 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5129 		return -EACCES;
5130 	}
5131 
5132 	cur = env->cur_state->frame[env->cur_state->curframe];
5133 	if (value_regno >= 0)
5134 		reg = &cur->regs[value_regno];
5135 	if (!env->bypass_spec_v4) {
5136 		bool sanitize = reg && is_spillable_regtype(reg->type);
5137 
5138 		for (i = 0; i < size; i++) {
5139 			u8 type = state->stack[spi].slot_type[i];
5140 
5141 			if (type != STACK_MISC && type != STACK_ZERO) {
5142 				sanitize = true;
5143 				break;
5144 			}
5145 		}
5146 
5147 		if (sanitize)
5148 			env->insn_aux_data[insn_idx].nospec_result = true;
5149 	}
5150 
5151 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5152 	if (err)
5153 		return err;
5154 
5155 	check_fastcall_stack_contract(env, state, insn_idx, off);
5156 	mark_stack_slot_scratched(env, spi);
5157 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5158 		bool reg_value_fits;
5159 
5160 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5161 		/* Make sure that reg had an ID to build a relation on spill. */
5162 		if (reg_value_fits)
5163 			assign_scalar_id_before_mov(env, reg);
5164 		save_register_state(env, state, spi, reg, size);
5165 		/* Break the relation on a narrowing spill. */
5166 		if (!reg_value_fits)
5167 			state->stack[spi].spilled_ptr.id = 0;
5168 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5169 		   env->bpf_capable) {
5170 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5171 
5172 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5173 		__mark_reg_known(tmp_reg, insn->imm);
5174 		tmp_reg->type = SCALAR_VALUE;
5175 		save_register_state(env, state, spi, tmp_reg, size);
5176 	} else if (reg && is_spillable_regtype(reg->type)) {
5177 		/* register containing pointer is being spilled into stack */
5178 		if (size != BPF_REG_SIZE) {
5179 			verbose_linfo(env, insn_idx, "; ");
5180 			verbose(env, "invalid size of register spill\n");
5181 			return -EACCES;
5182 		}
5183 		if (state != cur && reg->type == PTR_TO_STACK) {
5184 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5185 			return -EINVAL;
5186 		}
5187 		save_register_state(env, state, spi, reg, size);
5188 	} else {
5189 		u8 type = STACK_MISC;
5190 
5191 		/* regular write of data into stack destroys any spilled ptr */
5192 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5193 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5194 		if (is_stack_slot_special(&state->stack[spi]))
5195 			for (i = 0; i < BPF_REG_SIZE; i++)
5196 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5197 
5198 		/* only mark the slot as written if all 8 bytes were written
5199 		 * otherwise read propagation may incorrectly stop too soon
5200 		 * when stack slots are partially written.
5201 		 * This heuristic means that read propagation will be
5202 		 * conservative, since it will add reg_live_read marks
5203 		 * to stack slots all the way to first state when programs
5204 		 * writes+reads less than 8 bytes
5205 		 */
5206 		if (size == BPF_REG_SIZE)
5207 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
5208 
5209 		/* when we zero initialize stack slots mark them as such */
5210 		if ((reg && register_is_null(reg)) ||
5211 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5212 			/* STACK_ZERO case happened because register spill
5213 			 * wasn't properly aligned at the stack slot boundary,
5214 			 * so it's not a register spill anymore; force
5215 			 * originating register to be precise to make
5216 			 * STACK_ZERO correct for subsequent states
5217 			 */
5218 			err = mark_chain_precision(env, value_regno);
5219 			if (err)
5220 				return err;
5221 			type = STACK_ZERO;
5222 		}
5223 
5224 		/* Mark slots affected by this stack write. */
5225 		for (i = 0; i < size; i++)
5226 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5227 		insn_flags = 0; /* not a register spill */
5228 	}
5229 
5230 	if (insn_flags)
5231 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5232 	return 0;
5233 }
5234 
5235 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5236  * known to contain a variable offset.
5237  * This function checks whether the write is permitted and conservatively
5238  * tracks the effects of the write, considering that each stack slot in the
5239  * dynamic range is potentially written to.
5240  *
5241  * 'off' includes 'regno->off'.
5242  * 'value_regno' can be -1, meaning that an unknown value is being written to
5243  * the stack.
5244  *
5245  * Spilled pointers in range are not marked as written because we don't know
5246  * what's going to be actually written. This means that read propagation for
5247  * future reads cannot be terminated by this write.
5248  *
5249  * For privileged programs, uninitialized stack slots are considered
5250  * initialized by this write (even though we don't know exactly what offsets
5251  * are going to be written to). The idea is that we don't want the verifier to
5252  * reject future reads that access slots written to through variable offsets.
5253  */
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)5254 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5255 				     /* func where register points to */
5256 				     struct bpf_func_state *state,
5257 				     int ptr_regno, int off, int size,
5258 				     int value_regno, int insn_idx)
5259 {
5260 	struct bpf_func_state *cur; /* state of the current function */
5261 	int min_off, max_off;
5262 	int i, err;
5263 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5264 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5265 	bool writing_zero = false;
5266 	/* set if the fact that we're writing a zero is used to let any
5267 	 * stack slots remain STACK_ZERO
5268 	 */
5269 	bool zero_used = false;
5270 
5271 	cur = env->cur_state->frame[env->cur_state->curframe];
5272 	ptr_reg = &cur->regs[ptr_regno];
5273 	min_off = ptr_reg->smin_value + off;
5274 	max_off = ptr_reg->smax_value + off + size;
5275 	if (value_regno >= 0)
5276 		value_reg = &cur->regs[value_regno];
5277 	if ((value_reg && register_is_null(value_reg)) ||
5278 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5279 		writing_zero = true;
5280 
5281 	for (i = min_off; i < max_off; i++) {
5282 		int spi;
5283 
5284 		spi = __get_spi(i);
5285 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5286 		if (err)
5287 			return err;
5288 	}
5289 
5290 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5291 	/* Variable offset writes destroy any spilled pointers in range. */
5292 	for (i = min_off; i < max_off; i++) {
5293 		u8 new_type, *stype;
5294 		int slot, spi;
5295 
5296 		slot = -i - 1;
5297 		spi = slot / BPF_REG_SIZE;
5298 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5299 		mark_stack_slot_scratched(env, spi);
5300 
5301 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5302 			/* Reject the write if range we may write to has not
5303 			 * been initialized beforehand. If we didn't reject
5304 			 * here, the ptr status would be erased below (even
5305 			 * though not all slots are actually overwritten),
5306 			 * possibly opening the door to leaks.
5307 			 *
5308 			 * We do however catch STACK_INVALID case below, and
5309 			 * only allow reading possibly uninitialized memory
5310 			 * later for CAP_PERFMON, as the write may not happen to
5311 			 * that slot.
5312 			 */
5313 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5314 				insn_idx, i);
5315 			return -EINVAL;
5316 		}
5317 
5318 		/* If writing_zero and the spi slot contains a spill of value 0,
5319 		 * maintain the spill type.
5320 		 */
5321 		if (writing_zero && *stype == STACK_SPILL &&
5322 		    is_spilled_scalar_reg(&state->stack[spi])) {
5323 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5324 
5325 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5326 				zero_used = true;
5327 				continue;
5328 			}
5329 		}
5330 
5331 		/* Erase all other spilled pointers. */
5332 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5333 
5334 		/* Update the slot type. */
5335 		new_type = STACK_MISC;
5336 		if (writing_zero && *stype == STACK_ZERO) {
5337 			new_type = STACK_ZERO;
5338 			zero_used = true;
5339 		}
5340 		/* If the slot is STACK_INVALID, we check whether it's OK to
5341 		 * pretend that it will be initialized by this write. The slot
5342 		 * might not actually be written to, and so if we mark it as
5343 		 * initialized future reads might leak uninitialized memory.
5344 		 * For privileged programs, we will accept such reads to slots
5345 		 * that may or may not be written because, if we're reject
5346 		 * them, the error would be too confusing.
5347 		 */
5348 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5349 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5350 					insn_idx, i);
5351 			return -EINVAL;
5352 		}
5353 		*stype = new_type;
5354 	}
5355 	if (zero_used) {
5356 		/* backtracking doesn't work for STACK_ZERO yet. */
5357 		err = mark_chain_precision(env, value_regno);
5358 		if (err)
5359 			return err;
5360 	}
5361 	return 0;
5362 }
5363 
5364 /* When register 'dst_regno' is assigned some values from stack[min_off,
5365  * max_off), we set the register's type according to the types of the
5366  * respective stack slots. If all the stack values are known to be zeros, then
5367  * so is the destination reg. Otherwise, the register is considered to be
5368  * SCALAR. This function does not deal with register filling; the caller must
5369  * ensure that all spilled registers in the stack range have been marked as
5370  * read.
5371  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)5372 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5373 				/* func where src register points to */
5374 				struct bpf_func_state *ptr_state,
5375 				int min_off, int max_off, int dst_regno)
5376 {
5377 	struct bpf_verifier_state *vstate = env->cur_state;
5378 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5379 	int i, slot, spi;
5380 	u8 *stype;
5381 	int zeros = 0;
5382 
5383 	for (i = min_off; i < max_off; i++) {
5384 		slot = -i - 1;
5385 		spi = slot / BPF_REG_SIZE;
5386 		mark_stack_slot_scratched(env, spi);
5387 		stype = ptr_state->stack[spi].slot_type;
5388 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5389 			break;
5390 		zeros++;
5391 	}
5392 	if (zeros == max_off - min_off) {
5393 		/* Any access_size read into register is zero extended,
5394 		 * so the whole register == const_zero.
5395 		 */
5396 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5397 	} else {
5398 		/* have read misc data from the stack */
5399 		mark_reg_unknown(env, state->regs, dst_regno);
5400 	}
5401 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5402 }
5403 
5404 /* Read the stack at 'off' and put the results into the register indicated by
5405  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5406  * spilled reg.
5407  *
5408  * 'dst_regno' can be -1, meaning that the read value is not going to a
5409  * register.
5410  *
5411  * The access is assumed to be within the current stack bounds.
5412  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)5413 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5414 				      /* func where src register points to */
5415 				      struct bpf_func_state *reg_state,
5416 				      int off, int size, int dst_regno)
5417 {
5418 	struct bpf_verifier_state *vstate = env->cur_state;
5419 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5420 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5421 	struct bpf_reg_state *reg;
5422 	u8 *stype, type;
5423 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5424 
5425 	stype = reg_state->stack[spi].slot_type;
5426 	reg = &reg_state->stack[spi].spilled_ptr;
5427 
5428 	mark_stack_slot_scratched(env, spi);
5429 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5430 
5431 	if (is_spilled_reg(&reg_state->stack[spi])) {
5432 		u8 spill_size = 1;
5433 
5434 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5435 			spill_size++;
5436 
5437 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5438 			if (reg->type != SCALAR_VALUE) {
5439 				verbose_linfo(env, env->insn_idx, "; ");
5440 				verbose(env, "invalid size of register fill\n");
5441 				return -EACCES;
5442 			}
5443 
5444 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5445 			if (dst_regno < 0)
5446 				return 0;
5447 
5448 			if (size <= spill_size &&
5449 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5450 				/* The earlier check_reg_arg() has decided the
5451 				 * subreg_def for this insn.  Save it first.
5452 				 */
5453 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5454 
5455 				copy_register_state(&state->regs[dst_regno], reg);
5456 				state->regs[dst_regno].subreg_def = subreg_def;
5457 
5458 				/* Break the relation on a narrowing fill.
5459 				 * coerce_reg_to_size will adjust the boundaries.
5460 				 */
5461 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5462 					state->regs[dst_regno].id = 0;
5463 			} else {
5464 				int spill_cnt = 0, zero_cnt = 0;
5465 
5466 				for (i = 0; i < size; i++) {
5467 					type = stype[(slot - i) % BPF_REG_SIZE];
5468 					if (type == STACK_SPILL) {
5469 						spill_cnt++;
5470 						continue;
5471 					}
5472 					if (type == STACK_MISC)
5473 						continue;
5474 					if (type == STACK_ZERO) {
5475 						zero_cnt++;
5476 						continue;
5477 					}
5478 					if (type == STACK_INVALID && env->allow_uninit_stack)
5479 						continue;
5480 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5481 						off, i, size);
5482 					return -EACCES;
5483 				}
5484 
5485 				if (spill_cnt == size &&
5486 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5487 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5488 					/* this IS register fill, so keep insn_flags */
5489 				} else if (zero_cnt == size) {
5490 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5491 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5492 					insn_flags = 0; /* not restoring original register state */
5493 				} else {
5494 					mark_reg_unknown(env, state->regs, dst_regno);
5495 					insn_flags = 0; /* not restoring original register state */
5496 				}
5497 			}
5498 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5499 		} else if (dst_regno >= 0) {
5500 			/* restore register state from stack */
5501 			copy_register_state(&state->regs[dst_regno], reg);
5502 			/* mark reg as written since spilled pointer state likely
5503 			 * has its liveness marks cleared by is_state_visited()
5504 			 * which resets stack/reg liveness for state transitions
5505 			 */
5506 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
5507 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5508 			/* If dst_regno==-1, the caller is asking us whether
5509 			 * it is acceptable to use this value as a SCALAR_VALUE
5510 			 * (e.g. for XADD).
5511 			 * We must not allow unprivileged callers to do that
5512 			 * with spilled pointers.
5513 			 */
5514 			verbose(env, "leaking pointer from stack off %d\n",
5515 				off);
5516 			return -EACCES;
5517 		}
5518 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5519 	} else {
5520 		for (i = 0; i < size; i++) {
5521 			type = stype[(slot - i) % BPF_REG_SIZE];
5522 			if (type == STACK_MISC)
5523 				continue;
5524 			if (type == STACK_ZERO)
5525 				continue;
5526 			if (type == STACK_INVALID && env->allow_uninit_stack)
5527 				continue;
5528 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5529 				off, i, size);
5530 			return -EACCES;
5531 		}
5532 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5533 		if (dst_regno >= 0)
5534 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5535 		insn_flags = 0; /* we are not restoring spilled register */
5536 	}
5537 	if (insn_flags)
5538 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5539 	return 0;
5540 }
5541 
5542 enum bpf_access_src {
5543 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5544 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5545 };
5546 
5547 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5548 					 int regno, int off, int access_size,
5549 					 bool zero_size_allowed,
5550 					 enum bpf_access_type type,
5551 					 struct bpf_call_arg_meta *meta);
5552 
reg_state(struct bpf_verifier_env * env,int regno)5553 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5554 {
5555 	return cur_regs(env) + regno;
5556 }
5557 
5558 /* Read the stack at 'ptr_regno + off' and put the result into the register
5559  * 'dst_regno'.
5560  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5561  * but not its variable offset.
5562  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5563  *
5564  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5565  * filling registers (i.e. reads of spilled register cannot be detected when
5566  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5567  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5568  * offset; for a fixed offset check_stack_read_fixed_off should be used
5569  * instead.
5570  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5571 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5572 				    int ptr_regno, int off, int size, int dst_regno)
5573 {
5574 	/* The state of the source register. */
5575 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5576 	struct bpf_func_state *ptr_state = func(env, reg);
5577 	int err;
5578 	int min_off, max_off;
5579 
5580 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5581 	 */
5582 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5583 					    false, BPF_READ, NULL);
5584 	if (err)
5585 		return err;
5586 
5587 	min_off = reg->smin_value + off;
5588 	max_off = reg->smax_value + off;
5589 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5590 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5591 	return 0;
5592 }
5593 
5594 /* check_stack_read dispatches to check_stack_read_fixed_off or
5595  * check_stack_read_var_off.
5596  *
5597  * The caller must ensure that the offset falls within the allocated stack
5598  * bounds.
5599  *
5600  * 'dst_regno' is a register which will receive the value from the stack. It
5601  * can be -1, meaning that the read value is not going to a register.
5602  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5603 static int check_stack_read(struct bpf_verifier_env *env,
5604 			    int ptr_regno, int off, int size,
5605 			    int dst_regno)
5606 {
5607 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5608 	struct bpf_func_state *state = func(env, reg);
5609 	int err;
5610 	/* Some accesses are only permitted with a static offset. */
5611 	bool var_off = !tnum_is_const(reg->var_off);
5612 
5613 	/* The offset is required to be static when reads don't go to a
5614 	 * register, in order to not leak pointers (see
5615 	 * check_stack_read_fixed_off).
5616 	 */
5617 	if (dst_regno < 0 && var_off) {
5618 		char tn_buf[48];
5619 
5620 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5621 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5622 			tn_buf, off, size);
5623 		return -EACCES;
5624 	}
5625 	/* Variable offset is prohibited for unprivileged mode for simplicity
5626 	 * since it requires corresponding support in Spectre masking for stack
5627 	 * ALU. See also retrieve_ptr_limit(). The check in
5628 	 * check_stack_access_for_ptr_arithmetic() called by
5629 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5630 	 * with variable offsets, therefore no check is required here. Further,
5631 	 * just checking it here would be insufficient as speculative stack
5632 	 * writes could still lead to unsafe speculative behaviour.
5633 	 */
5634 	if (!var_off) {
5635 		off += reg->var_off.value;
5636 		err = check_stack_read_fixed_off(env, state, off, size,
5637 						 dst_regno);
5638 	} else {
5639 		/* Variable offset stack reads need more conservative handling
5640 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5641 		 * branch.
5642 		 */
5643 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5644 					       dst_regno);
5645 	}
5646 	return err;
5647 }
5648 
5649 
5650 /* check_stack_write dispatches to check_stack_write_fixed_off or
5651  * check_stack_write_var_off.
5652  *
5653  * 'ptr_regno' is the register used as a pointer into the stack.
5654  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5655  * 'value_regno' is the register whose value we're writing to the stack. It can
5656  * be -1, meaning that we're not writing from a register.
5657  *
5658  * The caller must ensure that the offset falls within the maximum stack size.
5659  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5660 static int check_stack_write(struct bpf_verifier_env *env,
5661 			     int ptr_regno, int off, int size,
5662 			     int value_regno, int insn_idx)
5663 {
5664 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5665 	struct bpf_func_state *state = func(env, reg);
5666 	int err;
5667 
5668 	if (tnum_is_const(reg->var_off)) {
5669 		off += reg->var_off.value;
5670 		err = check_stack_write_fixed_off(env, state, off, size,
5671 						  value_regno, insn_idx);
5672 	} else {
5673 		/* Variable offset stack reads need more conservative handling
5674 		 * than fixed offset ones.
5675 		 */
5676 		err = check_stack_write_var_off(env, state,
5677 						ptr_regno, off, size,
5678 						value_regno, insn_idx);
5679 	}
5680 	return err;
5681 }
5682 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5683 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5684 				 int off, int size, enum bpf_access_type type)
5685 {
5686 	struct bpf_reg_state *regs = cur_regs(env);
5687 	struct bpf_map *map = regs[regno].map_ptr;
5688 	u32 cap = bpf_map_flags_to_cap(map);
5689 
5690 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5691 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5692 			map->value_size, off, size);
5693 		return -EACCES;
5694 	}
5695 
5696 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5697 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5698 			map->value_size, off, size);
5699 		return -EACCES;
5700 	}
5701 
5702 	return 0;
5703 }
5704 
5705 /* 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)5706 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5707 			      int off, int size, u32 mem_size,
5708 			      bool zero_size_allowed)
5709 {
5710 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5711 	struct bpf_reg_state *reg;
5712 
5713 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5714 		return 0;
5715 
5716 	reg = &cur_regs(env)[regno];
5717 	switch (reg->type) {
5718 	case PTR_TO_MAP_KEY:
5719 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5720 			mem_size, off, size);
5721 		break;
5722 	case PTR_TO_MAP_VALUE:
5723 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5724 			mem_size, off, size);
5725 		break;
5726 	case PTR_TO_PACKET:
5727 	case PTR_TO_PACKET_META:
5728 	case PTR_TO_PACKET_END:
5729 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5730 			off, size, regno, reg->id, off, mem_size);
5731 		break;
5732 	case PTR_TO_MEM:
5733 	default:
5734 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5735 			mem_size, off, size);
5736 	}
5737 
5738 	return -EACCES;
5739 }
5740 
5741 /* 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)5742 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5743 				   int off, int size, u32 mem_size,
5744 				   bool zero_size_allowed)
5745 {
5746 	struct bpf_verifier_state *vstate = env->cur_state;
5747 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5748 	struct bpf_reg_state *reg = &state->regs[regno];
5749 	int err;
5750 
5751 	/* We may have adjusted the register pointing to memory region, so we
5752 	 * need to try adding each of min_value and max_value to off
5753 	 * to make sure our theoretical access will be safe.
5754 	 *
5755 	 * The minimum value is only important with signed
5756 	 * comparisons where we can't assume the floor of a
5757 	 * value is 0.  If we are using signed variables for our
5758 	 * index'es we need to make sure that whatever we use
5759 	 * will have a set floor within our range.
5760 	 */
5761 	if (reg->smin_value < 0 &&
5762 	    (reg->smin_value == S64_MIN ||
5763 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5764 	      reg->smin_value + off < 0)) {
5765 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5766 			regno);
5767 		return -EACCES;
5768 	}
5769 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5770 				 mem_size, zero_size_allowed);
5771 	if (err) {
5772 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5773 			regno);
5774 		return err;
5775 	}
5776 
5777 	/* If we haven't set a max value then we need to bail since we can't be
5778 	 * sure we won't do bad things.
5779 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5780 	 */
5781 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5782 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5783 			regno);
5784 		return -EACCES;
5785 	}
5786 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5787 				 mem_size, zero_size_allowed);
5788 	if (err) {
5789 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5790 			regno);
5791 		return err;
5792 	}
5793 
5794 	return 0;
5795 }
5796 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5797 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5798 			       const struct bpf_reg_state *reg, int regno,
5799 			       bool fixed_off_ok)
5800 {
5801 	/* Access to this pointer-typed register or passing it to a helper
5802 	 * is only allowed in its original, unmodified form.
5803 	 */
5804 
5805 	if (reg->off < 0) {
5806 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5807 			reg_type_str(env, reg->type), regno, reg->off);
5808 		return -EACCES;
5809 	}
5810 
5811 	if (!fixed_off_ok && reg->off) {
5812 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5813 			reg_type_str(env, reg->type), regno, reg->off);
5814 		return -EACCES;
5815 	}
5816 
5817 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5818 		char tn_buf[48];
5819 
5820 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5821 		verbose(env, "variable %s access var_off=%s disallowed\n",
5822 			reg_type_str(env, reg->type), tn_buf);
5823 		return -EACCES;
5824 	}
5825 
5826 	return 0;
5827 }
5828 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5829 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5830 		             const struct bpf_reg_state *reg, int regno)
5831 {
5832 	return __check_ptr_off_reg(env, reg, regno, false);
5833 }
5834 
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5835 static int map_kptr_match_type(struct bpf_verifier_env *env,
5836 			       struct btf_field *kptr_field,
5837 			       struct bpf_reg_state *reg, u32 regno)
5838 {
5839 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5840 	int perm_flags;
5841 	const char *reg_name = "";
5842 
5843 	if (btf_is_kernel(reg->btf)) {
5844 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5845 
5846 		/* Only unreferenced case accepts untrusted pointers */
5847 		if (kptr_field->type == BPF_KPTR_UNREF)
5848 			perm_flags |= PTR_UNTRUSTED;
5849 	} else {
5850 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5851 		if (kptr_field->type == BPF_KPTR_PERCPU)
5852 			perm_flags |= MEM_PERCPU;
5853 	}
5854 
5855 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5856 		goto bad_type;
5857 
5858 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5859 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5860 
5861 	/* For ref_ptr case, release function check should ensure we get one
5862 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5863 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5864 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5865 	 * reg->off and reg->ref_obj_id are not needed here.
5866 	 */
5867 	if (__check_ptr_off_reg(env, reg, regno, true))
5868 		return -EACCES;
5869 
5870 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5871 	 * we also need to take into account the reg->off.
5872 	 *
5873 	 * We want to support cases like:
5874 	 *
5875 	 * struct foo {
5876 	 *         struct bar br;
5877 	 *         struct baz bz;
5878 	 * };
5879 	 *
5880 	 * struct foo *v;
5881 	 * v = func();	      // PTR_TO_BTF_ID
5882 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5883 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5884 	 *                    // first member type of struct after comparison fails
5885 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5886 	 *                    // to match type
5887 	 *
5888 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5889 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5890 	 * the struct to match type against first member of struct, i.e. reject
5891 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5892 	 * strict mode to true for type match.
5893 	 */
5894 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5895 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5896 				  kptr_field->type != BPF_KPTR_UNREF))
5897 		goto bad_type;
5898 	return 0;
5899 bad_type:
5900 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5901 		reg_type_str(env, reg->type), reg_name);
5902 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5903 	if (kptr_field->type == BPF_KPTR_UNREF)
5904 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5905 			targ_name);
5906 	else
5907 		verbose(env, "\n");
5908 	return -EINVAL;
5909 }
5910 
in_sleepable(struct bpf_verifier_env * env)5911 static bool in_sleepable(struct bpf_verifier_env *env)
5912 {
5913 	return env->prog->sleepable ||
5914 	       (env->cur_state && env->cur_state->in_sleepable);
5915 }
5916 
5917 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5918  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5919  */
in_rcu_cs(struct bpf_verifier_env * env)5920 static bool in_rcu_cs(struct bpf_verifier_env *env)
5921 {
5922 	return env->cur_state->active_rcu_lock ||
5923 	       env->cur_state->active_locks ||
5924 	       !in_sleepable(env);
5925 }
5926 
5927 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5928 BTF_SET_START(rcu_protected_types)
5929 #ifdef CONFIG_NET
BTF_ID(struct,prog_test_ref_kfunc)5930 BTF_ID(struct, prog_test_ref_kfunc)
5931 #endif
5932 #ifdef CONFIG_CGROUPS
5933 BTF_ID(struct, cgroup)
5934 #endif
5935 #ifdef CONFIG_BPF_JIT
5936 BTF_ID(struct, bpf_cpumask)
5937 #endif
5938 BTF_ID(struct, task_struct)
5939 #ifdef CONFIG_CRYPTO
5940 BTF_ID(struct, bpf_crypto_ctx)
5941 #endif
5942 BTF_SET_END(rcu_protected_types)
5943 
5944 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5945 {
5946 	if (!btf_is_kernel(btf))
5947 		return true;
5948 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5949 }
5950 
kptr_pointee_btf_record(struct btf_field * kptr_field)5951 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5952 {
5953 	struct btf_struct_meta *meta;
5954 
5955 	if (btf_is_kernel(kptr_field->kptr.btf))
5956 		return NULL;
5957 
5958 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5959 				    kptr_field->kptr.btf_id);
5960 
5961 	return meta ? meta->record : NULL;
5962 }
5963 
rcu_safe_kptr(const struct btf_field * field)5964 static bool rcu_safe_kptr(const struct btf_field *field)
5965 {
5966 	const struct btf_field_kptr *kptr = &field->kptr;
5967 
5968 	return field->type == BPF_KPTR_PERCPU ||
5969 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5970 }
5971 
btf_ld_kptr_type(struct bpf_verifier_env * env,struct btf_field * kptr_field)5972 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5973 {
5974 	struct btf_record *rec;
5975 	u32 ret;
5976 
5977 	ret = PTR_MAYBE_NULL;
5978 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5979 		ret |= MEM_RCU;
5980 		if (kptr_field->type == BPF_KPTR_PERCPU)
5981 			ret |= MEM_PERCPU;
5982 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5983 			ret |= MEM_ALLOC;
5984 
5985 		rec = kptr_pointee_btf_record(kptr_field);
5986 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5987 			ret |= NON_OWN_REF;
5988 	} else {
5989 		ret |= PTR_UNTRUSTED;
5990 	}
5991 
5992 	return ret;
5993 }
5994 
mark_uptr_ld_reg(struct bpf_verifier_env * env,u32 regno,struct btf_field * field)5995 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5996 			    struct btf_field *field)
5997 {
5998 	struct bpf_reg_state *reg;
5999 	const struct btf_type *t;
6000 
6001 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
6002 	mark_reg_known_zero(env, cur_regs(env), regno);
6003 	reg = reg_state(env, regno);
6004 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6005 	reg->mem_size = t->size;
6006 	reg->id = ++env->id_gen;
6007 
6008 	return 0;
6009 }
6010 
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)6011 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
6012 				 int value_regno, int insn_idx,
6013 				 struct btf_field *kptr_field)
6014 {
6015 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
6016 	int class = BPF_CLASS(insn->code);
6017 	struct bpf_reg_state *val_reg;
6018 	int ret;
6019 
6020 	/* Things we already checked for in check_map_access and caller:
6021 	 *  - Reject cases where variable offset may touch kptr
6022 	 *  - size of access (must be BPF_DW)
6023 	 *  - tnum_is_const(reg->var_off)
6024 	 *  - kptr_field->offset == off + reg->var_off.value
6025 	 */
6026 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
6027 	if (BPF_MODE(insn->code) != BPF_MEM) {
6028 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
6029 		return -EACCES;
6030 	}
6031 
6032 	/* We only allow loading referenced kptr, since it will be marked as
6033 	 * untrusted, similar to unreferenced kptr.
6034 	 */
6035 	if (class != BPF_LDX &&
6036 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6037 		verbose(env, "store to referenced kptr disallowed\n");
6038 		return -EACCES;
6039 	}
6040 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6041 		verbose(env, "store to uptr disallowed\n");
6042 		return -EACCES;
6043 	}
6044 
6045 	if (class == BPF_LDX) {
6046 		if (kptr_field->type == BPF_UPTR)
6047 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
6048 
6049 		/* We can simply mark the value_regno receiving the pointer
6050 		 * value from map as PTR_TO_BTF_ID, with the correct type.
6051 		 */
6052 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6053 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6054 				      btf_ld_kptr_type(env, kptr_field));
6055 		if (ret < 0)
6056 			return ret;
6057 	} else if (class == BPF_STX) {
6058 		val_reg = reg_state(env, value_regno);
6059 		if (!register_is_null(val_reg) &&
6060 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6061 			return -EACCES;
6062 	} else if (class == BPF_ST) {
6063 		if (insn->imm) {
6064 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6065 				kptr_field->offset);
6066 			return -EACCES;
6067 		}
6068 	} else {
6069 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6070 		return -EACCES;
6071 	}
6072 	return 0;
6073 }
6074 
6075 /* 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)6076 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6077 			    int off, int size, bool zero_size_allowed,
6078 			    enum bpf_access_src src)
6079 {
6080 	struct bpf_verifier_state *vstate = env->cur_state;
6081 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6082 	struct bpf_reg_state *reg = &state->regs[regno];
6083 	struct bpf_map *map = reg->map_ptr;
6084 	struct btf_record *rec;
6085 	int err, i;
6086 
6087 	err = check_mem_region_access(env, regno, off, size, map->value_size,
6088 				      zero_size_allowed);
6089 	if (err)
6090 		return err;
6091 
6092 	if (IS_ERR_OR_NULL(map->record))
6093 		return 0;
6094 	rec = map->record;
6095 	for (i = 0; i < rec->cnt; i++) {
6096 		struct btf_field *field = &rec->fields[i];
6097 		u32 p = field->offset;
6098 
6099 		/* If any part of a field  can be touched by load/store, reject
6100 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6101 		 * it is sufficient to check x1 < y2 && y1 < x2.
6102 		 */
6103 		if (reg->smin_value + off < p + field->size &&
6104 		    p < reg->umax_value + off + size) {
6105 			switch (field->type) {
6106 			case BPF_KPTR_UNREF:
6107 			case BPF_KPTR_REF:
6108 			case BPF_KPTR_PERCPU:
6109 			case BPF_UPTR:
6110 				if (src != ACCESS_DIRECT) {
6111 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6112 						btf_field_type_name(field->type));
6113 					return -EACCES;
6114 				}
6115 				if (!tnum_is_const(reg->var_off)) {
6116 					verbose(env, "%s access cannot have variable offset\n",
6117 						btf_field_type_name(field->type));
6118 					return -EACCES;
6119 				}
6120 				if (p != off + reg->var_off.value) {
6121 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6122 						btf_field_type_name(field->type),
6123 						p, off + reg->var_off.value);
6124 					return -EACCES;
6125 				}
6126 				if (size != bpf_size_to_bytes(BPF_DW)) {
6127 					verbose(env, "%s access size must be BPF_DW\n",
6128 						btf_field_type_name(field->type));
6129 					return -EACCES;
6130 				}
6131 				break;
6132 			default:
6133 				verbose(env, "%s cannot be accessed directly by load/store\n",
6134 					btf_field_type_name(field->type));
6135 				return -EACCES;
6136 			}
6137 		}
6138 	}
6139 	return 0;
6140 }
6141 
6142 #define MAX_PACKET_OFF 0xffff
6143 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)6144 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6145 				       const struct bpf_call_arg_meta *meta,
6146 				       enum bpf_access_type t)
6147 {
6148 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6149 
6150 	switch (prog_type) {
6151 	/* Program types only with direct read access go here! */
6152 	case BPF_PROG_TYPE_LWT_IN:
6153 	case BPF_PROG_TYPE_LWT_OUT:
6154 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6155 	case BPF_PROG_TYPE_SK_REUSEPORT:
6156 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6157 	case BPF_PROG_TYPE_CGROUP_SKB:
6158 		if (t == BPF_WRITE)
6159 			return false;
6160 		fallthrough;
6161 
6162 	/* Program types with direct read + write access go here! */
6163 	case BPF_PROG_TYPE_SCHED_CLS:
6164 	case BPF_PROG_TYPE_SCHED_ACT:
6165 	case BPF_PROG_TYPE_XDP:
6166 	case BPF_PROG_TYPE_LWT_XMIT:
6167 	case BPF_PROG_TYPE_SK_SKB:
6168 	case BPF_PROG_TYPE_SK_MSG:
6169 		if (meta)
6170 			return meta->pkt_access;
6171 
6172 		env->seen_direct_write = true;
6173 		return true;
6174 
6175 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6176 		if (t == BPF_WRITE)
6177 			env->seen_direct_write = true;
6178 
6179 		return true;
6180 
6181 	default:
6182 		return false;
6183 	}
6184 }
6185 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)6186 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6187 			       int size, bool zero_size_allowed)
6188 {
6189 	struct bpf_reg_state *regs = cur_regs(env);
6190 	struct bpf_reg_state *reg = &regs[regno];
6191 	int err;
6192 
6193 	/* We may have added a variable offset to the packet pointer; but any
6194 	 * reg->range we have comes after that.  We are only checking the fixed
6195 	 * offset.
6196 	 */
6197 
6198 	/* We don't allow negative numbers, because we aren't tracking enough
6199 	 * detail to prove they're safe.
6200 	 */
6201 	if (reg->smin_value < 0) {
6202 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6203 			regno);
6204 		return -EACCES;
6205 	}
6206 
6207 	err = reg->range < 0 ? -EINVAL :
6208 	      __check_mem_access(env, regno, off, size, reg->range,
6209 				 zero_size_allowed);
6210 	if (err) {
6211 		verbose(env, "R%d offset is outside of the packet\n", regno);
6212 		return err;
6213 	}
6214 
6215 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6216 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6217 	 * otherwise find_good_pkt_pointers would have refused to set range info
6218 	 * that __check_mem_access would have rejected this pkt access.
6219 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6220 	 */
6221 	env->prog->aux->max_pkt_offset =
6222 		max_t(u32, env->prog->aux->max_pkt_offset,
6223 		      off + reg->umax_value + size - 1);
6224 
6225 	return err;
6226 }
6227 
6228 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,struct bpf_insn_access_aux * info)6229 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6230 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6231 {
6232 	if (env->ops->is_valid_access &&
6233 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6234 		/* A non zero info.ctx_field_size indicates that this field is a
6235 		 * candidate for later verifier transformation to load the whole
6236 		 * field and then apply a mask when accessed with a narrower
6237 		 * access than actual ctx access size. A zero info.ctx_field_size
6238 		 * will only allow for whole field access and rejects any other
6239 		 * type of narrower access.
6240 		 */
6241 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6242 			if (info->ref_obj_id &&
6243 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6244 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6245 					off);
6246 				return -EACCES;
6247 			}
6248 		} else {
6249 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6250 		}
6251 		/* remember the offset of last byte accessed in ctx */
6252 		if (env->prog->aux->max_ctx_offset < off + size)
6253 			env->prog->aux->max_ctx_offset = off + size;
6254 		return 0;
6255 	}
6256 
6257 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6258 	return -EACCES;
6259 }
6260 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)6261 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6262 				  int size)
6263 {
6264 	if (size < 0 || off < 0 ||
6265 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6266 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6267 			off, size);
6268 		return -EACCES;
6269 	}
6270 	return 0;
6271 }
6272 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)6273 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6274 			     u32 regno, int off, int size,
6275 			     enum bpf_access_type t)
6276 {
6277 	struct bpf_reg_state *regs = cur_regs(env);
6278 	struct bpf_reg_state *reg = &regs[regno];
6279 	struct bpf_insn_access_aux info = {};
6280 	bool valid;
6281 
6282 	if (reg->smin_value < 0) {
6283 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6284 			regno);
6285 		return -EACCES;
6286 	}
6287 
6288 	switch (reg->type) {
6289 	case PTR_TO_SOCK_COMMON:
6290 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6291 		break;
6292 	case PTR_TO_SOCKET:
6293 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6294 		break;
6295 	case PTR_TO_TCP_SOCK:
6296 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6297 		break;
6298 	case PTR_TO_XDP_SOCK:
6299 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6300 		break;
6301 	default:
6302 		valid = false;
6303 	}
6304 
6305 
6306 	if (valid) {
6307 		env->insn_aux_data[insn_idx].ctx_field_size =
6308 			info.ctx_field_size;
6309 		return 0;
6310 	}
6311 
6312 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6313 		regno, reg_type_str(env, reg->type), off, size);
6314 
6315 	return -EACCES;
6316 }
6317 
is_pointer_value(struct bpf_verifier_env * env,int regno)6318 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6319 {
6320 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6321 }
6322 
is_ctx_reg(struct bpf_verifier_env * env,int regno)6323 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6324 {
6325 	const struct bpf_reg_state *reg = reg_state(env, regno);
6326 
6327 	return reg->type == PTR_TO_CTX;
6328 }
6329 
is_sk_reg(struct bpf_verifier_env * env,int regno)6330 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6331 {
6332 	const struct bpf_reg_state *reg = reg_state(env, regno);
6333 
6334 	return type_is_sk_pointer(reg->type);
6335 }
6336 
is_pkt_reg(struct bpf_verifier_env * env,int regno)6337 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6338 {
6339 	const struct bpf_reg_state *reg = reg_state(env, regno);
6340 
6341 	return type_is_pkt_pointer(reg->type);
6342 }
6343 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)6344 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6345 {
6346 	const struct bpf_reg_state *reg = reg_state(env, regno);
6347 
6348 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6349 	return reg->type == PTR_TO_FLOW_KEYS;
6350 }
6351 
is_arena_reg(struct bpf_verifier_env * env,int regno)6352 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6353 {
6354 	const struct bpf_reg_state *reg = reg_state(env, regno);
6355 
6356 	return reg->type == PTR_TO_ARENA;
6357 }
6358 
6359 /* Return false if @regno contains a pointer whose type isn't supported for
6360  * atomic instruction @insn.
6361  */
atomic_ptr_type_ok(struct bpf_verifier_env * env,int regno,struct bpf_insn * insn)6362 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6363 			       struct bpf_insn *insn)
6364 {
6365 	if (is_ctx_reg(env, regno))
6366 		return false;
6367 	if (is_pkt_reg(env, regno))
6368 		return false;
6369 	if (is_flow_key_reg(env, regno))
6370 		return false;
6371 	if (is_sk_reg(env, regno))
6372 		return false;
6373 	if (is_arena_reg(env, regno))
6374 		return bpf_jit_supports_insn(insn, true);
6375 
6376 	return true;
6377 }
6378 
6379 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6380 #ifdef CONFIG_NET
6381 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6382 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6383 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6384 #endif
6385 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6386 };
6387 
is_trusted_reg(const struct bpf_reg_state * reg)6388 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6389 {
6390 	/* A referenced register is always trusted. */
6391 	if (reg->ref_obj_id)
6392 		return true;
6393 
6394 	/* Types listed in the reg2btf_ids are always trusted */
6395 	if (reg2btf_ids[base_type(reg->type)] &&
6396 	    !bpf_type_has_unsafe_modifiers(reg->type))
6397 		return true;
6398 
6399 	/* If a register is not referenced, it is trusted if it has the
6400 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6401 	 * other type modifiers may be safe, but we elect to take an opt-in
6402 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6403 	 * not.
6404 	 *
6405 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6406 	 * for whether a register is trusted.
6407 	 */
6408 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6409 	       !bpf_type_has_unsafe_modifiers(reg->type);
6410 }
6411 
is_rcu_reg(const struct bpf_reg_state * reg)6412 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6413 {
6414 	return reg->type & MEM_RCU;
6415 }
6416 
clear_trusted_flags(enum bpf_type_flag * flag)6417 static void clear_trusted_flags(enum bpf_type_flag *flag)
6418 {
6419 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6420 }
6421 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)6422 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6423 				   const struct bpf_reg_state *reg,
6424 				   int off, int size, bool strict)
6425 {
6426 	struct tnum reg_off;
6427 	int ip_align;
6428 
6429 	/* Byte size accesses are always allowed. */
6430 	if (!strict || size == 1)
6431 		return 0;
6432 
6433 	/* For platforms that do not have a Kconfig enabling
6434 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6435 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6436 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6437 	 * to this code only in strict mode where we want to emulate
6438 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6439 	 * unconditional IP align value of '2'.
6440 	 */
6441 	ip_align = 2;
6442 
6443 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6444 	if (!tnum_is_aligned(reg_off, size)) {
6445 		char tn_buf[48];
6446 
6447 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6448 		verbose(env,
6449 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6450 			ip_align, tn_buf, reg->off, off, size);
6451 		return -EACCES;
6452 	}
6453 
6454 	return 0;
6455 }
6456 
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)6457 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6458 				       const struct bpf_reg_state *reg,
6459 				       const char *pointer_desc,
6460 				       int off, int size, bool strict)
6461 {
6462 	struct tnum reg_off;
6463 
6464 	/* Byte size accesses are always allowed. */
6465 	if (!strict || size == 1)
6466 		return 0;
6467 
6468 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6469 	if (!tnum_is_aligned(reg_off, size)) {
6470 		char tn_buf[48];
6471 
6472 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6473 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6474 			pointer_desc, tn_buf, reg->off, off, size);
6475 		return -EACCES;
6476 	}
6477 
6478 	return 0;
6479 }
6480 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)6481 static int check_ptr_alignment(struct bpf_verifier_env *env,
6482 			       const struct bpf_reg_state *reg, int off,
6483 			       int size, bool strict_alignment_once)
6484 {
6485 	bool strict = env->strict_alignment || strict_alignment_once;
6486 	const char *pointer_desc = "";
6487 
6488 	switch (reg->type) {
6489 	case PTR_TO_PACKET:
6490 	case PTR_TO_PACKET_META:
6491 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6492 		 * right in front, treat it the very same way.
6493 		 */
6494 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6495 	case PTR_TO_FLOW_KEYS:
6496 		pointer_desc = "flow keys ";
6497 		break;
6498 	case PTR_TO_MAP_KEY:
6499 		pointer_desc = "key ";
6500 		break;
6501 	case PTR_TO_MAP_VALUE:
6502 		pointer_desc = "value ";
6503 		break;
6504 	case PTR_TO_CTX:
6505 		pointer_desc = "context ";
6506 		break;
6507 	case PTR_TO_STACK:
6508 		pointer_desc = "stack ";
6509 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6510 		 * and check_stack_read_fixed_off() relies on stack accesses being
6511 		 * aligned.
6512 		 */
6513 		strict = true;
6514 		break;
6515 	case PTR_TO_SOCKET:
6516 		pointer_desc = "sock ";
6517 		break;
6518 	case PTR_TO_SOCK_COMMON:
6519 		pointer_desc = "sock_common ";
6520 		break;
6521 	case PTR_TO_TCP_SOCK:
6522 		pointer_desc = "tcp_sock ";
6523 		break;
6524 	case PTR_TO_XDP_SOCK:
6525 		pointer_desc = "xdp_sock ";
6526 		break;
6527 	case PTR_TO_ARENA:
6528 		return 0;
6529 	default:
6530 		break;
6531 	}
6532 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6533 					   strict);
6534 }
6535 
bpf_enable_priv_stack(struct bpf_prog * prog)6536 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6537 {
6538 	if (!bpf_jit_supports_private_stack())
6539 		return NO_PRIV_STACK;
6540 
6541 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6542 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6543 	 * explicitly.
6544 	 */
6545 	switch (prog->type) {
6546 	case BPF_PROG_TYPE_KPROBE:
6547 	case BPF_PROG_TYPE_TRACEPOINT:
6548 	case BPF_PROG_TYPE_PERF_EVENT:
6549 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6550 		return PRIV_STACK_ADAPTIVE;
6551 	case BPF_PROG_TYPE_TRACING:
6552 	case BPF_PROG_TYPE_LSM:
6553 	case BPF_PROG_TYPE_STRUCT_OPS:
6554 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6555 			return PRIV_STACK_ADAPTIVE;
6556 		fallthrough;
6557 	default:
6558 		break;
6559 	}
6560 
6561 	return NO_PRIV_STACK;
6562 }
6563 
round_up_stack_depth(struct bpf_verifier_env * env,int stack_depth)6564 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6565 {
6566 	if (env->prog->jit_requested)
6567 		return round_up(stack_depth, 16);
6568 
6569 	/* round up to 32-bytes, since this is granularity
6570 	 * of interpreter stack size
6571 	 */
6572 	return round_up(max_t(u32, stack_depth, 1), 32);
6573 }
6574 
6575 /* starting from main bpf function walk all instructions of the function
6576  * and recursively walk all callees that given function can call.
6577  * Ignore jump and exit insns.
6578  * Since recursion is prevented by check_cfg() this algorithm
6579  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6580  */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx,bool priv_stack_supported)6581 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6582 					 bool priv_stack_supported)
6583 {
6584 	struct bpf_subprog_info *subprog = env->subprog_info;
6585 	struct bpf_insn *insn = env->prog->insnsi;
6586 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6587 	bool tail_call_reachable = false;
6588 	int ret_insn[MAX_CALL_FRAMES];
6589 	int ret_prog[MAX_CALL_FRAMES];
6590 	int j;
6591 
6592 	i = subprog[idx].start;
6593 	if (!priv_stack_supported)
6594 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6595 process_func:
6596 	/* protect against potential stack overflow that might happen when
6597 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6598 	 * depth for such case down to 256 so that the worst case scenario
6599 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6600 	 * 8k).
6601 	 *
6602 	 * To get the idea what might happen, see an example:
6603 	 * func1 -> sub rsp, 128
6604 	 *  subfunc1 -> sub rsp, 256
6605 	 *  tailcall1 -> add rsp, 256
6606 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6607 	 *   subfunc2 -> sub rsp, 64
6608 	 *   subfunc22 -> sub rsp, 128
6609 	 *   tailcall2 -> add rsp, 128
6610 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6611 	 *
6612 	 * tailcall will unwind the current stack frame but it will not get rid
6613 	 * of caller's stack as shown on the example above.
6614 	 */
6615 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6616 		verbose(env,
6617 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6618 			depth);
6619 		return -EACCES;
6620 	}
6621 
6622 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6623 	if (priv_stack_supported) {
6624 		/* Request private stack support only if the subprog stack
6625 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6626 		 * avoid jit penalty if the stack usage is small.
6627 		 */
6628 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6629 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6630 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6631 	}
6632 
6633 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6634 		if (subprog_depth > MAX_BPF_STACK) {
6635 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6636 				idx, subprog_depth);
6637 			return -EACCES;
6638 		}
6639 	} else {
6640 		depth += subprog_depth;
6641 		if (depth > MAX_BPF_STACK) {
6642 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6643 				frame + 1, depth);
6644 			return -EACCES;
6645 		}
6646 	}
6647 continue_func:
6648 	subprog_end = subprog[idx + 1].start;
6649 	for (; i < subprog_end; i++) {
6650 		int next_insn, sidx;
6651 
6652 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6653 			bool err = false;
6654 
6655 			if (!is_bpf_throw_kfunc(insn + i))
6656 				continue;
6657 			if (subprog[idx].is_cb)
6658 				err = true;
6659 			for (int c = 0; c < frame && !err; c++) {
6660 				if (subprog[ret_prog[c]].is_cb) {
6661 					err = true;
6662 					break;
6663 				}
6664 			}
6665 			if (!err)
6666 				continue;
6667 			verbose(env,
6668 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6669 				i, idx);
6670 			return -EINVAL;
6671 		}
6672 
6673 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6674 			continue;
6675 		/* remember insn and function to return to */
6676 		ret_insn[frame] = i + 1;
6677 		ret_prog[frame] = idx;
6678 
6679 		/* find the callee */
6680 		next_insn = i + insn[i].imm + 1;
6681 		sidx = find_subprog(env, next_insn);
6682 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6683 			return -EFAULT;
6684 		if (subprog[sidx].is_async_cb) {
6685 			if (subprog[sidx].has_tail_call) {
6686 				verifier_bug(env, "subprog has tail_call and async cb");
6687 				return -EFAULT;
6688 			}
6689 			/* async callbacks don't increase bpf prog stack size unless called directly */
6690 			if (!bpf_pseudo_call(insn + i))
6691 				continue;
6692 			if (subprog[sidx].is_exception_cb) {
6693 				verbose(env, "insn %d cannot call exception cb directly", i);
6694 				return -EINVAL;
6695 			}
6696 		}
6697 		i = next_insn;
6698 		idx = sidx;
6699 		if (!priv_stack_supported)
6700 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6701 
6702 		if (subprog[idx].has_tail_call)
6703 			tail_call_reachable = true;
6704 
6705 		frame++;
6706 		if (frame >= MAX_CALL_FRAMES) {
6707 			verbose(env, "the call stack of %d frames is too deep !\n",
6708 				frame);
6709 			return -E2BIG;
6710 		}
6711 		goto process_func;
6712 	}
6713 	/* if tail call got detected across bpf2bpf calls then mark each of the
6714 	 * currently present subprog frames as tail call reachable subprogs;
6715 	 * this info will be utilized by JIT so that we will be preserving the
6716 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6717 	 */
6718 	if (tail_call_reachable)
6719 		for (j = 0; j < frame; j++) {
6720 			if (subprog[ret_prog[j]].is_exception_cb) {
6721 				verbose(env, "cannot tail call within exception cb\n");
6722 				return -EINVAL;
6723 			}
6724 			subprog[ret_prog[j]].tail_call_reachable = true;
6725 		}
6726 	if (subprog[0].tail_call_reachable)
6727 		env->prog->aux->tail_call_reachable = true;
6728 
6729 	/* end of for() loop means the last insn of the 'subprog'
6730 	 * was reached. Doesn't matter whether it was JA or EXIT
6731 	 */
6732 	if (frame == 0)
6733 		return 0;
6734 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6735 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6736 	frame--;
6737 	i = ret_insn[frame];
6738 	idx = ret_prog[frame];
6739 	goto continue_func;
6740 }
6741 
check_max_stack_depth(struct bpf_verifier_env * env)6742 static int check_max_stack_depth(struct bpf_verifier_env *env)
6743 {
6744 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6745 	struct bpf_subprog_info *si = env->subprog_info;
6746 	bool priv_stack_supported;
6747 	int ret;
6748 
6749 	for (int i = 0; i < env->subprog_cnt; i++) {
6750 		if (si[i].has_tail_call) {
6751 			priv_stack_mode = NO_PRIV_STACK;
6752 			break;
6753 		}
6754 	}
6755 
6756 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6757 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6758 
6759 	/* All async_cb subprogs use normal kernel stack. If a particular
6760 	 * subprog appears in both main prog and async_cb subtree, that
6761 	 * subprog will use normal kernel stack to avoid potential nesting.
6762 	 * The reverse subprog traversal ensures when main prog subtree is
6763 	 * checked, the subprogs appearing in async_cb subtrees are already
6764 	 * marked as using normal kernel stack, so stack size checking can
6765 	 * be done properly.
6766 	 */
6767 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6768 		if (!i || si[i].is_async_cb) {
6769 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6770 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6771 			if (ret < 0)
6772 				return ret;
6773 		}
6774 	}
6775 
6776 	for (int i = 0; i < env->subprog_cnt; i++) {
6777 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6778 			env->prog->aux->jits_use_priv_stack = true;
6779 			break;
6780 		}
6781 	}
6782 
6783 	return 0;
6784 }
6785 
6786 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)6787 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6788 				  const struct bpf_insn *insn, int idx)
6789 {
6790 	int start = idx + insn->imm + 1, subprog;
6791 
6792 	subprog = find_subprog(env, start);
6793 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6794 		return -EFAULT;
6795 	return env->subprog_info[subprog].stack_depth;
6796 }
6797 #endif
6798 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)6799 static int __check_buffer_access(struct bpf_verifier_env *env,
6800 				 const char *buf_info,
6801 				 const struct bpf_reg_state *reg,
6802 				 int regno, int off, int size)
6803 {
6804 	if (off < 0) {
6805 		verbose(env,
6806 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6807 			regno, buf_info, off, size);
6808 		return -EACCES;
6809 	}
6810 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6811 		char tn_buf[48];
6812 
6813 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6814 		verbose(env,
6815 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6816 			regno, off, tn_buf);
6817 		return -EACCES;
6818 	}
6819 
6820 	return 0;
6821 }
6822 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)6823 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6824 				  const struct bpf_reg_state *reg,
6825 				  int regno, int off, int size)
6826 {
6827 	int err;
6828 
6829 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6830 	if (err)
6831 		return err;
6832 
6833 	if (off + size > env->prog->aux->max_tp_access)
6834 		env->prog->aux->max_tp_access = off + size;
6835 
6836 	return 0;
6837 }
6838 
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)6839 static int check_buffer_access(struct bpf_verifier_env *env,
6840 			       const struct bpf_reg_state *reg,
6841 			       int regno, int off, int size,
6842 			       bool zero_size_allowed,
6843 			       u32 *max_access)
6844 {
6845 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6846 	int err;
6847 
6848 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6849 	if (err)
6850 		return err;
6851 
6852 	if (off + size > *max_access)
6853 		*max_access = off + size;
6854 
6855 	return 0;
6856 }
6857 
6858 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6859 static void zext_32_to_64(struct bpf_reg_state *reg)
6860 {
6861 	reg->var_off = tnum_subreg(reg->var_off);
6862 	__reg_assign_32_into_64(reg);
6863 }
6864 
6865 /* truncate register to smaller size (in bytes)
6866  * must be called with size < BPF_REG_SIZE
6867  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6868 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6869 {
6870 	u64 mask;
6871 
6872 	/* clear high bits in bit representation */
6873 	reg->var_off = tnum_cast(reg->var_off, size);
6874 
6875 	/* fix arithmetic bounds */
6876 	mask = ((u64)1 << (size * 8)) - 1;
6877 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6878 		reg->umin_value &= mask;
6879 		reg->umax_value &= mask;
6880 	} else {
6881 		reg->umin_value = 0;
6882 		reg->umax_value = mask;
6883 	}
6884 	reg->smin_value = reg->umin_value;
6885 	reg->smax_value = reg->umax_value;
6886 
6887 	/* If size is smaller than 32bit register the 32bit register
6888 	 * values are also truncated so we push 64-bit bounds into
6889 	 * 32-bit bounds. Above were truncated < 32-bits already.
6890 	 */
6891 	if (size < 4)
6892 		__mark_reg32_unbounded(reg);
6893 
6894 	reg_bounds_sync(reg);
6895 }
6896 
set_sext64_default_val(struct bpf_reg_state * reg,int size)6897 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6898 {
6899 	if (size == 1) {
6900 		reg->smin_value = reg->s32_min_value = S8_MIN;
6901 		reg->smax_value = reg->s32_max_value = S8_MAX;
6902 	} else if (size == 2) {
6903 		reg->smin_value = reg->s32_min_value = S16_MIN;
6904 		reg->smax_value = reg->s32_max_value = S16_MAX;
6905 	} else {
6906 		/* size == 4 */
6907 		reg->smin_value = reg->s32_min_value = S32_MIN;
6908 		reg->smax_value = reg->s32_max_value = S32_MAX;
6909 	}
6910 	reg->umin_value = reg->u32_min_value = 0;
6911 	reg->umax_value = U64_MAX;
6912 	reg->u32_max_value = U32_MAX;
6913 	reg->var_off = tnum_unknown;
6914 }
6915 
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6916 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6917 {
6918 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6919 	u64 top_smax_value, top_smin_value;
6920 	u64 num_bits = size * 8;
6921 
6922 	if (tnum_is_const(reg->var_off)) {
6923 		u64_cval = reg->var_off.value;
6924 		if (size == 1)
6925 			reg->var_off = tnum_const((s8)u64_cval);
6926 		else if (size == 2)
6927 			reg->var_off = tnum_const((s16)u64_cval);
6928 		else
6929 			/* size == 4 */
6930 			reg->var_off = tnum_const((s32)u64_cval);
6931 
6932 		u64_cval = reg->var_off.value;
6933 		reg->smax_value = reg->smin_value = u64_cval;
6934 		reg->umax_value = reg->umin_value = u64_cval;
6935 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6936 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6937 		return;
6938 	}
6939 
6940 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6941 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6942 
6943 	if (top_smax_value != top_smin_value)
6944 		goto out;
6945 
6946 	/* find the s64_min and s64_min after sign extension */
6947 	if (size == 1) {
6948 		init_s64_max = (s8)reg->smax_value;
6949 		init_s64_min = (s8)reg->smin_value;
6950 	} else if (size == 2) {
6951 		init_s64_max = (s16)reg->smax_value;
6952 		init_s64_min = (s16)reg->smin_value;
6953 	} else {
6954 		init_s64_max = (s32)reg->smax_value;
6955 		init_s64_min = (s32)reg->smin_value;
6956 	}
6957 
6958 	s64_max = max(init_s64_max, init_s64_min);
6959 	s64_min = min(init_s64_max, init_s64_min);
6960 
6961 	/* both of s64_max/s64_min positive or negative */
6962 	if ((s64_max >= 0) == (s64_min >= 0)) {
6963 		reg->s32_min_value = reg->smin_value = s64_min;
6964 		reg->s32_max_value = reg->smax_value = s64_max;
6965 		reg->u32_min_value = reg->umin_value = s64_min;
6966 		reg->u32_max_value = reg->umax_value = s64_max;
6967 		reg->var_off = tnum_range(s64_min, s64_max);
6968 		return;
6969 	}
6970 
6971 out:
6972 	set_sext64_default_val(reg, size);
6973 }
6974 
set_sext32_default_val(struct bpf_reg_state * reg,int size)6975 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6976 {
6977 	if (size == 1) {
6978 		reg->s32_min_value = S8_MIN;
6979 		reg->s32_max_value = S8_MAX;
6980 	} else {
6981 		/* size == 2 */
6982 		reg->s32_min_value = S16_MIN;
6983 		reg->s32_max_value = S16_MAX;
6984 	}
6985 	reg->u32_min_value = 0;
6986 	reg->u32_max_value = U32_MAX;
6987 	reg->var_off = tnum_subreg(tnum_unknown);
6988 }
6989 
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6990 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6991 {
6992 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6993 	u32 top_smax_value, top_smin_value;
6994 	u32 num_bits = size * 8;
6995 
6996 	if (tnum_is_const(reg->var_off)) {
6997 		u32_val = reg->var_off.value;
6998 		if (size == 1)
6999 			reg->var_off = tnum_const((s8)u32_val);
7000 		else
7001 			reg->var_off = tnum_const((s16)u32_val);
7002 
7003 		u32_val = reg->var_off.value;
7004 		reg->s32_min_value = reg->s32_max_value = u32_val;
7005 		reg->u32_min_value = reg->u32_max_value = u32_val;
7006 		return;
7007 	}
7008 
7009 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
7010 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
7011 
7012 	if (top_smax_value != top_smin_value)
7013 		goto out;
7014 
7015 	/* find the s32_min and s32_min after sign extension */
7016 	if (size == 1) {
7017 		init_s32_max = (s8)reg->s32_max_value;
7018 		init_s32_min = (s8)reg->s32_min_value;
7019 	} else {
7020 		/* size == 2 */
7021 		init_s32_max = (s16)reg->s32_max_value;
7022 		init_s32_min = (s16)reg->s32_min_value;
7023 	}
7024 	s32_max = max(init_s32_max, init_s32_min);
7025 	s32_min = min(init_s32_max, init_s32_min);
7026 
7027 	if ((s32_min >= 0) == (s32_max >= 0)) {
7028 		reg->s32_min_value = s32_min;
7029 		reg->s32_max_value = s32_max;
7030 		reg->u32_min_value = (u32)s32_min;
7031 		reg->u32_max_value = (u32)s32_max;
7032 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7033 		return;
7034 	}
7035 
7036 out:
7037 	set_sext32_default_val(reg, size);
7038 }
7039 
bpf_map_is_rdonly(const struct bpf_map * map)7040 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7041 {
7042 	/* A map is considered read-only if the following condition are true:
7043 	 *
7044 	 * 1) BPF program side cannot change any of the map content. The
7045 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7046 	 *    and was set at map creation time.
7047 	 * 2) The map value(s) have been initialized from user space by a
7048 	 *    loader and then "frozen", such that no new map update/delete
7049 	 *    operations from syscall side are possible for the rest of
7050 	 *    the map's lifetime from that point onwards.
7051 	 * 3) Any parallel/pending map update/delete operations from syscall
7052 	 *    side have been completed. Only after that point, it's safe to
7053 	 *    assume that map value(s) are immutable.
7054 	 */
7055 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
7056 	       READ_ONCE(map->frozen) &&
7057 	       !bpf_map_write_active(map);
7058 }
7059 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)7060 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7061 			       bool is_ldsx)
7062 {
7063 	void *ptr;
7064 	u64 addr;
7065 	int err;
7066 
7067 	err = map->ops->map_direct_value_addr(map, &addr, off);
7068 	if (err)
7069 		return err;
7070 	ptr = (void *)(long)addr + off;
7071 
7072 	switch (size) {
7073 	case sizeof(u8):
7074 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7075 		break;
7076 	case sizeof(u16):
7077 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7078 		break;
7079 	case sizeof(u32):
7080 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7081 		break;
7082 	case sizeof(u64):
7083 		*val = *(u64 *)ptr;
7084 		break;
7085 	default:
7086 		return -EINVAL;
7087 	}
7088 	return 0;
7089 }
7090 
7091 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7092 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7093 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7094 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7095 
7096 /*
7097  * Allow list few fields as RCU trusted or full trusted.
7098  * This logic doesn't allow mix tagging and will be removed once GCC supports
7099  * btf_type_tag.
7100  */
7101 
7102 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)7103 BTF_TYPE_SAFE_RCU(struct task_struct) {
7104 	const cpumask_t *cpus_ptr;
7105 	struct css_set __rcu *cgroups;
7106 	struct task_struct __rcu *real_parent;
7107 	struct task_struct *group_leader;
7108 };
7109 
BTF_TYPE_SAFE_RCU(struct cgroup)7110 BTF_TYPE_SAFE_RCU(struct cgroup) {
7111 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7112 	struct kernfs_node *kn;
7113 };
7114 
BTF_TYPE_SAFE_RCU(struct css_set)7115 BTF_TYPE_SAFE_RCU(struct css_set) {
7116 	struct cgroup *dfl_cgrp;
7117 };
7118 
BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)7119 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7120 	struct cgroup *cgroup;
7121 };
7122 
7123 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)7124 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7125 	struct file __rcu *exe_file;
7126 };
7127 
7128 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7129  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7130  */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)7131 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7132 	struct sock *sk;
7133 };
7134 
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)7135 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7136 	struct sock *sk;
7137 };
7138 
7139 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)7140 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7141 	struct seq_file *seq;
7142 };
7143 
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)7144 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7145 	struct bpf_iter_meta *meta;
7146 	struct task_struct *task;
7147 };
7148 
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)7149 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7150 	struct file *file;
7151 };
7152 
BTF_TYPE_SAFE_TRUSTED(struct file)7153 BTF_TYPE_SAFE_TRUSTED(struct file) {
7154 	struct inode *f_inode;
7155 };
7156 
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)7157 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7158 	struct inode *d_inode;
7159 };
7160 
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)7161 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7162 	struct sock *sk;
7163 };
7164 
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7165 static bool type_is_rcu(struct bpf_verifier_env *env,
7166 			struct bpf_reg_state *reg,
7167 			const char *field_name, u32 btf_id)
7168 {
7169 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7170 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7171 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7172 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7173 
7174 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7175 }
7176 
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7177 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7178 				struct bpf_reg_state *reg,
7179 				const char *field_name, u32 btf_id)
7180 {
7181 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7182 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7183 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7184 
7185 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7186 }
7187 
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7188 static bool type_is_trusted(struct bpf_verifier_env *env,
7189 			    struct bpf_reg_state *reg,
7190 			    const char *field_name, u32 btf_id)
7191 {
7192 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7193 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7194 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7195 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7196 
7197 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7198 }
7199 
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7200 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7201 				    struct bpf_reg_state *reg,
7202 				    const char *field_name, u32 btf_id)
7203 {
7204 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7205 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7206 
7207 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7208 					  "__safe_trusted_or_null");
7209 }
7210 
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)7211 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7212 				   struct bpf_reg_state *regs,
7213 				   int regno, int off, int size,
7214 				   enum bpf_access_type atype,
7215 				   int value_regno)
7216 {
7217 	struct bpf_reg_state *reg = regs + regno;
7218 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7219 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7220 	const char *field_name = NULL;
7221 	enum bpf_type_flag flag = 0;
7222 	u32 btf_id = 0;
7223 	int ret;
7224 
7225 	if (!env->allow_ptr_leaks) {
7226 		verbose(env,
7227 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7228 			tname);
7229 		return -EPERM;
7230 	}
7231 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7232 		verbose(env,
7233 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7234 			tname);
7235 		return -EINVAL;
7236 	}
7237 	if (off < 0) {
7238 		verbose(env,
7239 			"R%d is ptr_%s invalid negative access: off=%d\n",
7240 			regno, tname, off);
7241 		return -EACCES;
7242 	}
7243 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7244 		char tn_buf[48];
7245 
7246 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7247 		verbose(env,
7248 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7249 			regno, tname, off, tn_buf);
7250 		return -EACCES;
7251 	}
7252 
7253 	if (reg->type & MEM_USER) {
7254 		verbose(env,
7255 			"R%d is ptr_%s access user memory: off=%d\n",
7256 			regno, tname, off);
7257 		return -EACCES;
7258 	}
7259 
7260 	if (reg->type & MEM_PERCPU) {
7261 		verbose(env,
7262 			"R%d is ptr_%s access percpu memory: off=%d\n",
7263 			regno, tname, off);
7264 		return -EACCES;
7265 	}
7266 
7267 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7268 		if (!btf_is_kernel(reg->btf)) {
7269 			verifier_bug(env, "reg->btf must be kernel btf");
7270 			return -EFAULT;
7271 		}
7272 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7273 	} else {
7274 		/* Writes are permitted with default btf_struct_access for
7275 		 * program allocated objects (which always have ref_obj_id > 0),
7276 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7277 		 */
7278 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7279 			verbose(env, "only read is supported\n");
7280 			return -EACCES;
7281 		}
7282 
7283 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7284 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7285 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7286 			return -EFAULT;
7287 		}
7288 
7289 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7290 	}
7291 
7292 	if (ret < 0)
7293 		return ret;
7294 
7295 	if (ret != PTR_TO_BTF_ID) {
7296 		/* just mark; */
7297 
7298 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7299 		/* If this is an untrusted pointer, all pointers formed by walking it
7300 		 * also inherit the untrusted flag.
7301 		 */
7302 		flag = PTR_UNTRUSTED;
7303 
7304 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7305 		/* By default any pointer obtained from walking a trusted pointer is no
7306 		 * longer trusted, unless the field being accessed has explicitly been
7307 		 * marked as inheriting its parent's state of trust (either full or RCU).
7308 		 * For example:
7309 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7310 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7311 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7312 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7313 		 *
7314 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7315 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7316 		 */
7317 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7318 			flag |= PTR_TRUSTED;
7319 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7320 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7321 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7322 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7323 				/* ignore __rcu tag and mark it MEM_RCU */
7324 				flag |= MEM_RCU;
7325 			} else if (flag & MEM_RCU ||
7326 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7327 				/* __rcu tagged pointers can be NULL */
7328 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7329 
7330 				/* We always trust them */
7331 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7332 				    flag & PTR_UNTRUSTED)
7333 					flag &= ~PTR_UNTRUSTED;
7334 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7335 				/* keep as-is */
7336 			} else {
7337 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7338 				clear_trusted_flags(&flag);
7339 			}
7340 		} else {
7341 			/*
7342 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7343 			 * aggressively mark as untrusted otherwise such
7344 			 * pointers will be plain PTR_TO_BTF_ID without flags
7345 			 * and will be allowed to be passed into helpers for
7346 			 * compat reasons.
7347 			 */
7348 			flag = PTR_UNTRUSTED;
7349 		}
7350 	} else {
7351 		/* Old compat. Deprecated */
7352 		clear_trusted_flags(&flag);
7353 	}
7354 
7355 	if (atype == BPF_READ && value_regno >= 0) {
7356 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7357 		if (ret < 0)
7358 			return ret;
7359 	}
7360 
7361 	return 0;
7362 }
7363 
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)7364 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7365 				   struct bpf_reg_state *regs,
7366 				   int regno, int off, int size,
7367 				   enum bpf_access_type atype,
7368 				   int value_regno)
7369 {
7370 	struct bpf_reg_state *reg = regs + regno;
7371 	struct bpf_map *map = reg->map_ptr;
7372 	struct bpf_reg_state map_reg;
7373 	enum bpf_type_flag flag = 0;
7374 	const struct btf_type *t;
7375 	const char *tname;
7376 	u32 btf_id;
7377 	int ret;
7378 
7379 	if (!btf_vmlinux) {
7380 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7381 		return -ENOTSUPP;
7382 	}
7383 
7384 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7385 		verbose(env, "map_ptr access not supported for map type %d\n",
7386 			map->map_type);
7387 		return -ENOTSUPP;
7388 	}
7389 
7390 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7391 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7392 
7393 	if (!env->allow_ptr_leaks) {
7394 		verbose(env,
7395 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7396 			tname);
7397 		return -EPERM;
7398 	}
7399 
7400 	if (off < 0) {
7401 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7402 			regno, tname, off);
7403 		return -EACCES;
7404 	}
7405 
7406 	if (atype != BPF_READ) {
7407 		verbose(env, "only read from %s is supported\n", tname);
7408 		return -EACCES;
7409 	}
7410 
7411 	/* Simulate access to a PTR_TO_BTF_ID */
7412 	memset(&map_reg, 0, sizeof(map_reg));
7413 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7414 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7415 	if (ret < 0)
7416 		return ret;
7417 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7418 	if (ret < 0)
7419 		return ret;
7420 
7421 	if (value_regno >= 0) {
7422 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7423 		if (ret < 0)
7424 			return ret;
7425 	}
7426 
7427 	return 0;
7428 }
7429 
7430 /* Check that the stack access at the given offset is within bounds. The
7431  * maximum valid offset is -1.
7432  *
7433  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7434  * -state->allocated_stack for reads.
7435  */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)7436 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7437                                           s64 off,
7438                                           struct bpf_func_state *state,
7439                                           enum bpf_access_type t)
7440 {
7441 	int min_valid_off;
7442 
7443 	if (t == BPF_WRITE || env->allow_uninit_stack)
7444 		min_valid_off = -MAX_BPF_STACK;
7445 	else
7446 		min_valid_off = -state->allocated_stack;
7447 
7448 	if (off < min_valid_off || off > -1)
7449 		return -EACCES;
7450 	return 0;
7451 }
7452 
7453 /* Check that the stack access at 'regno + off' falls within the maximum stack
7454  * bounds.
7455  *
7456  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7457  */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_type type)7458 static int check_stack_access_within_bounds(
7459 		struct bpf_verifier_env *env,
7460 		int regno, int off, int access_size,
7461 		enum bpf_access_type type)
7462 {
7463 	struct bpf_reg_state *regs = cur_regs(env);
7464 	struct bpf_reg_state *reg = regs + regno;
7465 	struct bpf_func_state *state = func(env, reg);
7466 	s64 min_off, max_off;
7467 	int err;
7468 	char *err_extra;
7469 
7470 	if (type == BPF_READ)
7471 		err_extra = " read from";
7472 	else
7473 		err_extra = " write to";
7474 
7475 	if (tnum_is_const(reg->var_off)) {
7476 		min_off = (s64)reg->var_off.value + off;
7477 		max_off = min_off + access_size;
7478 	} else {
7479 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7480 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7481 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7482 				err_extra, regno);
7483 			return -EACCES;
7484 		}
7485 		min_off = reg->smin_value + off;
7486 		max_off = reg->smax_value + off + access_size;
7487 	}
7488 
7489 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7490 	if (!err && max_off > 0)
7491 		err = -EINVAL; /* out of stack access into non-negative offsets */
7492 	if (!err && access_size < 0)
7493 		/* access_size should not be negative (or overflow an int); others checks
7494 		 * along the way should have prevented such an access.
7495 		 */
7496 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7497 
7498 	if (err) {
7499 		if (tnum_is_const(reg->var_off)) {
7500 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7501 				err_extra, regno, off, access_size);
7502 		} else {
7503 			char tn_buf[48];
7504 
7505 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7506 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7507 				err_extra, regno, tn_buf, off, access_size);
7508 		}
7509 		return err;
7510 	}
7511 
7512 	/* Note that there is no stack access with offset zero, so the needed stack
7513 	 * size is -min_off, not -min_off+1.
7514 	 */
7515 	return grow_stack_state(env, state, -min_off /* size */);
7516 }
7517 
get_func_retval_range(struct bpf_prog * prog,struct bpf_retval_range * range)7518 static bool get_func_retval_range(struct bpf_prog *prog,
7519 				  struct bpf_retval_range *range)
7520 {
7521 	if (prog->type == BPF_PROG_TYPE_LSM &&
7522 		prog->expected_attach_type == BPF_LSM_MAC &&
7523 		!bpf_lsm_get_retval_range(prog, range)) {
7524 		return true;
7525 	}
7526 	return false;
7527 }
7528 
7529 /* check whether memory at (regno + off) is accessible for t = (read | write)
7530  * if t==write, value_regno is a register which value is stored into memory
7531  * if t==read, value_regno is a register which will receive the value from memory
7532  * if t==write && value_regno==-1, some unknown value is stored into memory
7533  * if t==read && value_regno==-1, don't care what we read from memory
7534  */
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)7535 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7536 			    int off, int bpf_size, enum bpf_access_type t,
7537 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7538 {
7539 	struct bpf_reg_state *regs = cur_regs(env);
7540 	struct bpf_reg_state *reg = regs + regno;
7541 	int size, err = 0;
7542 
7543 	size = bpf_size_to_bytes(bpf_size);
7544 	if (size < 0)
7545 		return size;
7546 
7547 	/* alignment checks will add in reg->off themselves */
7548 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7549 	if (err)
7550 		return err;
7551 
7552 	/* for access checks, reg->off is just part of off */
7553 	off += reg->off;
7554 
7555 	if (reg->type == PTR_TO_MAP_KEY) {
7556 		if (t == BPF_WRITE) {
7557 			verbose(env, "write to change key R%d not allowed\n", regno);
7558 			return -EACCES;
7559 		}
7560 
7561 		err = check_mem_region_access(env, regno, off, size,
7562 					      reg->map_ptr->key_size, false);
7563 		if (err)
7564 			return err;
7565 		if (value_regno >= 0)
7566 			mark_reg_unknown(env, regs, value_regno);
7567 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7568 		struct btf_field *kptr_field = NULL;
7569 
7570 		if (t == BPF_WRITE && value_regno >= 0 &&
7571 		    is_pointer_value(env, value_regno)) {
7572 			verbose(env, "R%d leaks addr into map\n", value_regno);
7573 			return -EACCES;
7574 		}
7575 		err = check_map_access_type(env, regno, off, size, t);
7576 		if (err)
7577 			return err;
7578 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7579 		if (err)
7580 			return err;
7581 		if (tnum_is_const(reg->var_off))
7582 			kptr_field = btf_record_find(reg->map_ptr->record,
7583 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7584 		if (kptr_field) {
7585 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7586 		} else if (t == BPF_READ && value_regno >= 0) {
7587 			struct bpf_map *map = reg->map_ptr;
7588 
7589 			/* if map is read-only, track its contents as scalars */
7590 			if (tnum_is_const(reg->var_off) &&
7591 			    bpf_map_is_rdonly(map) &&
7592 			    map->ops->map_direct_value_addr) {
7593 				int map_off = off + reg->var_off.value;
7594 				u64 val = 0;
7595 
7596 				err = bpf_map_direct_read(map, map_off, size,
7597 							  &val, is_ldsx);
7598 				if (err)
7599 					return err;
7600 
7601 				regs[value_regno].type = SCALAR_VALUE;
7602 				__mark_reg_known(&regs[value_regno], val);
7603 			} else {
7604 				mark_reg_unknown(env, regs, value_regno);
7605 			}
7606 		}
7607 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7608 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7609 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7610 
7611 		if (type_may_be_null(reg->type)) {
7612 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7613 				reg_type_str(env, reg->type));
7614 			return -EACCES;
7615 		}
7616 
7617 		if (t == BPF_WRITE && rdonly_mem) {
7618 			verbose(env, "R%d cannot write into %s\n",
7619 				regno, reg_type_str(env, reg->type));
7620 			return -EACCES;
7621 		}
7622 
7623 		if (t == BPF_WRITE && value_regno >= 0 &&
7624 		    is_pointer_value(env, value_regno)) {
7625 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7626 			return -EACCES;
7627 		}
7628 
7629 		/*
7630 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7631 		 * instructions, hence no need to check bounds in that case.
7632 		 */
7633 		if (!rdonly_untrusted)
7634 			err = check_mem_region_access(env, regno, off, size,
7635 						      reg->mem_size, false);
7636 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7637 			mark_reg_unknown(env, regs, value_regno);
7638 	} else if (reg->type == PTR_TO_CTX) {
7639 		struct bpf_retval_range range;
7640 		struct bpf_insn_access_aux info = {
7641 			.reg_type = SCALAR_VALUE,
7642 			.is_ldsx = is_ldsx,
7643 			.log = &env->log,
7644 		};
7645 
7646 		if (t == BPF_WRITE && value_regno >= 0 &&
7647 		    is_pointer_value(env, value_regno)) {
7648 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7649 			return -EACCES;
7650 		}
7651 
7652 		err = check_ptr_off_reg(env, reg, regno);
7653 		if (err < 0)
7654 			return err;
7655 
7656 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7657 		if (err)
7658 			verbose_linfo(env, insn_idx, "; ");
7659 		if (!err && t == BPF_READ && value_regno >= 0) {
7660 			/* ctx access returns either a scalar, or a
7661 			 * PTR_TO_PACKET[_META,_END]. In the latter
7662 			 * case, we know the offset is zero.
7663 			 */
7664 			if (info.reg_type == SCALAR_VALUE) {
7665 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7666 					err = __mark_reg_s32_range(env, regs, value_regno,
7667 								   range.minval, range.maxval);
7668 					if (err)
7669 						return err;
7670 				} else {
7671 					mark_reg_unknown(env, regs, value_regno);
7672 				}
7673 			} else {
7674 				mark_reg_known_zero(env, regs,
7675 						    value_regno);
7676 				if (type_may_be_null(info.reg_type))
7677 					regs[value_regno].id = ++env->id_gen;
7678 				/* A load of ctx field could have different
7679 				 * actual load size with the one encoded in the
7680 				 * insn. When the dst is PTR, it is for sure not
7681 				 * a sub-register.
7682 				 */
7683 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7684 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7685 					regs[value_regno].btf = info.btf;
7686 					regs[value_regno].btf_id = info.btf_id;
7687 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7688 				}
7689 			}
7690 			regs[value_regno].type = info.reg_type;
7691 		}
7692 
7693 	} else if (reg->type == PTR_TO_STACK) {
7694 		/* Basic bounds checks. */
7695 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7696 		if (err)
7697 			return err;
7698 
7699 		if (t == BPF_READ)
7700 			err = check_stack_read(env, regno, off, size,
7701 					       value_regno);
7702 		else
7703 			err = check_stack_write(env, regno, off, size,
7704 						value_regno, insn_idx);
7705 	} else if (reg_is_pkt_pointer(reg)) {
7706 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7707 			verbose(env, "cannot write into packet\n");
7708 			return -EACCES;
7709 		}
7710 		if (t == BPF_WRITE && value_regno >= 0 &&
7711 		    is_pointer_value(env, value_regno)) {
7712 			verbose(env, "R%d leaks addr into packet\n",
7713 				value_regno);
7714 			return -EACCES;
7715 		}
7716 		err = check_packet_access(env, regno, off, size, false);
7717 		if (!err && t == BPF_READ && value_regno >= 0)
7718 			mark_reg_unknown(env, regs, value_regno);
7719 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7720 		if (t == BPF_WRITE && value_regno >= 0 &&
7721 		    is_pointer_value(env, value_regno)) {
7722 			verbose(env, "R%d leaks addr into flow keys\n",
7723 				value_regno);
7724 			return -EACCES;
7725 		}
7726 
7727 		err = check_flow_keys_access(env, off, size);
7728 		if (!err && t == BPF_READ && value_regno >= 0)
7729 			mark_reg_unknown(env, regs, value_regno);
7730 	} else if (type_is_sk_pointer(reg->type)) {
7731 		if (t == BPF_WRITE) {
7732 			verbose(env, "R%d cannot write into %s\n",
7733 				regno, reg_type_str(env, reg->type));
7734 			return -EACCES;
7735 		}
7736 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7737 		if (!err && value_regno >= 0)
7738 			mark_reg_unknown(env, regs, value_regno);
7739 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7740 		err = check_tp_buffer_access(env, reg, regno, off, size);
7741 		if (!err && t == BPF_READ && value_regno >= 0)
7742 			mark_reg_unknown(env, regs, value_regno);
7743 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7744 		   !type_may_be_null(reg->type)) {
7745 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7746 					      value_regno);
7747 	} else if (reg->type == CONST_PTR_TO_MAP) {
7748 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7749 					      value_regno);
7750 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7751 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7752 		u32 *max_access;
7753 
7754 		if (rdonly_mem) {
7755 			if (t == BPF_WRITE) {
7756 				verbose(env, "R%d cannot write into %s\n",
7757 					regno, reg_type_str(env, reg->type));
7758 				return -EACCES;
7759 			}
7760 			max_access = &env->prog->aux->max_rdonly_access;
7761 		} else {
7762 			max_access = &env->prog->aux->max_rdwr_access;
7763 		}
7764 
7765 		err = check_buffer_access(env, reg, regno, off, size, false,
7766 					  max_access);
7767 
7768 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7769 			mark_reg_unknown(env, regs, value_regno);
7770 	} else if (reg->type == PTR_TO_ARENA) {
7771 		if (t == BPF_READ && value_regno >= 0)
7772 			mark_reg_unknown(env, regs, value_regno);
7773 	} else {
7774 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7775 			reg_type_str(env, reg->type));
7776 		return -EACCES;
7777 	}
7778 
7779 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7780 	    regs[value_regno].type == SCALAR_VALUE) {
7781 		if (!is_ldsx)
7782 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7783 			coerce_reg_to_size(&regs[value_regno], size);
7784 		else
7785 			coerce_reg_to_size_sx(&regs[value_regno], size);
7786 	}
7787 	return err;
7788 }
7789 
7790 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7791 			     bool allow_trust_mismatch);
7792 
check_load_mem(struct bpf_verifier_env * env,struct bpf_insn * insn,bool strict_alignment_once,bool is_ldsx,bool allow_trust_mismatch,const char * ctx)7793 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7794 			  bool strict_alignment_once, bool is_ldsx,
7795 			  bool allow_trust_mismatch, const char *ctx)
7796 {
7797 	struct bpf_reg_state *regs = cur_regs(env);
7798 	enum bpf_reg_type src_reg_type;
7799 	int err;
7800 
7801 	/* check src operand */
7802 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7803 	if (err)
7804 		return err;
7805 
7806 	/* check dst operand */
7807 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7808 	if (err)
7809 		return err;
7810 
7811 	src_reg_type = regs[insn->src_reg].type;
7812 
7813 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7814 	 * updated by this call.
7815 	 */
7816 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7817 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7818 			       strict_alignment_once, is_ldsx);
7819 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7820 				       allow_trust_mismatch);
7821 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7822 
7823 	return err;
7824 }
7825 
check_store_reg(struct bpf_verifier_env * env,struct bpf_insn * insn,bool strict_alignment_once)7826 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7827 			   bool strict_alignment_once)
7828 {
7829 	struct bpf_reg_state *regs = cur_regs(env);
7830 	enum bpf_reg_type dst_reg_type;
7831 	int err;
7832 
7833 	/* check src1 operand */
7834 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7835 	if (err)
7836 		return err;
7837 
7838 	/* check src2 operand */
7839 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7840 	if (err)
7841 		return err;
7842 
7843 	dst_reg_type = regs[insn->dst_reg].type;
7844 
7845 	/* Check if (dst_reg + off) is writeable. */
7846 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7847 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7848 			       strict_alignment_once, false);
7849 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7850 
7851 	return err;
7852 }
7853 
check_atomic_rmw(struct bpf_verifier_env * env,struct bpf_insn * insn)7854 static int check_atomic_rmw(struct bpf_verifier_env *env,
7855 			    struct bpf_insn *insn)
7856 {
7857 	int load_reg;
7858 	int err;
7859 
7860 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7861 		verbose(env, "invalid atomic operand size\n");
7862 		return -EINVAL;
7863 	}
7864 
7865 	/* check src1 operand */
7866 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7867 	if (err)
7868 		return err;
7869 
7870 	/* check src2 operand */
7871 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7872 	if (err)
7873 		return err;
7874 
7875 	if (insn->imm == BPF_CMPXCHG) {
7876 		/* Check comparison of R0 with memory location */
7877 		const u32 aux_reg = BPF_REG_0;
7878 
7879 		err = check_reg_arg(env, aux_reg, SRC_OP);
7880 		if (err)
7881 			return err;
7882 
7883 		if (is_pointer_value(env, aux_reg)) {
7884 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7885 			return -EACCES;
7886 		}
7887 	}
7888 
7889 	if (is_pointer_value(env, insn->src_reg)) {
7890 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7891 		return -EACCES;
7892 	}
7893 
7894 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7895 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7896 			insn->dst_reg,
7897 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7898 		return -EACCES;
7899 	}
7900 
7901 	if (insn->imm & BPF_FETCH) {
7902 		if (insn->imm == BPF_CMPXCHG)
7903 			load_reg = BPF_REG_0;
7904 		else
7905 			load_reg = insn->src_reg;
7906 
7907 		/* check and record load of old value */
7908 		err = check_reg_arg(env, load_reg, DST_OP);
7909 		if (err)
7910 			return err;
7911 	} else {
7912 		/* This instruction accesses a memory location but doesn't
7913 		 * actually load it into a register.
7914 		 */
7915 		load_reg = -1;
7916 	}
7917 
7918 	/* Check whether we can read the memory, with second call for fetch
7919 	 * case to simulate the register fill.
7920 	 */
7921 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7922 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7923 	if (!err && load_reg >= 0)
7924 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7925 				       insn->off, BPF_SIZE(insn->code),
7926 				       BPF_READ, load_reg, true, false);
7927 	if (err)
7928 		return err;
7929 
7930 	if (is_arena_reg(env, insn->dst_reg)) {
7931 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7932 		if (err)
7933 			return err;
7934 	}
7935 	/* Check whether we can write into the same memory. */
7936 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7937 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7938 	if (err)
7939 		return err;
7940 	return 0;
7941 }
7942 
check_atomic_load(struct bpf_verifier_env * env,struct bpf_insn * insn)7943 static int check_atomic_load(struct bpf_verifier_env *env,
7944 			     struct bpf_insn *insn)
7945 {
7946 	int err;
7947 
7948 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7949 	if (err)
7950 		return err;
7951 
7952 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7953 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7954 			insn->src_reg,
7955 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7956 		return -EACCES;
7957 	}
7958 
7959 	return 0;
7960 }
7961 
check_atomic_store(struct bpf_verifier_env * env,struct bpf_insn * insn)7962 static int check_atomic_store(struct bpf_verifier_env *env,
7963 			      struct bpf_insn *insn)
7964 {
7965 	int err;
7966 
7967 	err = check_store_reg(env, insn, true);
7968 	if (err)
7969 		return err;
7970 
7971 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7972 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7973 			insn->dst_reg,
7974 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7975 		return -EACCES;
7976 	}
7977 
7978 	return 0;
7979 }
7980 
check_atomic(struct bpf_verifier_env * env,struct bpf_insn * insn)7981 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7982 {
7983 	switch (insn->imm) {
7984 	case BPF_ADD:
7985 	case BPF_ADD | BPF_FETCH:
7986 	case BPF_AND:
7987 	case BPF_AND | BPF_FETCH:
7988 	case BPF_OR:
7989 	case BPF_OR | BPF_FETCH:
7990 	case BPF_XOR:
7991 	case BPF_XOR | BPF_FETCH:
7992 	case BPF_XCHG:
7993 	case BPF_CMPXCHG:
7994 		return check_atomic_rmw(env, insn);
7995 	case BPF_LOAD_ACQ:
7996 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7997 			verbose(env,
7998 				"64-bit load-acquires are only supported on 64-bit arches\n");
7999 			return -EOPNOTSUPP;
8000 		}
8001 		return check_atomic_load(env, insn);
8002 	case BPF_STORE_REL:
8003 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8004 			verbose(env,
8005 				"64-bit store-releases are only supported on 64-bit arches\n");
8006 			return -EOPNOTSUPP;
8007 		}
8008 		return check_atomic_store(env, insn);
8009 	default:
8010 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8011 			insn->imm);
8012 		return -EINVAL;
8013 	}
8014 }
8015 
8016 /* When register 'regno' is used to read the stack (either directly or through
8017  * a helper function) make sure that it's within stack boundary and, depending
8018  * on the access type and privileges, that all elements of the stack are
8019  * initialized.
8020  *
8021  * 'off' includes 'regno->off', but not its dynamic part (if any).
8022  *
8023  * All registers that have been spilled on the stack in the slots within the
8024  * read offsets are marked as read.
8025  */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum bpf_access_type type,struct bpf_call_arg_meta * meta)8026 static int check_stack_range_initialized(
8027 		struct bpf_verifier_env *env, int regno, int off,
8028 		int access_size, bool zero_size_allowed,
8029 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8030 {
8031 	struct bpf_reg_state *reg = reg_state(env, regno);
8032 	struct bpf_func_state *state = func(env, reg);
8033 	int err, min_off, max_off, i, j, slot, spi;
8034 	/* Some accesses can write anything into the stack, others are
8035 	 * read-only.
8036 	 */
8037 	bool clobber = false;
8038 
8039 	if (access_size == 0 && !zero_size_allowed) {
8040 		verbose(env, "invalid zero-sized read\n");
8041 		return -EACCES;
8042 	}
8043 
8044 	if (type == BPF_WRITE)
8045 		clobber = true;
8046 
8047 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8048 	if (err)
8049 		return err;
8050 
8051 
8052 	if (tnum_is_const(reg->var_off)) {
8053 		min_off = max_off = reg->var_off.value + off;
8054 	} else {
8055 		/* Variable offset is prohibited for unprivileged mode for
8056 		 * simplicity since it requires corresponding support in
8057 		 * Spectre masking for stack ALU.
8058 		 * See also retrieve_ptr_limit().
8059 		 */
8060 		if (!env->bypass_spec_v1) {
8061 			char tn_buf[48];
8062 
8063 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8064 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8065 				regno, tn_buf);
8066 			return -EACCES;
8067 		}
8068 		/* Only initialized buffer on stack is allowed to be accessed
8069 		 * with variable offset. With uninitialized buffer it's hard to
8070 		 * guarantee that whole memory is marked as initialized on
8071 		 * helper return since specific bounds are unknown what may
8072 		 * cause uninitialized stack leaking.
8073 		 */
8074 		if (meta && meta->raw_mode)
8075 			meta = NULL;
8076 
8077 		min_off = reg->smin_value + off;
8078 		max_off = reg->smax_value + off;
8079 	}
8080 
8081 	if (meta && meta->raw_mode) {
8082 		/* Ensure we won't be overwriting dynptrs when simulating byte
8083 		 * by byte access in check_helper_call using meta.access_size.
8084 		 * This would be a problem if we have a helper in the future
8085 		 * which takes:
8086 		 *
8087 		 *	helper(uninit_mem, len, dynptr)
8088 		 *
8089 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8090 		 * may end up writing to dynptr itself when touching memory from
8091 		 * arg 1. This can be relaxed on a case by case basis for known
8092 		 * safe cases, but reject due to the possibilitiy of aliasing by
8093 		 * default.
8094 		 */
8095 		for (i = min_off; i < max_off + access_size; i++) {
8096 			int stack_off = -i - 1;
8097 
8098 			spi = __get_spi(i);
8099 			/* raw_mode may write past allocated_stack */
8100 			if (state->allocated_stack <= stack_off)
8101 				continue;
8102 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8103 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8104 				return -EACCES;
8105 			}
8106 		}
8107 		meta->access_size = access_size;
8108 		meta->regno = regno;
8109 		return 0;
8110 	}
8111 
8112 	for (i = min_off; i < max_off + access_size; i++) {
8113 		u8 *stype;
8114 
8115 		slot = -i - 1;
8116 		spi = slot / BPF_REG_SIZE;
8117 		if (state->allocated_stack <= slot) {
8118 			verbose(env, "allocated_stack too small\n");
8119 			return -EFAULT;
8120 		}
8121 
8122 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8123 		if (*stype == STACK_MISC)
8124 			goto mark;
8125 		if ((*stype == STACK_ZERO) ||
8126 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8127 			if (clobber) {
8128 				/* helper can write anything into the stack */
8129 				*stype = STACK_MISC;
8130 			}
8131 			goto mark;
8132 		}
8133 
8134 		if (is_spilled_reg(&state->stack[spi]) &&
8135 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8136 		     env->allow_ptr_leaks)) {
8137 			if (clobber) {
8138 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8139 				for (j = 0; j < BPF_REG_SIZE; j++)
8140 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8141 			}
8142 			goto mark;
8143 		}
8144 
8145 		if (tnum_is_const(reg->var_off)) {
8146 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8147 				regno, min_off, i - min_off, access_size);
8148 		} else {
8149 			char tn_buf[48];
8150 
8151 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8152 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8153 				regno, tn_buf, i - min_off, access_size);
8154 		}
8155 		return -EACCES;
8156 mark:
8157 		/* reading any byte out of 8-byte 'spill_slot' will cause
8158 		 * the whole slot to be marked as 'read'
8159 		 */
8160 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
8161 			      state->stack[spi].spilled_ptr.parent,
8162 			      REG_LIVE_READ64);
8163 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
8164 		 * be sure that whether stack slot is written to or not. Hence,
8165 		 * we must still conservatively propagate reads upwards even if
8166 		 * helper may write to the entire memory range.
8167 		 */
8168 	}
8169 	return 0;
8170 }
8171 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,enum bpf_access_type access_type,bool zero_size_allowed,struct bpf_call_arg_meta * meta)8172 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8173 				   int access_size, enum bpf_access_type access_type,
8174 				   bool zero_size_allowed,
8175 				   struct bpf_call_arg_meta *meta)
8176 {
8177 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8178 	u32 *max_access;
8179 
8180 	switch (base_type(reg->type)) {
8181 	case PTR_TO_PACKET:
8182 	case PTR_TO_PACKET_META:
8183 		return check_packet_access(env, regno, reg->off, access_size,
8184 					   zero_size_allowed);
8185 	case PTR_TO_MAP_KEY:
8186 		if (access_type == BPF_WRITE) {
8187 			verbose(env, "R%d cannot write into %s\n", regno,
8188 				reg_type_str(env, reg->type));
8189 			return -EACCES;
8190 		}
8191 		return check_mem_region_access(env, regno, reg->off, access_size,
8192 					       reg->map_ptr->key_size, false);
8193 	case PTR_TO_MAP_VALUE:
8194 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8195 			return -EACCES;
8196 		return check_map_access(env, regno, reg->off, access_size,
8197 					zero_size_allowed, ACCESS_HELPER);
8198 	case PTR_TO_MEM:
8199 		if (type_is_rdonly_mem(reg->type)) {
8200 			if (access_type == BPF_WRITE) {
8201 				verbose(env, "R%d cannot write into %s\n", regno,
8202 					reg_type_str(env, reg->type));
8203 				return -EACCES;
8204 			}
8205 		}
8206 		return check_mem_region_access(env, regno, reg->off,
8207 					       access_size, reg->mem_size,
8208 					       zero_size_allowed);
8209 	case PTR_TO_BUF:
8210 		if (type_is_rdonly_mem(reg->type)) {
8211 			if (access_type == BPF_WRITE) {
8212 				verbose(env, "R%d cannot write into %s\n", regno,
8213 					reg_type_str(env, reg->type));
8214 				return -EACCES;
8215 			}
8216 
8217 			max_access = &env->prog->aux->max_rdonly_access;
8218 		} else {
8219 			max_access = &env->prog->aux->max_rdwr_access;
8220 		}
8221 		return check_buffer_access(env, reg, regno, reg->off,
8222 					   access_size, zero_size_allowed,
8223 					   max_access);
8224 	case PTR_TO_STACK:
8225 		return check_stack_range_initialized(
8226 				env,
8227 				regno, reg->off, access_size,
8228 				zero_size_allowed, access_type, meta);
8229 	case PTR_TO_BTF_ID:
8230 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8231 					       access_size, BPF_READ, -1);
8232 	case PTR_TO_CTX:
8233 		/* in case the function doesn't know how to access the context,
8234 		 * (because we are in a program of type SYSCALL for example), we
8235 		 * can not statically check its size.
8236 		 * Dynamically check it now.
8237 		 */
8238 		if (!env->ops->convert_ctx_access) {
8239 			int offset = access_size - 1;
8240 
8241 			/* Allow zero-byte read from PTR_TO_CTX */
8242 			if (access_size == 0)
8243 				return zero_size_allowed ? 0 : -EACCES;
8244 
8245 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8246 						access_type, -1, false, false);
8247 		}
8248 
8249 		fallthrough;
8250 	default: /* scalar_value or invalid ptr */
8251 		/* Allow zero-byte read from NULL, regardless of pointer type */
8252 		if (zero_size_allowed && access_size == 0 &&
8253 		    register_is_null(reg))
8254 			return 0;
8255 
8256 		verbose(env, "R%d type=%s ", regno,
8257 			reg_type_str(env, reg->type));
8258 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8259 		return -EACCES;
8260 	}
8261 }
8262 
8263 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8264  * size.
8265  *
8266  * @regno is the register containing the access size. regno-1 is the register
8267  * containing the pointer.
8268  */
check_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,enum bpf_access_type access_type,bool zero_size_allowed,struct bpf_call_arg_meta * meta)8269 static int check_mem_size_reg(struct bpf_verifier_env *env,
8270 			      struct bpf_reg_state *reg, u32 regno,
8271 			      enum bpf_access_type access_type,
8272 			      bool zero_size_allowed,
8273 			      struct bpf_call_arg_meta *meta)
8274 {
8275 	int err;
8276 
8277 	/* This is used to refine r0 return value bounds for helpers
8278 	 * that enforce this value as an upper bound on return values.
8279 	 * See do_refine_retval_range() for helpers that can refine
8280 	 * the return value. C type of helper is u32 so we pull register
8281 	 * bound from umax_value however, if negative verifier errors
8282 	 * out. Only upper bounds can be learned because retval is an
8283 	 * int type and negative retvals are allowed.
8284 	 */
8285 	meta->msize_max_value = reg->umax_value;
8286 
8287 	/* The register is SCALAR_VALUE; the access check happens using
8288 	 * its boundaries. For unprivileged variable accesses, disable
8289 	 * raw mode so that the program is required to initialize all
8290 	 * the memory that the helper could just partially fill up.
8291 	 */
8292 	if (!tnum_is_const(reg->var_off))
8293 		meta = NULL;
8294 
8295 	if (reg->smin_value < 0) {
8296 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8297 			regno);
8298 		return -EACCES;
8299 	}
8300 
8301 	if (reg->umin_value == 0 && !zero_size_allowed) {
8302 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8303 			regno, reg->umin_value, reg->umax_value);
8304 		return -EACCES;
8305 	}
8306 
8307 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8308 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8309 			regno);
8310 		return -EACCES;
8311 	}
8312 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8313 				      access_type, zero_size_allowed, meta);
8314 	if (!err)
8315 		err = mark_chain_precision(env, regno);
8316 	return err;
8317 }
8318 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)8319 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8320 			 u32 regno, u32 mem_size)
8321 {
8322 	bool may_be_null = type_may_be_null(reg->type);
8323 	struct bpf_reg_state saved_reg;
8324 	int err;
8325 
8326 	if (register_is_null(reg))
8327 		return 0;
8328 
8329 	/* Assuming that the register contains a value check if the memory
8330 	 * access is safe. Temporarily save and restore the register's state as
8331 	 * the conversion shouldn't be visible to a caller.
8332 	 */
8333 	if (may_be_null) {
8334 		saved_reg = *reg;
8335 		mark_ptr_not_null_reg(reg);
8336 	}
8337 
8338 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8339 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8340 
8341 	if (may_be_null)
8342 		*reg = saved_reg;
8343 
8344 	return err;
8345 }
8346 
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)8347 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8348 				    u32 regno)
8349 {
8350 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8351 	bool may_be_null = type_may_be_null(mem_reg->type);
8352 	struct bpf_reg_state saved_reg;
8353 	struct bpf_call_arg_meta meta;
8354 	int err;
8355 
8356 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8357 
8358 	memset(&meta, 0, sizeof(meta));
8359 
8360 	if (may_be_null) {
8361 		saved_reg = *mem_reg;
8362 		mark_ptr_not_null_reg(mem_reg);
8363 	}
8364 
8365 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8366 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8367 
8368 	if (may_be_null)
8369 		*mem_reg = saved_reg;
8370 
8371 	return err;
8372 }
8373 
8374 enum {
8375 	PROCESS_SPIN_LOCK = (1 << 0),
8376 	PROCESS_RES_LOCK  = (1 << 1),
8377 	PROCESS_LOCK_IRQ  = (1 << 2),
8378 };
8379 
8380 /* Implementation details:
8381  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8382  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8383  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8384  * Two separate bpf_obj_new will also have different reg->id.
8385  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8386  * clears reg->id after value_or_null->value transition, since the verifier only
8387  * cares about the range of access to valid map value pointer and doesn't care
8388  * about actual address of the map element.
8389  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8390  * reg->id > 0 after value_or_null->value transition. By doing so
8391  * two bpf_map_lookups will be considered two different pointers that
8392  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8393  * returned from bpf_obj_new.
8394  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8395  * dead-locks.
8396  * Since only one bpf_spin_lock is allowed the checks are simpler than
8397  * reg_is_refcounted() logic. The verifier needs to remember only
8398  * one spin_lock instead of array of acquired_refs.
8399  * env->cur_state->active_locks remembers which map value element or allocated
8400  * object got locked and clears it after bpf_spin_unlock.
8401  */
process_spin_lock(struct bpf_verifier_env * env,int regno,int flags)8402 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8403 {
8404 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8405 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8406 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8407 	struct bpf_verifier_state *cur = env->cur_state;
8408 	bool is_const = tnum_is_const(reg->var_off);
8409 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8410 	u64 val = reg->var_off.value;
8411 	struct bpf_map *map = NULL;
8412 	struct btf *btf = NULL;
8413 	struct btf_record *rec;
8414 	u32 spin_lock_off;
8415 	int err;
8416 
8417 	if (!is_const) {
8418 		verbose(env,
8419 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8420 			regno, lock_str);
8421 		return -EINVAL;
8422 	}
8423 	if (reg->type == PTR_TO_MAP_VALUE) {
8424 		map = reg->map_ptr;
8425 		if (!map->btf) {
8426 			verbose(env,
8427 				"map '%s' has to have BTF in order to use %s_lock\n",
8428 				map->name, lock_str);
8429 			return -EINVAL;
8430 		}
8431 	} else {
8432 		btf = reg->btf;
8433 	}
8434 
8435 	rec = reg_btf_record(reg);
8436 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8437 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8438 			map ? map->name : "kptr", lock_str);
8439 		return -EINVAL;
8440 	}
8441 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8442 	if (spin_lock_off != val + reg->off) {
8443 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8444 			val + reg->off, lock_str, spin_lock_off);
8445 		return -EINVAL;
8446 	}
8447 	if (is_lock) {
8448 		void *ptr;
8449 		int type;
8450 
8451 		if (map)
8452 			ptr = map;
8453 		else
8454 			ptr = btf;
8455 
8456 		if (!is_res_lock && cur->active_locks) {
8457 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8458 				verbose(env,
8459 					"Locking two bpf_spin_locks are not allowed\n");
8460 				return -EINVAL;
8461 			}
8462 		} else if (is_res_lock && cur->active_locks) {
8463 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8464 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8465 				return -EINVAL;
8466 			}
8467 		}
8468 
8469 		if (is_res_lock && is_irq)
8470 			type = REF_TYPE_RES_LOCK_IRQ;
8471 		else if (is_res_lock)
8472 			type = REF_TYPE_RES_LOCK;
8473 		else
8474 			type = REF_TYPE_LOCK;
8475 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8476 		if (err < 0) {
8477 			verbose(env, "Failed to acquire lock state\n");
8478 			return err;
8479 		}
8480 	} else {
8481 		void *ptr;
8482 		int type;
8483 
8484 		if (map)
8485 			ptr = map;
8486 		else
8487 			ptr = btf;
8488 
8489 		if (!cur->active_locks) {
8490 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8491 			return -EINVAL;
8492 		}
8493 
8494 		if (is_res_lock && is_irq)
8495 			type = REF_TYPE_RES_LOCK_IRQ;
8496 		else if (is_res_lock)
8497 			type = REF_TYPE_RES_LOCK;
8498 		else
8499 			type = REF_TYPE_LOCK;
8500 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8501 			verbose(env, "%s_unlock of different lock\n", lock_str);
8502 			return -EINVAL;
8503 		}
8504 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8505 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8506 			return -EINVAL;
8507 		}
8508 		if (release_lock_state(cur, type, reg->id, ptr)) {
8509 			verbose(env, "%s_unlock of different lock\n", lock_str);
8510 			return -EINVAL;
8511 		}
8512 
8513 		invalidate_non_owning_refs(env);
8514 	}
8515 	return 0;
8516 }
8517 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)8518 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8519 			      struct bpf_call_arg_meta *meta)
8520 {
8521 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8522 	bool is_const = tnum_is_const(reg->var_off);
8523 	struct bpf_map *map = reg->map_ptr;
8524 	u64 val = reg->var_off.value;
8525 
8526 	if (!is_const) {
8527 		verbose(env,
8528 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
8529 			regno);
8530 		return -EINVAL;
8531 	}
8532 	if (!map->btf) {
8533 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
8534 			map->name);
8535 		return -EINVAL;
8536 	}
8537 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
8538 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
8539 		return -EINVAL;
8540 	}
8541 	if (map->record->timer_off != val + reg->off) {
8542 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
8543 			val + reg->off, map->record->timer_off);
8544 		return -EINVAL;
8545 	}
8546 	if (meta->map_ptr) {
8547 		verifier_bug(env, "Two map pointers in a timer helper");
8548 		return -EFAULT;
8549 	}
8550 	meta->map_uid = reg->map_uid;
8551 	meta->map_ptr = map;
8552 	return 0;
8553 }
8554 
process_wq_func(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)8555 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8556 			   struct bpf_kfunc_call_arg_meta *meta)
8557 {
8558 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8559 	struct bpf_map *map = reg->map_ptr;
8560 	u64 val = reg->var_off.value;
8561 
8562 	if (map->record->wq_off != val + reg->off) {
8563 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8564 			val + reg->off, map->record->wq_off);
8565 		return -EINVAL;
8566 	}
8567 	meta->map.uid = reg->map_uid;
8568 	meta->map.ptr = map;
8569 	return 0;
8570 }
8571 
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)8572 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8573 			     struct bpf_call_arg_meta *meta)
8574 {
8575 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8576 	struct btf_field *kptr_field;
8577 	struct bpf_map *map_ptr;
8578 	struct btf_record *rec;
8579 	u32 kptr_off;
8580 
8581 	if (type_is_ptr_alloc_obj(reg->type)) {
8582 		rec = reg_btf_record(reg);
8583 	} else { /* PTR_TO_MAP_VALUE */
8584 		map_ptr = reg->map_ptr;
8585 		if (!map_ptr->btf) {
8586 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8587 				map_ptr->name);
8588 			return -EINVAL;
8589 		}
8590 		rec = map_ptr->record;
8591 		meta->map_ptr = map_ptr;
8592 	}
8593 
8594 	if (!tnum_is_const(reg->var_off)) {
8595 		verbose(env,
8596 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8597 			regno);
8598 		return -EINVAL;
8599 	}
8600 
8601 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8602 		verbose(env, "R%d has no valid kptr\n", regno);
8603 		return -EINVAL;
8604 	}
8605 
8606 	kptr_off = reg->off + reg->var_off.value;
8607 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8608 	if (!kptr_field) {
8609 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8610 		return -EACCES;
8611 	}
8612 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8613 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8614 		return -EACCES;
8615 	}
8616 	meta->kptr_field = kptr_field;
8617 	return 0;
8618 }
8619 
8620 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8621  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8622  *
8623  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8624  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8625  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8626  *
8627  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8628  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8629  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8630  * mutate the view of the dynptr and also possibly destroy it. In the latter
8631  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8632  * memory that dynptr points to.
8633  *
8634  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8635  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8636  * readonly dynptr view yet, hence only the first case is tracked and checked.
8637  *
8638  * This is consistent with how C applies the const modifier to a struct object,
8639  * where the pointer itself inside bpf_dynptr becomes const but not what it
8640  * points to.
8641  *
8642  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8643  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8644  */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)8645 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8646 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8647 {
8648 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8649 	int err;
8650 
8651 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8652 		verbose(env,
8653 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8654 			regno - 1);
8655 		return -EINVAL;
8656 	}
8657 
8658 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8659 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8660 	 */
8661 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8662 		verifier_bug(env, "misconfigured dynptr helper type flags");
8663 		return -EFAULT;
8664 	}
8665 
8666 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8667 	 *		 constructing a mutable bpf_dynptr object.
8668 	 *
8669 	 *		 Currently, this is only possible with PTR_TO_STACK
8670 	 *		 pointing to a region of at least 16 bytes which doesn't
8671 	 *		 contain an existing bpf_dynptr.
8672 	 *
8673 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8674 	 *		 mutated or destroyed. However, the memory it points to
8675 	 *		 may be mutated.
8676 	 *
8677 	 *  None       - Points to a initialized dynptr that can be mutated and
8678 	 *		 destroyed, including mutation of the memory it points
8679 	 *		 to.
8680 	 */
8681 	if (arg_type & MEM_UNINIT) {
8682 		int i;
8683 
8684 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8685 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8686 			return -EINVAL;
8687 		}
8688 
8689 		/* we write BPF_DW bits (8 bytes) at a time */
8690 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8691 			err = check_mem_access(env, insn_idx, regno,
8692 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8693 			if (err)
8694 				return err;
8695 		}
8696 
8697 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8698 	} else /* MEM_RDONLY and None case from above */ {
8699 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8700 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8701 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8702 			return -EINVAL;
8703 		}
8704 
8705 		if (!is_dynptr_reg_valid_init(env, reg)) {
8706 			verbose(env,
8707 				"Expected an initialized dynptr as arg #%d\n",
8708 				regno - 1);
8709 			return -EINVAL;
8710 		}
8711 
8712 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8713 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8714 			verbose(env,
8715 				"Expected a dynptr of type %s as arg #%d\n",
8716 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8717 			return -EINVAL;
8718 		}
8719 
8720 		err = mark_dynptr_read(env, reg);
8721 	}
8722 	return err;
8723 }
8724 
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)8725 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8726 {
8727 	struct bpf_func_state *state = func(env, reg);
8728 
8729 	return state->stack[spi].spilled_ptr.ref_obj_id;
8730 }
8731 
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)8732 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8733 {
8734 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8735 }
8736 
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)8737 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8738 {
8739 	return meta->kfunc_flags & KF_ITER_NEW;
8740 }
8741 
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)8742 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8743 {
8744 	return meta->kfunc_flags & KF_ITER_NEXT;
8745 }
8746 
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)8747 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8748 {
8749 	return meta->kfunc_flags & KF_ITER_DESTROY;
8750 }
8751 
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg_idx,const struct btf_param * arg)8752 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8753 			      const struct btf_param *arg)
8754 {
8755 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8756 	 * kfunc is iter state pointer
8757 	 */
8758 	if (is_iter_kfunc(meta))
8759 		return arg_idx == 0;
8760 
8761 	/* iter passed as an argument to a generic kfunc */
8762 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8763 }
8764 
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)8765 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8766 			    struct bpf_kfunc_call_arg_meta *meta)
8767 {
8768 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8769 	const struct btf_type *t;
8770 	int spi, err, i, nr_slots, btf_id;
8771 
8772 	if (reg->type != PTR_TO_STACK) {
8773 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8774 		return -EINVAL;
8775 	}
8776 
8777 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8778 	 * ensures struct convention, so we wouldn't need to do any BTF
8779 	 * validation here. But given iter state can be passed as a parameter
8780 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8781 	 * conservative here.
8782 	 */
8783 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8784 	if (btf_id < 0) {
8785 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8786 		return -EINVAL;
8787 	}
8788 	t = btf_type_by_id(meta->btf, btf_id);
8789 	nr_slots = t->size / BPF_REG_SIZE;
8790 
8791 	if (is_iter_new_kfunc(meta)) {
8792 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8793 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8794 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8795 				iter_type_str(meta->btf, btf_id), regno - 1);
8796 			return -EINVAL;
8797 		}
8798 
8799 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8800 			err = check_mem_access(env, insn_idx, regno,
8801 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8802 			if (err)
8803 				return err;
8804 		}
8805 
8806 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8807 		if (err)
8808 			return err;
8809 	} else {
8810 		/* iter_next() or iter_destroy(), as well as any kfunc
8811 		 * accepting iter argument, expect initialized iter state
8812 		 */
8813 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8814 		switch (err) {
8815 		case 0:
8816 			break;
8817 		case -EINVAL:
8818 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8819 				iter_type_str(meta->btf, btf_id), regno - 1);
8820 			return err;
8821 		case -EPROTO:
8822 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8823 			return err;
8824 		default:
8825 			return err;
8826 		}
8827 
8828 		spi = iter_get_spi(env, reg, nr_slots);
8829 		if (spi < 0)
8830 			return spi;
8831 
8832 		err = mark_iter_read(env, reg, spi, nr_slots);
8833 		if (err)
8834 			return err;
8835 
8836 		/* remember meta->iter info for process_iter_next_call() */
8837 		meta->iter.spi = spi;
8838 		meta->iter.frameno = reg->frameno;
8839 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8840 
8841 		if (is_iter_destroy_kfunc(meta)) {
8842 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8843 			if (err)
8844 				return err;
8845 		}
8846 	}
8847 
8848 	return 0;
8849 }
8850 
8851 /* Look for a previous loop entry at insn_idx: nearest parent state
8852  * stopped at insn_idx with callsites matching those in cur->frame.
8853  */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)8854 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8855 						  struct bpf_verifier_state *cur,
8856 						  int insn_idx)
8857 {
8858 	struct bpf_verifier_state_list *sl;
8859 	struct bpf_verifier_state *st;
8860 	struct list_head *pos, *head;
8861 
8862 	/* Explored states are pushed in stack order, most recent states come first */
8863 	head = explored_state(env, insn_idx);
8864 	list_for_each(pos, head) {
8865 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8866 		/* If st->branches != 0 state is a part of current DFS verification path,
8867 		 * hence cur & st for a loop.
8868 		 */
8869 		st = &sl->state;
8870 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8871 		    st->dfs_depth < cur->dfs_depth)
8872 			return st;
8873 	}
8874 
8875 	return NULL;
8876 }
8877 
8878 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8879 static bool regs_exact(const struct bpf_reg_state *rold,
8880 		       const struct bpf_reg_state *rcur,
8881 		       struct bpf_idmap *idmap);
8882 
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)8883 static void maybe_widen_reg(struct bpf_verifier_env *env,
8884 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8885 			    struct bpf_idmap *idmap)
8886 {
8887 	if (rold->type != SCALAR_VALUE)
8888 		return;
8889 	if (rold->type != rcur->type)
8890 		return;
8891 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8892 		return;
8893 	__mark_reg_unknown(env, rcur);
8894 }
8895 
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)8896 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8897 				   struct bpf_verifier_state *old,
8898 				   struct bpf_verifier_state *cur)
8899 {
8900 	struct bpf_func_state *fold, *fcur;
8901 	int i, fr;
8902 
8903 	reset_idmap_scratch(env);
8904 	for (fr = old->curframe; fr >= 0; fr--) {
8905 		fold = old->frame[fr];
8906 		fcur = cur->frame[fr];
8907 
8908 		for (i = 0; i < MAX_BPF_REG; i++)
8909 			maybe_widen_reg(env,
8910 					&fold->regs[i],
8911 					&fcur->regs[i],
8912 					&env->idmap_scratch);
8913 
8914 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
8915 			if (!is_spilled_reg(&fold->stack[i]) ||
8916 			    !is_spilled_reg(&fcur->stack[i]))
8917 				continue;
8918 
8919 			maybe_widen_reg(env,
8920 					&fold->stack[i].spilled_ptr,
8921 					&fcur->stack[i].spilled_ptr,
8922 					&env->idmap_scratch);
8923 		}
8924 	}
8925 	return 0;
8926 }
8927 
get_iter_from_state(struct bpf_verifier_state * cur_st,struct bpf_kfunc_call_arg_meta * meta)8928 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8929 						 struct bpf_kfunc_call_arg_meta *meta)
8930 {
8931 	int iter_frameno = meta->iter.frameno;
8932 	int iter_spi = meta->iter.spi;
8933 
8934 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8935 }
8936 
8937 /* process_iter_next_call() is called when verifier gets to iterator's next
8938  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8939  * to it as just "iter_next()" in comments below.
8940  *
8941  * BPF verifier relies on a crucial contract for any iter_next()
8942  * implementation: it should *eventually* return NULL, and once that happens
8943  * it should keep returning NULL. That is, once iterator exhausts elements to
8944  * iterate, it should never reset or spuriously return new elements.
8945  *
8946  * With the assumption of such contract, process_iter_next_call() simulates
8947  * a fork in the verifier state to validate loop logic correctness and safety
8948  * without having to simulate infinite amount of iterations.
8949  *
8950  * In current state, we first assume that iter_next() returned NULL and
8951  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8952  * conditions we should not form an infinite loop and should eventually reach
8953  * exit.
8954  *
8955  * Besides that, we also fork current state and enqueue it for later
8956  * verification. In a forked state we keep iterator state as ACTIVE
8957  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8958  * also bump iteration depth to prevent erroneous infinite loop detection
8959  * later on (see iter_active_depths_differ() comment for details). In this
8960  * state we assume that we'll eventually loop back to another iter_next()
8961  * calls (it could be in exactly same location or in some other instruction,
8962  * it doesn't matter, we don't make any unnecessary assumptions about this,
8963  * everything revolves around iterator state in a stack slot, not which
8964  * instruction is calling iter_next()). When that happens, we either will come
8965  * to iter_next() with equivalent state and can conclude that next iteration
8966  * will proceed in exactly the same way as we just verified, so it's safe to
8967  * assume that loop converges. If not, we'll go on another iteration
8968  * simulation with a different input state, until all possible starting states
8969  * are validated or we reach maximum number of instructions limit.
8970  *
8971  * This way, we will either exhaustively discover all possible input states
8972  * that iterator loop can start with and eventually will converge, or we'll
8973  * effectively regress into bounded loop simulation logic and either reach
8974  * maximum number of instructions if loop is not provably convergent, or there
8975  * is some statically known limit on number of iterations (e.g., if there is
8976  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8977  *
8978  * Iteration convergence logic in is_state_visited() relies on exact
8979  * states comparison, which ignores read and precision marks.
8980  * This is necessary because read and precision marks are not finalized
8981  * while in the loop. Exact comparison might preclude convergence for
8982  * simple programs like below:
8983  *
8984  *     i = 0;
8985  *     while(iter_next(&it))
8986  *       i++;
8987  *
8988  * At each iteration step i++ would produce a new distinct state and
8989  * eventually instruction processing limit would be reached.
8990  *
8991  * To avoid such behavior speculatively forget (widen) range for
8992  * imprecise scalar registers, if those registers were not precise at the
8993  * end of the previous iteration and do not match exactly.
8994  *
8995  * This is a conservative heuristic that allows to verify wide range of programs,
8996  * however it precludes verification of programs that conjure an
8997  * imprecise value on the first loop iteration and use it as precise on a second.
8998  * For example, the following safe program would fail to verify:
8999  *
9000  *     struct bpf_num_iter it;
9001  *     int arr[10];
9002  *     int i = 0, a = 0;
9003  *     bpf_iter_num_new(&it, 0, 10);
9004  *     while (bpf_iter_num_next(&it)) {
9005  *       if (a == 0) {
9006  *         a = 1;
9007  *         i = 7; // Because i changed verifier would forget
9008  *                // it's range on second loop entry.
9009  *       } else {
9010  *         arr[i] = 42; // This would fail to verify.
9011  *       }
9012  *     }
9013  *     bpf_iter_num_destroy(&it);
9014  */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)9015 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9016 				  struct bpf_kfunc_call_arg_meta *meta)
9017 {
9018 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9019 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9020 	struct bpf_reg_state *cur_iter, *queued_iter;
9021 
9022 	BTF_TYPE_EMIT(struct bpf_iter);
9023 
9024 	cur_iter = get_iter_from_state(cur_st, meta);
9025 
9026 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9027 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9028 		verifier_bug(env, "unexpected iterator state %d (%s)",
9029 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9030 		return -EFAULT;
9031 	}
9032 
9033 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9034 		/* Because iter_next() call is a checkpoint is_state_visitied()
9035 		 * should guarantee parent state with same call sites and insn_idx.
9036 		 */
9037 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9038 		    !same_callsites(cur_st->parent, cur_st)) {
9039 			verifier_bug(env, "bad parent state for iter next call");
9040 			return -EFAULT;
9041 		}
9042 		/* Note cur_st->parent in the call below, it is necessary to skip
9043 		 * checkpoint created for cur_st by is_state_visited()
9044 		 * right at this instruction.
9045 		 */
9046 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9047 		/* branch out active iter state */
9048 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9049 		if (!queued_st)
9050 			return -ENOMEM;
9051 
9052 		queued_iter = get_iter_from_state(queued_st, meta);
9053 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9054 		queued_iter->iter.depth++;
9055 		if (prev_st)
9056 			widen_imprecise_scalars(env, prev_st, queued_st);
9057 
9058 		queued_fr = queued_st->frame[queued_st->curframe];
9059 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9060 	}
9061 
9062 	/* switch to DRAINED state, but keep the depth unchanged */
9063 	/* mark current iter state as drained and assume returned NULL */
9064 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9065 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9066 
9067 	return 0;
9068 }
9069 
arg_type_is_mem_size(enum bpf_arg_type type)9070 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9071 {
9072 	return type == ARG_CONST_SIZE ||
9073 	       type == ARG_CONST_SIZE_OR_ZERO;
9074 }
9075 
arg_type_is_raw_mem(enum bpf_arg_type type)9076 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9077 {
9078 	return base_type(type) == ARG_PTR_TO_MEM &&
9079 	       type & MEM_UNINIT;
9080 }
9081 
arg_type_is_release(enum bpf_arg_type type)9082 static bool arg_type_is_release(enum bpf_arg_type type)
9083 {
9084 	return type & OBJ_RELEASE;
9085 }
9086 
arg_type_is_dynptr(enum bpf_arg_type type)9087 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9088 {
9089 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9090 }
9091 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)9092 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9093 				 const struct bpf_call_arg_meta *meta,
9094 				 enum bpf_arg_type *arg_type)
9095 {
9096 	if (!meta->map_ptr) {
9097 		/* kernel subsystem misconfigured verifier */
9098 		verifier_bug(env, "invalid map_ptr to access map->type");
9099 		return -EFAULT;
9100 	}
9101 
9102 	switch (meta->map_ptr->map_type) {
9103 	case BPF_MAP_TYPE_SOCKMAP:
9104 	case BPF_MAP_TYPE_SOCKHASH:
9105 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9106 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9107 		} else {
9108 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9109 			return -EINVAL;
9110 		}
9111 		break;
9112 	case BPF_MAP_TYPE_BLOOM_FILTER:
9113 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9114 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9115 		break;
9116 	default:
9117 		break;
9118 	}
9119 	return 0;
9120 }
9121 
9122 struct bpf_reg_types {
9123 	const enum bpf_reg_type types[10];
9124 	u32 *btf_id;
9125 };
9126 
9127 static const struct bpf_reg_types sock_types = {
9128 	.types = {
9129 		PTR_TO_SOCK_COMMON,
9130 		PTR_TO_SOCKET,
9131 		PTR_TO_TCP_SOCK,
9132 		PTR_TO_XDP_SOCK,
9133 	},
9134 };
9135 
9136 #ifdef CONFIG_NET
9137 static const struct bpf_reg_types btf_id_sock_common_types = {
9138 	.types = {
9139 		PTR_TO_SOCK_COMMON,
9140 		PTR_TO_SOCKET,
9141 		PTR_TO_TCP_SOCK,
9142 		PTR_TO_XDP_SOCK,
9143 		PTR_TO_BTF_ID,
9144 		PTR_TO_BTF_ID | PTR_TRUSTED,
9145 	},
9146 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9147 };
9148 #endif
9149 
9150 static const struct bpf_reg_types mem_types = {
9151 	.types = {
9152 		PTR_TO_STACK,
9153 		PTR_TO_PACKET,
9154 		PTR_TO_PACKET_META,
9155 		PTR_TO_MAP_KEY,
9156 		PTR_TO_MAP_VALUE,
9157 		PTR_TO_MEM,
9158 		PTR_TO_MEM | MEM_RINGBUF,
9159 		PTR_TO_BUF,
9160 		PTR_TO_BTF_ID | PTR_TRUSTED,
9161 	},
9162 };
9163 
9164 static const struct bpf_reg_types spin_lock_types = {
9165 	.types = {
9166 		PTR_TO_MAP_VALUE,
9167 		PTR_TO_BTF_ID | MEM_ALLOC,
9168 	}
9169 };
9170 
9171 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9172 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9173 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9174 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9175 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9176 static const struct bpf_reg_types btf_ptr_types = {
9177 	.types = {
9178 		PTR_TO_BTF_ID,
9179 		PTR_TO_BTF_ID | PTR_TRUSTED,
9180 		PTR_TO_BTF_ID | MEM_RCU,
9181 	},
9182 };
9183 static const struct bpf_reg_types percpu_btf_ptr_types = {
9184 	.types = {
9185 		PTR_TO_BTF_ID | MEM_PERCPU,
9186 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9187 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9188 	}
9189 };
9190 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9191 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9192 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9193 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9194 static const struct bpf_reg_types kptr_xchg_dest_types = {
9195 	.types = {
9196 		PTR_TO_MAP_VALUE,
9197 		PTR_TO_BTF_ID | MEM_ALLOC
9198 	}
9199 };
9200 static const struct bpf_reg_types dynptr_types = {
9201 	.types = {
9202 		PTR_TO_STACK,
9203 		CONST_PTR_TO_DYNPTR,
9204 	}
9205 };
9206 
9207 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9208 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9209 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9210 	[ARG_CONST_SIZE]		= &scalar_types,
9211 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9212 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9213 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9214 	[ARG_PTR_TO_CTX]		= &context_types,
9215 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9216 #ifdef CONFIG_NET
9217 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9218 #endif
9219 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9220 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9221 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9222 	[ARG_PTR_TO_MEM]		= &mem_types,
9223 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9224 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9225 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9226 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9227 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9228 	[ARG_PTR_TO_TIMER]		= &timer_types,
9229 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9230 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9231 };
9232 
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)9233 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9234 			  enum bpf_arg_type arg_type,
9235 			  const u32 *arg_btf_id,
9236 			  struct bpf_call_arg_meta *meta)
9237 {
9238 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9239 	enum bpf_reg_type expected, type = reg->type;
9240 	const struct bpf_reg_types *compatible;
9241 	int i, j;
9242 
9243 	compatible = compatible_reg_types[base_type(arg_type)];
9244 	if (!compatible) {
9245 		verifier_bug(env, "unsupported arg type %d", arg_type);
9246 		return -EFAULT;
9247 	}
9248 
9249 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9250 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9251 	 *
9252 	 * Same for MAYBE_NULL:
9253 	 *
9254 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9255 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9256 	 *
9257 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9258 	 *
9259 	 * Therefore we fold these flags depending on the arg_type before comparison.
9260 	 */
9261 	if (arg_type & MEM_RDONLY)
9262 		type &= ~MEM_RDONLY;
9263 	if (arg_type & PTR_MAYBE_NULL)
9264 		type &= ~PTR_MAYBE_NULL;
9265 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9266 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9267 
9268 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9269 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9270 		type &= ~MEM_ALLOC;
9271 		type &= ~MEM_PERCPU;
9272 	}
9273 
9274 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9275 		expected = compatible->types[i];
9276 		if (expected == NOT_INIT)
9277 			break;
9278 
9279 		if (type == expected)
9280 			goto found;
9281 	}
9282 
9283 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9284 	for (j = 0; j + 1 < i; j++)
9285 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9286 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9287 	return -EACCES;
9288 
9289 found:
9290 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9291 		return 0;
9292 
9293 	if (compatible == &mem_types) {
9294 		if (!(arg_type & MEM_RDONLY)) {
9295 			verbose(env,
9296 				"%s() may write into memory pointed by R%d type=%s\n",
9297 				func_id_name(meta->func_id),
9298 				regno, reg_type_str(env, reg->type));
9299 			return -EACCES;
9300 		}
9301 		return 0;
9302 	}
9303 
9304 	switch ((int)reg->type) {
9305 	case PTR_TO_BTF_ID:
9306 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9307 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9308 	case PTR_TO_BTF_ID | MEM_RCU:
9309 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9310 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9311 	{
9312 		/* For bpf_sk_release, it needs to match against first member
9313 		 * 'struct sock_common', hence make an exception for it. This
9314 		 * allows bpf_sk_release to work for multiple socket types.
9315 		 */
9316 		bool strict_type_match = arg_type_is_release(arg_type) &&
9317 					 meta->func_id != BPF_FUNC_sk_release;
9318 
9319 		if (type_may_be_null(reg->type) &&
9320 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9321 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9322 			return -EACCES;
9323 		}
9324 
9325 		if (!arg_btf_id) {
9326 			if (!compatible->btf_id) {
9327 				verifier_bug(env, "missing arg compatible BTF ID");
9328 				return -EFAULT;
9329 			}
9330 			arg_btf_id = compatible->btf_id;
9331 		}
9332 
9333 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9334 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9335 				return -EACCES;
9336 		} else {
9337 			if (arg_btf_id == BPF_PTR_POISON) {
9338 				verbose(env, "verifier internal error:");
9339 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9340 					regno);
9341 				return -EACCES;
9342 			}
9343 
9344 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9345 						  btf_vmlinux, *arg_btf_id,
9346 						  strict_type_match)) {
9347 				verbose(env, "R%d is of type %s but %s is expected\n",
9348 					regno, btf_type_name(reg->btf, reg->btf_id),
9349 					btf_type_name(btf_vmlinux, *arg_btf_id));
9350 				return -EACCES;
9351 			}
9352 		}
9353 		break;
9354 	}
9355 	case PTR_TO_BTF_ID | MEM_ALLOC:
9356 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9357 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9358 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9359 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9360 			return -EFAULT;
9361 		}
9362 		/* Check if local kptr in src arg matches kptr in dst arg */
9363 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9364 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9365 				return -EACCES;
9366 		}
9367 		break;
9368 	case PTR_TO_BTF_ID | MEM_PERCPU:
9369 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9370 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9371 		/* Handled by helper specific checks */
9372 		break;
9373 	default:
9374 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9375 		return -EFAULT;
9376 	}
9377 	return 0;
9378 }
9379 
9380 static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)9381 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9382 {
9383 	struct btf_field *field;
9384 	struct btf_record *rec;
9385 
9386 	rec = reg_btf_record(reg);
9387 	if (!rec)
9388 		return NULL;
9389 
9390 	field = btf_record_find(rec, off, fields);
9391 	if (!field)
9392 		return NULL;
9393 
9394 	return field;
9395 }
9396 
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)9397 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9398 				  const struct bpf_reg_state *reg, int regno,
9399 				  enum bpf_arg_type arg_type)
9400 {
9401 	u32 type = reg->type;
9402 
9403 	/* When referenced register is passed to release function, its fixed
9404 	 * offset must be 0.
9405 	 *
9406 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9407 	 * meta->release_regno.
9408 	 */
9409 	if (arg_type_is_release(arg_type)) {
9410 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9411 		 * may not directly point to the object being released, but to
9412 		 * dynptr pointing to such object, which might be at some offset
9413 		 * on the stack. In that case, we simply to fallback to the
9414 		 * default handling.
9415 		 */
9416 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9417 			return 0;
9418 
9419 		/* Doing check_ptr_off_reg check for the offset will catch this
9420 		 * because fixed_off_ok is false, but checking here allows us
9421 		 * to give the user a better error message.
9422 		 */
9423 		if (reg->off) {
9424 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9425 				regno);
9426 			return -EINVAL;
9427 		}
9428 		return __check_ptr_off_reg(env, reg, regno, false);
9429 	}
9430 
9431 	switch (type) {
9432 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9433 	case PTR_TO_STACK:
9434 	case PTR_TO_PACKET:
9435 	case PTR_TO_PACKET_META:
9436 	case PTR_TO_MAP_KEY:
9437 	case PTR_TO_MAP_VALUE:
9438 	case PTR_TO_MEM:
9439 	case PTR_TO_MEM | MEM_RDONLY:
9440 	case PTR_TO_MEM | MEM_RINGBUF:
9441 	case PTR_TO_BUF:
9442 	case PTR_TO_BUF | MEM_RDONLY:
9443 	case PTR_TO_ARENA:
9444 	case SCALAR_VALUE:
9445 		return 0;
9446 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9447 	 * fixed offset.
9448 	 */
9449 	case PTR_TO_BTF_ID:
9450 	case PTR_TO_BTF_ID | MEM_ALLOC:
9451 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9452 	case PTR_TO_BTF_ID | MEM_RCU:
9453 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9454 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9455 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9456 		 * its fixed offset must be 0. In the other cases, fixed offset
9457 		 * can be non-zero. This was already checked above. So pass
9458 		 * fixed_off_ok as true to allow fixed offset for all other
9459 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9460 		 * still need to do checks instead of returning.
9461 		 */
9462 		return __check_ptr_off_reg(env, reg, regno, true);
9463 	default:
9464 		return __check_ptr_off_reg(env, reg, regno, false);
9465 	}
9466 }
9467 
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)9468 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9469 						const struct bpf_func_proto *fn,
9470 						struct bpf_reg_state *regs)
9471 {
9472 	struct bpf_reg_state *state = NULL;
9473 	int i;
9474 
9475 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9476 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9477 			if (state) {
9478 				verbose(env, "verifier internal error: multiple dynptr args\n");
9479 				return NULL;
9480 			}
9481 			state = &regs[BPF_REG_1 + i];
9482 		}
9483 
9484 	if (!state)
9485 		verbose(env, "verifier internal error: no dynptr arg found\n");
9486 
9487 	return state;
9488 }
9489 
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9490 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9491 {
9492 	struct bpf_func_state *state = func(env, reg);
9493 	int spi;
9494 
9495 	if (reg->type == CONST_PTR_TO_DYNPTR)
9496 		return reg->id;
9497 	spi = dynptr_get_spi(env, reg);
9498 	if (spi < 0)
9499 		return spi;
9500 	return state->stack[spi].spilled_ptr.id;
9501 }
9502 
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9503 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9504 {
9505 	struct bpf_func_state *state = func(env, reg);
9506 	int spi;
9507 
9508 	if (reg->type == CONST_PTR_TO_DYNPTR)
9509 		return reg->ref_obj_id;
9510 	spi = dynptr_get_spi(env, reg);
9511 	if (spi < 0)
9512 		return spi;
9513 	return state->stack[spi].spilled_ptr.ref_obj_id;
9514 }
9515 
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9516 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9517 					    struct bpf_reg_state *reg)
9518 {
9519 	struct bpf_func_state *state = func(env, reg);
9520 	int spi;
9521 
9522 	if (reg->type == CONST_PTR_TO_DYNPTR)
9523 		return reg->dynptr.type;
9524 
9525 	spi = __get_spi(reg->off);
9526 	if (spi < 0) {
9527 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9528 		return BPF_DYNPTR_TYPE_INVALID;
9529 	}
9530 
9531 	return state->stack[spi].spilled_ptr.dynptr.type;
9532 }
9533 
check_reg_const_str(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)9534 static int check_reg_const_str(struct bpf_verifier_env *env,
9535 			       struct bpf_reg_state *reg, u32 regno)
9536 {
9537 	struct bpf_map *map = reg->map_ptr;
9538 	int err;
9539 	int map_off;
9540 	u64 map_addr;
9541 	char *str_ptr;
9542 
9543 	if (reg->type != PTR_TO_MAP_VALUE)
9544 		return -EINVAL;
9545 
9546 	if (!bpf_map_is_rdonly(map)) {
9547 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9548 		return -EACCES;
9549 	}
9550 
9551 	if (!tnum_is_const(reg->var_off)) {
9552 		verbose(env, "R%d is not a constant address'\n", regno);
9553 		return -EACCES;
9554 	}
9555 
9556 	if (!map->ops->map_direct_value_addr) {
9557 		verbose(env, "no direct value access support for this map type\n");
9558 		return -EACCES;
9559 	}
9560 
9561 	err = check_map_access(env, regno, reg->off,
9562 			       map->value_size - reg->off, false,
9563 			       ACCESS_HELPER);
9564 	if (err)
9565 		return err;
9566 
9567 	map_off = reg->off + reg->var_off.value;
9568 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9569 	if (err) {
9570 		verbose(env, "direct value access on string failed\n");
9571 		return err;
9572 	}
9573 
9574 	str_ptr = (char *)(long)(map_addr);
9575 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9576 		verbose(env, "string is not zero-terminated\n");
9577 		return -EINVAL;
9578 	}
9579 	return 0;
9580 }
9581 
9582 /* Returns constant key value in `value` if possible, else negative error */
get_constant_map_key(struct bpf_verifier_env * env,struct bpf_reg_state * key,u32 key_size,s64 * value)9583 static int get_constant_map_key(struct bpf_verifier_env *env,
9584 				struct bpf_reg_state *key,
9585 				u32 key_size,
9586 				s64 *value)
9587 {
9588 	struct bpf_func_state *state = func(env, key);
9589 	struct bpf_reg_state *reg;
9590 	int slot, spi, off;
9591 	int spill_size = 0;
9592 	int zero_size = 0;
9593 	int stack_off;
9594 	int i, err;
9595 	u8 *stype;
9596 
9597 	if (!env->bpf_capable)
9598 		return -EOPNOTSUPP;
9599 	if (key->type != PTR_TO_STACK)
9600 		return -EOPNOTSUPP;
9601 	if (!tnum_is_const(key->var_off))
9602 		return -EOPNOTSUPP;
9603 
9604 	stack_off = key->off + key->var_off.value;
9605 	slot = -stack_off - 1;
9606 	spi = slot / BPF_REG_SIZE;
9607 	off = slot % BPF_REG_SIZE;
9608 	stype = state->stack[spi].slot_type;
9609 
9610 	/* First handle precisely tracked STACK_ZERO */
9611 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9612 		zero_size++;
9613 	if (zero_size >= key_size) {
9614 		*value = 0;
9615 		return 0;
9616 	}
9617 
9618 	/* Check that stack contains a scalar spill of expected size */
9619 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9620 		return -EOPNOTSUPP;
9621 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9622 		spill_size++;
9623 	if (spill_size != key_size)
9624 		return -EOPNOTSUPP;
9625 
9626 	reg = &state->stack[spi].spilled_ptr;
9627 	if (!tnum_is_const(reg->var_off))
9628 		/* Stack value not statically known */
9629 		return -EOPNOTSUPP;
9630 
9631 	/* We are relying on a constant value. So mark as precise
9632 	 * to prevent pruning on it.
9633 	 */
9634 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9635 	err = mark_chain_precision_batch(env, env->cur_state);
9636 	if (err < 0)
9637 		return err;
9638 
9639 	*value = reg->var_off.value;
9640 	return 0;
9641 }
9642 
9643 static bool can_elide_value_nullness(enum bpf_map_type type);
9644 
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)9645 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9646 			  struct bpf_call_arg_meta *meta,
9647 			  const struct bpf_func_proto *fn,
9648 			  int insn_idx)
9649 {
9650 	u32 regno = BPF_REG_1 + arg;
9651 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9652 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9653 	enum bpf_reg_type type = reg->type;
9654 	u32 *arg_btf_id = NULL;
9655 	u32 key_size;
9656 	int err = 0;
9657 
9658 	if (arg_type == ARG_DONTCARE)
9659 		return 0;
9660 
9661 	err = check_reg_arg(env, regno, SRC_OP);
9662 	if (err)
9663 		return err;
9664 
9665 	if (arg_type == ARG_ANYTHING) {
9666 		if (is_pointer_value(env, regno)) {
9667 			verbose(env, "R%d leaks addr into helper function\n",
9668 				regno);
9669 			return -EACCES;
9670 		}
9671 		return 0;
9672 	}
9673 
9674 	if (type_is_pkt_pointer(type) &&
9675 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9676 		verbose(env, "helper access to the packet is not allowed\n");
9677 		return -EACCES;
9678 	}
9679 
9680 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9681 		err = resolve_map_arg_type(env, meta, &arg_type);
9682 		if (err)
9683 			return err;
9684 	}
9685 
9686 	if (register_is_null(reg) && type_may_be_null(arg_type))
9687 		/* A NULL register has a SCALAR_VALUE type, so skip
9688 		 * type checking.
9689 		 */
9690 		goto skip_type_check;
9691 
9692 	/* arg_btf_id and arg_size are in a union. */
9693 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9694 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9695 		arg_btf_id = fn->arg_btf_id[arg];
9696 
9697 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9698 	if (err)
9699 		return err;
9700 
9701 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9702 	if (err)
9703 		return err;
9704 
9705 skip_type_check:
9706 	if (arg_type_is_release(arg_type)) {
9707 		if (arg_type_is_dynptr(arg_type)) {
9708 			struct bpf_func_state *state = func(env, reg);
9709 			int spi;
9710 
9711 			/* Only dynptr created on stack can be released, thus
9712 			 * the get_spi and stack state checks for spilled_ptr
9713 			 * should only be done before process_dynptr_func for
9714 			 * PTR_TO_STACK.
9715 			 */
9716 			if (reg->type == PTR_TO_STACK) {
9717 				spi = dynptr_get_spi(env, reg);
9718 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9719 					verbose(env, "arg %d is an unacquired reference\n", regno);
9720 					return -EINVAL;
9721 				}
9722 			} else {
9723 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9724 				return -EINVAL;
9725 			}
9726 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9727 			verbose(env, "R%d must be referenced when passed to release function\n",
9728 				regno);
9729 			return -EINVAL;
9730 		}
9731 		if (meta->release_regno) {
9732 			verifier_bug(env, "more than one release argument");
9733 			return -EFAULT;
9734 		}
9735 		meta->release_regno = regno;
9736 	}
9737 
9738 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9739 		if (meta->ref_obj_id) {
9740 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9741 				regno, reg->ref_obj_id,
9742 				meta->ref_obj_id);
9743 			return -EACCES;
9744 		}
9745 		meta->ref_obj_id = reg->ref_obj_id;
9746 	}
9747 
9748 	switch (base_type(arg_type)) {
9749 	case ARG_CONST_MAP_PTR:
9750 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9751 		if (meta->map_ptr) {
9752 			/* Use map_uid (which is unique id of inner map) to reject:
9753 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9754 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9755 			 * if (inner_map1 && inner_map2) {
9756 			 *     timer = bpf_map_lookup_elem(inner_map1);
9757 			 *     if (timer)
9758 			 *         // mismatch would have been allowed
9759 			 *         bpf_timer_init(timer, inner_map2);
9760 			 * }
9761 			 *
9762 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9763 			 */
9764 			if (meta->map_ptr != reg->map_ptr ||
9765 			    meta->map_uid != reg->map_uid) {
9766 				verbose(env,
9767 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9768 					meta->map_uid, reg->map_uid);
9769 				return -EINVAL;
9770 			}
9771 		}
9772 		meta->map_ptr = reg->map_ptr;
9773 		meta->map_uid = reg->map_uid;
9774 		break;
9775 	case ARG_PTR_TO_MAP_KEY:
9776 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9777 		 * check that [key, key + map->key_size) are within
9778 		 * stack limits and initialized
9779 		 */
9780 		if (!meta->map_ptr) {
9781 			/* in function declaration map_ptr must come before
9782 			 * map_key, so that it's verified and known before
9783 			 * we have to check map_key here. Otherwise it means
9784 			 * that kernel subsystem misconfigured verifier
9785 			 */
9786 			verifier_bug(env, "invalid map_ptr to access map->key");
9787 			return -EFAULT;
9788 		}
9789 		key_size = meta->map_ptr->key_size;
9790 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9791 		if (err)
9792 			return err;
9793 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9794 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9795 			if (err < 0) {
9796 				meta->const_map_key = -1;
9797 				if (err == -EOPNOTSUPP)
9798 					err = 0;
9799 				else
9800 					return err;
9801 			}
9802 		}
9803 		break;
9804 	case ARG_PTR_TO_MAP_VALUE:
9805 		if (type_may_be_null(arg_type) && register_is_null(reg))
9806 			return 0;
9807 
9808 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9809 		 * check [value, value + map->value_size) validity
9810 		 */
9811 		if (!meta->map_ptr) {
9812 			/* kernel subsystem misconfigured verifier */
9813 			verifier_bug(env, "invalid map_ptr to access map->value");
9814 			return -EFAULT;
9815 		}
9816 		meta->raw_mode = arg_type & MEM_UNINIT;
9817 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9818 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9819 					      false, meta);
9820 		break;
9821 	case ARG_PTR_TO_PERCPU_BTF_ID:
9822 		if (!reg->btf_id) {
9823 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9824 			return -EACCES;
9825 		}
9826 		meta->ret_btf = reg->btf;
9827 		meta->ret_btf_id = reg->btf_id;
9828 		break;
9829 	case ARG_PTR_TO_SPIN_LOCK:
9830 		if (in_rbtree_lock_required_cb(env)) {
9831 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9832 			return -EACCES;
9833 		}
9834 		if (meta->func_id == BPF_FUNC_spin_lock) {
9835 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9836 			if (err)
9837 				return err;
9838 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9839 			err = process_spin_lock(env, regno, 0);
9840 			if (err)
9841 				return err;
9842 		} else {
9843 			verifier_bug(env, "spin lock arg on unexpected helper");
9844 			return -EFAULT;
9845 		}
9846 		break;
9847 	case ARG_PTR_TO_TIMER:
9848 		err = process_timer_func(env, regno, meta);
9849 		if (err)
9850 			return err;
9851 		break;
9852 	case ARG_PTR_TO_FUNC:
9853 		meta->subprogno = reg->subprogno;
9854 		break;
9855 	case ARG_PTR_TO_MEM:
9856 		/* The access to this pointer is only checked when we hit the
9857 		 * next is_mem_size argument below.
9858 		 */
9859 		meta->raw_mode = arg_type & MEM_UNINIT;
9860 		if (arg_type & MEM_FIXED_SIZE) {
9861 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9862 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9863 						      false, meta);
9864 			if (err)
9865 				return err;
9866 			if (arg_type & MEM_ALIGNED)
9867 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9868 		}
9869 		break;
9870 	case ARG_CONST_SIZE:
9871 		err = check_mem_size_reg(env, reg, regno,
9872 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9873 					 BPF_WRITE : BPF_READ,
9874 					 false, meta);
9875 		break;
9876 	case ARG_CONST_SIZE_OR_ZERO:
9877 		err = check_mem_size_reg(env, reg, regno,
9878 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9879 					 BPF_WRITE : BPF_READ,
9880 					 true, meta);
9881 		break;
9882 	case ARG_PTR_TO_DYNPTR:
9883 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9884 		if (err)
9885 			return err;
9886 		break;
9887 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9888 		if (!tnum_is_const(reg->var_off)) {
9889 			verbose(env, "R%d is not a known constant'\n",
9890 				regno);
9891 			return -EACCES;
9892 		}
9893 		meta->mem_size = reg->var_off.value;
9894 		err = mark_chain_precision(env, regno);
9895 		if (err)
9896 			return err;
9897 		break;
9898 	case ARG_PTR_TO_CONST_STR:
9899 	{
9900 		err = check_reg_const_str(env, reg, regno);
9901 		if (err)
9902 			return err;
9903 		break;
9904 	}
9905 	case ARG_KPTR_XCHG_DEST:
9906 		err = process_kptr_func(env, regno, meta);
9907 		if (err)
9908 			return err;
9909 		break;
9910 	}
9911 
9912 	return err;
9913 }
9914 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)9915 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9916 {
9917 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9918 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9919 
9920 	if (func_id != BPF_FUNC_map_update_elem &&
9921 	    func_id != BPF_FUNC_map_delete_elem)
9922 		return false;
9923 
9924 	/* It's not possible to get access to a locked struct sock in these
9925 	 * contexts, so updating is safe.
9926 	 */
9927 	switch (type) {
9928 	case BPF_PROG_TYPE_TRACING:
9929 		if (eatype == BPF_TRACE_ITER)
9930 			return true;
9931 		break;
9932 	case BPF_PROG_TYPE_SOCK_OPS:
9933 		/* map_update allowed only via dedicated helpers with event type checks */
9934 		if (func_id == BPF_FUNC_map_delete_elem)
9935 			return true;
9936 		break;
9937 	case BPF_PROG_TYPE_SOCKET_FILTER:
9938 	case BPF_PROG_TYPE_SCHED_CLS:
9939 	case BPF_PROG_TYPE_SCHED_ACT:
9940 	case BPF_PROG_TYPE_XDP:
9941 	case BPF_PROG_TYPE_SK_REUSEPORT:
9942 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9943 	case BPF_PROG_TYPE_SK_LOOKUP:
9944 		return true;
9945 	default:
9946 		break;
9947 	}
9948 
9949 	verbose(env, "cannot update sockmap in this context\n");
9950 	return false;
9951 }
9952 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)9953 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9954 {
9955 	return env->prog->jit_requested &&
9956 	       bpf_jit_supports_subprog_tailcalls();
9957 }
9958 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)9959 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9960 					struct bpf_map *map, int func_id)
9961 {
9962 	if (!map)
9963 		return 0;
9964 
9965 	/* We need a two way check, first is from map perspective ... */
9966 	switch (map->map_type) {
9967 	case BPF_MAP_TYPE_PROG_ARRAY:
9968 		if (func_id != BPF_FUNC_tail_call)
9969 			goto error;
9970 		break;
9971 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9972 		if (func_id != BPF_FUNC_perf_event_read &&
9973 		    func_id != BPF_FUNC_perf_event_output &&
9974 		    func_id != BPF_FUNC_skb_output &&
9975 		    func_id != BPF_FUNC_perf_event_read_value &&
9976 		    func_id != BPF_FUNC_xdp_output)
9977 			goto error;
9978 		break;
9979 	case BPF_MAP_TYPE_RINGBUF:
9980 		if (func_id != BPF_FUNC_ringbuf_output &&
9981 		    func_id != BPF_FUNC_ringbuf_reserve &&
9982 		    func_id != BPF_FUNC_ringbuf_query &&
9983 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9984 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9985 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9986 			goto error;
9987 		break;
9988 	case BPF_MAP_TYPE_USER_RINGBUF:
9989 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9990 			goto error;
9991 		break;
9992 	case BPF_MAP_TYPE_STACK_TRACE:
9993 		if (func_id != BPF_FUNC_get_stackid)
9994 			goto error;
9995 		break;
9996 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9997 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9998 		    func_id != BPF_FUNC_current_task_under_cgroup)
9999 			goto error;
10000 		break;
10001 	case BPF_MAP_TYPE_CGROUP_STORAGE:
10002 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10003 		if (func_id != BPF_FUNC_get_local_storage)
10004 			goto error;
10005 		break;
10006 	case BPF_MAP_TYPE_DEVMAP:
10007 	case BPF_MAP_TYPE_DEVMAP_HASH:
10008 		if (func_id != BPF_FUNC_redirect_map &&
10009 		    func_id != BPF_FUNC_map_lookup_elem)
10010 			goto error;
10011 		break;
10012 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
10013 	 * appear.
10014 	 */
10015 	case BPF_MAP_TYPE_CPUMAP:
10016 		if (func_id != BPF_FUNC_redirect_map)
10017 			goto error;
10018 		break;
10019 	case BPF_MAP_TYPE_XSKMAP:
10020 		if (func_id != BPF_FUNC_redirect_map &&
10021 		    func_id != BPF_FUNC_map_lookup_elem)
10022 			goto error;
10023 		break;
10024 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10025 	case BPF_MAP_TYPE_HASH_OF_MAPS:
10026 		if (func_id != BPF_FUNC_map_lookup_elem)
10027 			goto error;
10028 		break;
10029 	case BPF_MAP_TYPE_SOCKMAP:
10030 		if (func_id != BPF_FUNC_sk_redirect_map &&
10031 		    func_id != BPF_FUNC_sock_map_update &&
10032 		    func_id != BPF_FUNC_msg_redirect_map &&
10033 		    func_id != BPF_FUNC_sk_select_reuseport &&
10034 		    func_id != BPF_FUNC_map_lookup_elem &&
10035 		    !may_update_sockmap(env, func_id))
10036 			goto error;
10037 		break;
10038 	case BPF_MAP_TYPE_SOCKHASH:
10039 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10040 		    func_id != BPF_FUNC_sock_hash_update &&
10041 		    func_id != BPF_FUNC_msg_redirect_hash &&
10042 		    func_id != BPF_FUNC_sk_select_reuseport &&
10043 		    func_id != BPF_FUNC_map_lookup_elem &&
10044 		    !may_update_sockmap(env, func_id))
10045 			goto error;
10046 		break;
10047 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10048 		if (func_id != BPF_FUNC_sk_select_reuseport)
10049 			goto error;
10050 		break;
10051 	case BPF_MAP_TYPE_QUEUE:
10052 	case BPF_MAP_TYPE_STACK:
10053 		if (func_id != BPF_FUNC_map_peek_elem &&
10054 		    func_id != BPF_FUNC_map_pop_elem &&
10055 		    func_id != BPF_FUNC_map_push_elem)
10056 			goto error;
10057 		break;
10058 	case BPF_MAP_TYPE_SK_STORAGE:
10059 		if (func_id != BPF_FUNC_sk_storage_get &&
10060 		    func_id != BPF_FUNC_sk_storage_delete &&
10061 		    func_id != BPF_FUNC_kptr_xchg)
10062 			goto error;
10063 		break;
10064 	case BPF_MAP_TYPE_INODE_STORAGE:
10065 		if (func_id != BPF_FUNC_inode_storage_get &&
10066 		    func_id != BPF_FUNC_inode_storage_delete &&
10067 		    func_id != BPF_FUNC_kptr_xchg)
10068 			goto error;
10069 		break;
10070 	case BPF_MAP_TYPE_TASK_STORAGE:
10071 		if (func_id != BPF_FUNC_task_storage_get &&
10072 		    func_id != BPF_FUNC_task_storage_delete &&
10073 		    func_id != BPF_FUNC_kptr_xchg)
10074 			goto error;
10075 		break;
10076 	case BPF_MAP_TYPE_CGRP_STORAGE:
10077 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10078 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10079 		    func_id != BPF_FUNC_kptr_xchg)
10080 			goto error;
10081 		break;
10082 	case BPF_MAP_TYPE_BLOOM_FILTER:
10083 		if (func_id != BPF_FUNC_map_peek_elem &&
10084 		    func_id != BPF_FUNC_map_push_elem)
10085 			goto error;
10086 		break;
10087 	default:
10088 		break;
10089 	}
10090 
10091 	/* ... and second from the function itself. */
10092 	switch (func_id) {
10093 	case BPF_FUNC_tail_call:
10094 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10095 			goto error;
10096 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10097 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10098 			return -EINVAL;
10099 		}
10100 		break;
10101 	case BPF_FUNC_perf_event_read:
10102 	case BPF_FUNC_perf_event_output:
10103 	case BPF_FUNC_perf_event_read_value:
10104 	case BPF_FUNC_skb_output:
10105 	case BPF_FUNC_xdp_output:
10106 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10107 			goto error;
10108 		break;
10109 	case BPF_FUNC_ringbuf_output:
10110 	case BPF_FUNC_ringbuf_reserve:
10111 	case BPF_FUNC_ringbuf_query:
10112 	case BPF_FUNC_ringbuf_reserve_dynptr:
10113 	case BPF_FUNC_ringbuf_submit_dynptr:
10114 	case BPF_FUNC_ringbuf_discard_dynptr:
10115 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10116 			goto error;
10117 		break;
10118 	case BPF_FUNC_user_ringbuf_drain:
10119 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10120 			goto error;
10121 		break;
10122 	case BPF_FUNC_get_stackid:
10123 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10124 			goto error;
10125 		break;
10126 	case BPF_FUNC_current_task_under_cgroup:
10127 	case BPF_FUNC_skb_under_cgroup:
10128 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10129 			goto error;
10130 		break;
10131 	case BPF_FUNC_redirect_map:
10132 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10133 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10134 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10135 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10136 			goto error;
10137 		break;
10138 	case BPF_FUNC_sk_redirect_map:
10139 	case BPF_FUNC_msg_redirect_map:
10140 	case BPF_FUNC_sock_map_update:
10141 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10142 			goto error;
10143 		break;
10144 	case BPF_FUNC_sk_redirect_hash:
10145 	case BPF_FUNC_msg_redirect_hash:
10146 	case BPF_FUNC_sock_hash_update:
10147 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10148 			goto error;
10149 		break;
10150 	case BPF_FUNC_get_local_storage:
10151 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10152 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10153 			goto error;
10154 		break;
10155 	case BPF_FUNC_sk_select_reuseport:
10156 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10157 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10158 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10159 			goto error;
10160 		break;
10161 	case BPF_FUNC_map_pop_elem:
10162 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10163 		    map->map_type != BPF_MAP_TYPE_STACK)
10164 			goto error;
10165 		break;
10166 	case BPF_FUNC_map_peek_elem:
10167 	case BPF_FUNC_map_push_elem:
10168 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10169 		    map->map_type != BPF_MAP_TYPE_STACK &&
10170 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10171 			goto error;
10172 		break;
10173 	case BPF_FUNC_map_lookup_percpu_elem:
10174 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10175 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10176 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10177 			goto error;
10178 		break;
10179 	case BPF_FUNC_sk_storage_get:
10180 	case BPF_FUNC_sk_storage_delete:
10181 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10182 			goto error;
10183 		break;
10184 	case BPF_FUNC_inode_storage_get:
10185 	case BPF_FUNC_inode_storage_delete:
10186 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10187 			goto error;
10188 		break;
10189 	case BPF_FUNC_task_storage_get:
10190 	case BPF_FUNC_task_storage_delete:
10191 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10192 			goto error;
10193 		break;
10194 	case BPF_FUNC_cgrp_storage_get:
10195 	case BPF_FUNC_cgrp_storage_delete:
10196 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10197 			goto error;
10198 		break;
10199 	default:
10200 		break;
10201 	}
10202 
10203 	return 0;
10204 error:
10205 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10206 		map->map_type, func_id_name(func_id), func_id);
10207 	return -EINVAL;
10208 }
10209 
check_raw_mode_ok(const struct bpf_func_proto * fn)10210 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10211 {
10212 	int count = 0;
10213 
10214 	if (arg_type_is_raw_mem(fn->arg1_type))
10215 		count++;
10216 	if (arg_type_is_raw_mem(fn->arg2_type))
10217 		count++;
10218 	if (arg_type_is_raw_mem(fn->arg3_type))
10219 		count++;
10220 	if (arg_type_is_raw_mem(fn->arg4_type))
10221 		count++;
10222 	if (arg_type_is_raw_mem(fn->arg5_type))
10223 		count++;
10224 
10225 	/* We only support one arg being in raw mode at the moment,
10226 	 * which is sufficient for the helper functions we have
10227 	 * right now.
10228 	 */
10229 	return count <= 1;
10230 }
10231 
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)10232 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10233 {
10234 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10235 	bool has_size = fn->arg_size[arg] != 0;
10236 	bool is_next_size = false;
10237 
10238 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10239 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10240 
10241 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10242 		return is_next_size;
10243 
10244 	return has_size == is_next_size || is_next_size == is_fixed;
10245 }
10246 
check_arg_pair_ok(const struct bpf_func_proto * fn)10247 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10248 {
10249 	/* bpf_xxx(..., buf, len) call will access 'len'
10250 	 * bytes from memory 'buf'. Both arg types need
10251 	 * to be paired, so make sure there's no buggy
10252 	 * helper function specification.
10253 	 */
10254 	if (arg_type_is_mem_size(fn->arg1_type) ||
10255 	    check_args_pair_invalid(fn, 0) ||
10256 	    check_args_pair_invalid(fn, 1) ||
10257 	    check_args_pair_invalid(fn, 2) ||
10258 	    check_args_pair_invalid(fn, 3) ||
10259 	    check_args_pair_invalid(fn, 4))
10260 		return false;
10261 
10262 	return true;
10263 }
10264 
check_btf_id_ok(const struct bpf_func_proto * fn)10265 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10266 {
10267 	int i;
10268 
10269 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10270 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10271 			return !!fn->arg_btf_id[i];
10272 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10273 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10274 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10275 		    /* arg_btf_id and arg_size are in a union. */
10276 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10277 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10278 			return false;
10279 	}
10280 
10281 	return true;
10282 }
10283 
check_func_proto(const struct bpf_func_proto * fn,int func_id)10284 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10285 {
10286 	return check_raw_mode_ok(fn) &&
10287 	       check_arg_pair_ok(fn) &&
10288 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10289 }
10290 
10291 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10292  * are now invalid, so turn them into unknown SCALAR_VALUE.
10293  *
10294  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10295  * since these slices point to packet data.
10296  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)10297 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10298 {
10299 	struct bpf_func_state *state;
10300 	struct bpf_reg_state *reg;
10301 
10302 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10303 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10304 			mark_reg_invalid(env, reg);
10305 	}));
10306 }
10307 
10308 enum {
10309 	AT_PKT_END = -1,
10310 	BEYOND_PKT_END = -2,
10311 };
10312 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)10313 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10314 {
10315 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10316 	struct bpf_reg_state *reg = &state->regs[regn];
10317 
10318 	if (reg->type != PTR_TO_PACKET)
10319 		/* PTR_TO_PACKET_META is not supported yet */
10320 		return;
10321 
10322 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10323 	 * How far beyond pkt_end it goes is unknown.
10324 	 * if (!range_open) it's the case of pkt >= pkt_end
10325 	 * if (range_open) it's the case of pkt > pkt_end
10326 	 * hence this pointer is at least 1 byte bigger than pkt_end
10327 	 */
10328 	if (range_open)
10329 		reg->range = BEYOND_PKT_END;
10330 	else
10331 		reg->range = AT_PKT_END;
10332 }
10333 
release_reference_nomark(struct bpf_verifier_state * state,int ref_obj_id)10334 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10335 {
10336 	int i;
10337 
10338 	for (i = 0; i < state->acquired_refs; i++) {
10339 		if (state->refs[i].type != REF_TYPE_PTR)
10340 			continue;
10341 		if (state->refs[i].id == ref_obj_id) {
10342 			release_reference_state(state, i);
10343 			return 0;
10344 		}
10345 	}
10346 	return -EINVAL;
10347 }
10348 
10349 /* The pointer with the specified id has released its reference to kernel
10350  * resources. Identify all copies of the same pointer and clear the reference.
10351  *
10352  * This is the release function corresponding to acquire_reference(). Idempotent.
10353  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)10354 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10355 {
10356 	struct bpf_verifier_state *vstate = env->cur_state;
10357 	struct bpf_func_state *state;
10358 	struct bpf_reg_state *reg;
10359 	int err;
10360 
10361 	err = release_reference_nomark(vstate, ref_obj_id);
10362 	if (err)
10363 		return err;
10364 
10365 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10366 		if (reg->ref_obj_id == ref_obj_id)
10367 			mark_reg_invalid(env, reg);
10368 	}));
10369 
10370 	return 0;
10371 }
10372 
invalidate_non_owning_refs(struct bpf_verifier_env * env)10373 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10374 {
10375 	struct bpf_func_state *unused;
10376 	struct bpf_reg_state *reg;
10377 
10378 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10379 		if (type_is_non_owning_ref(reg->type))
10380 			mark_reg_invalid(env, reg);
10381 	}));
10382 }
10383 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)10384 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10385 				    struct bpf_reg_state *regs)
10386 {
10387 	int i;
10388 
10389 	/* after the call registers r0 - r5 were scratched */
10390 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10391 		mark_reg_not_init(env, regs, caller_saved[i]);
10392 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10393 	}
10394 }
10395 
10396 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10397 				   struct bpf_func_state *caller,
10398 				   struct bpf_func_state *callee,
10399 				   int insn_idx);
10400 
10401 static int set_callee_state(struct bpf_verifier_env *env,
10402 			    struct bpf_func_state *caller,
10403 			    struct bpf_func_state *callee, int insn_idx);
10404 
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)10405 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10406 			    set_callee_state_fn set_callee_state_cb,
10407 			    struct bpf_verifier_state *state)
10408 {
10409 	struct bpf_func_state *caller, *callee;
10410 	int err;
10411 
10412 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10413 		verbose(env, "the call stack of %d frames is too deep\n",
10414 			state->curframe + 2);
10415 		return -E2BIG;
10416 	}
10417 
10418 	if (state->frame[state->curframe + 1]) {
10419 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10420 		return -EFAULT;
10421 	}
10422 
10423 	caller = state->frame[state->curframe];
10424 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10425 	if (!callee)
10426 		return -ENOMEM;
10427 	state->frame[state->curframe + 1] = callee;
10428 
10429 	/* callee cannot access r0, r6 - r9 for reading and has to write
10430 	 * into its own stack before reading from it.
10431 	 * callee can read/write into caller's stack
10432 	 */
10433 	init_func_state(env, callee,
10434 			/* remember the callsite, it will be used by bpf_exit */
10435 			callsite,
10436 			state->curframe + 1 /* frameno within this callchain */,
10437 			subprog /* subprog number within this prog */);
10438 	err = set_callee_state_cb(env, caller, callee, callsite);
10439 	if (err)
10440 		goto err_out;
10441 
10442 	/* only increment it after check_reg_arg() finished */
10443 	state->curframe++;
10444 
10445 	return 0;
10446 
10447 err_out:
10448 	free_func_state(callee);
10449 	state->frame[state->curframe + 1] = NULL;
10450 	return err;
10451 }
10452 
btf_check_func_arg_match(struct bpf_verifier_env * env,int subprog,const struct btf * btf,struct bpf_reg_state * regs)10453 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10454 				    const struct btf *btf,
10455 				    struct bpf_reg_state *regs)
10456 {
10457 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10458 	struct bpf_verifier_log *log = &env->log;
10459 	u32 i;
10460 	int ret;
10461 
10462 	ret = btf_prepare_func_args(env, subprog);
10463 	if (ret)
10464 		return ret;
10465 
10466 	/* check that BTF function arguments match actual types that the
10467 	 * verifier sees.
10468 	 */
10469 	for (i = 0; i < sub->arg_cnt; i++) {
10470 		u32 regno = i + 1;
10471 		struct bpf_reg_state *reg = &regs[regno];
10472 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10473 
10474 		if (arg->arg_type == ARG_ANYTHING) {
10475 			if (reg->type != SCALAR_VALUE) {
10476 				bpf_log(log, "R%d is not a scalar\n", regno);
10477 				return -EINVAL;
10478 			}
10479 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10480 			/*
10481 			 * Anything is allowed for untrusted arguments, as these are
10482 			 * read-only and probe read instructions would protect against
10483 			 * invalid memory access.
10484 			 */
10485 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10486 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10487 			if (ret < 0)
10488 				return ret;
10489 			/* If function expects ctx type in BTF check that caller
10490 			 * is passing PTR_TO_CTX.
10491 			 */
10492 			if (reg->type != PTR_TO_CTX) {
10493 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10494 				return -EINVAL;
10495 			}
10496 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10497 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10498 			if (ret < 0)
10499 				return ret;
10500 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10501 				return -EINVAL;
10502 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10503 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10504 				return -EINVAL;
10505 			}
10506 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10507 			/*
10508 			 * Can pass any value and the kernel won't crash, but
10509 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10510 			 * else is a bug in the bpf program. Point it out to
10511 			 * the user at the verification time instead of
10512 			 * run-time debug nightmare.
10513 			 */
10514 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10515 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10516 				return -EINVAL;
10517 			}
10518 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10519 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10520 			if (ret)
10521 				return ret;
10522 
10523 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10524 			if (ret)
10525 				return ret;
10526 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10527 			struct bpf_call_arg_meta meta;
10528 			int err;
10529 
10530 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10531 				continue;
10532 
10533 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10534 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10535 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10536 			if (err)
10537 				return err;
10538 		} else {
10539 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10540 			return -EFAULT;
10541 		}
10542 	}
10543 
10544 	return 0;
10545 }
10546 
10547 /* Compare BTF of a function call with given bpf_reg_state.
10548  * Returns:
10549  * EFAULT - there is a verifier bug. Abort verification.
10550  * EINVAL - there is a type mismatch or BTF is not available.
10551  * 0 - BTF matches with what bpf_reg_state expects.
10552  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10553  */
btf_check_subprog_call(struct bpf_verifier_env * env,int subprog,struct bpf_reg_state * regs)10554 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10555 				  struct bpf_reg_state *regs)
10556 {
10557 	struct bpf_prog *prog = env->prog;
10558 	struct btf *btf = prog->aux->btf;
10559 	u32 btf_id;
10560 	int err;
10561 
10562 	if (!prog->aux->func_info)
10563 		return -EINVAL;
10564 
10565 	btf_id = prog->aux->func_info[subprog].type_id;
10566 	if (!btf_id)
10567 		return -EFAULT;
10568 
10569 	if (prog->aux->func_info_aux[subprog].unreliable)
10570 		return -EINVAL;
10571 
10572 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10573 	/* Compiler optimizations can remove arguments from static functions
10574 	 * or mismatched type can be passed into a global function.
10575 	 * In such cases mark the function as unreliable from BTF point of view.
10576 	 */
10577 	if (err)
10578 		prog->aux->func_info_aux[subprog].unreliable = true;
10579 	return err;
10580 }
10581 
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)10582 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10583 			      int insn_idx, int subprog,
10584 			      set_callee_state_fn set_callee_state_cb)
10585 {
10586 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10587 	struct bpf_func_state *caller, *callee;
10588 	int err;
10589 
10590 	caller = state->frame[state->curframe];
10591 	err = btf_check_subprog_call(env, subprog, caller->regs);
10592 	if (err == -EFAULT)
10593 		return err;
10594 
10595 	/* set_callee_state is used for direct subprog calls, but we are
10596 	 * interested in validating only BPF helpers that can call subprogs as
10597 	 * callbacks
10598 	 */
10599 	env->subprog_info[subprog].is_cb = true;
10600 	if (bpf_pseudo_kfunc_call(insn) &&
10601 	    !is_callback_calling_kfunc(insn->imm)) {
10602 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10603 			     func_id_name(insn->imm), insn->imm);
10604 		return -EFAULT;
10605 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10606 		   !is_callback_calling_function(insn->imm)) { /* helper */
10607 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10608 			     func_id_name(insn->imm), insn->imm);
10609 		return -EFAULT;
10610 	}
10611 
10612 	if (is_async_callback_calling_insn(insn)) {
10613 		struct bpf_verifier_state *async_cb;
10614 
10615 		/* there is no real recursion here. timer and workqueue callbacks are async */
10616 		env->subprog_info[subprog].is_async_cb = true;
10617 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10618 					 insn_idx, subprog,
10619 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
10620 		if (!async_cb)
10621 			return -EFAULT;
10622 		callee = async_cb->frame[0];
10623 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10624 
10625 		/* Convert bpf_timer_set_callback() args into timer callback args */
10626 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10627 		if (err)
10628 			return err;
10629 
10630 		return 0;
10631 	}
10632 
10633 	/* for callback functions enqueue entry to callback and
10634 	 * proceed with next instruction within current frame.
10635 	 */
10636 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10637 	if (!callback_state)
10638 		return -ENOMEM;
10639 
10640 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10641 			       callback_state);
10642 	if (err)
10643 		return err;
10644 
10645 	callback_state->callback_unroll_depth++;
10646 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10647 	caller->callback_depth = 0;
10648 	return 0;
10649 }
10650 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)10651 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10652 			   int *insn_idx)
10653 {
10654 	struct bpf_verifier_state *state = env->cur_state;
10655 	struct bpf_func_state *caller;
10656 	int err, subprog, target_insn;
10657 
10658 	target_insn = *insn_idx + insn->imm + 1;
10659 	subprog = find_subprog(env, target_insn);
10660 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10661 			    target_insn))
10662 		return -EFAULT;
10663 
10664 	caller = state->frame[state->curframe];
10665 	err = btf_check_subprog_call(env, subprog, caller->regs);
10666 	if (err == -EFAULT)
10667 		return err;
10668 	if (subprog_is_global(env, subprog)) {
10669 		const char *sub_name = subprog_name(env, subprog);
10670 
10671 		if (env->cur_state->active_locks) {
10672 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10673 				     "use static function instead\n");
10674 			return -EINVAL;
10675 		}
10676 
10677 		if (env->subprog_info[subprog].might_sleep &&
10678 		    (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks ||
10679 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10680 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10681 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10682 				     "a non-sleepable BPF program context\n");
10683 			return -EINVAL;
10684 		}
10685 
10686 		if (err) {
10687 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10688 				subprog, sub_name);
10689 			return err;
10690 		}
10691 
10692 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10693 			subprog, sub_name);
10694 		if (env->subprog_info[subprog].changes_pkt_data)
10695 			clear_all_pkt_pointers(env);
10696 		/* mark global subprog for verifying after main prog */
10697 		subprog_aux(env, subprog)->called = true;
10698 		clear_caller_saved_regs(env, caller->regs);
10699 
10700 		/* All global functions return a 64-bit SCALAR_VALUE */
10701 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10702 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10703 
10704 		/* continue with next insn after call */
10705 		return 0;
10706 	}
10707 
10708 	/* for regular function entry setup new frame and continue
10709 	 * from that frame.
10710 	 */
10711 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10712 	if (err)
10713 		return err;
10714 
10715 	clear_caller_saved_regs(env, caller->regs);
10716 
10717 	/* and go analyze first insn of the callee */
10718 	*insn_idx = env->subprog_info[subprog].start - 1;
10719 
10720 	if (env->log.level & BPF_LOG_LEVEL) {
10721 		verbose(env, "caller:\n");
10722 		print_verifier_state(env, state, caller->frameno, true);
10723 		verbose(env, "callee:\n");
10724 		print_verifier_state(env, state, state->curframe, true);
10725 	}
10726 
10727 	return 0;
10728 }
10729 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)10730 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10731 				   struct bpf_func_state *caller,
10732 				   struct bpf_func_state *callee)
10733 {
10734 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10735 	 *      void *callback_ctx, u64 flags);
10736 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10737 	 *      void *callback_ctx);
10738 	 */
10739 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10740 
10741 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10742 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10743 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10744 
10745 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10746 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10747 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10748 
10749 	/* pointer to stack or null */
10750 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10751 
10752 	/* unused */
10753 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10754 	return 0;
10755 }
10756 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10757 static int set_callee_state(struct bpf_verifier_env *env,
10758 			    struct bpf_func_state *caller,
10759 			    struct bpf_func_state *callee, int insn_idx)
10760 {
10761 	int i;
10762 
10763 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10764 	 * pointers, which connects us up to the liveness chain
10765 	 */
10766 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10767 		callee->regs[i] = caller->regs[i];
10768 	return 0;
10769 }
10770 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10771 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10772 				       struct bpf_func_state *caller,
10773 				       struct bpf_func_state *callee,
10774 				       int insn_idx)
10775 {
10776 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10777 	struct bpf_map *map;
10778 	int err;
10779 
10780 	/* valid map_ptr and poison value does not matter */
10781 	map = insn_aux->map_ptr_state.map_ptr;
10782 	if (!map->ops->map_set_for_each_callback_args ||
10783 	    !map->ops->map_for_each_callback) {
10784 		verbose(env, "callback function not allowed for map\n");
10785 		return -ENOTSUPP;
10786 	}
10787 
10788 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10789 	if (err)
10790 		return err;
10791 
10792 	callee->in_callback_fn = true;
10793 	callee->callback_ret_range = retval_range(0, 1);
10794 	return 0;
10795 }
10796 
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10797 static int set_loop_callback_state(struct bpf_verifier_env *env,
10798 				   struct bpf_func_state *caller,
10799 				   struct bpf_func_state *callee,
10800 				   int insn_idx)
10801 {
10802 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10803 	 *	    u64 flags);
10804 	 * callback_fn(u64 index, void *callback_ctx);
10805 	 */
10806 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10807 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10808 
10809 	/* unused */
10810 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10811 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10812 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10813 
10814 	callee->in_callback_fn = true;
10815 	callee->callback_ret_range = retval_range(0, 1);
10816 	return 0;
10817 }
10818 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10819 static int set_timer_callback_state(struct bpf_verifier_env *env,
10820 				    struct bpf_func_state *caller,
10821 				    struct bpf_func_state *callee,
10822 				    int insn_idx)
10823 {
10824 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10825 
10826 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10827 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10828 	 */
10829 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10830 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10831 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10832 
10833 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10834 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10835 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10836 
10837 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10838 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10839 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10840 
10841 	/* unused */
10842 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10843 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10844 	callee->in_async_callback_fn = true;
10845 	callee->callback_ret_range = retval_range(0, 1);
10846 	return 0;
10847 }
10848 
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10849 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10850 				       struct bpf_func_state *caller,
10851 				       struct bpf_func_state *callee,
10852 				       int insn_idx)
10853 {
10854 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10855 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10856 	 * (callback_fn)(struct task_struct *task,
10857 	 *               struct vm_area_struct *vma, void *callback_ctx);
10858 	 */
10859 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10860 
10861 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10862 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10863 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10864 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10865 
10866 	/* pointer to stack or null */
10867 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10868 
10869 	/* unused */
10870 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10871 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10872 	callee->in_callback_fn = true;
10873 	callee->callback_ret_range = retval_range(0, 1);
10874 	return 0;
10875 }
10876 
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10877 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10878 					   struct bpf_func_state *caller,
10879 					   struct bpf_func_state *callee,
10880 					   int insn_idx)
10881 {
10882 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10883 	 *			  callback_ctx, u64 flags);
10884 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10885 	 */
10886 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10887 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10888 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10889 
10890 	/* unused */
10891 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10892 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10893 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10894 
10895 	callee->in_callback_fn = true;
10896 	callee->callback_ret_range = retval_range(0, 1);
10897 	return 0;
10898 }
10899 
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10900 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10901 					 struct bpf_func_state *caller,
10902 					 struct bpf_func_state *callee,
10903 					 int insn_idx)
10904 {
10905 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10906 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10907 	 *
10908 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10909 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10910 	 * by this point, so look at 'root'
10911 	 */
10912 	struct btf_field *field;
10913 
10914 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10915 				      BPF_RB_ROOT);
10916 	if (!field || !field->graph_root.value_btf_id)
10917 		return -EFAULT;
10918 
10919 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10920 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10921 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10922 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10923 
10924 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10925 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10926 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10927 	callee->in_callback_fn = true;
10928 	callee->callback_ret_range = retval_range(0, 1);
10929 	return 0;
10930 }
10931 
10932 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10933 
10934 /* Are we currently verifying the callback for a rbtree helper that must
10935  * be called with lock held? If so, no need to complain about unreleased
10936  * lock
10937  */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)10938 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10939 {
10940 	struct bpf_verifier_state *state = env->cur_state;
10941 	struct bpf_insn *insn = env->prog->insnsi;
10942 	struct bpf_func_state *callee;
10943 	int kfunc_btf_id;
10944 
10945 	if (!state->curframe)
10946 		return false;
10947 
10948 	callee = state->frame[state->curframe];
10949 
10950 	if (!callee->in_callback_fn)
10951 		return false;
10952 
10953 	kfunc_btf_id = insn[callee->callsite].imm;
10954 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10955 }
10956 
retval_range_within(struct bpf_retval_range range,const struct bpf_reg_state * reg,bool return_32bit)10957 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10958 				bool return_32bit)
10959 {
10960 	if (return_32bit)
10961 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10962 	else
10963 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10964 }
10965 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)10966 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10967 {
10968 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10969 	struct bpf_func_state *caller, *callee;
10970 	struct bpf_reg_state *r0;
10971 	bool in_callback_fn;
10972 	int err;
10973 
10974 	callee = state->frame[state->curframe];
10975 	r0 = &callee->regs[BPF_REG_0];
10976 	if (r0->type == PTR_TO_STACK) {
10977 		/* technically it's ok to return caller's stack pointer
10978 		 * (or caller's caller's pointer) back to the caller,
10979 		 * since these pointers are valid. Only current stack
10980 		 * pointer will be invalid as soon as function exits,
10981 		 * but let's be conservative
10982 		 */
10983 		verbose(env, "cannot return stack pointer to the caller\n");
10984 		return -EINVAL;
10985 	}
10986 
10987 	caller = state->frame[state->curframe - 1];
10988 	if (callee->in_callback_fn) {
10989 		if (r0->type != SCALAR_VALUE) {
10990 			verbose(env, "R0 not a scalar value\n");
10991 			return -EACCES;
10992 		}
10993 
10994 		/* we are going to rely on register's precise value */
10995 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
10996 		err = err ?: mark_chain_precision(env, BPF_REG_0);
10997 		if (err)
10998 			return err;
10999 
11000 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11001 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11002 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11003 					       "At callback return", "R0");
11004 			return -EINVAL;
11005 		}
11006 		if (!calls_callback(env, callee->callsite)) {
11007 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11008 				     *insn_idx, callee->callsite);
11009 			return -EFAULT;
11010 		}
11011 	} else {
11012 		/* return to the caller whatever r0 had in the callee */
11013 		caller->regs[BPF_REG_0] = *r0;
11014 	}
11015 
11016 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11017 	 * there function call logic would reschedule callback visit. If iteration
11018 	 * converges is_state_visited() would prune that visit eventually.
11019 	 */
11020 	in_callback_fn = callee->in_callback_fn;
11021 	if (in_callback_fn)
11022 		*insn_idx = callee->callsite;
11023 	else
11024 		*insn_idx = callee->callsite + 1;
11025 
11026 	if (env->log.level & BPF_LOG_LEVEL) {
11027 		verbose(env, "returning from callee:\n");
11028 		print_verifier_state(env, state, callee->frameno, true);
11029 		verbose(env, "to caller at %d:\n", *insn_idx);
11030 		print_verifier_state(env, state, caller->frameno, true);
11031 	}
11032 	/* clear everything in the callee. In case of exceptional exits using
11033 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11034 	free_func_state(callee);
11035 	state->frame[state->curframe--] = NULL;
11036 
11037 	/* for callbacks widen imprecise scalars to make programs like below verify:
11038 	 *
11039 	 *   struct ctx { int i; }
11040 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11041 	 *   ...
11042 	 *   struct ctx = { .i = 0; }
11043 	 *   bpf_loop(100, cb, &ctx, 0);
11044 	 *
11045 	 * This is similar to what is done in process_iter_next_call() for open
11046 	 * coded iterators.
11047 	 */
11048 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11049 	if (prev_st) {
11050 		err = widen_imprecise_scalars(env, prev_st, state);
11051 		if (err)
11052 			return err;
11053 	}
11054 	return 0;
11055 }
11056 
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)11057 static int do_refine_retval_range(struct bpf_verifier_env *env,
11058 				  struct bpf_reg_state *regs, int ret_type,
11059 				  int func_id,
11060 				  struct bpf_call_arg_meta *meta)
11061 {
11062 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11063 
11064 	if (ret_type != RET_INTEGER)
11065 		return 0;
11066 
11067 	switch (func_id) {
11068 	case BPF_FUNC_get_stack:
11069 	case BPF_FUNC_get_task_stack:
11070 	case BPF_FUNC_probe_read_str:
11071 	case BPF_FUNC_probe_read_kernel_str:
11072 	case BPF_FUNC_probe_read_user_str:
11073 		ret_reg->smax_value = meta->msize_max_value;
11074 		ret_reg->s32_max_value = meta->msize_max_value;
11075 		ret_reg->smin_value = -MAX_ERRNO;
11076 		ret_reg->s32_min_value = -MAX_ERRNO;
11077 		reg_bounds_sync(ret_reg);
11078 		break;
11079 	case BPF_FUNC_get_smp_processor_id:
11080 		ret_reg->umax_value = nr_cpu_ids - 1;
11081 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11082 		ret_reg->smax_value = nr_cpu_ids - 1;
11083 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11084 		ret_reg->umin_value = 0;
11085 		ret_reg->u32_min_value = 0;
11086 		ret_reg->smin_value = 0;
11087 		ret_reg->s32_min_value = 0;
11088 		reg_bounds_sync(ret_reg);
11089 		break;
11090 	}
11091 
11092 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11093 }
11094 
11095 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11096 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11097 		int func_id, int insn_idx)
11098 {
11099 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11100 	struct bpf_map *map = meta->map_ptr;
11101 
11102 	if (func_id != BPF_FUNC_tail_call &&
11103 	    func_id != BPF_FUNC_map_lookup_elem &&
11104 	    func_id != BPF_FUNC_map_update_elem &&
11105 	    func_id != BPF_FUNC_map_delete_elem &&
11106 	    func_id != BPF_FUNC_map_push_elem &&
11107 	    func_id != BPF_FUNC_map_pop_elem &&
11108 	    func_id != BPF_FUNC_map_peek_elem &&
11109 	    func_id != BPF_FUNC_for_each_map_elem &&
11110 	    func_id != BPF_FUNC_redirect_map &&
11111 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11112 		return 0;
11113 
11114 	if (map == NULL) {
11115 		verifier_bug(env, "expected map for helper call");
11116 		return -EFAULT;
11117 	}
11118 
11119 	/* In case of read-only, some additional restrictions
11120 	 * need to be applied in order to prevent altering the
11121 	 * state of the map from program side.
11122 	 */
11123 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11124 	    (func_id == BPF_FUNC_map_delete_elem ||
11125 	     func_id == BPF_FUNC_map_update_elem ||
11126 	     func_id == BPF_FUNC_map_push_elem ||
11127 	     func_id == BPF_FUNC_map_pop_elem)) {
11128 		verbose(env, "write into map forbidden\n");
11129 		return -EACCES;
11130 	}
11131 
11132 	if (!aux->map_ptr_state.map_ptr)
11133 		bpf_map_ptr_store(aux, meta->map_ptr,
11134 				  !meta->map_ptr->bypass_spec_v1, false);
11135 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11136 		bpf_map_ptr_store(aux, meta->map_ptr,
11137 				  !meta->map_ptr->bypass_spec_v1, true);
11138 	return 0;
11139 }
11140 
11141 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11142 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11143 		int func_id, int insn_idx)
11144 {
11145 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11146 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11147 	struct bpf_map *map = meta->map_ptr;
11148 	u64 val, max;
11149 	int err;
11150 
11151 	if (func_id != BPF_FUNC_tail_call)
11152 		return 0;
11153 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11154 		verbose(env, "expected prog array map for tail call");
11155 		return -EINVAL;
11156 	}
11157 
11158 	reg = &regs[BPF_REG_3];
11159 	val = reg->var_off.value;
11160 	max = map->max_entries;
11161 
11162 	if (!(is_reg_const(reg, false) && val < max)) {
11163 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11164 		return 0;
11165 	}
11166 
11167 	err = mark_chain_precision(env, BPF_REG_3);
11168 	if (err)
11169 		return err;
11170 	if (bpf_map_key_unseen(aux))
11171 		bpf_map_key_store(aux, val);
11172 	else if (!bpf_map_key_poisoned(aux) &&
11173 		  bpf_map_key_immediate(aux) != val)
11174 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11175 	return 0;
11176 }
11177 
check_reference_leak(struct bpf_verifier_env * env,bool exception_exit)11178 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11179 {
11180 	struct bpf_verifier_state *state = env->cur_state;
11181 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11182 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11183 	bool refs_lingering = false;
11184 	int i;
11185 
11186 	if (!exception_exit && cur_func(env)->frameno)
11187 		return 0;
11188 
11189 	for (i = 0; i < state->acquired_refs; i++) {
11190 		if (state->refs[i].type != REF_TYPE_PTR)
11191 			continue;
11192 		/* Allow struct_ops programs to return a referenced kptr back to
11193 		 * kernel. Type checks are performed later in check_return_code.
11194 		 */
11195 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11196 		    reg->ref_obj_id == state->refs[i].id)
11197 			continue;
11198 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11199 			state->refs[i].id, state->refs[i].insn_idx);
11200 		refs_lingering = true;
11201 	}
11202 	return refs_lingering ? -EINVAL : 0;
11203 }
11204 
check_resource_leak(struct bpf_verifier_env * env,bool exception_exit,bool check_lock,const char * prefix)11205 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11206 {
11207 	int err;
11208 
11209 	if (check_lock && env->cur_state->active_locks) {
11210 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11211 		return -EINVAL;
11212 	}
11213 
11214 	err = check_reference_leak(env, exception_exit);
11215 	if (err) {
11216 		verbose(env, "%s would lead to reference leak\n", prefix);
11217 		return err;
11218 	}
11219 
11220 	if (check_lock && env->cur_state->active_irq_id) {
11221 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11222 		return -EINVAL;
11223 	}
11224 
11225 	if (check_lock && env->cur_state->active_rcu_lock) {
11226 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11227 		return -EINVAL;
11228 	}
11229 
11230 	if (check_lock && env->cur_state->active_preempt_locks) {
11231 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11232 		return -EINVAL;
11233 	}
11234 
11235 	return 0;
11236 }
11237 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)11238 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11239 				   struct bpf_reg_state *regs)
11240 {
11241 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11242 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11243 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11244 	struct bpf_bprintf_data data = {};
11245 	int err, fmt_map_off, num_args;
11246 	u64 fmt_addr;
11247 	char *fmt;
11248 
11249 	/* data must be an array of u64 */
11250 	if (data_len_reg->var_off.value % 8)
11251 		return -EINVAL;
11252 	num_args = data_len_reg->var_off.value / 8;
11253 
11254 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11255 	 * and map_direct_value_addr is set.
11256 	 */
11257 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11258 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11259 						  fmt_map_off);
11260 	if (err) {
11261 		verbose(env, "failed to retrieve map value address\n");
11262 		return -EFAULT;
11263 	}
11264 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11265 
11266 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11267 	 * can focus on validating the format specifiers.
11268 	 */
11269 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11270 	if (err < 0)
11271 		verbose(env, "Invalid format string\n");
11272 
11273 	return err;
11274 }
11275 
check_get_func_ip(struct bpf_verifier_env * env)11276 static int check_get_func_ip(struct bpf_verifier_env *env)
11277 {
11278 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11279 	int func_id = BPF_FUNC_get_func_ip;
11280 
11281 	if (type == BPF_PROG_TYPE_TRACING) {
11282 		if (!bpf_prog_has_trampoline(env->prog)) {
11283 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11284 				func_id_name(func_id), func_id);
11285 			return -ENOTSUPP;
11286 		}
11287 		return 0;
11288 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11289 		return 0;
11290 	}
11291 
11292 	verbose(env, "func %s#%d not supported for program type %d\n",
11293 		func_id_name(func_id), func_id, type);
11294 	return -ENOTSUPP;
11295 }
11296 
cur_aux(const struct bpf_verifier_env * env)11297 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11298 {
11299 	return &env->insn_aux_data[env->insn_idx];
11300 }
11301 
loop_flag_is_zero(struct bpf_verifier_env * env)11302 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11303 {
11304 	struct bpf_reg_state *regs = cur_regs(env);
11305 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11306 	bool reg_is_null = register_is_null(reg);
11307 
11308 	if (reg_is_null)
11309 		mark_chain_precision(env, BPF_REG_4);
11310 
11311 	return reg_is_null;
11312 }
11313 
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)11314 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11315 {
11316 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11317 
11318 	if (!state->initialized) {
11319 		state->initialized = 1;
11320 		state->fit_for_inline = loop_flag_is_zero(env);
11321 		state->callback_subprogno = subprogno;
11322 		return;
11323 	}
11324 
11325 	if (!state->fit_for_inline)
11326 		return;
11327 
11328 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11329 				 state->callback_subprogno == subprogno);
11330 }
11331 
11332 /* Returns whether or not the given map type can potentially elide
11333  * lookup return value nullness check. This is possible if the key
11334  * is statically known.
11335  */
can_elide_value_nullness(enum bpf_map_type type)11336 static bool can_elide_value_nullness(enum bpf_map_type type)
11337 {
11338 	switch (type) {
11339 	case BPF_MAP_TYPE_ARRAY:
11340 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11341 		return true;
11342 	default:
11343 		return false;
11344 	}
11345 }
11346 
get_helper_proto(struct bpf_verifier_env * env,int func_id,const struct bpf_func_proto ** ptr)11347 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11348 			    const struct bpf_func_proto **ptr)
11349 {
11350 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11351 		return -ERANGE;
11352 
11353 	if (!env->ops->get_func_proto)
11354 		return -EINVAL;
11355 
11356 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11357 	return *ptr ? 0 : -EINVAL;
11358 }
11359 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11360 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11361 			     int *insn_idx_p)
11362 {
11363 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11364 	bool returns_cpu_specific_alloc_ptr = false;
11365 	const struct bpf_func_proto *fn = NULL;
11366 	enum bpf_return_type ret_type;
11367 	enum bpf_type_flag ret_flag;
11368 	struct bpf_reg_state *regs;
11369 	struct bpf_call_arg_meta meta;
11370 	int insn_idx = *insn_idx_p;
11371 	bool changes_data;
11372 	int i, err, func_id;
11373 
11374 	/* find function prototype */
11375 	func_id = insn->imm;
11376 	err = get_helper_proto(env, insn->imm, &fn);
11377 	if (err == -ERANGE) {
11378 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11379 		return -EINVAL;
11380 	}
11381 
11382 	if (err) {
11383 		verbose(env, "program of this type cannot use helper %s#%d\n",
11384 			func_id_name(func_id), func_id);
11385 		return err;
11386 	}
11387 
11388 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11389 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11390 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11391 		return -EINVAL;
11392 	}
11393 
11394 	if (fn->allowed && !fn->allowed(env->prog)) {
11395 		verbose(env, "helper call is not allowed in probe\n");
11396 		return -EINVAL;
11397 	}
11398 
11399 	if (!in_sleepable(env) && fn->might_sleep) {
11400 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11401 		return -EINVAL;
11402 	}
11403 
11404 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11405 	changes_data = bpf_helper_changes_pkt_data(func_id);
11406 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11407 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11408 		return -EFAULT;
11409 	}
11410 
11411 	memset(&meta, 0, sizeof(meta));
11412 	meta.pkt_access = fn->pkt_access;
11413 
11414 	err = check_func_proto(fn, func_id);
11415 	if (err) {
11416 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11417 		return err;
11418 	}
11419 
11420 	if (env->cur_state->active_rcu_lock) {
11421 		if (fn->might_sleep) {
11422 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11423 				func_id_name(func_id), func_id);
11424 			return -EINVAL;
11425 		}
11426 
11427 		if (in_sleepable(env) && is_storage_get_function(func_id))
11428 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11429 	}
11430 
11431 	if (env->cur_state->active_preempt_locks) {
11432 		if (fn->might_sleep) {
11433 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11434 				func_id_name(func_id), func_id);
11435 			return -EINVAL;
11436 		}
11437 
11438 		if (in_sleepable(env) && is_storage_get_function(func_id))
11439 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11440 	}
11441 
11442 	if (env->cur_state->active_irq_id) {
11443 		if (fn->might_sleep) {
11444 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11445 				func_id_name(func_id), func_id);
11446 			return -EINVAL;
11447 		}
11448 
11449 		if (in_sleepable(env) && is_storage_get_function(func_id))
11450 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11451 	}
11452 
11453 	meta.func_id = func_id;
11454 	/* check args */
11455 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11456 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11457 		if (err)
11458 			return err;
11459 	}
11460 
11461 	err = record_func_map(env, &meta, func_id, insn_idx);
11462 	if (err)
11463 		return err;
11464 
11465 	err = record_func_key(env, &meta, func_id, insn_idx);
11466 	if (err)
11467 		return err;
11468 
11469 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11470 	 * is inferred from register state.
11471 	 */
11472 	for (i = 0; i < meta.access_size; i++) {
11473 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11474 				       BPF_WRITE, -1, false, false);
11475 		if (err)
11476 			return err;
11477 	}
11478 
11479 	regs = cur_regs(env);
11480 
11481 	if (meta.release_regno) {
11482 		err = -EINVAL;
11483 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11484 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11485 		 * is safe to do directly.
11486 		 */
11487 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11488 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11489 				verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
11490 				return -EFAULT;
11491 			}
11492 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11493 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11494 			u32 ref_obj_id = meta.ref_obj_id;
11495 			bool in_rcu = in_rcu_cs(env);
11496 			struct bpf_func_state *state;
11497 			struct bpf_reg_state *reg;
11498 
11499 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11500 			if (!err) {
11501 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11502 					if (reg->ref_obj_id == ref_obj_id) {
11503 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11504 							reg->ref_obj_id = 0;
11505 							reg->type &= ~MEM_ALLOC;
11506 							reg->type |= MEM_RCU;
11507 						} else {
11508 							mark_reg_invalid(env, reg);
11509 						}
11510 					}
11511 				}));
11512 			}
11513 		} else if (meta.ref_obj_id) {
11514 			err = release_reference(env, meta.ref_obj_id);
11515 		} else if (register_is_null(&regs[meta.release_regno])) {
11516 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11517 			 * released is NULL, which must be > R0.
11518 			 */
11519 			err = 0;
11520 		}
11521 		if (err) {
11522 			verbose(env, "func %s#%d reference has not been acquired before\n",
11523 				func_id_name(func_id), func_id);
11524 			return err;
11525 		}
11526 	}
11527 
11528 	switch (func_id) {
11529 	case BPF_FUNC_tail_call:
11530 		err = check_resource_leak(env, false, true, "tail_call");
11531 		if (err)
11532 			return err;
11533 		break;
11534 	case BPF_FUNC_get_local_storage:
11535 		/* check that flags argument in get_local_storage(map, flags) is 0,
11536 		 * this is required because get_local_storage() can't return an error.
11537 		 */
11538 		if (!register_is_null(&regs[BPF_REG_2])) {
11539 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11540 			return -EINVAL;
11541 		}
11542 		break;
11543 	case BPF_FUNC_for_each_map_elem:
11544 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11545 					 set_map_elem_callback_state);
11546 		break;
11547 	case BPF_FUNC_timer_set_callback:
11548 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11549 					 set_timer_callback_state);
11550 		break;
11551 	case BPF_FUNC_find_vma:
11552 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11553 					 set_find_vma_callback_state);
11554 		break;
11555 	case BPF_FUNC_snprintf:
11556 		err = check_bpf_snprintf_call(env, regs);
11557 		break;
11558 	case BPF_FUNC_loop:
11559 		update_loop_inline_state(env, meta.subprogno);
11560 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11561 		 * is finished, thus mark it precise.
11562 		 */
11563 		err = mark_chain_precision(env, BPF_REG_1);
11564 		if (err)
11565 			return err;
11566 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11567 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11568 						 set_loop_callback_state);
11569 		} else {
11570 			cur_func(env)->callback_depth = 0;
11571 			if (env->log.level & BPF_LOG_LEVEL2)
11572 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11573 					env->cur_state->curframe);
11574 		}
11575 		break;
11576 	case BPF_FUNC_dynptr_from_mem:
11577 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11578 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11579 				reg_type_str(env, regs[BPF_REG_1].type));
11580 			return -EACCES;
11581 		}
11582 		break;
11583 	case BPF_FUNC_set_retval:
11584 		if (prog_type == BPF_PROG_TYPE_LSM &&
11585 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11586 			if (!env->prog->aux->attach_func_proto->type) {
11587 				/* Make sure programs that attach to void
11588 				 * hooks don't try to modify return value.
11589 				 */
11590 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11591 				return -EINVAL;
11592 			}
11593 		}
11594 		break;
11595 	case BPF_FUNC_dynptr_data:
11596 	{
11597 		struct bpf_reg_state *reg;
11598 		int id, ref_obj_id;
11599 
11600 		reg = get_dynptr_arg_reg(env, fn, regs);
11601 		if (!reg)
11602 			return -EFAULT;
11603 
11604 
11605 		if (meta.dynptr_id) {
11606 			verifier_bug(env, "meta.dynptr_id already set");
11607 			return -EFAULT;
11608 		}
11609 		if (meta.ref_obj_id) {
11610 			verifier_bug(env, "meta.ref_obj_id already set");
11611 			return -EFAULT;
11612 		}
11613 
11614 		id = dynptr_id(env, reg);
11615 		if (id < 0) {
11616 			verifier_bug(env, "failed to obtain dynptr id");
11617 			return id;
11618 		}
11619 
11620 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11621 		if (ref_obj_id < 0) {
11622 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11623 			return ref_obj_id;
11624 		}
11625 
11626 		meta.dynptr_id = id;
11627 		meta.ref_obj_id = ref_obj_id;
11628 
11629 		break;
11630 	}
11631 	case BPF_FUNC_dynptr_write:
11632 	{
11633 		enum bpf_dynptr_type dynptr_type;
11634 		struct bpf_reg_state *reg;
11635 
11636 		reg = get_dynptr_arg_reg(env, fn, regs);
11637 		if (!reg)
11638 			return -EFAULT;
11639 
11640 		dynptr_type = dynptr_get_type(env, reg);
11641 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11642 			return -EFAULT;
11643 
11644 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
11645 			/* this will trigger clear_all_pkt_pointers(), which will
11646 			 * invalidate all dynptr slices associated with the skb
11647 			 */
11648 			changes_data = true;
11649 
11650 		break;
11651 	}
11652 	case BPF_FUNC_per_cpu_ptr:
11653 	case BPF_FUNC_this_cpu_ptr:
11654 	{
11655 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11656 		const struct btf_type *type;
11657 
11658 		if (reg->type & MEM_RCU) {
11659 			type = btf_type_by_id(reg->btf, reg->btf_id);
11660 			if (!type || !btf_type_is_struct(type)) {
11661 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11662 				return -EFAULT;
11663 			}
11664 			returns_cpu_specific_alloc_ptr = true;
11665 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11666 		}
11667 		break;
11668 	}
11669 	case BPF_FUNC_user_ringbuf_drain:
11670 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11671 					 set_user_ringbuf_callback_state);
11672 		break;
11673 	}
11674 
11675 	if (err)
11676 		return err;
11677 
11678 	/* reset caller saved regs */
11679 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11680 		mark_reg_not_init(env, regs, caller_saved[i]);
11681 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11682 	}
11683 
11684 	/* helper call returns 64-bit value. */
11685 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11686 
11687 	/* update return register (already marked as written above) */
11688 	ret_type = fn->ret_type;
11689 	ret_flag = type_flag(ret_type);
11690 
11691 	switch (base_type(ret_type)) {
11692 	case RET_INTEGER:
11693 		/* sets type to SCALAR_VALUE */
11694 		mark_reg_unknown(env, regs, BPF_REG_0);
11695 		break;
11696 	case RET_VOID:
11697 		regs[BPF_REG_0].type = NOT_INIT;
11698 		break;
11699 	case RET_PTR_TO_MAP_VALUE:
11700 		/* There is no offset yet applied, variable or fixed */
11701 		mark_reg_known_zero(env, regs, BPF_REG_0);
11702 		/* remember map_ptr, so that check_map_access()
11703 		 * can check 'value_size' boundary of memory access
11704 		 * to map element returned from bpf_map_lookup_elem()
11705 		 */
11706 		if (meta.map_ptr == NULL) {
11707 			verifier_bug(env, "unexpected null map_ptr");
11708 			return -EFAULT;
11709 		}
11710 
11711 		if (func_id == BPF_FUNC_map_lookup_elem &&
11712 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11713 		    meta.const_map_key >= 0 &&
11714 		    meta.const_map_key < meta.map_ptr->max_entries)
11715 			ret_flag &= ~PTR_MAYBE_NULL;
11716 
11717 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11718 		regs[BPF_REG_0].map_uid = meta.map_uid;
11719 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11720 		if (!type_may_be_null(ret_flag) &&
11721 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11722 			regs[BPF_REG_0].id = ++env->id_gen;
11723 		}
11724 		break;
11725 	case RET_PTR_TO_SOCKET:
11726 		mark_reg_known_zero(env, regs, BPF_REG_0);
11727 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11728 		break;
11729 	case RET_PTR_TO_SOCK_COMMON:
11730 		mark_reg_known_zero(env, regs, BPF_REG_0);
11731 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11732 		break;
11733 	case RET_PTR_TO_TCP_SOCK:
11734 		mark_reg_known_zero(env, regs, BPF_REG_0);
11735 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11736 		break;
11737 	case RET_PTR_TO_MEM:
11738 		mark_reg_known_zero(env, regs, BPF_REG_0);
11739 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11740 		regs[BPF_REG_0].mem_size = meta.mem_size;
11741 		break;
11742 	case RET_PTR_TO_MEM_OR_BTF_ID:
11743 	{
11744 		const struct btf_type *t;
11745 
11746 		mark_reg_known_zero(env, regs, BPF_REG_0);
11747 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11748 		if (!btf_type_is_struct(t)) {
11749 			u32 tsize;
11750 			const struct btf_type *ret;
11751 			const char *tname;
11752 
11753 			/* resolve the type size of ksym. */
11754 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11755 			if (IS_ERR(ret)) {
11756 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11757 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11758 					tname, PTR_ERR(ret));
11759 				return -EINVAL;
11760 			}
11761 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11762 			regs[BPF_REG_0].mem_size = tsize;
11763 		} else {
11764 			if (returns_cpu_specific_alloc_ptr) {
11765 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11766 			} else {
11767 				/* MEM_RDONLY may be carried from ret_flag, but it
11768 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11769 				 * it will confuse the check of PTR_TO_BTF_ID in
11770 				 * check_mem_access().
11771 				 */
11772 				ret_flag &= ~MEM_RDONLY;
11773 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11774 			}
11775 
11776 			regs[BPF_REG_0].btf = meta.ret_btf;
11777 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11778 		}
11779 		break;
11780 	}
11781 	case RET_PTR_TO_BTF_ID:
11782 	{
11783 		struct btf *ret_btf;
11784 		int ret_btf_id;
11785 
11786 		mark_reg_known_zero(env, regs, BPF_REG_0);
11787 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11788 		if (func_id == BPF_FUNC_kptr_xchg) {
11789 			ret_btf = meta.kptr_field->kptr.btf;
11790 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11791 			if (!btf_is_kernel(ret_btf)) {
11792 				regs[BPF_REG_0].type |= MEM_ALLOC;
11793 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11794 					regs[BPF_REG_0].type |= MEM_PERCPU;
11795 			}
11796 		} else {
11797 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11798 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11799 					     func_id_name(func_id));
11800 				return -EFAULT;
11801 			}
11802 			ret_btf = btf_vmlinux;
11803 			ret_btf_id = *fn->ret_btf_id;
11804 		}
11805 		if (ret_btf_id == 0) {
11806 			verbose(env, "invalid return type %u of func %s#%d\n",
11807 				base_type(ret_type), func_id_name(func_id),
11808 				func_id);
11809 			return -EINVAL;
11810 		}
11811 		regs[BPF_REG_0].btf = ret_btf;
11812 		regs[BPF_REG_0].btf_id = ret_btf_id;
11813 		break;
11814 	}
11815 	default:
11816 		verbose(env, "unknown return type %u of func %s#%d\n",
11817 			base_type(ret_type), func_id_name(func_id), func_id);
11818 		return -EINVAL;
11819 	}
11820 
11821 	if (type_may_be_null(regs[BPF_REG_0].type))
11822 		regs[BPF_REG_0].id = ++env->id_gen;
11823 
11824 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11825 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11826 			     func_id_name(func_id), func_id);
11827 		return -EFAULT;
11828 	}
11829 
11830 	if (is_dynptr_ref_function(func_id))
11831 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11832 
11833 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11834 		/* For release_reference() */
11835 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11836 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11837 		int id = acquire_reference(env, insn_idx);
11838 
11839 		if (id < 0)
11840 			return id;
11841 		/* For mark_ptr_or_null_reg() */
11842 		regs[BPF_REG_0].id = id;
11843 		/* For release_reference() */
11844 		regs[BPF_REG_0].ref_obj_id = id;
11845 	}
11846 
11847 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11848 	if (err)
11849 		return err;
11850 
11851 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11852 	if (err)
11853 		return err;
11854 
11855 	if ((func_id == BPF_FUNC_get_stack ||
11856 	     func_id == BPF_FUNC_get_task_stack) &&
11857 	    !env->prog->has_callchain_buf) {
11858 		const char *err_str;
11859 
11860 #ifdef CONFIG_PERF_EVENTS
11861 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11862 		err_str = "cannot get callchain buffer for func %s#%d\n";
11863 #else
11864 		err = -ENOTSUPP;
11865 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11866 #endif
11867 		if (err) {
11868 			verbose(env, err_str, func_id_name(func_id), func_id);
11869 			return err;
11870 		}
11871 
11872 		env->prog->has_callchain_buf = true;
11873 	}
11874 
11875 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11876 		env->prog->call_get_stack = true;
11877 
11878 	if (func_id == BPF_FUNC_get_func_ip) {
11879 		if (check_get_func_ip(env))
11880 			return -ENOTSUPP;
11881 		env->prog->call_get_func_ip = true;
11882 	}
11883 
11884 	if (changes_data)
11885 		clear_all_pkt_pointers(env);
11886 	return 0;
11887 }
11888 
11889 /* mark_btf_func_reg_size() is used when the reg size is determined by
11890  * the BTF func_proto's return value size and argument.
11891  */
__mark_btf_func_reg_size(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,size_t reg_size)11892 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
11893 				     u32 regno, size_t reg_size)
11894 {
11895 	struct bpf_reg_state *reg = &regs[regno];
11896 
11897 	if (regno == BPF_REG_0) {
11898 		/* Function return value */
11899 		reg->live |= REG_LIVE_WRITTEN;
11900 		reg->subreg_def = reg_size == sizeof(u64) ?
11901 			DEF_NOT_SUBREG : env->insn_idx + 1;
11902 	} else {
11903 		/* Function argument */
11904 		if (reg_size == sizeof(u64)) {
11905 			mark_insn_zext(env, reg);
11906 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
11907 		} else {
11908 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
11909 		}
11910 	}
11911 }
11912 
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)11913 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11914 				   size_t reg_size)
11915 {
11916 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
11917 }
11918 
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)11919 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11920 {
11921 	return meta->kfunc_flags & KF_ACQUIRE;
11922 }
11923 
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)11924 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11925 {
11926 	return meta->kfunc_flags & KF_RELEASE;
11927 }
11928 
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)11929 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11930 {
11931 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11932 }
11933 
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)11934 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11935 {
11936 	return meta->kfunc_flags & KF_SLEEPABLE;
11937 }
11938 
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)11939 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11940 {
11941 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11942 }
11943 
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)11944 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11945 {
11946 	return meta->kfunc_flags & KF_RCU;
11947 }
11948 
is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta * meta)11949 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11950 {
11951 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11952 }
11953 
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)11954 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11955 				  const struct btf_param *arg,
11956 				  const struct bpf_reg_state *reg)
11957 {
11958 	const struct btf_type *t;
11959 
11960 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11961 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11962 		return false;
11963 
11964 	return btf_param_match_suffix(btf, arg, "__sz");
11965 }
11966 
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)11967 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11968 					const struct btf_param *arg,
11969 					const struct bpf_reg_state *reg)
11970 {
11971 	const struct btf_type *t;
11972 
11973 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11974 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11975 		return false;
11976 
11977 	return btf_param_match_suffix(btf, arg, "__szk");
11978 }
11979 
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)11980 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11981 {
11982 	return btf_param_match_suffix(btf, arg, "__opt");
11983 }
11984 
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)11985 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11986 {
11987 	return btf_param_match_suffix(btf, arg, "__k");
11988 }
11989 
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)11990 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11991 {
11992 	return btf_param_match_suffix(btf, arg, "__ign");
11993 }
11994 
is_kfunc_arg_map(const struct btf * btf,const struct btf_param * arg)11995 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11996 {
11997 	return btf_param_match_suffix(btf, arg, "__map");
11998 }
11999 
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)12000 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12001 {
12002 	return btf_param_match_suffix(btf, arg, "__alloc");
12003 }
12004 
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)12005 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12006 {
12007 	return btf_param_match_suffix(btf, arg, "__uninit");
12008 }
12009 
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)12010 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12011 {
12012 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12013 }
12014 
is_kfunc_arg_nullable(const struct btf * btf,const struct btf_param * arg)12015 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12016 {
12017 	return btf_param_match_suffix(btf, arg, "__nullable");
12018 }
12019 
is_kfunc_arg_const_str(const struct btf * btf,const struct btf_param * arg)12020 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12021 {
12022 	return btf_param_match_suffix(btf, arg, "__str");
12023 }
12024 
is_kfunc_arg_irq_flag(const struct btf * btf,const struct btf_param * arg)12025 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12026 {
12027 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12028 }
12029 
is_kfunc_arg_prog(const struct btf * btf,const struct btf_param * arg)12030 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12031 {
12032 	return btf_param_match_suffix(btf, arg, "__prog");
12033 }
12034 
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)12035 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12036 					  const struct btf_param *arg,
12037 					  const char *name)
12038 {
12039 	int len, target_len = strlen(name);
12040 	const char *param_name;
12041 
12042 	param_name = btf_name_by_offset(btf, arg->name_off);
12043 	if (str_is_empty(param_name))
12044 		return false;
12045 	len = strlen(param_name);
12046 	if (len != target_len)
12047 		return false;
12048 	if (strcmp(param_name, name))
12049 		return false;
12050 
12051 	return true;
12052 }
12053 
12054 enum {
12055 	KF_ARG_DYNPTR_ID,
12056 	KF_ARG_LIST_HEAD_ID,
12057 	KF_ARG_LIST_NODE_ID,
12058 	KF_ARG_RB_ROOT_ID,
12059 	KF_ARG_RB_NODE_ID,
12060 	KF_ARG_WORKQUEUE_ID,
12061 	KF_ARG_RES_SPIN_LOCK_ID,
12062 };
12063 
12064 BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr)12065 BTF_ID(struct, bpf_dynptr)
12066 BTF_ID(struct, bpf_list_head)
12067 BTF_ID(struct, bpf_list_node)
12068 BTF_ID(struct, bpf_rb_root)
12069 BTF_ID(struct, bpf_rb_node)
12070 BTF_ID(struct, bpf_wq)
12071 BTF_ID(struct, bpf_res_spin_lock)
12072 
12073 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12074 				    const struct btf_param *arg, int type)
12075 {
12076 	const struct btf_type *t;
12077 	u32 res_id;
12078 
12079 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12080 	if (!t)
12081 		return false;
12082 	if (!btf_type_is_ptr(t))
12083 		return false;
12084 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12085 	if (!t)
12086 		return false;
12087 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12088 }
12089 
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)12090 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12091 {
12092 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12093 }
12094 
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)12095 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12096 {
12097 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12098 }
12099 
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)12100 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12101 {
12102 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12103 }
12104 
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)12105 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12106 {
12107 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12108 }
12109 
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)12110 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12111 {
12112 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12113 }
12114 
is_kfunc_arg_wq(const struct btf * btf,const struct btf_param * arg)12115 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12116 {
12117 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12118 }
12119 
is_kfunc_arg_res_spin_lock(const struct btf * btf,const struct btf_param * arg)12120 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12121 {
12122 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12123 }
12124 
is_rbtree_node_type(const struct btf_type * t)12125 static bool is_rbtree_node_type(const struct btf_type *t)
12126 {
12127 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12128 }
12129 
is_list_node_type(const struct btf_type * t)12130 static bool is_list_node_type(const struct btf_type *t)
12131 {
12132 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12133 }
12134 
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)12135 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12136 				  const struct btf_param *arg)
12137 {
12138 	const struct btf_type *t;
12139 
12140 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12141 	if (!t)
12142 		return false;
12143 
12144 	return true;
12145 }
12146 
12147 /* 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)12148 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12149 					const struct btf *btf,
12150 					const struct btf_type *t, int rec)
12151 {
12152 	const struct btf_type *member_type;
12153 	const struct btf_member *member;
12154 	u32 i;
12155 
12156 	if (!btf_type_is_struct(t))
12157 		return false;
12158 
12159 	for_each_member(i, t, member) {
12160 		const struct btf_array *array;
12161 
12162 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12163 		if (btf_type_is_struct(member_type)) {
12164 			if (rec >= 3) {
12165 				verbose(env, "max struct nesting depth exceeded\n");
12166 				return false;
12167 			}
12168 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12169 				return false;
12170 			continue;
12171 		}
12172 		if (btf_type_is_array(member_type)) {
12173 			array = btf_array(member_type);
12174 			if (!array->nelems)
12175 				return false;
12176 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12177 			if (!btf_type_is_scalar(member_type))
12178 				return false;
12179 			continue;
12180 		}
12181 		if (!btf_type_is_scalar(member_type))
12182 			return false;
12183 	}
12184 	return true;
12185 }
12186 
12187 enum kfunc_ptr_arg_type {
12188 	KF_ARG_PTR_TO_CTX,
12189 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12190 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12191 	KF_ARG_PTR_TO_DYNPTR,
12192 	KF_ARG_PTR_TO_ITER,
12193 	KF_ARG_PTR_TO_LIST_HEAD,
12194 	KF_ARG_PTR_TO_LIST_NODE,
12195 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12196 	KF_ARG_PTR_TO_MEM,
12197 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12198 	KF_ARG_PTR_TO_CALLBACK,
12199 	KF_ARG_PTR_TO_RB_ROOT,
12200 	KF_ARG_PTR_TO_RB_NODE,
12201 	KF_ARG_PTR_TO_NULL,
12202 	KF_ARG_PTR_TO_CONST_STR,
12203 	KF_ARG_PTR_TO_MAP,
12204 	KF_ARG_PTR_TO_WORKQUEUE,
12205 	KF_ARG_PTR_TO_IRQ_FLAG,
12206 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12207 };
12208 
12209 enum special_kfunc_type {
12210 	KF_bpf_obj_new_impl,
12211 	KF_bpf_obj_drop_impl,
12212 	KF_bpf_refcount_acquire_impl,
12213 	KF_bpf_list_push_front_impl,
12214 	KF_bpf_list_push_back_impl,
12215 	KF_bpf_list_pop_front,
12216 	KF_bpf_list_pop_back,
12217 	KF_bpf_list_front,
12218 	KF_bpf_list_back,
12219 	KF_bpf_cast_to_kern_ctx,
12220 	KF_bpf_rdonly_cast,
12221 	KF_bpf_rcu_read_lock,
12222 	KF_bpf_rcu_read_unlock,
12223 	KF_bpf_rbtree_remove,
12224 	KF_bpf_rbtree_add_impl,
12225 	KF_bpf_rbtree_first,
12226 	KF_bpf_rbtree_root,
12227 	KF_bpf_rbtree_left,
12228 	KF_bpf_rbtree_right,
12229 	KF_bpf_dynptr_from_skb,
12230 	KF_bpf_dynptr_from_xdp,
12231 	KF_bpf_dynptr_slice,
12232 	KF_bpf_dynptr_slice_rdwr,
12233 	KF_bpf_dynptr_clone,
12234 	KF_bpf_percpu_obj_new_impl,
12235 	KF_bpf_percpu_obj_drop_impl,
12236 	KF_bpf_throw,
12237 	KF_bpf_wq_set_callback_impl,
12238 	KF_bpf_preempt_disable,
12239 	KF_bpf_preempt_enable,
12240 	KF_bpf_iter_css_task_new,
12241 	KF_bpf_session_cookie,
12242 	KF_bpf_get_kmem_cache,
12243 	KF_bpf_local_irq_save,
12244 	KF_bpf_local_irq_restore,
12245 	KF_bpf_iter_num_new,
12246 	KF_bpf_iter_num_next,
12247 	KF_bpf_iter_num_destroy,
12248 	KF_bpf_set_dentry_xattr,
12249 	KF_bpf_remove_dentry_xattr,
12250 	KF_bpf_res_spin_lock,
12251 	KF_bpf_res_spin_unlock,
12252 	KF_bpf_res_spin_lock_irqsave,
12253 	KF_bpf_res_spin_unlock_irqrestore,
12254 	KF___bpf_trap,
12255 };
12256 
12257 BTF_ID_LIST(special_kfunc_list)
BTF_ID(func,bpf_obj_new_impl)12258 BTF_ID(func, bpf_obj_new_impl)
12259 BTF_ID(func, bpf_obj_drop_impl)
12260 BTF_ID(func, bpf_refcount_acquire_impl)
12261 BTF_ID(func, bpf_list_push_front_impl)
12262 BTF_ID(func, bpf_list_push_back_impl)
12263 BTF_ID(func, bpf_list_pop_front)
12264 BTF_ID(func, bpf_list_pop_back)
12265 BTF_ID(func, bpf_list_front)
12266 BTF_ID(func, bpf_list_back)
12267 BTF_ID(func, bpf_cast_to_kern_ctx)
12268 BTF_ID(func, bpf_rdonly_cast)
12269 BTF_ID(func, bpf_rcu_read_lock)
12270 BTF_ID(func, bpf_rcu_read_unlock)
12271 BTF_ID(func, bpf_rbtree_remove)
12272 BTF_ID(func, bpf_rbtree_add_impl)
12273 BTF_ID(func, bpf_rbtree_first)
12274 BTF_ID(func, bpf_rbtree_root)
12275 BTF_ID(func, bpf_rbtree_left)
12276 BTF_ID(func, bpf_rbtree_right)
12277 #ifdef CONFIG_NET
12278 BTF_ID(func, bpf_dynptr_from_skb)
12279 BTF_ID(func, bpf_dynptr_from_xdp)
12280 #else
12281 BTF_ID_UNUSED
12282 BTF_ID_UNUSED
12283 #endif
12284 BTF_ID(func, bpf_dynptr_slice)
12285 BTF_ID(func, bpf_dynptr_slice_rdwr)
12286 BTF_ID(func, bpf_dynptr_clone)
12287 BTF_ID(func, bpf_percpu_obj_new_impl)
12288 BTF_ID(func, bpf_percpu_obj_drop_impl)
12289 BTF_ID(func, bpf_throw)
12290 BTF_ID(func, bpf_wq_set_callback_impl)
12291 BTF_ID(func, bpf_preempt_disable)
12292 BTF_ID(func, bpf_preempt_enable)
12293 #ifdef CONFIG_CGROUPS
12294 BTF_ID(func, bpf_iter_css_task_new)
12295 #else
12296 BTF_ID_UNUSED
12297 #endif
12298 #ifdef CONFIG_BPF_EVENTS
12299 BTF_ID(func, bpf_session_cookie)
12300 #else
12301 BTF_ID_UNUSED
12302 #endif
12303 BTF_ID(func, bpf_get_kmem_cache)
12304 BTF_ID(func, bpf_local_irq_save)
12305 BTF_ID(func, bpf_local_irq_restore)
12306 BTF_ID(func, bpf_iter_num_new)
12307 BTF_ID(func, bpf_iter_num_next)
12308 BTF_ID(func, bpf_iter_num_destroy)
12309 #ifdef CONFIG_BPF_LSM
12310 BTF_ID(func, bpf_set_dentry_xattr)
12311 BTF_ID(func, bpf_remove_dentry_xattr)
12312 #else
12313 BTF_ID_UNUSED
12314 BTF_ID_UNUSED
12315 #endif
12316 BTF_ID(func, bpf_res_spin_lock)
12317 BTF_ID(func, bpf_res_spin_unlock)
12318 BTF_ID(func, bpf_res_spin_lock_irqsave)
12319 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12320 BTF_ID(func, __bpf_trap)
12321 
12322 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12323 {
12324 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12325 	    meta->arg_owning_ref) {
12326 		return false;
12327 	}
12328 
12329 	return meta->kfunc_flags & KF_RET_NULL;
12330 }
12331 
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)12332 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12333 {
12334 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12335 }
12336 
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)12337 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12338 {
12339 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12340 }
12341 
is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta * meta)12342 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12343 {
12344 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12345 }
12346 
is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta * meta)12347 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12348 {
12349 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12350 }
12351 
12352 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)12353 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12354 		       struct bpf_kfunc_call_arg_meta *meta,
12355 		       const struct btf_type *t, const struct btf_type *ref_t,
12356 		       const char *ref_tname, const struct btf_param *args,
12357 		       int argno, int nargs)
12358 {
12359 	u32 regno = argno + 1;
12360 	struct bpf_reg_state *regs = cur_regs(env);
12361 	struct bpf_reg_state *reg = &regs[regno];
12362 	bool arg_mem_size = false;
12363 
12364 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12365 		return KF_ARG_PTR_TO_CTX;
12366 
12367 	/* In this function, we verify the kfunc's BTF as per the argument type,
12368 	 * leaving the rest of the verification with respect to the register
12369 	 * type to our caller. When a set of conditions hold in the BTF type of
12370 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12371 	 */
12372 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12373 		return KF_ARG_PTR_TO_CTX;
12374 
12375 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12376 		return KF_ARG_PTR_TO_NULL;
12377 
12378 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12379 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12380 
12381 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12382 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12383 
12384 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12385 		return KF_ARG_PTR_TO_DYNPTR;
12386 
12387 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12388 		return KF_ARG_PTR_TO_ITER;
12389 
12390 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12391 		return KF_ARG_PTR_TO_LIST_HEAD;
12392 
12393 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12394 		return KF_ARG_PTR_TO_LIST_NODE;
12395 
12396 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12397 		return KF_ARG_PTR_TO_RB_ROOT;
12398 
12399 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12400 		return KF_ARG_PTR_TO_RB_NODE;
12401 
12402 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12403 		return KF_ARG_PTR_TO_CONST_STR;
12404 
12405 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12406 		return KF_ARG_PTR_TO_MAP;
12407 
12408 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12409 		return KF_ARG_PTR_TO_WORKQUEUE;
12410 
12411 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12412 		return KF_ARG_PTR_TO_IRQ_FLAG;
12413 
12414 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12415 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12416 
12417 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12418 		if (!btf_type_is_struct(ref_t)) {
12419 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12420 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12421 			return -EINVAL;
12422 		}
12423 		return KF_ARG_PTR_TO_BTF_ID;
12424 	}
12425 
12426 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12427 		return KF_ARG_PTR_TO_CALLBACK;
12428 
12429 	if (argno + 1 < nargs &&
12430 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12431 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12432 		arg_mem_size = true;
12433 
12434 	/* This is the catch all argument type of register types supported by
12435 	 * check_helper_mem_access. However, we only allow when argument type is
12436 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12437 	 * arg_mem_size is true, the pointer can be void *.
12438 	 */
12439 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12440 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12441 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12442 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12443 		return -EINVAL;
12444 	}
12445 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12446 }
12447 
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)12448 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12449 					struct bpf_reg_state *reg,
12450 					const struct btf_type *ref_t,
12451 					const char *ref_tname, u32 ref_id,
12452 					struct bpf_kfunc_call_arg_meta *meta,
12453 					int argno)
12454 {
12455 	const struct btf_type *reg_ref_t;
12456 	bool strict_type_match = false;
12457 	const struct btf *reg_btf;
12458 	const char *reg_ref_tname;
12459 	bool taking_projection;
12460 	bool struct_same;
12461 	u32 reg_ref_id;
12462 
12463 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12464 		reg_btf = reg->btf;
12465 		reg_ref_id = reg->btf_id;
12466 	} else {
12467 		reg_btf = btf_vmlinux;
12468 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12469 	}
12470 
12471 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12472 	 * or releasing a reference, or are no-cast aliases. We do _not_
12473 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12474 	 * as we want to enable BPF programs to pass types that are bitwise
12475 	 * equivalent without forcing them to explicitly cast with something
12476 	 * like bpf_cast_to_kern_ctx().
12477 	 *
12478 	 * For example, say we had a type like the following:
12479 	 *
12480 	 * struct bpf_cpumask {
12481 	 *	cpumask_t cpumask;
12482 	 *	refcount_t usage;
12483 	 * };
12484 	 *
12485 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12486 	 * to a struct cpumask, so it would be safe to pass a struct
12487 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12488 	 *
12489 	 * The philosophy here is similar to how we allow scalars of different
12490 	 * types to be passed to kfuncs as long as the size is the same. The
12491 	 * only difference here is that we're simply allowing
12492 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12493 	 * resolve types.
12494 	 */
12495 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12496 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12497 		strict_type_match = true;
12498 
12499 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12500 		     (reg->off || !tnum_is_const(reg->var_off) ||
12501 		      reg->var_off.value));
12502 
12503 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12504 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12505 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12506 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12507 	 * actually use it -- it must cast to the underlying type. So we allow
12508 	 * caller to pass in the underlying type.
12509 	 */
12510 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12511 	if (!taking_projection && !struct_same) {
12512 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12513 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12514 			btf_type_str(reg_ref_t), reg_ref_tname);
12515 		return -EINVAL;
12516 	}
12517 	return 0;
12518 }
12519 
process_irq_flag(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)12520 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12521 			     struct bpf_kfunc_call_arg_meta *meta)
12522 {
12523 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12524 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12525 	bool irq_save;
12526 
12527 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12528 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12529 		irq_save = true;
12530 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12531 			kfunc_class = IRQ_LOCK_KFUNC;
12532 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12533 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12534 		irq_save = false;
12535 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12536 			kfunc_class = IRQ_LOCK_KFUNC;
12537 	} else {
12538 		verifier_bug(env, "unknown irq flags kfunc");
12539 		return -EFAULT;
12540 	}
12541 
12542 	if (irq_save) {
12543 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12544 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12545 			return -EINVAL;
12546 		}
12547 
12548 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12549 		if (err)
12550 			return err;
12551 
12552 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12553 		if (err)
12554 			return err;
12555 	} else {
12556 		err = is_irq_flag_reg_valid_init(env, reg);
12557 		if (err) {
12558 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12559 			return err;
12560 		}
12561 
12562 		err = mark_irq_flag_read(env, reg);
12563 		if (err)
12564 			return err;
12565 
12566 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12567 		if (err)
12568 			return err;
12569 	}
12570 	return 0;
12571 }
12572 
12573 
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12574 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12575 {
12576 	struct btf_record *rec = reg_btf_record(reg);
12577 
12578 	if (!env->cur_state->active_locks) {
12579 		verifier_bug(env, "%s w/o active lock", __func__);
12580 		return -EFAULT;
12581 	}
12582 
12583 	if (type_flag(reg->type) & NON_OWN_REF) {
12584 		verifier_bug(env, "NON_OWN_REF already set");
12585 		return -EFAULT;
12586 	}
12587 
12588 	reg->type |= NON_OWN_REF;
12589 	if (rec->refcount_off >= 0)
12590 		reg->type |= MEM_RCU;
12591 
12592 	return 0;
12593 }
12594 
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)12595 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12596 {
12597 	struct bpf_verifier_state *state = env->cur_state;
12598 	struct bpf_func_state *unused;
12599 	struct bpf_reg_state *reg;
12600 	int i;
12601 
12602 	if (!ref_obj_id) {
12603 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12604 		return -EFAULT;
12605 	}
12606 
12607 	for (i = 0; i < state->acquired_refs; i++) {
12608 		if (state->refs[i].id != ref_obj_id)
12609 			continue;
12610 
12611 		/* Clear ref_obj_id here so release_reference doesn't clobber
12612 		 * the whole reg
12613 		 */
12614 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12615 			if (reg->ref_obj_id == ref_obj_id) {
12616 				reg->ref_obj_id = 0;
12617 				ref_set_non_owning(env, reg);
12618 			}
12619 		}));
12620 		return 0;
12621 	}
12622 
12623 	verifier_bug(env, "ref state missing for ref_obj_id");
12624 	return -EFAULT;
12625 }
12626 
12627 /* Implementation details:
12628  *
12629  * Each register points to some region of memory, which we define as an
12630  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12631  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12632  * allocation. The lock and the data it protects are colocated in the same
12633  * memory region.
12634  *
12635  * Hence, everytime a register holds a pointer value pointing to such
12636  * allocation, the verifier preserves a unique reg->id for it.
12637  *
12638  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12639  * bpf_spin_lock is called.
12640  *
12641  * To enable this, lock state in the verifier captures two values:
12642  *	active_lock.ptr = Register's type specific pointer
12643  *	active_lock.id  = A unique ID for each register pointer value
12644  *
12645  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12646  * supported register types.
12647  *
12648  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12649  * allocated objects is the reg->btf pointer.
12650  *
12651  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12652  * can establish the provenance of the map value statically for each distinct
12653  * lookup into such maps. They always contain a single map value hence unique
12654  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12655  *
12656  * So, in case of global variables, they use array maps with max_entries = 1,
12657  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12658  * into the same map value as max_entries is 1, as described above).
12659  *
12660  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12661  * outer map pointer (in verifier context), but each lookup into an inner map
12662  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12663  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12664  * will get different reg->id assigned to each lookup, hence different
12665  * active_lock.id.
12666  *
12667  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12668  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12669  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12670  */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12671 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12672 {
12673 	struct bpf_reference_state *s;
12674 	void *ptr;
12675 	u32 id;
12676 
12677 	switch ((int)reg->type) {
12678 	case PTR_TO_MAP_VALUE:
12679 		ptr = reg->map_ptr;
12680 		break;
12681 	case PTR_TO_BTF_ID | MEM_ALLOC:
12682 		ptr = reg->btf;
12683 		break;
12684 	default:
12685 		verifier_bug(env, "unknown reg type for lock check");
12686 		return -EFAULT;
12687 	}
12688 	id = reg->id;
12689 
12690 	if (!env->cur_state->active_locks)
12691 		return -EINVAL;
12692 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12693 	if (!s) {
12694 		verbose(env, "held lock and object are not in the same allocation\n");
12695 		return -EINVAL;
12696 	}
12697 	return 0;
12698 }
12699 
is_bpf_list_api_kfunc(u32 btf_id)12700 static bool is_bpf_list_api_kfunc(u32 btf_id)
12701 {
12702 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12703 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12704 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12705 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12706 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12707 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12708 }
12709 
is_bpf_rbtree_api_kfunc(u32 btf_id)12710 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12711 {
12712 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12713 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12714 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12715 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12716 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12717 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12718 }
12719 
is_bpf_iter_num_api_kfunc(u32 btf_id)12720 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12721 {
12722 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12723 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12724 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12725 }
12726 
is_bpf_graph_api_kfunc(u32 btf_id)12727 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12728 {
12729 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12730 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12731 }
12732 
is_bpf_res_spin_lock_kfunc(u32 btf_id)12733 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12734 {
12735 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12736 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12737 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12738 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12739 }
12740 
kfunc_spin_allowed(u32 btf_id)12741 static bool kfunc_spin_allowed(u32 btf_id)
12742 {
12743 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12744 	       is_bpf_res_spin_lock_kfunc(btf_id);
12745 }
12746 
is_sync_callback_calling_kfunc(u32 btf_id)12747 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12748 {
12749 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12750 }
12751 
is_async_callback_calling_kfunc(u32 btf_id)12752 static bool is_async_callback_calling_kfunc(u32 btf_id)
12753 {
12754 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12755 }
12756 
is_bpf_throw_kfunc(struct bpf_insn * insn)12757 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12758 {
12759 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12760 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12761 }
12762 
is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)12763 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12764 {
12765 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12766 }
12767 
is_callback_calling_kfunc(u32 btf_id)12768 static bool is_callback_calling_kfunc(u32 btf_id)
12769 {
12770 	return is_sync_callback_calling_kfunc(btf_id) ||
12771 	       is_async_callback_calling_kfunc(btf_id);
12772 }
12773 
is_rbtree_lock_required_kfunc(u32 btf_id)12774 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12775 {
12776 	return is_bpf_rbtree_api_kfunc(btf_id);
12777 }
12778 
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)12779 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12780 					  enum btf_field_type head_field_type,
12781 					  u32 kfunc_btf_id)
12782 {
12783 	bool ret;
12784 
12785 	switch (head_field_type) {
12786 	case BPF_LIST_HEAD:
12787 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12788 		break;
12789 	case BPF_RB_ROOT:
12790 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12791 		break;
12792 	default:
12793 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12794 			btf_field_type_name(head_field_type));
12795 		return false;
12796 	}
12797 
12798 	if (!ret)
12799 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12800 			btf_field_type_name(head_field_type));
12801 	return ret;
12802 }
12803 
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)12804 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12805 					  enum btf_field_type node_field_type,
12806 					  u32 kfunc_btf_id)
12807 {
12808 	bool ret;
12809 
12810 	switch (node_field_type) {
12811 	case BPF_LIST_NODE:
12812 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12813 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12814 		break;
12815 	case BPF_RB_NODE:
12816 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12817 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12818 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12819 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12820 		break;
12821 	default:
12822 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12823 			btf_field_type_name(node_field_type));
12824 		return false;
12825 	}
12826 
12827 	if (!ret)
12828 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12829 			btf_field_type_name(node_field_type));
12830 	return ret;
12831 }
12832 
12833 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)12834 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12835 				   struct bpf_reg_state *reg, u32 regno,
12836 				   struct bpf_kfunc_call_arg_meta *meta,
12837 				   enum btf_field_type head_field_type,
12838 				   struct btf_field **head_field)
12839 {
12840 	const char *head_type_name;
12841 	struct btf_field *field;
12842 	struct btf_record *rec;
12843 	u32 head_off;
12844 
12845 	if (meta->btf != btf_vmlinux) {
12846 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12847 		return -EFAULT;
12848 	}
12849 
12850 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12851 		return -EFAULT;
12852 
12853 	head_type_name = btf_field_type_name(head_field_type);
12854 	if (!tnum_is_const(reg->var_off)) {
12855 		verbose(env,
12856 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12857 			regno, head_type_name);
12858 		return -EINVAL;
12859 	}
12860 
12861 	rec = reg_btf_record(reg);
12862 	head_off = reg->off + reg->var_off.value;
12863 	field = btf_record_find(rec, head_off, head_field_type);
12864 	if (!field) {
12865 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12866 		return -EINVAL;
12867 	}
12868 
12869 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12870 	if (check_reg_allocation_locked(env, reg)) {
12871 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12872 			rec->spin_lock_off, head_type_name);
12873 		return -EINVAL;
12874 	}
12875 
12876 	if (*head_field) {
12877 		verifier_bug(env, "repeating %s arg", head_type_name);
12878 		return -EFAULT;
12879 	}
12880 	*head_field = field;
12881 	return 0;
12882 }
12883 
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)12884 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12885 					   struct bpf_reg_state *reg, u32 regno,
12886 					   struct bpf_kfunc_call_arg_meta *meta)
12887 {
12888 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12889 							  &meta->arg_list_head.field);
12890 }
12891 
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)12892 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12893 					     struct bpf_reg_state *reg, u32 regno,
12894 					     struct bpf_kfunc_call_arg_meta *meta)
12895 {
12896 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12897 							  &meta->arg_rbtree_root.field);
12898 }
12899 
12900 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)12901 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12902 				   struct bpf_reg_state *reg, u32 regno,
12903 				   struct bpf_kfunc_call_arg_meta *meta,
12904 				   enum btf_field_type head_field_type,
12905 				   enum btf_field_type node_field_type,
12906 				   struct btf_field **node_field)
12907 {
12908 	const char *node_type_name;
12909 	const struct btf_type *et, *t;
12910 	struct btf_field *field;
12911 	u32 node_off;
12912 
12913 	if (meta->btf != btf_vmlinux) {
12914 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12915 		return -EFAULT;
12916 	}
12917 
12918 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12919 		return -EFAULT;
12920 
12921 	node_type_name = btf_field_type_name(node_field_type);
12922 	if (!tnum_is_const(reg->var_off)) {
12923 		verbose(env,
12924 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12925 			regno, node_type_name);
12926 		return -EINVAL;
12927 	}
12928 
12929 	node_off = reg->off + reg->var_off.value;
12930 	field = reg_find_field_offset(reg, node_off, node_field_type);
12931 	if (!field) {
12932 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12933 		return -EINVAL;
12934 	}
12935 
12936 	field = *node_field;
12937 
12938 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12939 	t = btf_type_by_id(reg->btf, reg->btf_id);
12940 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12941 				  field->graph_root.value_btf_id, true)) {
12942 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12943 			"in struct %s, but arg is at offset=%d in struct %s\n",
12944 			btf_field_type_name(head_field_type),
12945 			btf_field_type_name(node_field_type),
12946 			field->graph_root.node_offset,
12947 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12948 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12949 		return -EINVAL;
12950 	}
12951 	meta->arg_btf = reg->btf;
12952 	meta->arg_btf_id = reg->btf_id;
12953 
12954 	if (node_off != field->graph_root.node_offset) {
12955 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12956 			node_off, btf_field_type_name(node_field_type),
12957 			field->graph_root.node_offset,
12958 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12959 		return -EINVAL;
12960 	}
12961 
12962 	return 0;
12963 }
12964 
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)12965 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12966 					   struct bpf_reg_state *reg, u32 regno,
12967 					   struct bpf_kfunc_call_arg_meta *meta)
12968 {
12969 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12970 						  BPF_LIST_HEAD, BPF_LIST_NODE,
12971 						  &meta->arg_list_head.field);
12972 }
12973 
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)12974 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
12975 					     struct bpf_reg_state *reg, u32 regno,
12976 					     struct bpf_kfunc_call_arg_meta *meta)
12977 {
12978 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
12979 						  BPF_RB_ROOT, BPF_RB_NODE,
12980 						  &meta->arg_rbtree_root.field);
12981 }
12982 
12983 /*
12984  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
12985  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
12986  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
12987  * them can only be attached to some specific hook points.
12988  */
check_css_task_iter_allowlist(struct bpf_verifier_env * env)12989 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
12990 {
12991 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
12992 
12993 	switch (prog_type) {
12994 	case BPF_PROG_TYPE_LSM:
12995 		return true;
12996 	case BPF_PROG_TYPE_TRACING:
12997 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
12998 			return true;
12999 		fallthrough;
13000 	default:
13001 		return in_sleepable(env);
13002 	}
13003 }
13004 
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)13005 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13006 			    int insn_idx)
13007 {
13008 	const char *func_name = meta->func_name, *ref_tname;
13009 	const struct btf *btf = meta->btf;
13010 	const struct btf_param *args;
13011 	struct btf_record *rec;
13012 	u32 i, nargs;
13013 	int ret;
13014 
13015 	args = (const struct btf_param *)(meta->func_proto + 1);
13016 	nargs = btf_type_vlen(meta->func_proto);
13017 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13018 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13019 			MAX_BPF_FUNC_REG_ARGS);
13020 		return -EINVAL;
13021 	}
13022 
13023 	/* Check that BTF function arguments match actual types that the
13024 	 * verifier sees.
13025 	 */
13026 	for (i = 0; i < nargs; i++) {
13027 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13028 		const struct btf_type *t, *ref_t, *resolve_ret;
13029 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13030 		u32 regno = i + 1, ref_id, type_size;
13031 		bool is_ret_buf_sz = false;
13032 		int kf_arg_type;
13033 
13034 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13035 
13036 		if (is_kfunc_arg_ignore(btf, &args[i]))
13037 			continue;
13038 
13039 		if (is_kfunc_arg_prog(btf, &args[i])) {
13040 			/* Used to reject repeated use of __prog. */
13041 			if (meta->arg_prog) {
13042 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13043 				return -EFAULT;
13044 			}
13045 			meta->arg_prog = true;
13046 			cur_aux(env)->arg_prog = regno;
13047 			continue;
13048 		}
13049 
13050 		if (btf_type_is_scalar(t)) {
13051 			if (reg->type != SCALAR_VALUE) {
13052 				verbose(env, "R%d is not a scalar\n", regno);
13053 				return -EINVAL;
13054 			}
13055 
13056 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13057 				if (meta->arg_constant.found) {
13058 					verifier_bug(env, "only one constant argument permitted");
13059 					return -EFAULT;
13060 				}
13061 				if (!tnum_is_const(reg->var_off)) {
13062 					verbose(env, "R%d must be a known constant\n", regno);
13063 					return -EINVAL;
13064 				}
13065 				ret = mark_chain_precision(env, regno);
13066 				if (ret < 0)
13067 					return ret;
13068 				meta->arg_constant.found = true;
13069 				meta->arg_constant.value = reg->var_off.value;
13070 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13071 				meta->r0_rdonly = true;
13072 				is_ret_buf_sz = true;
13073 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13074 				is_ret_buf_sz = true;
13075 			}
13076 
13077 			if (is_ret_buf_sz) {
13078 				if (meta->r0_size) {
13079 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13080 					return -EINVAL;
13081 				}
13082 
13083 				if (!tnum_is_const(reg->var_off)) {
13084 					verbose(env, "R%d is not a const\n", regno);
13085 					return -EINVAL;
13086 				}
13087 
13088 				meta->r0_size = reg->var_off.value;
13089 				ret = mark_chain_precision(env, regno);
13090 				if (ret)
13091 					return ret;
13092 			}
13093 			continue;
13094 		}
13095 
13096 		if (!btf_type_is_ptr(t)) {
13097 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13098 			return -EINVAL;
13099 		}
13100 
13101 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13102 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
13103 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
13104 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13105 			return -EACCES;
13106 		}
13107 
13108 		if (reg->ref_obj_id) {
13109 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13110 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13111 					     regno, reg->ref_obj_id,
13112 					     meta->ref_obj_id);
13113 				return -EFAULT;
13114 			}
13115 			meta->ref_obj_id = reg->ref_obj_id;
13116 			if (is_kfunc_release(meta))
13117 				meta->release_regno = regno;
13118 		}
13119 
13120 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13121 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13122 
13123 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13124 		if (kf_arg_type < 0)
13125 			return kf_arg_type;
13126 
13127 		switch (kf_arg_type) {
13128 		case KF_ARG_PTR_TO_NULL:
13129 			continue;
13130 		case KF_ARG_PTR_TO_MAP:
13131 			if (!reg->map_ptr) {
13132 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13133 				return -EINVAL;
13134 			}
13135 			if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) {
13136 				/* Use map_uid (which is unique id of inner map) to reject:
13137 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13138 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13139 				 * if (inner_map1 && inner_map2) {
13140 				 *     wq = bpf_map_lookup_elem(inner_map1);
13141 				 *     if (wq)
13142 				 *         // mismatch would have been allowed
13143 				 *         bpf_wq_init(wq, inner_map2);
13144 				 * }
13145 				 *
13146 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13147 				 */
13148 				if (meta->map.ptr != reg->map_ptr ||
13149 				    meta->map.uid != reg->map_uid) {
13150 					verbose(env,
13151 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13152 						meta->map.uid, reg->map_uid);
13153 					return -EINVAL;
13154 				}
13155 			}
13156 			meta->map.ptr = reg->map_ptr;
13157 			meta->map.uid = reg->map_uid;
13158 			fallthrough;
13159 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13160 		case KF_ARG_PTR_TO_BTF_ID:
13161 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13162 				break;
13163 
13164 			if (!is_trusted_reg(reg)) {
13165 				if (!is_kfunc_rcu(meta)) {
13166 					verbose(env, "R%d must be referenced or trusted\n", regno);
13167 					return -EINVAL;
13168 				}
13169 				if (!is_rcu_reg(reg)) {
13170 					verbose(env, "R%d must be a rcu pointer\n", regno);
13171 					return -EINVAL;
13172 				}
13173 			}
13174 			fallthrough;
13175 		case KF_ARG_PTR_TO_CTX:
13176 		case KF_ARG_PTR_TO_DYNPTR:
13177 		case KF_ARG_PTR_TO_ITER:
13178 		case KF_ARG_PTR_TO_LIST_HEAD:
13179 		case KF_ARG_PTR_TO_LIST_NODE:
13180 		case KF_ARG_PTR_TO_RB_ROOT:
13181 		case KF_ARG_PTR_TO_RB_NODE:
13182 		case KF_ARG_PTR_TO_MEM:
13183 		case KF_ARG_PTR_TO_MEM_SIZE:
13184 		case KF_ARG_PTR_TO_CALLBACK:
13185 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13186 		case KF_ARG_PTR_TO_CONST_STR:
13187 		case KF_ARG_PTR_TO_WORKQUEUE:
13188 		case KF_ARG_PTR_TO_IRQ_FLAG:
13189 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13190 			break;
13191 		default:
13192 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13193 			return -EFAULT;
13194 		}
13195 
13196 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13197 			arg_type |= OBJ_RELEASE;
13198 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13199 		if (ret < 0)
13200 			return ret;
13201 
13202 		switch (kf_arg_type) {
13203 		case KF_ARG_PTR_TO_CTX:
13204 			if (reg->type != PTR_TO_CTX) {
13205 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13206 					i, reg_type_str(env, reg->type));
13207 				return -EINVAL;
13208 			}
13209 
13210 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13211 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13212 				if (ret < 0)
13213 					return -EINVAL;
13214 				meta->ret_btf_id  = ret;
13215 			}
13216 			break;
13217 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13218 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13219 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13220 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13221 					return -EINVAL;
13222 				}
13223 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13224 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13225 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13226 					return -EINVAL;
13227 				}
13228 			} else {
13229 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13230 				return -EINVAL;
13231 			}
13232 			if (!reg->ref_obj_id) {
13233 				verbose(env, "allocated object must be referenced\n");
13234 				return -EINVAL;
13235 			}
13236 			if (meta->btf == btf_vmlinux) {
13237 				meta->arg_btf = reg->btf;
13238 				meta->arg_btf_id = reg->btf_id;
13239 			}
13240 			break;
13241 		case KF_ARG_PTR_TO_DYNPTR:
13242 		{
13243 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13244 			int clone_ref_obj_id = 0;
13245 
13246 			if (reg->type == CONST_PTR_TO_DYNPTR)
13247 				dynptr_arg_type |= MEM_RDONLY;
13248 
13249 			if (is_kfunc_arg_uninit(btf, &args[i]))
13250 				dynptr_arg_type |= MEM_UNINIT;
13251 
13252 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13253 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13254 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13255 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13256 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13257 				   (dynptr_arg_type & MEM_UNINIT)) {
13258 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13259 
13260 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13261 					verifier_bug(env, "no dynptr type for parent of clone");
13262 					return -EFAULT;
13263 				}
13264 
13265 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13266 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13267 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13268 					verifier_bug(env, "missing ref obj id for parent of clone");
13269 					return -EFAULT;
13270 				}
13271 			}
13272 
13273 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13274 			if (ret < 0)
13275 				return ret;
13276 
13277 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13278 				int id = dynptr_id(env, reg);
13279 
13280 				if (id < 0) {
13281 					verifier_bug(env, "failed to obtain dynptr id");
13282 					return id;
13283 				}
13284 				meta->initialized_dynptr.id = id;
13285 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13286 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13287 			}
13288 
13289 			break;
13290 		}
13291 		case KF_ARG_PTR_TO_ITER:
13292 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13293 				if (!check_css_task_iter_allowlist(env)) {
13294 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13295 					return -EINVAL;
13296 				}
13297 			}
13298 			ret = process_iter_arg(env, regno, insn_idx, meta);
13299 			if (ret < 0)
13300 				return ret;
13301 			break;
13302 		case KF_ARG_PTR_TO_LIST_HEAD:
13303 			if (reg->type != PTR_TO_MAP_VALUE &&
13304 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13305 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13306 				return -EINVAL;
13307 			}
13308 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13309 				verbose(env, "allocated object must be referenced\n");
13310 				return -EINVAL;
13311 			}
13312 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13313 			if (ret < 0)
13314 				return ret;
13315 			break;
13316 		case KF_ARG_PTR_TO_RB_ROOT:
13317 			if (reg->type != PTR_TO_MAP_VALUE &&
13318 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13319 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13320 				return -EINVAL;
13321 			}
13322 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13323 				verbose(env, "allocated object must be referenced\n");
13324 				return -EINVAL;
13325 			}
13326 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13327 			if (ret < 0)
13328 				return ret;
13329 			break;
13330 		case KF_ARG_PTR_TO_LIST_NODE:
13331 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13332 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13333 				return -EINVAL;
13334 			}
13335 			if (!reg->ref_obj_id) {
13336 				verbose(env, "allocated object must be referenced\n");
13337 				return -EINVAL;
13338 			}
13339 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13340 			if (ret < 0)
13341 				return ret;
13342 			break;
13343 		case KF_ARG_PTR_TO_RB_NODE:
13344 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13345 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13346 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13347 					return -EINVAL;
13348 				}
13349 				if (!reg->ref_obj_id) {
13350 					verbose(env, "allocated object must be referenced\n");
13351 					return -EINVAL;
13352 				}
13353 			} else {
13354 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13355 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13356 					return -EINVAL;
13357 				}
13358 				if (in_rbtree_lock_required_cb(env)) {
13359 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13360 					return -EINVAL;
13361 				}
13362 			}
13363 
13364 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13365 			if (ret < 0)
13366 				return ret;
13367 			break;
13368 		case KF_ARG_PTR_TO_MAP:
13369 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13370 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13371 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13372 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13373 			fallthrough;
13374 		case KF_ARG_PTR_TO_BTF_ID:
13375 			/* Only base_type is checked, further checks are done here */
13376 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13377 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13378 			    !reg2btf_ids[base_type(reg->type)]) {
13379 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13380 				verbose(env, "expected %s or socket\n",
13381 					reg_type_str(env, base_type(reg->type) |
13382 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13383 				return -EINVAL;
13384 			}
13385 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13386 			if (ret < 0)
13387 				return ret;
13388 			break;
13389 		case KF_ARG_PTR_TO_MEM:
13390 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13391 			if (IS_ERR(resolve_ret)) {
13392 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13393 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13394 				return -EINVAL;
13395 			}
13396 			ret = check_mem_reg(env, reg, regno, type_size);
13397 			if (ret < 0)
13398 				return ret;
13399 			break;
13400 		case KF_ARG_PTR_TO_MEM_SIZE:
13401 		{
13402 			struct bpf_reg_state *buff_reg = &regs[regno];
13403 			const struct btf_param *buff_arg = &args[i];
13404 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13405 			const struct btf_param *size_arg = &args[i + 1];
13406 
13407 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13408 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13409 				if (ret < 0) {
13410 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13411 					return ret;
13412 				}
13413 			}
13414 
13415 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13416 				if (meta->arg_constant.found) {
13417 					verifier_bug(env, "only one constant argument permitted");
13418 					return -EFAULT;
13419 				}
13420 				if (!tnum_is_const(size_reg->var_off)) {
13421 					verbose(env, "R%d must be a known constant\n", regno + 1);
13422 					return -EINVAL;
13423 				}
13424 				meta->arg_constant.found = true;
13425 				meta->arg_constant.value = size_reg->var_off.value;
13426 			}
13427 
13428 			/* Skip next '__sz' or '__szk' argument */
13429 			i++;
13430 			break;
13431 		}
13432 		case KF_ARG_PTR_TO_CALLBACK:
13433 			if (reg->type != PTR_TO_FUNC) {
13434 				verbose(env, "arg%d expected pointer to func\n", i);
13435 				return -EINVAL;
13436 			}
13437 			meta->subprogno = reg->subprogno;
13438 			break;
13439 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13440 			if (!type_is_ptr_alloc_obj(reg->type)) {
13441 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13442 				return -EINVAL;
13443 			}
13444 			if (!type_is_non_owning_ref(reg->type))
13445 				meta->arg_owning_ref = true;
13446 
13447 			rec = reg_btf_record(reg);
13448 			if (!rec) {
13449 				verifier_bug(env, "Couldn't find btf_record");
13450 				return -EFAULT;
13451 			}
13452 
13453 			if (rec->refcount_off < 0) {
13454 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13455 				return -EINVAL;
13456 			}
13457 
13458 			meta->arg_btf = reg->btf;
13459 			meta->arg_btf_id = reg->btf_id;
13460 			break;
13461 		case KF_ARG_PTR_TO_CONST_STR:
13462 			if (reg->type != PTR_TO_MAP_VALUE) {
13463 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13464 				return -EINVAL;
13465 			}
13466 			ret = check_reg_const_str(env, reg, regno);
13467 			if (ret)
13468 				return ret;
13469 			break;
13470 		case KF_ARG_PTR_TO_WORKQUEUE:
13471 			if (reg->type != PTR_TO_MAP_VALUE) {
13472 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13473 				return -EINVAL;
13474 			}
13475 			ret = process_wq_func(env, regno, meta);
13476 			if (ret < 0)
13477 				return ret;
13478 			break;
13479 		case KF_ARG_PTR_TO_IRQ_FLAG:
13480 			if (reg->type != PTR_TO_STACK) {
13481 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13482 				return -EINVAL;
13483 			}
13484 			ret = process_irq_flag(env, regno, meta);
13485 			if (ret < 0)
13486 				return ret;
13487 			break;
13488 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13489 		{
13490 			int flags = PROCESS_RES_LOCK;
13491 
13492 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13493 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13494 				return -EINVAL;
13495 			}
13496 
13497 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13498 				return -EFAULT;
13499 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13500 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13501 				flags |= PROCESS_SPIN_LOCK;
13502 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13503 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13504 				flags |= PROCESS_LOCK_IRQ;
13505 			ret = process_spin_lock(env, regno, flags);
13506 			if (ret < 0)
13507 				return ret;
13508 			break;
13509 		}
13510 		}
13511 	}
13512 
13513 	if (is_kfunc_release(meta) && !meta->release_regno) {
13514 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13515 			func_name);
13516 		return -EINVAL;
13517 	}
13518 
13519 	return 0;
13520 }
13521 
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)13522 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13523 			    struct bpf_insn *insn,
13524 			    struct bpf_kfunc_call_arg_meta *meta,
13525 			    const char **kfunc_name)
13526 {
13527 	const struct btf_type *func, *func_proto;
13528 	u32 func_id, *kfunc_flags;
13529 	const char *func_name;
13530 	struct btf *desc_btf;
13531 
13532 	if (kfunc_name)
13533 		*kfunc_name = NULL;
13534 
13535 	if (!insn->imm)
13536 		return -EINVAL;
13537 
13538 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13539 	if (IS_ERR(desc_btf))
13540 		return PTR_ERR(desc_btf);
13541 
13542 	func_id = insn->imm;
13543 	func = btf_type_by_id(desc_btf, func_id);
13544 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13545 	if (kfunc_name)
13546 		*kfunc_name = func_name;
13547 	func_proto = btf_type_by_id(desc_btf, func->type);
13548 
13549 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13550 	if (!kfunc_flags) {
13551 		return -EACCES;
13552 	}
13553 
13554 	memset(meta, 0, sizeof(*meta));
13555 	meta->btf = desc_btf;
13556 	meta->func_id = func_id;
13557 	meta->kfunc_flags = *kfunc_flags;
13558 	meta->func_proto = func_proto;
13559 	meta->func_name = func_name;
13560 
13561 	return 0;
13562 }
13563 
13564 /* check special kfuncs and return:
13565  *  1  - not fall-through to 'else' branch, continue verification
13566  *  0  - fall-through to 'else' branch
13567  * < 0 - not fall-through to 'else' branch, return error
13568  */
check_special_kfunc(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,struct bpf_reg_state * regs,struct bpf_insn_aux_data * insn_aux,const struct btf_type * ptr_type,struct btf * desc_btf)13569 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13570 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13571 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13572 {
13573 	const struct btf_type *ret_t;
13574 	int err = 0;
13575 
13576 	if (meta->btf != btf_vmlinux)
13577 		return 0;
13578 
13579 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13580 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13581 		struct btf_struct_meta *struct_meta;
13582 		struct btf *ret_btf;
13583 		u32 ret_btf_id;
13584 
13585 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13586 			return -ENOMEM;
13587 
13588 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13589 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13590 			return -EINVAL;
13591 		}
13592 
13593 		ret_btf = env->prog->aux->btf;
13594 		ret_btf_id = meta->arg_constant.value;
13595 
13596 		/* This may be NULL due to user not supplying a BTF */
13597 		if (!ret_btf) {
13598 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13599 			return -EINVAL;
13600 		}
13601 
13602 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13603 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13604 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13605 			return -EINVAL;
13606 		}
13607 
13608 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13609 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13610 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13611 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13612 				return -EINVAL;
13613 			}
13614 
13615 			if (!bpf_global_percpu_ma_set) {
13616 				mutex_lock(&bpf_percpu_ma_lock);
13617 				if (!bpf_global_percpu_ma_set) {
13618 					/* Charge memory allocated with bpf_global_percpu_ma to
13619 					 * root memcg. The obj_cgroup for root memcg is NULL.
13620 					 */
13621 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13622 					if (!err)
13623 						bpf_global_percpu_ma_set = true;
13624 				}
13625 				mutex_unlock(&bpf_percpu_ma_lock);
13626 				if (err)
13627 					return err;
13628 			}
13629 
13630 			mutex_lock(&bpf_percpu_ma_lock);
13631 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13632 			mutex_unlock(&bpf_percpu_ma_lock);
13633 			if (err)
13634 				return err;
13635 		}
13636 
13637 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13638 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13639 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13640 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13641 				return -EINVAL;
13642 			}
13643 
13644 			if (struct_meta) {
13645 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13646 				return -EINVAL;
13647 			}
13648 		}
13649 
13650 		mark_reg_known_zero(env, regs, BPF_REG_0);
13651 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13652 		regs[BPF_REG_0].btf = ret_btf;
13653 		regs[BPF_REG_0].btf_id = ret_btf_id;
13654 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13655 			regs[BPF_REG_0].type |= MEM_PERCPU;
13656 
13657 		insn_aux->obj_new_size = ret_t->size;
13658 		insn_aux->kptr_struct_meta = struct_meta;
13659 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13660 		mark_reg_known_zero(env, regs, BPF_REG_0);
13661 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13662 		regs[BPF_REG_0].btf = meta->arg_btf;
13663 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13664 
13665 		insn_aux->kptr_struct_meta =
13666 			btf_find_struct_meta(meta->arg_btf,
13667 					     meta->arg_btf_id);
13668 	} else if (is_list_node_type(ptr_type)) {
13669 		struct btf_field *field = meta->arg_list_head.field;
13670 
13671 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13672 	} else if (is_rbtree_node_type(ptr_type)) {
13673 		struct btf_field *field = meta->arg_rbtree_root.field;
13674 
13675 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13676 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13677 		mark_reg_known_zero(env, regs, BPF_REG_0);
13678 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13679 		regs[BPF_REG_0].btf = desc_btf;
13680 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13681 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13682 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13683 		if (!ret_t) {
13684 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13685 				meta->arg_constant.value);
13686 			return -EINVAL;
13687 		} else if (btf_type_is_struct(ret_t)) {
13688 			mark_reg_known_zero(env, regs, BPF_REG_0);
13689 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13690 			regs[BPF_REG_0].btf = desc_btf;
13691 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13692 		} else if (btf_type_is_void(ret_t)) {
13693 			mark_reg_known_zero(env, regs, BPF_REG_0);
13694 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13695 			regs[BPF_REG_0].mem_size = 0;
13696 		} else {
13697 			verbose(env,
13698 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13699 			return -EINVAL;
13700 		}
13701 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13702 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13703 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13704 
13705 		mark_reg_known_zero(env, regs, BPF_REG_0);
13706 
13707 		if (!meta->arg_constant.found) {
13708 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13709 			return -EFAULT;
13710 		}
13711 
13712 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13713 
13714 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13715 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13716 
13717 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13718 			regs[BPF_REG_0].type |= MEM_RDONLY;
13719 		} else {
13720 			/* this will set env->seen_direct_write to true */
13721 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13722 				verbose(env, "the prog does not allow writes to packet data\n");
13723 				return -EINVAL;
13724 			}
13725 		}
13726 
13727 		if (!meta->initialized_dynptr.id) {
13728 			verifier_bug(env, "no dynptr id");
13729 			return -EFAULT;
13730 		}
13731 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13732 
13733 		/* we don't need to set BPF_REG_0's ref obj id
13734 		 * because packet slices are not refcounted (see
13735 		 * dynptr_type_refcounted)
13736 		 */
13737 	} else {
13738 		return 0;
13739 	}
13740 
13741 	return 1;
13742 }
13743 
13744 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13745 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)13746 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13747 			    int *insn_idx_p)
13748 {
13749 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13750 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13751 	struct bpf_reg_state *regs = cur_regs(env);
13752 	const char *func_name, *ptr_type_name;
13753 	const struct btf_type *t, *ptr_type;
13754 	struct bpf_kfunc_call_arg_meta meta;
13755 	struct bpf_insn_aux_data *insn_aux;
13756 	int err, insn_idx = *insn_idx_p;
13757 	const struct btf_param *args;
13758 	struct btf *desc_btf;
13759 
13760 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13761 	if (!insn->imm)
13762 		return 0;
13763 
13764 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13765 	if (err == -EACCES && func_name)
13766 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13767 	if (err)
13768 		return err;
13769 	desc_btf = meta.btf;
13770 	insn_aux = &env->insn_aux_data[insn_idx];
13771 
13772 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13773 
13774 	if (!insn->off &&
13775 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13776 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13777 		struct bpf_verifier_state *branch;
13778 		struct bpf_reg_state *regs;
13779 
13780 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13781 		if (!branch) {
13782 			verbose(env, "failed to push state for failed lock acquisition\n");
13783 			return -ENOMEM;
13784 		}
13785 
13786 		regs = branch->frame[branch->curframe]->regs;
13787 
13788 		/* Clear r0-r5 registers in forked state */
13789 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13790 			mark_reg_not_init(env, regs, caller_saved[i]);
13791 
13792 		mark_reg_unknown(env, regs, BPF_REG_0);
13793 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13794 		if (err) {
13795 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13796 			return err;
13797 		}
13798 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13799 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13800 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13801 		return -EFAULT;
13802 	}
13803 
13804 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13805 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13806 		return -EACCES;
13807 	}
13808 
13809 	sleepable = is_kfunc_sleepable(&meta);
13810 	if (sleepable && !in_sleepable(env)) {
13811 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13812 		return -EACCES;
13813 	}
13814 
13815 	/* Check the arguments */
13816 	err = check_kfunc_args(env, &meta, insn_idx);
13817 	if (err < 0)
13818 		return err;
13819 
13820 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13821 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13822 					 set_rbtree_add_callback_state);
13823 		if (err) {
13824 			verbose(env, "kfunc %s#%d failed callback verification\n",
13825 				func_name, meta.func_id);
13826 			return err;
13827 		}
13828 	}
13829 
13830 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13831 		meta.r0_size = sizeof(u64);
13832 		meta.r0_rdonly = false;
13833 	}
13834 
13835 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13836 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13837 					 set_timer_callback_state);
13838 		if (err) {
13839 			verbose(env, "kfunc %s#%d failed callback verification\n",
13840 				func_name, meta.func_id);
13841 			return err;
13842 		}
13843 	}
13844 
13845 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13846 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13847 
13848 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13849 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13850 
13851 	if (env->cur_state->active_rcu_lock) {
13852 		struct bpf_func_state *state;
13853 		struct bpf_reg_state *reg;
13854 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13855 
13856 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13857 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13858 			return -EACCES;
13859 		}
13860 
13861 		if (rcu_lock) {
13862 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13863 			return -EINVAL;
13864 		} else if (rcu_unlock) {
13865 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13866 				if (reg->type & MEM_RCU) {
13867 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13868 					reg->type |= PTR_UNTRUSTED;
13869 				}
13870 			}));
13871 			env->cur_state->active_rcu_lock = false;
13872 		} else if (sleepable) {
13873 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13874 			return -EACCES;
13875 		}
13876 	} else if (rcu_lock) {
13877 		env->cur_state->active_rcu_lock = true;
13878 	} else if (rcu_unlock) {
13879 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13880 		return -EINVAL;
13881 	}
13882 
13883 	if (env->cur_state->active_preempt_locks) {
13884 		if (preempt_disable) {
13885 			env->cur_state->active_preempt_locks++;
13886 		} else if (preempt_enable) {
13887 			env->cur_state->active_preempt_locks--;
13888 		} else if (sleepable) {
13889 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13890 			return -EACCES;
13891 		}
13892 	} else if (preempt_disable) {
13893 		env->cur_state->active_preempt_locks++;
13894 	} else if (preempt_enable) {
13895 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13896 		return -EINVAL;
13897 	}
13898 
13899 	if (env->cur_state->active_irq_id && sleepable) {
13900 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13901 		return -EACCES;
13902 	}
13903 
13904 	/* In case of release function, we get register number of refcounted
13905 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13906 	 */
13907 	if (meta.release_regno) {
13908 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13909 		if (err) {
13910 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13911 				func_name, meta.func_id);
13912 			return err;
13913 		}
13914 	}
13915 
13916 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13917 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13918 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13919 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13920 		insn_aux->insert_off = regs[BPF_REG_2].off;
13921 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13922 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13923 		if (err) {
13924 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13925 				func_name, meta.func_id);
13926 			return err;
13927 		}
13928 
13929 		err = release_reference(env, release_ref_obj_id);
13930 		if (err) {
13931 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13932 				func_name, meta.func_id);
13933 			return err;
13934 		}
13935 	}
13936 
13937 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
13938 		if (!bpf_jit_supports_exceptions()) {
13939 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
13940 				func_name, meta.func_id);
13941 			return -ENOTSUPP;
13942 		}
13943 		env->seen_exception = true;
13944 
13945 		/* In the case of the default callback, the cookie value passed
13946 		 * to bpf_throw becomes the return value of the program.
13947 		 */
13948 		if (!env->exception_callback_subprog) {
13949 			err = check_return_code(env, BPF_REG_1, "R1");
13950 			if (err < 0)
13951 				return err;
13952 		}
13953 	}
13954 
13955 	for (i = 0; i < CALLER_SAVED_REGS; i++)
13956 		mark_reg_not_init(env, regs, caller_saved[i]);
13957 
13958 	/* Check return type */
13959 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
13960 
13961 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
13962 		/* Only exception is bpf_obj_new_impl */
13963 		if (meta.btf != btf_vmlinux ||
13964 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
13965 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
13966 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
13967 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
13968 			return -EINVAL;
13969 		}
13970 	}
13971 
13972 	if (btf_type_is_scalar(t)) {
13973 		mark_reg_unknown(env, regs, BPF_REG_0);
13974 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13975 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
13976 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
13977 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
13978 	} else if (btf_type_is_ptr(t)) {
13979 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
13980 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
13981 		if (err) {
13982 			if (err < 0)
13983 				return err;
13984 		} else if (btf_type_is_void(ptr_type)) {
13985 			/* kfunc returning 'void *' is equivalent to returning scalar */
13986 			mark_reg_unknown(env, regs, BPF_REG_0);
13987 		} else if (!__btf_type_is_struct(ptr_type)) {
13988 			if (!meta.r0_size) {
13989 				__u32 sz;
13990 
13991 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
13992 					meta.r0_size = sz;
13993 					meta.r0_rdonly = true;
13994 				}
13995 			}
13996 			if (!meta.r0_size) {
13997 				ptr_type_name = btf_name_by_offset(desc_btf,
13998 								   ptr_type->name_off);
13999 				verbose(env,
14000 					"kernel function %s returns pointer type %s %s is not supported\n",
14001 					func_name,
14002 					btf_type_str(ptr_type),
14003 					ptr_type_name);
14004 				return -EINVAL;
14005 			}
14006 
14007 			mark_reg_known_zero(env, regs, BPF_REG_0);
14008 			regs[BPF_REG_0].type = PTR_TO_MEM;
14009 			regs[BPF_REG_0].mem_size = meta.r0_size;
14010 
14011 			if (meta.r0_rdonly)
14012 				regs[BPF_REG_0].type |= MEM_RDONLY;
14013 
14014 			/* Ensures we don't access the memory after a release_reference() */
14015 			if (meta.ref_obj_id)
14016 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14017 		} else {
14018 			mark_reg_known_zero(env, regs, BPF_REG_0);
14019 			regs[BPF_REG_0].btf = desc_btf;
14020 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14021 			regs[BPF_REG_0].btf_id = ptr_type_id;
14022 
14023 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14024 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14025 
14026 			if (is_iter_next_kfunc(&meta)) {
14027 				struct bpf_reg_state *cur_iter;
14028 
14029 				cur_iter = get_iter_from_state(env->cur_state, &meta);
14030 
14031 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14032 					regs[BPF_REG_0].type |= MEM_RCU;
14033 				else
14034 					regs[BPF_REG_0].type |= PTR_TRUSTED;
14035 			}
14036 		}
14037 
14038 		if (is_kfunc_ret_null(&meta)) {
14039 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14040 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14041 			regs[BPF_REG_0].id = ++env->id_gen;
14042 		}
14043 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14044 		if (is_kfunc_acquire(&meta)) {
14045 			int id = acquire_reference(env, insn_idx);
14046 
14047 			if (id < 0)
14048 				return id;
14049 			if (is_kfunc_ret_null(&meta))
14050 				regs[BPF_REG_0].id = id;
14051 			regs[BPF_REG_0].ref_obj_id = id;
14052 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14053 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14054 		}
14055 
14056 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14057 			regs[BPF_REG_0].id = ++env->id_gen;
14058 	} else if (btf_type_is_void(t)) {
14059 		if (meta.btf == btf_vmlinux) {
14060 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14061 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14062 				insn_aux->kptr_struct_meta =
14063 					btf_find_struct_meta(meta.arg_btf,
14064 							     meta.arg_btf_id);
14065 			}
14066 		}
14067 	}
14068 
14069 	nargs = btf_type_vlen(meta.func_proto);
14070 	args = (const struct btf_param *)(meta.func_proto + 1);
14071 	for (i = 0; i < nargs; i++) {
14072 		u32 regno = i + 1;
14073 
14074 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14075 		if (btf_type_is_ptr(t))
14076 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14077 		else
14078 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14079 			mark_btf_func_reg_size(env, regno, t->size);
14080 	}
14081 
14082 	if (is_iter_next_kfunc(&meta)) {
14083 		err = process_iter_next_call(env, insn_idx, &meta);
14084 		if (err)
14085 			return err;
14086 	}
14087 
14088 	return 0;
14089 }
14090 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)14091 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14092 				  const struct bpf_reg_state *reg,
14093 				  enum bpf_reg_type type)
14094 {
14095 	bool known = tnum_is_const(reg->var_off);
14096 	s64 val = reg->var_off.value;
14097 	s64 smin = reg->smin_value;
14098 
14099 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14100 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14101 			reg_type_str(env, type), val);
14102 		return false;
14103 	}
14104 
14105 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14106 		verbose(env, "%s pointer offset %d is not allowed\n",
14107 			reg_type_str(env, type), reg->off);
14108 		return false;
14109 	}
14110 
14111 	if (smin == S64_MIN) {
14112 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14113 			reg_type_str(env, type));
14114 		return false;
14115 	}
14116 
14117 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14118 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14119 			smin, reg_type_str(env, type));
14120 		return false;
14121 	}
14122 
14123 	return true;
14124 }
14125 
14126 enum {
14127 	REASON_BOUNDS	= -1,
14128 	REASON_TYPE	= -2,
14129 	REASON_PATHS	= -3,
14130 	REASON_LIMIT	= -4,
14131 	REASON_STACK	= -5,
14132 };
14133 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)14134 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14135 			      u32 *alu_limit, bool mask_to_left)
14136 {
14137 	u32 max = 0, ptr_limit = 0;
14138 
14139 	switch (ptr_reg->type) {
14140 	case PTR_TO_STACK:
14141 		/* Offset 0 is out-of-bounds, but acceptable start for the
14142 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14143 		 * offset where we would need to deal with min/max bounds is
14144 		 * currently prohibited for unprivileged.
14145 		 */
14146 		max = MAX_BPF_STACK + mask_to_left;
14147 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14148 		break;
14149 	case PTR_TO_MAP_VALUE:
14150 		max = ptr_reg->map_ptr->value_size;
14151 		ptr_limit = (mask_to_left ?
14152 			     ptr_reg->smin_value :
14153 			     ptr_reg->umax_value) + ptr_reg->off;
14154 		break;
14155 	default:
14156 		return REASON_TYPE;
14157 	}
14158 
14159 	if (ptr_limit >= max)
14160 		return REASON_LIMIT;
14161 	*alu_limit = ptr_limit;
14162 	return 0;
14163 }
14164 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)14165 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14166 				    const struct bpf_insn *insn)
14167 {
14168 	return env->bypass_spec_v1 ||
14169 		BPF_SRC(insn->code) == BPF_K ||
14170 		cur_aux(env)->nospec;
14171 }
14172 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)14173 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14174 				       u32 alu_state, u32 alu_limit)
14175 {
14176 	/* If we arrived here from different branches with different
14177 	 * state or limits to sanitize, then this won't work.
14178 	 */
14179 	if (aux->alu_state &&
14180 	    (aux->alu_state != alu_state ||
14181 	     aux->alu_limit != alu_limit))
14182 		return REASON_PATHS;
14183 
14184 	/* Corresponding fixup done in do_misc_fixups(). */
14185 	aux->alu_state = alu_state;
14186 	aux->alu_limit = alu_limit;
14187 	return 0;
14188 }
14189 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)14190 static int sanitize_val_alu(struct bpf_verifier_env *env,
14191 			    struct bpf_insn *insn)
14192 {
14193 	struct bpf_insn_aux_data *aux = cur_aux(env);
14194 
14195 	if (can_skip_alu_sanitation(env, insn))
14196 		return 0;
14197 
14198 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14199 }
14200 
sanitize_needed(u8 opcode)14201 static bool sanitize_needed(u8 opcode)
14202 {
14203 	return opcode == BPF_ADD || opcode == BPF_SUB;
14204 }
14205 
14206 struct bpf_sanitize_info {
14207 	struct bpf_insn_aux_data aux;
14208 	bool mask_to_left;
14209 };
14210 
14211 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)14212 sanitize_speculative_path(struct bpf_verifier_env *env,
14213 			  const struct bpf_insn *insn,
14214 			  u32 next_idx, u32 curr_idx)
14215 {
14216 	struct bpf_verifier_state *branch;
14217 	struct bpf_reg_state *regs;
14218 
14219 	branch = push_stack(env, next_idx, curr_idx, true);
14220 	if (branch && insn) {
14221 		regs = branch->frame[branch->curframe]->regs;
14222 		if (BPF_SRC(insn->code) == BPF_K) {
14223 			mark_reg_unknown(env, regs, insn->dst_reg);
14224 		} else if (BPF_SRC(insn->code) == BPF_X) {
14225 			mark_reg_unknown(env, regs, insn->dst_reg);
14226 			mark_reg_unknown(env, regs, insn->src_reg);
14227 		}
14228 	}
14229 	return branch;
14230 }
14231 
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)14232 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14233 			    struct bpf_insn *insn,
14234 			    const struct bpf_reg_state *ptr_reg,
14235 			    const struct bpf_reg_state *off_reg,
14236 			    struct bpf_reg_state *dst_reg,
14237 			    struct bpf_sanitize_info *info,
14238 			    const bool commit_window)
14239 {
14240 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14241 	struct bpf_verifier_state *vstate = env->cur_state;
14242 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14243 	bool off_is_neg = off_reg->smin_value < 0;
14244 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14245 	u8 opcode = BPF_OP(insn->code);
14246 	u32 alu_state, alu_limit;
14247 	struct bpf_reg_state tmp;
14248 	bool ret;
14249 	int err;
14250 
14251 	if (can_skip_alu_sanitation(env, insn))
14252 		return 0;
14253 
14254 	/* We already marked aux for masking from non-speculative
14255 	 * paths, thus we got here in the first place. We only care
14256 	 * to explore bad access from here.
14257 	 */
14258 	if (vstate->speculative)
14259 		goto do_sim;
14260 
14261 	if (!commit_window) {
14262 		if (!tnum_is_const(off_reg->var_off) &&
14263 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14264 			return REASON_BOUNDS;
14265 
14266 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14267 				     (opcode == BPF_SUB && !off_is_neg);
14268 	}
14269 
14270 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14271 	if (err < 0)
14272 		return err;
14273 
14274 	if (commit_window) {
14275 		/* In commit phase we narrow the masking window based on
14276 		 * the observed pointer move after the simulated operation.
14277 		 */
14278 		alu_state = info->aux.alu_state;
14279 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14280 	} else {
14281 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14282 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14283 		alu_state |= ptr_is_dst_reg ?
14284 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14285 
14286 		/* Limit pruning on unknown scalars to enable deep search for
14287 		 * potential masking differences from other program paths.
14288 		 */
14289 		if (!off_is_imm)
14290 			env->explore_alu_limits = true;
14291 	}
14292 
14293 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14294 	if (err < 0)
14295 		return err;
14296 do_sim:
14297 	/* If we're in commit phase, we're done here given we already
14298 	 * pushed the truncated dst_reg into the speculative verification
14299 	 * stack.
14300 	 *
14301 	 * Also, when register is a known constant, we rewrite register-based
14302 	 * operation to immediate-based, and thus do not need masking (and as
14303 	 * a consequence, do not need to simulate the zero-truncation either).
14304 	 */
14305 	if (commit_window || off_is_imm)
14306 		return 0;
14307 
14308 	/* Simulate and find potential out-of-bounds access under
14309 	 * speculative execution from truncation as a result of
14310 	 * masking when off was not within expected range. If off
14311 	 * sits in dst, then we temporarily need to move ptr there
14312 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14313 	 * for cases where we use K-based arithmetic in one direction
14314 	 * and truncated reg-based in the other in order to explore
14315 	 * bad access.
14316 	 */
14317 	if (!ptr_is_dst_reg) {
14318 		tmp = *dst_reg;
14319 		copy_register_state(dst_reg, ptr_reg);
14320 	}
14321 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
14322 					env->insn_idx);
14323 	if (!ptr_is_dst_reg && ret)
14324 		*dst_reg = tmp;
14325 	return !ret ? REASON_STACK : 0;
14326 }
14327 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)14328 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14329 {
14330 	struct bpf_verifier_state *vstate = env->cur_state;
14331 
14332 	/* If we simulate paths under speculation, we don't update the
14333 	 * insn as 'seen' such that when we verify unreachable paths in
14334 	 * the non-speculative domain, sanitize_dead_code() can still
14335 	 * rewrite/sanitize them.
14336 	 */
14337 	if (!vstate->speculative)
14338 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14339 }
14340 
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)14341 static int sanitize_err(struct bpf_verifier_env *env,
14342 			const struct bpf_insn *insn, int reason,
14343 			const struct bpf_reg_state *off_reg,
14344 			const struct bpf_reg_state *dst_reg)
14345 {
14346 	static const char *err = "pointer arithmetic with it prohibited for !root";
14347 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14348 	u32 dst = insn->dst_reg, src = insn->src_reg;
14349 
14350 	switch (reason) {
14351 	case REASON_BOUNDS:
14352 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14353 			off_reg == dst_reg ? dst : src, err);
14354 		break;
14355 	case REASON_TYPE:
14356 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14357 			off_reg == dst_reg ? src : dst, err);
14358 		break;
14359 	case REASON_PATHS:
14360 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14361 			dst, op, err);
14362 		break;
14363 	case REASON_LIMIT:
14364 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14365 			dst, op, err);
14366 		break;
14367 	case REASON_STACK:
14368 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14369 			dst, err);
14370 		return -ENOMEM;
14371 	default:
14372 		verifier_bug(env, "unknown reason (%d)", reason);
14373 		break;
14374 	}
14375 
14376 	return -EACCES;
14377 }
14378 
14379 /* check that stack access falls within stack limits and that 'reg' doesn't
14380  * have a variable offset.
14381  *
14382  * Variable offset is prohibited for unprivileged mode for simplicity since it
14383  * requires corresponding support in Spectre masking for stack ALU.  See also
14384  * retrieve_ptr_limit().
14385  *
14386  *
14387  * 'off' includes 'reg->off'.
14388  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)14389 static int check_stack_access_for_ptr_arithmetic(
14390 				struct bpf_verifier_env *env,
14391 				int regno,
14392 				const struct bpf_reg_state *reg,
14393 				int off)
14394 {
14395 	if (!tnum_is_const(reg->var_off)) {
14396 		char tn_buf[48];
14397 
14398 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14399 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14400 			regno, tn_buf, off);
14401 		return -EACCES;
14402 	}
14403 
14404 	if (off >= 0 || off < -MAX_BPF_STACK) {
14405 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14406 			"prohibited for !root; off=%d\n", regno, off);
14407 		return -EACCES;
14408 	}
14409 
14410 	return 0;
14411 }
14412 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)14413 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14414 				 const struct bpf_insn *insn,
14415 				 const struct bpf_reg_state *dst_reg)
14416 {
14417 	u32 dst = insn->dst_reg;
14418 
14419 	/* For unprivileged we require that resulting offset must be in bounds
14420 	 * in order to be able to sanitize access later on.
14421 	 */
14422 	if (env->bypass_spec_v1)
14423 		return 0;
14424 
14425 	switch (dst_reg->type) {
14426 	case PTR_TO_STACK:
14427 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14428 					dst_reg->off + dst_reg->var_off.value))
14429 			return -EACCES;
14430 		break;
14431 	case PTR_TO_MAP_VALUE:
14432 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14433 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14434 				"prohibited for !root\n", dst);
14435 			return -EACCES;
14436 		}
14437 		break;
14438 	default:
14439 		return -EOPNOTSUPP;
14440 	}
14441 
14442 	return 0;
14443 }
14444 
14445 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14446  * Caller should also handle BPF_MOV case separately.
14447  * If we return -EACCES, caller may want to try again treating pointer as a
14448  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14449  */
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)14450 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14451 				   struct bpf_insn *insn,
14452 				   const struct bpf_reg_state *ptr_reg,
14453 				   const struct bpf_reg_state *off_reg)
14454 {
14455 	struct bpf_verifier_state *vstate = env->cur_state;
14456 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14457 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14458 	bool known = tnum_is_const(off_reg->var_off);
14459 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14460 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14461 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14462 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14463 	struct bpf_sanitize_info info = {};
14464 	u8 opcode = BPF_OP(insn->code);
14465 	u32 dst = insn->dst_reg;
14466 	int ret, bounds_ret;
14467 
14468 	dst_reg = &regs[dst];
14469 
14470 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14471 	    smin_val > smax_val || umin_val > umax_val) {
14472 		/* Taint dst register if offset had invalid bounds derived from
14473 		 * e.g. dead branches.
14474 		 */
14475 		__mark_reg_unknown(env, dst_reg);
14476 		return 0;
14477 	}
14478 
14479 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14480 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14481 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14482 			__mark_reg_unknown(env, dst_reg);
14483 			return 0;
14484 		}
14485 
14486 		verbose(env,
14487 			"R%d 32-bit pointer arithmetic prohibited\n",
14488 			dst);
14489 		return -EACCES;
14490 	}
14491 
14492 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14493 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14494 			dst, reg_type_str(env, ptr_reg->type));
14495 		return -EACCES;
14496 	}
14497 
14498 	/*
14499 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14500 	 * instructions, hence no need to track offsets.
14501 	 */
14502 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14503 		return 0;
14504 
14505 	switch (base_type(ptr_reg->type)) {
14506 	case PTR_TO_CTX:
14507 	case PTR_TO_MAP_VALUE:
14508 	case PTR_TO_MAP_KEY:
14509 	case PTR_TO_STACK:
14510 	case PTR_TO_PACKET_META:
14511 	case PTR_TO_PACKET:
14512 	case PTR_TO_TP_BUFFER:
14513 	case PTR_TO_BTF_ID:
14514 	case PTR_TO_MEM:
14515 	case PTR_TO_BUF:
14516 	case PTR_TO_FUNC:
14517 	case CONST_PTR_TO_DYNPTR:
14518 		break;
14519 	case PTR_TO_FLOW_KEYS:
14520 		if (known)
14521 			break;
14522 		fallthrough;
14523 	case CONST_PTR_TO_MAP:
14524 		/* smin_val represents the known value */
14525 		if (known && smin_val == 0 && opcode == BPF_ADD)
14526 			break;
14527 		fallthrough;
14528 	default:
14529 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14530 			dst, reg_type_str(env, ptr_reg->type));
14531 		return -EACCES;
14532 	}
14533 
14534 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14535 	 * The id may be overwritten later if we create a new variable offset.
14536 	 */
14537 	dst_reg->type = ptr_reg->type;
14538 	dst_reg->id = ptr_reg->id;
14539 
14540 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14541 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14542 		return -EINVAL;
14543 
14544 	/* pointer types do not carry 32-bit bounds at the moment. */
14545 	__mark_reg32_unbounded(dst_reg);
14546 
14547 	if (sanitize_needed(opcode)) {
14548 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14549 				       &info, false);
14550 		if (ret < 0)
14551 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14552 	}
14553 
14554 	switch (opcode) {
14555 	case BPF_ADD:
14556 		/* We can take a fixed offset as long as it doesn't overflow
14557 		 * the s32 'off' field
14558 		 */
14559 		if (known && (ptr_reg->off + smin_val ==
14560 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14561 			/* pointer += K.  Accumulate it into fixed offset */
14562 			dst_reg->smin_value = smin_ptr;
14563 			dst_reg->smax_value = smax_ptr;
14564 			dst_reg->umin_value = umin_ptr;
14565 			dst_reg->umax_value = umax_ptr;
14566 			dst_reg->var_off = ptr_reg->var_off;
14567 			dst_reg->off = ptr_reg->off + smin_val;
14568 			dst_reg->raw = ptr_reg->raw;
14569 			break;
14570 		}
14571 		/* A new variable offset is created.  Note that off_reg->off
14572 		 * == 0, since it's a scalar.
14573 		 * dst_reg gets the pointer type and since some positive
14574 		 * integer value was added to the pointer, give it a new 'id'
14575 		 * if it's a PTR_TO_PACKET.
14576 		 * this creates a new 'base' pointer, off_reg (variable) gets
14577 		 * added into the variable offset, and we copy the fixed offset
14578 		 * from ptr_reg.
14579 		 */
14580 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14581 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14582 			dst_reg->smin_value = S64_MIN;
14583 			dst_reg->smax_value = S64_MAX;
14584 		}
14585 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14586 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14587 			dst_reg->umin_value = 0;
14588 			dst_reg->umax_value = U64_MAX;
14589 		}
14590 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14591 		dst_reg->off = ptr_reg->off;
14592 		dst_reg->raw = ptr_reg->raw;
14593 		if (reg_is_pkt_pointer(ptr_reg)) {
14594 			dst_reg->id = ++env->id_gen;
14595 			/* something was added to pkt_ptr, set range to zero */
14596 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14597 		}
14598 		break;
14599 	case BPF_SUB:
14600 		if (dst_reg == off_reg) {
14601 			/* scalar -= pointer.  Creates an unknown scalar */
14602 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14603 				dst);
14604 			return -EACCES;
14605 		}
14606 		/* We don't allow subtraction from FP, because (according to
14607 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14608 		 * be able to deal with it.
14609 		 */
14610 		if (ptr_reg->type == PTR_TO_STACK) {
14611 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14612 				dst);
14613 			return -EACCES;
14614 		}
14615 		if (known && (ptr_reg->off - smin_val ==
14616 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14617 			/* pointer -= K.  Subtract it from fixed offset */
14618 			dst_reg->smin_value = smin_ptr;
14619 			dst_reg->smax_value = smax_ptr;
14620 			dst_reg->umin_value = umin_ptr;
14621 			dst_reg->umax_value = umax_ptr;
14622 			dst_reg->var_off = ptr_reg->var_off;
14623 			dst_reg->id = ptr_reg->id;
14624 			dst_reg->off = ptr_reg->off - smin_val;
14625 			dst_reg->raw = ptr_reg->raw;
14626 			break;
14627 		}
14628 		/* A new variable offset is created.  If the subtrahend is known
14629 		 * nonnegative, then any reg->range we had before is still good.
14630 		 */
14631 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14632 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14633 			/* Overflow possible, we know nothing */
14634 			dst_reg->smin_value = S64_MIN;
14635 			dst_reg->smax_value = S64_MAX;
14636 		}
14637 		if (umin_ptr < umax_val) {
14638 			/* Overflow possible, we know nothing */
14639 			dst_reg->umin_value = 0;
14640 			dst_reg->umax_value = U64_MAX;
14641 		} else {
14642 			/* Cannot overflow (as long as bounds are consistent) */
14643 			dst_reg->umin_value = umin_ptr - umax_val;
14644 			dst_reg->umax_value = umax_ptr - umin_val;
14645 		}
14646 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14647 		dst_reg->off = ptr_reg->off;
14648 		dst_reg->raw = ptr_reg->raw;
14649 		if (reg_is_pkt_pointer(ptr_reg)) {
14650 			dst_reg->id = ++env->id_gen;
14651 			/* something was added to pkt_ptr, set range to zero */
14652 			if (smin_val < 0)
14653 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14654 		}
14655 		break;
14656 	case BPF_AND:
14657 	case BPF_OR:
14658 	case BPF_XOR:
14659 		/* bitwise ops on pointers are troublesome, prohibit. */
14660 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14661 			dst, bpf_alu_string[opcode >> 4]);
14662 		return -EACCES;
14663 	default:
14664 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14665 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14666 			dst, bpf_alu_string[opcode >> 4]);
14667 		return -EACCES;
14668 	}
14669 
14670 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14671 		return -EINVAL;
14672 	reg_bounds_sync(dst_reg);
14673 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14674 	if (bounds_ret == -EACCES)
14675 		return bounds_ret;
14676 	if (sanitize_needed(opcode)) {
14677 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14678 				       &info, true);
14679 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14680 				    && !env->cur_state->speculative
14681 				    && bounds_ret
14682 				    && !ret,
14683 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14684 			return -EFAULT;
14685 		}
14686 		if (ret < 0)
14687 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14688 	}
14689 
14690 	return 0;
14691 }
14692 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14693 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14694 				 struct bpf_reg_state *src_reg)
14695 {
14696 	s32 *dst_smin = &dst_reg->s32_min_value;
14697 	s32 *dst_smax = &dst_reg->s32_max_value;
14698 	u32 *dst_umin = &dst_reg->u32_min_value;
14699 	u32 *dst_umax = &dst_reg->u32_max_value;
14700 	u32 umin_val = src_reg->u32_min_value;
14701 	u32 umax_val = src_reg->u32_max_value;
14702 	bool min_overflow, max_overflow;
14703 
14704 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14705 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14706 		*dst_smin = S32_MIN;
14707 		*dst_smax = S32_MAX;
14708 	}
14709 
14710 	/* If either all additions overflow or no additions overflow, then
14711 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14712 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14713 	 * the output bounds to unbounded.
14714 	 */
14715 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14716 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14717 
14718 	if (!min_overflow && max_overflow) {
14719 		*dst_umin = 0;
14720 		*dst_umax = U32_MAX;
14721 	}
14722 }
14723 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14724 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14725 			       struct bpf_reg_state *src_reg)
14726 {
14727 	s64 *dst_smin = &dst_reg->smin_value;
14728 	s64 *dst_smax = &dst_reg->smax_value;
14729 	u64 *dst_umin = &dst_reg->umin_value;
14730 	u64 *dst_umax = &dst_reg->umax_value;
14731 	u64 umin_val = src_reg->umin_value;
14732 	u64 umax_val = src_reg->umax_value;
14733 	bool min_overflow, max_overflow;
14734 
14735 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14736 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14737 		*dst_smin = S64_MIN;
14738 		*dst_smax = S64_MAX;
14739 	}
14740 
14741 	/* If either all additions overflow or no additions overflow, then
14742 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14743 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14744 	 * the output bounds to unbounded.
14745 	 */
14746 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14747 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14748 
14749 	if (!min_overflow && max_overflow) {
14750 		*dst_umin = 0;
14751 		*dst_umax = U64_MAX;
14752 	}
14753 }
14754 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14755 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14756 				 struct bpf_reg_state *src_reg)
14757 {
14758 	s32 *dst_smin = &dst_reg->s32_min_value;
14759 	s32 *dst_smax = &dst_reg->s32_max_value;
14760 	u32 *dst_umin = &dst_reg->u32_min_value;
14761 	u32 *dst_umax = &dst_reg->u32_max_value;
14762 	u32 umin_val = src_reg->u32_min_value;
14763 	u32 umax_val = src_reg->u32_max_value;
14764 	bool min_underflow, max_underflow;
14765 
14766 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14767 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14768 		/* Overflow possible, we know nothing */
14769 		*dst_smin = S32_MIN;
14770 		*dst_smax = S32_MAX;
14771 	}
14772 
14773 	/* If either all subtractions underflow or no subtractions
14774 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14775 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14776 	 * underflow), set the output bounds to unbounded.
14777 	 */
14778 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14779 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14780 
14781 	if (min_underflow && !max_underflow) {
14782 		*dst_umin = 0;
14783 		*dst_umax = U32_MAX;
14784 	}
14785 }
14786 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14787 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14788 			       struct bpf_reg_state *src_reg)
14789 {
14790 	s64 *dst_smin = &dst_reg->smin_value;
14791 	s64 *dst_smax = &dst_reg->smax_value;
14792 	u64 *dst_umin = &dst_reg->umin_value;
14793 	u64 *dst_umax = &dst_reg->umax_value;
14794 	u64 umin_val = src_reg->umin_value;
14795 	u64 umax_val = src_reg->umax_value;
14796 	bool min_underflow, max_underflow;
14797 
14798 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14799 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14800 		/* Overflow possible, we know nothing */
14801 		*dst_smin = S64_MIN;
14802 		*dst_smax = S64_MAX;
14803 	}
14804 
14805 	/* If either all subtractions underflow or no subtractions
14806 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14807 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14808 	 * underflow), set the output bounds to unbounded.
14809 	 */
14810 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14811 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14812 
14813 	if (min_underflow && !max_underflow) {
14814 		*dst_umin = 0;
14815 		*dst_umax = U64_MAX;
14816 	}
14817 }
14818 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14819 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14820 				 struct bpf_reg_state *src_reg)
14821 {
14822 	s32 *dst_smin = &dst_reg->s32_min_value;
14823 	s32 *dst_smax = &dst_reg->s32_max_value;
14824 	u32 *dst_umin = &dst_reg->u32_min_value;
14825 	u32 *dst_umax = &dst_reg->u32_max_value;
14826 	s32 tmp_prod[4];
14827 
14828 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14829 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14830 		/* Overflow possible, we know nothing */
14831 		*dst_umin = 0;
14832 		*dst_umax = U32_MAX;
14833 	}
14834 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14835 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14836 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14837 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14838 		/* Overflow possible, we know nothing */
14839 		*dst_smin = S32_MIN;
14840 		*dst_smax = S32_MAX;
14841 	} else {
14842 		*dst_smin = min_array(tmp_prod, 4);
14843 		*dst_smax = max_array(tmp_prod, 4);
14844 	}
14845 }
14846 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14847 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14848 			       struct bpf_reg_state *src_reg)
14849 {
14850 	s64 *dst_smin = &dst_reg->smin_value;
14851 	s64 *dst_smax = &dst_reg->smax_value;
14852 	u64 *dst_umin = &dst_reg->umin_value;
14853 	u64 *dst_umax = &dst_reg->umax_value;
14854 	s64 tmp_prod[4];
14855 
14856 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14857 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14858 		/* Overflow possible, we know nothing */
14859 		*dst_umin = 0;
14860 		*dst_umax = U64_MAX;
14861 	}
14862 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14863 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14864 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14865 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14866 		/* Overflow possible, we know nothing */
14867 		*dst_smin = S64_MIN;
14868 		*dst_smax = S64_MAX;
14869 	} else {
14870 		*dst_smin = min_array(tmp_prod, 4);
14871 		*dst_smax = max_array(tmp_prod, 4);
14872 	}
14873 }
14874 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14875 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14876 				 struct bpf_reg_state *src_reg)
14877 {
14878 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14879 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14880 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14881 	u32 umax_val = src_reg->u32_max_value;
14882 
14883 	if (src_known && dst_known) {
14884 		__mark_reg32_known(dst_reg, var32_off.value);
14885 		return;
14886 	}
14887 
14888 	/* We get our minimum from the var_off, since that's inherently
14889 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14890 	 */
14891 	dst_reg->u32_min_value = var32_off.value;
14892 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14893 
14894 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14895 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14896 	 */
14897 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14898 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14899 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14900 	} else {
14901 		dst_reg->s32_min_value = S32_MIN;
14902 		dst_reg->s32_max_value = S32_MAX;
14903 	}
14904 }
14905 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14906 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14907 			       struct bpf_reg_state *src_reg)
14908 {
14909 	bool src_known = tnum_is_const(src_reg->var_off);
14910 	bool dst_known = tnum_is_const(dst_reg->var_off);
14911 	u64 umax_val = src_reg->umax_value;
14912 
14913 	if (src_known && dst_known) {
14914 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14915 		return;
14916 	}
14917 
14918 	/* We get our minimum from the var_off, since that's inherently
14919 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14920 	 */
14921 	dst_reg->umin_value = dst_reg->var_off.value;
14922 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14923 
14924 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14925 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14926 	 */
14927 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14928 		dst_reg->smin_value = dst_reg->umin_value;
14929 		dst_reg->smax_value = dst_reg->umax_value;
14930 	} else {
14931 		dst_reg->smin_value = S64_MIN;
14932 		dst_reg->smax_value = S64_MAX;
14933 	}
14934 	/* We may learn something more from the var_off */
14935 	__update_reg_bounds(dst_reg);
14936 }
14937 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14938 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
14939 				struct bpf_reg_state *src_reg)
14940 {
14941 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14942 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14943 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14944 	u32 umin_val = src_reg->u32_min_value;
14945 
14946 	if (src_known && dst_known) {
14947 		__mark_reg32_known(dst_reg, var32_off.value);
14948 		return;
14949 	}
14950 
14951 	/* We get our maximum from the var_off, and our minimum is the
14952 	 * maximum of the operands' minima
14953 	 */
14954 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
14955 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
14956 
14957 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14958 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14959 	 */
14960 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14961 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14962 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14963 	} else {
14964 		dst_reg->s32_min_value = S32_MIN;
14965 		dst_reg->s32_max_value = S32_MAX;
14966 	}
14967 }
14968 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14969 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
14970 			      struct bpf_reg_state *src_reg)
14971 {
14972 	bool src_known = tnum_is_const(src_reg->var_off);
14973 	bool dst_known = tnum_is_const(dst_reg->var_off);
14974 	u64 umin_val = src_reg->umin_value;
14975 
14976 	if (src_known && dst_known) {
14977 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14978 		return;
14979 	}
14980 
14981 	/* We get our maximum from the var_off, and our minimum is the
14982 	 * maximum of the operands' minima
14983 	 */
14984 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
14985 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
14986 
14987 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14988 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
14989 	 */
14990 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
14991 		dst_reg->smin_value = dst_reg->umin_value;
14992 		dst_reg->smax_value = dst_reg->umax_value;
14993 	} else {
14994 		dst_reg->smin_value = S64_MIN;
14995 		dst_reg->smax_value = S64_MAX;
14996 	}
14997 	/* We may learn something more from the var_off */
14998 	__update_reg_bounds(dst_reg);
14999 }
15000 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15001 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15002 				 struct bpf_reg_state *src_reg)
15003 {
15004 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15005 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15006 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15007 
15008 	if (src_known && dst_known) {
15009 		__mark_reg32_known(dst_reg, var32_off.value);
15010 		return;
15011 	}
15012 
15013 	/* We get both minimum and maximum from the var32_off. */
15014 	dst_reg->u32_min_value = var32_off.value;
15015 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15016 
15017 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15018 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15019 	 */
15020 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15021 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15022 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15023 	} else {
15024 		dst_reg->s32_min_value = S32_MIN;
15025 		dst_reg->s32_max_value = S32_MAX;
15026 	}
15027 }
15028 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15029 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15030 			       struct bpf_reg_state *src_reg)
15031 {
15032 	bool src_known = tnum_is_const(src_reg->var_off);
15033 	bool dst_known = tnum_is_const(dst_reg->var_off);
15034 
15035 	if (src_known && dst_known) {
15036 		/* dst_reg->var_off.value has been updated earlier */
15037 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15038 		return;
15039 	}
15040 
15041 	/* We get both minimum and maximum from the var_off. */
15042 	dst_reg->umin_value = dst_reg->var_off.value;
15043 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15044 
15045 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15046 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15047 	 */
15048 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15049 		dst_reg->smin_value = dst_reg->umin_value;
15050 		dst_reg->smax_value = dst_reg->umax_value;
15051 	} else {
15052 		dst_reg->smin_value = S64_MIN;
15053 		dst_reg->smax_value = S64_MAX;
15054 	}
15055 
15056 	__update_reg_bounds(dst_reg);
15057 }
15058 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15059 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15060 				   u64 umin_val, u64 umax_val)
15061 {
15062 	/* We lose all sign bit information (except what we can pick
15063 	 * up from var_off)
15064 	 */
15065 	dst_reg->s32_min_value = S32_MIN;
15066 	dst_reg->s32_max_value = S32_MAX;
15067 	/* If we might shift our top bit out, then we know nothing */
15068 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15069 		dst_reg->u32_min_value = 0;
15070 		dst_reg->u32_max_value = U32_MAX;
15071 	} else {
15072 		dst_reg->u32_min_value <<= umin_val;
15073 		dst_reg->u32_max_value <<= umax_val;
15074 	}
15075 }
15076 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15077 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15078 				 struct bpf_reg_state *src_reg)
15079 {
15080 	u32 umax_val = src_reg->u32_max_value;
15081 	u32 umin_val = src_reg->u32_min_value;
15082 	/* u32 alu operation will zext upper bits */
15083 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15084 
15085 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15086 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15087 	/* Not required but being careful mark reg64 bounds as unknown so
15088 	 * that we are forced to pick them up from tnum and zext later and
15089 	 * if some path skips this step we are still safe.
15090 	 */
15091 	__mark_reg64_unbounded(dst_reg);
15092 	__update_reg32_bounds(dst_reg);
15093 }
15094 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15095 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15096 				   u64 umin_val, u64 umax_val)
15097 {
15098 	/* Special case <<32 because it is a common compiler pattern to sign
15099 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15100 	 * positive we know this shift will also be positive so we can track
15101 	 * bounds correctly. Otherwise we lose all sign bit information except
15102 	 * what we can pick up from var_off. Perhaps we can generalize this
15103 	 * later to shifts of any length.
15104 	 */
15105 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15106 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15107 	else
15108 		dst_reg->smax_value = S64_MAX;
15109 
15110 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15111 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15112 	else
15113 		dst_reg->smin_value = S64_MIN;
15114 
15115 	/* If we might shift our top bit out, then we know nothing */
15116 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15117 		dst_reg->umin_value = 0;
15118 		dst_reg->umax_value = U64_MAX;
15119 	} else {
15120 		dst_reg->umin_value <<= umin_val;
15121 		dst_reg->umax_value <<= umax_val;
15122 	}
15123 }
15124 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15125 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15126 			       struct bpf_reg_state *src_reg)
15127 {
15128 	u64 umax_val = src_reg->umax_value;
15129 	u64 umin_val = src_reg->umin_value;
15130 
15131 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15132 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15133 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15134 
15135 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15136 	/* We may learn something more from the var_off */
15137 	__update_reg_bounds(dst_reg);
15138 }
15139 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15140 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15141 				 struct bpf_reg_state *src_reg)
15142 {
15143 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15144 	u32 umax_val = src_reg->u32_max_value;
15145 	u32 umin_val = src_reg->u32_min_value;
15146 
15147 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15148 	 * be negative, then either:
15149 	 * 1) src_reg might be zero, so the sign bit of the result is
15150 	 *    unknown, so we lose our signed bounds
15151 	 * 2) it's known negative, thus the unsigned bounds capture the
15152 	 *    signed bounds
15153 	 * 3) the signed bounds cross zero, so they tell us nothing
15154 	 *    about the result
15155 	 * If the value in dst_reg is known nonnegative, then again the
15156 	 * unsigned bounds capture the signed bounds.
15157 	 * Thus, in all cases it suffices to blow away our signed bounds
15158 	 * and rely on inferring new ones from the unsigned bounds and
15159 	 * var_off of the result.
15160 	 */
15161 	dst_reg->s32_min_value = S32_MIN;
15162 	dst_reg->s32_max_value = S32_MAX;
15163 
15164 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15165 	dst_reg->u32_min_value >>= umax_val;
15166 	dst_reg->u32_max_value >>= umin_val;
15167 
15168 	__mark_reg64_unbounded(dst_reg);
15169 	__update_reg32_bounds(dst_reg);
15170 }
15171 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15172 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15173 			       struct bpf_reg_state *src_reg)
15174 {
15175 	u64 umax_val = src_reg->umax_value;
15176 	u64 umin_val = src_reg->umin_value;
15177 
15178 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15179 	 * be negative, then either:
15180 	 * 1) src_reg might be zero, so the sign bit of the result is
15181 	 *    unknown, so we lose our signed bounds
15182 	 * 2) it's known negative, thus the unsigned bounds capture the
15183 	 *    signed bounds
15184 	 * 3) the signed bounds cross zero, so they tell us nothing
15185 	 *    about the result
15186 	 * If the value in dst_reg is known nonnegative, then again the
15187 	 * unsigned bounds capture the signed bounds.
15188 	 * Thus, in all cases it suffices to blow away our signed bounds
15189 	 * and rely on inferring new ones from the unsigned bounds and
15190 	 * var_off of the result.
15191 	 */
15192 	dst_reg->smin_value = S64_MIN;
15193 	dst_reg->smax_value = S64_MAX;
15194 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15195 	dst_reg->umin_value >>= umax_val;
15196 	dst_reg->umax_value >>= umin_val;
15197 
15198 	/* Its not easy to operate on alu32 bounds here because it depends
15199 	 * on bits being shifted in. Take easy way out and mark unbounded
15200 	 * so we can recalculate later from tnum.
15201 	 */
15202 	__mark_reg32_unbounded(dst_reg);
15203 	__update_reg_bounds(dst_reg);
15204 }
15205 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15206 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15207 				  struct bpf_reg_state *src_reg)
15208 {
15209 	u64 umin_val = src_reg->u32_min_value;
15210 
15211 	/* Upon reaching here, src_known is true and
15212 	 * umax_val is equal to umin_val.
15213 	 */
15214 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15215 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15216 
15217 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15218 
15219 	/* blow away the dst_reg umin_value/umax_value and rely on
15220 	 * dst_reg var_off to refine the result.
15221 	 */
15222 	dst_reg->u32_min_value = 0;
15223 	dst_reg->u32_max_value = U32_MAX;
15224 
15225 	__mark_reg64_unbounded(dst_reg);
15226 	__update_reg32_bounds(dst_reg);
15227 }
15228 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15229 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15230 				struct bpf_reg_state *src_reg)
15231 {
15232 	u64 umin_val = src_reg->umin_value;
15233 
15234 	/* Upon reaching here, src_known is true and umax_val is equal
15235 	 * to umin_val.
15236 	 */
15237 	dst_reg->smin_value >>= umin_val;
15238 	dst_reg->smax_value >>= umin_val;
15239 
15240 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15241 
15242 	/* blow away the dst_reg umin_value/umax_value and rely on
15243 	 * dst_reg var_off to refine the result.
15244 	 */
15245 	dst_reg->umin_value = 0;
15246 	dst_reg->umax_value = U64_MAX;
15247 
15248 	/* Its not easy to operate on alu32 bounds here because it depends
15249 	 * on bits being shifted in from upper 32-bits. Take easy way out
15250 	 * and mark unbounded so we can recalculate later from tnum.
15251 	 */
15252 	__mark_reg32_unbounded(dst_reg);
15253 	__update_reg_bounds(dst_reg);
15254 }
15255 
is_safe_to_compute_dst_reg_range(struct bpf_insn * insn,const struct bpf_reg_state * src_reg)15256 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15257 					     const struct bpf_reg_state *src_reg)
15258 {
15259 	bool src_is_const = false;
15260 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15261 
15262 	if (insn_bitness == 32) {
15263 		if (tnum_subreg_is_const(src_reg->var_off)
15264 		    && src_reg->s32_min_value == src_reg->s32_max_value
15265 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15266 			src_is_const = true;
15267 	} else {
15268 		if (tnum_is_const(src_reg->var_off)
15269 		    && src_reg->smin_value == src_reg->smax_value
15270 		    && src_reg->umin_value == src_reg->umax_value)
15271 			src_is_const = true;
15272 	}
15273 
15274 	switch (BPF_OP(insn->code)) {
15275 	case BPF_ADD:
15276 	case BPF_SUB:
15277 	case BPF_NEG:
15278 	case BPF_AND:
15279 	case BPF_XOR:
15280 	case BPF_OR:
15281 	case BPF_MUL:
15282 		return true;
15283 
15284 	/* Shift operators range is only computable if shift dimension operand
15285 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15286 	 * includes shifts by a negative number.
15287 	 */
15288 	case BPF_LSH:
15289 	case BPF_RSH:
15290 	case BPF_ARSH:
15291 		return (src_is_const && src_reg->umax_value < insn_bitness);
15292 	default:
15293 		return false;
15294 	}
15295 }
15296 
15297 /* WARNING: This function does calculations on 64-bit values, but the actual
15298  * execution may occur on 32-bit values. Therefore, things like bitshifts
15299  * need extra checks in the 32-bit case.
15300  */
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)15301 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15302 				      struct bpf_insn *insn,
15303 				      struct bpf_reg_state *dst_reg,
15304 				      struct bpf_reg_state src_reg)
15305 {
15306 	u8 opcode = BPF_OP(insn->code);
15307 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15308 	int ret;
15309 
15310 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15311 		__mark_reg_unknown(env, dst_reg);
15312 		return 0;
15313 	}
15314 
15315 	if (sanitize_needed(opcode)) {
15316 		ret = sanitize_val_alu(env, insn);
15317 		if (ret < 0)
15318 			return sanitize_err(env, insn, ret, NULL, NULL);
15319 	}
15320 
15321 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15322 	 * There are two classes of instructions: The first class we track both
15323 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15324 	 * greatest amount of precision when alu operations are mixed with jmp32
15325 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15326 	 * and BPF_OR. This is possible because these ops have fairly easy to
15327 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15328 	 * See alu32 verifier tests for examples. The second class of
15329 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15330 	 * with regards to tracking sign/unsigned bounds because the bits may
15331 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15332 	 * the reg unbounded in the subreg bound space and use the resulting
15333 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15334 	 */
15335 	switch (opcode) {
15336 	case BPF_ADD:
15337 		scalar32_min_max_add(dst_reg, &src_reg);
15338 		scalar_min_max_add(dst_reg, &src_reg);
15339 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15340 		break;
15341 	case BPF_SUB:
15342 		scalar32_min_max_sub(dst_reg, &src_reg);
15343 		scalar_min_max_sub(dst_reg, &src_reg);
15344 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15345 		break;
15346 	case BPF_NEG:
15347 		env->fake_reg[0] = *dst_reg;
15348 		__mark_reg_known(dst_reg, 0);
15349 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15350 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15351 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15352 		break;
15353 	case BPF_MUL:
15354 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15355 		scalar32_min_max_mul(dst_reg, &src_reg);
15356 		scalar_min_max_mul(dst_reg, &src_reg);
15357 		break;
15358 	case BPF_AND:
15359 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15360 		scalar32_min_max_and(dst_reg, &src_reg);
15361 		scalar_min_max_and(dst_reg, &src_reg);
15362 		break;
15363 	case BPF_OR:
15364 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15365 		scalar32_min_max_or(dst_reg, &src_reg);
15366 		scalar_min_max_or(dst_reg, &src_reg);
15367 		break;
15368 	case BPF_XOR:
15369 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15370 		scalar32_min_max_xor(dst_reg, &src_reg);
15371 		scalar_min_max_xor(dst_reg, &src_reg);
15372 		break;
15373 	case BPF_LSH:
15374 		if (alu32)
15375 			scalar32_min_max_lsh(dst_reg, &src_reg);
15376 		else
15377 			scalar_min_max_lsh(dst_reg, &src_reg);
15378 		break;
15379 	case BPF_RSH:
15380 		if (alu32)
15381 			scalar32_min_max_rsh(dst_reg, &src_reg);
15382 		else
15383 			scalar_min_max_rsh(dst_reg, &src_reg);
15384 		break;
15385 	case BPF_ARSH:
15386 		if (alu32)
15387 			scalar32_min_max_arsh(dst_reg, &src_reg);
15388 		else
15389 			scalar_min_max_arsh(dst_reg, &src_reg);
15390 		break;
15391 	default:
15392 		break;
15393 	}
15394 
15395 	/* ALU32 ops are zero extended into 64bit register */
15396 	if (alu32)
15397 		zext_32_to_64(dst_reg);
15398 	reg_bounds_sync(dst_reg);
15399 	return 0;
15400 }
15401 
15402 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15403  * and var_off.
15404  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)15405 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15406 				   struct bpf_insn *insn)
15407 {
15408 	struct bpf_verifier_state *vstate = env->cur_state;
15409 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15410 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15411 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15412 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15413 	u8 opcode = BPF_OP(insn->code);
15414 	int err;
15415 
15416 	dst_reg = &regs[insn->dst_reg];
15417 	src_reg = NULL;
15418 
15419 	if (dst_reg->type == PTR_TO_ARENA) {
15420 		struct bpf_insn_aux_data *aux = cur_aux(env);
15421 
15422 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15423 			/*
15424 			 * 32-bit operations zero upper bits automatically.
15425 			 * 64-bit operations need to be converted to 32.
15426 			 */
15427 			aux->needs_zext = true;
15428 
15429 		/* Any arithmetic operations are allowed on arena pointers */
15430 		return 0;
15431 	}
15432 
15433 	if (dst_reg->type != SCALAR_VALUE)
15434 		ptr_reg = dst_reg;
15435 
15436 	if (BPF_SRC(insn->code) == BPF_X) {
15437 		src_reg = &regs[insn->src_reg];
15438 		if (src_reg->type != SCALAR_VALUE) {
15439 			if (dst_reg->type != SCALAR_VALUE) {
15440 				/* Combining two pointers by any ALU op yields
15441 				 * an arbitrary scalar. Disallow all math except
15442 				 * pointer subtraction
15443 				 */
15444 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15445 					mark_reg_unknown(env, regs, insn->dst_reg);
15446 					return 0;
15447 				}
15448 				verbose(env, "R%d pointer %s pointer prohibited\n",
15449 					insn->dst_reg,
15450 					bpf_alu_string[opcode >> 4]);
15451 				return -EACCES;
15452 			} else {
15453 				/* scalar += pointer
15454 				 * This is legal, but we have to reverse our
15455 				 * src/dest handling in computing the range
15456 				 */
15457 				err = mark_chain_precision(env, insn->dst_reg);
15458 				if (err)
15459 					return err;
15460 				return adjust_ptr_min_max_vals(env, insn,
15461 							       src_reg, dst_reg);
15462 			}
15463 		} else if (ptr_reg) {
15464 			/* pointer += scalar */
15465 			err = mark_chain_precision(env, insn->src_reg);
15466 			if (err)
15467 				return err;
15468 			return adjust_ptr_min_max_vals(env, insn,
15469 						       dst_reg, src_reg);
15470 		} else if (dst_reg->precise) {
15471 			/* if dst_reg is precise, src_reg should be precise as well */
15472 			err = mark_chain_precision(env, insn->src_reg);
15473 			if (err)
15474 				return err;
15475 		}
15476 	} else {
15477 		/* Pretend the src is a reg with a known value, since we only
15478 		 * need to be able to read from this state.
15479 		 */
15480 		off_reg.type = SCALAR_VALUE;
15481 		__mark_reg_known(&off_reg, insn->imm);
15482 		src_reg = &off_reg;
15483 		if (ptr_reg) /* pointer += K */
15484 			return adjust_ptr_min_max_vals(env, insn,
15485 						       ptr_reg, src_reg);
15486 	}
15487 
15488 	/* Got here implies adding two SCALAR_VALUEs */
15489 	if (WARN_ON_ONCE(ptr_reg)) {
15490 		print_verifier_state(env, vstate, vstate->curframe, true);
15491 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15492 		return -EFAULT;
15493 	}
15494 	if (WARN_ON(!src_reg)) {
15495 		print_verifier_state(env, vstate, vstate->curframe, true);
15496 		verbose(env, "verifier internal error: no src_reg\n");
15497 		return -EFAULT;
15498 	}
15499 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15500 	if (err)
15501 		return err;
15502 	/*
15503 	 * Compilers can generate the code
15504 	 * r1 = r2
15505 	 * r1 += 0x1
15506 	 * if r2 < 1000 goto ...
15507 	 * use r1 in memory access
15508 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15509 	 * update r1 after 'if' condition.
15510 	 */
15511 	if (env->bpf_capable &&
15512 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15513 	    dst_reg->id && is_reg_const(src_reg, false)) {
15514 		u64 val = reg_const_value(src_reg, false);
15515 
15516 		if ((dst_reg->id & BPF_ADD_CONST) ||
15517 		    /* prevent overflow in sync_linked_regs() later */
15518 		    val > (u32)S32_MAX) {
15519 			/*
15520 			 * If the register already went through rX += val
15521 			 * we cannot accumulate another val into rx->off.
15522 			 */
15523 			dst_reg->off = 0;
15524 			dst_reg->id = 0;
15525 		} else {
15526 			dst_reg->id |= BPF_ADD_CONST;
15527 			dst_reg->off = val;
15528 		}
15529 	} else {
15530 		/*
15531 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15532 		 * incorrectly propagated into other registers by sync_linked_regs()
15533 		 */
15534 		dst_reg->id = 0;
15535 	}
15536 	return 0;
15537 }
15538 
15539 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)15540 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15541 {
15542 	struct bpf_reg_state *regs = cur_regs(env);
15543 	u8 opcode = BPF_OP(insn->code);
15544 	int err;
15545 
15546 	if (opcode == BPF_END || opcode == BPF_NEG) {
15547 		if (opcode == BPF_NEG) {
15548 			if (BPF_SRC(insn->code) != BPF_K ||
15549 			    insn->src_reg != BPF_REG_0 ||
15550 			    insn->off != 0 || insn->imm != 0) {
15551 				verbose(env, "BPF_NEG uses reserved fields\n");
15552 				return -EINVAL;
15553 			}
15554 		} else {
15555 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15556 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15557 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15558 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15559 				verbose(env, "BPF_END uses reserved fields\n");
15560 				return -EINVAL;
15561 			}
15562 		}
15563 
15564 		/* check src operand */
15565 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15566 		if (err)
15567 			return err;
15568 
15569 		if (is_pointer_value(env, insn->dst_reg)) {
15570 			verbose(env, "R%d pointer arithmetic prohibited\n",
15571 				insn->dst_reg);
15572 			return -EACCES;
15573 		}
15574 
15575 		/* check dest operand */
15576 		if (opcode == BPF_NEG) {
15577 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15578 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15579 							 &regs[insn->dst_reg],
15580 							 regs[insn->dst_reg]);
15581 		} else {
15582 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15583 		}
15584 		if (err)
15585 			return err;
15586 
15587 	} else if (opcode == BPF_MOV) {
15588 
15589 		if (BPF_SRC(insn->code) == BPF_X) {
15590 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15591 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15592 				    insn->imm) {
15593 					verbose(env, "BPF_MOV uses reserved fields\n");
15594 					return -EINVAL;
15595 				}
15596 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15597 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15598 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15599 					return -EINVAL;
15600 				}
15601 				if (!env->prog->aux->arena) {
15602 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15603 					return -EINVAL;
15604 				}
15605 			} else {
15606 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15607 				     insn->off != 32) || insn->imm) {
15608 					verbose(env, "BPF_MOV uses reserved fields\n");
15609 					return -EINVAL;
15610 				}
15611 			}
15612 
15613 			/* check src operand */
15614 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15615 			if (err)
15616 				return err;
15617 		} else {
15618 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15619 				verbose(env, "BPF_MOV uses reserved fields\n");
15620 				return -EINVAL;
15621 			}
15622 		}
15623 
15624 		/* check dest operand, mark as required later */
15625 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15626 		if (err)
15627 			return err;
15628 
15629 		if (BPF_SRC(insn->code) == BPF_X) {
15630 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15631 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15632 
15633 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15634 				if (insn->imm) {
15635 					/* off == BPF_ADDR_SPACE_CAST */
15636 					mark_reg_unknown(env, regs, insn->dst_reg);
15637 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15638 						dst_reg->type = PTR_TO_ARENA;
15639 						/* PTR_TO_ARENA is 32-bit */
15640 						dst_reg->subreg_def = env->insn_idx + 1;
15641 					}
15642 				} else if (insn->off == 0) {
15643 					/* case: R1 = R2
15644 					 * copy register state to dest reg
15645 					 */
15646 					assign_scalar_id_before_mov(env, src_reg);
15647 					copy_register_state(dst_reg, src_reg);
15648 					dst_reg->live |= REG_LIVE_WRITTEN;
15649 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15650 				} else {
15651 					/* case: R1 = (s8, s16 s32)R2 */
15652 					if (is_pointer_value(env, insn->src_reg)) {
15653 						verbose(env,
15654 							"R%d sign-extension part of pointer\n",
15655 							insn->src_reg);
15656 						return -EACCES;
15657 					} else if (src_reg->type == SCALAR_VALUE) {
15658 						bool no_sext;
15659 
15660 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15661 						if (no_sext)
15662 							assign_scalar_id_before_mov(env, src_reg);
15663 						copy_register_state(dst_reg, src_reg);
15664 						if (!no_sext)
15665 							dst_reg->id = 0;
15666 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15667 						dst_reg->live |= REG_LIVE_WRITTEN;
15668 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15669 					} else {
15670 						mark_reg_unknown(env, regs, insn->dst_reg);
15671 					}
15672 				}
15673 			} else {
15674 				/* R1 = (u32) R2 */
15675 				if (is_pointer_value(env, insn->src_reg)) {
15676 					verbose(env,
15677 						"R%d partial copy of pointer\n",
15678 						insn->src_reg);
15679 					return -EACCES;
15680 				} else if (src_reg->type == SCALAR_VALUE) {
15681 					if (insn->off == 0) {
15682 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15683 
15684 						if (is_src_reg_u32)
15685 							assign_scalar_id_before_mov(env, src_reg);
15686 						copy_register_state(dst_reg, src_reg);
15687 						/* Make sure ID is cleared if src_reg is not in u32
15688 						 * range otherwise dst_reg min/max could be incorrectly
15689 						 * propagated into src_reg by sync_linked_regs()
15690 						 */
15691 						if (!is_src_reg_u32)
15692 							dst_reg->id = 0;
15693 						dst_reg->live |= REG_LIVE_WRITTEN;
15694 						dst_reg->subreg_def = env->insn_idx + 1;
15695 					} else {
15696 						/* case: W1 = (s8, s16)W2 */
15697 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15698 
15699 						if (no_sext)
15700 							assign_scalar_id_before_mov(env, src_reg);
15701 						copy_register_state(dst_reg, src_reg);
15702 						if (!no_sext)
15703 							dst_reg->id = 0;
15704 						dst_reg->live |= REG_LIVE_WRITTEN;
15705 						dst_reg->subreg_def = env->insn_idx + 1;
15706 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15707 					}
15708 				} else {
15709 					mark_reg_unknown(env, regs,
15710 							 insn->dst_reg);
15711 				}
15712 				zext_32_to_64(dst_reg);
15713 				reg_bounds_sync(dst_reg);
15714 			}
15715 		} else {
15716 			/* case: R = imm
15717 			 * remember the value we stored into this reg
15718 			 */
15719 			/* clear any state __mark_reg_known doesn't set */
15720 			mark_reg_unknown(env, regs, insn->dst_reg);
15721 			regs[insn->dst_reg].type = SCALAR_VALUE;
15722 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15723 				__mark_reg_known(regs + insn->dst_reg,
15724 						 insn->imm);
15725 			} else {
15726 				__mark_reg_known(regs + insn->dst_reg,
15727 						 (u32)insn->imm);
15728 			}
15729 		}
15730 
15731 	} else if (opcode > BPF_END) {
15732 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15733 		return -EINVAL;
15734 
15735 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15736 
15737 		if (BPF_SRC(insn->code) == BPF_X) {
15738 			if (insn->imm != 0 || insn->off > 1 ||
15739 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15740 				verbose(env, "BPF_ALU uses reserved fields\n");
15741 				return -EINVAL;
15742 			}
15743 			/* check src1 operand */
15744 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15745 			if (err)
15746 				return err;
15747 		} else {
15748 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
15749 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15750 				verbose(env, "BPF_ALU uses reserved fields\n");
15751 				return -EINVAL;
15752 			}
15753 		}
15754 
15755 		/* check src2 operand */
15756 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15757 		if (err)
15758 			return err;
15759 
15760 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15761 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15762 			verbose(env, "div by zero\n");
15763 			return -EINVAL;
15764 		}
15765 
15766 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15767 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15768 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15769 
15770 			if (insn->imm < 0 || insn->imm >= size) {
15771 				verbose(env, "invalid shift %d\n", insn->imm);
15772 				return -EINVAL;
15773 			}
15774 		}
15775 
15776 		/* check dest operand */
15777 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15778 		err = err ?: adjust_reg_min_max_vals(env, insn);
15779 		if (err)
15780 			return err;
15781 	}
15782 
15783 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15784 }
15785 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)15786 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15787 				   struct bpf_reg_state *dst_reg,
15788 				   enum bpf_reg_type type,
15789 				   bool range_right_open)
15790 {
15791 	struct bpf_func_state *state;
15792 	struct bpf_reg_state *reg;
15793 	int new_range;
15794 
15795 	if (dst_reg->off < 0 ||
15796 	    (dst_reg->off == 0 && range_right_open))
15797 		/* This doesn't give us any range */
15798 		return;
15799 
15800 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15801 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15802 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15803 		 * than pkt_end, but that's because it's also less than pkt.
15804 		 */
15805 		return;
15806 
15807 	new_range = dst_reg->off;
15808 	if (range_right_open)
15809 		new_range++;
15810 
15811 	/* Examples for register markings:
15812 	 *
15813 	 * pkt_data in dst register:
15814 	 *
15815 	 *   r2 = r3;
15816 	 *   r2 += 8;
15817 	 *   if (r2 > pkt_end) goto <handle exception>
15818 	 *   <access okay>
15819 	 *
15820 	 *   r2 = r3;
15821 	 *   r2 += 8;
15822 	 *   if (r2 < pkt_end) goto <access okay>
15823 	 *   <handle exception>
15824 	 *
15825 	 *   Where:
15826 	 *     r2 == dst_reg, pkt_end == src_reg
15827 	 *     r2=pkt(id=n,off=8,r=0)
15828 	 *     r3=pkt(id=n,off=0,r=0)
15829 	 *
15830 	 * pkt_data in src register:
15831 	 *
15832 	 *   r2 = r3;
15833 	 *   r2 += 8;
15834 	 *   if (pkt_end >= r2) goto <access okay>
15835 	 *   <handle exception>
15836 	 *
15837 	 *   r2 = r3;
15838 	 *   r2 += 8;
15839 	 *   if (pkt_end <= r2) goto <handle exception>
15840 	 *   <access okay>
15841 	 *
15842 	 *   Where:
15843 	 *     pkt_end == dst_reg, r2 == src_reg
15844 	 *     r2=pkt(id=n,off=8,r=0)
15845 	 *     r3=pkt(id=n,off=0,r=0)
15846 	 *
15847 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15848 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15849 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15850 	 * the check.
15851 	 */
15852 
15853 	/* If our ids match, then we must have the same max_value.  And we
15854 	 * don't care about the other reg's fixed offset, since if it's too big
15855 	 * the range won't allow anything.
15856 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15857 	 */
15858 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15859 		if (reg->type == type && reg->id == dst_reg->id)
15860 			/* keep the maximum range already checked */
15861 			reg->range = max(reg->range, new_range);
15862 	}));
15863 }
15864 
15865 /*
15866  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15867  */
is_scalar_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)15868 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15869 				  u8 opcode, bool is_jmp32)
15870 {
15871 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15872 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15873 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15874 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15875 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15876 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15877 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15878 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15879 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15880 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15881 
15882 	switch (opcode) {
15883 	case BPF_JEQ:
15884 		/* constants, umin/umax and smin/smax checks would be
15885 		 * redundant in this case because they all should match
15886 		 */
15887 		if (tnum_is_const(t1) && tnum_is_const(t2))
15888 			return t1.value == t2.value;
15889 		/* non-overlapping ranges */
15890 		if (umin1 > umax2 || umax1 < umin2)
15891 			return 0;
15892 		if (smin1 > smax2 || smax1 < smin2)
15893 			return 0;
15894 		if (!is_jmp32) {
15895 			/* if 64-bit ranges are inconclusive, see if we can
15896 			 * utilize 32-bit subrange knowledge to eliminate
15897 			 * branches that can't be taken a priori
15898 			 */
15899 			if (reg1->u32_min_value > reg2->u32_max_value ||
15900 			    reg1->u32_max_value < reg2->u32_min_value)
15901 				return 0;
15902 			if (reg1->s32_min_value > reg2->s32_max_value ||
15903 			    reg1->s32_max_value < reg2->s32_min_value)
15904 				return 0;
15905 		}
15906 		break;
15907 	case BPF_JNE:
15908 		/* constants, umin/umax and smin/smax checks would be
15909 		 * redundant in this case because they all should match
15910 		 */
15911 		if (tnum_is_const(t1) && tnum_is_const(t2))
15912 			return t1.value != t2.value;
15913 		/* non-overlapping ranges */
15914 		if (umin1 > umax2 || umax1 < umin2)
15915 			return 1;
15916 		if (smin1 > smax2 || smax1 < smin2)
15917 			return 1;
15918 		if (!is_jmp32) {
15919 			/* if 64-bit ranges are inconclusive, see if we can
15920 			 * utilize 32-bit subrange knowledge to eliminate
15921 			 * branches that can't be taken a priori
15922 			 */
15923 			if (reg1->u32_min_value > reg2->u32_max_value ||
15924 			    reg1->u32_max_value < reg2->u32_min_value)
15925 				return 1;
15926 			if (reg1->s32_min_value > reg2->s32_max_value ||
15927 			    reg1->s32_max_value < reg2->s32_min_value)
15928 				return 1;
15929 		}
15930 		break;
15931 	case BPF_JSET:
15932 		if (!is_reg_const(reg2, is_jmp32)) {
15933 			swap(reg1, reg2);
15934 			swap(t1, t2);
15935 		}
15936 		if (!is_reg_const(reg2, is_jmp32))
15937 			return -1;
15938 		if ((~t1.mask & t1.value) & t2.value)
15939 			return 1;
15940 		if (!((t1.mask | t1.value) & t2.value))
15941 			return 0;
15942 		break;
15943 	case BPF_JGT:
15944 		if (umin1 > umax2)
15945 			return 1;
15946 		else if (umax1 <= umin2)
15947 			return 0;
15948 		break;
15949 	case BPF_JSGT:
15950 		if (smin1 > smax2)
15951 			return 1;
15952 		else if (smax1 <= smin2)
15953 			return 0;
15954 		break;
15955 	case BPF_JLT:
15956 		if (umax1 < umin2)
15957 			return 1;
15958 		else if (umin1 >= umax2)
15959 			return 0;
15960 		break;
15961 	case BPF_JSLT:
15962 		if (smax1 < smin2)
15963 			return 1;
15964 		else if (smin1 >= smax2)
15965 			return 0;
15966 		break;
15967 	case BPF_JGE:
15968 		if (umin1 >= umax2)
15969 			return 1;
15970 		else if (umax1 < umin2)
15971 			return 0;
15972 		break;
15973 	case BPF_JSGE:
15974 		if (smin1 >= smax2)
15975 			return 1;
15976 		else if (smax1 < smin2)
15977 			return 0;
15978 		break;
15979 	case BPF_JLE:
15980 		if (umax1 <= umin2)
15981 			return 1;
15982 		else if (umin1 > umax2)
15983 			return 0;
15984 		break;
15985 	case BPF_JSLE:
15986 		if (smax1 <= smin2)
15987 			return 1;
15988 		else if (smin1 > smax2)
15989 			return 0;
15990 		break;
15991 	}
15992 
15993 	return -1;
15994 }
15995 
flip_opcode(u32 opcode)15996 static int flip_opcode(u32 opcode)
15997 {
15998 	/* How can we transform "a <op> b" into "b <op> a"? */
15999 	static const u8 opcode_flip[16] = {
16000 		/* these stay the same */
16001 		[BPF_JEQ  >> 4] = BPF_JEQ,
16002 		[BPF_JNE  >> 4] = BPF_JNE,
16003 		[BPF_JSET >> 4] = BPF_JSET,
16004 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16005 		[BPF_JGE  >> 4] = BPF_JLE,
16006 		[BPF_JGT  >> 4] = BPF_JLT,
16007 		[BPF_JLE  >> 4] = BPF_JGE,
16008 		[BPF_JLT  >> 4] = BPF_JGT,
16009 		[BPF_JSGE >> 4] = BPF_JSLE,
16010 		[BPF_JSGT >> 4] = BPF_JSLT,
16011 		[BPF_JSLE >> 4] = BPF_JSGE,
16012 		[BPF_JSLT >> 4] = BPF_JSGT
16013 	};
16014 	return opcode_flip[opcode >> 4];
16015 }
16016 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)16017 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16018 				   struct bpf_reg_state *src_reg,
16019 				   u8 opcode)
16020 {
16021 	struct bpf_reg_state *pkt;
16022 
16023 	if (src_reg->type == PTR_TO_PACKET_END) {
16024 		pkt = dst_reg;
16025 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16026 		pkt = src_reg;
16027 		opcode = flip_opcode(opcode);
16028 	} else {
16029 		return -1;
16030 	}
16031 
16032 	if (pkt->range >= 0)
16033 		return -1;
16034 
16035 	switch (opcode) {
16036 	case BPF_JLE:
16037 		/* pkt <= pkt_end */
16038 		fallthrough;
16039 	case BPF_JGT:
16040 		/* pkt > pkt_end */
16041 		if (pkt->range == BEYOND_PKT_END)
16042 			/* pkt has at last one extra byte beyond pkt_end */
16043 			return opcode == BPF_JGT;
16044 		break;
16045 	case BPF_JLT:
16046 		/* pkt < pkt_end */
16047 		fallthrough;
16048 	case BPF_JGE:
16049 		/* pkt >= pkt_end */
16050 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16051 			return opcode == BPF_JGE;
16052 		break;
16053 	}
16054 	return -1;
16055 }
16056 
16057 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16058  * and return:
16059  *  1 - branch will be taken and "goto target" will be executed
16060  *  0 - branch will not be taken and fall-through to next insn
16061  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16062  *      range [0,10]
16063  */
is_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16064 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16065 			   u8 opcode, bool is_jmp32)
16066 {
16067 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16068 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16069 
16070 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16071 		u64 val;
16072 
16073 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16074 		if (!is_reg_const(reg2, is_jmp32)) {
16075 			opcode = flip_opcode(opcode);
16076 			swap(reg1, reg2);
16077 		}
16078 		/* and ensure that reg2 is a constant */
16079 		if (!is_reg_const(reg2, is_jmp32))
16080 			return -1;
16081 
16082 		if (!reg_not_null(reg1))
16083 			return -1;
16084 
16085 		/* If pointer is valid tests against zero will fail so we can
16086 		 * use this to direct branch taken.
16087 		 */
16088 		val = reg_const_value(reg2, is_jmp32);
16089 		if (val != 0)
16090 			return -1;
16091 
16092 		switch (opcode) {
16093 		case BPF_JEQ:
16094 			return 0;
16095 		case BPF_JNE:
16096 			return 1;
16097 		default:
16098 			return -1;
16099 		}
16100 	}
16101 
16102 	/* now deal with two scalars, but not necessarily constants */
16103 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16104 }
16105 
16106 /* Opcode that corresponds to a *false* branch condition.
16107  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16108  */
rev_opcode(u8 opcode)16109 static u8 rev_opcode(u8 opcode)
16110 {
16111 	switch (opcode) {
16112 	case BPF_JEQ:		return BPF_JNE;
16113 	case BPF_JNE:		return BPF_JEQ;
16114 	/* JSET doesn't have it's reverse opcode in BPF, so add
16115 	 * BPF_X flag to denote the reverse of that operation
16116 	 */
16117 	case BPF_JSET:		return BPF_JSET | BPF_X;
16118 	case BPF_JSET | BPF_X:	return BPF_JSET;
16119 	case BPF_JGE:		return BPF_JLT;
16120 	case BPF_JGT:		return BPF_JLE;
16121 	case BPF_JLE:		return BPF_JGT;
16122 	case BPF_JLT:		return BPF_JGE;
16123 	case BPF_JSGE:		return BPF_JSLT;
16124 	case BPF_JSGT:		return BPF_JSLE;
16125 	case BPF_JSLE:		return BPF_JSGT;
16126 	case BPF_JSLT:		return BPF_JSGE;
16127 	default:		return 0;
16128 	}
16129 }
16130 
16131 /* 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)16132 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16133 				u8 opcode, bool is_jmp32)
16134 {
16135 	struct tnum t;
16136 	u64 val;
16137 
16138 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16139 	switch (opcode) {
16140 	case BPF_JGE:
16141 	case BPF_JGT:
16142 	case BPF_JSGE:
16143 	case BPF_JSGT:
16144 		opcode = flip_opcode(opcode);
16145 		swap(reg1, reg2);
16146 		break;
16147 	default:
16148 		break;
16149 	}
16150 
16151 	switch (opcode) {
16152 	case BPF_JEQ:
16153 		if (is_jmp32) {
16154 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16155 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16156 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16157 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16158 			reg2->u32_min_value = reg1->u32_min_value;
16159 			reg2->u32_max_value = reg1->u32_max_value;
16160 			reg2->s32_min_value = reg1->s32_min_value;
16161 			reg2->s32_max_value = reg1->s32_max_value;
16162 
16163 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16164 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16165 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16166 		} else {
16167 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16168 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16169 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16170 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16171 			reg2->umin_value = reg1->umin_value;
16172 			reg2->umax_value = reg1->umax_value;
16173 			reg2->smin_value = reg1->smin_value;
16174 			reg2->smax_value = reg1->smax_value;
16175 
16176 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16177 			reg2->var_off = reg1->var_off;
16178 		}
16179 		break;
16180 	case BPF_JNE:
16181 		if (!is_reg_const(reg2, is_jmp32))
16182 			swap(reg1, reg2);
16183 		if (!is_reg_const(reg2, is_jmp32))
16184 			break;
16185 
16186 		/* try to recompute the bound of reg1 if reg2 is a const and
16187 		 * is exactly the edge of reg1.
16188 		 */
16189 		val = reg_const_value(reg2, is_jmp32);
16190 		if (is_jmp32) {
16191 			/* u32_min_value is not equal to 0xffffffff at this point,
16192 			 * because otherwise u32_max_value is 0xffffffff as well,
16193 			 * in such a case both reg1 and reg2 would be constants,
16194 			 * jump would be predicted and reg_set_min_max() won't
16195 			 * be called.
16196 			 *
16197 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16198 			 * below.
16199 			 */
16200 			if (reg1->u32_min_value == (u32)val)
16201 				reg1->u32_min_value++;
16202 			if (reg1->u32_max_value == (u32)val)
16203 				reg1->u32_max_value--;
16204 			if (reg1->s32_min_value == (s32)val)
16205 				reg1->s32_min_value++;
16206 			if (reg1->s32_max_value == (s32)val)
16207 				reg1->s32_max_value--;
16208 		} else {
16209 			if (reg1->umin_value == (u64)val)
16210 				reg1->umin_value++;
16211 			if (reg1->umax_value == (u64)val)
16212 				reg1->umax_value--;
16213 			if (reg1->smin_value == (s64)val)
16214 				reg1->smin_value++;
16215 			if (reg1->smax_value == (s64)val)
16216 				reg1->smax_value--;
16217 		}
16218 		break;
16219 	case BPF_JSET:
16220 		if (!is_reg_const(reg2, is_jmp32))
16221 			swap(reg1, reg2);
16222 		if (!is_reg_const(reg2, is_jmp32))
16223 			break;
16224 		val = reg_const_value(reg2, is_jmp32);
16225 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16226 		 * requires single bit to learn something useful. E.g., if we
16227 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16228 		 * are actually set? We can learn something definite only if
16229 		 * it's a single-bit value to begin with.
16230 		 *
16231 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16232 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16233 		 * bit 1 is set, which we can readily use in adjustments.
16234 		 */
16235 		if (!is_power_of_2(val))
16236 			break;
16237 		if (is_jmp32) {
16238 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16239 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16240 		} else {
16241 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16242 		}
16243 		break;
16244 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16245 		if (!is_reg_const(reg2, is_jmp32))
16246 			swap(reg1, reg2);
16247 		if (!is_reg_const(reg2, is_jmp32))
16248 			break;
16249 		val = reg_const_value(reg2, is_jmp32);
16250 		/* Forget the ranges before narrowing tnums, to avoid invariant
16251 		 * violations if we're on a dead branch.
16252 		 */
16253 		__mark_reg_unbounded(reg1);
16254 		if (is_jmp32) {
16255 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16256 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16257 		} else {
16258 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16259 		}
16260 		break;
16261 	case BPF_JLE:
16262 		if (is_jmp32) {
16263 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16264 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16265 		} else {
16266 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16267 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16268 		}
16269 		break;
16270 	case BPF_JLT:
16271 		if (is_jmp32) {
16272 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16273 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16274 		} else {
16275 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16276 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16277 		}
16278 		break;
16279 	case BPF_JSLE:
16280 		if (is_jmp32) {
16281 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16282 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16283 		} else {
16284 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16285 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16286 		}
16287 		break;
16288 	case BPF_JSLT:
16289 		if (is_jmp32) {
16290 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16291 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16292 		} else {
16293 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16294 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16295 		}
16296 		break;
16297 	default:
16298 		return;
16299 	}
16300 }
16301 
16302 /* Adjusts the register min/max values in the case that the dst_reg and
16303  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16304  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16305  * Technically we can do similar adjustments for pointers to the same object,
16306  * but we don't support that right now.
16307  */
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)16308 static int reg_set_min_max(struct bpf_verifier_env *env,
16309 			   struct bpf_reg_state *true_reg1,
16310 			   struct bpf_reg_state *true_reg2,
16311 			   struct bpf_reg_state *false_reg1,
16312 			   struct bpf_reg_state *false_reg2,
16313 			   u8 opcode, bool is_jmp32)
16314 {
16315 	int err;
16316 
16317 	/* If either register is a pointer, we can't learn anything about its
16318 	 * variable offset from the compare (unless they were a pointer into
16319 	 * the same object, but we don't bother with that).
16320 	 */
16321 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16322 		return 0;
16323 
16324 	/* fallthrough (FALSE) branch */
16325 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16326 	reg_bounds_sync(false_reg1);
16327 	reg_bounds_sync(false_reg2);
16328 
16329 	/* jump (TRUE) branch */
16330 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16331 	reg_bounds_sync(true_reg1);
16332 	reg_bounds_sync(true_reg2);
16333 
16334 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16335 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16336 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16337 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16338 	return err;
16339 }
16340 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)16341 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16342 				 struct bpf_reg_state *reg, u32 id,
16343 				 bool is_null)
16344 {
16345 	if (type_may_be_null(reg->type) && reg->id == id &&
16346 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16347 		/* Old offset (both fixed and variable parts) should have been
16348 		 * known-zero, because we don't allow pointer arithmetic on
16349 		 * pointers that might be NULL. If we see this happening, don't
16350 		 * convert the register.
16351 		 *
16352 		 * But in some cases, some helpers that return local kptrs
16353 		 * advance offset for the returned pointer. In those cases, it
16354 		 * is fine to expect to see reg->off.
16355 		 */
16356 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16357 			return;
16358 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16359 		    WARN_ON_ONCE(reg->off))
16360 			return;
16361 
16362 		if (is_null) {
16363 			reg->type = SCALAR_VALUE;
16364 			/* We don't need id and ref_obj_id from this point
16365 			 * onwards anymore, thus we should better reset it,
16366 			 * so that state pruning has chances to take effect.
16367 			 */
16368 			reg->id = 0;
16369 			reg->ref_obj_id = 0;
16370 
16371 			return;
16372 		}
16373 
16374 		mark_ptr_not_null_reg(reg);
16375 
16376 		if (!reg_may_point_to_spin_lock(reg)) {
16377 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16378 			 * in release_reference().
16379 			 *
16380 			 * reg->id is still used by spin_lock ptr. Other
16381 			 * than spin_lock ptr type, reg->id can be reset.
16382 			 */
16383 			reg->id = 0;
16384 		}
16385 	}
16386 }
16387 
16388 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16389  * be folded together at some point.
16390  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)16391 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16392 				  bool is_null)
16393 {
16394 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16395 	struct bpf_reg_state *regs = state->regs, *reg;
16396 	u32 ref_obj_id = regs[regno].ref_obj_id;
16397 	u32 id = regs[regno].id;
16398 
16399 	if (ref_obj_id && ref_obj_id == id && is_null)
16400 		/* regs[regno] is in the " == NULL" branch.
16401 		 * No one could have freed the reference state before
16402 		 * doing the NULL check.
16403 		 */
16404 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16405 
16406 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16407 		mark_ptr_or_null_reg(state, reg, id, is_null);
16408 	}));
16409 }
16410 
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)16411 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16412 				   struct bpf_reg_state *dst_reg,
16413 				   struct bpf_reg_state *src_reg,
16414 				   struct bpf_verifier_state *this_branch,
16415 				   struct bpf_verifier_state *other_branch)
16416 {
16417 	if (BPF_SRC(insn->code) != BPF_X)
16418 		return false;
16419 
16420 	/* Pointers are always 64-bit. */
16421 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16422 		return false;
16423 
16424 	switch (BPF_OP(insn->code)) {
16425 	case BPF_JGT:
16426 		if ((dst_reg->type == PTR_TO_PACKET &&
16427 		     src_reg->type == PTR_TO_PACKET_END) ||
16428 		    (dst_reg->type == PTR_TO_PACKET_META &&
16429 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16430 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16431 			find_good_pkt_pointers(this_branch, dst_reg,
16432 					       dst_reg->type, false);
16433 			mark_pkt_end(other_branch, insn->dst_reg, true);
16434 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16435 			    src_reg->type == PTR_TO_PACKET) ||
16436 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16437 			    src_reg->type == PTR_TO_PACKET_META)) {
16438 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16439 			find_good_pkt_pointers(other_branch, src_reg,
16440 					       src_reg->type, true);
16441 			mark_pkt_end(this_branch, insn->src_reg, false);
16442 		} else {
16443 			return false;
16444 		}
16445 		break;
16446 	case BPF_JLT:
16447 		if ((dst_reg->type == PTR_TO_PACKET &&
16448 		     src_reg->type == PTR_TO_PACKET_END) ||
16449 		    (dst_reg->type == PTR_TO_PACKET_META &&
16450 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16451 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16452 			find_good_pkt_pointers(other_branch, dst_reg,
16453 					       dst_reg->type, true);
16454 			mark_pkt_end(this_branch, insn->dst_reg, false);
16455 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16456 			    src_reg->type == PTR_TO_PACKET) ||
16457 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16458 			    src_reg->type == PTR_TO_PACKET_META)) {
16459 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16460 			find_good_pkt_pointers(this_branch, src_reg,
16461 					       src_reg->type, false);
16462 			mark_pkt_end(other_branch, insn->src_reg, true);
16463 		} else {
16464 			return false;
16465 		}
16466 		break;
16467 	case BPF_JGE:
16468 		if ((dst_reg->type == PTR_TO_PACKET &&
16469 		     src_reg->type == PTR_TO_PACKET_END) ||
16470 		    (dst_reg->type == PTR_TO_PACKET_META &&
16471 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16472 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16473 			find_good_pkt_pointers(this_branch, dst_reg,
16474 					       dst_reg->type, true);
16475 			mark_pkt_end(other_branch, insn->dst_reg, false);
16476 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16477 			    src_reg->type == PTR_TO_PACKET) ||
16478 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16479 			    src_reg->type == PTR_TO_PACKET_META)) {
16480 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16481 			find_good_pkt_pointers(other_branch, src_reg,
16482 					       src_reg->type, false);
16483 			mark_pkt_end(this_branch, insn->src_reg, true);
16484 		} else {
16485 			return false;
16486 		}
16487 		break;
16488 	case BPF_JLE:
16489 		if ((dst_reg->type == PTR_TO_PACKET &&
16490 		     src_reg->type == PTR_TO_PACKET_END) ||
16491 		    (dst_reg->type == PTR_TO_PACKET_META &&
16492 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16493 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16494 			find_good_pkt_pointers(other_branch, dst_reg,
16495 					       dst_reg->type, false);
16496 			mark_pkt_end(this_branch, insn->dst_reg, true);
16497 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16498 			    src_reg->type == PTR_TO_PACKET) ||
16499 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16500 			    src_reg->type == PTR_TO_PACKET_META)) {
16501 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16502 			find_good_pkt_pointers(this_branch, src_reg,
16503 					       src_reg->type, true);
16504 			mark_pkt_end(other_branch, insn->src_reg, false);
16505 		} else {
16506 			return false;
16507 		}
16508 		break;
16509 	default:
16510 		return false;
16511 	}
16512 
16513 	return true;
16514 }
16515 
__collect_linked_regs(struct linked_regs * reg_set,struct bpf_reg_state * reg,u32 id,u32 frameno,u32 spi_or_reg,bool is_reg)16516 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16517 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16518 {
16519 	struct linked_reg *e;
16520 
16521 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16522 		return;
16523 
16524 	e = linked_regs_push(reg_set);
16525 	if (e) {
16526 		e->frameno = frameno;
16527 		e->is_reg = is_reg;
16528 		e->regno = spi_or_reg;
16529 	} else {
16530 		reg->id = 0;
16531 	}
16532 }
16533 
16534 /* For all R being scalar registers or spilled scalar registers
16535  * in verifier state, save R in linked_regs if R->id == id.
16536  * If there are too many Rs sharing same id, reset id for leftover Rs.
16537  */
collect_linked_regs(struct bpf_verifier_state * vstate,u32 id,struct linked_regs * linked_regs)16538 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16539 				struct linked_regs *linked_regs)
16540 {
16541 	struct bpf_func_state *func;
16542 	struct bpf_reg_state *reg;
16543 	int i, j;
16544 
16545 	id = id & ~BPF_ADD_CONST;
16546 	for (i = vstate->curframe; i >= 0; i--) {
16547 		func = vstate->frame[i];
16548 		for (j = 0; j < BPF_REG_FP; j++) {
16549 			reg = &func->regs[j];
16550 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16551 		}
16552 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16553 			if (!is_spilled_reg(&func->stack[j]))
16554 				continue;
16555 			reg = &func->stack[j].spilled_ptr;
16556 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16557 		}
16558 	}
16559 }
16560 
16561 /* For all R in linked_regs, copy known_reg range into R
16562  * if R->id == known_reg->id.
16563  */
sync_linked_regs(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg,struct linked_regs * linked_regs)16564 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16565 			     struct linked_regs *linked_regs)
16566 {
16567 	struct bpf_reg_state fake_reg;
16568 	struct bpf_reg_state *reg;
16569 	struct linked_reg *e;
16570 	int i;
16571 
16572 	for (i = 0; i < linked_regs->cnt; ++i) {
16573 		e = &linked_regs->entries[i];
16574 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16575 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16576 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16577 			continue;
16578 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16579 			continue;
16580 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16581 		    reg->off == known_reg->off) {
16582 			s32 saved_subreg_def = reg->subreg_def;
16583 
16584 			copy_register_state(reg, known_reg);
16585 			reg->subreg_def = saved_subreg_def;
16586 		} else {
16587 			s32 saved_subreg_def = reg->subreg_def;
16588 			s32 saved_off = reg->off;
16589 
16590 			fake_reg.type = SCALAR_VALUE;
16591 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16592 
16593 			/* reg = known_reg; reg += delta */
16594 			copy_register_state(reg, known_reg);
16595 			/*
16596 			 * Must preserve off, id and add_const flag,
16597 			 * otherwise another sync_linked_regs() will be incorrect.
16598 			 */
16599 			reg->off = saved_off;
16600 			reg->subreg_def = saved_subreg_def;
16601 
16602 			scalar32_min_max_add(reg, &fake_reg);
16603 			scalar_min_max_add(reg, &fake_reg);
16604 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16605 		}
16606 	}
16607 }
16608 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)16609 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16610 			     struct bpf_insn *insn, int *insn_idx)
16611 {
16612 	struct bpf_verifier_state *this_branch = env->cur_state;
16613 	struct bpf_verifier_state *other_branch;
16614 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16615 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16616 	struct bpf_reg_state *eq_branch_regs;
16617 	struct linked_regs linked_regs = {};
16618 	u8 opcode = BPF_OP(insn->code);
16619 	int insn_flags = 0;
16620 	bool is_jmp32;
16621 	int pred = -1;
16622 	int err;
16623 
16624 	/* Only conditional jumps are expected to reach here. */
16625 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16626 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16627 		return -EINVAL;
16628 	}
16629 
16630 	if (opcode == BPF_JCOND) {
16631 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16632 		int idx = *insn_idx;
16633 
16634 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16635 		    insn->src_reg != BPF_MAY_GOTO ||
16636 		    insn->dst_reg || insn->imm) {
16637 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16638 			return -EINVAL;
16639 		}
16640 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16641 
16642 		/* branch out 'fallthrough' insn as a new state to explore */
16643 		queued_st = push_stack(env, idx + 1, idx, false);
16644 		if (!queued_st)
16645 			return -ENOMEM;
16646 
16647 		queued_st->may_goto_depth++;
16648 		if (prev_st)
16649 			widen_imprecise_scalars(env, prev_st, queued_st);
16650 		*insn_idx += insn->off;
16651 		return 0;
16652 	}
16653 
16654 	/* check src2 operand */
16655 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16656 	if (err)
16657 		return err;
16658 
16659 	dst_reg = &regs[insn->dst_reg];
16660 	if (BPF_SRC(insn->code) == BPF_X) {
16661 		if (insn->imm != 0) {
16662 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16663 			return -EINVAL;
16664 		}
16665 
16666 		/* check src1 operand */
16667 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16668 		if (err)
16669 			return err;
16670 
16671 		src_reg = &regs[insn->src_reg];
16672 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16673 		    is_pointer_value(env, insn->src_reg)) {
16674 			verbose(env, "R%d pointer comparison prohibited\n",
16675 				insn->src_reg);
16676 			return -EACCES;
16677 		}
16678 
16679 		if (src_reg->type == PTR_TO_STACK)
16680 			insn_flags |= INSN_F_SRC_REG_STACK;
16681 		if (dst_reg->type == PTR_TO_STACK)
16682 			insn_flags |= INSN_F_DST_REG_STACK;
16683 	} else {
16684 		if (insn->src_reg != BPF_REG_0) {
16685 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16686 			return -EINVAL;
16687 		}
16688 		src_reg = &env->fake_reg[0];
16689 		memset(src_reg, 0, sizeof(*src_reg));
16690 		src_reg->type = SCALAR_VALUE;
16691 		__mark_reg_known(src_reg, insn->imm);
16692 
16693 		if (dst_reg->type == PTR_TO_STACK)
16694 			insn_flags |= INSN_F_DST_REG_STACK;
16695 	}
16696 
16697 	if (insn_flags) {
16698 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16699 		if (err)
16700 			return err;
16701 	}
16702 
16703 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16704 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16705 	if (pred >= 0) {
16706 		/* If we get here with a dst_reg pointer type it is because
16707 		 * above is_branch_taken() special cased the 0 comparison.
16708 		 */
16709 		if (!__is_pointer_value(false, dst_reg))
16710 			err = mark_chain_precision(env, insn->dst_reg);
16711 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16712 		    !__is_pointer_value(false, src_reg))
16713 			err = mark_chain_precision(env, insn->src_reg);
16714 		if (err)
16715 			return err;
16716 	}
16717 
16718 	if (pred == 1) {
16719 		/* Only follow the goto, ignore fall-through. If needed, push
16720 		 * the fall-through branch for simulation under speculative
16721 		 * execution.
16722 		 */
16723 		if (!env->bypass_spec_v1 &&
16724 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16725 					       *insn_idx))
16726 			return -EFAULT;
16727 		if (env->log.level & BPF_LOG_LEVEL)
16728 			print_insn_state(env, this_branch, this_branch->curframe);
16729 		*insn_idx += insn->off;
16730 		return 0;
16731 	} else if (pred == 0) {
16732 		/* Only follow the fall-through branch, since that's where the
16733 		 * program will go. If needed, push the goto branch for
16734 		 * simulation under speculative execution.
16735 		 */
16736 		if (!env->bypass_spec_v1 &&
16737 		    !sanitize_speculative_path(env, insn,
16738 					       *insn_idx + insn->off + 1,
16739 					       *insn_idx))
16740 			return -EFAULT;
16741 		if (env->log.level & BPF_LOG_LEVEL)
16742 			print_insn_state(env, this_branch, this_branch->curframe);
16743 		return 0;
16744 	}
16745 
16746 	/* Push scalar registers sharing same ID to jump history,
16747 	 * do this before creating 'other_branch', so that both
16748 	 * 'this_branch' and 'other_branch' share this history
16749 	 * if parent state is created.
16750 	 */
16751 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16752 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16753 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16754 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16755 	if (linked_regs.cnt > 1) {
16756 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16757 		if (err)
16758 			return err;
16759 	}
16760 
16761 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16762 				  false);
16763 	if (!other_branch)
16764 		return -EFAULT;
16765 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16766 
16767 	if (BPF_SRC(insn->code) == BPF_X) {
16768 		err = reg_set_min_max(env,
16769 				      &other_branch_regs[insn->dst_reg],
16770 				      &other_branch_regs[insn->src_reg],
16771 				      dst_reg, src_reg, opcode, is_jmp32);
16772 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16773 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16774 		 * so that these are two different memory locations. The
16775 		 * src_reg is not used beyond here in context of K.
16776 		 */
16777 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16778 		       sizeof(env->fake_reg[0]));
16779 		err = reg_set_min_max(env,
16780 				      &other_branch_regs[insn->dst_reg],
16781 				      &env->fake_reg[0],
16782 				      dst_reg, &env->fake_reg[1],
16783 				      opcode, is_jmp32);
16784 	}
16785 	if (err)
16786 		return err;
16787 
16788 	if (BPF_SRC(insn->code) == BPF_X &&
16789 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16790 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16791 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16792 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16793 	}
16794 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16795 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16796 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16797 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16798 	}
16799 
16800 	/* if one pointer register is compared to another pointer
16801 	 * register check if PTR_MAYBE_NULL could be lifted.
16802 	 * E.g. register A - maybe null
16803 	 *      register B - not null
16804 	 * for JNE A, B, ... - A is not null in the false branch;
16805 	 * for JEQ A, B, ... - A is not null in the true branch.
16806 	 *
16807 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16808 	 * not need to be null checked by the BPF program, i.e.,
16809 	 * could be null even without PTR_MAYBE_NULL marking, so
16810 	 * only propagate nullness when neither reg is that type.
16811 	 */
16812 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16813 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16814 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16815 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16816 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16817 		eq_branch_regs = NULL;
16818 		switch (opcode) {
16819 		case BPF_JEQ:
16820 			eq_branch_regs = other_branch_regs;
16821 			break;
16822 		case BPF_JNE:
16823 			eq_branch_regs = regs;
16824 			break;
16825 		default:
16826 			/* do nothing */
16827 			break;
16828 		}
16829 		if (eq_branch_regs) {
16830 			if (type_may_be_null(src_reg->type))
16831 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16832 			else
16833 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16834 		}
16835 	}
16836 
16837 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16838 	 * NOTE: these optimizations below are related with pointer comparison
16839 	 *       which will never be JMP32.
16840 	 */
16841 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16842 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16843 	    type_may_be_null(dst_reg->type)) {
16844 		/* Mark all identical registers in each branch as either
16845 		 * safe or unknown depending R == 0 or R != 0 conditional.
16846 		 */
16847 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16848 				      opcode == BPF_JNE);
16849 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16850 				      opcode == BPF_JEQ);
16851 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16852 					   this_branch, other_branch) &&
16853 		   is_pointer_value(env, insn->dst_reg)) {
16854 		verbose(env, "R%d pointer comparison prohibited\n",
16855 			insn->dst_reg);
16856 		return -EACCES;
16857 	}
16858 	if (env->log.level & BPF_LOG_LEVEL)
16859 		print_insn_state(env, this_branch, this_branch->curframe);
16860 	return 0;
16861 }
16862 
16863 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)16864 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16865 {
16866 	struct bpf_insn_aux_data *aux = cur_aux(env);
16867 	struct bpf_reg_state *regs = cur_regs(env);
16868 	struct bpf_reg_state *dst_reg;
16869 	struct bpf_map *map;
16870 	int err;
16871 
16872 	if (BPF_SIZE(insn->code) != BPF_DW) {
16873 		verbose(env, "invalid BPF_LD_IMM insn\n");
16874 		return -EINVAL;
16875 	}
16876 	if (insn->off != 0) {
16877 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16878 		return -EINVAL;
16879 	}
16880 
16881 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16882 	if (err)
16883 		return err;
16884 
16885 	dst_reg = &regs[insn->dst_reg];
16886 	if (insn->src_reg == 0) {
16887 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16888 
16889 		dst_reg->type = SCALAR_VALUE;
16890 		__mark_reg_known(&regs[insn->dst_reg], imm);
16891 		return 0;
16892 	}
16893 
16894 	/* All special src_reg cases are listed below. From this point onwards
16895 	 * we either succeed and assign a corresponding dst_reg->type after
16896 	 * zeroing the offset, or fail and reject the program.
16897 	 */
16898 	mark_reg_known_zero(env, regs, insn->dst_reg);
16899 
16900 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16901 		dst_reg->type = aux->btf_var.reg_type;
16902 		switch (base_type(dst_reg->type)) {
16903 		case PTR_TO_MEM:
16904 			dst_reg->mem_size = aux->btf_var.mem_size;
16905 			break;
16906 		case PTR_TO_BTF_ID:
16907 			dst_reg->btf = aux->btf_var.btf;
16908 			dst_reg->btf_id = aux->btf_var.btf_id;
16909 			break;
16910 		default:
16911 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16912 			return -EFAULT;
16913 		}
16914 		return 0;
16915 	}
16916 
16917 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16918 		struct bpf_prog_aux *aux = env->prog->aux;
16919 		u32 subprogno = find_subprog(env,
16920 					     env->insn_idx + insn->imm + 1);
16921 
16922 		if (!aux->func_info) {
16923 			verbose(env, "missing btf func_info\n");
16924 			return -EINVAL;
16925 		}
16926 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
16927 			verbose(env, "callback function not static\n");
16928 			return -EINVAL;
16929 		}
16930 
16931 		dst_reg->type = PTR_TO_FUNC;
16932 		dst_reg->subprogno = subprogno;
16933 		return 0;
16934 	}
16935 
16936 	map = env->used_maps[aux->map_index];
16937 	dst_reg->map_ptr = map;
16938 
16939 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
16940 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
16941 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
16942 			__mark_reg_unknown(env, dst_reg);
16943 			return 0;
16944 		}
16945 		dst_reg->type = PTR_TO_MAP_VALUE;
16946 		dst_reg->off = aux->map_off;
16947 		WARN_ON_ONCE(map->max_entries != 1);
16948 		/* We want reg->id to be same (0) as map_value is not distinct */
16949 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
16950 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
16951 		dst_reg->type = CONST_PTR_TO_MAP;
16952 	} else {
16953 		verifier_bug(env, "unexpected src reg value for ldimm64");
16954 		return -EFAULT;
16955 	}
16956 
16957 	return 0;
16958 }
16959 
may_access_skb(enum bpf_prog_type type)16960 static bool may_access_skb(enum bpf_prog_type type)
16961 {
16962 	switch (type) {
16963 	case BPF_PROG_TYPE_SOCKET_FILTER:
16964 	case BPF_PROG_TYPE_SCHED_CLS:
16965 	case BPF_PROG_TYPE_SCHED_ACT:
16966 		return true;
16967 	default:
16968 		return false;
16969 	}
16970 }
16971 
16972 /* verify safety of LD_ABS|LD_IND instructions:
16973  * - they can only appear in the programs where ctx == skb
16974  * - since they are wrappers of function calls, they scratch R1-R5 registers,
16975  *   preserve R6-R9, and store return value into R0
16976  *
16977  * Implicit input:
16978  *   ctx == skb == R6 == CTX
16979  *
16980  * Explicit input:
16981  *   SRC == any register
16982  *   IMM == 32-bit immediate
16983  *
16984  * Output:
16985  *   R0 - 8/16/32-bit skb data converted to cpu endianness
16986  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)16987 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
16988 {
16989 	struct bpf_reg_state *regs = cur_regs(env);
16990 	static const int ctx_reg = BPF_REG_6;
16991 	u8 mode = BPF_MODE(insn->code);
16992 	int i, err;
16993 
16994 	if (!may_access_skb(resolve_prog_type(env->prog))) {
16995 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
16996 		return -EINVAL;
16997 	}
16998 
16999 	if (!env->ops->gen_ld_abs) {
17000 		verifier_bug(env, "gen_ld_abs is null");
17001 		return -EFAULT;
17002 	}
17003 
17004 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17005 	    BPF_SIZE(insn->code) == BPF_DW ||
17006 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17007 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17008 		return -EINVAL;
17009 	}
17010 
17011 	/* check whether implicit source operand (register R6) is readable */
17012 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17013 	if (err)
17014 		return err;
17015 
17016 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17017 	 * gen_ld_abs() may terminate the program at runtime, leading to
17018 	 * reference leak.
17019 	 */
17020 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17021 	if (err)
17022 		return err;
17023 
17024 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17025 		verbose(env,
17026 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17027 		return -EINVAL;
17028 	}
17029 
17030 	if (mode == BPF_IND) {
17031 		/* check explicit source operand */
17032 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17033 		if (err)
17034 			return err;
17035 	}
17036 
17037 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17038 	if (err < 0)
17039 		return err;
17040 
17041 	/* reset caller saved regs to unreadable */
17042 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17043 		mark_reg_not_init(env, regs, caller_saved[i]);
17044 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17045 	}
17046 
17047 	/* mark destination R0 register as readable, since it contains
17048 	 * the value fetched from the packet.
17049 	 * Already marked as written above.
17050 	 */
17051 	mark_reg_unknown(env, regs, BPF_REG_0);
17052 	/* ld_abs load up to 32-bit skb data. */
17053 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17054 	return 0;
17055 }
17056 
check_return_code(struct bpf_verifier_env * env,int regno,const char * reg_name)17057 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17058 {
17059 	const char *exit_ctx = "At program exit";
17060 	struct tnum enforce_attach_type_range = tnum_unknown;
17061 	const struct bpf_prog *prog = env->prog;
17062 	struct bpf_reg_state *reg = reg_state(env, regno);
17063 	struct bpf_retval_range range = retval_range(0, 1);
17064 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17065 	int err;
17066 	struct bpf_func_state *frame = env->cur_state->frame[0];
17067 	const bool is_subprog = frame->subprogno;
17068 	bool return_32bit = false;
17069 	const struct btf_type *reg_type, *ret_type = NULL;
17070 
17071 	/* LSM and struct_ops func-ptr's return type could be "void" */
17072 	if (!is_subprog || frame->in_exception_callback_fn) {
17073 		switch (prog_type) {
17074 		case BPF_PROG_TYPE_LSM:
17075 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17076 				/* See below, can be 0 or 0-1 depending on hook. */
17077 				break;
17078 			if (!prog->aux->attach_func_proto->type)
17079 				return 0;
17080 			break;
17081 		case BPF_PROG_TYPE_STRUCT_OPS:
17082 			if (!prog->aux->attach_func_proto->type)
17083 				return 0;
17084 
17085 			if (frame->in_exception_callback_fn)
17086 				break;
17087 
17088 			/* Allow a struct_ops program to return a referenced kptr if it
17089 			 * matches the operator's return type and is in its unmodified
17090 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17091 			 */
17092 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17093 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17094 							prog->aux->attach_func_proto->type,
17095 							NULL);
17096 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17097 				return __check_ptr_off_reg(env, reg, regno, false);
17098 			break;
17099 		default:
17100 			break;
17101 		}
17102 	}
17103 
17104 	/* eBPF calling convention is such that R0 is used
17105 	 * to return the value from eBPF program.
17106 	 * Make sure that it's readable at this time
17107 	 * of bpf_exit, which means that program wrote
17108 	 * something into it earlier
17109 	 */
17110 	err = check_reg_arg(env, regno, SRC_OP);
17111 	if (err)
17112 		return err;
17113 
17114 	if (is_pointer_value(env, regno)) {
17115 		verbose(env, "R%d leaks addr as return value\n", regno);
17116 		return -EACCES;
17117 	}
17118 
17119 	if (frame->in_async_callback_fn) {
17120 		/* enforce return zero from async callbacks like timer */
17121 		exit_ctx = "At async callback return";
17122 		range = retval_range(0, 0);
17123 		goto enforce_retval;
17124 	}
17125 
17126 	if (is_subprog && !frame->in_exception_callback_fn) {
17127 		if (reg->type != SCALAR_VALUE) {
17128 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17129 				regno, reg_type_str(env, reg->type));
17130 			return -EINVAL;
17131 		}
17132 		return 0;
17133 	}
17134 
17135 	switch (prog_type) {
17136 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17137 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17138 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17139 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17140 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17141 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17142 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17143 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17144 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17145 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17146 			range = retval_range(1, 1);
17147 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17148 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17149 			range = retval_range(0, 3);
17150 		break;
17151 	case BPF_PROG_TYPE_CGROUP_SKB:
17152 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17153 			range = retval_range(0, 3);
17154 			enforce_attach_type_range = tnum_range(2, 3);
17155 		}
17156 		break;
17157 	case BPF_PROG_TYPE_CGROUP_SOCK:
17158 	case BPF_PROG_TYPE_SOCK_OPS:
17159 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17160 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17161 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17162 		break;
17163 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17164 		if (!env->prog->aux->attach_btf_id)
17165 			return 0;
17166 		range = retval_range(0, 0);
17167 		break;
17168 	case BPF_PROG_TYPE_TRACING:
17169 		switch (env->prog->expected_attach_type) {
17170 		case BPF_TRACE_FENTRY:
17171 		case BPF_TRACE_FEXIT:
17172 			range = retval_range(0, 0);
17173 			break;
17174 		case BPF_TRACE_RAW_TP:
17175 		case BPF_MODIFY_RETURN:
17176 			return 0;
17177 		case BPF_TRACE_ITER:
17178 			break;
17179 		default:
17180 			return -ENOTSUPP;
17181 		}
17182 		break;
17183 	case BPF_PROG_TYPE_KPROBE:
17184 		switch (env->prog->expected_attach_type) {
17185 		case BPF_TRACE_KPROBE_SESSION:
17186 		case BPF_TRACE_UPROBE_SESSION:
17187 			range = retval_range(0, 1);
17188 			break;
17189 		default:
17190 			return 0;
17191 		}
17192 		break;
17193 	case BPF_PROG_TYPE_SK_LOOKUP:
17194 		range = retval_range(SK_DROP, SK_PASS);
17195 		break;
17196 
17197 	case BPF_PROG_TYPE_LSM:
17198 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17199 			/* no range found, any return value is allowed */
17200 			if (!get_func_retval_range(env->prog, &range))
17201 				return 0;
17202 			/* no restricted range, any return value is allowed */
17203 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17204 				return 0;
17205 			return_32bit = true;
17206 		} else if (!env->prog->aux->attach_func_proto->type) {
17207 			/* Make sure programs that attach to void
17208 			 * hooks don't try to modify return value.
17209 			 */
17210 			range = retval_range(1, 1);
17211 		}
17212 		break;
17213 
17214 	case BPF_PROG_TYPE_NETFILTER:
17215 		range = retval_range(NF_DROP, NF_ACCEPT);
17216 		break;
17217 	case BPF_PROG_TYPE_STRUCT_OPS:
17218 		if (!ret_type)
17219 			return 0;
17220 		range = retval_range(0, 0);
17221 		break;
17222 	case BPF_PROG_TYPE_EXT:
17223 		/* freplace program can return anything as its return value
17224 		 * depends on the to-be-replaced kernel func or bpf program.
17225 		 */
17226 	default:
17227 		return 0;
17228 	}
17229 
17230 enforce_retval:
17231 	if (reg->type != SCALAR_VALUE) {
17232 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17233 			exit_ctx, regno, reg_type_str(env, reg->type));
17234 		return -EINVAL;
17235 	}
17236 
17237 	err = mark_chain_precision(env, regno);
17238 	if (err)
17239 		return err;
17240 
17241 	if (!retval_range_within(range, reg, return_32bit)) {
17242 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17243 		if (!is_subprog &&
17244 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17245 		    prog_type == BPF_PROG_TYPE_LSM &&
17246 		    !prog->aux->attach_func_proto->type)
17247 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17248 		return -EINVAL;
17249 	}
17250 
17251 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17252 	    tnum_in(enforce_attach_type_range, reg->var_off))
17253 		env->prog->enforce_expected_attach_type = 1;
17254 	return 0;
17255 }
17256 
mark_subprog_changes_pkt_data(struct bpf_verifier_env * env,int off)17257 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17258 {
17259 	struct bpf_subprog_info *subprog;
17260 
17261 	subprog = find_containing_subprog(env, off);
17262 	subprog->changes_pkt_data = true;
17263 }
17264 
mark_subprog_might_sleep(struct bpf_verifier_env * env,int off)17265 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17266 {
17267 	struct bpf_subprog_info *subprog;
17268 
17269 	subprog = find_containing_subprog(env, off);
17270 	subprog->might_sleep = true;
17271 }
17272 
17273 /* 't' is an index of a call-site.
17274  * 'w' is a callee entry point.
17275  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17276  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17277  * callee's change_pkt_data marks would be correct at that moment.
17278  */
merge_callee_effects(struct bpf_verifier_env * env,int t,int w)17279 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17280 {
17281 	struct bpf_subprog_info *caller, *callee;
17282 
17283 	caller = find_containing_subprog(env, t);
17284 	callee = find_containing_subprog(env, w);
17285 	caller->changes_pkt_data |= callee->changes_pkt_data;
17286 	caller->might_sleep |= callee->might_sleep;
17287 }
17288 
17289 /* non-recursive DFS pseudo code
17290  * 1  procedure DFS-iterative(G,v):
17291  * 2      label v as discovered
17292  * 3      let S be a stack
17293  * 4      S.push(v)
17294  * 5      while S is not empty
17295  * 6            t <- S.peek()
17296  * 7            if t is what we're looking for:
17297  * 8                return t
17298  * 9            for all edges e in G.adjacentEdges(t) do
17299  * 10               if edge e is already labelled
17300  * 11                   continue with the next edge
17301  * 12               w <- G.adjacentVertex(t,e)
17302  * 13               if vertex w is not discovered and not explored
17303  * 14                   label e as tree-edge
17304  * 15                   label w as discovered
17305  * 16                   S.push(w)
17306  * 17                   continue at 5
17307  * 18               else if vertex w is discovered
17308  * 19                   label e as back-edge
17309  * 20               else
17310  * 21                   // vertex w is explored
17311  * 22                   label e as forward- or cross-edge
17312  * 23           label t as explored
17313  * 24           S.pop()
17314  *
17315  * convention:
17316  * 0x10 - discovered
17317  * 0x11 - discovered and fall-through edge labelled
17318  * 0x12 - discovered and fall-through and branch edges labelled
17319  * 0x20 - explored
17320  */
17321 
17322 enum {
17323 	DISCOVERED = 0x10,
17324 	EXPLORED = 0x20,
17325 	FALLTHROUGH = 1,
17326 	BRANCH = 2,
17327 };
17328 
mark_prune_point(struct bpf_verifier_env * env,int idx)17329 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17330 {
17331 	env->insn_aux_data[idx].prune_point = true;
17332 }
17333 
is_prune_point(struct bpf_verifier_env * env,int insn_idx)17334 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17335 {
17336 	return env->insn_aux_data[insn_idx].prune_point;
17337 }
17338 
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)17339 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17340 {
17341 	env->insn_aux_data[idx].force_checkpoint = true;
17342 }
17343 
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)17344 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17345 {
17346 	return env->insn_aux_data[insn_idx].force_checkpoint;
17347 }
17348 
mark_calls_callback(struct bpf_verifier_env * env,int idx)17349 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17350 {
17351 	env->insn_aux_data[idx].calls_callback = true;
17352 }
17353 
calls_callback(struct bpf_verifier_env * env,int insn_idx)17354 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
17355 {
17356 	return env->insn_aux_data[insn_idx].calls_callback;
17357 }
17358 
17359 enum {
17360 	DONE_EXPLORING = 0,
17361 	KEEP_EXPLORING = 1,
17362 };
17363 
17364 /* t, w, e - match pseudo-code above:
17365  * t - index of current instruction
17366  * w - next instruction
17367  * e - edge
17368  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)17369 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17370 {
17371 	int *insn_stack = env->cfg.insn_stack;
17372 	int *insn_state = env->cfg.insn_state;
17373 
17374 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17375 		return DONE_EXPLORING;
17376 
17377 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17378 		return DONE_EXPLORING;
17379 
17380 	if (w < 0 || w >= env->prog->len) {
17381 		verbose_linfo(env, t, "%d: ", t);
17382 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17383 		return -EINVAL;
17384 	}
17385 
17386 	if (e == BRANCH) {
17387 		/* mark branch target for state pruning */
17388 		mark_prune_point(env, w);
17389 		mark_jmp_point(env, w);
17390 	}
17391 
17392 	if (insn_state[w] == 0) {
17393 		/* tree-edge */
17394 		insn_state[t] = DISCOVERED | e;
17395 		insn_state[w] = DISCOVERED;
17396 		if (env->cfg.cur_stack >= env->prog->len)
17397 			return -E2BIG;
17398 		insn_stack[env->cfg.cur_stack++] = w;
17399 		return KEEP_EXPLORING;
17400 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17401 		if (env->bpf_capable)
17402 			return DONE_EXPLORING;
17403 		verbose_linfo(env, t, "%d: ", t);
17404 		verbose_linfo(env, w, "%d: ", w);
17405 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17406 		return -EINVAL;
17407 	} else if (insn_state[w] == EXPLORED) {
17408 		/* forward- or cross-edge */
17409 		insn_state[t] = DISCOVERED | e;
17410 	} else {
17411 		verifier_bug(env, "insn state internal bug");
17412 		return -EFAULT;
17413 	}
17414 	return DONE_EXPLORING;
17415 }
17416 
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)17417 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17418 				struct bpf_verifier_env *env,
17419 				bool visit_callee)
17420 {
17421 	int ret, insn_sz;
17422 	int w;
17423 
17424 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17425 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17426 	if (ret)
17427 		return ret;
17428 
17429 	mark_prune_point(env, t + insn_sz);
17430 	/* when we exit from subprog, we need to record non-linear history */
17431 	mark_jmp_point(env, t + insn_sz);
17432 
17433 	if (visit_callee) {
17434 		w = t + insns[t].imm + 1;
17435 		mark_prune_point(env, t);
17436 		merge_callee_effects(env, t, w);
17437 		ret = push_insn(t, w, BRANCH, env);
17438 	}
17439 	return ret;
17440 }
17441 
17442 /* Bitmask with 1s for all caller saved registers */
17443 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17444 
17445 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17446  * replacement patch is presumed to follow bpf_fastcall contract
17447  * (see mark_fastcall_pattern_for_call() below).
17448  */
verifier_inlines_helper_call(struct bpf_verifier_env * env,s32 imm)17449 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17450 {
17451 	switch (imm) {
17452 #ifdef CONFIG_X86_64
17453 	case BPF_FUNC_get_smp_processor_id:
17454 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17455 #endif
17456 	default:
17457 		return false;
17458 	}
17459 }
17460 
17461 struct call_summary {
17462 	u8 num_params;
17463 	bool is_void;
17464 	bool fastcall;
17465 };
17466 
17467 /* If @call is a kfunc or helper call, fills @cs and returns true,
17468  * otherwise returns false.
17469  */
get_call_summary(struct bpf_verifier_env * env,struct bpf_insn * call,struct call_summary * cs)17470 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17471 			     struct call_summary *cs)
17472 {
17473 	struct bpf_kfunc_call_arg_meta meta;
17474 	const struct bpf_func_proto *fn;
17475 	int i;
17476 
17477 	if (bpf_helper_call(call)) {
17478 
17479 		if (get_helper_proto(env, call->imm, &fn) < 0)
17480 			/* error would be reported later */
17481 			return false;
17482 		cs->fastcall = fn->allow_fastcall &&
17483 			       (verifier_inlines_helper_call(env, call->imm) ||
17484 				bpf_jit_inlines_helper_call(call->imm));
17485 		cs->is_void = fn->ret_type == RET_VOID;
17486 		cs->num_params = 0;
17487 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17488 			if (fn->arg_type[i] == ARG_DONTCARE)
17489 				break;
17490 			cs->num_params++;
17491 		}
17492 		return true;
17493 	}
17494 
17495 	if (bpf_pseudo_kfunc_call(call)) {
17496 		int err;
17497 
17498 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17499 		if (err < 0)
17500 			/* error would be reported later */
17501 			return false;
17502 		cs->num_params = btf_type_vlen(meta.func_proto);
17503 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17504 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17505 		return true;
17506 	}
17507 
17508 	return false;
17509 }
17510 
17511 /* LLVM define a bpf_fastcall function attribute.
17512  * This attribute means that function scratches only some of
17513  * the caller saved registers defined by ABI.
17514  * For BPF the set of such registers could be defined as follows:
17515  * - R0 is scratched only if function is non-void;
17516  * - R1-R5 are scratched only if corresponding parameter type is defined
17517  *   in the function prototype.
17518  *
17519  * The contract between kernel and clang allows to simultaneously use
17520  * such functions and maintain backwards compatibility with old
17521  * kernels that don't understand bpf_fastcall calls:
17522  *
17523  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17524  *   registers are not scratched by the call;
17525  *
17526  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17527  *   spill/fill for every live r0-r5;
17528  *
17529  * - stack offsets used for the spill/fill are allocated as lowest
17530  *   stack offsets in whole function and are not used for any other
17531  *   purposes;
17532  *
17533  * - when kernel loads a program, it looks for such patterns
17534  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17535  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17536  *
17537  * - if so, and if verifier or current JIT inlines the call to the
17538  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17539  *   spill/fill pairs;
17540  *
17541  * - when old kernel loads a program, presence of spill/fill pairs
17542  *   keeps BPF program valid, albeit slightly less efficient.
17543  *
17544  * For example:
17545  *
17546  *   r1 = 1;
17547  *   r2 = 2;
17548  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17549  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17550  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17551  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17552  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17553  *   r0 = r1;                            exit;
17554  *   r0 += r2;
17555  *   exit;
17556  *
17557  * The purpose of mark_fastcall_pattern_for_call is to:
17558  * - look for such patterns;
17559  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17560  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17561  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17562  *   at which bpf_fastcall spill/fill stack slots start;
17563  * - update env->subprog_info[*]->keep_fastcall_stack.
17564  *
17565  * The .fastcall_pattern and .fastcall_stack_off are used by
17566  * check_fastcall_stack_contract() to check if every stack access to
17567  * fastcall spill/fill stack slot originates from spill/fill
17568  * instructions, members of fastcall patterns.
17569  *
17570  * If such condition holds true for a subprogram, fastcall patterns could
17571  * be rewritten by remove_fastcall_spills_fills().
17572  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17573  * (code, presumably, generated by an older clang version).
17574  *
17575  * For example, it is *not* safe to remove spill/fill below:
17576  *
17577  *   r1 = 1;
17578  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17579  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17580  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17581  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17582  *   r0 += r1;                           exit;
17583  *   exit;
17584  */
mark_fastcall_pattern_for_call(struct bpf_verifier_env * env,struct bpf_subprog_info * subprog,int insn_idx,s16 lowest_off)17585 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17586 					   struct bpf_subprog_info *subprog,
17587 					   int insn_idx, s16 lowest_off)
17588 {
17589 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17590 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17591 	u32 clobbered_regs_mask;
17592 	struct call_summary cs;
17593 	u32 expected_regs_mask;
17594 	s16 off;
17595 	int i;
17596 
17597 	if (!get_call_summary(env, call, &cs))
17598 		return;
17599 
17600 	/* A bitmask specifying which caller saved registers are clobbered
17601 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17602 	 * bpf_fastcall contract:
17603 	 * - includes R0 if function is non-void;
17604 	 * - includes R1-R5 if corresponding parameter has is described
17605 	 *   in the function prototype.
17606 	 */
17607 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17608 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17609 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17610 
17611 	/* match pairs of form:
17612 	 *
17613 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17614 	 * ...
17615 	 * call %[to_be_inlined]
17616 	 * ...
17617 	 * rX = *(u64 *)(r10 - Y)
17618 	 */
17619 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17620 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17621 			break;
17622 		stx = &insns[insn_idx - i];
17623 		ldx = &insns[insn_idx + i];
17624 		/* must be a stack spill/fill pair */
17625 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17626 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17627 		    stx->dst_reg != BPF_REG_10 ||
17628 		    ldx->src_reg != BPF_REG_10)
17629 			break;
17630 		/* must be a spill/fill for the same reg */
17631 		if (stx->src_reg != ldx->dst_reg)
17632 			break;
17633 		/* must be one of the previously unseen registers */
17634 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17635 			break;
17636 		/* must be a spill/fill for the same expected offset,
17637 		 * no need to check offset alignment, BPF_DW stack access
17638 		 * is always 8-byte aligned.
17639 		 */
17640 		if (stx->off != off || ldx->off != off)
17641 			break;
17642 		expected_regs_mask &= ~BIT(stx->src_reg);
17643 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17644 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17645 	}
17646 	if (i == 1)
17647 		return;
17648 
17649 	/* Conditionally set 'fastcall_spills_num' to allow forward
17650 	 * compatibility when more helper functions are marked as
17651 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17652 	 *
17653 	 *   1: *(u64 *)(r10 - 8) = r1
17654 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17655 	 *   3: r1 = *(u64 *)(r10 - 8)
17656 	 *   4: *(u64 *)(r10 - 8) = r1
17657 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17658 	 *   6: r1 = *(u64 *)(r10 - 8)
17659 	 *
17660 	 * There is no need to block bpf_fastcall rewrite for such program.
17661 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17662 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17663 	 * does not remove spill/fill pair {4,6}.
17664 	 */
17665 	if (cs.fastcall)
17666 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17667 	else
17668 		subprog->keep_fastcall_stack = 1;
17669 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17670 }
17671 
mark_fastcall_patterns(struct bpf_verifier_env * env)17672 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17673 {
17674 	struct bpf_subprog_info *subprog = env->subprog_info;
17675 	struct bpf_insn *insn;
17676 	s16 lowest_off;
17677 	int s, i;
17678 
17679 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17680 		/* find lowest stack spill offset used in this subprog */
17681 		lowest_off = 0;
17682 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17683 			insn = env->prog->insnsi + i;
17684 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17685 			    insn->dst_reg != BPF_REG_10)
17686 				continue;
17687 			lowest_off = min(lowest_off, insn->off);
17688 		}
17689 		/* use this offset to find fastcall patterns */
17690 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17691 			insn = env->prog->insnsi + i;
17692 			if (insn->code != (BPF_JMP | BPF_CALL))
17693 				continue;
17694 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17695 		}
17696 	}
17697 	return 0;
17698 }
17699 
17700 /* Visits the instruction at index t and returns one of the following:
17701  *  < 0 - an error occurred
17702  *  DONE_EXPLORING - the instruction was fully explored
17703  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17704  */
visit_insn(int t,struct bpf_verifier_env * env)17705 static int visit_insn(int t, struct bpf_verifier_env *env)
17706 {
17707 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17708 	int ret, off, insn_sz;
17709 
17710 	if (bpf_pseudo_func(insn))
17711 		return visit_func_call_insn(t, insns, env, true);
17712 
17713 	/* All non-branch instructions have a single fall-through edge. */
17714 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17715 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17716 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17717 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17718 	}
17719 
17720 	switch (BPF_OP(insn->code)) {
17721 	case BPF_EXIT:
17722 		return DONE_EXPLORING;
17723 
17724 	case BPF_CALL:
17725 		if (is_async_callback_calling_insn(insn))
17726 			/* Mark this call insn as a prune point to trigger
17727 			 * is_state_visited() check before call itself is
17728 			 * processed by __check_func_call(). Otherwise new
17729 			 * async state will be pushed for further exploration.
17730 			 */
17731 			mark_prune_point(env, t);
17732 		/* For functions that invoke callbacks it is not known how many times
17733 		 * callback would be called. Verifier models callback calling functions
17734 		 * by repeatedly visiting callback bodies and returning to origin call
17735 		 * instruction.
17736 		 * In order to stop such iteration verifier needs to identify when a
17737 		 * state identical some state from a previous iteration is reached.
17738 		 * Check below forces creation of checkpoint before callback calling
17739 		 * instruction to allow search for such identical states.
17740 		 */
17741 		if (is_sync_callback_calling_insn(insn)) {
17742 			mark_calls_callback(env, t);
17743 			mark_force_checkpoint(env, t);
17744 			mark_prune_point(env, t);
17745 			mark_jmp_point(env, t);
17746 		}
17747 		if (bpf_helper_call(insn)) {
17748 			const struct bpf_func_proto *fp;
17749 
17750 			ret = get_helper_proto(env, insn->imm, &fp);
17751 			/* If called in a non-sleepable context program will be
17752 			 * rejected anyway, so we should end up with precise
17753 			 * sleepable marks on subprogs, except for dead code
17754 			 * elimination.
17755 			 */
17756 			if (ret == 0 && fp->might_sleep)
17757 				mark_subprog_might_sleep(env, t);
17758 			if (bpf_helper_changes_pkt_data(insn->imm))
17759 				mark_subprog_changes_pkt_data(env, t);
17760 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17761 			struct bpf_kfunc_call_arg_meta meta;
17762 
17763 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17764 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17765 				mark_prune_point(env, t);
17766 				/* Checking and saving state checkpoints at iter_next() call
17767 				 * is crucial for fast convergence of open-coded iterator loop
17768 				 * logic, so we need to force it. If we don't do that,
17769 				 * is_state_visited() might skip saving a checkpoint, causing
17770 				 * unnecessarily long sequence of not checkpointed
17771 				 * instructions and jumps, leading to exhaustion of jump
17772 				 * history buffer, and potentially other undesired outcomes.
17773 				 * It is expected that with correct open-coded iterators
17774 				 * convergence will happen quickly, so we don't run a risk of
17775 				 * exhausting memory.
17776 				 */
17777 				mark_force_checkpoint(env, t);
17778 			}
17779 			/* Same as helpers, if called in a non-sleepable context
17780 			 * program will be rejected anyway, so we should end up
17781 			 * with precise sleepable marks on subprogs, except for
17782 			 * dead code elimination.
17783 			 */
17784 			if (ret == 0 && is_kfunc_sleepable(&meta))
17785 				mark_subprog_might_sleep(env, t);
17786 		}
17787 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17788 
17789 	case BPF_JA:
17790 		if (BPF_SRC(insn->code) != BPF_K)
17791 			return -EINVAL;
17792 
17793 		if (BPF_CLASS(insn->code) == BPF_JMP)
17794 			off = insn->off;
17795 		else
17796 			off = insn->imm;
17797 
17798 		/* unconditional jump with single edge */
17799 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17800 		if (ret)
17801 			return ret;
17802 
17803 		mark_prune_point(env, t + off + 1);
17804 		mark_jmp_point(env, t + off + 1);
17805 
17806 		return ret;
17807 
17808 	default:
17809 		/* conditional jump with two edges */
17810 		mark_prune_point(env, t);
17811 		if (is_may_goto_insn(insn))
17812 			mark_force_checkpoint(env, t);
17813 
17814 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17815 		if (ret)
17816 			return ret;
17817 
17818 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17819 	}
17820 }
17821 
17822 /* non-recursive depth-first-search to detect loops in BPF program
17823  * loop == back-edge in directed graph
17824  */
check_cfg(struct bpf_verifier_env * env)17825 static int check_cfg(struct bpf_verifier_env *env)
17826 {
17827 	int insn_cnt = env->prog->len;
17828 	int *insn_stack, *insn_state, *insn_postorder;
17829 	int ex_insn_beg, i, ret = 0;
17830 
17831 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17832 	if (!insn_state)
17833 		return -ENOMEM;
17834 
17835 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17836 	if (!insn_stack) {
17837 		kvfree(insn_state);
17838 		return -ENOMEM;
17839 	}
17840 
17841 	insn_postorder = env->cfg.insn_postorder =
17842 		kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17843 	if (!insn_postorder) {
17844 		kvfree(insn_state);
17845 		kvfree(insn_stack);
17846 		return -ENOMEM;
17847 	}
17848 
17849 	ex_insn_beg = env->exception_callback_subprog
17850 		      ? env->subprog_info[env->exception_callback_subprog].start
17851 		      : 0;
17852 
17853 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17854 	insn_stack[0] = 0; /* 0 is the first instruction */
17855 	env->cfg.cur_stack = 1;
17856 
17857 walk_cfg:
17858 	while (env->cfg.cur_stack > 0) {
17859 		int t = insn_stack[env->cfg.cur_stack - 1];
17860 
17861 		ret = visit_insn(t, env);
17862 		switch (ret) {
17863 		case DONE_EXPLORING:
17864 			insn_state[t] = EXPLORED;
17865 			env->cfg.cur_stack--;
17866 			insn_postorder[env->cfg.cur_postorder++] = t;
17867 			break;
17868 		case KEEP_EXPLORING:
17869 			break;
17870 		default:
17871 			if (ret > 0) {
17872 				verifier_bug(env, "visit_insn internal bug");
17873 				ret = -EFAULT;
17874 			}
17875 			goto err_free;
17876 		}
17877 	}
17878 
17879 	if (env->cfg.cur_stack < 0) {
17880 		verifier_bug(env, "pop stack internal bug");
17881 		ret = -EFAULT;
17882 		goto err_free;
17883 	}
17884 
17885 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
17886 		insn_state[ex_insn_beg] = DISCOVERED;
17887 		insn_stack[0] = ex_insn_beg;
17888 		env->cfg.cur_stack = 1;
17889 		goto walk_cfg;
17890 	}
17891 
17892 	for (i = 0; i < insn_cnt; i++) {
17893 		struct bpf_insn *insn = &env->prog->insnsi[i];
17894 
17895 		if (insn_state[i] != EXPLORED) {
17896 			verbose(env, "unreachable insn %d\n", i);
17897 			ret = -EINVAL;
17898 			goto err_free;
17899 		}
17900 		if (bpf_is_ldimm64(insn)) {
17901 			if (insn_state[i + 1] != 0) {
17902 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17903 				ret = -EINVAL;
17904 				goto err_free;
17905 			}
17906 			i++; /* skip second half of ldimm64 */
17907 		}
17908 	}
17909 	ret = 0; /* cfg looks good */
17910 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17911 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
17912 
17913 err_free:
17914 	kvfree(insn_state);
17915 	kvfree(insn_stack);
17916 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17917 	return ret;
17918 }
17919 
check_abnormal_return(struct bpf_verifier_env * env)17920 static int check_abnormal_return(struct bpf_verifier_env *env)
17921 {
17922 	int i;
17923 
17924 	for (i = 1; i < env->subprog_cnt; i++) {
17925 		if (env->subprog_info[i].has_ld_abs) {
17926 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
17927 			return -EINVAL;
17928 		}
17929 		if (env->subprog_info[i].has_tail_call) {
17930 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
17931 			return -EINVAL;
17932 		}
17933 	}
17934 	return 0;
17935 }
17936 
17937 /* The minimum supported BTF func info size */
17938 #define MIN_BPF_FUNCINFO_SIZE	8
17939 #define MAX_FUNCINFO_REC_SIZE	252
17940 
check_btf_func_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)17941 static int check_btf_func_early(struct bpf_verifier_env *env,
17942 				const union bpf_attr *attr,
17943 				bpfptr_t uattr)
17944 {
17945 	u32 krec_size = sizeof(struct bpf_func_info);
17946 	const struct btf_type *type, *func_proto;
17947 	u32 i, nfuncs, urec_size, min_size;
17948 	struct bpf_func_info *krecord;
17949 	struct bpf_prog *prog;
17950 	const struct btf *btf;
17951 	u32 prev_offset = 0;
17952 	bpfptr_t urecord;
17953 	int ret = -ENOMEM;
17954 
17955 	nfuncs = attr->func_info_cnt;
17956 	if (!nfuncs) {
17957 		if (check_abnormal_return(env))
17958 			return -EINVAL;
17959 		return 0;
17960 	}
17961 
17962 	urec_size = attr->func_info_rec_size;
17963 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
17964 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
17965 	    urec_size % sizeof(u32)) {
17966 		verbose(env, "invalid func info rec size %u\n", urec_size);
17967 		return -EINVAL;
17968 	}
17969 
17970 	prog = env->prog;
17971 	btf = prog->aux->btf;
17972 
17973 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
17974 	min_size = min_t(u32, krec_size, urec_size);
17975 
17976 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
17977 	if (!krecord)
17978 		return -ENOMEM;
17979 
17980 	for (i = 0; i < nfuncs; i++) {
17981 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
17982 		if (ret) {
17983 			if (ret == -E2BIG) {
17984 				verbose(env, "nonzero tailing record in func info");
17985 				/* set the size kernel expects so loader can zero
17986 				 * out the rest of the record.
17987 				 */
17988 				if (copy_to_bpfptr_offset(uattr,
17989 							  offsetof(union bpf_attr, func_info_rec_size),
17990 							  &min_size, sizeof(min_size)))
17991 					ret = -EFAULT;
17992 			}
17993 			goto err_free;
17994 		}
17995 
17996 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
17997 			ret = -EFAULT;
17998 			goto err_free;
17999 		}
18000 
18001 		/* check insn_off */
18002 		ret = -EINVAL;
18003 		if (i == 0) {
18004 			if (krecord[i].insn_off) {
18005 				verbose(env,
18006 					"nonzero insn_off %u for the first func info record",
18007 					krecord[i].insn_off);
18008 				goto err_free;
18009 			}
18010 		} else if (krecord[i].insn_off <= prev_offset) {
18011 			verbose(env,
18012 				"same or smaller insn offset (%u) than previous func info record (%u)",
18013 				krecord[i].insn_off, prev_offset);
18014 			goto err_free;
18015 		}
18016 
18017 		/* check type_id */
18018 		type = btf_type_by_id(btf, krecord[i].type_id);
18019 		if (!type || !btf_type_is_func(type)) {
18020 			verbose(env, "invalid type id %d in func info",
18021 				krecord[i].type_id);
18022 			goto err_free;
18023 		}
18024 
18025 		func_proto = btf_type_by_id(btf, type->type);
18026 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18027 			/* btf_func_check() already verified it during BTF load */
18028 			goto err_free;
18029 
18030 		prev_offset = krecord[i].insn_off;
18031 		bpfptr_add(&urecord, urec_size);
18032 	}
18033 
18034 	prog->aux->func_info = krecord;
18035 	prog->aux->func_info_cnt = nfuncs;
18036 	return 0;
18037 
18038 err_free:
18039 	kvfree(krecord);
18040 	return ret;
18041 }
18042 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18043 static int check_btf_func(struct bpf_verifier_env *env,
18044 			  const union bpf_attr *attr,
18045 			  bpfptr_t uattr)
18046 {
18047 	const struct btf_type *type, *func_proto, *ret_type;
18048 	u32 i, nfuncs, urec_size;
18049 	struct bpf_func_info *krecord;
18050 	struct bpf_func_info_aux *info_aux = NULL;
18051 	struct bpf_prog *prog;
18052 	const struct btf *btf;
18053 	bpfptr_t urecord;
18054 	bool scalar_return;
18055 	int ret = -ENOMEM;
18056 
18057 	nfuncs = attr->func_info_cnt;
18058 	if (!nfuncs) {
18059 		if (check_abnormal_return(env))
18060 			return -EINVAL;
18061 		return 0;
18062 	}
18063 	if (nfuncs != env->subprog_cnt) {
18064 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18065 		return -EINVAL;
18066 	}
18067 
18068 	urec_size = attr->func_info_rec_size;
18069 
18070 	prog = env->prog;
18071 	btf = prog->aux->btf;
18072 
18073 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18074 
18075 	krecord = prog->aux->func_info;
18076 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18077 	if (!info_aux)
18078 		return -ENOMEM;
18079 
18080 	for (i = 0; i < nfuncs; i++) {
18081 		/* check insn_off */
18082 		ret = -EINVAL;
18083 
18084 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18085 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18086 			goto err_free;
18087 		}
18088 
18089 		/* Already checked type_id */
18090 		type = btf_type_by_id(btf, krecord[i].type_id);
18091 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18092 		/* Already checked func_proto */
18093 		func_proto = btf_type_by_id(btf, type->type);
18094 
18095 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18096 		scalar_return =
18097 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18098 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18099 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18100 			goto err_free;
18101 		}
18102 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18103 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18104 			goto err_free;
18105 		}
18106 
18107 		bpfptr_add(&urecord, urec_size);
18108 	}
18109 
18110 	prog->aux->func_info_aux = info_aux;
18111 	return 0;
18112 
18113 err_free:
18114 	kfree(info_aux);
18115 	return ret;
18116 }
18117 
adjust_btf_func(struct bpf_verifier_env * env)18118 static void adjust_btf_func(struct bpf_verifier_env *env)
18119 {
18120 	struct bpf_prog_aux *aux = env->prog->aux;
18121 	int i;
18122 
18123 	if (!aux->func_info)
18124 		return;
18125 
18126 	/* func_info is not available for hidden subprogs */
18127 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18128 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18129 }
18130 
18131 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18132 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18133 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18134 static int check_btf_line(struct bpf_verifier_env *env,
18135 			  const union bpf_attr *attr,
18136 			  bpfptr_t uattr)
18137 {
18138 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18139 	struct bpf_subprog_info *sub;
18140 	struct bpf_line_info *linfo;
18141 	struct bpf_prog *prog;
18142 	const struct btf *btf;
18143 	bpfptr_t ulinfo;
18144 	int err;
18145 
18146 	nr_linfo = attr->line_info_cnt;
18147 	if (!nr_linfo)
18148 		return 0;
18149 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18150 		return -EINVAL;
18151 
18152 	rec_size = attr->line_info_rec_size;
18153 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18154 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18155 	    rec_size & (sizeof(u32) - 1))
18156 		return -EINVAL;
18157 
18158 	/* Need to zero it in case the userspace may
18159 	 * pass in a smaller bpf_line_info object.
18160 	 */
18161 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18162 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18163 	if (!linfo)
18164 		return -ENOMEM;
18165 
18166 	prog = env->prog;
18167 	btf = prog->aux->btf;
18168 
18169 	s = 0;
18170 	sub = env->subprog_info;
18171 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18172 	expected_size = sizeof(struct bpf_line_info);
18173 	ncopy = min_t(u32, expected_size, rec_size);
18174 	for (i = 0; i < nr_linfo; i++) {
18175 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18176 		if (err) {
18177 			if (err == -E2BIG) {
18178 				verbose(env, "nonzero tailing record in line_info");
18179 				if (copy_to_bpfptr_offset(uattr,
18180 							  offsetof(union bpf_attr, line_info_rec_size),
18181 							  &expected_size, sizeof(expected_size)))
18182 					err = -EFAULT;
18183 			}
18184 			goto err_free;
18185 		}
18186 
18187 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18188 			err = -EFAULT;
18189 			goto err_free;
18190 		}
18191 
18192 		/*
18193 		 * Check insn_off to ensure
18194 		 * 1) strictly increasing AND
18195 		 * 2) bounded by prog->len
18196 		 *
18197 		 * The linfo[0].insn_off == 0 check logically falls into
18198 		 * the later "missing bpf_line_info for func..." case
18199 		 * because the first linfo[0].insn_off must be the
18200 		 * first sub also and the first sub must have
18201 		 * subprog_info[0].start == 0.
18202 		 */
18203 		if ((i && linfo[i].insn_off <= prev_offset) ||
18204 		    linfo[i].insn_off >= prog->len) {
18205 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18206 				i, linfo[i].insn_off, prev_offset,
18207 				prog->len);
18208 			err = -EINVAL;
18209 			goto err_free;
18210 		}
18211 
18212 		if (!prog->insnsi[linfo[i].insn_off].code) {
18213 			verbose(env,
18214 				"Invalid insn code at line_info[%u].insn_off\n",
18215 				i);
18216 			err = -EINVAL;
18217 			goto err_free;
18218 		}
18219 
18220 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18221 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18222 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18223 			err = -EINVAL;
18224 			goto err_free;
18225 		}
18226 
18227 		if (s != env->subprog_cnt) {
18228 			if (linfo[i].insn_off == sub[s].start) {
18229 				sub[s].linfo_idx = i;
18230 				s++;
18231 			} else if (sub[s].start < linfo[i].insn_off) {
18232 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18233 				err = -EINVAL;
18234 				goto err_free;
18235 			}
18236 		}
18237 
18238 		prev_offset = linfo[i].insn_off;
18239 		bpfptr_add(&ulinfo, rec_size);
18240 	}
18241 
18242 	if (s != env->subprog_cnt) {
18243 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18244 			env->subprog_cnt - s, s);
18245 		err = -EINVAL;
18246 		goto err_free;
18247 	}
18248 
18249 	prog->aux->linfo = linfo;
18250 	prog->aux->nr_linfo = nr_linfo;
18251 
18252 	return 0;
18253 
18254 err_free:
18255 	kvfree(linfo);
18256 	return err;
18257 }
18258 
18259 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18260 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18261 
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18262 static int check_core_relo(struct bpf_verifier_env *env,
18263 			   const union bpf_attr *attr,
18264 			   bpfptr_t uattr)
18265 {
18266 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18267 	struct bpf_core_relo core_relo = {};
18268 	struct bpf_prog *prog = env->prog;
18269 	const struct btf *btf = prog->aux->btf;
18270 	struct bpf_core_ctx ctx = {
18271 		.log = &env->log,
18272 		.btf = btf,
18273 	};
18274 	bpfptr_t u_core_relo;
18275 	int err;
18276 
18277 	nr_core_relo = attr->core_relo_cnt;
18278 	if (!nr_core_relo)
18279 		return 0;
18280 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18281 		return -EINVAL;
18282 
18283 	rec_size = attr->core_relo_rec_size;
18284 	if (rec_size < MIN_CORE_RELO_SIZE ||
18285 	    rec_size > MAX_CORE_RELO_SIZE ||
18286 	    rec_size % sizeof(u32))
18287 		return -EINVAL;
18288 
18289 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18290 	expected_size = sizeof(struct bpf_core_relo);
18291 	ncopy = min_t(u32, expected_size, rec_size);
18292 
18293 	/* Unlike func_info and line_info, copy and apply each CO-RE
18294 	 * relocation record one at a time.
18295 	 */
18296 	for (i = 0; i < nr_core_relo; i++) {
18297 		/* future proofing when sizeof(bpf_core_relo) changes */
18298 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18299 		if (err) {
18300 			if (err == -E2BIG) {
18301 				verbose(env, "nonzero tailing record in core_relo");
18302 				if (copy_to_bpfptr_offset(uattr,
18303 							  offsetof(union bpf_attr, core_relo_rec_size),
18304 							  &expected_size, sizeof(expected_size)))
18305 					err = -EFAULT;
18306 			}
18307 			break;
18308 		}
18309 
18310 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18311 			err = -EFAULT;
18312 			break;
18313 		}
18314 
18315 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18316 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18317 				i, core_relo.insn_off, prog->len);
18318 			err = -EINVAL;
18319 			break;
18320 		}
18321 
18322 		err = bpf_core_apply(&ctx, &core_relo, i,
18323 				     &prog->insnsi[core_relo.insn_off / 8]);
18324 		if (err)
18325 			break;
18326 		bpfptr_add(&u_core_relo, rec_size);
18327 	}
18328 	return err;
18329 }
18330 
check_btf_info_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18331 static int check_btf_info_early(struct bpf_verifier_env *env,
18332 				const union bpf_attr *attr,
18333 				bpfptr_t uattr)
18334 {
18335 	struct btf *btf;
18336 	int err;
18337 
18338 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18339 		if (check_abnormal_return(env))
18340 			return -EINVAL;
18341 		return 0;
18342 	}
18343 
18344 	btf = btf_get_by_fd(attr->prog_btf_fd);
18345 	if (IS_ERR(btf))
18346 		return PTR_ERR(btf);
18347 	if (btf_is_kernel(btf)) {
18348 		btf_put(btf);
18349 		return -EACCES;
18350 	}
18351 	env->prog->aux->btf = btf;
18352 
18353 	err = check_btf_func_early(env, attr, uattr);
18354 	if (err)
18355 		return err;
18356 	return 0;
18357 }
18358 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18359 static int check_btf_info(struct bpf_verifier_env *env,
18360 			  const union bpf_attr *attr,
18361 			  bpfptr_t uattr)
18362 {
18363 	int err;
18364 
18365 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18366 		if (check_abnormal_return(env))
18367 			return -EINVAL;
18368 		return 0;
18369 	}
18370 
18371 	err = check_btf_func(env, attr, uattr);
18372 	if (err)
18373 		return err;
18374 
18375 	err = check_btf_line(env, attr, uattr);
18376 	if (err)
18377 		return err;
18378 
18379 	err = check_core_relo(env, attr, uattr);
18380 	if (err)
18381 		return err;
18382 
18383 	return 0;
18384 }
18385 
18386 /* check %cur's range satisfies %old's */
range_within(const struct bpf_reg_state * old,const struct bpf_reg_state * cur)18387 static bool range_within(const struct bpf_reg_state *old,
18388 			 const struct bpf_reg_state *cur)
18389 {
18390 	return old->umin_value <= cur->umin_value &&
18391 	       old->umax_value >= cur->umax_value &&
18392 	       old->smin_value <= cur->smin_value &&
18393 	       old->smax_value >= cur->smax_value &&
18394 	       old->u32_min_value <= cur->u32_min_value &&
18395 	       old->u32_max_value >= cur->u32_max_value &&
18396 	       old->s32_min_value <= cur->s32_min_value &&
18397 	       old->s32_max_value >= cur->s32_max_value;
18398 }
18399 
18400 /* If in the old state two registers had the same id, then they need to have
18401  * the same id in the new state as well.  But that id could be different from
18402  * the old state, so we need to track the mapping from old to new ids.
18403  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18404  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18405  * regs with a different old id could still have new id 9, we don't care about
18406  * that.
18407  * So we look through our idmap to see if this old id has been seen before.  If
18408  * so, we require the new id to match; otherwise, we add the id pair to the map.
18409  */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18410 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18411 {
18412 	struct bpf_id_pair *map = idmap->map;
18413 	unsigned int i;
18414 
18415 	/* either both IDs should be set or both should be zero */
18416 	if (!!old_id != !!cur_id)
18417 		return false;
18418 
18419 	if (old_id == 0) /* cur_id == 0 as well */
18420 		return true;
18421 
18422 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18423 		if (!map[i].old) {
18424 			/* Reached an empty slot; haven't seen this id before */
18425 			map[i].old = old_id;
18426 			map[i].cur = cur_id;
18427 			return true;
18428 		}
18429 		if (map[i].old == old_id)
18430 			return map[i].cur == cur_id;
18431 		if (map[i].cur == cur_id)
18432 			return false;
18433 	}
18434 	/* We ran out of idmap slots, which should be impossible */
18435 	WARN_ON_ONCE(1);
18436 	return false;
18437 }
18438 
18439 /* Similar to check_ids(), but allocate a unique temporary ID
18440  * for 'old_id' or 'cur_id' of zero.
18441  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18442  */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18443 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18444 {
18445 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18446 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18447 
18448 	return check_ids(old_id, cur_id, idmap);
18449 }
18450 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)18451 static void clean_func_state(struct bpf_verifier_env *env,
18452 			     struct bpf_func_state *st)
18453 {
18454 	enum bpf_reg_liveness live;
18455 	int i, j;
18456 
18457 	for (i = 0; i < BPF_REG_FP; i++) {
18458 		live = st->regs[i].live;
18459 		/* liveness must not touch this register anymore */
18460 		st->regs[i].live |= REG_LIVE_DONE;
18461 		if (!(live & REG_LIVE_READ))
18462 			/* since the register is unused, clear its state
18463 			 * to make further comparison simpler
18464 			 */
18465 			__mark_reg_not_init(env, &st->regs[i]);
18466 	}
18467 
18468 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18469 		live = st->stack[i].spilled_ptr.live;
18470 		/* liveness must not touch this stack slot anymore */
18471 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
18472 		if (!(live & REG_LIVE_READ)) {
18473 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18474 			for (j = 0; j < BPF_REG_SIZE; j++)
18475 				st->stack[i].slot_type[j] = STACK_INVALID;
18476 		}
18477 	}
18478 }
18479 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)18480 static void clean_verifier_state(struct bpf_verifier_env *env,
18481 				 struct bpf_verifier_state *st)
18482 {
18483 	int i;
18484 
18485 	for (i = 0; i <= st->curframe; i++)
18486 		clean_func_state(env, st->frame[i]);
18487 }
18488 
18489 /* the parentage chains form a tree.
18490  * the verifier states are added to state lists at given insn and
18491  * pushed into state stack for future exploration.
18492  * when the verifier reaches bpf_exit insn some of the verifier states
18493  * stored in the state lists have their final liveness state already,
18494  * but a lot of states will get revised from liveness point of view when
18495  * the verifier explores other branches.
18496  * Example:
18497  * 1: r0 = 1
18498  * 2: if r1 == 100 goto pc+1
18499  * 3: r0 = 2
18500  * 4: exit
18501  * when the verifier reaches exit insn the register r0 in the state list of
18502  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
18503  * of insn 2 and goes exploring further. At the insn 4 it will walk the
18504  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
18505  *
18506  * Since the verifier pushes the branch states as it sees them while exploring
18507  * the program the condition of walking the branch instruction for the second
18508  * time means that all states below this branch were already explored and
18509  * their final liveness marks are already propagated.
18510  * Hence when the verifier completes the search of state list in is_state_visited()
18511  * we can call this clean_live_states() function to mark all liveness states
18512  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
18513  * will not be used.
18514  * This function also clears the registers and stack for states that !READ
18515  * to simplify state merging.
18516  *
18517  * Important note here that walking the same branch instruction in the callee
18518  * doesn't meant that the states are DONE. The verifier has to compare
18519  * the callsites
18520  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)18521 static void clean_live_states(struct bpf_verifier_env *env, int insn,
18522 			      struct bpf_verifier_state *cur)
18523 {
18524 	struct bpf_verifier_state_list *sl;
18525 	struct list_head *pos, *head;
18526 
18527 	head = explored_state(env, insn);
18528 	list_for_each(pos, head) {
18529 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18530 		if (sl->state.branches)
18531 			continue;
18532 		if (sl->state.insn_idx != insn ||
18533 		    !same_callsites(&sl->state, cur))
18534 			continue;
18535 		if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE)
18536 			/* all regs in this state in all frames were already marked */
18537 			continue;
18538 		if (incomplete_read_marks(env, &sl->state))
18539 			continue;
18540 		clean_verifier_state(env, &sl->state);
18541 	}
18542 }
18543 
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)18544 static bool regs_exact(const struct bpf_reg_state *rold,
18545 		       const struct bpf_reg_state *rcur,
18546 		       struct bpf_idmap *idmap)
18547 {
18548 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18549 	       check_ids(rold->id, rcur->id, idmap) &&
18550 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18551 }
18552 
18553 enum exact_level {
18554 	NOT_EXACT,
18555 	EXACT,
18556 	RANGE_WITHIN
18557 };
18558 
18559 /* 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)18560 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
18561 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
18562 		    enum exact_level exact)
18563 {
18564 	if (exact == EXACT)
18565 		return regs_exact(rold, rcur, idmap);
18566 
18567 	if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT)
18568 		/* explored state didn't use this */
18569 		return true;
18570 	if (rold->type == NOT_INIT) {
18571 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
18572 			/* explored state can't have used this */
18573 			return true;
18574 	}
18575 
18576 	/* Enforce that register types have to match exactly, including their
18577 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
18578 	 * rule.
18579 	 *
18580 	 * One can make a point that using a pointer register as unbounded
18581 	 * SCALAR would be technically acceptable, but this could lead to
18582 	 * pointer leaks because scalars are allowed to leak while pointers
18583 	 * are not. We could make this safe in special cases if root is
18584 	 * calling us, but it's probably not worth the hassle.
18585 	 *
18586 	 * Also, register types that are *not* MAYBE_NULL could technically be
18587 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
18588 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
18589 	 * to the same map).
18590 	 * However, if the old MAYBE_NULL register then got NULL checked,
18591 	 * doing so could have affected others with the same id, and we can't
18592 	 * check for that because we lost the id when we converted to
18593 	 * a non-MAYBE_NULL variant.
18594 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
18595 	 * non-MAYBE_NULL registers as well.
18596 	 */
18597 	if (rold->type != rcur->type)
18598 		return false;
18599 
18600 	switch (base_type(rold->type)) {
18601 	case SCALAR_VALUE:
18602 		if (env->explore_alu_limits) {
18603 			/* explore_alu_limits disables tnum_in() and range_within()
18604 			 * logic and requires everything to be strict
18605 			 */
18606 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18607 			       check_scalar_ids(rold->id, rcur->id, idmap);
18608 		}
18609 		if (!rold->precise && exact == NOT_EXACT)
18610 			return true;
18611 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
18612 			return false;
18613 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
18614 			return false;
18615 		/* Why check_ids() for scalar registers?
18616 		 *
18617 		 * Consider the following BPF code:
18618 		 *   1: r6 = ... unbound scalar, ID=a ...
18619 		 *   2: r7 = ... unbound scalar, ID=b ...
18620 		 *   3: if (r6 > r7) goto +1
18621 		 *   4: r6 = r7
18622 		 *   5: if (r6 > X) goto ...
18623 		 *   6: ... memory operation using r7 ...
18624 		 *
18625 		 * First verification path is [1-6]:
18626 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
18627 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
18628 		 *   r7 <= X, because r6 and r7 share same id.
18629 		 * Next verification path is [1-4, 6].
18630 		 *
18631 		 * Instruction (6) would be reached in two states:
18632 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
18633 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
18634 		 *
18635 		 * Use check_ids() to distinguish these states.
18636 		 * ---
18637 		 * Also verify that new value satisfies old value range knowledge.
18638 		 */
18639 		return range_within(rold, rcur) &&
18640 		       tnum_in(rold->var_off, rcur->var_off) &&
18641 		       check_scalar_ids(rold->id, rcur->id, idmap);
18642 	case PTR_TO_MAP_KEY:
18643 	case PTR_TO_MAP_VALUE:
18644 	case PTR_TO_MEM:
18645 	case PTR_TO_BUF:
18646 	case PTR_TO_TP_BUFFER:
18647 		/* If the new min/max/var_off satisfy the old ones and
18648 		 * everything else matches, we are OK.
18649 		 */
18650 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
18651 		       range_within(rold, rcur) &&
18652 		       tnum_in(rold->var_off, rcur->var_off) &&
18653 		       check_ids(rold->id, rcur->id, idmap) &&
18654 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18655 	case PTR_TO_PACKET_META:
18656 	case PTR_TO_PACKET:
18657 		/* We must have at least as much range as the old ptr
18658 		 * did, so that any accesses which were safe before are
18659 		 * still safe.  This is true even if old range < old off,
18660 		 * since someone could have accessed through (ptr - k), or
18661 		 * even done ptr -= k in a register, to get a safe access.
18662 		 */
18663 		if (rold->range > rcur->range)
18664 			return false;
18665 		/* If the offsets don't match, we can't trust our alignment;
18666 		 * nor can we be sure that we won't fall out of range.
18667 		 */
18668 		if (rold->off != rcur->off)
18669 			return false;
18670 		/* id relations must be preserved */
18671 		if (!check_ids(rold->id, rcur->id, idmap))
18672 			return false;
18673 		/* new val must satisfy old val knowledge */
18674 		return range_within(rold, rcur) &&
18675 		       tnum_in(rold->var_off, rcur->var_off);
18676 	case PTR_TO_STACK:
18677 		/* two stack pointers are equal only if they're pointing to
18678 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
18679 		 */
18680 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
18681 	case PTR_TO_ARENA:
18682 		return true;
18683 	default:
18684 		return regs_exact(rold, rcur, idmap);
18685 	}
18686 }
18687 
18688 static struct bpf_reg_state unbound_reg;
18689 
unbound_reg_init(void)18690 static __init int unbound_reg_init(void)
18691 {
18692 	__mark_reg_unknown_imprecise(&unbound_reg);
18693 	unbound_reg.live |= REG_LIVE_READ;
18694 	return 0;
18695 }
18696 late_initcall(unbound_reg_init);
18697 
is_stack_all_misc(struct bpf_verifier_env * env,struct bpf_stack_state * stack)18698 static bool is_stack_all_misc(struct bpf_verifier_env *env,
18699 			      struct bpf_stack_state *stack)
18700 {
18701 	u32 i;
18702 
18703 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
18704 		if ((stack->slot_type[i] == STACK_MISC) ||
18705 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
18706 			continue;
18707 		return false;
18708 	}
18709 
18710 	return true;
18711 }
18712 
scalar_reg_for_stack(struct bpf_verifier_env * env,struct bpf_stack_state * stack)18713 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
18714 						  struct bpf_stack_state *stack)
18715 {
18716 	if (is_spilled_scalar_reg64(stack))
18717 		return &stack->spilled_ptr;
18718 
18719 	if (is_stack_all_misc(env, stack))
18720 		return &unbound_reg;
18721 
18722 	return NULL;
18723 }
18724 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,enum exact_level exact)18725 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18726 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18727 		      enum exact_level exact)
18728 {
18729 	int i, spi;
18730 
18731 	/* walk slots of the explored stack and ignore any additional
18732 	 * slots in the current stack, since explored(safe) state
18733 	 * didn't use them
18734 	 */
18735 	for (i = 0; i < old->allocated_stack; i++) {
18736 		struct bpf_reg_state *old_reg, *cur_reg;
18737 
18738 		spi = i / BPF_REG_SIZE;
18739 
18740 		if (exact != NOT_EXACT &&
18741 		    (i >= cur->allocated_stack ||
18742 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18743 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18744 			return false;
18745 
18746 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)
18747 		    && exact == NOT_EXACT) {
18748 			i += BPF_REG_SIZE - 1;
18749 			/* explored state didn't use this */
18750 			continue;
18751 		}
18752 
18753 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18754 			continue;
18755 
18756 		if (env->allow_uninit_stack &&
18757 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18758 			continue;
18759 
18760 		/* explored stack has more populated slots than current stack
18761 		 * and these slots were used
18762 		 */
18763 		if (i >= cur->allocated_stack)
18764 			return false;
18765 
18766 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18767 		 * Load from all slots MISC produces unbound scalar.
18768 		 * Construct a fake register for such stack and call
18769 		 * regsafe() to ensure scalar ids are compared.
18770 		 */
18771 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18772 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18773 		if (old_reg && cur_reg) {
18774 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18775 				return false;
18776 			i += BPF_REG_SIZE - 1;
18777 			continue;
18778 		}
18779 
18780 		/* if old state was safe with misc data in the stack
18781 		 * it will be safe with zero-initialized stack.
18782 		 * The opposite is not true
18783 		 */
18784 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18785 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18786 			continue;
18787 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18788 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18789 			/* Ex: old explored (safe) state has STACK_SPILL in
18790 			 * this stack slot, but current has STACK_MISC ->
18791 			 * this verifier states are not equivalent,
18792 			 * return false to continue verification of this path
18793 			 */
18794 			return false;
18795 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18796 			continue;
18797 		/* Both old and cur are having same slot_type */
18798 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18799 		case STACK_SPILL:
18800 			/* when explored and current stack slot are both storing
18801 			 * spilled registers, check that stored pointers types
18802 			 * are the same as well.
18803 			 * Ex: explored safe path could have stored
18804 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18805 			 * but current path has stored:
18806 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18807 			 * such verifier states are not equivalent.
18808 			 * return false to continue verification of this path
18809 			 */
18810 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18811 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18812 				return false;
18813 			break;
18814 		case STACK_DYNPTR:
18815 			old_reg = &old->stack[spi].spilled_ptr;
18816 			cur_reg = &cur->stack[spi].spilled_ptr;
18817 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18818 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18819 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18820 				return false;
18821 			break;
18822 		case STACK_ITER:
18823 			old_reg = &old->stack[spi].spilled_ptr;
18824 			cur_reg = &cur->stack[spi].spilled_ptr;
18825 			/* iter.depth is not compared between states as it
18826 			 * doesn't matter for correctness and would otherwise
18827 			 * prevent convergence; we maintain it only to prevent
18828 			 * infinite loop check triggering, see
18829 			 * iter_active_depths_differ()
18830 			 */
18831 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18832 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18833 			    old_reg->iter.state != cur_reg->iter.state ||
18834 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18835 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18836 				return false;
18837 			break;
18838 		case STACK_IRQ_FLAG:
18839 			old_reg = &old->stack[spi].spilled_ptr;
18840 			cur_reg = &cur->stack[spi].spilled_ptr;
18841 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
18842 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
18843 				return false;
18844 			break;
18845 		case STACK_MISC:
18846 		case STACK_ZERO:
18847 		case STACK_INVALID:
18848 			continue;
18849 		/* Ensure that new unhandled slot types return false by default */
18850 		default:
18851 			return false;
18852 		}
18853 	}
18854 	return true;
18855 }
18856 
refsafe(struct bpf_verifier_state * old,struct bpf_verifier_state * cur,struct bpf_idmap * idmap)18857 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18858 		    struct bpf_idmap *idmap)
18859 {
18860 	int i;
18861 
18862 	if (old->acquired_refs != cur->acquired_refs)
18863 		return false;
18864 
18865 	if (old->active_locks != cur->active_locks)
18866 		return false;
18867 
18868 	if (old->active_preempt_locks != cur->active_preempt_locks)
18869 		return false;
18870 
18871 	if (old->active_rcu_lock != cur->active_rcu_lock)
18872 		return false;
18873 
18874 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18875 		return false;
18876 
18877 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
18878 	    old->active_lock_ptr != cur->active_lock_ptr)
18879 		return false;
18880 
18881 	for (i = 0; i < old->acquired_refs; i++) {
18882 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18883 		    old->refs[i].type != cur->refs[i].type)
18884 			return false;
18885 		switch (old->refs[i].type) {
18886 		case REF_TYPE_PTR:
18887 		case REF_TYPE_IRQ:
18888 			break;
18889 		case REF_TYPE_LOCK:
18890 		case REF_TYPE_RES_LOCK:
18891 		case REF_TYPE_RES_LOCK_IRQ:
18892 			if (old->refs[i].ptr != cur->refs[i].ptr)
18893 				return false;
18894 			break;
18895 		default:
18896 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
18897 			return false;
18898 		}
18899 	}
18900 
18901 	return true;
18902 }
18903 
18904 /* compare two verifier states
18905  *
18906  * all states stored in state_list are known to be valid, since
18907  * verifier reached 'bpf_exit' instruction through them
18908  *
18909  * this function is called when verifier exploring different branches of
18910  * execution popped from the state stack. If it sees an old state that has
18911  * more strict register state and more strict stack state then this execution
18912  * branch doesn't need to be explored further, since verifier already
18913  * concluded that more strict state leads to valid finish.
18914  *
18915  * Therefore two states are equivalent if register state is more conservative
18916  * and explored stack state is more conservative than the current one.
18917  * Example:
18918  *       explored                   current
18919  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
18920  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
18921  *
18922  * In other words if current stack state (one being explored) has more
18923  * valid slots than old one that already passed validation, it means
18924  * the verifier can stop exploring and conclude that current state is valid too
18925  *
18926  * Similarly with registers. If explored state has register type as invalid
18927  * whereas register type in current state is meaningful, it means that
18928  * the current state will reach 'bpf_exit' instruction safely
18929  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,u32 insn_idx,enum exact_level exact)18930 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
18931 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
18932 {
18933 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
18934 	u16 i;
18935 
18936 	if (old->callback_depth > cur->callback_depth)
18937 		return false;
18938 
18939 	for (i = 0; i < MAX_BPF_REG; i++)
18940 		if (((1 << i) & live_regs) &&
18941 		    !regsafe(env, &old->regs[i], &cur->regs[i],
18942 			     &env->idmap_scratch, exact))
18943 			return false;
18944 
18945 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
18946 		return false;
18947 
18948 	return true;
18949 }
18950 
reset_idmap_scratch(struct bpf_verifier_env * env)18951 static void reset_idmap_scratch(struct bpf_verifier_env *env)
18952 {
18953 	env->idmap_scratch.tmp_id_gen = env->id_gen;
18954 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
18955 }
18956 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,enum exact_level exact)18957 static bool states_equal(struct bpf_verifier_env *env,
18958 			 struct bpf_verifier_state *old,
18959 			 struct bpf_verifier_state *cur,
18960 			 enum exact_level exact)
18961 {
18962 	u32 insn_idx;
18963 	int i;
18964 
18965 	if (old->curframe != cur->curframe)
18966 		return false;
18967 
18968 	reset_idmap_scratch(env);
18969 
18970 	/* Verification state from speculative execution simulation
18971 	 * must never prune a non-speculative execution one.
18972 	 */
18973 	if (old->speculative && !cur->speculative)
18974 		return false;
18975 
18976 	if (old->in_sleepable != cur->in_sleepable)
18977 		return false;
18978 
18979 	if (!refsafe(old, cur, &env->idmap_scratch))
18980 		return false;
18981 
18982 	/* for states to be equal callsites have to be the same
18983 	 * and all frame states need to be equivalent
18984 	 */
18985 	for (i = 0; i <= old->curframe; i++) {
18986 		insn_idx = frame_insn_idx(old, i);
18987 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
18988 			return false;
18989 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
18990 			return false;
18991 	}
18992 	return true;
18993 }
18994 
18995 /* Return 0 if no propagation happened. Return negative error code if error
18996  * happened. Otherwise, return the propagated bit.
18997  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)18998 static int propagate_liveness_reg(struct bpf_verifier_env *env,
18999 				  struct bpf_reg_state *reg,
19000 				  struct bpf_reg_state *parent_reg)
19001 {
19002 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
19003 	u8 flag = reg->live & REG_LIVE_READ;
19004 	int err;
19005 
19006 	/* When comes here, read flags of PARENT_REG or REG could be any of
19007 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
19008 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
19009 	 */
19010 	if (parent_flag == REG_LIVE_READ64 ||
19011 	    /* Or if there is no read flag from REG. */
19012 	    !flag ||
19013 	    /* Or if the read flag from REG is the same as PARENT_REG. */
19014 	    parent_flag == flag)
19015 		return 0;
19016 
19017 	err = mark_reg_read(env, reg, parent_reg, flag);
19018 	if (err)
19019 		return err;
19020 
19021 	return flag;
19022 }
19023 
19024 /* A write screens off any subsequent reads; but write marks come from the
19025  * straight-line code between a state and its parent.  When we arrive at an
19026  * equivalent state (jump target or such) we didn't arrive by the straight-line
19027  * code, so read marks in the state must propagate to the parent regardless
19028  * of the state's write marks. That's what 'parent == state->parent' comparison
19029  * in mark_reg_read() is for.
19030  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent,bool * changed)19031 static int propagate_liveness(struct bpf_verifier_env *env,
19032 			      const struct bpf_verifier_state *vstate,
19033 			      struct bpf_verifier_state *vparent,
19034 			      bool *changed)
19035 {
19036 	struct bpf_reg_state *state_reg, *parent_reg;
19037 	struct bpf_func_state *state, *parent;
19038 	int i, frame, err = 0;
19039 	bool tmp = false;
19040 
19041 	changed = changed ?: &tmp;
19042 	if (vparent->curframe != vstate->curframe) {
19043 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
19044 		     vparent->curframe, vstate->curframe);
19045 		return -EFAULT;
19046 	}
19047 	/* Propagate read liveness of registers... */
19048 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
19049 	for (frame = 0; frame <= vstate->curframe; frame++) {
19050 		parent = vparent->frame[frame];
19051 		state = vstate->frame[frame];
19052 		parent_reg = parent->regs;
19053 		state_reg = state->regs;
19054 		/* We don't need to worry about FP liveness, it's read-only */
19055 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
19056 			err = propagate_liveness_reg(env, &state_reg[i],
19057 						     &parent_reg[i]);
19058 			if (err < 0)
19059 				return err;
19060 			*changed |= err > 0;
19061 			if (err == REG_LIVE_READ64)
19062 				mark_insn_zext(env, &parent_reg[i]);
19063 		}
19064 
19065 		/* Propagate stack slots. */
19066 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
19067 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
19068 			parent_reg = &parent->stack[i].spilled_ptr;
19069 			state_reg = &state->stack[i].spilled_ptr;
19070 			err = propagate_liveness_reg(env, state_reg,
19071 						     parent_reg);
19072 			*changed |= err > 0;
19073 			if (err < 0)
19074 				return err;
19075 		}
19076 	}
19077 	return 0;
19078 }
19079 
19080 /* find precise scalars in the previous equivalent state and
19081  * propagate them into the current state
19082  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool * changed)19083 static int propagate_precision(struct bpf_verifier_env *env,
19084 			       const struct bpf_verifier_state *old,
19085 			       struct bpf_verifier_state *cur,
19086 			       bool *changed)
19087 {
19088 	struct bpf_reg_state *state_reg;
19089 	struct bpf_func_state *state;
19090 	int i, err = 0, fr;
19091 	bool first;
19092 
19093 	for (fr = old->curframe; fr >= 0; fr--) {
19094 		state = old->frame[fr];
19095 		state_reg = state->regs;
19096 		first = true;
19097 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19098 			if (state_reg->type != SCALAR_VALUE ||
19099 			    !state_reg->precise ||
19100 			    !(state_reg->live & REG_LIVE_READ))
19101 				continue;
19102 			if (env->log.level & BPF_LOG_LEVEL2) {
19103 				if (first)
19104 					verbose(env, "frame %d: propagating r%d", fr, i);
19105 				else
19106 					verbose(env, ",r%d", i);
19107 			}
19108 			bt_set_frame_reg(&env->bt, fr, i);
19109 			first = false;
19110 		}
19111 
19112 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19113 			if (!is_spilled_reg(&state->stack[i]))
19114 				continue;
19115 			state_reg = &state->stack[i].spilled_ptr;
19116 			if (state_reg->type != SCALAR_VALUE ||
19117 			    !state_reg->precise ||
19118 			    !(state_reg->live & REG_LIVE_READ))
19119 				continue;
19120 			if (env->log.level & BPF_LOG_LEVEL2) {
19121 				if (first)
19122 					verbose(env, "frame %d: propagating fp%d",
19123 						fr, (-i - 1) * BPF_REG_SIZE);
19124 				else
19125 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19126 			}
19127 			bt_set_frame_slot(&env->bt, fr, i);
19128 			first = false;
19129 		}
19130 		if (!first)
19131 			verbose(env, "\n");
19132 	}
19133 
19134 	err = __mark_chain_precision(env, cur, -1, changed);
19135 	if (err < 0)
19136 		return err;
19137 
19138 	return 0;
19139 }
19140 
19141 #define MAX_BACKEDGE_ITERS 64
19142 
19143 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19144  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19145  * then free visit->backedges.
19146  * After execution of this function incomplete_read_marks() will return false
19147  * for all states corresponding to @visit->callchain.
19148  */
propagate_backedges(struct bpf_verifier_env * env,struct bpf_scc_visit * visit)19149 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19150 {
19151 	struct bpf_scc_backedge *backedge;
19152 	struct bpf_verifier_state *st;
19153 	bool changed;
19154 	int i, err;
19155 
19156 	i = 0;
19157 	do {
19158 		if (i++ > MAX_BACKEDGE_ITERS) {
19159 			if (env->log.level & BPF_LOG_LEVEL2)
19160 				verbose(env, "%s: too many iterations\n", __func__);
19161 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19162 				mark_all_scalars_precise(env, &backedge->state);
19163 			break;
19164 		}
19165 		changed = false;
19166 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19167 			st = &backedge->state;
19168 			err = propagate_liveness(env, st->equal_state, st, &changed);
19169 			if (err)
19170 				return err;
19171 			err = propagate_precision(env, st->equal_state, st, &changed);
19172 			if (err)
19173 				return err;
19174 		}
19175 	} while (changed);
19176 
19177 	free_backedges(visit);
19178 	return 0;
19179 }
19180 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19181 static bool states_maybe_looping(struct bpf_verifier_state *old,
19182 				 struct bpf_verifier_state *cur)
19183 {
19184 	struct bpf_func_state *fold, *fcur;
19185 	int i, fr = cur->curframe;
19186 
19187 	if (old->curframe != fr)
19188 		return false;
19189 
19190 	fold = old->frame[fr];
19191 	fcur = cur->frame[fr];
19192 	for (i = 0; i < MAX_BPF_REG; i++)
19193 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19194 			   offsetof(struct bpf_reg_state, parent)))
19195 			return false;
19196 	return true;
19197 }
19198 
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)19199 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19200 {
19201 	return env->insn_aux_data[insn_idx].is_iter_next;
19202 }
19203 
19204 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19205  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19206  * states to match, which otherwise would look like an infinite loop. So while
19207  * iter_next() calls are taken care of, we still need to be careful and
19208  * prevent erroneous and too eager declaration of "infinite loop", when
19209  * iterators are involved.
19210  *
19211  * Here's a situation in pseudo-BPF assembly form:
19212  *
19213  *   0: again:                          ; set up iter_next() call args
19214  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19215  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19216  *   3:   if r0 == 0 goto done
19217  *   4:   ... something useful here ...
19218  *   5:   goto again                    ; another iteration
19219  *   6: done:
19220  *   7:   r1 = &it
19221  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19222  *   9:   exit
19223  *
19224  * This is a typical loop. Let's assume that we have a prune point at 1:,
19225  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19226  * again`, assuming other heuristics don't get in a way).
19227  *
19228  * When we first time come to 1:, let's say we have some state X. We proceed
19229  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19230  * Now we come back to validate that forked ACTIVE state. We proceed through
19231  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19232  * are converging. But the problem is that we don't know that yet, as this
19233  * convergence has to happen at iter_next() call site only. So if nothing is
19234  * done, at 1: verifier will use bounded loop logic and declare infinite
19235  * looping (and would be *technically* correct, if not for iterator's
19236  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19237  * don't want that. So what we do in process_iter_next_call() when we go on
19238  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19239  * a different iteration. So when we suspect an infinite loop, we additionally
19240  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19241  * pretend we are not looping and wait for next iter_next() call.
19242  *
19243  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19244  * loop, because that would actually mean infinite loop, as DRAINED state is
19245  * "sticky", and so we'll keep returning into the same instruction with the
19246  * same state (at least in one of possible code paths).
19247  *
19248  * This approach allows to keep infinite loop heuristic even in the face of
19249  * active iterator. E.g., C snippet below is and will be detected as
19250  * infinitely looping:
19251  *
19252  *   struct bpf_iter_num it;
19253  *   int *p, x;
19254  *
19255  *   bpf_iter_num_new(&it, 0, 10);
19256  *   while ((p = bpf_iter_num_next(&t))) {
19257  *       x = p;
19258  *       while (x--) {} // <<-- infinite loop here
19259  *   }
19260  *
19261  */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19262 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19263 {
19264 	struct bpf_reg_state *slot, *cur_slot;
19265 	struct bpf_func_state *state;
19266 	int i, fr;
19267 
19268 	for (fr = old->curframe; fr >= 0; fr--) {
19269 		state = old->frame[fr];
19270 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19271 			if (state->stack[i].slot_type[0] != STACK_ITER)
19272 				continue;
19273 
19274 			slot = &state->stack[i].spilled_ptr;
19275 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19276 				continue;
19277 
19278 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19279 			if (cur_slot->iter.depth != slot->iter.depth)
19280 				return true;
19281 		}
19282 	}
19283 	return false;
19284 }
19285 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)19286 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19287 {
19288 	struct bpf_verifier_state_list *new_sl;
19289 	struct bpf_verifier_state_list *sl;
19290 	struct bpf_verifier_state *cur = env->cur_state, *new;
19291 	bool force_new_state, add_new_state, loop;
19292 	int i, j, n, err, states_cnt = 0;
19293 	struct list_head *pos, *tmp, *head;
19294 
19295 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19296 			  /* Avoid accumulating infinitely long jmp history */
19297 			  cur->jmp_history_cnt > 40;
19298 
19299 	/* bpf progs typically have pruning point every 4 instructions
19300 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19301 	 * Do not add new state for future pruning if the verifier hasn't seen
19302 	 * at least 2 jumps and at least 8 instructions.
19303 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19304 	 * In tests that amounts to up to 50% reduction into total verifier
19305 	 * memory consumption and 20% verifier time speedup.
19306 	 */
19307 	add_new_state = force_new_state;
19308 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19309 	    env->insn_processed - env->prev_insn_processed >= 8)
19310 		add_new_state = true;
19311 
19312 	clean_live_states(env, insn_idx, cur);
19313 
19314 	loop = false;
19315 	head = explored_state(env, insn_idx);
19316 	list_for_each_safe(pos, tmp, head) {
19317 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19318 		states_cnt++;
19319 		if (sl->state.insn_idx != insn_idx)
19320 			continue;
19321 
19322 		if (sl->state.branches) {
19323 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19324 
19325 			if (frame->in_async_callback_fn &&
19326 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19327 				/* Different async_entry_cnt means that the verifier is
19328 				 * processing another entry into async callback.
19329 				 * Seeing the same state is not an indication of infinite
19330 				 * loop or infinite recursion.
19331 				 * But finding the same state doesn't mean that it's safe
19332 				 * to stop processing the current state. The previous state
19333 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19334 				 * Checking in_async_callback_fn alone is not enough either.
19335 				 * Since the verifier still needs to catch infinite loops
19336 				 * inside async callbacks.
19337 				 */
19338 				goto skip_inf_loop_check;
19339 			}
19340 			/* BPF open-coded iterators loop detection is special.
19341 			 * states_maybe_looping() logic is too simplistic in detecting
19342 			 * states that *might* be equivalent, because it doesn't know
19343 			 * about ID remapping, so don't even perform it.
19344 			 * See process_iter_next_call() and iter_active_depths_differ()
19345 			 * for overview of the logic. When current and one of parent
19346 			 * states are detected as equivalent, it's a good thing: we prove
19347 			 * convergence and can stop simulating further iterations.
19348 			 * It's safe to assume that iterator loop will finish, taking into
19349 			 * account iter_next() contract of eventually returning
19350 			 * sticky NULL result.
19351 			 *
19352 			 * Note, that states have to be compared exactly in this case because
19353 			 * read and precision marks might not be finalized inside the loop.
19354 			 * E.g. as in the program below:
19355 			 *
19356 			 *     1. r7 = -16
19357 			 *     2. r6 = bpf_get_prandom_u32()
19358 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19359 			 *     4.   if (r6 != 42) {
19360 			 *     5.     r7 = -32
19361 			 *     6.     r6 = bpf_get_prandom_u32()
19362 			 *     7.     continue
19363 			 *     8.   }
19364 			 *     9.   r0 = r10
19365 			 *    10.   r0 += r7
19366 			 *    11.   r8 = *(u64 *)(r0 + 0)
19367 			 *    12.   r6 = bpf_get_prandom_u32()
19368 			 *    13. }
19369 			 *
19370 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19371 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19372 			 * not have read or precision mark for r7 yet, thus inexact states
19373 			 * comparison would discard current state with r7=-32
19374 			 * => unsafe memory access at 11 would not be caught.
19375 			 */
19376 			if (is_iter_next_insn(env, insn_idx)) {
19377 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19378 					struct bpf_func_state *cur_frame;
19379 					struct bpf_reg_state *iter_state, *iter_reg;
19380 					int spi;
19381 
19382 					cur_frame = cur->frame[cur->curframe];
19383 					/* btf_check_iter_kfuncs() enforces that
19384 					 * iter state pointer is always the first arg
19385 					 */
19386 					iter_reg = &cur_frame->regs[BPF_REG_1];
19387 					/* current state is valid due to states_equal(),
19388 					 * so we can assume valid iter and reg state,
19389 					 * no need for extra (re-)validations
19390 					 */
19391 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19392 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19393 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19394 						loop = true;
19395 						goto hit;
19396 					}
19397 				}
19398 				goto skip_inf_loop_check;
19399 			}
19400 			if (is_may_goto_insn_at(env, insn_idx)) {
19401 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19402 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19403 					loop = true;
19404 					goto hit;
19405 				}
19406 			}
19407 			if (calls_callback(env, insn_idx)) {
19408 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19409 					goto hit;
19410 				goto skip_inf_loop_check;
19411 			}
19412 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19413 			if (states_maybe_looping(&sl->state, cur) &&
19414 			    states_equal(env, &sl->state, cur, EXACT) &&
19415 			    !iter_active_depths_differ(&sl->state, cur) &&
19416 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19417 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19418 				verbose_linfo(env, insn_idx, "; ");
19419 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19420 				verbose(env, "cur state:");
19421 				print_verifier_state(env, cur, cur->curframe, true);
19422 				verbose(env, "old state:");
19423 				print_verifier_state(env, &sl->state, cur->curframe, true);
19424 				return -EINVAL;
19425 			}
19426 			/* if the verifier is processing a loop, avoid adding new state
19427 			 * too often, since different loop iterations have distinct
19428 			 * states and may not help future pruning.
19429 			 * This threshold shouldn't be too low to make sure that
19430 			 * a loop with large bound will be rejected quickly.
19431 			 * The most abusive loop will be:
19432 			 * r1 += 1
19433 			 * if r1 < 1000000 goto pc-2
19434 			 * 1M insn_procssed limit / 100 == 10k peak states.
19435 			 * This threshold shouldn't be too high either, since states
19436 			 * at the end of the loop are likely to be useful in pruning.
19437 			 */
19438 skip_inf_loop_check:
19439 			if (!force_new_state &&
19440 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19441 			    env->insn_processed - env->prev_insn_processed < 100)
19442 				add_new_state = false;
19443 			goto miss;
19444 		}
19445 		/* See comments for mark_all_regs_read_and_precise() */
19446 		loop = incomplete_read_marks(env, &sl->state);
19447 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19448 hit:
19449 			sl->hit_cnt++;
19450 			/* reached equivalent register/stack state,
19451 			 * prune the search.
19452 			 * Registers read by the continuation are read by us.
19453 			 * If we have any write marks in env->cur_state, they
19454 			 * will prevent corresponding reads in the continuation
19455 			 * from reaching our parent (an explored_state).  Our
19456 			 * own state will get the read marks recorded, but
19457 			 * they'll be immediately forgotten as we're pruning
19458 			 * this state and will pop a new one.
19459 			 */
19460 			err = propagate_liveness(env, &sl->state, cur, NULL);
19461 
19462 			/* if previous state reached the exit with precision and
19463 			 * current state is equivalent to it (except precision marks)
19464 			 * the precision needs to be propagated back in
19465 			 * the current state.
19466 			 */
19467 			if (is_jmp_point(env, env->insn_idx))
19468 				err = err ? : push_jmp_history(env, cur, 0, 0);
19469 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19470 			if (err)
19471 				return err;
19472 			/* When processing iterator based loops above propagate_liveness and
19473 			 * propagate_precision calls are not sufficient to transfer all relevant
19474 			 * read and precision marks. E.g. consider the following case:
19475 			 *
19476 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19477 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19478 			 *  |   v   v  At this point, state C is not processed yet, so state A
19479 			 *  '-- B   C  has not received any read or precision marks from C.
19480 			 *             Thus, marks propagated from A to B are incomplete.
19481 			 *
19482 			 * The verifier mitigates this by performing the following steps:
19483 			 *
19484 			 * - Prior to the main verification pass, strongly connected components
19485 			 *   (SCCs) are computed over the program's control flow graph,
19486 			 *   intraprocedurally.
19487 			 *
19488 			 * - During the main verification pass, `maybe_enter_scc()` checks
19489 			 *   whether the current verifier state is entering an SCC. If so, an
19490 			 *   instance of a `bpf_scc_visit` object is created, and the state
19491 			 *   entering the SCC is recorded as the entry state.
19492 			 *
19493 			 * - This instance is associated not with the SCC itself, but with a
19494 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19495 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19496 			 *
19497 			 * - When a verification path encounters a `states_equal(...,
19498 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19499 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19500 			 *   of the current state is created and added to
19501 			 *   `bpf_scc_visit->backedges`.
19502 			 *
19503 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19504 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19505 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19506 			 *   instance. If it is, this indicates that all paths originating from
19507 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19508 			 *   called, which propagates read and precision marks through the
19509 			 *   backedges until a fixed point is reached.
19510 			 *   (In the earlier example, this would propagate marks from A to B,
19511 			 *    from C to A, and then again from A to B.)
19512 			 *
19513 			 * A note on callchains
19514 			 * --------------------
19515 			 *
19516 			 * Consider the following example:
19517 			 *
19518 			 *     void foo() { loop { ... SCC#1 ... } }
19519 			 *     void main() {
19520 			 *       A: foo();
19521 			 *       B: ...
19522 			 *       C: foo();
19523 			 *     }
19524 			 *
19525 			 * Here, there are two distinct callchains leading to SCC#1:
19526 			 * - (A, SCC#1)
19527 			 * - (C, SCC#1)
19528 			 *
19529 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19530 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19531 			 * functions traverse the parent state of each backedge state, which
19532 			 * means these parent states must remain valid (i.e., not freed) while
19533 			 * the corresponding `bpf_scc_visit` instance exists.
19534 			 *
19535 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19536 			 * callchains would break this invariant:
19537 			 * - States explored during `C: foo()` would contribute backedges to
19538 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
19539 			 *   `A: foo()` completes.
19540 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
19541 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
19542 			 *   links for states from `C: foo()` to become invalid.
19543 			 */
19544 			if (loop) {
19545 				struct bpf_scc_backedge *backedge;
19546 
19547 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19548 				if (!backedge)
19549 					return -ENOMEM;
19550 				err = copy_verifier_state(&backedge->state, cur);
19551 				backedge->state.equal_state = &sl->state;
19552 				backedge->state.insn_idx = insn_idx;
19553 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
19554 				if (err) {
19555 					free_verifier_state(&backedge->state, false);
19556 					kvfree(backedge);
19557 					return err;
19558 				}
19559 			}
19560 			return 1;
19561 		}
19562 miss:
19563 		/* when new state is not going to be added do not increase miss count.
19564 		 * Otherwise several loop iterations will remove the state
19565 		 * recorded earlier. The goal of these heuristics is to have
19566 		 * states from some iterations of the loop (some in the beginning
19567 		 * and some at the end) to help pruning.
19568 		 */
19569 		if (add_new_state)
19570 			sl->miss_cnt++;
19571 		/* heuristic to determine whether this state is beneficial
19572 		 * to keep checking from state equivalence point of view.
19573 		 * Higher numbers increase max_states_per_insn and verification time,
19574 		 * but do not meaningfully decrease insn_processed.
19575 		 * 'n' controls how many times state could miss before eviction.
19576 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19577 		 * too early would hinder iterator convergence.
19578 		 */
19579 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19580 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19581 			/* the state is unlikely to be useful. Remove it to
19582 			 * speed up verification
19583 			 */
19584 			sl->in_free_list = true;
19585 			list_del(&sl->node);
19586 			list_add(&sl->node, &env->free_list);
19587 			env->free_list_size++;
19588 			env->explored_states_size--;
19589 			maybe_free_verifier_state(env, sl);
19590 		}
19591 	}
19592 
19593 	if (env->max_states_per_insn < states_cnt)
19594 		env->max_states_per_insn = states_cnt;
19595 
19596 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
19597 		return 0;
19598 
19599 	if (!add_new_state)
19600 		return 0;
19601 
19602 	/* There were no equivalent states, remember the current one.
19603 	 * Technically the current state is not proven to be safe yet,
19604 	 * but it will either reach outer most bpf_exit (which means it's safe)
19605 	 * or it will be rejected. When there are no loops the verifier won't be
19606 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
19607 	 * again on the way to bpf_exit.
19608 	 * When looping the sl->state.branches will be > 0 and this state
19609 	 * will not be considered for equivalence until branches == 0.
19610 	 */
19611 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
19612 	if (!new_sl)
19613 		return -ENOMEM;
19614 	env->total_states++;
19615 	env->explored_states_size++;
19616 	update_peak_states(env);
19617 	env->prev_jmps_processed = env->jmps_processed;
19618 	env->prev_insn_processed = env->insn_processed;
19619 
19620 	/* forget precise markings we inherited, see __mark_chain_precision */
19621 	if (env->bpf_capable)
19622 		mark_all_scalars_imprecise(env, cur);
19623 
19624 	/* add new state to the head of linked list */
19625 	new = &new_sl->state;
19626 	err = copy_verifier_state(new, cur);
19627 	if (err) {
19628 		free_verifier_state(new, false);
19629 		kfree(new_sl);
19630 		return err;
19631 	}
19632 	new->insn_idx = insn_idx;
19633 	verifier_bug_if(new->branches != 1, env,
19634 			"%s:branches_to_explore=%d insn %d",
19635 			__func__, new->branches, insn_idx);
19636 	err = maybe_enter_scc(env, new);
19637 	if (err) {
19638 		free_verifier_state(new, false);
19639 		kvfree(new_sl);
19640 		return err;
19641 	}
19642 
19643 	cur->parent = new;
19644 	cur->first_insn_idx = insn_idx;
19645 	cur->dfs_depth = new->dfs_depth + 1;
19646 	clear_jmp_history(cur);
19647 	list_add(&new_sl->node, head);
19648 
19649 	/* connect new state to parentage chain. Current frame needs all
19650 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
19651 	 * to the stack implicitly by JITs) so in callers' frames connect just
19652 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
19653 	 * the state of the call instruction (with WRITTEN set), and r0 comes
19654 	 * from callee with its full parentage chain, anyway.
19655 	 */
19656 	/* clear write marks in current state: the writes we did are not writes
19657 	 * our child did, so they don't screen off its reads from us.
19658 	 * (There are no read marks in current state, because reads always mark
19659 	 * their parent and current state never has children yet.  Only
19660 	 * explored_states can get read marks.)
19661 	 */
19662 	for (j = 0; j <= cur->curframe; j++) {
19663 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
19664 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
19665 		for (i = 0; i < BPF_REG_FP; i++)
19666 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
19667 	}
19668 
19669 	/* all stack frames are accessible from callee, clear them all */
19670 	for (j = 0; j <= cur->curframe; j++) {
19671 		struct bpf_func_state *frame = cur->frame[j];
19672 		struct bpf_func_state *newframe = new->frame[j];
19673 
19674 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
19675 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
19676 			frame->stack[i].spilled_ptr.parent =
19677 						&newframe->stack[i].spilled_ptr;
19678 		}
19679 	}
19680 	return 0;
19681 }
19682 
19683 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)19684 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19685 {
19686 	switch (base_type(type)) {
19687 	case PTR_TO_CTX:
19688 	case PTR_TO_SOCKET:
19689 	case PTR_TO_SOCK_COMMON:
19690 	case PTR_TO_TCP_SOCK:
19691 	case PTR_TO_XDP_SOCK:
19692 	case PTR_TO_BTF_ID:
19693 	case PTR_TO_ARENA:
19694 		return false;
19695 	default:
19696 		return true;
19697 	}
19698 }
19699 
19700 /* If an instruction was previously used with particular pointer types, then we
19701  * need to be careful to avoid cases such as the below, where it may be ok
19702  * for one branch accessing the pointer, but not ok for the other branch:
19703  *
19704  * R1 = sock_ptr
19705  * goto X;
19706  * ...
19707  * R1 = some_other_valid_ptr;
19708  * goto X;
19709  * ...
19710  * R2 = *(u32 *)(R1 + 0);
19711  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)19712 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19713 {
19714 	return src != prev && (!reg_type_mismatch_ok(src) ||
19715 			       !reg_type_mismatch_ok(prev));
19716 }
19717 
is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)19718 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
19719 {
19720 	switch (base_type(type)) {
19721 	case PTR_TO_MEM:
19722 	case PTR_TO_BTF_ID:
19723 		return true;
19724 	default:
19725 		return false;
19726 	}
19727 }
19728 
is_ptr_to_mem(enum bpf_reg_type type)19729 static bool is_ptr_to_mem(enum bpf_reg_type type)
19730 {
19731 	return base_type(type) == PTR_TO_MEM;
19732 }
19733 
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_mismatch)19734 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19735 			     bool allow_trust_mismatch)
19736 {
19737 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19738 	enum bpf_reg_type merged_type;
19739 
19740 	if (*prev_type == NOT_INIT) {
19741 		/* Saw a valid insn
19742 		 * dst_reg = *(u32 *)(src_reg + off)
19743 		 * save type to validate intersecting paths
19744 		 */
19745 		*prev_type = type;
19746 	} else if (reg_type_mismatch(type, *prev_type)) {
19747 		/* Abuser program is trying to use the same insn
19748 		 * dst_reg = *(u32*) (src_reg + off)
19749 		 * with different pointer types:
19750 		 * src_reg == ctx in one branch and
19751 		 * src_reg == stack|map in some other branch.
19752 		 * Reject it.
19753 		 */
19754 		if (allow_trust_mismatch &&
19755 		    is_ptr_to_mem_or_btf_id(type) &&
19756 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
19757 			/*
19758 			 * Have to support a use case when one path through
19759 			 * the program yields TRUSTED pointer while another
19760 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
19761 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
19762 			 * Same behavior of MEM_RDONLY flag.
19763 			 */
19764 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
19765 				merged_type = PTR_TO_MEM;
19766 			else
19767 				merged_type = PTR_TO_BTF_ID;
19768 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
19769 				merged_type |= PTR_UNTRUSTED;
19770 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
19771 				merged_type |= MEM_RDONLY;
19772 			*prev_type = merged_type;
19773 		} else {
19774 			verbose(env, "same insn cannot be used with different pointers\n");
19775 			return -EINVAL;
19776 		}
19777 	}
19778 
19779 	return 0;
19780 }
19781 
19782 enum {
19783 	PROCESS_BPF_EXIT = 1
19784 };
19785 
process_bpf_exit_full(struct bpf_verifier_env * env,bool * do_print_state,bool exception_exit)19786 static int process_bpf_exit_full(struct bpf_verifier_env *env,
19787 				 bool *do_print_state,
19788 				 bool exception_exit)
19789 {
19790 	/* We must do check_reference_leak here before
19791 	 * prepare_func_exit to handle the case when
19792 	 * state->curframe > 0, it may be a callback function,
19793 	 * for which reference_state must match caller reference
19794 	 * state when it exits.
19795 	 */
19796 	int err = check_resource_leak(env, exception_exit,
19797 				      !env->cur_state->curframe,
19798 				      "BPF_EXIT instruction in main prog");
19799 	if (err)
19800 		return err;
19801 
19802 	/* The side effect of the prepare_func_exit which is
19803 	 * being skipped is that it frees bpf_func_state.
19804 	 * Typically, process_bpf_exit will only be hit with
19805 	 * outermost exit. copy_verifier_state in pop_stack will
19806 	 * handle freeing of any extra bpf_func_state left over
19807 	 * from not processing all nested function exits. We
19808 	 * also skip return code checks as they are not needed
19809 	 * for exceptional exits.
19810 	 */
19811 	if (exception_exit)
19812 		return PROCESS_BPF_EXIT;
19813 
19814 	if (env->cur_state->curframe) {
19815 		/* exit from nested function */
19816 		err = prepare_func_exit(env, &env->insn_idx);
19817 		if (err)
19818 			return err;
19819 		*do_print_state = true;
19820 		return 0;
19821 	}
19822 
19823 	err = check_return_code(env, BPF_REG_0, "R0");
19824 	if (err)
19825 		return err;
19826 	return PROCESS_BPF_EXIT;
19827 }
19828 
do_check_insn(struct bpf_verifier_env * env,bool * do_print_state)19829 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
19830 {
19831 	int err;
19832 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
19833 	u8 class = BPF_CLASS(insn->code);
19834 
19835 	if (class == BPF_ALU || class == BPF_ALU64) {
19836 		err = check_alu_op(env, insn);
19837 		if (err)
19838 			return err;
19839 
19840 	} else if (class == BPF_LDX) {
19841 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
19842 
19843 		/* Check for reserved fields is already done in
19844 		 * resolve_pseudo_ldimm64().
19845 		 */
19846 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
19847 		if (err)
19848 			return err;
19849 	} else if (class == BPF_STX) {
19850 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19851 			err = check_atomic(env, insn);
19852 			if (err)
19853 				return err;
19854 			env->insn_idx++;
19855 			return 0;
19856 		}
19857 
19858 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19859 			verbose(env, "BPF_STX uses reserved fields\n");
19860 			return -EINVAL;
19861 		}
19862 
19863 		err = check_store_reg(env, insn, false);
19864 		if (err)
19865 			return err;
19866 	} else if (class == BPF_ST) {
19867 		enum bpf_reg_type dst_reg_type;
19868 
19869 		if (BPF_MODE(insn->code) != BPF_MEM ||
19870 		    insn->src_reg != BPF_REG_0) {
19871 			verbose(env, "BPF_ST uses reserved fields\n");
19872 			return -EINVAL;
19873 		}
19874 		/* check src operand */
19875 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19876 		if (err)
19877 			return err;
19878 
19879 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
19880 
19881 		/* check that memory (dst_reg + off) is writeable */
19882 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19883 				       insn->off, BPF_SIZE(insn->code),
19884 				       BPF_WRITE, -1, false, false);
19885 		if (err)
19886 			return err;
19887 
19888 		err = save_aux_ptr_type(env, dst_reg_type, false);
19889 		if (err)
19890 			return err;
19891 	} else if (class == BPF_JMP || class == BPF_JMP32) {
19892 		u8 opcode = BPF_OP(insn->code);
19893 
19894 		env->jmps_processed++;
19895 		if (opcode == BPF_CALL) {
19896 			if (BPF_SRC(insn->code) != BPF_K ||
19897 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
19898 			     insn->off != 0) ||
19899 			    (insn->src_reg != BPF_REG_0 &&
19900 			     insn->src_reg != BPF_PSEUDO_CALL &&
19901 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19902 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
19903 				verbose(env, "BPF_CALL uses reserved fields\n");
19904 				return -EINVAL;
19905 			}
19906 
19907 			if (env->cur_state->active_locks) {
19908 				if ((insn->src_reg == BPF_REG_0 &&
19909 				     insn->imm != BPF_FUNC_spin_unlock) ||
19910 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19911 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19912 					verbose(env,
19913 						"function calls are not allowed while holding a lock\n");
19914 					return -EINVAL;
19915 				}
19916 			}
19917 			if (insn->src_reg == BPF_PSEUDO_CALL) {
19918 				err = check_func_call(env, insn, &env->insn_idx);
19919 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19920 				err = check_kfunc_call(env, insn, &env->insn_idx);
19921 				if (!err && is_bpf_throw_kfunc(insn))
19922 					return process_bpf_exit_full(env, do_print_state, true);
19923 			} else {
19924 				err = check_helper_call(env, insn, &env->insn_idx);
19925 			}
19926 			if (err)
19927 				return err;
19928 
19929 			mark_reg_scratched(env, BPF_REG_0);
19930 		} else if (opcode == BPF_JA) {
19931 			if (BPF_SRC(insn->code) != BPF_K ||
19932 			    insn->src_reg != BPF_REG_0 ||
19933 			    insn->dst_reg != BPF_REG_0 ||
19934 			    (class == BPF_JMP && insn->imm != 0) ||
19935 			    (class == BPF_JMP32 && insn->off != 0)) {
19936 				verbose(env, "BPF_JA uses reserved fields\n");
19937 				return -EINVAL;
19938 			}
19939 
19940 			if (class == BPF_JMP)
19941 				env->insn_idx += insn->off + 1;
19942 			else
19943 				env->insn_idx += insn->imm + 1;
19944 			return 0;
19945 		} else if (opcode == BPF_EXIT) {
19946 			if (BPF_SRC(insn->code) != BPF_K ||
19947 			    insn->imm != 0 ||
19948 			    insn->src_reg != BPF_REG_0 ||
19949 			    insn->dst_reg != BPF_REG_0 ||
19950 			    class == BPF_JMP32) {
19951 				verbose(env, "BPF_EXIT uses reserved fields\n");
19952 				return -EINVAL;
19953 			}
19954 			return process_bpf_exit_full(env, do_print_state, false);
19955 		} else {
19956 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
19957 			if (err)
19958 				return err;
19959 		}
19960 	} else if (class == BPF_LD) {
19961 		u8 mode = BPF_MODE(insn->code);
19962 
19963 		if (mode == BPF_ABS || mode == BPF_IND) {
19964 			err = check_ld_abs(env, insn);
19965 			if (err)
19966 				return err;
19967 
19968 		} else if (mode == BPF_IMM) {
19969 			err = check_ld_imm(env, insn);
19970 			if (err)
19971 				return err;
19972 
19973 			env->insn_idx++;
19974 			sanitize_mark_insn_seen(env);
19975 		} else {
19976 			verbose(env, "invalid BPF_LD mode\n");
19977 			return -EINVAL;
19978 		}
19979 	} else {
19980 		verbose(env, "unknown insn class %d\n", class);
19981 		return -EINVAL;
19982 	}
19983 
19984 	env->insn_idx++;
19985 	return 0;
19986 }
19987 
do_check(struct bpf_verifier_env * env)19988 static int do_check(struct bpf_verifier_env *env)
19989 {
19990 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19991 	struct bpf_verifier_state *state = env->cur_state;
19992 	struct bpf_insn *insns = env->prog->insnsi;
19993 	int insn_cnt = env->prog->len;
19994 	bool do_print_state = false;
19995 	int prev_insn_idx = -1;
19996 
19997 	for (;;) {
19998 		struct bpf_insn *insn;
19999 		struct bpf_insn_aux_data *insn_aux;
20000 		int err;
20001 
20002 		/* reset current history entry on each new instruction */
20003 		env->cur_hist_ent = NULL;
20004 
20005 		env->prev_insn_idx = prev_insn_idx;
20006 		if (env->insn_idx >= insn_cnt) {
20007 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
20008 				env->insn_idx, insn_cnt);
20009 			return -EFAULT;
20010 		}
20011 
20012 		insn = &insns[env->insn_idx];
20013 		insn_aux = &env->insn_aux_data[env->insn_idx];
20014 
20015 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20016 			verbose(env,
20017 				"BPF program is too large. Processed %d insn\n",
20018 				env->insn_processed);
20019 			return -E2BIG;
20020 		}
20021 
20022 		state->last_insn_idx = env->prev_insn_idx;
20023 		state->insn_idx = env->insn_idx;
20024 
20025 		if (is_prune_point(env, env->insn_idx)) {
20026 			err = is_state_visited(env, env->insn_idx);
20027 			if (err < 0)
20028 				return err;
20029 			if (err == 1) {
20030 				/* found equivalent state, can prune the search */
20031 				if (env->log.level & BPF_LOG_LEVEL) {
20032 					if (do_print_state)
20033 						verbose(env, "\nfrom %d to %d%s: safe\n",
20034 							env->prev_insn_idx, env->insn_idx,
20035 							env->cur_state->speculative ?
20036 							" (speculative execution)" : "");
20037 					else
20038 						verbose(env, "%d: safe\n", env->insn_idx);
20039 				}
20040 				goto process_bpf_exit;
20041 			}
20042 		}
20043 
20044 		if (is_jmp_point(env, env->insn_idx)) {
20045 			err = push_jmp_history(env, state, 0, 0);
20046 			if (err)
20047 				return err;
20048 		}
20049 
20050 		if (signal_pending(current))
20051 			return -EAGAIN;
20052 
20053 		if (need_resched())
20054 			cond_resched();
20055 
20056 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20057 			verbose(env, "\nfrom %d to %d%s:",
20058 				env->prev_insn_idx, env->insn_idx,
20059 				env->cur_state->speculative ?
20060 				" (speculative execution)" : "");
20061 			print_verifier_state(env, state, state->curframe, true);
20062 			do_print_state = false;
20063 		}
20064 
20065 		if (env->log.level & BPF_LOG_LEVEL) {
20066 			if (verifier_state_scratched(env))
20067 				print_insn_state(env, state, state->curframe);
20068 
20069 			verbose_linfo(env, env->insn_idx, "; ");
20070 			env->prev_log_pos = env->log.end_pos;
20071 			verbose(env, "%d: ", env->insn_idx);
20072 			verbose_insn(env, insn);
20073 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20074 			env->prev_log_pos = env->log.end_pos;
20075 		}
20076 
20077 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20078 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20079 							   env->prev_insn_idx);
20080 			if (err)
20081 				return err;
20082 		}
20083 
20084 		sanitize_mark_insn_seen(env);
20085 		prev_insn_idx = env->insn_idx;
20086 
20087 		/* Reduce verification complexity by stopping speculative path
20088 		 * verification when a nospec is encountered.
20089 		 */
20090 		if (state->speculative && insn_aux->nospec)
20091 			goto process_bpf_exit;
20092 
20093 		err = do_check_insn(env, &do_print_state);
20094 		if (error_recoverable_with_nospec(err) && state->speculative) {
20095 			/* Prevent this speculative path from ever reaching the
20096 			 * insn that would have been unsafe to execute.
20097 			 */
20098 			insn_aux->nospec = true;
20099 			/* If it was an ADD/SUB insn, potentially remove any
20100 			 * markings for alu sanitization.
20101 			 */
20102 			insn_aux->alu_state = 0;
20103 			goto process_bpf_exit;
20104 		} else if (err < 0) {
20105 			return err;
20106 		} else if (err == PROCESS_BPF_EXIT) {
20107 			goto process_bpf_exit;
20108 		}
20109 		WARN_ON_ONCE(err);
20110 
20111 		if (state->speculative && insn_aux->nospec_result) {
20112 			/* If we are on a path that performed a jump-op, this
20113 			 * may skip a nospec patched-in after the jump. This can
20114 			 * currently never happen because nospec_result is only
20115 			 * used for the write-ops
20116 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20117 			 * never skip the following insn. Still, add a warning
20118 			 * to document this in case nospec_result is used
20119 			 * elsewhere in the future.
20120 			 *
20121 			 * All non-branch instructions have a single
20122 			 * fall-through edge. For these, nospec_result should
20123 			 * already work.
20124 			 */
20125 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20126 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20127 					    "speculation barrier after jump instruction may not have the desired effect"))
20128 				return -EFAULT;
20129 process_bpf_exit:
20130 			mark_verifier_state_scratched(env);
20131 			err = update_branch_counts(env, env->cur_state);
20132 			if (err)
20133 				return err;
20134 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20135 					pop_log);
20136 			if (err < 0) {
20137 				if (err != -ENOENT)
20138 					return err;
20139 				break;
20140 			} else {
20141 				do_print_state = true;
20142 				continue;
20143 			}
20144 		}
20145 	}
20146 
20147 	return 0;
20148 }
20149 
find_btf_percpu_datasec(struct btf * btf)20150 static int find_btf_percpu_datasec(struct btf *btf)
20151 {
20152 	const struct btf_type *t;
20153 	const char *tname;
20154 	int i, n;
20155 
20156 	/*
20157 	 * Both vmlinux and module each have their own ".data..percpu"
20158 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20159 	 * types to look at only module's own BTF types.
20160 	 */
20161 	n = btf_nr_types(btf);
20162 	if (btf_is_module(btf))
20163 		i = btf_nr_types(btf_vmlinux);
20164 	else
20165 		i = 1;
20166 
20167 	for(; i < n; i++) {
20168 		t = btf_type_by_id(btf, i);
20169 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20170 			continue;
20171 
20172 		tname = btf_name_by_offset(btf, t->name_off);
20173 		if (!strcmp(tname, ".data..percpu"))
20174 			return i;
20175 	}
20176 
20177 	return -ENOENT;
20178 }
20179 
20180 /*
20181  * Add btf to the used_btfs array and return the index. (If the btf was
20182  * already added, then just return the index.) Upon successful insertion
20183  * increase btf refcnt, and, if present, also refcount the corresponding
20184  * kernel module.
20185  */
__add_used_btf(struct bpf_verifier_env * env,struct btf * btf)20186 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20187 {
20188 	struct btf_mod_pair *btf_mod;
20189 	int i;
20190 
20191 	/* check whether we recorded this BTF (and maybe module) already */
20192 	for (i = 0; i < env->used_btf_cnt; i++)
20193 		if (env->used_btfs[i].btf == btf)
20194 			return i;
20195 
20196 	if (env->used_btf_cnt >= MAX_USED_BTFS)
20197 		return -E2BIG;
20198 
20199 	btf_get(btf);
20200 
20201 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20202 	btf_mod->btf = btf;
20203 	btf_mod->module = NULL;
20204 
20205 	/* if we reference variables from kernel module, bump its refcount */
20206 	if (btf_is_module(btf)) {
20207 		btf_mod->module = btf_try_get_module(btf);
20208 		if (!btf_mod->module) {
20209 			btf_put(btf);
20210 			return -ENXIO;
20211 		}
20212 	}
20213 
20214 	return env->used_btf_cnt++;
20215 }
20216 
20217 /* replace pseudo btf_id with kernel symbol address */
__check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux,struct btf * btf)20218 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20219 				 struct bpf_insn *insn,
20220 				 struct bpf_insn_aux_data *aux,
20221 				 struct btf *btf)
20222 {
20223 	const struct btf_var_secinfo *vsi;
20224 	const struct btf_type *datasec;
20225 	const struct btf_type *t;
20226 	const char *sym_name;
20227 	bool percpu = false;
20228 	u32 type, id = insn->imm;
20229 	s32 datasec_id;
20230 	u64 addr;
20231 	int i;
20232 
20233 	t = btf_type_by_id(btf, id);
20234 	if (!t) {
20235 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20236 		return -ENOENT;
20237 	}
20238 
20239 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20240 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20241 		return -EINVAL;
20242 	}
20243 
20244 	sym_name = btf_name_by_offset(btf, t->name_off);
20245 	addr = kallsyms_lookup_name(sym_name);
20246 	if (!addr) {
20247 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20248 			sym_name);
20249 		return -ENOENT;
20250 	}
20251 	insn[0].imm = (u32)addr;
20252 	insn[1].imm = addr >> 32;
20253 
20254 	if (btf_type_is_func(t)) {
20255 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20256 		aux->btf_var.mem_size = 0;
20257 		return 0;
20258 	}
20259 
20260 	datasec_id = find_btf_percpu_datasec(btf);
20261 	if (datasec_id > 0) {
20262 		datasec = btf_type_by_id(btf, datasec_id);
20263 		for_each_vsi(i, datasec, vsi) {
20264 			if (vsi->type == id) {
20265 				percpu = true;
20266 				break;
20267 			}
20268 		}
20269 	}
20270 
20271 	type = t->type;
20272 	t = btf_type_skip_modifiers(btf, type, NULL);
20273 	if (percpu) {
20274 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20275 		aux->btf_var.btf = btf;
20276 		aux->btf_var.btf_id = type;
20277 	} else if (!btf_type_is_struct(t)) {
20278 		const struct btf_type *ret;
20279 		const char *tname;
20280 		u32 tsize;
20281 
20282 		/* resolve the type size of ksym. */
20283 		ret = btf_resolve_size(btf, t, &tsize);
20284 		if (IS_ERR(ret)) {
20285 			tname = btf_name_by_offset(btf, t->name_off);
20286 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20287 				tname, PTR_ERR(ret));
20288 			return -EINVAL;
20289 		}
20290 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20291 		aux->btf_var.mem_size = tsize;
20292 	} else {
20293 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20294 		aux->btf_var.btf = btf;
20295 		aux->btf_var.btf_id = type;
20296 	}
20297 
20298 	return 0;
20299 }
20300 
check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux)20301 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20302 			       struct bpf_insn *insn,
20303 			       struct bpf_insn_aux_data *aux)
20304 {
20305 	struct btf *btf;
20306 	int btf_fd;
20307 	int err;
20308 
20309 	btf_fd = insn[1].imm;
20310 	if (btf_fd) {
20311 		CLASS(fd, f)(btf_fd);
20312 
20313 		btf = __btf_get_by_fd(f);
20314 		if (IS_ERR(btf)) {
20315 			verbose(env, "invalid module BTF object FD specified.\n");
20316 			return -EINVAL;
20317 		}
20318 	} else {
20319 		if (!btf_vmlinux) {
20320 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20321 			return -EINVAL;
20322 		}
20323 		btf = btf_vmlinux;
20324 	}
20325 
20326 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20327 	if (err)
20328 		return err;
20329 
20330 	err = __add_used_btf(env, btf);
20331 	if (err < 0)
20332 		return err;
20333 	return 0;
20334 }
20335 
is_tracing_prog_type(enum bpf_prog_type type)20336 static bool is_tracing_prog_type(enum bpf_prog_type type)
20337 {
20338 	switch (type) {
20339 	case BPF_PROG_TYPE_KPROBE:
20340 	case BPF_PROG_TYPE_TRACEPOINT:
20341 	case BPF_PROG_TYPE_PERF_EVENT:
20342 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20343 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20344 		return true;
20345 	default:
20346 		return false;
20347 	}
20348 }
20349 
bpf_map_is_cgroup_storage(struct bpf_map * map)20350 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20351 {
20352 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20353 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20354 }
20355 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)20356 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20357 					struct bpf_map *map,
20358 					struct bpf_prog *prog)
20359 
20360 {
20361 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20362 
20363 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20364 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20365 		if (is_tracing_prog_type(prog_type)) {
20366 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20367 			return -EINVAL;
20368 		}
20369 	}
20370 
20371 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20372 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20373 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20374 			return -EINVAL;
20375 		}
20376 
20377 		if (is_tracing_prog_type(prog_type)) {
20378 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20379 			return -EINVAL;
20380 		}
20381 	}
20382 
20383 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20384 		if (is_tracing_prog_type(prog_type)) {
20385 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20386 			return -EINVAL;
20387 		}
20388 	}
20389 
20390 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20391 		if (is_tracing_prog_type(prog_type)) {
20392 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20393 			return -EINVAL;
20394 		}
20395 	}
20396 
20397 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20398 	    !bpf_offload_prog_map_match(prog, map)) {
20399 		verbose(env, "offload device mismatch between prog and map\n");
20400 		return -EINVAL;
20401 	}
20402 
20403 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20404 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20405 		return -EINVAL;
20406 	}
20407 
20408 	if (prog->sleepable)
20409 		switch (map->map_type) {
20410 		case BPF_MAP_TYPE_HASH:
20411 		case BPF_MAP_TYPE_LRU_HASH:
20412 		case BPF_MAP_TYPE_ARRAY:
20413 		case BPF_MAP_TYPE_PERCPU_HASH:
20414 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20415 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20416 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20417 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20418 		case BPF_MAP_TYPE_RINGBUF:
20419 		case BPF_MAP_TYPE_USER_RINGBUF:
20420 		case BPF_MAP_TYPE_INODE_STORAGE:
20421 		case BPF_MAP_TYPE_SK_STORAGE:
20422 		case BPF_MAP_TYPE_TASK_STORAGE:
20423 		case BPF_MAP_TYPE_CGRP_STORAGE:
20424 		case BPF_MAP_TYPE_QUEUE:
20425 		case BPF_MAP_TYPE_STACK:
20426 		case BPF_MAP_TYPE_ARENA:
20427 			break;
20428 		default:
20429 			verbose(env,
20430 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20431 			return -EINVAL;
20432 		}
20433 
20434 	if (bpf_map_is_cgroup_storage(map) &&
20435 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20436 		verbose(env, "only one cgroup storage of each type is allowed\n");
20437 		return -EBUSY;
20438 	}
20439 
20440 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20441 		if (env->prog->aux->arena) {
20442 			verbose(env, "Only one arena per program\n");
20443 			return -EBUSY;
20444 		}
20445 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20446 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20447 			return -EPERM;
20448 		}
20449 		if (!env->prog->jit_requested) {
20450 			verbose(env, "JIT is required to use arena\n");
20451 			return -EOPNOTSUPP;
20452 		}
20453 		if (!bpf_jit_supports_arena()) {
20454 			verbose(env, "JIT doesn't support arena\n");
20455 			return -EOPNOTSUPP;
20456 		}
20457 		env->prog->aux->arena = (void *)map;
20458 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20459 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20460 			return -EINVAL;
20461 		}
20462 	}
20463 
20464 	return 0;
20465 }
20466 
__add_used_map(struct bpf_verifier_env * env,struct bpf_map * map)20467 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20468 {
20469 	int i, err;
20470 
20471 	/* check whether we recorded this map already */
20472 	for (i = 0; i < env->used_map_cnt; i++)
20473 		if (env->used_maps[i] == map)
20474 			return i;
20475 
20476 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20477 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20478 			MAX_USED_MAPS);
20479 		return -E2BIG;
20480 	}
20481 
20482 	err = check_map_prog_compatibility(env, map, env->prog);
20483 	if (err)
20484 		return err;
20485 
20486 	if (env->prog->sleepable)
20487 		atomic64_inc(&map->sleepable_refcnt);
20488 
20489 	/* hold the map. If the program is rejected by verifier,
20490 	 * the map will be released by release_maps() or it
20491 	 * will be used by the valid program until it's unloaded
20492 	 * and all maps are released in bpf_free_used_maps()
20493 	 */
20494 	bpf_map_inc(map);
20495 
20496 	env->used_maps[env->used_map_cnt++] = map;
20497 
20498 	return env->used_map_cnt - 1;
20499 }
20500 
20501 /* Add map behind fd to used maps list, if it's not already there, and return
20502  * its index.
20503  * Returns <0 on error, or >= 0 index, on success.
20504  */
add_used_map(struct bpf_verifier_env * env,int fd)20505 static int add_used_map(struct bpf_verifier_env *env, int fd)
20506 {
20507 	struct bpf_map *map;
20508 	CLASS(fd, f)(fd);
20509 
20510 	map = __bpf_map_get(f);
20511 	if (IS_ERR(map)) {
20512 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20513 		return PTR_ERR(map);
20514 	}
20515 
20516 	return __add_used_map(env, map);
20517 }
20518 
20519 /* find and rewrite pseudo imm in ld_imm64 instructions:
20520  *
20521  * 1. if it accesses map FD, replace it with actual map pointer.
20522  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
20523  *
20524  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
20525  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)20526 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
20527 {
20528 	struct bpf_insn *insn = env->prog->insnsi;
20529 	int insn_cnt = env->prog->len;
20530 	int i, err;
20531 
20532 	err = bpf_prog_calc_tag(env->prog);
20533 	if (err)
20534 		return err;
20535 
20536 	for (i = 0; i < insn_cnt; i++, insn++) {
20537 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20538 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20539 		    insn->imm != 0)) {
20540 			verbose(env, "BPF_LDX uses reserved fields\n");
20541 			return -EINVAL;
20542 		}
20543 
20544 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
20545 			struct bpf_insn_aux_data *aux;
20546 			struct bpf_map *map;
20547 			int map_idx;
20548 			u64 addr;
20549 			u32 fd;
20550 
20551 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
20552 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
20553 			    insn[1].off != 0) {
20554 				verbose(env, "invalid bpf_ld_imm64 insn\n");
20555 				return -EINVAL;
20556 			}
20557 
20558 			if (insn[0].src_reg == 0)
20559 				/* valid generic load 64-bit imm */
20560 				goto next_insn;
20561 
20562 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
20563 				aux = &env->insn_aux_data[i];
20564 				err = check_pseudo_btf_id(env, insn, aux);
20565 				if (err)
20566 					return err;
20567 				goto next_insn;
20568 			}
20569 
20570 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
20571 				aux = &env->insn_aux_data[i];
20572 				aux->ptr_type = PTR_TO_FUNC;
20573 				goto next_insn;
20574 			}
20575 
20576 			/* In final convert_pseudo_ld_imm64() step, this is
20577 			 * converted into regular 64-bit imm load insn.
20578 			 */
20579 			switch (insn[0].src_reg) {
20580 			case BPF_PSEUDO_MAP_VALUE:
20581 			case BPF_PSEUDO_MAP_IDX_VALUE:
20582 				break;
20583 			case BPF_PSEUDO_MAP_FD:
20584 			case BPF_PSEUDO_MAP_IDX:
20585 				if (insn[1].imm == 0)
20586 					break;
20587 				fallthrough;
20588 			default:
20589 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
20590 				return -EINVAL;
20591 			}
20592 
20593 			switch (insn[0].src_reg) {
20594 			case BPF_PSEUDO_MAP_IDX_VALUE:
20595 			case BPF_PSEUDO_MAP_IDX:
20596 				if (bpfptr_is_null(env->fd_array)) {
20597 					verbose(env, "fd_idx without fd_array is invalid\n");
20598 					return -EPROTO;
20599 				}
20600 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
20601 							    insn[0].imm * sizeof(fd),
20602 							    sizeof(fd)))
20603 					return -EFAULT;
20604 				break;
20605 			default:
20606 				fd = insn[0].imm;
20607 				break;
20608 			}
20609 
20610 			map_idx = add_used_map(env, fd);
20611 			if (map_idx < 0)
20612 				return map_idx;
20613 			map = env->used_maps[map_idx];
20614 
20615 			aux = &env->insn_aux_data[i];
20616 			aux->map_index = map_idx;
20617 
20618 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
20619 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
20620 				addr = (unsigned long)map;
20621 			} else {
20622 				u32 off = insn[1].imm;
20623 
20624 				if (off >= BPF_MAX_VAR_OFF) {
20625 					verbose(env, "direct value offset of %u is not allowed\n", off);
20626 					return -EINVAL;
20627 				}
20628 
20629 				if (!map->ops->map_direct_value_addr) {
20630 					verbose(env, "no direct value access support for this map type\n");
20631 					return -EINVAL;
20632 				}
20633 
20634 				err = map->ops->map_direct_value_addr(map, &addr, off);
20635 				if (err) {
20636 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
20637 						map->value_size, off);
20638 					return err;
20639 				}
20640 
20641 				aux->map_off = off;
20642 				addr += off;
20643 			}
20644 
20645 			insn[0].imm = (u32)addr;
20646 			insn[1].imm = addr >> 32;
20647 
20648 next_insn:
20649 			insn++;
20650 			i++;
20651 			continue;
20652 		}
20653 
20654 		/* Basic sanity check before we invest more work here. */
20655 		if (!bpf_opcode_in_insntable(insn->code)) {
20656 			verbose(env, "unknown opcode %02x\n", insn->code);
20657 			return -EINVAL;
20658 		}
20659 	}
20660 
20661 	/* now all pseudo BPF_LD_IMM64 instructions load valid
20662 	 * 'struct bpf_map *' into a register instead of user map_fd.
20663 	 * These pointers will be used later by verifier to validate map access.
20664 	 */
20665 	return 0;
20666 }
20667 
20668 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)20669 static void release_maps(struct bpf_verifier_env *env)
20670 {
20671 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
20672 			     env->used_map_cnt);
20673 }
20674 
20675 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)20676 static void release_btfs(struct bpf_verifier_env *env)
20677 {
20678 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
20679 }
20680 
20681 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)20682 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
20683 {
20684 	struct bpf_insn *insn = env->prog->insnsi;
20685 	int insn_cnt = env->prog->len;
20686 	int i;
20687 
20688 	for (i = 0; i < insn_cnt; i++, insn++) {
20689 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
20690 			continue;
20691 		if (insn->src_reg == BPF_PSEUDO_FUNC)
20692 			continue;
20693 		insn->src_reg = 0;
20694 	}
20695 }
20696 
20697 /* single env->prog->insni[off] instruction was replaced with the range
20698  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
20699  * [0, off) and [off, end) to new locations, so the patched range stays zero
20700  */
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)20701 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
20702 				 struct bpf_insn_aux_data *new_data,
20703 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
20704 {
20705 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
20706 	struct bpf_insn *insn = new_prog->insnsi;
20707 	u32 old_seen = old_data[off].seen;
20708 	u32 prog_len;
20709 	int i;
20710 
20711 	/* aux info at OFF always needs adjustment, no matter fast path
20712 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
20713 	 * original insn at old prog.
20714 	 */
20715 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
20716 
20717 	if (cnt == 1)
20718 		return;
20719 	prog_len = new_prog->len;
20720 
20721 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
20722 	memcpy(new_data + off + cnt - 1, old_data + off,
20723 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
20724 	for (i = off; i < off + cnt - 1; i++) {
20725 		/* Expand insni[off]'s seen count to the patched range. */
20726 		new_data[i].seen = old_seen;
20727 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
20728 	}
20729 	env->insn_aux_data = new_data;
20730 	vfree(old_data);
20731 }
20732 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)20733 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
20734 {
20735 	int i;
20736 
20737 	if (len == 1)
20738 		return;
20739 	/* NOTE: fake 'exit' subprog should be updated as well. */
20740 	for (i = 0; i <= env->subprog_cnt; i++) {
20741 		if (env->subprog_info[i].start <= off)
20742 			continue;
20743 		env->subprog_info[i].start += len - 1;
20744 	}
20745 }
20746 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)20747 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
20748 {
20749 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
20750 	int i, sz = prog->aux->size_poke_tab;
20751 	struct bpf_jit_poke_descriptor *desc;
20752 
20753 	for (i = 0; i < sz; i++) {
20754 		desc = &tab[i];
20755 		if (desc->insn_idx <= off)
20756 			continue;
20757 		desc->insn_idx += len - 1;
20758 	}
20759 }
20760 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)20761 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
20762 					    const struct bpf_insn *patch, u32 len)
20763 {
20764 	struct bpf_prog *new_prog;
20765 	struct bpf_insn_aux_data *new_data = NULL;
20766 
20767 	if (len > 1) {
20768 		new_data = vzalloc(array_size(env->prog->len + len - 1,
20769 					      sizeof(struct bpf_insn_aux_data)));
20770 		if (!new_data)
20771 			return NULL;
20772 	}
20773 
20774 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
20775 	if (IS_ERR(new_prog)) {
20776 		if (PTR_ERR(new_prog) == -ERANGE)
20777 			verbose(env,
20778 				"insn %d cannot be patched due to 16-bit range\n",
20779 				env->insn_aux_data[off].orig_idx);
20780 		vfree(new_data);
20781 		return NULL;
20782 	}
20783 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
20784 	adjust_subprog_starts(env, off, len);
20785 	adjust_poke_descs(new_prog, off, len);
20786 	return new_prog;
20787 }
20788 
20789 /*
20790  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
20791  * jump offset by 'delta'.
20792  */
adjust_jmp_off(struct bpf_prog * prog,u32 tgt_idx,u32 delta)20793 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
20794 {
20795 	struct bpf_insn *insn = prog->insnsi;
20796 	u32 insn_cnt = prog->len, i;
20797 	s32 imm;
20798 	s16 off;
20799 
20800 	for (i = 0; i < insn_cnt; i++, insn++) {
20801 		u8 code = insn->code;
20802 
20803 		if (tgt_idx <= i && i < tgt_idx + delta)
20804 			continue;
20805 
20806 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
20807 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
20808 			continue;
20809 
20810 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
20811 			if (i + 1 + insn->imm != tgt_idx)
20812 				continue;
20813 			if (check_add_overflow(insn->imm, delta, &imm))
20814 				return -ERANGE;
20815 			insn->imm = imm;
20816 		} else {
20817 			if (i + 1 + insn->off != tgt_idx)
20818 				continue;
20819 			if (check_add_overflow(insn->off, delta, &off))
20820 				return -ERANGE;
20821 			insn->off = off;
20822 		}
20823 	}
20824 	return 0;
20825 }
20826 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)20827 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
20828 					      u32 off, u32 cnt)
20829 {
20830 	int i, j;
20831 
20832 	/* find first prog starting at or after off (first to remove) */
20833 	for (i = 0; i < env->subprog_cnt; i++)
20834 		if (env->subprog_info[i].start >= off)
20835 			break;
20836 	/* find first prog starting at or after off + cnt (first to stay) */
20837 	for (j = i; j < env->subprog_cnt; j++)
20838 		if (env->subprog_info[j].start >= off + cnt)
20839 			break;
20840 	/* if j doesn't start exactly at off + cnt, we are just removing
20841 	 * the front of previous prog
20842 	 */
20843 	if (env->subprog_info[j].start != off + cnt)
20844 		j--;
20845 
20846 	if (j > i) {
20847 		struct bpf_prog_aux *aux = env->prog->aux;
20848 		int move;
20849 
20850 		/* move fake 'exit' subprog as well */
20851 		move = env->subprog_cnt + 1 - j;
20852 
20853 		memmove(env->subprog_info + i,
20854 			env->subprog_info + j,
20855 			sizeof(*env->subprog_info) * move);
20856 		env->subprog_cnt -= j - i;
20857 
20858 		/* remove func_info */
20859 		if (aux->func_info) {
20860 			move = aux->func_info_cnt - j;
20861 
20862 			memmove(aux->func_info + i,
20863 				aux->func_info + j,
20864 				sizeof(*aux->func_info) * move);
20865 			aux->func_info_cnt -= j - i;
20866 			/* func_info->insn_off is set after all code rewrites,
20867 			 * in adjust_btf_func() - no need to adjust
20868 			 */
20869 		}
20870 	} else {
20871 		/* convert i from "first prog to remove" to "first to adjust" */
20872 		if (env->subprog_info[i].start == off)
20873 			i++;
20874 	}
20875 
20876 	/* update fake 'exit' subprog as well */
20877 	for (; i <= env->subprog_cnt; i++)
20878 		env->subprog_info[i].start -= cnt;
20879 
20880 	return 0;
20881 }
20882 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)20883 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20884 				      u32 cnt)
20885 {
20886 	struct bpf_prog *prog = env->prog;
20887 	u32 i, l_off, l_cnt, nr_linfo;
20888 	struct bpf_line_info *linfo;
20889 
20890 	nr_linfo = prog->aux->nr_linfo;
20891 	if (!nr_linfo)
20892 		return 0;
20893 
20894 	linfo = prog->aux->linfo;
20895 
20896 	/* find first line info to remove, count lines to be removed */
20897 	for (i = 0; i < nr_linfo; i++)
20898 		if (linfo[i].insn_off >= off)
20899 			break;
20900 
20901 	l_off = i;
20902 	l_cnt = 0;
20903 	for (; i < nr_linfo; i++)
20904 		if (linfo[i].insn_off < off + cnt)
20905 			l_cnt++;
20906 		else
20907 			break;
20908 
20909 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20910 	 * last removed linfo.  prog is already modified, so prog->len == off
20911 	 * means no live instructions after (tail of the program was removed).
20912 	 */
20913 	if (prog->len != off && l_cnt &&
20914 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20915 		l_cnt--;
20916 		linfo[--i].insn_off = off + cnt;
20917 	}
20918 
20919 	/* remove the line info which refer to the removed instructions */
20920 	if (l_cnt) {
20921 		memmove(linfo + l_off, linfo + i,
20922 			sizeof(*linfo) * (nr_linfo - i));
20923 
20924 		prog->aux->nr_linfo -= l_cnt;
20925 		nr_linfo = prog->aux->nr_linfo;
20926 	}
20927 
20928 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20929 	for (i = l_off; i < nr_linfo; i++)
20930 		linfo[i].insn_off -= cnt;
20931 
20932 	/* fix up all subprogs (incl. 'exit') which start >= off */
20933 	for (i = 0; i <= env->subprog_cnt; i++)
20934 		if (env->subprog_info[i].linfo_idx > l_off) {
20935 			/* program may have started in the removed region but
20936 			 * may not be fully removed
20937 			 */
20938 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20939 				env->subprog_info[i].linfo_idx -= l_cnt;
20940 			else
20941 				env->subprog_info[i].linfo_idx = l_off;
20942 		}
20943 
20944 	return 0;
20945 }
20946 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)20947 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20948 {
20949 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20950 	unsigned int orig_prog_len = env->prog->len;
20951 	int err;
20952 
20953 	if (bpf_prog_is_offloaded(env->prog->aux))
20954 		bpf_prog_offload_remove_insns(env, off, cnt);
20955 
20956 	err = bpf_remove_insns(env->prog, off, cnt);
20957 	if (err)
20958 		return err;
20959 
20960 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20961 	if (err)
20962 		return err;
20963 
20964 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20965 	if (err)
20966 		return err;
20967 
20968 	memmove(aux_data + off,	aux_data + off + cnt,
20969 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20970 
20971 	return 0;
20972 }
20973 
20974 /* The verifier does more data flow analysis than llvm and will not
20975  * explore branches that are dead at run time. Malicious programs can
20976  * have dead code too. Therefore replace all dead at-run-time code
20977  * with 'ja -1'.
20978  *
20979  * Just nops are not optimal, e.g. if they would sit at the end of the
20980  * program and through another bug we would manage to jump there, then
20981  * we'd execute beyond program memory otherwise. Returning exception
20982  * code also wouldn't work since we can have subprogs where the dead
20983  * code could be located.
20984  */
sanitize_dead_code(struct bpf_verifier_env * env)20985 static void sanitize_dead_code(struct bpf_verifier_env *env)
20986 {
20987 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20988 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20989 	struct bpf_insn *insn = env->prog->insnsi;
20990 	const int insn_cnt = env->prog->len;
20991 	int i;
20992 
20993 	for (i = 0; i < insn_cnt; i++) {
20994 		if (aux_data[i].seen)
20995 			continue;
20996 		memcpy(insn + i, &trap, sizeof(trap));
20997 		aux_data[i].zext_dst = false;
20998 	}
20999 }
21000 
insn_is_cond_jump(u8 code)21001 static bool insn_is_cond_jump(u8 code)
21002 {
21003 	u8 op;
21004 
21005 	op = BPF_OP(code);
21006 	if (BPF_CLASS(code) == BPF_JMP32)
21007 		return op != BPF_JA;
21008 
21009 	if (BPF_CLASS(code) != BPF_JMP)
21010 		return false;
21011 
21012 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21013 }
21014 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)21015 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21016 {
21017 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21018 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21019 	struct bpf_insn *insn = env->prog->insnsi;
21020 	const int insn_cnt = env->prog->len;
21021 	int i;
21022 
21023 	for (i = 0; i < insn_cnt; i++, insn++) {
21024 		if (!insn_is_cond_jump(insn->code))
21025 			continue;
21026 
21027 		if (!aux_data[i + 1].seen)
21028 			ja.off = insn->off;
21029 		else if (!aux_data[i + 1 + insn->off].seen)
21030 			ja.off = 0;
21031 		else
21032 			continue;
21033 
21034 		if (bpf_prog_is_offloaded(env->prog->aux))
21035 			bpf_prog_offload_replace_insn(env, i, &ja);
21036 
21037 		memcpy(insn, &ja, sizeof(ja));
21038 	}
21039 }
21040 
opt_remove_dead_code(struct bpf_verifier_env * env)21041 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21042 {
21043 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21044 	int insn_cnt = env->prog->len;
21045 	int i, err;
21046 
21047 	for (i = 0; i < insn_cnt; i++) {
21048 		int j;
21049 
21050 		j = 0;
21051 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21052 			j++;
21053 		if (!j)
21054 			continue;
21055 
21056 		err = verifier_remove_insns(env, i, j);
21057 		if (err)
21058 			return err;
21059 		insn_cnt = env->prog->len;
21060 	}
21061 
21062 	return 0;
21063 }
21064 
21065 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21066 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21067 
opt_remove_nops(struct bpf_verifier_env * env)21068 static int opt_remove_nops(struct bpf_verifier_env *env)
21069 {
21070 	struct bpf_insn *insn = env->prog->insnsi;
21071 	int insn_cnt = env->prog->len;
21072 	bool is_may_goto_0, is_ja;
21073 	int i, err;
21074 
21075 	for (i = 0; i < insn_cnt; i++) {
21076 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21077 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21078 
21079 		if (!is_may_goto_0 && !is_ja)
21080 			continue;
21081 
21082 		err = verifier_remove_insns(env, i, 1);
21083 		if (err)
21084 			return err;
21085 		insn_cnt--;
21086 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21087 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21088 	}
21089 
21090 	return 0;
21091 }
21092 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)21093 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21094 					 const union bpf_attr *attr)
21095 {
21096 	struct bpf_insn *patch;
21097 	/* use env->insn_buf as two independent buffers */
21098 	struct bpf_insn *zext_patch = env->insn_buf;
21099 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21100 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21101 	int i, patch_len, delta = 0, len = env->prog->len;
21102 	struct bpf_insn *insns = env->prog->insnsi;
21103 	struct bpf_prog *new_prog;
21104 	bool rnd_hi32;
21105 
21106 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21107 	zext_patch[1] = BPF_ZEXT_REG(0);
21108 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21109 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21110 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21111 	for (i = 0; i < len; i++) {
21112 		int adj_idx = i + delta;
21113 		struct bpf_insn insn;
21114 		int load_reg;
21115 
21116 		insn = insns[adj_idx];
21117 		load_reg = insn_def_regno(&insn);
21118 		if (!aux[adj_idx].zext_dst) {
21119 			u8 code, class;
21120 			u32 imm_rnd;
21121 
21122 			if (!rnd_hi32)
21123 				continue;
21124 
21125 			code = insn.code;
21126 			class = BPF_CLASS(code);
21127 			if (load_reg == -1)
21128 				continue;
21129 
21130 			/* NOTE: arg "reg" (the fourth one) is only used for
21131 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21132 			 *       here.
21133 			 */
21134 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
21135 				if (class == BPF_LD &&
21136 				    BPF_MODE(code) == BPF_IMM)
21137 					i++;
21138 				continue;
21139 			}
21140 
21141 			/* ctx load could be transformed into wider load. */
21142 			if (class == BPF_LDX &&
21143 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21144 				continue;
21145 
21146 			imm_rnd = get_random_u32();
21147 			rnd_hi32_patch[0] = insn;
21148 			rnd_hi32_patch[1].imm = imm_rnd;
21149 			rnd_hi32_patch[3].dst_reg = load_reg;
21150 			patch = rnd_hi32_patch;
21151 			patch_len = 4;
21152 			goto apply_patch_buffer;
21153 		}
21154 
21155 		/* Add in an zero-extend instruction if a) the JIT has requested
21156 		 * it or b) it's a CMPXCHG.
21157 		 *
21158 		 * The latter is because: BPF_CMPXCHG always loads a value into
21159 		 * R0, therefore always zero-extends. However some archs'
21160 		 * equivalent instruction only does this load when the
21161 		 * comparison is successful. This detail of CMPXCHG is
21162 		 * orthogonal to the general zero-extension behaviour of the
21163 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21164 		 */
21165 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21166 			continue;
21167 
21168 		/* Zero-extension is done by the caller. */
21169 		if (bpf_pseudo_kfunc_call(&insn))
21170 			continue;
21171 
21172 		if (verifier_bug_if(load_reg == -1, env,
21173 				    "zext_dst is set, but no reg is defined"))
21174 			return -EFAULT;
21175 
21176 		zext_patch[0] = insn;
21177 		zext_patch[1].dst_reg = load_reg;
21178 		zext_patch[1].src_reg = load_reg;
21179 		patch = zext_patch;
21180 		patch_len = 2;
21181 apply_patch_buffer:
21182 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21183 		if (!new_prog)
21184 			return -ENOMEM;
21185 		env->prog = new_prog;
21186 		insns = new_prog->insnsi;
21187 		aux = env->insn_aux_data;
21188 		delta += patch_len - 1;
21189 	}
21190 
21191 	return 0;
21192 }
21193 
21194 /* convert load instructions that access fields of a context type into a
21195  * sequence of instructions that access fields of the underlying structure:
21196  *     struct __sk_buff    -> struct sk_buff
21197  *     struct bpf_sock_ops -> struct sock
21198  */
convert_ctx_accesses(struct bpf_verifier_env * env)21199 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21200 {
21201 	struct bpf_subprog_info *subprogs = env->subprog_info;
21202 	const struct bpf_verifier_ops *ops = env->ops;
21203 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21204 	const int insn_cnt = env->prog->len;
21205 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21206 	struct bpf_insn *insn_buf = env->insn_buf;
21207 	struct bpf_insn *insn;
21208 	u32 target_size, size_default, off;
21209 	struct bpf_prog *new_prog;
21210 	enum bpf_access_type type;
21211 	bool is_narrower_load;
21212 	int epilogue_idx = 0;
21213 
21214 	if (ops->gen_epilogue) {
21215 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21216 						 -(subprogs[0].stack_depth + 8));
21217 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21218 			verifier_bug(env, "epilogue is too long");
21219 			return -EFAULT;
21220 		} else if (epilogue_cnt) {
21221 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21222 			cnt = 0;
21223 			subprogs[0].stack_depth += 8;
21224 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21225 						      -subprogs[0].stack_depth);
21226 			insn_buf[cnt++] = env->prog->insnsi[0];
21227 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21228 			if (!new_prog)
21229 				return -ENOMEM;
21230 			env->prog = new_prog;
21231 			delta += cnt - 1;
21232 
21233 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21234 			if (ret < 0)
21235 				return ret;
21236 		}
21237 	}
21238 
21239 	if (ops->gen_prologue || env->seen_direct_write) {
21240 		if (!ops->gen_prologue) {
21241 			verifier_bug(env, "gen_prologue is null");
21242 			return -EFAULT;
21243 		}
21244 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21245 					env->prog);
21246 		if (cnt >= INSN_BUF_SIZE) {
21247 			verifier_bug(env, "prologue is too long");
21248 			return -EFAULT;
21249 		} else if (cnt) {
21250 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21251 			if (!new_prog)
21252 				return -ENOMEM;
21253 
21254 			env->prog = new_prog;
21255 			delta += cnt - 1;
21256 
21257 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21258 			if (ret < 0)
21259 				return ret;
21260 		}
21261 	}
21262 
21263 	if (delta)
21264 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21265 
21266 	if (bpf_prog_is_offloaded(env->prog->aux))
21267 		return 0;
21268 
21269 	insn = env->prog->insnsi + delta;
21270 
21271 	for (i = 0; i < insn_cnt; i++, insn++) {
21272 		bpf_convert_ctx_access_t convert_ctx_access;
21273 		u8 mode;
21274 
21275 		if (env->insn_aux_data[i + delta].nospec) {
21276 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21277 			struct bpf_insn *patch = insn_buf;
21278 
21279 			*patch++ = BPF_ST_NOSPEC();
21280 			*patch++ = *insn;
21281 			cnt = patch - insn_buf;
21282 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21283 			if (!new_prog)
21284 				return -ENOMEM;
21285 
21286 			delta    += cnt - 1;
21287 			env->prog = new_prog;
21288 			insn      = new_prog->insnsi + i + delta;
21289 			/* This can not be easily merged with the
21290 			 * nospec_result-case, because an insn may require a
21291 			 * nospec before and after itself. Therefore also do not
21292 			 * 'continue' here but potentially apply further
21293 			 * patching to insn. *insn should equal patch[1] now.
21294 			 */
21295 		}
21296 
21297 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21298 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21299 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21300 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21301 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21302 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21303 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21304 			type = BPF_READ;
21305 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21306 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21307 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21308 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21309 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21310 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21311 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21312 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21313 			type = BPF_WRITE;
21314 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21315 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21316 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21317 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21318 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21319 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21320 			env->prog->aux->num_exentries++;
21321 			continue;
21322 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21323 			   epilogue_cnt &&
21324 			   i + delta < subprogs[1].start) {
21325 			/* Generate epilogue for the main prog */
21326 			if (epilogue_idx) {
21327 				/* jump back to the earlier generated epilogue */
21328 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21329 				cnt = 1;
21330 			} else {
21331 				memcpy(insn_buf, epilogue_buf,
21332 				       epilogue_cnt * sizeof(*epilogue_buf));
21333 				cnt = epilogue_cnt;
21334 				/* epilogue_idx cannot be 0. It must have at
21335 				 * least one ctx ptr saving insn before the
21336 				 * epilogue.
21337 				 */
21338 				epilogue_idx = i + delta;
21339 			}
21340 			goto patch_insn_buf;
21341 		} else {
21342 			continue;
21343 		}
21344 
21345 		if (type == BPF_WRITE &&
21346 		    env->insn_aux_data[i + delta].nospec_result) {
21347 			/* nospec_result is only used to mitigate Spectre v4 and
21348 			 * to limit verification-time for Spectre v1.
21349 			 */
21350 			struct bpf_insn *patch = insn_buf;
21351 
21352 			*patch++ = *insn;
21353 			*patch++ = BPF_ST_NOSPEC();
21354 			cnt = patch - insn_buf;
21355 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21356 			if (!new_prog)
21357 				return -ENOMEM;
21358 
21359 			delta    += cnt - 1;
21360 			env->prog = new_prog;
21361 			insn      = new_prog->insnsi + i + delta;
21362 			continue;
21363 		}
21364 
21365 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21366 		case PTR_TO_CTX:
21367 			if (!ops->convert_ctx_access)
21368 				continue;
21369 			convert_ctx_access = ops->convert_ctx_access;
21370 			break;
21371 		case PTR_TO_SOCKET:
21372 		case PTR_TO_SOCK_COMMON:
21373 			convert_ctx_access = bpf_sock_convert_ctx_access;
21374 			break;
21375 		case PTR_TO_TCP_SOCK:
21376 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21377 			break;
21378 		case PTR_TO_XDP_SOCK:
21379 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21380 			break;
21381 		case PTR_TO_BTF_ID:
21382 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21383 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21384 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21385 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21386 		 * any faults for loads into such types. BPF_WRITE is disallowed
21387 		 * for this case.
21388 		 */
21389 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21390 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21391 			if (type == BPF_READ) {
21392 				if (BPF_MODE(insn->code) == BPF_MEM)
21393 					insn->code = BPF_LDX | BPF_PROBE_MEM |
21394 						     BPF_SIZE((insn)->code);
21395 				else
21396 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21397 						     BPF_SIZE((insn)->code);
21398 				env->prog->aux->num_exentries++;
21399 			}
21400 			continue;
21401 		case PTR_TO_ARENA:
21402 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
21403 				verbose(env, "sign extending loads from arena are not supported yet\n");
21404 				return -EOPNOTSUPP;
21405 			}
21406 			insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21407 			env->prog->aux->num_exentries++;
21408 			continue;
21409 		default:
21410 			continue;
21411 		}
21412 
21413 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21414 		size = BPF_LDST_BYTES(insn);
21415 		mode = BPF_MODE(insn->code);
21416 
21417 		/* If the read access is a narrower load of the field,
21418 		 * convert to a 4/8-byte load, to minimum program type specific
21419 		 * convert_ctx_access changes. If conversion is successful,
21420 		 * we will apply proper mask to the result.
21421 		 */
21422 		is_narrower_load = size < ctx_field_size;
21423 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21424 		off = insn->off;
21425 		if (is_narrower_load) {
21426 			u8 size_code;
21427 
21428 			if (type == BPF_WRITE) {
21429 				verifier_bug(env, "narrow ctx access misconfigured");
21430 				return -EFAULT;
21431 			}
21432 
21433 			size_code = BPF_H;
21434 			if (ctx_field_size == 4)
21435 				size_code = BPF_W;
21436 			else if (ctx_field_size == 8)
21437 				size_code = BPF_DW;
21438 
21439 			insn->off = off & ~(size_default - 1);
21440 			insn->code = BPF_LDX | BPF_MEM | size_code;
21441 		}
21442 
21443 		target_size = 0;
21444 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
21445 					 &target_size);
21446 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
21447 		    (ctx_field_size && !target_size)) {
21448 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
21449 			return -EFAULT;
21450 		}
21451 
21452 		if (is_narrower_load && size < target_size) {
21453 			u8 shift = bpf_ctx_narrow_access_offset(
21454 				off, size, size_default) * 8;
21455 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
21456 				verifier_bug(env, "narrow ctx load misconfigured");
21457 				return -EFAULT;
21458 			}
21459 			if (ctx_field_size <= 4) {
21460 				if (shift)
21461 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
21462 									insn->dst_reg,
21463 									shift);
21464 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21465 								(1 << size * 8) - 1);
21466 			} else {
21467 				if (shift)
21468 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
21469 									insn->dst_reg,
21470 									shift);
21471 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21472 								(1ULL << size * 8) - 1);
21473 			}
21474 		}
21475 		if (mode == BPF_MEMSX)
21476 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
21477 						       insn->dst_reg, insn->dst_reg,
21478 						       size * 8, 0);
21479 
21480 patch_insn_buf:
21481 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21482 		if (!new_prog)
21483 			return -ENOMEM;
21484 
21485 		delta += cnt - 1;
21486 
21487 		/* keep walking new program and skip insns we just inserted */
21488 		env->prog = new_prog;
21489 		insn      = new_prog->insnsi + i + delta;
21490 	}
21491 
21492 	return 0;
21493 }
21494 
jit_subprogs(struct bpf_verifier_env * env)21495 static int jit_subprogs(struct bpf_verifier_env *env)
21496 {
21497 	struct bpf_prog *prog = env->prog, **func, *tmp;
21498 	int i, j, subprog_start, subprog_end = 0, len, subprog;
21499 	struct bpf_map *map_ptr;
21500 	struct bpf_insn *insn;
21501 	void *old_bpf_func;
21502 	int err, num_exentries;
21503 
21504 	if (env->subprog_cnt <= 1)
21505 		return 0;
21506 
21507 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21508 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
21509 			continue;
21510 
21511 		/* Upon error here we cannot fall back to interpreter but
21512 		 * need a hard reject of the program. Thus -EFAULT is
21513 		 * propagated in any case.
21514 		 */
21515 		subprog = find_subprog(env, i + insn->imm + 1);
21516 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
21517 				    i + insn->imm + 1))
21518 			return -EFAULT;
21519 		/* temporarily remember subprog id inside insn instead of
21520 		 * aux_data, since next loop will split up all insns into funcs
21521 		 */
21522 		insn->off = subprog;
21523 		/* remember original imm in case JIT fails and fallback
21524 		 * to interpreter will be needed
21525 		 */
21526 		env->insn_aux_data[i].call_imm = insn->imm;
21527 		/* point imm to __bpf_call_base+1 from JITs point of view */
21528 		insn->imm = 1;
21529 		if (bpf_pseudo_func(insn)) {
21530 #if defined(MODULES_VADDR)
21531 			u64 addr = MODULES_VADDR;
21532 #else
21533 			u64 addr = VMALLOC_START;
21534 #endif
21535 			/* jit (e.g. x86_64) may emit fewer instructions
21536 			 * if it learns a u32 imm is the same as a u64 imm.
21537 			 * Set close enough to possible prog address.
21538 			 */
21539 			insn[0].imm = (u32)addr;
21540 			insn[1].imm = addr >> 32;
21541 		}
21542 	}
21543 
21544 	err = bpf_prog_alloc_jited_linfo(prog);
21545 	if (err)
21546 		goto out_undo_insn;
21547 
21548 	err = -ENOMEM;
21549 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
21550 	if (!func)
21551 		goto out_undo_insn;
21552 
21553 	for (i = 0; i < env->subprog_cnt; i++) {
21554 		subprog_start = subprog_end;
21555 		subprog_end = env->subprog_info[i + 1].start;
21556 
21557 		len = subprog_end - subprog_start;
21558 		/* bpf_prog_run() doesn't call subprogs directly,
21559 		 * hence main prog stats include the runtime of subprogs.
21560 		 * subprogs don't have IDs and not reachable via prog_get_next_id
21561 		 * func[i]->stats will never be accessed and stays NULL
21562 		 */
21563 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
21564 		if (!func[i])
21565 			goto out_free;
21566 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
21567 		       len * sizeof(struct bpf_insn));
21568 		func[i]->type = prog->type;
21569 		func[i]->len = len;
21570 		if (bpf_prog_calc_tag(func[i]))
21571 			goto out_free;
21572 		func[i]->is_func = 1;
21573 		func[i]->sleepable = prog->sleepable;
21574 		func[i]->aux->func_idx = i;
21575 		/* Below members will be freed only at prog->aux */
21576 		func[i]->aux->btf = prog->aux->btf;
21577 		func[i]->aux->func_info = prog->aux->func_info;
21578 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
21579 		func[i]->aux->poke_tab = prog->aux->poke_tab;
21580 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
21581 
21582 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
21583 			struct bpf_jit_poke_descriptor *poke;
21584 
21585 			poke = &prog->aux->poke_tab[j];
21586 			if (poke->insn_idx < subprog_end &&
21587 			    poke->insn_idx >= subprog_start)
21588 				poke->aux = func[i]->aux;
21589 		}
21590 
21591 		func[i]->aux->name[0] = 'F';
21592 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
21593 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
21594 			func[i]->aux->jits_use_priv_stack = true;
21595 
21596 		func[i]->jit_requested = 1;
21597 		func[i]->blinding_requested = prog->blinding_requested;
21598 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
21599 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
21600 		func[i]->aux->linfo = prog->aux->linfo;
21601 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
21602 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
21603 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
21604 		func[i]->aux->arena = prog->aux->arena;
21605 		num_exentries = 0;
21606 		insn = func[i]->insnsi;
21607 		for (j = 0; j < func[i]->len; j++, insn++) {
21608 			if (BPF_CLASS(insn->code) == BPF_LDX &&
21609 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
21610 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
21611 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
21612 				num_exentries++;
21613 			if ((BPF_CLASS(insn->code) == BPF_STX ||
21614 			     BPF_CLASS(insn->code) == BPF_ST) &&
21615 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
21616 				num_exentries++;
21617 			if (BPF_CLASS(insn->code) == BPF_STX &&
21618 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
21619 				num_exentries++;
21620 		}
21621 		func[i]->aux->num_exentries = num_exentries;
21622 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
21623 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
21624 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
21625 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
21626 		if (!i)
21627 			func[i]->aux->exception_boundary = env->seen_exception;
21628 		func[i] = bpf_int_jit_compile(func[i]);
21629 		if (!func[i]->jited) {
21630 			err = -ENOTSUPP;
21631 			goto out_free;
21632 		}
21633 		cond_resched();
21634 	}
21635 
21636 	/* at this point all bpf functions were successfully JITed
21637 	 * now populate all bpf_calls with correct addresses and
21638 	 * run last pass of JIT
21639 	 */
21640 	for (i = 0; i < env->subprog_cnt; i++) {
21641 		insn = func[i]->insnsi;
21642 		for (j = 0; j < func[i]->len; j++, insn++) {
21643 			if (bpf_pseudo_func(insn)) {
21644 				subprog = insn->off;
21645 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
21646 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
21647 				continue;
21648 			}
21649 			if (!bpf_pseudo_call(insn))
21650 				continue;
21651 			subprog = insn->off;
21652 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
21653 		}
21654 
21655 		/* we use the aux data to keep a list of the start addresses
21656 		 * of the JITed images for each function in the program
21657 		 *
21658 		 * for some architectures, such as powerpc64, the imm field
21659 		 * might not be large enough to hold the offset of the start
21660 		 * address of the callee's JITed image from __bpf_call_base
21661 		 *
21662 		 * in such cases, we can lookup the start address of a callee
21663 		 * by using its subprog id, available from the off field of
21664 		 * the call instruction, as an index for this list
21665 		 */
21666 		func[i]->aux->func = func;
21667 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21668 		func[i]->aux->real_func_cnt = env->subprog_cnt;
21669 	}
21670 	for (i = 0; i < env->subprog_cnt; i++) {
21671 		old_bpf_func = func[i]->bpf_func;
21672 		tmp = bpf_int_jit_compile(func[i]);
21673 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
21674 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
21675 			err = -ENOTSUPP;
21676 			goto out_free;
21677 		}
21678 		cond_resched();
21679 	}
21680 
21681 	/* finally lock prog and jit images for all functions and
21682 	 * populate kallsysm. Begin at the first subprogram, since
21683 	 * bpf_prog_load will add the kallsyms for the main program.
21684 	 */
21685 	for (i = 1; i < env->subprog_cnt; i++) {
21686 		err = bpf_prog_lock_ro(func[i]);
21687 		if (err)
21688 			goto out_free;
21689 	}
21690 
21691 	for (i = 1; i < env->subprog_cnt; i++)
21692 		bpf_prog_kallsyms_add(func[i]);
21693 
21694 	/* Last step: make now unused interpreter insns from main
21695 	 * prog consistent for later dump requests, so they can
21696 	 * later look the same as if they were interpreted only.
21697 	 */
21698 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21699 		if (bpf_pseudo_func(insn)) {
21700 			insn[0].imm = env->insn_aux_data[i].call_imm;
21701 			insn[1].imm = insn->off;
21702 			insn->off = 0;
21703 			continue;
21704 		}
21705 		if (!bpf_pseudo_call(insn))
21706 			continue;
21707 		insn->off = env->insn_aux_data[i].call_imm;
21708 		subprog = find_subprog(env, i + insn->off + 1);
21709 		insn->imm = subprog;
21710 	}
21711 
21712 	prog->jited = 1;
21713 	prog->bpf_func = func[0]->bpf_func;
21714 	prog->jited_len = func[0]->jited_len;
21715 	prog->aux->extable = func[0]->aux->extable;
21716 	prog->aux->num_exentries = func[0]->aux->num_exentries;
21717 	prog->aux->func = func;
21718 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21719 	prog->aux->real_func_cnt = env->subprog_cnt;
21720 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
21721 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
21722 	bpf_prog_jit_attempt_done(prog);
21723 	return 0;
21724 out_free:
21725 	/* We failed JIT'ing, so at this point we need to unregister poke
21726 	 * descriptors from subprogs, so that kernel is not attempting to
21727 	 * patch it anymore as we're freeing the subprog JIT memory.
21728 	 */
21729 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21730 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21731 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
21732 	}
21733 	/* At this point we're guaranteed that poke descriptors are not
21734 	 * live anymore. We can just unlink its descriptor table as it's
21735 	 * released with the main prog.
21736 	 */
21737 	for (i = 0; i < env->subprog_cnt; i++) {
21738 		if (!func[i])
21739 			continue;
21740 		func[i]->aux->poke_tab = NULL;
21741 		bpf_jit_free(func[i]);
21742 	}
21743 	kfree(func);
21744 out_undo_insn:
21745 	/* cleanup main prog to be interpreted */
21746 	prog->jit_requested = 0;
21747 	prog->blinding_requested = 0;
21748 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21749 		if (!bpf_pseudo_call(insn))
21750 			continue;
21751 		insn->off = 0;
21752 		insn->imm = env->insn_aux_data[i].call_imm;
21753 	}
21754 	bpf_prog_jit_attempt_done(prog);
21755 	return err;
21756 }
21757 
fixup_call_args(struct bpf_verifier_env * env)21758 static int fixup_call_args(struct bpf_verifier_env *env)
21759 {
21760 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21761 	struct bpf_prog *prog = env->prog;
21762 	struct bpf_insn *insn = prog->insnsi;
21763 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
21764 	int i, depth;
21765 #endif
21766 	int err = 0;
21767 
21768 	if (env->prog->jit_requested &&
21769 	    !bpf_prog_is_offloaded(env->prog->aux)) {
21770 		err = jit_subprogs(env);
21771 		if (err == 0)
21772 			return 0;
21773 		if (err == -EFAULT)
21774 			return err;
21775 	}
21776 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21777 	if (has_kfunc_call) {
21778 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
21779 		return -EINVAL;
21780 	}
21781 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
21782 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
21783 		 * have to be rejected, since interpreter doesn't support them yet.
21784 		 */
21785 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
21786 		return -EINVAL;
21787 	}
21788 	for (i = 0; i < prog->len; i++, insn++) {
21789 		if (bpf_pseudo_func(insn)) {
21790 			/* When JIT fails the progs with callback calls
21791 			 * have to be rejected, since interpreter doesn't support them yet.
21792 			 */
21793 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
21794 			return -EINVAL;
21795 		}
21796 
21797 		if (!bpf_pseudo_call(insn))
21798 			continue;
21799 		depth = get_callee_stack_depth(env, insn, i);
21800 		if (depth < 0)
21801 			return depth;
21802 		bpf_patch_call_args(insn, depth);
21803 	}
21804 	err = 0;
21805 #endif
21806 	return err;
21807 }
21808 
21809 /* 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)21810 static void specialize_kfunc(struct bpf_verifier_env *env,
21811 			     u32 func_id, u16 offset, unsigned long *addr)
21812 {
21813 	struct bpf_prog *prog = env->prog;
21814 	bool seen_direct_write;
21815 	void *xdp_kfunc;
21816 	bool is_rdonly;
21817 
21818 	if (bpf_dev_bound_kfunc_id(func_id)) {
21819 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
21820 		if (xdp_kfunc) {
21821 			*addr = (unsigned long)xdp_kfunc;
21822 			return;
21823 		}
21824 		/* fallback to default kfunc when not supported by netdev */
21825 	}
21826 
21827 	if (offset)
21828 		return;
21829 
21830 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
21831 		seen_direct_write = env->seen_direct_write;
21832 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
21833 
21834 		if (is_rdonly)
21835 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
21836 
21837 		/* restore env->seen_direct_write to its original value, since
21838 		 * may_access_direct_pkt_data mutates it
21839 		 */
21840 		env->seen_direct_write = seen_direct_write;
21841 	}
21842 
21843 	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
21844 	    bpf_lsm_has_d_inode_locked(prog))
21845 		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
21846 
21847 	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
21848 	    bpf_lsm_has_d_inode_locked(prog))
21849 		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
21850 }
21851 
__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)21852 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
21853 					    u16 struct_meta_reg,
21854 					    u16 node_offset_reg,
21855 					    struct bpf_insn *insn,
21856 					    struct bpf_insn *insn_buf,
21857 					    int *cnt)
21858 {
21859 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
21860 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
21861 
21862 	insn_buf[0] = addr[0];
21863 	insn_buf[1] = addr[1];
21864 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
21865 	insn_buf[3] = *insn;
21866 	*cnt = 4;
21867 }
21868 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)21869 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
21870 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
21871 {
21872 	const struct bpf_kfunc_desc *desc;
21873 
21874 	if (!insn->imm) {
21875 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
21876 		return -EINVAL;
21877 	}
21878 
21879 	*cnt = 0;
21880 
21881 	/* insn->imm has the btf func_id. Replace it with an offset relative to
21882 	 * __bpf_call_base, unless the JIT needs to call functions that are
21883 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
21884 	 */
21885 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
21886 	if (!desc) {
21887 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
21888 			     insn->imm);
21889 		return -EFAULT;
21890 	}
21891 
21892 	if (!bpf_jit_supports_far_kfunc_call())
21893 		insn->imm = BPF_CALL_IMM(desc->addr);
21894 	if (insn->off)
21895 		return 0;
21896 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
21897 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
21898 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21899 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21900 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
21901 
21902 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
21903 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21904 				     insn_idx);
21905 			return -EFAULT;
21906 		}
21907 
21908 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
21909 		insn_buf[1] = addr[0];
21910 		insn_buf[2] = addr[1];
21911 		insn_buf[3] = *insn;
21912 		*cnt = 4;
21913 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
21914 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
21915 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
21916 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21917 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21918 
21919 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
21920 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21921 				     insn_idx);
21922 			return -EFAULT;
21923 		}
21924 
21925 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21926 		    !kptr_struct_meta) {
21927 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21928 				     insn_idx);
21929 			return -EFAULT;
21930 		}
21931 
21932 		insn_buf[0] = addr[0];
21933 		insn_buf[1] = addr[1];
21934 		insn_buf[2] = *insn;
21935 		*cnt = 3;
21936 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21937 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21938 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21939 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21940 		int struct_meta_reg = BPF_REG_3;
21941 		int node_offset_reg = BPF_REG_4;
21942 
21943 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21944 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21945 			struct_meta_reg = BPF_REG_4;
21946 			node_offset_reg = BPF_REG_5;
21947 		}
21948 
21949 		if (!kptr_struct_meta) {
21950 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21951 				     insn_idx);
21952 			return -EFAULT;
21953 		}
21954 
21955 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21956 						node_offset_reg, insn, insn_buf, cnt);
21957 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21958 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21959 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21960 		*cnt = 1;
21961 	}
21962 
21963 	if (env->insn_aux_data[insn_idx].arg_prog) {
21964 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
21965 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
21966 		int idx = *cnt;
21967 
21968 		insn_buf[idx++] = ld_addrs[0];
21969 		insn_buf[idx++] = ld_addrs[1];
21970 		insn_buf[idx++] = *insn;
21971 		*cnt = idx;
21972 	}
21973 	return 0;
21974 }
21975 
21976 /* 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)21977 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21978 {
21979 	struct bpf_subprog_info *info = env->subprog_info;
21980 	int cnt = env->subprog_cnt;
21981 	struct bpf_prog *prog;
21982 
21983 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21984 	if (env->hidden_subprog_cnt) {
21985 		verifier_bug(env, "only one hidden subprog supported");
21986 		return -EFAULT;
21987 	}
21988 	/* We're not patching any existing instruction, just appending the new
21989 	 * ones for the hidden subprog. Hence all of the adjustment operations
21990 	 * in bpf_patch_insn_data are no-ops.
21991 	 */
21992 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
21993 	if (!prog)
21994 		return -ENOMEM;
21995 	env->prog = prog;
21996 	info[cnt + 1].start = info[cnt].start;
21997 	info[cnt].start = prog->len - len + 1;
21998 	env->subprog_cnt++;
21999 	env->hidden_subprog_cnt++;
22000 	return 0;
22001 }
22002 
22003 /* Do various post-verification rewrites in a single program pass.
22004  * These rewrites simplify JIT and interpreter implementations.
22005  */
do_misc_fixups(struct bpf_verifier_env * env)22006 static int do_misc_fixups(struct bpf_verifier_env *env)
22007 {
22008 	struct bpf_prog *prog = env->prog;
22009 	enum bpf_attach_type eatype = prog->expected_attach_type;
22010 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22011 	struct bpf_insn *insn = prog->insnsi;
22012 	const struct bpf_func_proto *fn;
22013 	const int insn_cnt = prog->len;
22014 	const struct bpf_map_ops *ops;
22015 	struct bpf_insn_aux_data *aux;
22016 	struct bpf_insn *insn_buf = env->insn_buf;
22017 	struct bpf_prog *new_prog;
22018 	struct bpf_map *map_ptr;
22019 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22020 	struct bpf_subprog_info *subprogs = env->subprog_info;
22021 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22022 	u16 stack_depth_extra = 0;
22023 
22024 	if (env->seen_exception && !env->exception_callback_subprog) {
22025 		struct bpf_insn *patch = insn_buf;
22026 
22027 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22028 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22029 		*patch++ = BPF_EXIT_INSN();
22030 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22031 		if (ret < 0)
22032 			return ret;
22033 		prog = env->prog;
22034 		insn = prog->insnsi;
22035 
22036 		env->exception_callback_subprog = env->subprog_cnt - 1;
22037 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22038 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22039 	}
22040 
22041 	for (i = 0; i < insn_cnt;) {
22042 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22043 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22044 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22045 				/* convert to 32-bit mov that clears upper 32-bit */
22046 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22047 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22048 				insn->off = 0;
22049 				insn->imm = 0;
22050 			} /* cast from as(0) to as(1) should be handled by JIT */
22051 			goto next_insn;
22052 		}
22053 
22054 		if (env->insn_aux_data[i + delta].needs_zext)
22055 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22056 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22057 
22058 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22059 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22060 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22061 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22062 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22063 		    insn->off == 1 && insn->imm == -1) {
22064 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22065 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22066 			struct bpf_insn *patch = insn_buf;
22067 
22068 			if (isdiv)
22069 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22070 							BPF_NEG | BPF_K, insn->dst_reg,
22071 							0, 0, 0);
22072 			else
22073 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22074 
22075 			cnt = patch - insn_buf;
22076 
22077 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22078 			if (!new_prog)
22079 				return -ENOMEM;
22080 
22081 			delta    += cnt - 1;
22082 			env->prog = prog = new_prog;
22083 			insn      = new_prog->insnsi + i + delta;
22084 			goto next_insn;
22085 		}
22086 
22087 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22088 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22089 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22090 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22091 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22092 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22093 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22094 			bool is_sdiv = isdiv && insn->off == 1;
22095 			bool is_smod = !isdiv && insn->off == 1;
22096 			struct bpf_insn *patch = insn_buf;
22097 
22098 			if (is_sdiv) {
22099 				/* [R,W]x sdiv 0 -> 0
22100 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22101 				 * INT_MIN sdiv -1 -> INT_MIN
22102 				 */
22103 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22104 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22105 							BPF_ADD | BPF_K, BPF_REG_AX,
22106 							0, 0, 1);
22107 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22108 							BPF_JGT | BPF_K, BPF_REG_AX,
22109 							0, 4, 1);
22110 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22111 							BPF_JEQ | BPF_K, BPF_REG_AX,
22112 							0, 1, 0);
22113 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22114 							BPF_MOV | BPF_K, insn->dst_reg,
22115 							0, 0, 0);
22116 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22117 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22118 							BPF_NEG | BPF_K, insn->dst_reg,
22119 							0, 0, 0);
22120 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22121 				*patch++ = *insn;
22122 				cnt = patch - insn_buf;
22123 			} else if (is_smod) {
22124 				/* [R,W]x mod 0 -> [R,W]x */
22125 				/* [R,W]x mod -1 -> 0 */
22126 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22127 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22128 							BPF_ADD | BPF_K, BPF_REG_AX,
22129 							0, 0, 1);
22130 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22131 							BPF_JGT | BPF_K, BPF_REG_AX,
22132 							0, 3, 1);
22133 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22134 							BPF_JEQ | BPF_K, BPF_REG_AX,
22135 							0, 3 + (is64 ? 0 : 1), 1);
22136 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22137 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22138 				*patch++ = *insn;
22139 
22140 				if (!is64) {
22141 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22142 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22143 				}
22144 				cnt = patch - insn_buf;
22145 			} else if (isdiv) {
22146 				/* [R,W]x div 0 -> 0 */
22147 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22148 							BPF_JNE | BPF_K, insn->src_reg,
22149 							0, 2, 0);
22150 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22151 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22152 				*patch++ = *insn;
22153 				cnt = patch - insn_buf;
22154 			} else {
22155 				/* [R,W]x mod 0 -> [R,W]x */
22156 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22157 							BPF_JEQ | BPF_K, insn->src_reg,
22158 							0, 1 + (is64 ? 0 : 1), 0);
22159 				*patch++ = *insn;
22160 
22161 				if (!is64) {
22162 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22163 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22164 				}
22165 				cnt = patch - insn_buf;
22166 			}
22167 
22168 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22169 			if (!new_prog)
22170 				return -ENOMEM;
22171 
22172 			delta    += cnt - 1;
22173 			env->prog = prog = new_prog;
22174 			insn      = new_prog->insnsi + i + delta;
22175 			goto next_insn;
22176 		}
22177 
22178 		/* Make it impossible to de-reference a userspace address */
22179 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22180 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22181 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22182 			struct bpf_insn *patch = insn_buf;
22183 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22184 
22185 			if (!uaddress_limit)
22186 				goto next_insn;
22187 
22188 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22189 			if (insn->off)
22190 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22191 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22192 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22193 			*patch++ = *insn;
22194 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22195 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22196 
22197 			cnt = patch - insn_buf;
22198 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22199 			if (!new_prog)
22200 				return -ENOMEM;
22201 
22202 			delta    += cnt - 1;
22203 			env->prog = prog = new_prog;
22204 			insn      = new_prog->insnsi + i + delta;
22205 			goto next_insn;
22206 		}
22207 
22208 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22209 		if (BPF_CLASS(insn->code) == BPF_LD &&
22210 		    (BPF_MODE(insn->code) == BPF_ABS ||
22211 		     BPF_MODE(insn->code) == BPF_IND)) {
22212 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22213 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22214 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22215 				return -EFAULT;
22216 			}
22217 
22218 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22219 			if (!new_prog)
22220 				return -ENOMEM;
22221 
22222 			delta    += cnt - 1;
22223 			env->prog = prog = new_prog;
22224 			insn      = new_prog->insnsi + i + delta;
22225 			goto next_insn;
22226 		}
22227 
22228 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22229 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22230 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22231 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22232 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22233 			struct bpf_insn *patch = insn_buf;
22234 			bool issrc, isneg, isimm;
22235 			u32 off_reg;
22236 
22237 			aux = &env->insn_aux_data[i + delta];
22238 			if (!aux->alu_state ||
22239 			    aux->alu_state == BPF_ALU_NON_POINTER)
22240 				goto next_insn;
22241 
22242 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22243 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22244 				BPF_ALU_SANITIZE_SRC;
22245 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22246 
22247 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22248 			if (isimm) {
22249 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22250 			} else {
22251 				if (isneg)
22252 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22253 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22254 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22255 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22256 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22257 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22258 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22259 			}
22260 			if (!issrc)
22261 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22262 			insn->src_reg = BPF_REG_AX;
22263 			if (isneg)
22264 				insn->code = insn->code == code_add ?
22265 					     code_sub : code_add;
22266 			*patch++ = *insn;
22267 			if (issrc && isneg && !isimm)
22268 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22269 			cnt = patch - insn_buf;
22270 
22271 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22272 			if (!new_prog)
22273 				return -ENOMEM;
22274 
22275 			delta    += cnt - 1;
22276 			env->prog = prog = new_prog;
22277 			insn      = new_prog->insnsi + i + delta;
22278 			goto next_insn;
22279 		}
22280 
22281 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22282 			int stack_off_cnt = -stack_depth - 16;
22283 
22284 			/*
22285 			 * Two 8 byte slots, depth-16 stores the count, and
22286 			 * depth-8 stores the start timestamp of the loop.
22287 			 *
22288 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22289 			 * (0xffff).  Every iteration loads it and subs it by 1,
22290 			 * until the value becomes 0 in AX (thus, 1 in stack),
22291 			 * after which we call arch_bpf_timed_may_goto, which
22292 			 * either sets AX to 0xffff to keep looping, or to 0
22293 			 * upon timeout. AX is then stored into the stack. In
22294 			 * the next iteration, we either see 0 and break out, or
22295 			 * continue iterating until the next time value is 0
22296 			 * after subtraction, rinse and repeat.
22297 			 */
22298 			stack_depth_extra = 16;
22299 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22300 			if (insn->off >= 0)
22301 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22302 			else
22303 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22304 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22305 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22306 			/*
22307 			 * AX is used as an argument to pass in stack_off_cnt
22308 			 * (to add to r10/fp), and also as the return value of
22309 			 * the call to arch_bpf_timed_may_goto.
22310 			 */
22311 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22312 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22313 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22314 			cnt = 7;
22315 
22316 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22317 			if (!new_prog)
22318 				return -ENOMEM;
22319 
22320 			delta += cnt - 1;
22321 			env->prog = prog = new_prog;
22322 			insn = new_prog->insnsi + i + delta;
22323 			goto next_insn;
22324 		} else if (is_may_goto_insn(insn)) {
22325 			int stack_off = -stack_depth - 8;
22326 
22327 			stack_depth_extra = 8;
22328 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22329 			if (insn->off >= 0)
22330 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22331 			else
22332 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22333 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22334 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22335 			cnt = 4;
22336 
22337 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22338 			if (!new_prog)
22339 				return -ENOMEM;
22340 
22341 			delta += cnt - 1;
22342 			env->prog = prog = new_prog;
22343 			insn = new_prog->insnsi + i + delta;
22344 			goto next_insn;
22345 		}
22346 
22347 		if (insn->code != (BPF_JMP | BPF_CALL))
22348 			goto next_insn;
22349 		if (insn->src_reg == BPF_PSEUDO_CALL)
22350 			goto next_insn;
22351 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22352 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22353 			if (ret)
22354 				return ret;
22355 			if (cnt == 0)
22356 				goto next_insn;
22357 
22358 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22359 			if (!new_prog)
22360 				return -ENOMEM;
22361 
22362 			delta	 += cnt - 1;
22363 			env->prog = prog = new_prog;
22364 			insn	  = new_prog->insnsi + i + delta;
22365 			goto next_insn;
22366 		}
22367 
22368 		/* Skip inlining the helper call if the JIT does it. */
22369 		if (bpf_jit_inlines_helper_call(insn->imm))
22370 			goto next_insn;
22371 
22372 		if (insn->imm == BPF_FUNC_get_route_realm)
22373 			prog->dst_needed = 1;
22374 		if (insn->imm == BPF_FUNC_get_prandom_u32)
22375 			bpf_user_rnd_init_once();
22376 		if (insn->imm == BPF_FUNC_override_return)
22377 			prog->kprobe_override = 1;
22378 		if (insn->imm == BPF_FUNC_tail_call) {
22379 			/* If we tail call into other programs, we
22380 			 * cannot make any assumptions since they can
22381 			 * be replaced dynamically during runtime in
22382 			 * the program array.
22383 			 */
22384 			prog->cb_access = 1;
22385 			if (!allow_tail_call_in_subprogs(env))
22386 				prog->aux->stack_depth = MAX_BPF_STACK;
22387 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22388 
22389 			/* mark bpf_tail_call as different opcode to avoid
22390 			 * conditional branch in the interpreter for every normal
22391 			 * call and to prevent accidental JITing by JIT compiler
22392 			 * that doesn't support bpf_tail_call yet
22393 			 */
22394 			insn->imm = 0;
22395 			insn->code = BPF_JMP | BPF_TAIL_CALL;
22396 
22397 			aux = &env->insn_aux_data[i + delta];
22398 			if (env->bpf_capable && !prog->blinding_requested &&
22399 			    prog->jit_requested &&
22400 			    !bpf_map_key_poisoned(aux) &&
22401 			    !bpf_map_ptr_poisoned(aux) &&
22402 			    !bpf_map_ptr_unpriv(aux)) {
22403 				struct bpf_jit_poke_descriptor desc = {
22404 					.reason = BPF_POKE_REASON_TAIL_CALL,
22405 					.tail_call.map = aux->map_ptr_state.map_ptr,
22406 					.tail_call.key = bpf_map_key_immediate(aux),
22407 					.insn_idx = i + delta,
22408 				};
22409 
22410 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
22411 				if (ret < 0) {
22412 					verbose(env, "adding tail call poke descriptor failed\n");
22413 					return ret;
22414 				}
22415 
22416 				insn->imm = ret + 1;
22417 				goto next_insn;
22418 			}
22419 
22420 			if (!bpf_map_ptr_unpriv(aux))
22421 				goto next_insn;
22422 
22423 			/* instead of changing every JIT dealing with tail_call
22424 			 * emit two extra insns:
22425 			 * if (index >= max_entries) goto out;
22426 			 * index &= array->index_mask;
22427 			 * to avoid out-of-bounds cpu speculation
22428 			 */
22429 			if (bpf_map_ptr_poisoned(aux)) {
22430 				verbose(env, "tail_call abusing map_ptr\n");
22431 				return -EINVAL;
22432 			}
22433 
22434 			map_ptr = aux->map_ptr_state.map_ptr;
22435 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
22436 						  map_ptr->max_entries, 2);
22437 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
22438 						    container_of(map_ptr,
22439 								 struct bpf_array,
22440 								 map)->index_mask);
22441 			insn_buf[2] = *insn;
22442 			cnt = 3;
22443 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22444 			if (!new_prog)
22445 				return -ENOMEM;
22446 
22447 			delta    += cnt - 1;
22448 			env->prog = prog = new_prog;
22449 			insn      = new_prog->insnsi + i + delta;
22450 			goto next_insn;
22451 		}
22452 
22453 		if (insn->imm == BPF_FUNC_timer_set_callback) {
22454 			/* The verifier will process callback_fn as many times as necessary
22455 			 * with different maps and the register states prepared by
22456 			 * set_timer_callback_state will be accurate.
22457 			 *
22458 			 * The following use case is valid:
22459 			 *   map1 is shared by prog1, prog2, prog3.
22460 			 *   prog1 calls bpf_timer_init for some map1 elements
22461 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
22462 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
22463 			 *   prog3 calls bpf_timer_start for some map1 elements.
22464 			 *     Those that were not both bpf_timer_init-ed and
22465 			 *     bpf_timer_set_callback-ed will return -EINVAL.
22466 			 */
22467 			struct bpf_insn ld_addrs[2] = {
22468 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
22469 			};
22470 
22471 			insn_buf[0] = ld_addrs[0];
22472 			insn_buf[1] = ld_addrs[1];
22473 			insn_buf[2] = *insn;
22474 			cnt = 3;
22475 
22476 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22477 			if (!new_prog)
22478 				return -ENOMEM;
22479 
22480 			delta    += cnt - 1;
22481 			env->prog = prog = new_prog;
22482 			insn      = new_prog->insnsi + i + delta;
22483 			goto patch_call_imm;
22484 		}
22485 
22486 		if (is_storage_get_function(insn->imm)) {
22487 			if (!in_sleepable(env) ||
22488 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
22489 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
22490 			else
22491 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
22492 			insn_buf[1] = *insn;
22493 			cnt = 2;
22494 
22495 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22496 			if (!new_prog)
22497 				return -ENOMEM;
22498 
22499 			delta += cnt - 1;
22500 			env->prog = prog = new_prog;
22501 			insn = new_prog->insnsi + i + delta;
22502 			goto patch_call_imm;
22503 		}
22504 
22505 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
22506 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
22507 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
22508 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
22509 			 */
22510 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
22511 			insn_buf[1] = *insn;
22512 			cnt = 2;
22513 
22514 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22515 			if (!new_prog)
22516 				return -ENOMEM;
22517 
22518 			delta += cnt - 1;
22519 			env->prog = prog = new_prog;
22520 			insn = new_prog->insnsi + i + delta;
22521 			goto patch_call_imm;
22522 		}
22523 
22524 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
22525 		 * and other inlining handlers are currently limited to 64 bit
22526 		 * only.
22527 		 */
22528 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22529 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
22530 		     insn->imm == BPF_FUNC_map_update_elem ||
22531 		     insn->imm == BPF_FUNC_map_delete_elem ||
22532 		     insn->imm == BPF_FUNC_map_push_elem   ||
22533 		     insn->imm == BPF_FUNC_map_pop_elem    ||
22534 		     insn->imm == BPF_FUNC_map_peek_elem   ||
22535 		     insn->imm == BPF_FUNC_redirect_map    ||
22536 		     insn->imm == BPF_FUNC_for_each_map_elem ||
22537 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
22538 			aux = &env->insn_aux_data[i + delta];
22539 			if (bpf_map_ptr_poisoned(aux))
22540 				goto patch_call_imm;
22541 
22542 			map_ptr = aux->map_ptr_state.map_ptr;
22543 			ops = map_ptr->ops;
22544 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
22545 			    ops->map_gen_lookup) {
22546 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
22547 				if (cnt == -EOPNOTSUPP)
22548 					goto patch_map_ops_generic;
22549 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
22550 					verifier_bug(env, "%d insns generated for map lookup", cnt);
22551 					return -EFAULT;
22552 				}
22553 
22554 				new_prog = bpf_patch_insn_data(env, i + delta,
22555 							       insn_buf, cnt);
22556 				if (!new_prog)
22557 					return -ENOMEM;
22558 
22559 				delta    += cnt - 1;
22560 				env->prog = prog = new_prog;
22561 				insn      = new_prog->insnsi + i + delta;
22562 				goto next_insn;
22563 			}
22564 
22565 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
22566 				     (void *(*)(struct bpf_map *map, void *key))NULL));
22567 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
22568 				     (long (*)(struct bpf_map *map, void *key))NULL));
22569 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
22570 				     (long (*)(struct bpf_map *map, void *key, void *value,
22571 					      u64 flags))NULL));
22572 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
22573 				     (long (*)(struct bpf_map *map, void *value,
22574 					      u64 flags))NULL));
22575 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
22576 				     (long (*)(struct bpf_map *map, void *value))NULL));
22577 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
22578 				     (long (*)(struct bpf_map *map, void *value))NULL));
22579 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
22580 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
22581 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
22582 				     (long (*)(struct bpf_map *map,
22583 					      bpf_callback_t callback_fn,
22584 					      void *callback_ctx,
22585 					      u64 flags))NULL));
22586 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
22587 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
22588 
22589 patch_map_ops_generic:
22590 			switch (insn->imm) {
22591 			case BPF_FUNC_map_lookup_elem:
22592 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
22593 				goto next_insn;
22594 			case BPF_FUNC_map_update_elem:
22595 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
22596 				goto next_insn;
22597 			case BPF_FUNC_map_delete_elem:
22598 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
22599 				goto next_insn;
22600 			case BPF_FUNC_map_push_elem:
22601 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
22602 				goto next_insn;
22603 			case BPF_FUNC_map_pop_elem:
22604 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
22605 				goto next_insn;
22606 			case BPF_FUNC_map_peek_elem:
22607 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
22608 				goto next_insn;
22609 			case BPF_FUNC_redirect_map:
22610 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
22611 				goto next_insn;
22612 			case BPF_FUNC_for_each_map_elem:
22613 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
22614 				goto next_insn;
22615 			case BPF_FUNC_map_lookup_percpu_elem:
22616 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
22617 				goto next_insn;
22618 			}
22619 
22620 			goto patch_call_imm;
22621 		}
22622 
22623 		/* Implement bpf_jiffies64 inline. */
22624 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22625 		    insn->imm == BPF_FUNC_jiffies64) {
22626 			struct bpf_insn ld_jiffies_addr[2] = {
22627 				BPF_LD_IMM64(BPF_REG_0,
22628 					     (unsigned long)&jiffies),
22629 			};
22630 
22631 			insn_buf[0] = ld_jiffies_addr[0];
22632 			insn_buf[1] = ld_jiffies_addr[1];
22633 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
22634 						  BPF_REG_0, 0);
22635 			cnt = 3;
22636 
22637 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
22638 						       cnt);
22639 			if (!new_prog)
22640 				return -ENOMEM;
22641 
22642 			delta    += cnt - 1;
22643 			env->prog = prog = new_prog;
22644 			insn      = new_prog->insnsi + i + delta;
22645 			goto next_insn;
22646 		}
22647 
22648 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
22649 		/* Implement bpf_get_smp_processor_id() inline. */
22650 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
22651 		    verifier_inlines_helper_call(env, insn->imm)) {
22652 			/* BPF_FUNC_get_smp_processor_id inlining is an
22653 			 * optimization, so if cpu_number is ever
22654 			 * changed in some incompatible and hard to support
22655 			 * way, it's fine to back out this inlining logic
22656 			 */
22657 #ifdef CONFIG_SMP
22658 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
22659 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
22660 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
22661 			cnt = 3;
22662 #else
22663 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
22664 			cnt = 1;
22665 #endif
22666 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22667 			if (!new_prog)
22668 				return -ENOMEM;
22669 
22670 			delta    += cnt - 1;
22671 			env->prog = prog = new_prog;
22672 			insn      = new_prog->insnsi + i + delta;
22673 			goto next_insn;
22674 		}
22675 #endif
22676 		/* Implement bpf_get_func_arg inline. */
22677 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22678 		    insn->imm == BPF_FUNC_get_func_arg) {
22679 			/* Load nr_args from ctx - 8 */
22680 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22681 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
22682 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
22683 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
22684 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
22685 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22686 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
22687 			insn_buf[7] = BPF_JMP_A(1);
22688 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22689 			cnt = 9;
22690 
22691 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22692 			if (!new_prog)
22693 				return -ENOMEM;
22694 
22695 			delta    += cnt - 1;
22696 			env->prog = prog = new_prog;
22697 			insn      = new_prog->insnsi + i + delta;
22698 			goto next_insn;
22699 		}
22700 
22701 		/* Implement bpf_get_func_ret inline. */
22702 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22703 		    insn->imm == BPF_FUNC_get_func_ret) {
22704 			if (eatype == BPF_TRACE_FEXIT ||
22705 			    eatype == BPF_MODIFY_RETURN) {
22706 				/* Load nr_args from ctx - 8 */
22707 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22708 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22709 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
22710 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22711 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
22712 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
22713 				cnt = 6;
22714 			} else {
22715 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
22716 				cnt = 1;
22717 			}
22718 
22719 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22720 			if (!new_prog)
22721 				return -ENOMEM;
22722 
22723 			delta    += cnt - 1;
22724 			env->prog = prog = new_prog;
22725 			insn      = new_prog->insnsi + i + delta;
22726 			goto next_insn;
22727 		}
22728 
22729 		/* Implement get_func_arg_cnt inline. */
22730 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22731 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
22732 			/* Load nr_args from ctx - 8 */
22733 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22734 
22735 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22736 			if (!new_prog)
22737 				return -ENOMEM;
22738 
22739 			env->prog = prog = new_prog;
22740 			insn      = new_prog->insnsi + i + delta;
22741 			goto next_insn;
22742 		}
22743 
22744 		/* Implement bpf_get_func_ip inline. */
22745 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22746 		    insn->imm == BPF_FUNC_get_func_ip) {
22747 			/* Load IP address from ctx - 16 */
22748 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
22749 
22750 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22751 			if (!new_prog)
22752 				return -ENOMEM;
22753 
22754 			env->prog = prog = new_prog;
22755 			insn      = new_prog->insnsi + i + delta;
22756 			goto next_insn;
22757 		}
22758 
22759 		/* Implement bpf_get_branch_snapshot inline. */
22760 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
22761 		    prog->jit_requested && BITS_PER_LONG == 64 &&
22762 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
22763 			/* We are dealing with the following func protos:
22764 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
22765 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
22766 			 */
22767 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
22768 
22769 			/* struct perf_branch_entry is part of UAPI and is
22770 			 * used as an array element, so extremely unlikely to
22771 			 * ever grow or shrink
22772 			 */
22773 			BUILD_BUG_ON(br_entry_size != 24);
22774 
22775 			/* if (unlikely(flags)) return -EINVAL */
22776 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
22777 
22778 			/* Transform size (bytes) into number of entries (cnt = size / 24).
22779 			 * But to avoid expensive division instruction, we implement
22780 			 * divide-by-3 through multiplication, followed by further
22781 			 * division by 8 through 3-bit right shift.
22782 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
22783 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
22784 			 *
22785 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
22786 			 */
22787 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
22788 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
22789 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
22790 
22791 			/* call perf_snapshot_branch_stack implementation */
22792 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
22793 			/* if (entry_cnt == 0) return -ENOENT */
22794 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
22795 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
22796 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
22797 			insn_buf[7] = BPF_JMP_A(3);
22798 			/* return -EINVAL; */
22799 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22800 			insn_buf[9] = BPF_JMP_A(1);
22801 			/* return -ENOENT; */
22802 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
22803 			cnt = 11;
22804 
22805 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22806 			if (!new_prog)
22807 				return -ENOMEM;
22808 
22809 			delta    += cnt - 1;
22810 			env->prog = prog = new_prog;
22811 			insn      = new_prog->insnsi + i + delta;
22812 			goto next_insn;
22813 		}
22814 
22815 		/* Implement bpf_kptr_xchg inline */
22816 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22817 		    insn->imm == BPF_FUNC_kptr_xchg &&
22818 		    bpf_jit_supports_ptr_xchg()) {
22819 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
22820 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
22821 			cnt = 2;
22822 
22823 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22824 			if (!new_prog)
22825 				return -ENOMEM;
22826 
22827 			delta    += cnt - 1;
22828 			env->prog = prog = new_prog;
22829 			insn      = new_prog->insnsi + i + delta;
22830 			goto next_insn;
22831 		}
22832 patch_call_imm:
22833 		fn = env->ops->get_func_proto(insn->imm, env->prog);
22834 		/* all functions that have prototype and verifier allowed
22835 		 * programs to call them, must be real in-kernel functions
22836 		 */
22837 		if (!fn->func) {
22838 			verifier_bug(env,
22839 				     "not inlined functions %s#%d is missing func",
22840 				     func_id_name(insn->imm), insn->imm);
22841 			return -EFAULT;
22842 		}
22843 		insn->imm = fn->func - __bpf_call_base;
22844 next_insn:
22845 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22846 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22847 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
22848 
22849 			stack_depth = subprogs[cur_subprog].stack_depth;
22850 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
22851 				verbose(env, "stack size %d(extra %d) is too large\n",
22852 					stack_depth, stack_depth_extra);
22853 				return -EINVAL;
22854 			}
22855 			cur_subprog++;
22856 			stack_depth = subprogs[cur_subprog].stack_depth;
22857 			stack_depth_extra = 0;
22858 		}
22859 		i++;
22860 		insn++;
22861 	}
22862 
22863 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
22864 	for (i = 0; i < env->subprog_cnt; i++) {
22865 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
22866 		int subprog_start = subprogs[i].start;
22867 		int stack_slots = subprogs[i].stack_extra / 8;
22868 		int slots = delta, cnt = 0;
22869 
22870 		if (!stack_slots)
22871 			continue;
22872 		/* We need two slots in case timed may_goto is supported. */
22873 		if (stack_slots > slots) {
22874 			verifier_bug(env, "stack_slots supports may_goto only");
22875 			return -EFAULT;
22876 		}
22877 
22878 		stack_depth = subprogs[i].stack_depth;
22879 		if (bpf_jit_supports_timed_may_goto()) {
22880 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22881 						     BPF_MAX_TIMED_LOOPS);
22882 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
22883 		} else {
22884 			/* Add ST insn to subprog prologue to init extra stack */
22885 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22886 						     BPF_MAX_LOOPS);
22887 		}
22888 		/* Copy first actual insn to preserve it */
22889 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
22890 
22891 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
22892 		if (!new_prog)
22893 			return -ENOMEM;
22894 		env->prog = prog = new_prog;
22895 		/*
22896 		 * If may_goto is a first insn of a prog there could be a jmp
22897 		 * insn that points to it, hence adjust all such jmps to point
22898 		 * to insn after BPF_ST that inits may_goto count.
22899 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
22900 		 */
22901 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
22902 	}
22903 
22904 	/* Since poke tab is now finalized, publish aux to tracker. */
22905 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22906 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22907 		if (!map_ptr->ops->map_poke_track ||
22908 		    !map_ptr->ops->map_poke_untrack ||
22909 		    !map_ptr->ops->map_poke_run) {
22910 			verifier_bug(env, "poke tab is misconfigured");
22911 			return -EFAULT;
22912 		}
22913 
22914 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
22915 		if (ret < 0) {
22916 			verbose(env, "tracking tail call prog failed\n");
22917 			return ret;
22918 		}
22919 	}
22920 
22921 	sort_kfunc_descs_by_imm_off(env->prog);
22922 
22923 	return 0;
22924 }
22925 
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * total_cnt)22926 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
22927 					int position,
22928 					s32 stack_base,
22929 					u32 callback_subprogno,
22930 					u32 *total_cnt)
22931 {
22932 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
22933 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
22934 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
22935 	int reg_loop_max = BPF_REG_6;
22936 	int reg_loop_cnt = BPF_REG_7;
22937 	int reg_loop_ctx = BPF_REG_8;
22938 
22939 	struct bpf_insn *insn_buf = env->insn_buf;
22940 	struct bpf_prog *new_prog;
22941 	u32 callback_start;
22942 	u32 call_insn_offset;
22943 	s32 callback_offset;
22944 	u32 cnt = 0;
22945 
22946 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
22947 	 * be careful to modify this code in sync.
22948 	 */
22949 
22950 	/* Return error and jump to the end of the patch if
22951 	 * expected number of iterations is too big.
22952 	 */
22953 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
22954 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
22955 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
22956 	/* spill R6, R7, R8 to use these as loop vars */
22957 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
22958 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
22959 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
22960 	/* initialize loop vars */
22961 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
22962 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
22963 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
22964 	/* loop header,
22965 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
22966 	 */
22967 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
22968 	/* callback call,
22969 	 * correct callback offset would be set after patching
22970 	 */
22971 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
22972 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
22973 	insn_buf[cnt++] = BPF_CALL_REL(0);
22974 	/* increment loop counter */
22975 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
22976 	/* jump to loop header if callback returned 0 */
22977 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
22978 	/* return value of bpf_loop,
22979 	 * set R0 to the number of iterations
22980 	 */
22981 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22982 	/* restore original values of R6, R7, R8 */
22983 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22984 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22985 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22986 
22987 	*total_cnt = cnt;
22988 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
22989 	if (!new_prog)
22990 		return new_prog;
22991 
22992 	/* callback start is known only after patching */
22993 	callback_start = env->subprog_info[callback_subprogno].start;
22994 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
22995 	call_insn_offset = position + 12;
22996 	callback_offset = callback_start - call_insn_offset - 1;
22997 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
22998 
22999 	return new_prog;
23000 }
23001 
is_bpf_loop_call(struct bpf_insn * insn)23002 static bool is_bpf_loop_call(struct bpf_insn *insn)
23003 {
23004 	return insn->code == (BPF_JMP | BPF_CALL) &&
23005 		insn->src_reg == 0 &&
23006 		insn->imm == BPF_FUNC_loop;
23007 }
23008 
23009 /* For all sub-programs in the program (including main) check
23010  * insn_aux_data to see if there are bpf_loop calls that require
23011  * inlining. If such calls are found the calls are replaced with a
23012  * sequence of instructions produced by `inline_bpf_loop` function and
23013  * subprog stack_depth is increased by the size of 3 registers.
23014  * This stack space is used to spill values of the R6, R7, R8.  These
23015  * registers are used to store the loop bound, counter and context
23016  * variables.
23017  */
optimize_bpf_loop(struct bpf_verifier_env * env)23018 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23019 {
23020 	struct bpf_subprog_info *subprogs = env->subprog_info;
23021 	int i, cur_subprog = 0, cnt, delta = 0;
23022 	struct bpf_insn *insn = env->prog->insnsi;
23023 	int insn_cnt = env->prog->len;
23024 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23025 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23026 	u16 stack_depth_extra = 0;
23027 
23028 	for (i = 0; i < insn_cnt; i++, insn++) {
23029 		struct bpf_loop_inline_state *inline_state =
23030 			&env->insn_aux_data[i + delta].loop_inline_state;
23031 
23032 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23033 			struct bpf_prog *new_prog;
23034 
23035 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23036 			new_prog = inline_bpf_loop(env,
23037 						   i + delta,
23038 						   -(stack_depth + stack_depth_extra),
23039 						   inline_state->callback_subprogno,
23040 						   &cnt);
23041 			if (!new_prog)
23042 				return -ENOMEM;
23043 
23044 			delta     += cnt - 1;
23045 			env->prog  = new_prog;
23046 			insn       = new_prog->insnsi + i + delta;
23047 		}
23048 
23049 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23050 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23051 			cur_subprog++;
23052 			stack_depth = subprogs[cur_subprog].stack_depth;
23053 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23054 			stack_depth_extra = 0;
23055 		}
23056 	}
23057 
23058 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23059 
23060 	return 0;
23061 }
23062 
23063 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23064  * adjust subprograms stack depth when possible.
23065  */
remove_fastcall_spills_fills(struct bpf_verifier_env * env)23066 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23067 {
23068 	struct bpf_subprog_info *subprog = env->subprog_info;
23069 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23070 	struct bpf_insn *insn = env->prog->insnsi;
23071 	int insn_cnt = env->prog->len;
23072 	u32 spills_num;
23073 	bool modified = false;
23074 	int i, j;
23075 
23076 	for (i = 0; i < insn_cnt; i++, insn++) {
23077 		if (aux[i].fastcall_spills_num > 0) {
23078 			spills_num = aux[i].fastcall_spills_num;
23079 			/* NOPs would be removed by opt_remove_nops() */
23080 			for (j = 1; j <= spills_num; ++j) {
23081 				*(insn - j) = NOP;
23082 				*(insn + j) = NOP;
23083 			}
23084 			modified = true;
23085 		}
23086 		if ((subprog + 1)->start == i + 1) {
23087 			if (modified && !subprog->keep_fastcall_stack)
23088 				subprog->stack_depth = -subprog->fastcall_stack_off;
23089 			subprog++;
23090 			modified = false;
23091 		}
23092 	}
23093 
23094 	return 0;
23095 }
23096 
free_states(struct bpf_verifier_env * env)23097 static void free_states(struct bpf_verifier_env *env)
23098 {
23099 	struct bpf_verifier_state_list *sl;
23100 	struct list_head *head, *pos, *tmp;
23101 	struct bpf_scc_info *info;
23102 	int i, j;
23103 
23104 	free_verifier_state(env->cur_state, true);
23105 	env->cur_state = NULL;
23106 	while (!pop_stack(env, NULL, NULL, false));
23107 
23108 	list_for_each_safe(pos, tmp, &env->free_list) {
23109 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23110 		free_verifier_state(&sl->state, false);
23111 		kfree(sl);
23112 	}
23113 	INIT_LIST_HEAD(&env->free_list);
23114 
23115 	for (i = 0; i < env->scc_cnt; ++i) {
23116 		info = env->scc_info[i];
23117 		if (!info)
23118 			continue;
23119 		for (j = 0; j < info->num_visits; j++)
23120 			free_backedges(&info->visits[j]);
23121 		kvfree(info);
23122 		env->scc_info[i] = NULL;
23123 	}
23124 
23125 	if (!env->explored_states)
23126 		return;
23127 
23128 	for (i = 0; i < state_htab_size(env); i++) {
23129 		head = &env->explored_states[i];
23130 
23131 		list_for_each_safe(pos, tmp, head) {
23132 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23133 			free_verifier_state(&sl->state, false);
23134 			kfree(sl);
23135 		}
23136 		INIT_LIST_HEAD(&env->explored_states[i]);
23137 	}
23138 }
23139 
do_check_common(struct bpf_verifier_env * env,int subprog)23140 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23141 {
23142 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23143 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23144 	struct bpf_prog_aux *aux = env->prog->aux;
23145 	struct bpf_verifier_state *state;
23146 	struct bpf_reg_state *regs;
23147 	int ret, i;
23148 
23149 	env->prev_linfo = NULL;
23150 	env->pass_cnt++;
23151 
23152 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23153 	if (!state)
23154 		return -ENOMEM;
23155 	state->curframe = 0;
23156 	state->speculative = false;
23157 	state->branches = 1;
23158 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23159 	if (!state->frame[0]) {
23160 		kfree(state);
23161 		return -ENOMEM;
23162 	}
23163 	env->cur_state = state;
23164 	init_func_state(env, state->frame[0],
23165 			BPF_MAIN_FUNC /* callsite */,
23166 			0 /* frameno */,
23167 			subprog);
23168 	state->first_insn_idx = env->subprog_info[subprog].start;
23169 	state->last_insn_idx = -1;
23170 
23171 	regs = state->frame[state->curframe]->regs;
23172 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23173 		const char *sub_name = subprog_name(env, subprog);
23174 		struct bpf_subprog_arg_info *arg;
23175 		struct bpf_reg_state *reg;
23176 
23177 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23178 		ret = btf_prepare_func_args(env, subprog);
23179 		if (ret)
23180 			goto out;
23181 
23182 		if (subprog_is_exc_cb(env, subprog)) {
23183 			state->frame[0]->in_exception_callback_fn = true;
23184 			/* We have already ensured that the callback returns an integer, just
23185 			 * like all global subprogs. We need to determine it only has a single
23186 			 * scalar argument.
23187 			 */
23188 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23189 				verbose(env, "exception cb only supports single integer argument\n");
23190 				ret = -EINVAL;
23191 				goto out;
23192 			}
23193 		}
23194 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23195 			arg = &sub->args[i - BPF_REG_1];
23196 			reg = &regs[i];
23197 
23198 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23199 				reg->type = PTR_TO_CTX;
23200 				mark_reg_known_zero(env, regs, i);
23201 			} else if (arg->arg_type == ARG_ANYTHING) {
23202 				reg->type = SCALAR_VALUE;
23203 				mark_reg_unknown(env, regs, i);
23204 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23205 				/* assume unspecial LOCAL dynptr type */
23206 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23207 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23208 				reg->type = PTR_TO_MEM;
23209 				reg->type |= arg->arg_type &
23210 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23211 				mark_reg_known_zero(env, regs, i);
23212 				reg->mem_size = arg->mem_size;
23213 				if (arg->arg_type & PTR_MAYBE_NULL)
23214 					reg->id = ++env->id_gen;
23215 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23216 				reg->type = PTR_TO_BTF_ID;
23217 				if (arg->arg_type & PTR_MAYBE_NULL)
23218 					reg->type |= PTR_MAYBE_NULL;
23219 				if (arg->arg_type & PTR_UNTRUSTED)
23220 					reg->type |= PTR_UNTRUSTED;
23221 				if (arg->arg_type & PTR_TRUSTED)
23222 					reg->type |= PTR_TRUSTED;
23223 				mark_reg_known_zero(env, regs, i);
23224 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23225 				reg->btf_id = arg->btf_id;
23226 				reg->id = ++env->id_gen;
23227 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23228 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23229 				mark_reg_unknown(env, regs, i);
23230 			} else {
23231 				verifier_bug(env, "unhandled arg#%d type %d",
23232 					     i - BPF_REG_1, arg->arg_type);
23233 				ret = -EFAULT;
23234 				goto out;
23235 			}
23236 		}
23237 	} else {
23238 		/* if main BPF program has associated BTF info, validate that
23239 		 * it's matching expected signature, and otherwise mark BTF
23240 		 * info for main program as unreliable
23241 		 */
23242 		if (env->prog->aux->func_info_aux) {
23243 			ret = btf_prepare_func_args(env, 0);
23244 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23245 				env->prog->aux->func_info_aux[0].unreliable = true;
23246 		}
23247 
23248 		/* 1st arg to a function */
23249 		regs[BPF_REG_1].type = PTR_TO_CTX;
23250 		mark_reg_known_zero(env, regs, BPF_REG_1);
23251 	}
23252 
23253 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23254 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23255 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23256 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23257 							  acquire_reference(env, 0) : 0;
23258 	}
23259 
23260 	ret = do_check(env);
23261 out:
23262 	if (!ret && pop_log)
23263 		bpf_vlog_reset(&env->log, 0);
23264 	free_states(env);
23265 	return ret;
23266 }
23267 
23268 /* Lazily verify all global functions based on their BTF, if they are called
23269  * from main BPF program or any of subprograms transitively.
23270  * BPF global subprogs called from dead code are not validated.
23271  * All callable global functions must pass verification.
23272  * Otherwise the whole program is rejected.
23273  * Consider:
23274  * int bar(int);
23275  * int foo(int f)
23276  * {
23277  *    return bar(f);
23278  * }
23279  * int bar(int b)
23280  * {
23281  *    ...
23282  * }
23283  * foo() will be verified first for R1=any_scalar_value. During verification it
23284  * will be assumed that bar() already verified successfully and call to bar()
23285  * from foo() will be checked for type match only. Later bar() will be verified
23286  * independently to check that it's safe for R1=any_scalar_value.
23287  */
do_check_subprogs(struct bpf_verifier_env * env)23288 static int do_check_subprogs(struct bpf_verifier_env *env)
23289 {
23290 	struct bpf_prog_aux *aux = env->prog->aux;
23291 	struct bpf_func_info_aux *sub_aux;
23292 	int i, ret, new_cnt;
23293 
23294 	if (!aux->func_info)
23295 		return 0;
23296 
23297 	/* exception callback is presumed to be always called */
23298 	if (env->exception_callback_subprog)
23299 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23300 
23301 again:
23302 	new_cnt = 0;
23303 	for (i = 1; i < env->subprog_cnt; i++) {
23304 		if (!subprog_is_global(env, i))
23305 			continue;
23306 
23307 		sub_aux = subprog_aux(env, i);
23308 		if (!sub_aux->called || sub_aux->verified)
23309 			continue;
23310 
23311 		env->insn_idx = env->subprog_info[i].start;
23312 		WARN_ON_ONCE(env->insn_idx == 0);
23313 		ret = do_check_common(env, i);
23314 		if (ret) {
23315 			return ret;
23316 		} else if (env->log.level & BPF_LOG_LEVEL) {
23317 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23318 				i, subprog_name(env, i));
23319 		}
23320 
23321 		/* We verified new global subprog, it might have called some
23322 		 * more global subprogs that we haven't verified yet, so we
23323 		 * need to do another pass over subprogs to verify those.
23324 		 */
23325 		sub_aux->verified = true;
23326 		new_cnt++;
23327 	}
23328 
23329 	/* We can't loop forever as we verify at least one global subprog on
23330 	 * each pass.
23331 	 */
23332 	if (new_cnt)
23333 		goto again;
23334 
23335 	return 0;
23336 }
23337 
do_check_main(struct bpf_verifier_env * env)23338 static int do_check_main(struct bpf_verifier_env *env)
23339 {
23340 	int ret;
23341 
23342 	env->insn_idx = 0;
23343 	ret = do_check_common(env, 0);
23344 	if (!ret)
23345 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23346 	return ret;
23347 }
23348 
23349 
print_verification_stats(struct bpf_verifier_env * env)23350 static void print_verification_stats(struct bpf_verifier_env *env)
23351 {
23352 	int i;
23353 
23354 	if (env->log.level & BPF_LOG_STATS) {
23355 		verbose(env, "verification time %lld usec\n",
23356 			div_u64(env->verification_time, 1000));
23357 		verbose(env, "stack depth ");
23358 		for (i = 0; i < env->subprog_cnt; i++) {
23359 			u32 depth = env->subprog_info[i].stack_depth;
23360 
23361 			verbose(env, "%d", depth);
23362 			if (i + 1 < env->subprog_cnt)
23363 				verbose(env, "+");
23364 		}
23365 		verbose(env, "\n");
23366 	}
23367 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23368 		"total_states %d peak_states %d mark_read %d\n",
23369 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23370 		env->max_states_per_insn, env->total_states,
23371 		env->peak_states, env->longest_mark_read_walk);
23372 }
23373 
bpf_prog_ctx_arg_info_init(struct bpf_prog * prog,const struct bpf_ctx_arg_aux * info,u32 cnt)23374 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23375 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
23376 {
23377 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23378 	prog->aux->ctx_arg_info_size = cnt;
23379 
23380 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23381 }
23382 
check_struct_ops_btf_id(struct bpf_verifier_env * env)23383 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23384 {
23385 	const struct btf_type *t, *func_proto;
23386 	const struct bpf_struct_ops_desc *st_ops_desc;
23387 	const struct bpf_struct_ops *st_ops;
23388 	const struct btf_member *member;
23389 	struct bpf_prog *prog = env->prog;
23390 	bool has_refcounted_arg = false;
23391 	u32 btf_id, member_idx, member_off;
23392 	struct btf *btf;
23393 	const char *mname;
23394 	int i, err;
23395 
23396 	if (!prog->gpl_compatible) {
23397 		verbose(env, "struct ops programs must have a GPL compatible license\n");
23398 		return -EINVAL;
23399 	}
23400 
23401 	if (!prog->aux->attach_btf_id)
23402 		return -ENOTSUPP;
23403 
23404 	btf = prog->aux->attach_btf;
23405 	if (btf_is_module(btf)) {
23406 		/* Make sure st_ops is valid through the lifetime of env */
23407 		env->attach_btf_mod = btf_try_get_module(btf);
23408 		if (!env->attach_btf_mod) {
23409 			verbose(env, "struct_ops module %s is not found\n",
23410 				btf_get_name(btf));
23411 			return -ENOTSUPP;
23412 		}
23413 	}
23414 
23415 	btf_id = prog->aux->attach_btf_id;
23416 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
23417 	if (!st_ops_desc) {
23418 		verbose(env, "attach_btf_id %u is not a supported struct\n",
23419 			btf_id);
23420 		return -ENOTSUPP;
23421 	}
23422 	st_ops = st_ops_desc->st_ops;
23423 
23424 	t = st_ops_desc->type;
23425 	member_idx = prog->expected_attach_type;
23426 	if (member_idx >= btf_type_vlen(t)) {
23427 		verbose(env, "attach to invalid member idx %u of struct %s\n",
23428 			member_idx, st_ops->name);
23429 		return -EINVAL;
23430 	}
23431 
23432 	member = &btf_type_member(t)[member_idx];
23433 	mname = btf_name_by_offset(btf, member->name_off);
23434 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
23435 					       NULL);
23436 	if (!func_proto) {
23437 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
23438 			mname, member_idx, st_ops->name);
23439 		return -EINVAL;
23440 	}
23441 
23442 	member_off = __btf_member_bit_offset(t, member) / 8;
23443 	err = bpf_struct_ops_supported(st_ops, member_off);
23444 	if (err) {
23445 		verbose(env, "attach to unsupported member %s of struct %s\n",
23446 			mname, st_ops->name);
23447 		return err;
23448 	}
23449 
23450 	if (st_ops->check_member) {
23451 		err = st_ops->check_member(t, member, prog);
23452 
23453 		if (err) {
23454 			verbose(env, "attach to unsupported member %s of struct %s\n",
23455 				mname, st_ops->name);
23456 			return err;
23457 		}
23458 	}
23459 
23460 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
23461 		verbose(env, "Private stack not supported by jit\n");
23462 		return -EACCES;
23463 	}
23464 
23465 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
23466 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
23467 			has_refcounted_arg = true;
23468 			break;
23469 		}
23470 	}
23471 
23472 	/* Tail call is not allowed for programs with refcounted arguments since we
23473 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
23474 	 */
23475 	for (i = 0; i < env->subprog_cnt; i++) {
23476 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
23477 			verbose(env, "program with __ref argument cannot tail call\n");
23478 			return -EINVAL;
23479 		}
23480 	}
23481 
23482 	prog->aux->st_ops = st_ops;
23483 	prog->aux->attach_st_ops_member_off = member_off;
23484 
23485 	prog->aux->attach_func_proto = func_proto;
23486 	prog->aux->attach_func_name = mname;
23487 	env->ops = st_ops->verifier_ops;
23488 
23489 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
23490 					  st_ops_desc->arg_info[member_idx].cnt);
23491 }
23492 #define SECURITY_PREFIX "security_"
23493 
check_attach_modify_return(unsigned long addr,const char * func_name)23494 static int check_attach_modify_return(unsigned long addr, const char *func_name)
23495 {
23496 	if (within_error_injection_list(addr) ||
23497 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
23498 		return 0;
23499 
23500 	return -EINVAL;
23501 }
23502 
23503 /* list of non-sleepable functions that are otherwise on
23504  * ALLOW_ERROR_INJECTION list
23505  */
23506 BTF_SET_START(btf_non_sleepable_error_inject)
23507 /* Three functions below can be called from sleepable and non-sleepable context.
23508  * Assume non-sleepable from bpf safety point of view.
23509  */
BTF_ID(func,__filemap_add_folio)23510 BTF_ID(func, __filemap_add_folio)
23511 #ifdef CONFIG_FAIL_PAGE_ALLOC
23512 BTF_ID(func, should_fail_alloc_page)
23513 #endif
23514 #ifdef CONFIG_FAILSLAB
23515 BTF_ID(func, should_failslab)
23516 #endif
23517 BTF_SET_END(btf_non_sleepable_error_inject)
23518 
23519 static int check_non_sleepable_error_inject(u32 btf_id)
23520 {
23521 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
23522 }
23523 
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)23524 int bpf_check_attach_target(struct bpf_verifier_log *log,
23525 			    const struct bpf_prog *prog,
23526 			    const struct bpf_prog *tgt_prog,
23527 			    u32 btf_id,
23528 			    struct bpf_attach_target_info *tgt_info)
23529 {
23530 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
23531 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
23532 	char trace_symbol[KSYM_SYMBOL_LEN];
23533 	const char prefix[] = "btf_trace_";
23534 	struct bpf_raw_event_map *btp;
23535 	int ret = 0, subprog = -1, i;
23536 	const struct btf_type *t;
23537 	bool conservative = true;
23538 	const char *tname, *fname;
23539 	struct btf *btf;
23540 	long addr = 0;
23541 	struct module *mod = NULL;
23542 
23543 	if (!btf_id) {
23544 		bpf_log(log, "Tracing programs must provide btf_id\n");
23545 		return -EINVAL;
23546 	}
23547 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
23548 	if (!btf) {
23549 		bpf_log(log,
23550 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
23551 		return -EINVAL;
23552 	}
23553 	t = btf_type_by_id(btf, btf_id);
23554 	if (!t) {
23555 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
23556 		return -EINVAL;
23557 	}
23558 	tname = btf_name_by_offset(btf, t->name_off);
23559 	if (!tname) {
23560 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
23561 		return -EINVAL;
23562 	}
23563 	if (tgt_prog) {
23564 		struct bpf_prog_aux *aux = tgt_prog->aux;
23565 		bool tgt_changes_pkt_data;
23566 		bool tgt_might_sleep;
23567 
23568 		if (bpf_prog_is_dev_bound(prog->aux) &&
23569 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
23570 			bpf_log(log, "Target program bound device mismatch");
23571 			return -EINVAL;
23572 		}
23573 
23574 		for (i = 0; i < aux->func_info_cnt; i++)
23575 			if (aux->func_info[i].type_id == btf_id) {
23576 				subprog = i;
23577 				break;
23578 			}
23579 		if (subprog == -1) {
23580 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
23581 			return -EINVAL;
23582 		}
23583 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
23584 			bpf_log(log,
23585 				"%s programs cannot attach to exception callback\n",
23586 				prog_extension ? "Extension" : "FENTRY/FEXIT");
23587 			return -EINVAL;
23588 		}
23589 		conservative = aux->func_info_aux[subprog].unreliable;
23590 		if (prog_extension) {
23591 			if (conservative) {
23592 				bpf_log(log,
23593 					"Cannot replace static functions\n");
23594 				return -EINVAL;
23595 			}
23596 			if (!prog->jit_requested) {
23597 				bpf_log(log,
23598 					"Extension programs should be JITed\n");
23599 				return -EINVAL;
23600 			}
23601 			tgt_changes_pkt_data = aux->func
23602 					       ? aux->func[subprog]->aux->changes_pkt_data
23603 					       : aux->changes_pkt_data;
23604 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
23605 				bpf_log(log,
23606 					"Extension program changes packet data, while original does not\n");
23607 				return -EINVAL;
23608 			}
23609 
23610 			tgt_might_sleep = aux->func
23611 					  ? aux->func[subprog]->aux->might_sleep
23612 					  : aux->might_sleep;
23613 			if (prog->aux->might_sleep && !tgt_might_sleep) {
23614 				bpf_log(log,
23615 					"Extension program may sleep, while original does not\n");
23616 				return -EINVAL;
23617 			}
23618 		}
23619 		if (!tgt_prog->jited) {
23620 			bpf_log(log, "Can attach to only JITed progs\n");
23621 			return -EINVAL;
23622 		}
23623 		if (prog_tracing) {
23624 			if (aux->attach_tracing_prog) {
23625 				/*
23626 				 * Target program is an fentry/fexit which is already attached
23627 				 * to another tracing program. More levels of nesting
23628 				 * attachment are not allowed.
23629 				 */
23630 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
23631 				return -EINVAL;
23632 			}
23633 		} else if (tgt_prog->type == prog->type) {
23634 			/*
23635 			 * To avoid potential call chain cycles, prevent attaching of a
23636 			 * program extension to another extension. It's ok to attach
23637 			 * fentry/fexit to extension program.
23638 			 */
23639 			bpf_log(log, "Cannot recursively attach\n");
23640 			return -EINVAL;
23641 		}
23642 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
23643 		    prog_extension &&
23644 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
23645 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
23646 			/* Program extensions can extend all program types
23647 			 * except fentry/fexit. The reason is the following.
23648 			 * The fentry/fexit programs are used for performance
23649 			 * analysis, stats and can be attached to any program
23650 			 * type. When extension program is replacing XDP function
23651 			 * it is necessary to allow performance analysis of all
23652 			 * functions. Both original XDP program and its program
23653 			 * extension. Hence attaching fentry/fexit to
23654 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
23655 			 * fentry/fexit was allowed it would be possible to create
23656 			 * long call chain fentry->extension->fentry->extension
23657 			 * beyond reasonable stack size. Hence extending fentry
23658 			 * is not allowed.
23659 			 */
23660 			bpf_log(log, "Cannot extend fentry/fexit\n");
23661 			return -EINVAL;
23662 		}
23663 	} else {
23664 		if (prog_extension) {
23665 			bpf_log(log, "Cannot replace kernel functions\n");
23666 			return -EINVAL;
23667 		}
23668 	}
23669 
23670 	switch (prog->expected_attach_type) {
23671 	case BPF_TRACE_RAW_TP:
23672 		if (tgt_prog) {
23673 			bpf_log(log,
23674 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
23675 			return -EINVAL;
23676 		}
23677 		if (!btf_type_is_typedef(t)) {
23678 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
23679 				btf_id);
23680 			return -EINVAL;
23681 		}
23682 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
23683 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
23684 				btf_id, tname);
23685 			return -EINVAL;
23686 		}
23687 		tname += sizeof(prefix) - 1;
23688 
23689 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
23690 		 * names. Thus using bpf_raw_event_map to get argument names.
23691 		 */
23692 		btp = bpf_get_raw_tracepoint(tname);
23693 		if (!btp)
23694 			return -EINVAL;
23695 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
23696 					trace_symbol);
23697 		bpf_put_raw_tracepoint(btp);
23698 
23699 		if (fname)
23700 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
23701 
23702 		if (!fname || ret < 0) {
23703 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
23704 				prefix, tname);
23705 			t = btf_type_by_id(btf, t->type);
23706 			if (!btf_type_is_ptr(t))
23707 				/* should never happen in valid vmlinux build */
23708 				return -EINVAL;
23709 		} else {
23710 			t = btf_type_by_id(btf, ret);
23711 			if (!btf_type_is_func(t))
23712 				/* should never happen in valid vmlinux build */
23713 				return -EINVAL;
23714 		}
23715 
23716 		t = btf_type_by_id(btf, t->type);
23717 		if (!btf_type_is_func_proto(t))
23718 			/* should never happen in valid vmlinux build */
23719 			return -EINVAL;
23720 
23721 		break;
23722 	case BPF_TRACE_ITER:
23723 		if (!btf_type_is_func(t)) {
23724 			bpf_log(log, "attach_btf_id %u is not a function\n",
23725 				btf_id);
23726 			return -EINVAL;
23727 		}
23728 		t = btf_type_by_id(btf, t->type);
23729 		if (!btf_type_is_func_proto(t))
23730 			return -EINVAL;
23731 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23732 		if (ret)
23733 			return ret;
23734 		break;
23735 	default:
23736 		if (!prog_extension)
23737 			return -EINVAL;
23738 		fallthrough;
23739 	case BPF_MODIFY_RETURN:
23740 	case BPF_LSM_MAC:
23741 	case BPF_LSM_CGROUP:
23742 	case BPF_TRACE_FENTRY:
23743 	case BPF_TRACE_FEXIT:
23744 		if (!btf_type_is_func(t)) {
23745 			bpf_log(log, "attach_btf_id %u is not a function\n",
23746 				btf_id);
23747 			return -EINVAL;
23748 		}
23749 		if (prog_extension &&
23750 		    btf_check_type_match(log, prog, btf, t))
23751 			return -EINVAL;
23752 		t = btf_type_by_id(btf, t->type);
23753 		if (!btf_type_is_func_proto(t))
23754 			return -EINVAL;
23755 
23756 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
23757 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
23758 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
23759 			return -EINVAL;
23760 
23761 		if (tgt_prog && conservative)
23762 			t = NULL;
23763 
23764 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23765 		if (ret < 0)
23766 			return ret;
23767 
23768 		if (tgt_prog) {
23769 			if (subprog == 0)
23770 				addr = (long) tgt_prog->bpf_func;
23771 			else
23772 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23773 		} else {
23774 			if (btf_is_module(btf)) {
23775 				mod = btf_try_get_module(btf);
23776 				if (mod)
23777 					addr = find_kallsyms_symbol_value(mod, tname);
23778 				else
23779 					addr = 0;
23780 			} else {
23781 				addr = kallsyms_lookup_name(tname);
23782 			}
23783 			if (!addr) {
23784 				module_put(mod);
23785 				bpf_log(log,
23786 					"The address of function %s cannot be found\n",
23787 					tname);
23788 				return -ENOENT;
23789 			}
23790 		}
23791 
23792 		if (prog->sleepable) {
23793 			ret = -EINVAL;
23794 			switch (prog->type) {
23795 			case BPF_PROG_TYPE_TRACING:
23796 
23797 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
23798 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
23799 				 */
23800 				if (!check_non_sleepable_error_inject(btf_id) &&
23801 				    within_error_injection_list(addr))
23802 					ret = 0;
23803 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
23804 				 * in the fmodret id set with the KF_SLEEPABLE flag.
23805 				 */
23806 				else {
23807 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
23808 										prog);
23809 
23810 					if (flags && (*flags & KF_SLEEPABLE))
23811 						ret = 0;
23812 				}
23813 				break;
23814 			case BPF_PROG_TYPE_LSM:
23815 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
23816 				 * Only some of them are sleepable.
23817 				 */
23818 				if (bpf_lsm_is_sleepable_hook(btf_id))
23819 					ret = 0;
23820 				break;
23821 			default:
23822 				break;
23823 			}
23824 			if (ret) {
23825 				module_put(mod);
23826 				bpf_log(log, "%s is not sleepable\n", tname);
23827 				return ret;
23828 			}
23829 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23830 			if (tgt_prog) {
23831 				module_put(mod);
23832 				bpf_log(log, "can't modify return codes of BPF programs\n");
23833 				return -EINVAL;
23834 			}
23835 			ret = -EINVAL;
23836 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23837 			    !check_attach_modify_return(addr, tname))
23838 				ret = 0;
23839 			if (ret) {
23840 				module_put(mod);
23841 				bpf_log(log, "%s() is not modifiable\n", tname);
23842 				return ret;
23843 			}
23844 		}
23845 
23846 		break;
23847 	}
23848 	tgt_info->tgt_addr = addr;
23849 	tgt_info->tgt_name = tname;
23850 	tgt_info->tgt_type = t;
23851 	tgt_info->tgt_mod = mod;
23852 	return 0;
23853 }
23854 
BTF_SET_START(btf_id_deny)23855 BTF_SET_START(btf_id_deny)
23856 BTF_ID_UNUSED
23857 #ifdef CONFIG_SMP
23858 BTF_ID(func, migrate_disable)
23859 BTF_ID(func, migrate_enable)
23860 #endif
23861 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23862 BTF_ID(func, rcu_read_unlock_strict)
23863 #endif
23864 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23865 BTF_ID(func, preempt_count_add)
23866 BTF_ID(func, preempt_count_sub)
23867 #endif
23868 #ifdef CONFIG_PREEMPT_RCU
23869 BTF_ID(func, __rcu_read_lock)
23870 BTF_ID(func, __rcu_read_unlock)
23871 #endif
23872 BTF_SET_END(btf_id_deny)
23873 
23874 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23875  * Currently, we must manually list all __noreturn functions here. Once a more
23876  * robust solution is implemented, this workaround can be removed.
23877  */
23878 BTF_SET_START(noreturn_deny)
23879 #ifdef CONFIG_IA32_EMULATION
23880 BTF_ID(func, __ia32_sys_exit)
23881 BTF_ID(func, __ia32_sys_exit_group)
23882 #endif
23883 #ifdef CONFIG_KUNIT
23884 BTF_ID(func, __kunit_abort)
23885 BTF_ID(func, kunit_try_catch_throw)
23886 #endif
23887 #ifdef CONFIG_MODULES
23888 BTF_ID(func, __module_put_and_kthread_exit)
23889 #endif
23890 #ifdef CONFIG_X86_64
23891 BTF_ID(func, __x64_sys_exit)
23892 BTF_ID(func, __x64_sys_exit_group)
23893 #endif
23894 BTF_ID(func, do_exit)
23895 BTF_ID(func, do_group_exit)
23896 BTF_ID(func, kthread_complete_and_exit)
23897 BTF_ID(func, kthread_exit)
23898 BTF_ID(func, make_task_dead)
23899 BTF_SET_END(noreturn_deny)
23900 
23901 static bool can_be_sleepable(struct bpf_prog *prog)
23902 {
23903 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23904 		switch (prog->expected_attach_type) {
23905 		case BPF_TRACE_FENTRY:
23906 		case BPF_TRACE_FEXIT:
23907 		case BPF_MODIFY_RETURN:
23908 		case BPF_TRACE_ITER:
23909 			return true;
23910 		default:
23911 			return false;
23912 		}
23913 	}
23914 	return prog->type == BPF_PROG_TYPE_LSM ||
23915 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23916 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
23917 }
23918 
check_attach_btf_id(struct bpf_verifier_env * env)23919 static int check_attach_btf_id(struct bpf_verifier_env *env)
23920 {
23921 	struct bpf_prog *prog = env->prog;
23922 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23923 	struct bpf_attach_target_info tgt_info = {};
23924 	u32 btf_id = prog->aux->attach_btf_id;
23925 	struct bpf_trampoline *tr;
23926 	int ret;
23927 	u64 key;
23928 
23929 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23930 		if (prog->sleepable)
23931 			/* attach_btf_id checked to be zero already */
23932 			return 0;
23933 		verbose(env, "Syscall programs can only be sleepable\n");
23934 		return -EINVAL;
23935 	}
23936 
23937 	if (prog->sleepable && !can_be_sleepable(prog)) {
23938 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
23939 		return -EINVAL;
23940 	}
23941 
23942 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23943 		return check_struct_ops_btf_id(env);
23944 
23945 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23946 	    prog->type != BPF_PROG_TYPE_LSM &&
23947 	    prog->type != BPF_PROG_TYPE_EXT)
23948 		return 0;
23949 
23950 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23951 	if (ret)
23952 		return ret;
23953 
23954 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23955 		/* to make freplace equivalent to their targets, they need to
23956 		 * inherit env->ops and expected_attach_type for the rest of the
23957 		 * verification
23958 		 */
23959 		env->ops = bpf_verifier_ops[tgt_prog->type];
23960 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23961 	}
23962 
23963 	/* store info about the attachment target that will be used later */
23964 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23965 	prog->aux->attach_func_name = tgt_info.tgt_name;
23966 	prog->aux->mod = tgt_info.tgt_mod;
23967 
23968 	if (tgt_prog) {
23969 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23970 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23971 	}
23972 
23973 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23974 		prog->aux->attach_btf_trace = true;
23975 		return 0;
23976 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23977 		return bpf_iter_prog_supported(prog);
23978 	}
23979 
23980 	if (prog->type == BPF_PROG_TYPE_LSM) {
23981 		ret = bpf_lsm_verify_prog(&env->log, prog);
23982 		if (ret < 0)
23983 			return ret;
23984 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23985 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23986 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23987 			tgt_info.tgt_name);
23988 		return -EINVAL;
23989 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23990 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23991 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23992 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
23993 			tgt_info.tgt_name);
23994 		return -EINVAL;
23995 	}
23996 
23997 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
23998 	tr = bpf_trampoline_get(key, &tgt_info);
23999 	if (!tr)
24000 		return -ENOMEM;
24001 
24002 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24003 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24004 
24005 	prog->aux->dst_trampoline = tr;
24006 	return 0;
24007 }
24008 
bpf_get_btf_vmlinux(void)24009 struct btf *bpf_get_btf_vmlinux(void)
24010 {
24011 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24012 		mutex_lock(&bpf_verifier_lock);
24013 		if (!btf_vmlinux)
24014 			btf_vmlinux = btf_parse_vmlinux();
24015 		mutex_unlock(&bpf_verifier_lock);
24016 	}
24017 	return btf_vmlinux;
24018 }
24019 
24020 /*
24021  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24022  * this case expect that every file descriptor in the array is either a map or
24023  * a BTF. Everything else is considered to be trash.
24024  */
add_fd_from_fd_array(struct bpf_verifier_env * env,int fd)24025 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24026 {
24027 	struct bpf_map *map;
24028 	struct btf *btf;
24029 	CLASS(fd, f)(fd);
24030 	int err;
24031 
24032 	map = __bpf_map_get(f);
24033 	if (!IS_ERR(map)) {
24034 		err = __add_used_map(env, map);
24035 		if (err < 0)
24036 			return err;
24037 		return 0;
24038 	}
24039 
24040 	btf = __btf_get_by_fd(f);
24041 	if (!IS_ERR(btf)) {
24042 		err = __add_used_btf(env, btf);
24043 		if (err < 0)
24044 			return err;
24045 		return 0;
24046 	}
24047 
24048 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24049 	return PTR_ERR(map);
24050 }
24051 
process_fd_array(struct bpf_verifier_env * env,union bpf_attr * attr,bpfptr_t uattr)24052 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24053 {
24054 	size_t size = sizeof(int);
24055 	int ret;
24056 	int fd;
24057 	u32 i;
24058 
24059 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24060 
24061 	/*
24062 	 * The only difference between old (no fd_array_cnt is given) and new
24063 	 * APIs is that in the latter case the fd_array is expected to be
24064 	 * continuous and is scanned for map fds right away
24065 	 */
24066 	if (!attr->fd_array_cnt)
24067 		return 0;
24068 
24069 	/* Check for integer overflow */
24070 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24071 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24072 		return -EINVAL;
24073 	}
24074 
24075 	for (i = 0; i < attr->fd_array_cnt; i++) {
24076 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24077 			return -EFAULT;
24078 
24079 		ret = add_fd_from_fd_array(env, fd);
24080 		if (ret)
24081 			return ret;
24082 	}
24083 
24084 	return 0;
24085 }
24086 
can_fallthrough(struct bpf_insn * insn)24087 static bool can_fallthrough(struct bpf_insn *insn)
24088 {
24089 	u8 class = BPF_CLASS(insn->code);
24090 	u8 opcode = BPF_OP(insn->code);
24091 
24092 	if (class != BPF_JMP && class != BPF_JMP32)
24093 		return true;
24094 
24095 	if (opcode == BPF_EXIT || opcode == BPF_JA)
24096 		return false;
24097 
24098 	return true;
24099 }
24100 
can_jump(struct bpf_insn * insn)24101 static bool can_jump(struct bpf_insn *insn)
24102 {
24103 	u8 class = BPF_CLASS(insn->code);
24104 	u8 opcode = BPF_OP(insn->code);
24105 
24106 	if (class != BPF_JMP && class != BPF_JMP32)
24107 		return false;
24108 
24109 	switch (opcode) {
24110 	case BPF_JA:
24111 	case BPF_JEQ:
24112 	case BPF_JNE:
24113 	case BPF_JLT:
24114 	case BPF_JLE:
24115 	case BPF_JGT:
24116 	case BPF_JGE:
24117 	case BPF_JSGT:
24118 	case BPF_JSGE:
24119 	case BPF_JSLT:
24120 	case BPF_JSLE:
24121 	case BPF_JCOND:
24122 	case BPF_JSET:
24123 		return true;
24124 	}
24125 
24126 	return false;
24127 }
24128 
insn_successors(struct bpf_prog * prog,u32 idx,u32 succ[2])24129 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2])
24130 {
24131 	struct bpf_insn *insn = &prog->insnsi[idx];
24132 	int i = 0, insn_sz;
24133 	u32 dst;
24134 
24135 	insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
24136 	if (can_fallthrough(insn) && idx + 1 < prog->len)
24137 		succ[i++] = idx + insn_sz;
24138 
24139 	if (can_jump(insn)) {
24140 		dst = idx + jmp_offset(insn) + 1;
24141 		if (i == 0 || succ[0] != dst)
24142 			succ[i++] = dst;
24143 	}
24144 
24145 	return i;
24146 }
24147 
24148 /* Each field is a register bitmask */
24149 struct insn_live_regs {
24150 	u16 use;	/* registers read by instruction */
24151 	u16 def;	/* registers written by instruction */
24152 	u16 in;		/* registers that may be alive before instruction */
24153 	u16 out;	/* registers that may be alive after instruction */
24154 };
24155 
24156 /* Bitmask with 1s for all caller saved registers */
24157 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24158 
24159 /* Compute info->{use,def} fields for the instruction */
compute_insn_live_regs(struct bpf_verifier_env * env,struct bpf_insn * insn,struct insn_live_regs * info)24160 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24161 				   struct bpf_insn *insn,
24162 				   struct insn_live_regs *info)
24163 {
24164 	struct call_summary cs;
24165 	u8 class = BPF_CLASS(insn->code);
24166 	u8 code = BPF_OP(insn->code);
24167 	u8 mode = BPF_MODE(insn->code);
24168 	u16 src = BIT(insn->src_reg);
24169 	u16 dst = BIT(insn->dst_reg);
24170 	u16 r0  = BIT(0);
24171 	u16 def = 0;
24172 	u16 use = 0xffff;
24173 
24174 	switch (class) {
24175 	case BPF_LD:
24176 		switch (mode) {
24177 		case BPF_IMM:
24178 			if (BPF_SIZE(insn->code) == BPF_DW) {
24179 				def = dst;
24180 				use = 0;
24181 			}
24182 			break;
24183 		case BPF_LD | BPF_ABS:
24184 		case BPF_LD | BPF_IND:
24185 			/* stick with defaults */
24186 			break;
24187 		}
24188 		break;
24189 	case BPF_LDX:
24190 		switch (mode) {
24191 		case BPF_MEM:
24192 		case BPF_MEMSX:
24193 			def = dst;
24194 			use = src;
24195 			break;
24196 		}
24197 		break;
24198 	case BPF_ST:
24199 		switch (mode) {
24200 		case BPF_MEM:
24201 			def = 0;
24202 			use = dst;
24203 			break;
24204 		}
24205 		break;
24206 	case BPF_STX:
24207 		switch (mode) {
24208 		case BPF_MEM:
24209 			def = 0;
24210 			use = dst | src;
24211 			break;
24212 		case BPF_ATOMIC:
24213 			switch (insn->imm) {
24214 			case BPF_CMPXCHG:
24215 				use = r0 | dst | src;
24216 				def = r0;
24217 				break;
24218 			case BPF_LOAD_ACQ:
24219 				def = dst;
24220 				use = src;
24221 				break;
24222 			case BPF_STORE_REL:
24223 				def = 0;
24224 				use = dst | src;
24225 				break;
24226 			default:
24227 				use = dst | src;
24228 				if (insn->imm & BPF_FETCH)
24229 					def = src;
24230 				else
24231 					def = 0;
24232 			}
24233 			break;
24234 		}
24235 		break;
24236 	case BPF_ALU:
24237 	case BPF_ALU64:
24238 		switch (code) {
24239 		case BPF_END:
24240 			use = dst;
24241 			def = dst;
24242 			break;
24243 		case BPF_MOV:
24244 			def = dst;
24245 			if (BPF_SRC(insn->code) == BPF_K)
24246 				use = 0;
24247 			else
24248 				use = src;
24249 			break;
24250 		default:
24251 			def = dst;
24252 			if (BPF_SRC(insn->code) == BPF_K)
24253 				use = dst;
24254 			else
24255 				use = dst | src;
24256 		}
24257 		break;
24258 	case BPF_JMP:
24259 	case BPF_JMP32:
24260 		switch (code) {
24261 		case BPF_JA:
24262 		case BPF_JCOND:
24263 			def = 0;
24264 			use = 0;
24265 			break;
24266 		case BPF_EXIT:
24267 			def = 0;
24268 			use = r0;
24269 			break;
24270 		case BPF_CALL:
24271 			def = ALL_CALLER_SAVED_REGS;
24272 			use = def & ~BIT(BPF_REG_0);
24273 			if (get_call_summary(env, insn, &cs))
24274 				use = GENMASK(cs.num_params, 1);
24275 			break;
24276 		default:
24277 			def = 0;
24278 			if (BPF_SRC(insn->code) == BPF_K)
24279 				use = dst;
24280 			else
24281 				use = dst | src;
24282 		}
24283 		break;
24284 	}
24285 
24286 	info->def = def;
24287 	info->use = use;
24288 }
24289 
24290 /* Compute may-live registers after each instruction in the program.
24291  * The register is live after the instruction I if it is read by some
24292  * instruction S following I during program execution and is not
24293  * overwritten between I and S.
24294  *
24295  * Store result in env->insn_aux_data[i].live_regs.
24296  */
compute_live_registers(struct bpf_verifier_env * env)24297 static int compute_live_registers(struct bpf_verifier_env *env)
24298 {
24299 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24300 	struct bpf_insn *insns = env->prog->insnsi;
24301 	struct insn_live_regs *state;
24302 	int insn_cnt = env->prog->len;
24303 	int err = 0, i, j;
24304 	bool changed;
24305 
24306 	/* Use the following algorithm:
24307 	 * - define the following:
24308 	 *   - I.use : a set of all registers read by instruction I;
24309 	 *   - I.def : a set of all registers written by instruction I;
24310 	 *   - I.in  : a set of all registers that may be alive before I execution;
24311 	 *   - I.out : a set of all registers that may be alive after I execution;
24312 	 *   - insn_successors(I): a set of instructions S that might immediately
24313 	 *                         follow I for some program execution;
24314 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24315 	 * - visit each instruction in a postorder and update
24316 	 *   state[i].in, state[i].out as follows:
24317 	 *
24318 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24319 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24320 	 *
24321 	 *   (where U stands for set union, / stands for set difference)
24322 	 * - repeat the computation while {in,out} fields changes for
24323 	 *   any instruction.
24324 	 */
24325 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24326 	if (!state) {
24327 		err = -ENOMEM;
24328 		goto out;
24329 	}
24330 
24331 	for (i = 0; i < insn_cnt; ++i)
24332 		compute_insn_live_regs(env, &insns[i], &state[i]);
24333 
24334 	changed = true;
24335 	while (changed) {
24336 		changed = false;
24337 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24338 			int insn_idx = env->cfg.insn_postorder[i];
24339 			struct insn_live_regs *live = &state[insn_idx];
24340 			int succ_num;
24341 			u32 succ[2];
24342 			u16 new_out = 0;
24343 			u16 new_in = 0;
24344 
24345 			succ_num = insn_successors(env->prog, insn_idx, succ);
24346 			for (int s = 0; s < succ_num; ++s)
24347 				new_out |= state[succ[s]].in;
24348 			new_in = (new_out & ~live->def) | live->use;
24349 			if (new_out != live->out || new_in != live->in) {
24350 				live->in = new_in;
24351 				live->out = new_out;
24352 				changed = true;
24353 			}
24354 		}
24355 	}
24356 
24357 	for (i = 0; i < insn_cnt; ++i)
24358 		insn_aux[i].live_regs_before = state[i].in;
24359 
24360 	if (env->log.level & BPF_LOG_LEVEL2) {
24361 		verbose(env, "Live regs before insn:\n");
24362 		for (i = 0; i < insn_cnt; ++i) {
24363 			if (env->insn_aux_data[i].scc)
24364 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24365 			else
24366 				verbose(env, "    ");
24367 			verbose(env, "%3d: ", i);
24368 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24369 				if (insn_aux[i].live_regs_before & BIT(j))
24370 					verbose(env, "%d", j);
24371 				else
24372 					verbose(env, ".");
24373 			verbose(env, " ");
24374 			verbose_insn(env, &insns[i]);
24375 			if (bpf_is_ldimm64(&insns[i]))
24376 				i++;
24377 		}
24378 	}
24379 
24380 out:
24381 	kvfree(state);
24382 	kvfree(env->cfg.insn_postorder);
24383 	env->cfg.insn_postorder = NULL;
24384 	env->cfg.cur_postorder = 0;
24385 	return err;
24386 }
24387 
24388 /*
24389  * Compute strongly connected components (SCCs) on the CFG.
24390  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24391  * If instruction is a sole member of its SCC and there are no self edges,
24392  * assign it SCC number of zero.
24393  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24394  */
compute_scc(struct bpf_verifier_env * env)24395 static int compute_scc(struct bpf_verifier_env *env)
24396 {
24397 	const u32 NOT_ON_STACK = U32_MAX;
24398 
24399 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24400 	const u32 insn_cnt = env->prog->len;
24401 	int stack_sz, dfs_sz, err = 0;
24402 	u32 *stack, *pre, *low, *dfs;
24403 	u32 succ_cnt, i, j, t, w;
24404 	u32 next_preorder_num;
24405 	u32 next_scc_id;
24406 	bool assign_scc;
24407 	u32 succ[2];
24408 
24409 	next_preorder_num = 1;
24410 	next_scc_id = 1;
24411 	/*
24412 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24413 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24414 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24415 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24416 	 */
24417 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24418 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24419 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24420 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24421 	if (!stack || !pre || !low || !dfs) {
24422 		err = -ENOMEM;
24423 		goto exit;
24424 	}
24425 	/*
24426 	 * References:
24427 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24428 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24429 	 *
24430 	 * The algorithm maintains the following invariant:
24431 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24432 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24433 	 *
24434 	 * Consequently:
24435 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24436 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24437 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
24438 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24439 	 *   and 'v' can be considered the root of some SCC.
24440 	 *
24441 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24442 	 *
24443 	 *    NOT_ON_STACK = insn_cnt + 1
24444 	 *    pre = [0] * insn_cnt
24445 	 *    low = [0] * insn_cnt
24446 	 *    scc = [0] * insn_cnt
24447 	 *    stack = []
24448 	 *
24449 	 *    next_preorder_num = 1
24450 	 *    next_scc_id = 1
24451 	 *
24452 	 *    def recur(w):
24453 	 *        nonlocal next_preorder_num
24454 	 *        nonlocal next_scc_id
24455 	 *
24456 	 *        pre[w] = next_preorder_num
24457 	 *        low[w] = next_preorder_num
24458 	 *        next_preorder_num += 1
24459 	 *        stack.append(w)
24460 	 *        for s in successors(w):
24461 	 *            # Note: for classic algorithm the block below should look as:
24462 	 *            #
24463 	 *            # if pre[s] == 0:
24464 	 *            #     recur(s)
24465 	 *            #	    low[w] = min(low[w], low[s])
24466 	 *            # elif low[s] != NOT_ON_STACK:
24467 	 *            #     low[w] = min(low[w], pre[s])
24468 	 *            #
24469 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
24470 	 *            # does not break the invariant and makes itartive version of the algorithm
24471 	 *            # simpler. See 'Algorithm #3' from [2].
24472 	 *
24473 	 *            # 's' not yet visited
24474 	 *            if pre[s] == 0:
24475 	 *                recur(s)
24476 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
24477 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
24478 	 *            # so 'min' would be a noop.
24479 	 *            low[w] = min(low[w], low[s])
24480 	 *
24481 	 *        if low[w] == pre[w]:
24482 	 *            # 'w' is the root of an SCC, pop all vertices
24483 	 *            # below 'w' on stack and assign same SCC to them.
24484 	 *            while True:
24485 	 *                t = stack.pop()
24486 	 *                low[t] = NOT_ON_STACK
24487 	 *                scc[t] = next_scc_id
24488 	 *                if t == w:
24489 	 *                    break
24490 	 *            next_scc_id += 1
24491 	 *
24492 	 *    for i in range(0, insn_cnt):
24493 	 *        if pre[i] == 0:
24494 	 *            recur(i)
24495 	 *
24496 	 * Below implementation replaces explicit recursion with array 'dfs'.
24497 	 */
24498 	for (i = 0; i < insn_cnt; i++) {
24499 		if (pre[i])
24500 			continue;
24501 		stack_sz = 0;
24502 		dfs_sz = 1;
24503 		dfs[0] = i;
24504 dfs_continue:
24505 		while (dfs_sz) {
24506 			w = dfs[dfs_sz - 1];
24507 			if (pre[w] == 0) {
24508 				low[w] = next_preorder_num;
24509 				pre[w] = next_preorder_num;
24510 				next_preorder_num++;
24511 				stack[stack_sz++] = w;
24512 			}
24513 			/* Visit 'w' successors */
24514 			succ_cnt = insn_successors(env->prog, w, succ);
24515 			for (j = 0; j < succ_cnt; ++j) {
24516 				if (pre[succ[j]]) {
24517 					low[w] = min(low[w], low[succ[j]]);
24518 				} else {
24519 					dfs[dfs_sz++] = succ[j];
24520 					goto dfs_continue;
24521 				}
24522 			}
24523 			/*
24524 			 * Preserve the invariant: if some vertex above in the stack
24525 			 * is reachable from 'w', keep 'w' on the stack.
24526 			 */
24527 			if (low[w] < pre[w]) {
24528 				dfs_sz--;
24529 				goto dfs_continue;
24530 			}
24531 			/*
24532 			 * Assign SCC number only if component has two or more elements,
24533 			 * or if component has a self reference.
24534 			 */
24535 			assign_scc = stack[stack_sz - 1] != w;
24536 			for (j = 0; j < succ_cnt; ++j) {
24537 				if (succ[j] == w) {
24538 					assign_scc = true;
24539 					break;
24540 				}
24541 			}
24542 			/* Pop component elements from stack */
24543 			do {
24544 				t = stack[--stack_sz];
24545 				low[t] = NOT_ON_STACK;
24546 				if (assign_scc)
24547 					aux[t].scc = next_scc_id;
24548 			} while (t != w);
24549 			if (assign_scc)
24550 				next_scc_id++;
24551 			dfs_sz--;
24552 		}
24553 	}
24554 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
24555 	if (!env->scc_info) {
24556 		err = -ENOMEM;
24557 		goto exit;
24558 	}
24559 	env->scc_cnt = next_scc_id;
24560 exit:
24561 	kvfree(stack);
24562 	kvfree(pre);
24563 	kvfree(low);
24564 	kvfree(dfs);
24565 	return err;
24566 }
24567 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)24568 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
24569 {
24570 	u64 start_time = ktime_get_ns();
24571 	struct bpf_verifier_env *env;
24572 	int i, len, ret = -EINVAL, err;
24573 	u32 log_true_size;
24574 	bool is_priv;
24575 
24576 	BTF_TYPE_EMIT(enum bpf_features);
24577 
24578 	/* no program is valid */
24579 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
24580 		return -EINVAL;
24581 
24582 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
24583 	 * allocate/free it every time bpf_check() is called
24584 	 */
24585 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
24586 	if (!env)
24587 		return -ENOMEM;
24588 
24589 	env->bt.env = env;
24590 
24591 	len = (*prog)->len;
24592 	env->insn_aux_data =
24593 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
24594 	ret = -ENOMEM;
24595 	if (!env->insn_aux_data)
24596 		goto err_free_env;
24597 	for (i = 0; i < len; i++)
24598 		env->insn_aux_data[i].orig_idx = i;
24599 	env->prog = *prog;
24600 	env->ops = bpf_verifier_ops[env->prog->type];
24601 
24602 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
24603 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
24604 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
24605 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
24606 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
24607 
24608 	bpf_get_btf_vmlinux();
24609 
24610 	/* grab the mutex to protect few globals used by verifier */
24611 	if (!is_priv)
24612 		mutex_lock(&bpf_verifier_lock);
24613 
24614 	/* user could have requested verbose verifier output
24615 	 * and supplied buffer to store the verification trace
24616 	 */
24617 	ret = bpf_vlog_init(&env->log, attr->log_level,
24618 			    (char __user *) (unsigned long) attr->log_buf,
24619 			    attr->log_size);
24620 	if (ret)
24621 		goto err_unlock;
24622 
24623 	ret = process_fd_array(env, attr, uattr);
24624 	if (ret)
24625 		goto skip_full_check;
24626 
24627 	mark_verifier_state_clean(env);
24628 
24629 	if (IS_ERR(btf_vmlinux)) {
24630 		/* Either gcc or pahole or kernel are broken. */
24631 		verbose(env, "in-kernel BTF is malformed\n");
24632 		ret = PTR_ERR(btf_vmlinux);
24633 		goto skip_full_check;
24634 	}
24635 
24636 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24637 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24638 		env->strict_alignment = true;
24639 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24640 		env->strict_alignment = false;
24641 
24642 	if (is_priv)
24643 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24644 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24645 
24646 	env->explored_states = kvcalloc(state_htab_size(env),
24647 				       sizeof(struct list_head),
24648 				       GFP_KERNEL_ACCOUNT);
24649 	ret = -ENOMEM;
24650 	if (!env->explored_states)
24651 		goto skip_full_check;
24652 
24653 	for (i = 0; i < state_htab_size(env); i++)
24654 		INIT_LIST_HEAD(&env->explored_states[i]);
24655 	INIT_LIST_HEAD(&env->free_list);
24656 
24657 	ret = check_btf_info_early(env, attr, uattr);
24658 	if (ret < 0)
24659 		goto skip_full_check;
24660 
24661 	ret = add_subprog_and_kfunc(env);
24662 	if (ret < 0)
24663 		goto skip_full_check;
24664 
24665 	ret = check_subprogs(env);
24666 	if (ret < 0)
24667 		goto skip_full_check;
24668 
24669 	ret = check_btf_info(env, attr, uattr);
24670 	if (ret < 0)
24671 		goto skip_full_check;
24672 
24673 	ret = resolve_pseudo_ldimm64(env);
24674 	if (ret < 0)
24675 		goto skip_full_check;
24676 
24677 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24678 		ret = bpf_prog_offload_verifier_prep(env->prog);
24679 		if (ret)
24680 			goto skip_full_check;
24681 	}
24682 
24683 	ret = check_cfg(env);
24684 	if (ret < 0)
24685 		goto skip_full_check;
24686 
24687 	ret = check_attach_btf_id(env);
24688 	if (ret)
24689 		goto skip_full_check;
24690 
24691 	ret = compute_scc(env);
24692 	if (ret < 0)
24693 		goto skip_full_check;
24694 
24695 	ret = compute_live_registers(env);
24696 	if (ret < 0)
24697 		goto skip_full_check;
24698 
24699 	ret = mark_fastcall_patterns(env);
24700 	if (ret < 0)
24701 		goto skip_full_check;
24702 
24703 	ret = do_check_main(env);
24704 	ret = ret ?: do_check_subprogs(env);
24705 
24706 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24707 		ret = bpf_prog_offload_finalize(env);
24708 
24709 skip_full_check:
24710 	kvfree(env->explored_states);
24711 
24712 	/* might decrease stack depth, keep it before passes that
24713 	 * allocate additional slots.
24714 	 */
24715 	if (ret == 0)
24716 		ret = remove_fastcall_spills_fills(env);
24717 
24718 	if (ret == 0)
24719 		ret = check_max_stack_depth(env);
24720 
24721 	/* instruction rewrites happen after this point */
24722 	if (ret == 0)
24723 		ret = optimize_bpf_loop(env);
24724 
24725 	if (is_priv) {
24726 		if (ret == 0)
24727 			opt_hard_wire_dead_code_branches(env);
24728 		if (ret == 0)
24729 			ret = opt_remove_dead_code(env);
24730 		if (ret == 0)
24731 			ret = opt_remove_nops(env);
24732 	} else {
24733 		if (ret == 0)
24734 			sanitize_dead_code(env);
24735 	}
24736 
24737 	if (ret == 0)
24738 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24739 		ret = convert_ctx_accesses(env);
24740 
24741 	if (ret == 0)
24742 		ret = do_misc_fixups(env);
24743 
24744 	/* do 32-bit optimization after insn patching has done so those patched
24745 	 * insns could be handled correctly.
24746 	 */
24747 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24748 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
24749 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24750 								     : false;
24751 	}
24752 
24753 	if (ret == 0)
24754 		ret = fixup_call_args(env);
24755 
24756 	env->verification_time = ktime_get_ns() - start_time;
24757 	print_verification_stats(env);
24758 	env->prog->aux->verified_insns = env->insn_processed;
24759 
24760 	/* preserve original error even if log finalization is successful */
24761 	err = bpf_vlog_finalize(&env->log, &log_true_size);
24762 	if (err)
24763 		ret = err;
24764 
24765 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
24766 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
24767 				  &log_true_size, sizeof(log_true_size))) {
24768 		ret = -EFAULT;
24769 		goto err_release_maps;
24770 	}
24771 
24772 	if (ret)
24773 		goto err_release_maps;
24774 
24775 	if (env->used_map_cnt) {
24776 		/* if program passed verifier, update used_maps in bpf_prog_info */
24777 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
24778 							  sizeof(env->used_maps[0]),
24779 							  GFP_KERNEL_ACCOUNT);
24780 
24781 		if (!env->prog->aux->used_maps) {
24782 			ret = -ENOMEM;
24783 			goto err_release_maps;
24784 		}
24785 
24786 		memcpy(env->prog->aux->used_maps, env->used_maps,
24787 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24788 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24789 	}
24790 	if (env->used_btf_cnt) {
24791 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24792 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
24793 							  sizeof(env->used_btfs[0]),
24794 							  GFP_KERNEL_ACCOUNT);
24795 		if (!env->prog->aux->used_btfs) {
24796 			ret = -ENOMEM;
24797 			goto err_release_maps;
24798 		}
24799 
24800 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24801 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24802 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24803 	}
24804 	if (env->used_map_cnt || env->used_btf_cnt) {
24805 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24806 		 * bpf_ld_imm64 instructions
24807 		 */
24808 		convert_pseudo_ld_imm64(env);
24809 	}
24810 
24811 	adjust_btf_func(env);
24812 
24813 err_release_maps:
24814 	if (!env->prog->aux->used_maps)
24815 		/* if we didn't copy map pointers into bpf_prog_info, release
24816 		 * them now. Otherwise free_used_maps() will release them.
24817 		 */
24818 		release_maps(env);
24819 	if (!env->prog->aux->used_btfs)
24820 		release_btfs(env);
24821 
24822 	/* extension progs temporarily inherit the attach_type of their targets
24823 	   for verification purposes, so set it back to zero before returning
24824 	 */
24825 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24826 		env->prog->expected_attach_type = 0;
24827 
24828 	*prog = env->prog;
24829 
24830 	module_put(env->attach_btf_mod);
24831 err_unlock:
24832 	if (!is_priv)
24833 		mutex_unlock(&bpf_verifier_lock);
24834 	vfree(env->insn_aux_data);
24835 err_free_env:
24836 	kvfree(env->cfg.insn_postorder);
24837 	kvfree(env->scc_info);
24838 	kvfree(env);
24839 	return ret;
24840 }
24841