xref: /linux/kernel/bpf/verifier.c (revision cbba5d1b53fb82209feacb459edecb1ef8427119)
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 	case DYNPTR_TYPE_SKB_META:
678 		return BPF_DYNPTR_TYPE_SKB_META;
679 	default:
680 		return BPF_DYNPTR_TYPE_INVALID;
681 	}
682 }
683 
get_dynptr_type_flag(enum bpf_dynptr_type type)684 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
685 {
686 	switch (type) {
687 	case BPF_DYNPTR_TYPE_LOCAL:
688 		return DYNPTR_TYPE_LOCAL;
689 	case BPF_DYNPTR_TYPE_RINGBUF:
690 		return DYNPTR_TYPE_RINGBUF;
691 	case BPF_DYNPTR_TYPE_SKB:
692 		return DYNPTR_TYPE_SKB;
693 	case BPF_DYNPTR_TYPE_XDP:
694 		return DYNPTR_TYPE_XDP;
695 	case BPF_DYNPTR_TYPE_SKB_META:
696 		return DYNPTR_TYPE_SKB_META;
697 	default:
698 		return 0;
699 	}
700 }
701 
dynptr_type_refcounted(enum bpf_dynptr_type type)702 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
703 {
704 	return type == BPF_DYNPTR_TYPE_RINGBUF;
705 }
706 
707 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
708 			      enum bpf_dynptr_type type,
709 			      bool first_slot, int dynptr_id);
710 
711 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
712 				struct bpf_reg_state *reg);
713 
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)714 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
715 				   struct bpf_reg_state *sreg1,
716 				   struct bpf_reg_state *sreg2,
717 				   enum bpf_dynptr_type type)
718 {
719 	int id = ++env->id_gen;
720 
721 	__mark_dynptr_reg(sreg1, type, true, id);
722 	__mark_dynptr_reg(sreg2, type, false, id);
723 }
724 
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)725 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
726 			       struct bpf_reg_state *reg,
727 			       enum bpf_dynptr_type type)
728 {
729 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
730 }
731 
732 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
733 				        struct bpf_func_state *state, int spi);
734 
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)735 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
736 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
737 {
738 	struct bpf_func_state *state = func(env, reg);
739 	enum bpf_dynptr_type type;
740 	int spi, i, err;
741 
742 	spi = dynptr_get_spi(env, reg);
743 	if (spi < 0)
744 		return spi;
745 
746 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
747 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
748 	 * to ensure that for the following example:
749 	 *	[d1][d1][d2][d2]
750 	 * spi    3   2   1   0
751 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
752 	 * case they do belong to same dynptr, second call won't see slot_type
753 	 * as STACK_DYNPTR and will simply skip destruction.
754 	 */
755 	err = destroy_if_dynptr_stack_slot(env, state, spi);
756 	if (err)
757 		return err;
758 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
759 	if (err)
760 		return err;
761 
762 	for (i = 0; i < BPF_REG_SIZE; i++) {
763 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
764 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
765 	}
766 
767 	type = arg_to_dynptr_type(arg_type);
768 	if (type == BPF_DYNPTR_TYPE_INVALID)
769 		return -EINVAL;
770 
771 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
772 			       &state->stack[spi - 1].spilled_ptr, type);
773 
774 	if (dynptr_type_refcounted(type)) {
775 		/* The id is used to track proper releasing */
776 		int id;
777 
778 		if (clone_ref_obj_id)
779 			id = clone_ref_obj_id;
780 		else
781 			id = acquire_reference(env, insn_idx);
782 
783 		if (id < 0)
784 			return id;
785 
786 		state->stack[spi].spilled_ptr.ref_obj_id = id;
787 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
788 	}
789 
790 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
791 
792 	return 0;
793 }
794 
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)795 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
796 {
797 	int i;
798 
799 	for (i = 0; i < BPF_REG_SIZE; i++) {
800 		state->stack[spi].slot_type[i] = STACK_INVALID;
801 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
802 	}
803 
804 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
805 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
806 
807 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
808 }
809 
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)810 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
811 {
812 	struct bpf_func_state *state = func(env, reg);
813 	int spi, ref_obj_id, i;
814 
815 	spi = dynptr_get_spi(env, reg);
816 	if (spi < 0)
817 		return spi;
818 
819 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
820 		invalidate_dynptr(env, state, spi);
821 		return 0;
822 	}
823 
824 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
825 
826 	/* If the dynptr has a ref_obj_id, then we need to invalidate
827 	 * two things:
828 	 *
829 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
830 	 * 2) Any slices derived from this dynptr.
831 	 */
832 
833 	/* Invalidate any slices associated with this dynptr */
834 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
835 
836 	/* Invalidate any dynptr clones */
837 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
838 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
839 			continue;
840 
841 		/* it should always be the case that if the ref obj id
842 		 * matches then the stack slot also belongs to a
843 		 * dynptr
844 		 */
845 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
846 			verifier_bug(env, "misconfigured ref_obj_id");
847 			return -EFAULT;
848 		}
849 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
850 			invalidate_dynptr(env, state, i);
851 	}
852 
853 	return 0;
854 }
855 
856 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
857 			       struct bpf_reg_state *reg);
858 
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)859 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
860 {
861 	if (!env->allow_ptr_leaks)
862 		__mark_reg_not_init(env, reg);
863 	else
864 		__mark_reg_unknown(env, reg);
865 }
866 
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)867 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
868 				        struct bpf_func_state *state, int spi)
869 {
870 	struct bpf_func_state *fstate;
871 	struct bpf_reg_state *dreg;
872 	int i, dynptr_id;
873 
874 	/* We always ensure that STACK_DYNPTR is never set partially,
875 	 * hence just checking for slot_type[0] is enough. This is
876 	 * different for STACK_SPILL, where it may be only set for
877 	 * 1 byte, so code has to use is_spilled_reg.
878 	 */
879 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
880 		return 0;
881 
882 	/* Reposition spi to first slot */
883 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
884 		spi = spi + 1;
885 
886 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
887 		verbose(env, "cannot overwrite referenced dynptr\n");
888 		return -EINVAL;
889 	}
890 
891 	mark_stack_slot_scratched(env, spi);
892 	mark_stack_slot_scratched(env, spi - 1);
893 
894 	/* Writing partially to one dynptr stack slot destroys both. */
895 	for (i = 0; i < BPF_REG_SIZE; i++) {
896 		state->stack[spi].slot_type[i] = STACK_INVALID;
897 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
898 	}
899 
900 	dynptr_id = state->stack[spi].spilled_ptr.id;
901 	/* Invalidate any slices associated with this dynptr */
902 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
903 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
904 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
905 			continue;
906 		if (dreg->dynptr_id == dynptr_id)
907 			mark_reg_invalid(env, dreg);
908 	}));
909 
910 	/* Do not release reference state, we are destroying dynptr on stack,
911 	 * not using some helper to release it. Just reset register.
912 	 */
913 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
914 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
915 
916 	bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
917 
918 	return 0;
919 }
920 
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
922 {
923 	int spi;
924 
925 	if (reg->type == CONST_PTR_TO_DYNPTR)
926 		return false;
927 
928 	spi = dynptr_get_spi(env, reg);
929 
930 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
931 	 * error because this just means the stack state hasn't been updated yet.
932 	 * We will do check_mem_access to check and update stack bounds later.
933 	 */
934 	if (spi < 0 && spi != -ERANGE)
935 		return false;
936 
937 	/* We don't need to check if the stack slots are marked by previous
938 	 * dynptr initializations because we allow overwriting existing unreferenced
939 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
940 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
941 	 * touching are completely destructed before we reinitialize them for a new
942 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
943 	 * instead of delaying it until the end where the user will get "Unreleased
944 	 * reference" error.
945 	 */
946 	return true;
947 }
948 
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
950 {
951 	struct bpf_func_state *state = func(env, reg);
952 	int i, spi;
953 
954 	/* This already represents first slot of initialized bpf_dynptr.
955 	 *
956 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
957 	 * check_func_arg_reg_off's logic, so we don't need to check its
958 	 * offset and alignment.
959 	 */
960 	if (reg->type == CONST_PTR_TO_DYNPTR)
961 		return true;
962 
963 	spi = dynptr_get_spi(env, reg);
964 	if (spi < 0)
965 		return false;
966 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
967 		return false;
968 
969 	for (i = 0; i < BPF_REG_SIZE; i++) {
970 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
971 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
972 			return false;
973 	}
974 
975 	return true;
976 }
977 
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
979 				    enum bpf_arg_type arg_type)
980 {
981 	struct bpf_func_state *state = func(env, reg);
982 	enum bpf_dynptr_type dynptr_type;
983 	int spi;
984 
985 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
986 	if (arg_type == ARG_PTR_TO_DYNPTR)
987 		return true;
988 
989 	dynptr_type = arg_to_dynptr_type(arg_type);
990 	if (reg->type == CONST_PTR_TO_DYNPTR) {
991 		return reg->dynptr.type == dynptr_type;
992 	} else {
993 		spi = dynptr_get_spi(env, reg);
994 		if (spi < 0)
995 			return false;
996 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
997 	}
998 }
999 
1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1001 
1002 static bool in_rcu_cs(struct bpf_verifier_env *env);
1003 
1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1005 
mark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,struct bpf_reg_state * reg,int insn_idx,struct btf * btf,u32 btf_id,int nr_slots)1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1007 				 struct bpf_kfunc_call_arg_meta *meta,
1008 				 struct bpf_reg_state *reg, int insn_idx,
1009 				 struct btf *btf, u32 btf_id, int nr_slots)
1010 {
1011 	struct bpf_func_state *state = func(env, reg);
1012 	int spi, i, j, id;
1013 
1014 	spi = iter_get_spi(env, reg, nr_slots);
1015 	if (spi < 0)
1016 		return spi;
1017 
1018 	id = acquire_reference(env, insn_idx);
1019 	if (id < 0)
1020 		return id;
1021 
1022 	for (i = 0; i < nr_slots; i++) {
1023 		struct bpf_stack_state *slot = &state->stack[spi - i];
1024 		struct bpf_reg_state *st = &slot->spilled_ptr;
1025 
1026 		__mark_reg_known_zero(st);
1027 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1028 		if (is_kfunc_rcu_protected(meta)) {
1029 			if (in_rcu_cs(env))
1030 				st->type |= MEM_RCU;
1031 			else
1032 				st->type |= PTR_UNTRUSTED;
1033 		}
1034 		st->ref_obj_id = i == 0 ? id : 0;
1035 		st->iter.btf = btf;
1036 		st->iter.btf_id = btf_id;
1037 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1038 		st->iter.depth = 0;
1039 
1040 		for (j = 0; j < BPF_REG_SIZE; j++)
1041 			slot->slot_type[j] = STACK_ITER;
1042 
1043 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1044 		mark_stack_slot_scratched(env, spi - i);
1045 	}
1046 
1047 	return 0;
1048 }
1049 
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1050 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1051 				   struct bpf_reg_state *reg, int nr_slots)
1052 {
1053 	struct bpf_func_state *state = func(env, reg);
1054 	int spi, i, j;
1055 
1056 	spi = iter_get_spi(env, reg, nr_slots);
1057 	if (spi < 0)
1058 		return spi;
1059 
1060 	for (i = 0; i < nr_slots; i++) {
1061 		struct bpf_stack_state *slot = &state->stack[spi - i];
1062 		struct bpf_reg_state *st = &slot->spilled_ptr;
1063 
1064 		if (i == 0)
1065 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1066 
1067 		__mark_reg_not_init(env, st);
1068 
1069 		for (j = 0; j < BPF_REG_SIZE; j++)
1070 			slot->slot_type[j] = STACK_INVALID;
1071 
1072 		bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1073 		mark_stack_slot_scratched(env, spi - i);
1074 	}
1075 
1076 	return 0;
1077 }
1078 
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1079 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1080 				     struct bpf_reg_state *reg, int nr_slots)
1081 {
1082 	struct bpf_func_state *state = func(env, reg);
1083 	int spi, i, j;
1084 
1085 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1086 	 * will do check_mem_access to check and update stack bounds later, so
1087 	 * return true for that case.
1088 	 */
1089 	spi = iter_get_spi(env, reg, nr_slots);
1090 	if (spi == -ERANGE)
1091 		return true;
1092 	if (spi < 0)
1093 		return false;
1094 
1095 	for (i = 0; i < nr_slots; i++) {
1096 		struct bpf_stack_state *slot = &state->stack[spi - i];
1097 
1098 		for (j = 0; j < BPF_REG_SIZE; j++)
1099 			if (slot->slot_type[j] == STACK_ITER)
1100 				return false;
1101 	}
1102 
1103 	return true;
1104 }
1105 
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1106 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1107 				   struct btf *btf, u32 btf_id, int nr_slots)
1108 {
1109 	struct bpf_func_state *state = func(env, reg);
1110 	int spi, i, j;
1111 
1112 	spi = iter_get_spi(env, reg, nr_slots);
1113 	if (spi < 0)
1114 		return -EINVAL;
1115 
1116 	for (i = 0; i < nr_slots; i++) {
1117 		struct bpf_stack_state *slot = &state->stack[spi - i];
1118 		struct bpf_reg_state *st = &slot->spilled_ptr;
1119 
1120 		if (st->type & PTR_UNTRUSTED)
1121 			return -EPROTO;
1122 		/* only main (first) slot has ref_obj_id set */
1123 		if (i == 0 && !st->ref_obj_id)
1124 			return -EINVAL;
1125 		if (i != 0 && st->ref_obj_id)
1126 			return -EINVAL;
1127 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1128 			return -EINVAL;
1129 
1130 		for (j = 0; j < BPF_REG_SIZE; j++)
1131 			if (slot->slot_type[j] != STACK_ITER)
1132 				return -EINVAL;
1133 	}
1134 
1135 	return 0;
1136 }
1137 
1138 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1139 static int release_irq_state(struct bpf_verifier_state *state, int id);
1140 
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)1141 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1142 				     struct bpf_kfunc_call_arg_meta *meta,
1143 				     struct bpf_reg_state *reg, int insn_idx,
1144 				     int kfunc_class)
1145 {
1146 	struct bpf_func_state *state = func(env, reg);
1147 	struct bpf_stack_state *slot;
1148 	struct bpf_reg_state *st;
1149 	int spi, i, id;
1150 
1151 	spi = irq_flag_get_spi(env, reg);
1152 	if (spi < 0)
1153 		return spi;
1154 
1155 	id = acquire_irq_state(env, insn_idx);
1156 	if (id < 0)
1157 		return id;
1158 
1159 	slot = &state->stack[spi];
1160 	st = &slot->spilled_ptr;
1161 
1162 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1163 	__mark_reg_known_zero(st);
1164 	st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1165 	st->ref_obj_id = id;
1166 	st->irq.kfunc_class = kfunc_class;
1167 
1168 	for (i = 0; i < BPF_REG_SIZE; i++)
1169 		slot->slot_type[i] = STACK_IRQ_FLAG;
1170 
1171 	mark_stack_slot_scratched(env, spi);
1172 	return 0;
1173 }
1174 
unmark_stack_slot_irq_flag(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int kfunc_class)1175 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1176 				      int kfunc_class)
1177 {
1178 	struct bpf_func_state *state = func(env, reg);
1179 	struct bpf_stack_state *slot;
1180 	struct bpf_reg_state *st;
1181 	int spi, i, err;
1182 
1183 	spi = irq_flag_get_spi(env, reg);
1184 	if (spi < 0)
1185 		return spi;
1186 
1187 	slot = &state->stack[spi];
1188 	st = &slot->spilled_ptr;
1189 
1190 	if (st->irq.kfunc_class != kfunc_class) {
1191 		const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1192 		const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1193 
1194 		verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1195 			flag_kfunc, used_kfunc);
1196 		return -EINVAL;
1197 	}
1198 
1199 	err = release_irq_state(env->cur_state, st->ref_obj_id);
1200 	WARN_ON_ONCE(err && err != -EACCES);
1201 	if (err) {
1202 		int insn_idx = 0;
1203 
1204 		for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1205 			if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1206 				insn_idx = env->cur_state->refs[i].insn_idx;
1207 				break;
1208 			}
1209 		}
1210 
1211 		verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1212 			env->cur_state->active_irq_id, insn_idx);
1213 		return err;
1214 	}
1215 
1216 	__mark_reg_not_init(env, st);
1217 
1218 	bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1219 
1220 	for (i = 0; i < BPF_REG_SIZE; i++)
1221 		slot->slot_type[i] = STACK_INVALID;
1222 
1223 	mark_stack_slot_scratched(env, spi);
1224 	return 0;
1225 }
1226 
is_irq_flag_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1227 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1228 {
1229 	struct bpf_func_state *state = func(env, reg);
1230 	struct bpf_stack_state *slot;
1231 	int spi, i;
1232 
1233 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1234 	 * will do check_mem_access to check and update stack bounds later, so
1235 	 * return true for that case.
1236 	 */
1237 	spi = irq_flag_get_spi(env, reg);
1238 	if (spi == -ERANGE)
1239 		return true;
1240 	if (spi < 0)
1241 		return false;
1242 
1243 	slot = &state->stack[spi];
1244 
1245 	for (i = 0; i < BPF_REG_SIZE; i++)
1246 		if (slot->slot_type[i] == STACK_IRQ_FLAG)
1247 			return false;
1248 	return true;
1249 }
1250 
is_irq_flag_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1251 static int is_irq_flag_reg_valid_init(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 	struct bpf_reg_state *st;
1256 	int spi, i;
1257 
1258 	spi = irq_flag_get_spi(env, reg);
1259 	if (spi < 0)
1260 		return -EINVAL;
1261 
1262 	slot = &state->stack[spi];
1263 	st = &slot->spilled_ptr;
1264 
1265 	if (!st->ref_obj_id)
1266 		return -EINVAL;
1267 
1268 	for (i = 0; i < BPF_REG_SIZE; i++)
1269 		if (slot->slot_type[i] != STACK_IRQ_FLAG)
1270 			return -EINVAL;
1271 	return 0;
1272 }
1273 
1274 /* Check if given stack slot is "special":
1275  *   - spilled register state (STACK_SPILL);
1276  *   - dynptr state (STACK_DYNPTR);
1277  *   - iter state (STACK_ITER).
1278  *   - irq flag state (STACK_IRQ_FLAG)
1279  */
is_stack_slot_special(const struct bpf_stack_state * stack)1280 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1281 {
1282 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1283 
1284 	switch (type) {
1285 	case STACK_SPILL:
1286 	case STACK_DYNPTR:
1287 	case STACK_ITER:
1288 	case STACK_IRQ_FLAG:
1289 		return true;
1290 	case STACK_INVALID:
1291 	case STACK_MISC:
1292 	case STACK_ZERO:
1293 		return false;
1294 	default:
1295 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1296 		return true;
1297 	}
1298 }
1299 
1300 /* The reg state of a pointer or a bounded scalar was saved when
1301  * it was spilled to the stack.
1302  */
is_spilled_reg(const struct bpf_stack_state * stack)1303 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1304 {
1305 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1306 }
1307 
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1308 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1309 {
1310 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1311 	       stack->spilled_ptr.type == SCALAR_VALUE;
1312 }
1313 
is_spilled_scalar_reg64(const struct bpf_stack_state * stack)1314 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1315 {
1316 	return stack->slot_type[0] == STACK_SPILL &&
1317 	       stack->spilled_ptr.type == SCALAR_VALUE;
1318 }
1319 
1320 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1321  * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1322  * more precise STACK_ZERO.
1323  * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1324  * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1325  * unnecessary as both are considered equivalent when loading data and pruning,
1326  * in case of unprivileged mode it will be incorrect to allow reads of invalid
1327  * slots.
1328  */
mark_stack_slot_misc(struct bpf_verifier_env * env,u8 * stype)1329 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1330 {
1331 	if (*stype == STACK_ZERO)
1332 		return;
1333 	if (*stype == STACK_INVALID)
1334 		return;
1335 	*stype = STACK_MISC;
1336 }
1337 
scrub_spilled_slot(u8 * stype)1338 static void scrub_spilled_slot(u8 *stype)
1339 {
1340 	if (*stype != STACK_INVALID)
1341 		*stype = STACK_MISC;
1342 }
1343 
1344 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1345  * small to hold src. This is different from krealloc since we don't want to preserve
1346  * the contents of dst.
1347  *
1348  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1349  * not be allocated.
1350  */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1351 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1352 {
1353 	size_t alloc_bytes;
1354 	void *orig = dst;
1355 	size_t bytes;
1356 
1357 	if (ZERO_OR_NULL_PTR(src))
1358 		goto out;
1359 
1360 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1361 		return NULL;
1362 
1363 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1364 	dst = krealloc(orig, alloc_bytes, flags);
1365 	if (!dst) {
1366 		kfree(orig);
1367 		return NULL;
1368 	}
1369 
1370 	memcpy(dst, src, bytes);
1371 out:
1372 	return dst ? dst : ZERO_SIZE_PTR;
1373 }
1374 
1375 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1376  * small to hold new_n items. new items are zeroed out if the array grows.
1377  *
1378  * Contrary to krealloc_array, does not free arr if new_n is zero.
1379  */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1380 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1381 {
1382 	size_t alloc_size;
1383 	void *new_arr;
1384 
1385 	if (!new_n || old_n == new_n)
1386 		goto out;
1387 
1388 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1389 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1390 	if (!new_arr) {
1391 		kfree(arr);
1392 		return NULL;
1393 	}
1394 	arr = new_arr;
1395 
1396 	if (new_n > old_n)
1397 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1398 
1399 out:
1400 	return arr ? arr : ZERO_SIZE_PTR;
1401 }
1402 
copy_reference_state(struct bpf_verifier_state * dst,const struct bpf_verifier_state * src)1403 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1404 {
1405 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1406 			       sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1407 	if (!dst->refs)
1408 		return -ENOMEM;
1409 
1410 	dst->acquired_refs = src->acquired_refs;
1411 	dst->active_locks = src->active_locks;
1412 	dst->active_preempt_locks = src->active_preempt_locks;
1413 	dst->active_rcu_lock = src->active_rcu_lock;
1414 	dst->active_irq_id = src->active_irq_id;
1415 	dst->active_lock_id = src->active_lock_id;
1416 	dst->active_lock_ptr = src->active_lock_ptr;
1417 	return 0;
1418 }
1419 
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1420 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1421 {
1422 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1423 
1424 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1425 				GFP_KERNEL_ACCOUNT);
1426 	if (!dst->stack)
1427 		return -ENOMEM;
1428 
1429 	dst->allocated_stack = src->allocated_stack;
1430 	return 0;
1431 }
1432 
resize_reference_state(struct bpf_verifier_state * state,size_t n)1433 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1434 {
1435 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1436 				    sizeof(struct bpf_reference_state));
1437 	if (!state->refs)
1438 		return -ENOMEM;
1439 
1440 	state->acquired_refs = n;
1441 	return 0;
1442 }
1443 
1444 /* Possibly update state->allocated_stack to be at least size bytes. Also
1445  * possibly update the function's high-water mark in its bpf_subprog_info.
1446  */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1447 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1448 {
1449 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1450 
1451 	/* The stack size is always a multiple of BPF_REG_SIZE. */
1452 	size = round_up(size, BPF_REG_SIZE);
1453 	n = size / BPF_REG_SIZE;
1454 
1455 	if (old_n >= n)
1456 		return 0;
1457 
1458 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1459 	if (!state->stack)
1460 		return -ENOMEM;
1461 
1462 	state->allocated_stack = size;
1463 
1464 	/* update known max for given subprogram */
1465 	if (env->subprog_info[state->subprogno].stack_depth < size)
1466 		env->subprog_info[state->subprogno].stack_depth = size;
1467 
1468 	return 0;
1469 }
1470 
1471 /* Acquire a pointer id from the env and update the state->refs to include
1472  * this new pointer reference.
1473  * On success, returns a valid pointer id to associate with the register
1474  * On failure, returns a negative errno.
1475  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1476 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1477 {
1478 	struct bpf_verifier_state *state = env->cur_state;
1479 	int new_ofs = state->acquired_refs;
1480 	int err;
1481 
1482 	err = resize_reference_state(state, state->acquired_refs + 1);
1483 	if (err)
1484 		return NULL;
1485 	state->refs[new_ofs].insn_idx = insn_idx;
1486 
1487 	return &state->refs[new_ofs];
1488 }
1489 
acquire_reference(struct bpf_verifier_env * env,int insn_idx)1490 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1491 {
1492 	struct bpf_reference_state *s;
1493 
1494 	s = acquire_reference_state(env, insn_idx);
1495 	if (!s)
1496 		return -ENOMEM;
1497 	s->type = REF_TYPE_PTR;
1498 	s->id = ++env->id_gen;
1499 	return s->id;
1500 }
1501 
acquire_lock_state(struct bpf_verifier_env * env,int insn_idx,enum ref_state_type type,int id,void * ptr)1502 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1503 			      int id, void *ptr)
1504 {
1505 	struct bpf_verifier_state *state = env->cur_state;
1506 	struct bpf_reference_state *s;
1507 
1508 	s = acquire_reference_state(env, insn_idx);
1509 	if (!s)
1510 		return -ENOMEM;
1511 	s->type = type;
1512 	s->id = id;
1513 	s->ptr = ptr;
1514 
1515 	state->active_locks++;
1516 	state->active_lock_id = id;
1517 	state->active_lock_ptr = ptr;
1518 	return 0;
1519 }
1520 
acquire_irq_state(struct bpf_verifier_env * env,int insn_idx)1521 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1522 {
1523 	struct bpf_verifier_state *state = env->cur_state;
1524 	struct bpf_reference_state *s;
1525 
1526 	s = acquire_reference_state(env, insn_idx);
1527 	if (!s)
1528 		return -ENOMEM;
1529 	s->type = REF_TYPE_IRQ;
1530 	s->id = ++env->id_gen;
1531 
1532 	state->active_irq_id = s->id;
1533 	return s->id;
1534 }
1535 
release_reference_state(struct bpf_verifier_state * state,int idx)1536 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1537 {
1538 	int last_idx;
1539 	size_t rem;
1540 
1541 	/* IRQ state requires the relative ordering of elements remaining the
1542 	 * same, since it relies on the refs array to behave as a stack, so that
1543 	 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1544 	 * the array instead of swapping the final element into the deleted idx.
1545 	 */
1546 	last_idx = state->acquired_refs - 1;
1547 	rem = state->acquired_refs - idx - 1;
1548 	if (last_idx && idx != last_idx)
1549 		memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1550 	memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1551 	state->acquired_refs--;
1552 	return;
1553 }
1554 
find_reference_state(struct bpf_verifier_state * state,int ptr_id)1555 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1556 {
1557 	int i;
1558 
1559 	for (i = 0; i < state->acquired_refs; i++)
1560 		if (state->refs[i].id == ptr_id)
1561 			return true;
1562 
1563 	return false;
1564 }
1565 
release_lock_state(struct bpf_verifier_state * state,int type,int id,void * ptr)1566 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1567 {
1568 	void *prev_ptr = NULL;
1569 	u32 prev_id = 0;
1570 	int i;
1571 
1572 	for (i = 0; i < state->acquired_refs; i++) {
1573 		if (state->refs[i].type == type && state->refs[i].id == id &&
1574 		    state->refs[i].ptr == ptr) {
1575 			release_reference_state(state, i);
1576 			state->active_locks--;
1577 			/* Reassign active lock (id, ptr). */
1578 			state->active_lock_id = prev_id;
1579 			state->active_lock_ptr = prev_ptr;
1580 			return 0;
1581 		}
1582 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1583 			prev_id = state->refs[i].id;
1584 			prev_ptr = state->refs[i].ptr;
1585 		}
1586 	}
1587 	return -EINVAL;
1588 }
1589 
release_irq_state(struct bpf_verifier_state * state,int id)1590 static int release_irq_state(struct bpf_verifier_state *state, int id)
1591 {
1592 	u32 prev_id = 0;
1593 	int i;
1594 
1595 	if (id != state->active_irq_id)
1596 		return -EACCES;
1597 
1598 	for (i = 0; i < state->acquired_refs; i++) {
1599 		if (state->refs[i].type != REF_TYPE_IRQ)
1600 			continue;
1601 		if (state->refs[i].id == id) {
1602 			release_reference_state(state, i);
1603 			state->active_irq_id = prev_id;
1604 			return 0;
1605 		} else {
1606 			prev_id = state->refs[i].id;
1607 		}
1608 	}
1609 	return -EINVAL;
1610 }
1611 
find_lock_state(struct bpf_verifier_state * state,enum ref_state_type type,int id,void * ptr)1612 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1613 						   int id, void *ptr)
1614 {
1615 	int i;
1616 
1617 	for (i = 0; i < state->acquired_refs; i++) {
1618 		struct bpf_reference_state *s = &state->refs[i];
1619 
1620 		if (!(s->type & type))
1621 			continue;
1622 
1623 		if (s->id == id && s->ptr == ptr)
1624 			return s;
1625 	}
1626 	return NULL;
1627 }
1628 
update_peak_states(struct bpf_verifier_env * env)1629 static void update_peak_states(struct bpf_verifier_env *env)
1630 {
1631 	u32 cur_states;
1632 
1633 	cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1634 	env->peak_states = max(env->peak_states, cur_states);
1635 }
1636 
free_func_state(struct bpf_func_state * state)1637 static void free_func_state(struct bpf_func_state *state)
1638 {
1639 	if (!state)
1640 		return;
1641 	kfree(state->stack);
1642 	kfree(state);
1643 }
1644 
clear_jmp_history(struct bpf_verifier_state * state)1645 static void clear_jmp_history(struct bpf_verifier_state *state)
1646 {
1647 	kfree(state->jmp_history);
1648 	state->jmp_history = NULL;
1649 	state->jmp_history_cnt = 0;
1650 }
1651 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1652 static void free_verifier_state(struct bpf_verifier_state *state,
1653 				bool free_self)
1654 {
1655 	int i;
1656 
1657 	for (i = 0; i <= state->curframe; i++) {
1658 		free_func_state(state->frame[i]);
1659 		state->frame[i] = NULL;
1660 	}
1661 	kfree(state->refs);
1662 	clear_jmp_history(state);
1663 	if (free_self)
1664 		kfree(state);
1665 }
1666 
1667 /* struct bpf_verifier_state->parent refers to states
1668  * that are in either of env->{expored_states,free_list}.
1669  * In both cases the state is contained in struct bpf_verifier_state_list.
1670  */
state_parent_as_list(struct bpf_verifier_state * st)1671 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1672 {
1673 	if (st->parent)
1674 		return container_of(st->parent, struct bpf_verifier_state_list, state);
1675 	return NULL;
1676 }
1677 
1678 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1679 				  struct bpf_verifier_state *st);
1680 
1681 /* A state can be freed if it is no longer referenced:
1682  * - is in the env->free_list;
1683  * - has no children states;
1684  */
maybe_free_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state_list * sl)1685 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1686 				      struct bpf_verifier_state_list *sl)
1687 {
1688 	if (!sl->in_free_list
1689 	    || sl->state.branches != 0
1690 	    || incomplete_read_marks(env, &sl->state))
1691 		return;
1692 	list_del(&sl->node);
1693 	free_verifier_state(&sl->state, false);
1694 	kfree(sl);
1695 	env->free_list_size--;
1696 }
1697 
1698 /* copy verifier state from src to dst growing dst stack space
1699  * when necessary to accommodate larger src stack
1700  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1701 static int copy_func_state(struct bpf_func_state *dst,
1702 			   const struct bpf_func_state *src)
1703 {
1704 	memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1705 	return copy_stack_state(dst, src);
1706 }
1707 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1708 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1709 			       const struct bpf_verifier_state *src)
1710 {
1711 	struct bpf_func_state *dst;
1712 	int i, err;
1713 
1714 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1715 					  src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1716 					  GFP_KERNEL_ACCOUNT);
1717 	if (!dst_state->jmp_history)
1718 		return -ENOMEM;
1719 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1720 
1721 	/* if dst has more stack frames then src frame, free them, this is also
1722 	 * necessary in case of exceptional exits using bpf_throw.
1723 	 */
1724 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1725 		free_func_state(dst_state->frame[i]);
1726 		dst_state->frame[i] = NULL;
1727 	}
1728 	err = copy_reference_state(dst_state, src);
1729 	if (err)
1730 		return err;
1731 	dst_state->speculative = src->speculative;
1732 	dst_state->in_sleepable = src->in_sleepable;
1733 	dst_state->cleaned = src->cleaned;
1734 	dst_state->curframe = src->curframe;
1735 	dst_state->branches = src->branches;
1736 	dst_state->parent = src->parent;
1737 	dst_state->first_insn_idx = src->first_insn_idx;
1738 	dst_state->last_insn_idx = src->last_insn_idx;
1739 	dst_state->dfs_depth = src->dfs_depth;
1740 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1741 	dst_state->may_goto_depth = src->may_goto_depth;
1742 	dst_state->equal_state = src->equal_state;
1743 	for (i = 0; i <= src->curframe; i++) {
1744 		dst = dst_state->frame[i];
1745 		if (!dst) {
1746 			dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1747 			if (!dst)
1748 				return -ENOMEM;
1749 			dst_state->frame[i] = dst;
1750 		}
1751 		err = copy_func_state(dst, src->frame[i]);
1752 		if (err)
1753 			return err;
1754 	}
1755 	return 0;
1756 }
1757 
state_htab_size(struct bpf_verifier_env * env)1758 static u32 state_htab_size(struct bpf_verifier_env *env)
1759 {
1760 	return env->prog->len;
1761 }
1762 
explored_state(struct bpf_verifier_env * env,int idx)1763 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1764 {
1765 	struct bpf_verifier_state *cur = env->cur_state;
1766 	struct bpf_func_state *state = cur->frame[cur->curframe];
1767 
1768 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1769 }
1770 
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1771 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1772 {
1773 	int fr;
1774 
1775 	if (a->curframe != b->curframe)
1776 		return false;
1777 
1778 	for (fr = a->curframe; fr >= 0; fr--)
1779 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1780 			return false;
1781 
1782 	return true;
1783 }
1784 
1785 /* Return IP for a given frame in a call stack */
frame_insn_idx(struct bpf_verifier_state * st,u32 frame)1786 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1787 {
1788 	return frame == st->curframe
1789 	       ? st->insn_idx
1790 	       : st->frame[frame + 1]->callsite;
1791 }
1792 
1793 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1794  * if such frame exists form a corresponding @callchain as an array of
1795  * call sites leading to this frame and SCC id.
1796  * E.g.:
1797  *
1798  *    void foo()  { A: loop {... SCC#1 ...}; }
1799  *    void bar()  { B: loop { C: foo(); ... SCC#2 ... }
1800  *                  D: loop { E: foo(); ... SCC#3 ... } }
1801  *    void main() { F: bar(); }
1802  *
1803  * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1804  * on @st frame call sites being (F,C,A) or (F,E,A).
1805  */
compute_scc_callchain(struct bpf_verifier_env * env,struct bpf_verifier_state * st,struct bpf_scc_callchain * callchain)1806 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1807 				  struct bpf_verifier_state *st,
1808 				  struct bpf_scc_callchain *callchain)
1809 {
1810 	u32 i, scc, insn_idx;
1811 
1812 	memset(callchain, 0, sizeof(*callchain));
1813 	for (i = 0; i <= st->curframe; i++) {
1814 		insn_idx = frame_insn_idx(st, i);
1815 		scc = env->insn_aux_data[insn_idx].scc;
1816 		if (scc) {
1817 			callchain->scc = scc;
1818 			break;
1819 		} else if (i < st->curframe) {
1820 			callchain->callsites[i] = insn_idx;
1821 		} else {
1822 			return false;
1823 		}
1824 	}
1825 	return true;
1826 }
1827 
1828 /* Check if bpf_scc_visit instance for @callchain exists. */
scc_visit_lookup(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1829 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1830 					      struct bpf_scc_callchain *callchain)
1831 {
1832 	struct bpf_scc_info *info = env->scc_info[callchain->scc];
1833 	struct bpf_scc_visit *visits = info->visits;
1834 	u32 i;
1835 
1836 	if (!info)
1837 		return NULL;
1838 	for (i = 0; i < info->num_visits; i++)
1839 		if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1840 			return &visits[i];
1841 	return NULL;
1842 }
1843 
1844 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1845  * Allocated instances are alive for a duration of the do_check_common()
1846  * call and are freed by free_states().
1847  */
scc_visit_alloc(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1848 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1849 					     struct bpf_scc_callchain *callchain)
1850 {
1851 	struct bpf_scc_visit *visit;
1852 	struct bpf_scc_info *info;
1853 	u32 scc, num_visits;
1854 	u64 new_sz;
1855 
1856 	scc = callchain->scc;
1857 	info = env->scc_info[scc];
1858 	num_visits = info ? info->num_visits : 0;
1859 	new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1860 	info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1861 	if (!info)
1862 		return NULL;
1863 	env->scc_info[scc] = info;
1864 	info->num_visits = num_visits + 1;
1865 	visit = &info->visits[num_visits];
1866 	memset(visit, 0, sizeof(*visit));
1867 	memcpy(&visit->callchain, callchain, sizeof(*callchain));
1868 	return visit;
1869 }
1870 
1871 /* 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)1872 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1873 {
1874 	char *buf = env->tmp_str_buf;
1875 	int i, delta = 0;
1876 
1877 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1878 	for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1879 		if (!callchain->callsites[i])
1880 			break;
1881 		delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1882 				  callchain->callsites[i]);
1883 	}
1884 	delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1885 	return env->tmp_str_buf;
1886 }
1887 
1888 /* If callchain for @st exists (@st is in some SCC), ensure that
1889  * bpf_scc_visit instance for this callchain exists.
1890  * If instance does not exist or is empty, assign visit->entry_state to @st.
1891  */
maybe_enter_scc(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1892 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1893 {
1894 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1895 	struct bpf_scc_visit *visit;
1896 
1897 	if (!compute_scc_callchain(env, st, callchain))
1898 		return 0;
1899 	visit = scc_visit_lookup(env, callchain);
1900 	visit = visit ?: scc_visit_alloc(env, callchain);
1901 	if (!visit)
1902 		return -ENOMEM;
1903 	if (!visit->entry_state) {
1904 		visit->entry_state = st;
1905 		if (env->log.level & BPF_LOG_LEVEL2)
1906 			verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1907 	}
1908 	return 0;
1909 }
1910 
1911 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1912 
1913 /* If callchain for @st exists (@st is in some SCC), make it empty:
1914  * - set visit->entry_state to NULL;
1915  * - flush accumulated backedges.
1916  */
maybe_exit_scc(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1917 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1918 {
1919 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1920 	struct bpf_scc_visit *visit;
1921 
1922 	if (!compute_scc_callchain(env, st, callchain))
1923 		return 0;
1924 	visit = scc_visit_lookup(env, callchain);
1925 	if (!visit) {
1926 		/*
1927 		 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1928 		 * must exist for non-speculative paths. For non-speculative paths
1929 		 * traversal stops when:
1930 		 * a. Verification error is found, maybe_exit_scc() is not called.
1931 		 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1932 		 *    of any SCC.
1933 		 * c. A checkpoint is reached and matched. Checkpoints are created by
1934 		 *    is_state_visited(), which calls maybe_enter_scc(), which allocates
1935 		 *    bpf_scc_visit instances for checkpoints within SCCs.
1936 		 * (c) is the only case that can reach this point.
1937 		 */
1938 		if (!st->speculative) {
1939 			verifier_bug(env, "scc exit: no visit info for call chain %s",
1940 				     format_callchain(env, callchain));
1941 			return -EFAULT;
1942 		}
1943 		return 0;
1944 	}
1945 	if (visit->entry_state != st)
1946 		return 0;
1947 	if (env->log.level & BPF_LOG_LEVEL2)
1948 		verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1949 	visit->entry_state = NULL;
1950 	env->num_backedges -= visit->num_backedges;
1951 	visit->num_backedges = 0;
1952 	update_peak_states(env);
1953 	return propagate_backedges(env, visit);
1954 }
1955 
1956 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1957  * and add @backedge to visit->backedges. @st callchain must exist.
1958  */
add_scc_backedge(struct bpf_verifier_env * env,struct bpf_verifier_state * st,struct bpf_scc_backedge * backedge)1959 static int add_scc_backedge(struct bpf_verifier_env *env,
1960 			    struct bpf_verifier_state *st,
1961 			    struct bpf_scc_backedge *backedge)
1962 {
1963 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1964 	struct bpf_scc_visit *visit;
1965 
1966 	if (!compute_scc_callchain(env, st, callchain)) {
1967 		verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1968 			     st->insn_idx);
1969 		return -EFAULT;
1970 	}
1971 	visit = scc_visit_lookup(env, callchain);
1972 	if (!visit) {
1973 		verifier_bug(env, "add backedge: no visit info for call chain %s",
1974 			     format_callchain(env, callchain));
1975 		return -EFAULT;
1976 	}
1977 	if (env->log.level & BPF_LOG_LEVEL2)
1978 		verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
1979 	backedge->next = visit->backedges;
1980 	visit->backedges = backedge;
1981 	visit->num_backedges++;
1982 	env->num_backedges++;
1983 	update_peak_states(env);
1984 	return 0;
1985 }
1986 
1987 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
1988  * if state @st is in some SCC and not all execution paths starting at this
1989  * SCC are fully explored.
1990  */
incomplete_read_marks(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1991 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1992 				  struct bpf_verifier_state *st)
1993 {
1994 	struct bpf_scc_callchain *callchain = &env->callchain_buf;
1995 	struct bpf_scc_visit *visit;
1996 
1997 	if (!compute_scc_callchain(env, st, callchain))
1998 		return false;
1999 	visit = scc_visit_lookup(env, callchain);
2000 	if (!visit)
2001 		return false;
2002 	return !!visit->backedges;
2003 }
2004 
free_backedges(struct bpf_scc_visit * visit)2005 static void free_backedges(struct bpf_scc_visit *visit)
2006 {
2007 	struct bpf_scc_backedge *backedge, *next;
2008 
2009 	for (backedge = visit->backedges; backedge; backedge = next) {
2010 		free_verifier_state(&backedge->state, false);
2011 		next = backedge->next;
2012 		kfree(backedge);
2013 	}
2014 	visit->backedges = NULL;
2015 }
2016 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2017 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2018 {
2019 	struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2020 	struct bpf_verifier_state *parent;
2021 	int err;
2022 
2023 	while (st) {
2024 		u32 br = --st->branches;
2025 
2026 		/* verifier_bug_if(br > 1, ...) technically makes sense here,
2027 		 * but see comment in push_stack(), hence:
2028 		 */
2029 		verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2030 		if (br)
2031 			break;
2032 		err = maybe_exit_scc(env, st);
2033 		if (err)
2034 			return err;
2035 		parent = st->parent;
2036 		parent_sl = state_parent_as_list(st);
2037 		if (sl)
2038 			maybe_free_verifier_state(env, sl);
2039 		st = parent;
2040 		sl = parent_sl;
2041 	}
2042 	return 0;
2043 }
2044 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)2045 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2046 		     int *insn_idx, bool pop_log)
2047 {
2048 	struct bpf_verifier_state *cur = env->cur_state;
2049 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2050 	int err;
2051 
2052 	if (env->head == NULL)
2053 		return -ENOENT;
2054 
2055 	if (cur) {
2056 		err = copy_verifier_state(cur, &head->st);
2057 		if (err)
2058 			return err;
2059 	}
2060 	if (pop_log)
2061 		bpf_vlog_reset(&env->log, head->log_pos);
2062 	if (insn_idx)
2063 		*insn_idx = head->insn_idx;
2064 	if (prev_insn_idx)
2065 		*prev_insn_idx = head->prev_insn_idx;
2066 	elem = head->next;
2067 	free_verifier_state(&head->st, false);
2068 	kfree(head);
2069 	env->head = elem;
2070 	env->stack_size--;
2071 	return 0;
2072 }
2073 
error_recoverable_with_nospec(int err)2074 static bool error_recoverable_with_nospec(int err)
2075 {
2076 	/* Should only return true for non-fatal errors that are allowed to
2077 	 * occur during speculative verification. For these we can insert a
2078 	 * nospec and the program might still be accepted. Do not include
2079 	 * something like ENOMEM because it is likely to re-occur for the next
2080 	 * architectural path once it has been recovered-from in all speculative
2081 	 * paths.
2082 	 */
2083 	return err == -EPERM || err == -EACCES || err == -EINVAL;
2084 }
2085 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)2086 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2087 					     int insn_idx, int prev_insn_idx,
2088 					     bool speculative)
2089 {
2090 	struct bpf_verifier_state *cur = env->cur_state;
2091 	struct bpf_verifier_stack_elem *elem;
2092 	int err;
2093 
2094 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2095 	if (!elem)
2096 		return NULL;
2097 
2098 	elem->insn_idx = insn_idx;
2099 	elem->prev_insn_idx = prev_insn_idx;
2100 	elem->next = env->head;
2101 	elem->log_pos = env->log.end_pos;
2102 	env->head = elem;
2103 	env->stack_size++;
2104 	err = copy_verifier_state(&elem->st, cur);
2105 	if (err)
2106 		return NULL;
2107 	elem->st.speculative |= speculative;
2108 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2109 		verbose(env, "The sequence of %d jumps is too complex.\n",
2110 			env->stack_size);
2111 		return NULL;
2112 	}
2113 	if (elem->st.parent) {
2114 		++elem->st.parent->branches;
2115 		/* WARN_ON(branches > 2) technically makes sense here,
2116 		 * but
2117 		 * 1. speculative states will bump 'branches' for non-branch
2118 		 * instructions
2119 		 * 2. is_state_visited() heuristics may decide not to create
2120 		 * a new state for a sequence of branches and all such current
2121 		 * and cloned states will be pointing to a single parent state
2122 		 * which might have large 'branches' count.
2123 		 */
2124 	}
2125 	return &elem->st;
2126 }
2127 
2128 #define CALLER_SAVED_REGS 6
2129 static const int caller_saved[CALLER_SAVED_REGS] = {
2130 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2131 };
2132 
2133 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)2134 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2135 {
2136 	reg->var_off = tnum_const(imm);
2137 	reg->smin_value = (s64)imm;
2138 	reg->smax_value = (s64)imm;
2139 	reg->umin_value = imm;
2140 	reg->umax_value = imm;
2141 
2142 	reg->s32_min_value = (s32)imm;
2143 	reg->s32_max_value = (s32)imm;
2144 	reg->u32_min_value = (u32)imm;
2145 	reg->u32_max_value = (u32)imm;
2146 }
2147 
2148 /* Mark the unknown part of a register (variable offset or scalar value) as
2149  * known to have the value @imm.
2150  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)2151 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2152 {
2153 	/* Clear off and union(map_ptr, range) */
2154 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2155 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2156 	reg->id = 0;
2157 	reg->ref_obj_id = 0;
2158 	___mark_reg_known(reg, imm);
2159 }
2160 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)2161 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2162 {
2163 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2164 	reg->s32_min_value = (s32)imm;
2165 	reg->s32_max_value = (s32)imm;
2166 	reg->u32_min_value = (u32)imm;
2167 	reg->u32_max_value = (u32)imm;
2168 }
2169 
2170 /* Mark the 'variable offset' part of a register as zero.  This should be
2171  * used only on registers holding a pointer type.
2172  */
__mark_reg_known_zero(struct bpf_reg_state * reg)2173 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2174 {
2175 	__mark_reg_known(reg, 0);
2176 }
2177 
__mark_reg_const_zero(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2178 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2179 {
2180 	__mark_reg_known(reg, 0);
2181 	reg->type = SCALAR_VALUE;
2182 	/* all scalars are assumed imprecise initially (unless unprivileged,
2183 	 * in which case everything is forced to be precise)
2184 	 */
2185 	reg->precise = !env->bpf_capable;
2186 }
2187 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2188 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2189 				struct bpf_reg_state *regs, u32 regno)
2190 {
2191 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2192 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2193 		/* Something bad happened, let's kill all regs */
2194 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2195 			__mark_reg_not_init(env, regs + regno);
2196 		return;
2197 	}
2198 	__mark_reg_known_zero(regs + regno);
2199 }
2200 
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)2201 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2202 			      bool first_slot, int dynptr_id)
2203 {
2204 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2205 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2206 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2207 	 */
2208 	__mark_reg_known_zero(reg);
2209 	reg->type = CONST_PTR_TO_DYNPTR;
2210 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2211 	reg->id = dynptr_id;
2212 	reg->dynptr.type = type;
2213 	reg->dynptr.first_slot = first_slot;
2214 }
2215 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)2216 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2217 {
2218 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2219 		const struct bpf_map *map = reg->map_ptr;
2220 
2221 		if (map->inner_map_meta) {
2222 			reg->type = CONST_PTR_TO_MAP;
2223 			reg->map_ptr = map->inner_map_meta;
2224 			/* transfer reg's id which is unique for every map_lookup_elem
2225 			 * as UID of the inner map.
2226 			 */
2227 			if (btf_record_has_field(map->inner_map_meta->record,
2228 						 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2229 				reg->map_uid = reg->id;
2230 			}
2231 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2232 			reg->type = PTR_TO_XDP_SOCK;
2233 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2234 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2235 			reg->type = PTR_TO_SOCKET;
2236 		} else {
2237 			reg->type = PTR_TO_MAP_VALUE;
2238 		}
2239 		return;
2240 	}
2241 
2242 	reg->type &= ~PTR_MAYBE_NULL;
2243 }
2244 
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)2245 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2246 				struct btf_field_graph_root *ds_head)
2247 {
2248 	__mark_reg_known_zero(&regs[regno]);
2249 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2250 	regs[regno].btf = ds_head->btf;
2251 	regs[regno].btf_id = ds_head->value_btf_id;
2252 	regs[regno].off = ds_head->node_offset;
2253 }
2254 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)2255 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2256 {
2257 	return type_is_pkt_pointer(reg->type);
2258 }
2259 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)2260 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2261 {
2262 	return reg_is_pkt_pointer(reg) ||
2263 	       reg->type == PTR_TO_PACKET_END;
2264 }
2265 
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)2266 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2267 {
2268 	return base_type(reg->type) == PTR_TO_MEM &&
2269 	       (reg->type &
2270 		(DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2271 }
2272 
2273 /* 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)2274 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2275 				    enum bpf_reg_type which)
2276 {
2277 	/* The register can already have a range from prior markings.
2278 	 * This is fine as long as it hasn't been advanced from its
2279 	 * origin.
2280 	 */
2281 	return reg->type == which &&
2282 	       reg->id == 0 &&
2283 	       reg->off == 0 &&
2284 	       tnum_equals_const(reg->var_off, 0);
2285 }
2286 
2287 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)2288 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2289 {
2290 	reg->smin_value = S64_MIN;
2291 	reg->smax_value = S64_MAX;
2292 	reg->umin_value = 0;
2293 	reg->umax_value = U64_MAX;
2294 
2295 	reg->s32_min_value = S32_MIN;
2296 	reg->s32_max_value = S32_MAX;
2297 	reg->u32_min_value = 0;
2298 	reg->u32_max_value = U32_MAX;
2299 }
2300 
__mark_reg64_unbounded(struct bpf_reg_state * reg)2301 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2302 {
2303 	reg->smin_value = S64_MIN;
2304 	reg->smax_value = S64_MAX;
2305 	reg->umin_value = 0;
2306 	reg->umax_value = U64_MAX;
2307 }
2308 
__mark_reg32_unbounded(struct bpf_reg_state * reg)2309 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2310 {
2311 	reg->s32_min_value = S32_MIN;
2312 	reg->s32_max_value = S32_MAX;
2313 	reg->u32_min_value = 0;
2314 	reg->u32_max_value = U32_MAX;
2315 }
2316 
__update_reg32_bounds(struct bpf_reg_state * reg)2317 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2318 {
2319 	struct tnum var32_off = tnum_subreg(reg->var_off);
2320 
2321 	/* min signed is max(sign bit) | min(other bits) */
2322 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2323 			var32_off.value | (var32_off.mask & S32_MIN));
2324 	/* max signed is min(sign bit) | max(other bits) */
2325 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2326 			var32_off.value | (var32_off.mask & S32_MAX));
2327 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2328 	reg->u32_max_value = min(reg->u32_max_value,
2329 				 (u32)(var32_off.value | var32_off.mask));
2330 }
2331 
__update_reg64_bounds(struct bpf_reg_state * reg)2332 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2333 {
2334 	/* min signed is max(sign bit) | min(other bits) */
2335 	reg->smin_value = max_t(s64, reg->smin_value,
2336 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2337 	/* max signed is min(sign bit) | max(other bits) */
2338 	reg->smax_value = min_t(s64, reg->smax_value,
2339 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2340 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2341 	reg->umax_value = min(reg->umax_value,
2342 			      reg->var_off.value | reg->var_off.mask);
2343 }
2344 
__update_reg_bounds(struct bpf_reg_state * reg)2345 static void __update_reg_bounds(struct bpf_reg_state *reg)
2346 {
2347 	__update_reg32_bounds(reg);
2348 	__update_reg64_bounds(reg);
2349 }
2350 
2351 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)2352 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2353 {
2354 	/* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2355 	 * bits to improve our u32/s32 boundaries.
2356 	 *
2357 	 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2358 	 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2359 	 * [10, 20] range. But this property holds for any 64-bit range as
2360 	 * long as upper 32 bits in that entire range of values stay the same.
2361 	 *
2362 	 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2363 	 * in decimal) has the same upper 32 bits throughout all the values in
2364 	 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2365 	 * range.
2366 	 *
2367 	 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2368 	 * following the rules outlined below about u64/s64 correspondence
2369 	 * (which equally applies to u32 vs s32 correspondence). In general it
2370 	 * depends on actual hexadecimal values of 32-bit range. They can form
2371 	 * only valid u32, or only valid s32 ranges in some cases.
2372 	 *
2373 	 * So we use all these insights to derive bounds for subregisters here.
2374 	 */
2375 	if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2376 		/* u64 to u32 casting preserves validity of low 32 bits as
2377 		 * a range, if upper 32 bits are the same
2378 		 */
2379 		reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2380 		reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2381 
2382 		if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2383 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2384 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2385 		}
2386 	}
2387 	if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2388 		/* low 32 bits should form a proper u32 range */
2389 		if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2390 			reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2391 			reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2392 		}
2393 		/* low 32 bits should form a proper s32 range */
2394 		if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2395 			reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2396 			reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2397 		}
2398 	}
2399 	/* Special case where upper bits form a small sequence of two
2400 	 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2401 	 * 0x00000000 is also valid), while lower bits form a proper s32 range
2402 	 * going from negative numbers to positive numbers. E.g., let's say we
2403 	 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2404 	 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2405 	 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2406 	 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2407 	 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2408 	 * upper 32 bits. As a random example, s64 range
2409 	 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2410 	 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2411 	 */
2412 	if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2413 	    (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2414 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2415 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2416 	}
2417 	if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2418 	    (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2419 		reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2420 		reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2421 	}
2422 	/* if u32 range forms a valid s32 range (due to matching sign bit),
2423 	 * try to learn from that
2424 	 */
2425 	if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2426 		reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2427 		reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2428 	}
2429 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2430 	 * are the same, so combine.  This works even in the negative case, e.g.
2431 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2432 	 */
2433 	if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2434 		reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2435 		reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2436 	}
2437 }
2438 
__reg64_deduce_bounds(struct bpf_reg_state * reg)2439 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2440 {
2441 	/* If u64 range forms a valid s64 range (due to matching sign bit),
2442 	 * try to learn from that. Let's do a bit of ASCII art to see when
2443 	 * this is happening. Let's take u64 range first:
2444 	 *
2445 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2446 	 * |-------------------------------|--------------------------------|
2447 	 *
2448 	 * Valid u64 range is formed when umin and umax are anywhere in the
2449 	 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2450 	 * straightforward. Let's see how s64 range maps onto the same range
2451 	 * of values, annotated below the line for comparison:
2452 	 *
2453 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2454 	 * |-------------------------------|--------------------------------|
2455 	 * 0                        S64_MAX S64_MIN                        -1
2456 	 *
2457 	 * So s64 values basically start in the middle and they are logically
2458 	 * contiguous to the right of it, wrapping around from -1 to 0, and
2459 	 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2460 	 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2461 	 * more visually as mapped to sign-agnostic range of hex values.
2462 	 *
2463 	 *  u64 start                                               u64 end
2464 	 *  _______________________________________________________________
2465 	 * /                                                               \
2466 	 * 0             0x7fffffffffffffff 0x8000000000000000        U64_MAX
2467 	 * |-------------------------------|--------------------------------|
2468 	 * 0                        S64_MAX S64_MIN                        -1
2469 	 *                                / \
2470 	 * >------------------------------   ------------------------------->
2471 	 * s64 continues...        s64 end   s64 start          s64 "midpoint"
2472 	 *
2473 	 * What this means is that, in general, we can't always derive
2474 	 * something new about u64 from any random s64 range, and vice versa.
2475 	 *
2476 	 * But we can do that in two particular cases. One is when entire
2477 	 * u64/s64 range is *entirely* contained within left half of the above
2478 	 * diagram or when it is *entirely* contained in the right half. I.e.:
2479 	 *
2480 	 * |-------------------------------|--------------------------------|
2481 	 *     ^                   ^            ^                 ^
2482 	 *     A                   B            C                 D
2483 	 *
2484 	 * [A, B] and [C, D] are contained entirely in their respective halves
2485 	 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2486 	 * will be non-negative both as u64 and s64 (and in fact it will be
2487 	 * identical ranges no matter the signedness). [C, D] treated as s64
2488 	 * will be a range of negative values, while in u64 it will be
2489 	 * non-negative range of values larger than 0x8000000000000000.
2490 	 *
2491 	 * Now, any other range here can't be represented in both u64 and s64
2492 	 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2493 	 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2494 	 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2495 	 * for example. Similarly, valid s64 range [D, A] (going from negative
2496 	 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2497 	 * ranges as u64. Currently reg_state can't represent two segments per
2498 	 * numeric domain, so in such situations we can only derive maximal
2499 	 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2500 	 *
2501 	 * So we use these facts to derive umin/umax from smin/smax and vice
2502 	 * versa only if they stay within the same "half". This is equivalent
2503 	 * to checking sign bit: lower half will have sign bit as zero, upper
2504 	 * half have sign bit 1. Below in code we simplify this by just
2505 	 * casting umin/umax as smin/smax and checking if they form valid
2506 	 * range, and vice versa. Those are equivalent checks.
2507 	 */
2508 	if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2509 		reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2510 		reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2511 	}
2512 	/* If we cannot cross the sign boundary, then signed and unsigned bounds
2513 	 * are the same, so combine.  This works even in the negative case, e.g.
2514 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2515 	 */
2516 	if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2517 		reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2518 		reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2519 	} else {
2520 		/* If the s64 range crosses the sign boundary, then it's split
2521 		 * between the beginning and end of the U64 domain. In that
2522 		 * case, we can derive new bounds if the u64 range overlaps
2523 		 * with only one end of the s64 range.
2524 		 *
2525 		 * In the following example, the u64 range overlaps only with
2526 		 * positive portion of the s64 range.
2527 		 *
2528 		 * 0                                                   U64_MAX
2529 		 * |  [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]              |
2530 		 * |----------------------------|----------------------------|
2531 		 * |xxxxx s64 range xxxxxxxxx]                       [xxxxxxx|
2532 		 * 0                     S64_MAX S64_MIN                    -1
2533 		 *
2534 		 * We can thus derive the following new s64 and u64 ranges.
2535 		 *
2536 		 * 0                                                   U64_MAX
2537 		 * |  [xxxxxx u64 range xxxxx]                               |
2538 		 * |----------------------------|----------------------------|
2539 		 * |  [xxxxxx s64 range xxxxx]                               |
2540 		 * 0                     S64_MAX S64_MIN                    -1
2541 		 *
2542 		 * If they overlap in two places, we can't derive anything
2543 		 * because reg_state can't represent two ranges per numeric
2544 		 * domain.
2545 		 *
2546 		 * 0                                                   U64_MAX
2547 		 * |  [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx]        |
2548 		 * |----------------------------|----------------------------|
2549 		 * |xxxxx s64 range xxxxxxxxx]                    [xxxxxxxxxx|
2550 		 * 0                     S64_MAX S64_MIN                    -1
2551 		 *
2552 		 * The first condition below corresponds to the first diagram
2553 		 * above.
2554 		 */
2555 		if (reg->umax_value < (u64)reg->smin_value) {
2556 			reg->smin_value = (s64)reg->umin_value;
2557 			reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2558 		} else if ((u64)reg->smax_value < reg->umin_value) {
2559 			/* This second condition considers the case where the u64 range
2560 			 * overlaps with the negative portion of the s64 range:
2561 			 *
2562 			 * 0                                                   U64_MAX
2563 			 * |              [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx]  |
2564 			 * |----------------------------|----------------------------|
2565 			 * |xxxxxxxxx]                       [xxxxxxxxxxxx s64 range |
2566 			 * 0                     S64_MAX S64_MIN                    -1
2567 			 */
2568 			reg->smax_value = (s64)reg->umax_value;
2569 			reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2570 		}
2571 	}
2572 }
2573 
__reg_deduce_mixed_bounds(struct bpf_reg_state * reg)2574 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2575 {
2576 	/* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2577 	 * values on both sides of 64-bit range in hope to have tighter range.
2578 	 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2579 	 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2580 	 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2581 	 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2582 	 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2583 	 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2584 	 * We just need to make sure that derived bounds we are intersecting
2585 	 * with are well-formed ranges in respective s64 or u64 domain, just
2586 	 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2587 	 */
2588 	__u64 new_umin, new_umax;
2589 	__s64 new_smin, new_smax;
2590 
2591 	/* u32 -> u64 tightening, it's always well-formed */
2592 	new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2593 	new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2594 	reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2595 	reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2596 	/* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2597 	new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2598 	new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2599 	reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2600 	reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2601 
2602 	/* Here we would like to handle a special case after sign extending load,
2603 	 * when upper bits for a 64-bit range are all 1s or all 0s.
2604 	 *
2605 	 * Upper bits are all 1s when register is in a range:
2606 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2607 	 * Upper bits are all 0s when register is in a range:
2608 	 *   [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2609 	 * Together this forms are continuous range:
2610 	 *   [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2611 	 *
2612 	 * Now, suppose that register range is in fact tighter:
2613 	 *   [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2614 	 * Also suppose that it's 32-bit range is positive,
2615 	 * meaning that lower 32-bits of the full 64-bit register
2616 	 * are in the range:
2617 	 *   [0x0000_0000, 0x7fff_ffff] (W)
2618 	 *
2619 	 * If this happens, then any value in a range:
2620 	 *   [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2621 	 * is smaller than a lowest bound of the range (R):
2622 	 *   0xffff_ffff_8000_0000
2623 	 * which means that upper bits of the full 64-bit register
2624 	 * can't be all 1s, when lower bits are in range (W).
2625 	 *
2626 	 * Note that:
2627 	 *  - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2628 	 *  - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2629 	 * These relations are used in the conditions below.
2630 	 */
2631 	if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2632 		reg->smin_value = reg->s32_min_value;
2633 		reg->smax_value = reg->s32_max_value;
2634 		reg->umin_value = reg->s32_min_value;
2635 		reg->umax_value = reg->s32_max_value;
2636 		reg->var_off = tnum_intersect(reg->var_off,
2637 					      tnum_range(reg->smin_value, reg->smax_value));
2638 	}
2639 }
2640 
__reg_deduce_bounds(struct bpf_reg_state * reg)2641 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2642 {
2643 	__reg32_deduce_bounds(reg);
2644 	__reg64_deduce_bounds(reg);
2645 	__reg_deduce_mixed_bounds(reg);
2646 }
2647 
2648 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2649 static void __reg_bound_offset(struct bpf_reg_state *reg)
2650 {
2651 	struct tnum var64_off = tnum_intersect(reg->var_off,
2652 					       tnum_range(reg->umin_value,
2653 							  reg->umax_value));
2654 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2655 					       tnum_range(reg->u32_min_value,
2656 							  reg->u32_max_value));
2657 
2658 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2659 }
2660 
reg_bounds_sync(struct bpf_reg_state * reg)2661 static void reg_bounds_sync(struct bpf_reg_state *reg)
2662 {
2663 	/* We might have learned new bounds from the var_off. */
2664 	__update_reg_bounds(reg);
2665 	/* We might have learned something about the sign bit. */
2666 	__reg_deduce_bounds(reg);
2667 	__reg_deduce_bounds(reg);
2668 	__reg_deduce_bounds(reg);
2669 	/* We might have learned some bits from the bounds. */
2670 	__reg_bound_offset(reg);
2671 	/* Intersecting with the old var_off might have improved our bounds
2672 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2673 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2674 	 */
2675 	__update_reg_bounds(reg);
2676 }
2677 
reg_bounds_sanity_check(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * ctx)2678 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2679 				   struct bpf_reg_state *reg, const char *ctx)
2680 {
2681 	const char *msg;
2682 
2683 	if (reg->umin_value > reg->umax_value ||
2684 	    reg->smin_value > reg->smax_value ||
2685 	    reg->u32_min_value > reg->u32_max_value ||
2686 	    reg->s32_min_value > reg->s32_max_value) {
2687 		    msg = "range bounds violation";
2688 		    goto out;
2689 	}
2690 
2691 	if (tnum_is_const(reg->var_off)) {
2692 		u64 uval = reg->var_off.value;
2693 		s64 sval = (s64)uval;
2694 
2695 		if (reg->umin_value != uval || reg->umax_value != uval ||
2696 		    reg->smin_value != sval || reg->smax_value != sval) {
2697 			msg = "const tnum out of sync with range bounds";
2698 			goto out;
2699 		}
2700 	}
2701 
2702 	if (tnum_subreg_is_const(reg->var_off)) {
2703 		u32 uval32 = tnum_subreg(reg->var_off).value;
2704 		s32 sval32 = (s32)uval32;
2705 
2706 		if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2707 		    reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2708 			msg = "const subreg tnum out of sync with range bounds";
2709 			goto out;
2710 		}
2711 	}
2712 
2713 	return 0;
2714 out:
2715 	verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2716 		     "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2717 		     ctx, msg, reg->umin_value, reg->umax_value,
2718 		     reg->smin_value, reg->smax_value,
2719 		     reg->u32_min_value, reg->u32_max_value,
2720 		     reg->s32_min_value, reg->s32_max_value,
2721 		     reg->var_off.value, reg->var_off.mask);
2722 	if (env->test_reg_invariants)
2723 		return -EFAULT;
2724 	__mark_reg_unbounded(reg);
2725 	return 0;
2726 }
2727 
__reg32_bound_s64(s32 a)2728 static bool __reg32_bound_s64(s32 a)
2729 {
2730 	return a >= 0 && a <= S32_MAX;
2731 }
2732 
__reg_assign_32_into_64(struct bpf_reg_state * reg)2733 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2734 {
2735 	reg->umin_value = reg->u32_min_value;
2736 	reg->umax_value = reg->u32_max_value;
2737 
2738 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2739 	 * be positive otherwise set to worse case bounds and refine later
2740 	 * from tnum.
2741 	 */
2742 	if (__reg32_bound_s64(reg->s32_min_value) &&
2743 	    __reg32_bound_s64(reg->s32_max_value)) {
2744 		reg->smin_value = reg->s32_min_value;
2745 		reg->smax_value = reg->s32_max_value;
2746 	} else {
2747 		reg->smin_value = 0;
2748 		reg->smax_value = U32_MAX;
2749 	}
2750 }
2751 
2752 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown_imprecise(struct bpf_reg_state * reg)2753 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2754 {
2755 	/*
2756 	 * Clear type, off, and union(map_ptr, range) and
2757 	 * padding between 'type' and union
2758 	 */
2759 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2760 	reg->type = SCALAR_VALUE;
2761 	reg->id = 0;
2762 	reg->ref_obj_id = 0;
2763 	reg->var_off = tnum_unknown;
2764 	reg->frameno = 0;
2765 	reg->precise = false;
2766 	__mark_reg_unbounded(reg);
2767 }
2768 
2769 /* Mark a register as having a completely unknown (scalar) value,
2770  * initialize .precise as true when not bpf capable.
2771  */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2772 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2773 			       struct bpf_reg_state *reg)
2774 {
2775 	__mark_reg_unknown_imprecise(reg);
2776 	reg->precise = !env->bpf_capable;
2777 }
2778 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2779 static void mark_reg_unknown(struct bpf_verifier_env *env,
2780 			     struct bpf_reg_state *regs, u32 regno)
2781 {
2782 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2783 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2784 		/* Something bad happened, let's kill all regs except FP */
2785 		for (regno = 0; regno < BPF_REG_FP; regno++)
2786 			__mark_reg_not_init(env, regs + regno);
2787 		return;
2788 	}
2789 	__mark_reg_unknown(env, regs + regno);
2790 }
2791 
__mark_reg_s32_range(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,s32 s32_min,s32 s32_max)2792 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2793 				struct bpf_reg_state *regs,
2794 				u32 regno,
2795 				s32 s32_min,
2796 				s32 s32_max)
2797 {
2798 	struct bpf_reg_state *reg = regs + regno;
2799 
2800 	reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2801 	reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2802 
2803 	reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2804 	reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2805 
2806 	reg_bounds_sync(reg);
2807 
2808 	return reg_bounds_sanity_check(env, reg, "s32_range");
2809 }
2810 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2811 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2812 				struct bpf_reg_state *reg)
2813 {
2814 	__mark_reg_unknown(env, reg);
2815 	reg->type = NOT_INIT;
2816 }
2817 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2818 static void mark_reg_not_init(struct bpf_verifier_env *env,
2819 			      struct bpf_reg_state *regs, u32 regno)
2820 {
2821 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2822 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2823 		/* Something bad happened, let's kill all regs except FP */
2824 		for (regno = 0; regno < BPF_REG_FP; regno++)
2825 			__mark_reg_not_init(env, regs + regno);
2826 		return;
2827 	}
2828 	__mark_reg_not_init(env, regs + regno);
2829 }
2830 
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)2831 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2832 			   struct bpf_reg_state *regs, u32 regno,
2833 			   enum bpf_reg_type reg_type,
2834 			   struct btf *btf, u32 btf_id,
2835 			   enum bpf_type_flag flag)
2836 {
2837 	switch (reg_type) {
2838 	case SCALAR_VALUE:
2839 		mark_reg_unknown(env, regs, regno);
2840 		return 0;
2841 	case PTR_TO_BTF_ID:
2842 		mark_reg_known_zero(env, regs, regno);
2843 		regs[regno].type = PTR_TO_BTF_ID | flag;
2844 		regs[regno].btf = btf;
2845 		regs[regno].btf_id = btf_id;
2846 		if (type_may_be_null(flag))
2847 			regs[regno].id = ++env->id_gen;
2848 		return 0;
2849 	case PTR_TO_MEM:
2850 		mark_reg_known_zero(env, regs, regno);
2851 		regs[regno].type = PTR_TO_MEM | flag;
2852 		regs[regno].mem_size = 0;
2853 		return 0;
2854 	default:
2855 		verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2856 		return -EFAULT;
2857 	}
2858 }
2859 
2860 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2861 static void init_reg_state(struct bpf_verifier_env *env,
2862 			   struct bpf_func_state *state)
2863 {
2864 	struct bpf_reg_state *regs = state->regs;
2865 	int i;
2866 
2867 	for (i = 0; i < MAX_BPF_REG; i++) {
2868 		mark_reg_not_init(env, regs, i);
2869 		regs[i].subreg_def = DEF_NOT_SUBREG;
2870 	}
2871 
2872 	/* frame pointer */
2873 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2874 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2875 	regs[BPF_REG_FP].frameno = state->frameno;
2876 }
2877 
retval_range(s32 minval,s32 maxval)2878 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2879 {
2880 	return (struct bpf_retval_range){ minval, maxval };
2881 }
2882 
2883 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2884 static void init_func_state(struct bpf_verifier_env *env,
2885 			    struct bpf_func_state *state,
2886 			    int callsite, int frameno, int subprogno)
2887 {
2888 	state->callsite = callsite;
2889 	state->frameno = frameno;
2890 	state->subprogno = subprogno;
2891 	state->callback_ret_range = retval_range(0, 0);
2892 	init_reg_state(env, state);
2893 	mark_verifier_state_scratched(env);
2894 }
2895 
2896 /* 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)2897 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2898 						int insn_idx, int prev_insn_idx,
2899 						int subprog, bool is_sleepable)
2900 {
2901 	struct bpf_verifier_stack_elem *elem;
2902 	struct bpf_func_state *frame;
2903 
2904 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2905 	if (!elem)
2906 		return NULL;
2907 
2908 	elem->insn_idx = insn_idx;
2909 	elem->prev_insn_idx = prev_insn_idx;
2910 	elem->next = env->head;
2911 	elem->log_pos = env->log.end_pos;
2912 	env->head = elem;
2913 	env->stack_size++;
2914 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2915 		verbose(env,
2916 			"The sequence of %d jumps is too complex for async cb.\n",
2917 			env->stack_size);
2918 		return NULL;
2919 	}
2920 	/* Unlike push_stack() do not copy_verifier_state().
2921 	 * The caller state doesn't matter.
2922 	 * This is async callback. It starts in a fresh stack.
2923 	 * Initialize it similar to do_check_common().
2924 	 */
2925 	elem->st.branches = 1;
2926 	elem->st.in_sleepable = is_sleepable;
2927 	frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2928 	if (!frame)
2929 		return NULL;
2930 	init_func_state(env, frame,
2931 			BPF_MAIN_FUNC /* callsite */,
2932 			0 /* frameno within this callchain */,
2933 			subprog /* subprog number within this prog */);
2934 	elem->st.frame[0] = frame;
2935 	return &elem->st;
2936 }
2937 
2938 
2939 enum reg_arg_type {
2940 	SRC_OP,		/* register is used as source operand */
2941 	DST_OP,		/* register is used as destination operand */
2942 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2943 };
2944 
cmp_subprogs(const void * a,const void * b)2945 static int cmp_subprogs(const void *a, const void *b)
2946 {
2947 	return ((struct bpf_subprog_info *)a)->start -
2948 	       ((struct bpf_subprog_info *)b)->start;
2949 }
2950 
2951 /* Find subprogram that contains instruction at 'off' */
bpf_find_containing_subprog(struct bpf_verifier_env * env,int off)2952 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2953 {
2954 	struct bpf_subprog_info *vals = env->subprog_info;
2955 	int l, r, m;
2956 
2957 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2958 		return NULL;
2959 
2960 	l = 0;
2961 	r = env->subprog_cnt - 1;
2962 	while (l < r) {
2963 		m = l + (r - l + 1) / 2;
2964 		if (vals[m].start <= off)
2965 			l = m;
2966 		else
2967 			r = m - 1;
2968 	}
2969 	return &vals[l];
2970 }
2971 
2972 /* Find subprogram that starts exactly at 'off' */
find_subprog(struct bpf_verifier_env * env,int off)2973 static int find_subprog(struct bpf_verifier_env *env, int off)
2974 {
2975 	struct bpf_subprog_info *p;
2976 
2977 	p = bpf_find_containing_subprog(env, off);
2978 	if (!p || p->start != off)
2979 		return -ENOENT;
2980 	return p - env->subprog_info;
2981 }
2982 
add_subprog(struct bpf_verifier_env * env,int off)2983 static int add_subprog(struct bpf_verifier_env *env, int off)
2984 {
2985 	int insn_cnt = env->prog->len;
2986 	int ret;
2987 
2988 	if (off >= insn_cnt || off < 0) {
2989 		verbose(env, "call to invalid destination\n");
2990 		return -EINVAL;
2991 	}
2992 	ret = find_subprog(env, off);
2993 	if (ret >= 0)
2994 		return ret;
2995 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2996 		verbose(env, "too many subprograms\n");
2997 		return -E2BIG;
2998 	}
2999 	/* determine subprog starts. The end is one before the next starts */
3000 	env->subprog_info[env->subprog_cnt++].start = off;
3001 	sort(env->subprog_info, env->subprog_cnt,
3002 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3003 	return env->subprog_cnt - 1;
3004 }
3005 
bpf_find_exception_callback_insn_off(struct bpf_verifier_env * env)3006 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3007 {
3008 	struct bpf_prog_aux *aux = env->prog->aux;
3009 	struct btf *btf = aux->btf;
3010 	const struct btf_type *t;
3011 	u32 main_btf_id, id;
3012 	const char *name;
3013 	int ret, i;
3014 
3015 	/* Non-zero func_info_cnt implies valid btf */
3016 	if (!aux->func_info_cnt)
3017 		return 0;
3018 	main_btf_id = aux->func_info[0].type_id;
3019 
3020 	t = btf_type_by_id(btf, main_btf_id);
3021 	if (!t) {
3022 		verbose(env, "invalid btf id for main subprog in func_info\n");
3023 		return -EINVAL;
3024 	}
3025 
3026 	name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3027 	if (IS_ERR(name)) {
3028 		ret = PTR_ERR(name);
3029 		/* If there is no tag present, there is no exception callback */
3030 		if (ret == -ENOENT)
3031 			ret = 0;
3032 		else if (ret == -EEXIST)
3033 			verbose(env, "multiple exception callback tags for main subprog\n");
3034 		return ret;
3035 	}
3036 
3037 	ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3038 	if (ret < 0) {
3039 		verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3040 		return ret;
3041 	}
3042 	id = ret;
3043 	t = btf_type_by_id(btf, id);
3044 	if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3045 		verbose(env, "exception callback '%s' must have global linkage\n", name);
3046 		return -EINVAL;
3047 	}
3048 	ret = 0;
3049 	for (i = 0; i < aux->func_info_cnt; i++) {
3050 		if (aux->func_info[i].type_id != id)
3051 			continue;
3052 		ret = aux->func_info[i].insn_off;
3053 		/* Further func_info and subprog checks will also happen
3054 		 * later, so assume this is the right insn_off for now.
3055 		 */
3056 		if (!ret) {
3057 			verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3058 			ret = -EINVAL;
3059 		}
3060 	}
3061 	if (!ret) {
3062 		verbose(env, "exception callback type id not found in func_info\n");
3063 		ret = -EINVAL;
3064 	}
3065 	return ret;
3066 }
3067 
3068 #define MAX_KFUNC_DESCS 256
3069 #define MAX_KFUNC_BTFS	256
3070 
3071 struct bpf_kfunc_desc {
3072 	struct btf_func_model func_model;
3073 	u32 func_id;
3074 	s32 imm;
3075 	u16 offset;
3076 	unsigned long addr;
3077 };
3078 
3079 struct bpf_kfunc_btf {
3080 	struct btf *btf;
3081 	struct module *module;
3082 	u16 offset;
3083 };
3084 
3085 struct bpf_kfunc_desc_tab {
3086 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3087 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
3088 	 * available, therefore at the end of verification do_misc_fixups()
3089 	 * sorts this by imm and offset.
3090 	 */
3091 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3092 	u32 nr_descs;
3093 };
3094 
3095 struct bpf_kfunc_btf_tab {
3096 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3097 	u32 nr_descs;
3098 };
3099 
kfunc_desc_cmp_by_id_off(const void * a,const void * b)3100 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3101 {
3102 	const struct bpf_kfunc_desc *d0 = a;
3103 	const struct bpf_kfunc_desc *d1 = b;
3104 
3105 	/* func_id is not greater than BTF_MAX_TYPE */
3106 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3107 }
3108 
kfunc_btf_cmp_by_off(const void * a,const void * b)3109 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3110 {
3111 	const struct bpf_kfunc_btf *d0 = a;
3112 	const struct bpf_kfunc_btf *d1 = b;
3113 
3114 	return d0->offset - d1->offset;
3115 }
3116 
3117 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)3118 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3119 {
3120 	struct bpf_kfunc_desc desc = {
3121 		.func_id = func_id,
3122 		.offset = offset,
3123 	};
3124 	struct bpf_kfunc_desc_tab *tab;
3125 
3126 	tab = prog->aux->kfunc_tab;
3127 	return bsearch(&desc, tab->descs, tab->nr_descs,
3128 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3129 }
3130 
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)3131 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3132 		       u16 btf_fd_idx, u8 **func_addr)
3133 {
3134 	const struct bpf_kfunc_desc *desc;
3135 
3136 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3137 	if (!desc)
3138 		return -EFAULT;
3139 
3140 	*func_addr = (u8 *)desc->addr;
3141 	return 0;
3142 }
3143 
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)3144 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3145 					 s16 offset)
3146 {
3147 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
3148 	struct bpf_kfunc_btf_tab *tab;
3149 	struct bpf_kfunc_btf *b;
3150 	struct module *mod;
3151 	struct btf *btf;
3152 	int btf_fd;
3153 
3154 	tab = env->prog->aux->kfunc_btf_tab;
3155 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3156 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3157 	if (!b) {
3158 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
3159 			verbose(env, "too many different module BTFs\n");
3160 			return ERR_PTR(-E2BIG);
3161 		}
3162 
3163 		if (bpfptr_is_null(env->fd_array)) {
3164 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3165 			return ERR_PTR(-EPROTO);
3166 		}
3167 
3168 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3169 					    offset * sizeof(btf_fd),
3170 					    sizeof(btf_fd)))
3171 			return ERR_PTR(-EFAULT);
3172 
3173 		btf = btf_get_by_fd(btf_fd);
3174 		if (IS_ERR(btf)) {
3175 			verbose(env, "invalid module BTF fd specified\n");
3176 			return btf;
3177 		}
3178 
3179 		if (!btf_is_module(btf)) {
3180 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
3181 			btf_put(btf);
3182 			return ERR_PTR(-EINVAL);
3183 		}
3184 
3185 		mod = btf_try_get_module(btf);
3186 		if (!mod) {
3187 			btf_put(btf);
3188 			return ERR_PTR(-ENXIO);
3189 		}
3190 
3191 		b = &tab->descs[tab->nr_descs++];
3192 		b->btf = btf;
3193 		b->module = mod;
3194 		b->offset = offset;
3195 
3196 		/* sort() reorders entries by value, so b may no longer point
3197 		 * to the right entry after this
3198 		 */
3199 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3200 		     kfunc_btf_cmp_by_off, NULL);
3201 	} else {
3202 		btf = b->btf;
3203 	}
3204 
3205 	return btf;
3206 }
3207 
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)3208 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3209 {
3210 	if (!tab)
3211 		return;
3212 
3213 	while (tab->nr_descs--) {
3214 		module_put(tab->descs[tab->nr_descs].module);
3215 		btf_put(tab->descs[tab->nr_descs].btf);
3216 	}
3217 	kfree(tab);
3218 }
3219 
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)3220 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3221 {
3222 	if (offset) {
3223 		if (offset < 0) {
3224 			/* In the future, this can be allowed to increase limit
3225 			 * of fd index into fd_array, interpreted as u16.
3226 			 */
3227 			verbose(env, "negative offset disallowed for kernel module function call\n");
3228 			return ERR_PTR(-EINVAL);
3229 		}
3230 
3231 		return __find_kfunc_desc_btf(env, offset);
3232 	}
3233 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
3234 }
3235 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)3236 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3237 {
3238 	const struct btf_type *func, *func_proto;
3239 	struct bpf_kfunc_btf_tab *btf_tab;
3240 	struct bpf_kfunc_desc_tab *tab;
3241 	struct bpf_prog_aux *prog_aux;
3242 	struct bpf_kfunc_desc *desc;
3243 	const char *func_name;
3244 	struct btf *desc_btf;
3245 	unsigned long call_imm;
3246 	unsigned long addr;
3247 	int err;
3248 
3249 	prog_aux = env->prog->aux;
3250 	tab = prog_aux->kfunc_tab;
3251 	btf_tab = prog_aux->kfunc_btf_tab;
3252 	if (!tab) {
3253 		if (!btf_vmlinux) {
3254 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3255 			return -ENOTSUPP;
3256 		}
3257 
3258 		if (!env->prog->jit_requested) {
3259 			verbose(env, "JIT is required for calling kernel function\n");
3260 			return -ENOTSUPP;
3261 		}
3262 
3263 		if (!bpf_jit_supports_kfunc_call()) {
3264 			verbose(env, "JIT does not support calling kernel function\n");
3265 			return -ENOTSUPP;
3266 		}
3267 
3268 		if (!env->prog->gpl_compatible) {
3269 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3270 			return -EINVAL;
3271 		}
3272 
3273 		tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3274 		if (!tab)
3275 			return -ENOMEM;
3276 		prog_aux->kfunc_tab = tab;
3277 	}
3278 
3279 	/* func_id == 0 is always invalid, but instead of returning an error, be
3280 	 * conservative and wait until the code elimination pass before returning
3281 	 * error, so that invalid calls that get pruned out can be in BPF programs
3282 	 * loaded from userspace.  It is also required that offset be untouched
3283 	 * for such calls.
3284 	 */
3285 	if (!func_id && !offset)
3286 		return 0;
3287 
3288 	if (!btf_tab && offset) {
3289 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3290 		if (!btf_tab)
3291 			return -ENOMEM;
3292 		prog_aux->kfunc_btf_tab = btf_tab;
3293 	}
3294 
3295 	desc_btf = find_kfunc_desc_btf(env, offset);
3296 	if (IS_ERR(desc_btf)) {
3297 		verbose(env, "failed to find BTF for kernel function\n");
3298 		return PTR_ERR(desc_btf);
3299 	}
3300 
3301 	if (find_kfunc_desc(env->prog, func_id, offset))
3302 		return 0;
3303 
3304 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
3305 		verbose(env, "too many different kernel function calls\n");
3306 		return -E2BIG;
3307 	}
3308 
3309 	func = btf_type_by_id(desc_btf, func_id);
3310 	if (!func || !btf_type_is_func(func)) {
3311 		verbose(env, "kernel btf_id %u is not a function\n",
3312 			func_id);
3313 		return -EINVAL;
3314 	}
3315 	func_proto = btf_type_by_id(desc_btf, func->type);
3316 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3317 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3318 			func_id);
3319 		return -EINVAL;
3320 	}
3321 
3322 	func_name = btf_name_by_offset(desc_btf, func->name_off);
3323 	addr = kallsyms_lookup_name(func_name);
3324 	if (!addr) {
3325 		verbose(env, "cannot find address for kernel function %s\n",
3326 			func_name);
3327 		return -EINVAL;
3328 	}
3329 	specialize_kfunc(env, func_id, offset, &addr);
3330 
3331 	if (bpf_jit_supports_far_kfunc_call()) {
3332 		call_imm = func_id;
3333 	} else {
3334 		call_imm = BPF_CALL_IMM(addr);
3335 		/* Check whether the relative offset overflows desc->imm */
3336 		if ((unsigned long)(s32)call_imm != call_imm) {
3337 			verbose(env, "address of kernel function %s is out of range\n",
3338 				func_name);
3339 			return -EINVAL;
3340 		}
3341 	}
3342 
3343 	if (bpf_dev_bound_kfunc_id(func_id)) {
3344 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3345 		if (err)
3346 			return err;
3347 	}
3348 
3349 	desc = &tab->descs[tab->nr_descs++];
3350 	desc->func_id = func_id;
3351 	desc->imm = call_imm;
3352 	desc->offset = offset;
3353 	desc->addr = addr;
3354 	err = btf_distill_func_proto(&env->log, desc_btf,
3355 				     func_proto, func_name,
3356 				     &desc->func_model);
3357 	if (!err)
3358 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3359 		     kfunc_desc_cmp_by_id_off, NULL);
3360 	return err;
3361 }
3362 
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)3363 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3364 {
3365 	const struct bpf_kfunc_desc *d0 = a;
3366 	const struct bpf_kfunc_desc *d1 = b;
3367 
3368 	if (d0->imm != d1->imm)
3369 		return d0->imm < d1->imm ? -1 : 1;
3370 	if (d0->offset != d1->offset)
3371 		return d0->offset < d1->offset ? -1 : 1;
3372 	return 0;
3373 }
3374 
sort_kfunc_descs_by_imm_off(struct bpf_prog * prog)3375 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3376 {
3377 	struct bpf_kfunc_desc_tab *tab;
3378 
3379 	tab = prog->aux->kfunc_tab;
3380 	if (!tab)
3381 		return;
3382 
3383 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3384 	     kfunc_desc_cmp_by_imm_off, NULL);
3385 }
3386 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)3387 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3388 {
3389 	return !!prog->aux->kfunc_tab;
3390 }
3391 
3392 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)3393 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3394 			 const struct bpf_insn *insn)
3395 {
3396 	const struct bpf_kfunc_desc desc = {
3397 		.imm = insn->imm,
3398 		.offset = insn->off,
3399 	};
3400 	const struct bpf_kfunc_desc *res;
3401 	struct bpf_kfunc_desc_tab *tab;
3402 
3403 	tab = prog->aux->kfunc_tab;
3404 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3405 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3406 
3407 	return res ? &res->func_model : NULL;
3408 }
3409 
add_kfunc_in_insns(struct bpf_verifier_env * env,struct bpf_insn * insn,int cnt)3410 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3411 			      struct bpf_insn *insn, int cnt)
3412 {
3413 	int i, ret;
3414 
3415 	for (i = 0; i < cnt; i++, insn++) {
3416 		if (bpf_pseudo_kfunc_call(insn)) {
3417 			ret = add_kfunc_call(env, insn->imm, insn->off);
3418 			if (ret < 0)
3419 				return ret;
3420 		}
3421 	}
3422 	return 0;
3423 }
3424 
add_subprog_and_kfunc(struct bpf_verifier_env * env)3425 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3426 {
3427 	struct bpf_subprog_info *subprog = env->subprog_info;
3428 	int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3429 	struct bpf_insn *insn = env->prog->insnsi;
3430 
3431 	/* Add entry function. */
3432 	ret = add_subprog(env, 0);
3433 	if (ret)
3434 		return ret;
3435 
3436 	for (i = 0; i < insn_cnt; i++, insn++) {
3437 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3438 		    !bpf_pseudo_kfunc_call(insn))
3439 			continue;
3440 
3441 		if (!env->bpf_capable) {
3442 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3443 			return -EPERM;
3444 		}
3445 
3446 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3447 			ret = add_subprog(env, i + insn->imm + 1);
3448 		else
3449 			ret = add_kfunc_call(env, insn->imm, insn->off);
3450 
3451 		if (ret < 0)
3452 			return ret;
3453 	}
3454 
3455 	ret = bpf_find_exception_callback_insn_off(env);
3456 	if (ret < 0)
3457 		return ret;
3458 	ex_cb_insn = ret;
3459 
3460 	/* If ex_cb_insn > 0, this means that the main program has a subprog
3461 	 * marked using BTF decl tag to serve as the exception callback.
3462 	 */
3463 	if (ex_cb_insn) {
3464 		ret = add_subprog(env, ex_cb_insn);
3465 		if (ret < 0)
3466 			return ret;
3467 		for (i = 1; i < env->subprog_cnt; i++) {
3468 			if (env->subprog_info[i].start != ex_cb_insn)
3469 				continue;
3470 			env->exception_callback_subprog = i;
3471 			mark_subprog_exc_cb(env, i);
3472 			break;
3473 		}
3474 	}
3475 
3476 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3477 	 * logic. 'subprog_cnt' should not be increased.
3478 	 */
3479 	subprog[env->subprog_cnt].start = insn_cnt;
3480 
3481 	if (env->log.level & BPF_LOG_LEVEL2)
3482 		for (i = 0; i < env->subprog_cnt; i++)
3483 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3484 
3485 	return 0;
3486 }
3487 
check_subprogs(struct bpf_verifier_env * env)3488 static int check_subprogs(struct bpf_verifier_env *env)
3489 {
3490 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3491 	struct bpf_subprog_info *subprog = env->subprog_info;
3492 	struct bpf_insn *insn = env->prog->insnsi;
3493 	int insn_cnt = env->prog->len;
3494 
3495 	/* now check that all jumps are within the same subprog */
3496 	subprog_start = subprog[cur_subprog].start;
3497 	subprog_end = subprog[cur_subprog + 1].start;
3498 	for (i = 0; i < insn_cnt; i++) {
3499 		u8 code = insn[i].code;
3500 
3501 		if (code == (BPF_JMP | BPF_CALL) &&
3502 		    insn[i].src_reg == 0 &&
3503 		    insn[i].imm == BPF_FUNC_tail_call) {
3504 			subprog[cur_subprog].has_tail_call = true;
3505 			subprog[cur_subprog].tail_call_reachable = true;
3506 		}
3507 		if (BPF_CLASS(code) == BPF_LD &&
3508 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3509 			subprog[cur_subprog].has_ld_abs = true;
3510 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3511 			goto next;
3512 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3513 			goto next;
3514 		off = i + bpf_jmp_offset(&insn[i]) + 1;
3515 		if (off < subprog_start || off >= subprog_end) {
3516 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3517 			return -EINVAL;
3518 		}
3519 next:
3520 		if (i == subprog_end - 1) {
3521 			/* to avoid fall-through from one subprog into another
3522 			 * the last insn of the subprog should be either exit
3523 			 * or unconditional jump back or bpf_throw call
3524 			 */
3525 			if (code != (BPF_JMP | BPF_EXIT) &&
3526 			    code != (BPF_JMP32 | BPF_JA) &&
3527 			    code != (BPF_JMP | BPF_JA)) {
3528 				verbose(env, "last insn is not an exit or jmp\n");
3529 				return -EINVAL;
3530 			}
3531 			subprog_start = subprog_end;
3532 			cur_subprog++;
3533 			if (cur_subprog < env->subprog_cnt)
3534 				subprog_end = subprog[cur_subprog + 1].start;
3535 		}
3536 	}
3537 	return 0;
3538 }
3539 
mark_stack_slot_obj_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3540 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3541 				    int spi, int nr_slots)
3542 {
3543 	int err, i;
3544 
3545 	for (i = 0; i < nr_slots; i++) {
3546 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3547 		if (err)
3548 			return err;
3549 		mark_stack_slot_scratched(env, spi - i);
3550 	}
3551 	return 0;
3552 }
3553 
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3554 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3555 {
3556 	int spi;
3557 
3558 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3559 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3560 	 * check_kfunc_call.
3561 	 */
3562 	if (reg->type == CONST_PTR_TO_DYNPTR)
3563 		return 0;
3564 	spi = dynptr_get_spi(env, reg);
3565 	if (spi < 0)
3566 		return spi;
3567 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3568 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3569 	 * read.
3570 	 */
3571 	return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3572 }
3573 
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3574 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3575 			  int spi, int nr_slots)
3576 {
3577 	return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3578 }
3579 
mark_irq_flag_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3580 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3581 {
3582 	int spi;
3583 
3584 	spi = irq_flag_get_spi(env, reg);
3585 	if (spi < 0)
3586 		return spi;
3587 	return mark_stack_slot_obj_read(env, reg, spi, 1);
3588 }
3589 
3590 /* This function is supposed to be used by the following 32-bit optimization
3591  * code only. It returns TRUE if the source or destination register operates
3592  * on 64-bit, otherwise return FALSE.
3593  */
is_reg64(struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3594 static bool is_reg64(struct bpf_insn *insn,
3595 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3596 {
3597 	u8 code, class, op;
3598 
3599 	code = insn->code;
3600 	class = BPF_CLASS(code);
3601 	op = BPF_OP(code);
3602 	if (class == BPF_JMP) {
3603 		/* BPF_EXIT for "main" will reach here. Return TRUE
3604 		 * conservatively.
3605 		 */
3606 		if (op == BPF_EXIT)
3607 			return true;
3608 		if (op == BPF_CALL) {
3609 			/* BPF to BPF call will reach here because of marking
3610 			 * caller saved clobber with DST_OP_NO_MARK for which we
3611 			 * don't care the register def because they are anyway
3612 			 * marked as NOT_INIT already.
3613 			 */
3614 			if (insn->src_reg == BPF_PSEUDO_CALL)
3615 				return false;
3616 			/* Helper call will reach here because of arg type
3617 			 * check, conservatively return TRUE.
3618 			 */
3619 			if (t == SRC_OP)
3620 				return true;
3621 
3622 			return false;
3623 		}
3624 	}
3625 
3626 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3627 		return false;
3628 
3629 	if (class == BPF_ALU64 || class == BPF_JMP ||
3630 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3631 		return true;
3632 
3633 	if (class == BPF_ALU || class == BPF_JMP32)
3634 		return false;
3635 
3636 	if (class == BPF_LDX) {
3637 		if (t != SRC_OP)
3638 			return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3639 		/* LDX source must be ptr. */
3640 		return true;
3641 	}
3642 
3643 	if (class == BPF_STX) {
3644 		/* BPF_STX (including atomic variants) has one or more source
3645 		 * operands, one of which is a ptr. Check whether the caller is
3646 		 * asking about it.
3647 		 */
3648 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3649 			return true;
3650 		return BPF_SIZE(code) == BPF_DW;
3651 	}
3652 
3653 	if (class == BPF_LD) {
3654 		u8 mode = BPF_MODE(code);
3655 
3656 		/* LD_IMM64 */
3657 		if (mode == BPF_IMM)
3658 			return true;
3659 
3660 		/* Both LD_IND and LD_ABS return 32-bit data. */
3661 		if (t != SRC_OP)
3662 			return  false;
3663 
3664 		/* Implicit ctx ptr. */
3665 		if (regno == BPF_REG_6)
3666 			return true;
3667 
3668 		/* Explicit source could be any width. */
3669 		return true;
3670 	}
3671 
3672 	if (class == BPF_ST)
3673 		/* The only source register for BPF_ST is a ptr. */
3674 		return true;
3675 
3676 	/* Conservatively return true at default. */
3677 	return true;
3678 }
3679 
3680 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3681 static int insn_def_regno(const struct bpf_insn *insn)
3682 {
3683 	switch (BPF_CLASS(insn->code)) {
3684 	case BPF_JMP:
3685 	case BPF_JMP32:
3686 	case BPF_ST:
3687 		return -1;
3688 	case BPF_STX:
3689 		if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3690 		    BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3691 			if (insn->imm == BPF_CMPXCHG)
3692 				return BPF_REG_0;
3693 			else if (insn->imm == BPF_LOAD_ACQ)
3694 				return insn->dst_reg;
3695 			else if (insn->imm & BPF_FETCH)
3696 				return insn->src_reg;
3697 		}
3698 		return -1;
3699 	default:
3700 		return insn->dst_reg;
3701 	}
3702 }
3703 
3704 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_insn * insn)3705 static bool insn_has_def32(struct bpf_insn *insn)
3706 {
3707 	int dst_reg = insn_def_regno(insn);
3708 
3709 	if (dst_reg == -1)
3710 		return false;
3711 
3712 	return !is_reg64(insn, dst_reg, NULL, DST_OP);
3713 }
3714 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3715 static void mark_insn_zext(struct bpf_verifier_env *env,
3716 			   struct bpf_reg_state *reg)
3717 {
3718 	s32 def_idx = reg->subreg_def;
3719 
3720 	if (def_idx == DEF_NOT_SUBREG)
3721 		return;
3722 
3723 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3724 	/* The dst will be zero extended, so won't be sub-register anymore. */
3725 	reg->subreg_def = DEF_NOT_SUBREG;
3726 }
3727 
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3728 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3729 			   enum reg_arg_type t)
3730 {
3731 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3732 	struct bpf_reg_state *reg;
3733 	bool rw64;
3734 
3735 	if (regno >= MAX_BPF_REG) {
3736 		verbose(env, "R%d is invalid\n", regno);
3737 		return -EINVAL;
3738 	}
3739 
3740 	mark_reg_scratched(env, regno);
3741 
3742 	reg = &regs[regno];
3743 	rw64 = is_reg64(insn, regno, reg, t);
3744 	if (t == SRC_OP) {
3745 		/* check whether register used as source operand can be read */
3746 		if (reg->type == NOT_INIT) {
3747 			verbose(env, "R%d !read_ok\n", regno);
3748 			return -EACCES;
3749 		}
3750 		/* We don't need to worry about FP liveness because it's read-only */
3751 		if (regno == BPF_REG_FP)
3752 			return 0;
3753 
3754 		if (rw64)
3755 			mark_insn_zext(env, reg);
3756 
3757 		return 0;
3758 	} else {
3759 		/* check whether register used as dest operand can be written to */
3760 		if (regno == BPF_REG_FP) {
3761 			verbose(env, "frame pointer is read only\n");
3762 			return -EACCES;
3763 		}
3764 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3765 		if (t == DST_OP)
3766 			mark_reg_unknown(env, regs, regno);
3767 	}
3768 	return 0;
3769 }
3770 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3771 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3772 			 enum reg_arg_type t)
3773 {
3774 	struct bpf_verifier_state *vstate = env->cur_state;
3775 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3776 
3777 	return __check_reg_arg(env, state->regs, regno, t);
3778 }
3779 
insn_stack_access_flags(int frameno,int spi)3780 static int insn_stack_access_flags(int frameno, int spi)
3781 {
3782 	return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3783 }
3784 
insn_stack_access_spi(int insn_flags)3785 static int insn_stack_access_spi(int insn_flags)
3786 {
3787 	return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3788 }
3789 
insn_stack_access_frameno(int insn_flags)3790 static int insn_stack_access_frameno(int insn_flags)
3791 {
3792 	return insn_flags & INSN_F_FRAMENO_MASK;
3793 }
3794 
mark_jmp_point(struct bpf_verifier_env * env,int idx)3795 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3796 {
3797 	env->insn_aux_data[idx].jmp_point = true;
3798 }
3799 
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3800 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3801 {
3802 	return env->insn_aux_data[insn_idx].jmp_point;
3803 }
3804 
3805 #define LR_FRAMENO_BITS	3
3806 #define LR_SPI_BITS	6
3807 #define LR_ENTRY_BITS	(LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3808 #define LR_SIZE_BITS	4
3809 #define LR_FRAMENO_MASK	((1ull << LR_FRAMENO_BITS) - 1)
3810 #define LR_SPI_MASK	((1ull << LR_SPI_BITS)     - 1)
3811 #define LR_SIZE_MASK	((1ull << LR_SIZE_BITS)    - 1)
3812 #define LR_SPI_OFF	LR_FRAMENO_BITS
3813 #define LR_IS_REG_OFF	(LR_SPI_BITS + LR_FRAMENO_BITS)
3814 #define LINKED_REGS_MAX	6
3815 
3816 struct linked_reg {
3817 	u8 frameno;
3818 	union {
3819 		u8 spi;
3820 		u8 regno;
3821 	};
3822 	bool is_reg;
3823 };
3824 
3825 struct linked_regs {
3826 	int cnt;
3827 	struct linked_reg entries[LINKED_REGS_MAX];
3828 };
3829 
linked_regs_push(struct linked_regs * s)3830 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3831 {
3832 	if (s->cnt < LINKED_REGS_MAX)
3833 		return &s->entries[s->cnt++];
3834 
3835 	return NULL;
3836 }
3837 
3838 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3839  * number of elements currently in stack.
3840  * Pack one history entry for linked registers as 10 bits in the following format:
3841  * - 3-bits frameno
3842  * - 6-bits spi_or_reg
3843  * - 1-bit  is_reg
3844  */
linked_regs_pack(struct linked_regs * s)3845 static u64 linked_regs_pack(struct linked_regs *s)
3846 {
3847 	u64 val = 0;
3848 	int i;
3849 
3850 	for (i = 0; i < s->cnt; ++i) {
3851 		struct linked_reg *e = &s->entries[i];
3852 		u64 tmp = 0;
3853 
3854 		tmp |= e->frameno;
3855 		tmp |= e->spi << LR_SPI_OFF;
3856 		tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3857 
3858 		val <<= LR_ENTRY_BITS;
3859 		val |= tmp;
3860 	}
3861 	val <<= LR_SIZE_BITS;
3862 	val |= s->cnt;
3863 	return val;
3864 }
3865 
linked_regs_unpack(u64 val,struct linked_regs * s)3866 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3867 {
3868 	int i;
3869 
3870 	s->cnt = val & LR_SIZE_MASK;
3871 	val >>= LR_SIZE_BITS;
3872 
3873 	for (i = 0; i < s->cnt; ++i) {
3874 		struct linked_reg *e = &s->entries[i];
3875 
3876 		e->frameno =  val & LR_FRAMENO_MASK;
3877 		e->spi     = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3878 		e->is_reg  = (val >> LR_IS_REG_OFF) & 0x1;
3879 		val >>= LR_ENTRY_BITS;
3880 	}
3881 }
3882 
3883 /* 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)3884 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3885 			    int insn_flags, u64 linked_regs)
3886 {
3887 	u32 cnt = cur->jmp_history_cnt;
3888 	struct bpf_jmp_history_entry *p;
3889 	size_t alloc_size;
3890 
3891 	/* combine instruction flags if we already recorded this instruction */
3892 	if (env->cur_hist_ent) {
3893 		/* atomic instructions push insn_flags twice, for READ and
3894 		 * WRITE sides, but they should agree on stack slot
3895 		 */
3896 		verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3897 				(env->cur_hist_ent->flags & insn_flags) != insn_flags,
3898 				env, "insn history: insn_idx %d cur flags %x new flags %x",
3899 				env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3900 		env->cur_hist_ent->flags |= insn_flags;
3901 		verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3902 				"insn history: insn_idx %d linked_regs: %#llx",
3903 				env->insn_idx, env->cur_hist_ent->linked_regs);
3904 		env->cur_hist_ent->linked_regs = linked_regs;
3905 		return 0;
3906 	}
3907 
3908 	cnt++;
3909 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3910 	p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3911 	if (!p)
3912 		return -ENOMEM;
3913 	cur->jmp_history = p;
3914 
3915 	p = &cur->jmp_history[cnt - 1];
3916 	p->idx = env->insn_idx;
3917 	p->prev_idx = env->prev_insn_idx;
3918 	p->flags = insn_flags;
3919 	p->linked_regs = linked_regs;
3920 	cur->jmp_history_cnt = cnt;
3921 	env->cur_hist_ent = p;
3922 
3923 	return 0;
3924 }
3925 
get_jmp_hist_entry(struct bpf_verifier_state * st,u32 hist_end,int insn_idx)3926 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3927 						        u32 hist_end, int insn_idx)
3928 {
3929 	if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3930 		return &st->jmp_history[hist_end - 1];
3931 	return NULL;
3932 }
3933 
3934 /* Backtrack one insn at a time. If idx is not at the top of recorded
3935  * history then previous instruction came from straight line execution.
3936  * Return -ENOENT if we exhausted all instructions within given state.
3937  *
3938  * It's legal to have a bit of a looping with the same starting and ending
3939  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3940  * instruction index is the same as state's first_idx doesn't mean we are
3941  * done. If there is still some jump history left, we should keep going. We
3942  * need to take into account that we might have a jump history between given
3943  * state's parent and itself, due to checkpointing. In this case, we'll have
3944  * history entry recording a jump from last instruction of parent state and
3945  * first instruction of given state.
3946  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)3947 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3948 			     u32 *history)
3949 {
3950 	u32 cnt = *history;
3951 
3952 	if (i == st->first_insn_idx) {
3953 		if (cnt == 0)
3954 			return -ENOENT;
3955 		if (cnt == 1 && st->jmp_history[0].idx == i)
3956 			return -ENOENT;
3957 	}
3958 
3959 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3960 		i = st->jmp_history[cnt - 1].prev_idx;
3961 		(*history)--;
3962 	} else {
3963 		i--;
3964 	}
3965 	return i;
3966 }
3967 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)3968 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3969 {
3970 	const struct btf_type *func;
3971 	struct btf *desc_btf;
3972 
3973 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3974 		return NULL;
3975 
3976 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3977 	if (IS_ERR(desc_btf))
3978 		return "<error>";
3979 
3980 	func = btf_type_by_id(desc_btf, insn->imm);
3981 	return btf_name_by_offset(desc_btf, func->name_off);
3982 }
3983 
verbose_insn(struct bpf_verifier_env * env,struct bpf_insn * insn)3984 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
3985 {
3986 	const struct bpf_insn_cbs cbs = {
3987 		.cb_call	= disasm_kfunc_name,
3988 		.cb_print	= verbose,
3989 		.private_data	= env,
3990 	};
3991 
3992 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3993 }
3994 
bt_init(struct backtrack_state * bt,u32 frame)3995 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3996 {
3997 	bt->frame = frame;
3998 }
3999 
bt_reset(struct backtrack_state * bt)4000 static inline void bt_reset(struct backtrack_state *bt)
4001 {
4002 	struct bpf_verifier_env *env = bt->env;
4003 
4004 	memset(bt, 0, sizeof(*bt));
4005 	bt->env = env;
4006 }
4007 
bt_empty(struct backtrack_state * bt)4008 static inline u32 bt_empty(struct backtrack_state *bt)
4009 {
4010 	u64 mask = 0;
4011 	int i;
4012 
4013 	for (i = 0; i <= bt->frame; i++)
4014 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
4015 
4016 	return mask == 0;
4017 }
4018 
bt_subprog_enter(struct backtrack_state * bt)4019 static inline int bt_subprog_enter(struct backtrack_state *bt)
4020 {
4021 	if (bt->frame == MAX_CALL_FRAMES - 1) {
4022 		verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4023 		return -EFAULT;
4024 	}
4025 	bt->frame++;
4026 	return 0;
4027 }
4028 
bt_subprog_exit(struct backtrack_state * bt)4029 static inline int bt_subprog_exit(struct backtrack_state *bt)
4030 {
4031 	if (bt->frame == 0) {
4032 		verifier_bug(bt->env, "subprog exit from frame 0");
4033 		return -EFAULT;
4034 	}
4035 	bt->frame--;
4036 	return 0;
4037 }
4038 
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)4039 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4040 {
4041 	bt->reg_masks[frame] |= 1 << reg;
4042 }
4043 
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)4044 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4045 {
4046 	bt->reg_masks[frame] &= ~(1 << reg);
4047 }
4048 
bt_set_reg(struct backtrack_state * bt,u32 reg)4049 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4050 {
4051 	bt_set_frame_reg(bt, bt->frame, reg);
4052 }
4053 
bt_clear_reg(struct backtrack_state * bt,u32 reg)4054 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4055 {
4056 	bt_clear_frame_reg(bt, bt->frame, reg);
4057 }
4058 
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)4059 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4060 {
4061 	bt->stack_masks[frame] |= 1ull << slot;
4062 }
4063 
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)4064 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4065 {
4066 	bt->stack_masks[frame] &= ~(1ull << slot);
4067 }
4068 
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)4069 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4070 {
4071 	return bt->reg_masks[frame];
4072 }
4073 
bt_reg_mask(struct backtrack_state * bt)4074 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4075 {
4076 	return bt->reg_masks[bt->frame];
4077 }
4078 
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)4079 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4080 {
4081 	return bt->stack_masks[frame];
4082 }
4083 
bt_stack_mask(struct backtrack_state * bt)4084 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4085 {
4086 	return bt->stack_masks[bt->frame];
4087 }
4088 
bt_is_reg_set(struct backtrack_state * bt,u32 reg)4089 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4090 {
4091 	return bt->reg_masks[bt->frame] & (1 << reg);
4092 }
4093 
bt_is_frame_reg_set(struct backtrack_state * bt,u32 frame,u32 reg)4094 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4095 {
4096 	return bt->reg_masks[frame] & (1 << reg);
4097 }
4098 
bt_is_frame_slot_set(struct backtrack_state * bt,u32 frame,u32 slot)4099 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4100 {
4101 	return bt->stack_masks[frame] & (1ull << slot);
4102 }
4103 
4104 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)4105 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4106 {
4107 	DECLARE_BITMAP(mask, 64);
4108 	bool first = true;
4109 	int i, n;
4110 
4111 	buf[0] = '\0';
4112 
4113 	bitmap_from_u64(mask, reg_mask);
4114 	for_each_set_bit(i, mask, 32) {
4115 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4116 		first = false;
4117 		buf += n;
4118 		buf_sz -= n;
4119 		if (buf_sz < 0)
4120 			break;
4121 	}
4122 }
4123 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
bpf_fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)4124 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4125 {
4126 	DECLARE_BITMAP(mask, 64);
4127 	bool first = true;
4128 	int i, n;
4129 
4130 	buf[0] = '\0';
4131 
4132 	bitmap_from_u64(mask, stack_mask);
4133 	for_each_set_bit(i, mask, 64) {
4134 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4135 		first = false;
4136 		buf += n;
4137 		buf_sz -= n;
4138 		if (buf_sz < 0)
4139 			break;
4140 	}
4141 }
4142 
4143 /* If any register R in hist->linked_regs is marked as precise in bt,
4144  * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4145  */
bt_sync_linked_regs(struct backtrack_state * bt,struct bpf_jmp_history_entry * hist)4146 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4147 {
4148 	struct linked_regs linked_regs;
4149 	bool some_precise = false;
4150 	int i;
4151 
4152 	if (!hist || hist->linked_regs == 0)
4153 		return;
4154 
4155 	linked_regs_unpack(hist->linked_regs, &linked_regs);
4156 	for (i = 0; i < linked_regs.cnt; ++i) {
4157 		struct linked_reg *e = &linked_regs.entries[i];
4158 
4159 		if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4160 		    (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4161 			some_precise = true;
4162 			break;
4163 		}
4164 	}
4165 
4166 	if (!some_precise)
4167 		return;
4168 
4169 	for (i = 0; i < linked_regs.cnt; ++i) {
4170 		struct linked_reg *e = &linked_regs.entries[i];
4171 
4172 		if (e->is_reg)
4173 			bt_set_frame_reg(bt, e->frameno, e->regno);
4174 		else
4175 			bt_set_frame_slot(bt, e->frameno, e->spi);
4176 	}
4177 }
4178 
4179 /* For given verifier state backtrack_insn() is called from the last insn to
4180  * the first insn. Its purpose is to compute a bitmask of registers and
4181  * stack slots that needs precision in the parent verifier state.
4182  *
4183  * @idx is an index of the instruction we are currently processing;
4184  * @subseq_idx is an index of the subsequent instruction that:
4185  *   - *would be* executed next, if jump history is viewed in forward order;
4186  *   - *was* processed previously during backtracking.
4187  */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct bpf_jmp_history_entry * hist,struct backtrack_state * bt)4188 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4189 			  struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4190 {
4191 	struct bpf_insn *insn = env->prog->insnsi + idx;
4192 	u8 class = BPF_CLASS(insn->code);
4193 	u8 opcode = BPF_OP(insn->code);
4194 	u8 mode = BPF_MODE(insn->code);
4195 	u32 dreg = insn->dst_reg;
4196 	u32 sreg = insn->src_reg;
4197 	u32 spi, i, fr;
4198 
4199 	if (insn->code == 0)
4200 		return 0;
4201 	if (env->log.level & BPF_LOG_LEVEL2) {
4202 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4203 		verbose(env, "mark_precise: frame%d: regs=%s ",
4204 			bt->frame, env->tmp_str_buf);
4205 		bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4206 		verbose(env, "stack=%s before ", env->tmp_str_buf);
4207 		verbose(env, "%d: ", idx);
4208 		verbose_insn(env, insn);
4209 	}
4210 
4211 	/* If there is a history record that some registers gained range at this insn,
4212 	 * propagate precision marks to those registers, so that bt_is_reg_set()
4213 	 * accounts for these registers.
4214 	 */
4215 	bt_sync_linked_regs(bt, hist);
4216 
4217 	if (class == BPF_ALU || class == BPF_ALU64) {
4218 		if (!bt_is_reg_set(bt, dreg))
4219 			return 0;
4220 		if (opcode == BPF_END || opcode == BPF_NEG) {
4221 			/* sreg is reserved and unused
4222 			 * dreg still need precision before this insn
4223 			 */
4224 			return 0;
4225 		} else if (opcode == BPF_MOV) {
4226 			if (BPF_SRC(insn->code) == BPF_X) {
4227 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
4228 				 * dreg needs precision after this insn
4229 				 * sreg needs precision before this insn
4230 				 */
4231 				bt_clear_reg(bt, dreg);
4232 				if (sreg != BPF_REG_FP)
4233 					bt_set_reg(bt, sreg);
4234 			} else {
4235 				/* dreg = K
4236 				 * dreg needs precision after this insn.
4237 				 * Corresponding register is already marked
4238 				 * as precise=true in this verifier state.
4239 				 * No further markings in parent are necessary
4240 				 */
4241 				bt_clear_reg(bt, dreg);
4242 			}
4243 		} else {
4244 			if (BPF_SRC(insn->code) == BPF_X) {
4245 				/* dreg += sreg
4246 				 * both dreg and sreg need precision
4247 				 * before this insn
4248 				 */
4249 				if (sreg != BPF_REG_FP)
4250 					bt_set_reg(bt, sreg);
4251 			} /* else dreg += K
4252 			   * dreg still needs precision before this insn
4253 			   */
4254 		}
4255 	} else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4256 		if (!bt_is_reg_set(bt, dreg))
4257 			return 0;
4258 		bt_clear_reg(bt, dreg);
4259 
4260 		/* scalars can only be spilled into stack w/o losing precision.
4261 		 * Load from any other memory can be zero extended.
4262 		 * The desire to keep that precision is already indicated
4263 		 * by 'precise' mark in corresponding register of this state.
4264 		 * No further tracking necessary.
4265 		 */
4266 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4267 			return 0;
4268 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
4269 		 * that [fp - off] slot contains scalar that needs to be
4270 		 * tracked with precision
4271 		 */
4272 		spi = insn_stack_access_spi(hist->flags);
4273 		fr = insn_stack_access_frameno(hist->flags);
4274 		bt_set_frame_slot(bt, fr, spi);
4275 	} else if (class == BPF_STX || class == BPF_ST) {
4276 		if (bt_is_reg_set(bt, dreg))
4277 			/* stx & st shouldn't be using _scalar_ dst_reg
4278 			 * to access memory. It means backtracking
4279 			 * encountered a case of pointer subtraction.
4280 			 */
4281 			return -ENOTSUPP;
4282 		/* scalars can only be spilled into stack */
4283 		if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4284 			return 0;
4285 		spi = insn_stack_access_spi(hist->flags);
4286 		fr = insn_stack_access_frameno(hist->flags);
4287 		if (!bt_is_frame_slot_set(bt, fr, spi))
4288 			return 0;
4289 		bt_clear_frame_slot(bt, fr, spi);
4290 		if (class == BPF_STX)
4291 			bt_set_reg(bt, sreg);
4292 	} else if (class == BPF_JMP || class == BPF_JMP32) {
4293 		if (bpf_pseudo_call(insn)) {
4294 			int subprog_insn_idx, subprog;
4295 
4296 			subprog_insn_idx = idx + insn->imm + 1;
4297 			subprog = find_subprog(env, subprog_insn_idx);
4298 			if (subprog < 0)
4299 				return -EFAULT;
4300 
4301 			if (subprog_is_global(env, subprog)) {
4302 				/* check that jump history doesn't have any
4303 				 * extra instructions from subprog; the next
4304 				 * instruction after call to global subprog
4305 				 * should be literally next instruction in
4306 				 * caller program
4307 				 */
4308 				verifier_bug_if(idx + 1 != subseq_idx, env,
4309 						"extra insn from subprog");
4310 				/* r1-r5 are invalidated after subprog call,
4311 				 * so for global func call it shouldn't be set
4312 				 * anymore
4313 				 */
4314 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4315 					verifier_bug(env, "global subprog unexpected regs %x",
4316 						     bt_reg_mask(bt));
4317 					return -EFAULT;
4318 				}
4319 				/* global subprog always sets R0 */
4320 				bt_clear_reg(bt, BPF_REG_0);
4321 				return 0;
4322 			} else {
4323 				/* static subprog call instruction, which
4324 				 * means that we are exiting current subprog,
4325 				 * so only r1-r5 could be still requested as
4326 				 * precise, r0 and r6-r10 or any stack slot in
4327 				 * the current frame should be zero by now
4328 				 */
4329 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4330 					verifier_bug(env, "static subprog unexpected regs %x",
4331 						     bt_reg_mask(bt));
4332 					return -EFAULT;
4333 				}
4334 				/* we are now tracking register spills correctly,
4335 				 * so any instance of leftover slots is a bug
4336 				 */
4337 				if (bt_stack_mask(bt) != 0) {
4338 					verifier_bug(env,
4339 						     "static subprog leftover stack slots %llx",
4340 						     bt_stack_mask(bt));
4341 					return -EFAULT;
4342 				}
4343 				/* propagate r1-r5 to the caller */
4344 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4345 					if (bt_is_reg_set(bt, i)) {
4346 						bt_clear_reg(bt, i);
4347 						bt_set_frame_reg(bt, bt->frame - 1, i);
4348 					}
4349 				}
4350 				if (bt_subprog_exit(bt))
4351 					return -EFAULT;
4352 				return 0;
4353 			}
4354 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4355 			/* exit from callback subprog to callback-calling helper or
4356 			 * kfunc call. Use idx/subseq_idx check to discern it from
4357 			 * straight line code backtracking.
4358 			 * Unlike the subprog call handling above, we shouldn't
4359 			 * propagate precision of r1-r5 (if any requested), as they are
4360 			 * not actually arguments passed directly to callback subprogs
4361 			 */
4362 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4363 				verifier_bug(env, "callback unexpected regs %x",
4364 					     bt_reg_mask(bt));
4365 				return -EFAULT;
4366 			}
4367 			if (bt_stack_mask(bt) != 0) {
4368 				verifier_bug(env, "callback leftover stack slots %llx",
4369 					     bt_stack_mask(bt));
4370 				return -EFAULT;
4371 			}
4372 			/* clear r1-r5 in callback subprog's mask */
4373 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4374 				bt_clear_reg(bt, i);
4375 			if (bt_subprog_exit(bt))
4376 				return -EFAULT;
4377 			return 0;
4378 		} else if (opcode == BPF_CALL) {
4379 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
4380 			 * catch this error later. Make backtracking conservative
4381 			 * with ENOTSUPP.
4382 			 */
4383 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4384 				return -ENOTSUPP;
4385 			/* regular helper call sets R0 */
4386 			bt_clear_reg(bt, BPF_REG_0);
4387 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4388 				/* if backtracking was looking for registers R1-R5
4389 				 * they should have been found already.
4390 				 */
4391 				verifier_bug(env, "backtracking call unexpected regs %x",
4392 					     bt_reg_mask(bt));
4393 				return -EFAULT;
4394 			}
4395 		} else if (opcode == BPF_EXIT) {
4396 			bool r0_precise;
4397 
4398 			/* Backtracking to a nested function call, 'idx' is a part of
4399 			 * the inner frame 'subseq_idx' is a part of the outer frame.
4400 			 * In case of a regular function call, instructions giving
4401 			 * precision to registers R1-R5 should have been found already.
4402 			 * In case of a callback, it is ok to have R1-R5 marked for
4403 			 * backtracking, as these registers are set by the function
4404 			 * invoking callback.
4405 			 */
4406 			if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4407 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4408 					bt_clear_reg(bt, i);
4409 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4410 				verifier_bug(env, "backtracking exit unexpected regs %x",
4411 					     bt_reg_mask(bt));
4412 				return -EFAULT;
4413 			}
4414 
4415 			/* BPF_EXIT in subprog or callback always returns
4416 			 * right after the call instruction, so by checking
4417 			 * whether the instruction at subseq_idx-1 is subprog
4418 			 * call or not we can distinguish actual exit from
4419 			 * *subprog* from exit from *callback*. In the former
4420 			 * case, we need to propagate r0 precision, if
4421 			 * necessary. In the former we never do that.
4422 			 */
4423 			r0_precise = subseq_idx - 1 >= 0 &&
4424 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4425 				     bt_is_reg_set(bt, BPF_REG_0);
4426 
4427 			bt_clear_reg(bt, BPF_REG_0);
4428 			if (bt_subprog_enter(bt))
4429 				return -EFAULT;
4430 
4431 			if (r0_precise)
4432 				bt_set_reg(bt, BPF_REG_0);
4433 			/* r6-r9 and stack slots will stay set in caller frame
4434 			 * bitmasks until we return back from callee(s)
4435 			 */
4436 			return 0;
4437 		} else if (BPF_SRC(insn->code) == BPF_X) {
4438 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4439 				return 0;
4440 			/* dreg <cond> sreg
4441 			 * Both dreg and sreg need precision before
4442 			 * this insn. If only sreg was marked precise
4443 			 * before it would be equally necessary to
4444 			 * propagate it to dreg.
4445 			 */
4446 			if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4447 				bt_set_reg(bt, sreg);
4448 			if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4449 				bt_set_reg(bt, dreg);
4450 		} else if (BPF_SRC(insn->code) == BPF_K) {
4451 			 /* dreg <cond> K
4452 			  * Only dreg still needs precision before
4453 			  * this insn, so for the K-based conditional
4454 			  * there is nothing new to be marked.
4455 			  */
4456 		}
4457 	} else if (class == BPF_LD) {
4458 		if (!bt_is_reg_set(bt, dreg))
4459 			return 0;
4460 		bt_clear_reg(bt, dreg);
4461 		/* It's ld_imm64 or ld_abs or ld_ind.
4462 		 * For ld_imm64 no further tracking of precision
4463 		 * into parent is necessary
4464 		 */
4465 		if (mode == BPF_IND || mode == BPF_ABS)
4466 			/* to be analyzed */
4467 			return -ENOTSUPP;
4468 	}
4469 	/* Propagate precision marks to linked registers, to account for
4470 	 * registers marked as precise in this function.
4471 	 */
4472 	bt_sync_linked_regs(bt, hist);
4473 	return 0;
4474 }
4475 
4476 /* the scalar precision tracking algorithm:
4477  * . at the start all registers have precise=false.
4478  * . scalar ranges are tracked as normal through alu and jmp insns.
4479  * . once precise value of the scalar register is used in:
4480  *   .  ptr + scalar alu
4481  *   . if (scalar cond K|scalar)
4482  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
4483  *   backtrack through the verifier states and mark all registers and
4484  *   stack slots with spilled constants that these scalar registers
4485  *   should be precise.
4486  * . during state pruning two registers (or spilled stack slots)
4487  *   are equivalent if both are not precise.
4488  *
4489  * Note the verifier cannot simply walk register parentage chain,
4490  * since many different registers and stack slots could have been
4491  * used to compute single precise scalar.
4492  *
4493  * The approach of starting with precise=true for all registers and then
4494  * backtrack to mark a register as not precise when the verifier detects
4495  * that program doesn't care about specific value (e.g., when helper
4496  * takes register as ARG_ANYTHING parameter) is not safe.
4497  *
4498  * It's ok to walk single parentage chain of the verifier states.
4499  * It's possible that this backtracking will go all the way till 1st insn.
4500  * All other branches will be explored for needing precision later.
4501  *
4502  * The backtracking needs to deal with cases like:
4503  *   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)
4504  * r9 -= r8
4505  * r5 = r9
4506  * if r5 > 0x79f goto pc+7
4507  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4508  * r5 += 1
4509  * ...
4510  * call bpf_perf_event_output#25
4511  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4512  *
4513  * and this case:
4514  * r6 = 1
4515  * call foo // uses callee's r6 inside to compute r0
4516  * r0 += r6
4517  * if r0 == 0 goto
4518  *
4519  * to track above reg_mask/stack_mask needs to be independent for each frame.
4520  *
4521  * Also if parent's curframe > frame where backtracking started,
4522  * the verifier need to mark registers in both frames, otherwise callees
4523  * may incorrectly prune callers. This is similar to
4524  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4525  *
4526  * For now backtracking falls back into conservative marking.
4527  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4528 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4529 				     struct bpf_verifier_state *st)
4530 {
4531 	struct bpf_func_state *func;
4532 	struct bpf_reg_state *reg;
4533 	int i, j;
4534 
4535 	if (env->log.level & BPF_LOG_LEVEL2) {
4536 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4537 			st->curframe);
4538 	}
4539 
4540 	/* big hammer: mark all scalars precise in this path.
4541 	 * pop_stack may still get !precise scalars.
4542 	 * We also skip current state and go straight to first parent state,
4543 	 * because precision markings in current non-checkpointed state are
4544 	 * not needed. See why in the comment in __mark_chain_precision below.
4545 	 */
4546 	for (st = st->parent; st; st = st->parent) {
4547 		for (i = 0; i <= st->curframe; i++) {
4548 			func = st->frame[i];
4549 			for (j = 0; j < BPF_REG_FP; j++) {
4550 				reg = &func->regs[j];
4551 				if (reg->type != SCALAR_VALUE || reg->precise)
4552 					continue;
4553 				reg->precise = true;
4554 				if (env->log.level & BPF_LOG_LEVEL2) {
4555 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4556 						i, j);
4557 				}
4558 			}
4559 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4560 				if (!is_spilled_reg(&func->stack[j]))
4561 					continue;
4562 				reg = &func->stack[j].spilled_ptr;
4563 				if (reg->type != SCALAR_VALUE || reg->precise)
4564 					continue;
4565 				reg->precise = true;
4566 				if (env->log.level & BPF_LOG_LEVEL2) {
4567 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4568 						i, -(j + 1) * 8);
4569 				}
4570 			}
4571 		}
4572 	}
4573 }
4574 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4575 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4576 {
4577 	struct bpf_func_state *func;
4578 	struct bpf_reg_state *reg;
4579 	int i, j;
4580 
4581 	for (i = 0; i <= st->curframe; i++) {
4582 		func = st->frame[i];
4583 		for (j = 0; j < BPF_REG_FP; j++) {
4584 			reg = &func->regs[j];
4585 			if (reg->type != SCALAR_VALUE)
4586 				continue;
4587 			reg->precise = false;
4588 		}
4589 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4590 			if (!is_spilled_reg(&func->stack[j]))
4591 				continue;
4592 			reg = &func->stack[j].spilled_ptr;
4593 			if (reg->type != SCALAR_VALUE)
4594 				continue;
4595 			reg->precise = false;
4596 		}
4597 	}
4598 }
4599 
4600 /*
4601  * __mark_chain_precision() backtracks BPF program instruction sequence and
4602  * chain of verifier states making sure that register *regno* (if regno >= 0)
4603  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4604  * SCALARS, as well as any other registers and slots that contribute to
4605  * a tracked state of given registers/stack slots, depending on specific BPF
4606  * assembly instructions (see backtrack_insns() for exact instruction handling
4607  * logic). This backtracking relies on recorded jmp_history and is able to
4608  * traverse entire chain of parent states. This process ends only when all the
4609  * necessary registers/slots and their transitive dependencies are marked as
4610  * precise.
4611  *
4612  * One important and subtle aspect is that precise marks *do not matter* in
4613  * the currently verified state (current state). It is important to understand
4614  * why this is the case.
4615  *
4616  * First, note that current state is the state that is not yet "checkpointed",
4617  * i.e., it is not yet put into env->explored_states, and it has no children
4618  * states as well. It's ephemeral, and can end up either a) being discarded if
4619  * compatible explored state is found at some point or BPF_EXIT instruction is
4620  * reached or b) checkpointed and put into env->explored_states, branching out
4621  * into one or more children states.
4622  *
4623  * In the former case, precise markings in current state are completely
4624  * ignored by state comparison code (see regsafe() for details). Only
4625  * checkpointed ("old") state precise markings are important, and if old
4626  * state's register/slot is precise, regsafe() assumes current state's
4627  * register/slot as precise and checks value ranges exactly and precisely. If
4628  * states turn out to be compatible, current state's necessary precise
4629  * markings and any required parent states' precise markings are enforced
4630  * after the fact with propagate_precision() logic, after the fact. But it's
4631  * important to realize that in this case, even after marking current state
4632  * registers/slots as precise, we immediately discard current state. So what
4633  * actually matters is any of the precise markings propagated into current
4634  * state's parent states, which are always checkpointed (due to b) case above).
4635  * As such, for scenario a) it doesn't matter if current state has precise
4636  * markings set or not.
4637  *
4638  * Now, for the scenario b), checkpointing and forking into child(ren)
4639  * state(s). Note that before current state gets to checkpointing step, any
4640  * processed instruction always assumes precise SCALAR register/slot
4641  * knowledge: if precise value or range is useful to prune jump branch, BPF
4642  * verifier takes this opportunity enthusiastically. Similarly, when
4643  * register's value is used to calculate offset or memory address, exact
4644  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4645  * what we mentioned above about state comparison ignoring precise markings
4646  * during state comparison, BPF verifier ignores and also assumes precise
4647  * markings *at will* during instruction verification process. But as verifier
4648  * assumes precision, it also propagates any precision dependencies across
4649  * parent states, which are not yet finalized, so can be further restricted
4650  * based on new knowledge gained from restrictions enforced by their children
4651  * states. This is so that once those parent states are finalized, i.e., when
4652  * they have no more active children state, state comparison logic in
4653  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4654  * required for correctness.
4655  *
4656  * To build a bit more intuition, note also that once a state is checkpointed,
4657  * the path we took to get to that state is not important. This is crucial
4658  * property for state pruning. When state is checkpointed and finalized at
4659  * some instruction index, it can be correctly and safely used to "short
4660  * circuit" any *compatible* state that reaches exactly the same instruction
4661  * index. I.e., if we jumped to that instruction from a completely different
4662  * code path than original finalized state was derived from, it doesn't
4663  * matter, current state can be discarded because from that instruction
4664  * forward having a compatible state will ensure we will safely reach the
4665  * exit. States describe preconditions for further exploration, but completely
4666  * forget the history of how we got here.
4667  *
4668  * This also means that even if we needed precise SCALAR range to get to
4669  * finalized state, but from that point forward *that same* SCALAR register is
4670  * never used in a precise context (i.e., it's precise value is not needed for
4671  * correctness), it's correct and safe to mark such register as "imprecise"
4672  * (i.e., precise marking set to false). This is what we rely on when we do
4673  * not set precise marking in current state. If no child state requires
4674  * precision for any given SCALAR register, it's safe to dictate that it can
4675  * be imprecise. If any child state does require this register to be precise,
4676  * we'll mark it precise later retroactively during precise markings
4677  * propagation from child state to parent states.
4678  *
4679  * Skipping precise marking setting in current state is a mild version of
4680  * relying on the above observation. But we can utilize this property even
4681  * more aggressively by proactively forgetting any precise marking in the
4682  * current state (which we inherited from the parent state), right before we
4683  * checkpoint it and branch off into new child state. This is done by
4684  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4685  * finalized states which help in short circuiting more future states.
4686  */
__mark_chain_precision(struct bpf_verifier_env * env,struct bpf_verifier_state * starting_state,int regno,bool * changed)4687 static int __mark_chain_precision(struct bpf_verifier_env *env,
4688 				  struct bpf_verifier_state *starting_state,
4689 				  int regno,
4690 				  bool *changed)
4691 {
4692 	struct bpf_verifier_state *st = starting_state;
4693 	struct backtrack_state *bt = &env->bt;
4694 	int first_idx = st->first_insn_idx;
4695 	int last_idx = starting_state->insn_idx;
4696 	int subseq_idx = -1;
4697 	struct bpf_func_state *func;
4698 	bool tmp, skip_first = true;
4699 	struct bpf_reg_state *reg;
4700 	int i, fr, err;
4701 
4702 	if (!env->bpf_capable)
4703 		return 0;
4704 
4705 	changed = changed ?: &tmp;
4706 	/* set frame number from which we are starting to backtrack */
4707 	bt_init(bt, starting_state->curframe);
4708 
4709 	/* Do sanity checks against current state of register and/or stack
4710 	 * slot, but don't set precise flag in current state, as precision
4711 	 * tracking in the current state is unnecessary.
4712 	 */
4713 	func = st->frame[bt->frame];
4714 	if (regno >= 0) {
4715 		reg = &func->regs[regno];
4716 		if (reg->type != SCALAR_VALUE) {
4717 			verifier_bug(env, "backtracking misuse");
4718 			return -EFAULT;
4719 		}
4720 		bt_set_reg(bt, regno);
4721 	}
4722 
4723 	if (bt_empty(bt))
4724 		return 0;
4725 
4726 	for (;;) {
4727 		DECLARE_BITMAP(mask, 64);
4728 		u32 history = st->jmp_history_cnt;
4729 		struct bpf_jmp_history_entry *hist;
4730 
4731 		if (env->log.level & BPF_LOG_LEVEL2) {
4732 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4733 				bt->frame, last_idx, first_idx, subseq_idx);
4734 		}
4735 
4736 		if (last_idx < 0) {
4737 			/* we are at the entry into subprog, which
4738 			 * is expected for global funcs, but only if
4739 			 * requested precise registers are R1-R5
4740 			 * (which are global func's input arguments)
4741 			 */
4742 			if (st->curframe == 0 &&
4743 			    st->frame[0]->subprogno > 0 &&
4744 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4745 			    bt_stack_mask(bt) == 0 &&
4746 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4747 				bitmap_from_u64(mask, bt_reg_mask(bt));
4748 				for_each_set_bit(i, mask, 32) {
4749 					reg = &st->frame[0]->regs[i];
4750 					bt_clear_reg(bt, i);
4751 					if (reg->type == SCALAR_VALUE) {
4752 						reg->precise = true;
4753 						*changed = true;
4754 					}
4755 				}
4756 				return 0;
4757 			}
4758 
4759 			verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4760 				     st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4761 			return -EFAULT;
4762 		}
4763 
4764 		for (i = last_idx;;) {
4765 			if (skip_first) {
4766 				err = 0;
4767 				skip_first = false;
4768 			} else {
4769 				hist = get_jmp_hist_entry(st, history, i);
4770 				err = backtrack_insn(env, i, subseq_idx, hist, bt);
4771 			}
4772 			if (err == -ENOTSUPP) {
4773 				mark_all_scalars_precise(env, starting_state);
4774 				bt_reset(bt);
4775 				return 0;
4776 			} else if (err) {
4777 				return err;
4778 			}
4779 			if (bt_empty(bt))
4780 				/* Found assignment(s) into tracked register in this state.
4781 				 * Since this state is already marked, just return.
4782 				 * Nothing to be tracked further in the parent state.
4783 				 */
4784 				return 0;
4785 			subseq_idx = i;
4786 			i = get_prev_insn_idx(st, i, &history);
4787 			if (i == -ENOENT)
4788 				break;
4789 			if (i >= env->prog->len) {
4790 				/* This can happen if backtracking reached insn 0
4791 				 * and there are still reg_mask or stack_mask
4792 				 * to backtrack.
4793 				 * It means the backtracking missed the spot where
4794 				 * particular register was initialized with a constant.
4795 				 */
4796 				verifier_bug(env, "backtracking idx %d", i);
4797 				return -EFAULT;
4798 			}
4799 		}
4800 		st = st->parent;
4801 		if (!st)
4802 			break;
4803 
4804 		for (fr = bt->frame; fr >= 0; fr--) {
4805 			func = st->frame[fr];
4806 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4807 			for_each_set_bit(i, mask, 32) {
4808 				reg = &func->regs[i];
4809 				if (reg->type != SCALAR_VALUE) {
4810 					bt_clear_frame_reg(bt, fr, i);
4811 					continue;
4812 				}
4813 				if (reg->precise) {
4814 					bt_clear_frame_reg(bt, fr, i);
4815 				} else {
4816 					reg->precise = true;
4817 					*changed = true;
4818 				}
4819 			}
4820 
4821 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4822 			for_each_set_bit(i, mask, 64) {
4823 				if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4824 						    env, "stack slot %d, total slots %d",
4825 						    i, func->allocated_stack / BPF_REG_SIZE))
4826 					return -EFAULT;
4827 
4828 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4829 					bt_clear_frame_slot(bt, fr, i);
4830 					continue;
4831 				}
4832 				reg = &func->stack[i].spilled_ptr;
4833 				if (reg->precise) {
4834 					bt_clear_frame_slot(bt, fr, i);
4835 				} else {
4836 					reg->precise = true;
4837 					*changed = true;
4838 				}
4839 			}
4840 			if (env->log.level & BPF_LOG_LEVEL2) {
4841 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4842 					     bt_frame_reg_mask(bt, fr));
4843 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4844 					fr, env->tmp_str_buf);
4845 				bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4846 					       bt_frame_stack_mask(bt, fr));
4847 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4848 				print_verifier_state(env, st, fr, true);
4849 			}
4850 		}
4851 
4852 		if (bt_empty(bt))
4853 			return 0;
4854 
4855 		subseq_idx = first_idx;
4856 		last_idx = st->last_insn_idx;
4857 		first_idx = st->first_insn_idx;
4858 	}
4859 
4860 	/* if we still have requested precise regs or slots, we missed
4861 	 * something (e.g., stack access through non-r10 register), so
4862 	 * fallback to marking all precise
4863 	 */
4864 	if (!bt_empty(bt)) {
4865 		mark_all_scalars_precise(env, starting_state);
4866 		bt_reset(bt);
4867 	}
4868 
4869 	return 0;
4870 }
4871 
mark_chain_precision(struct bpf_verifier_env * env,int regno)4872 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4873 {
4874 	return __mark_chain_precision(env, env->cur_state, regno, NULL);
4875 }
4876 
4877 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4878  * desired reg and stack masks across all relevant frames
4879  */
mark_chain_precision_batch(struct bpf_verifier_env * env,struct bpf_verifier_state * starting_state)4880 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4881 				      struct bpf_verifier_state *starting_state)
4882 {
4883 	return __mark_chain_precision(env, starting_state, -1, NULL);
4884 }
4885 
is_spillable_regtype(enum bpf_reg_type type)4886 static bool is_spillable_regtype(enum bpf_reg_type type)
4887 {
4888 	switch (base_type(type)) {
4889 	case PTR_TO_MAP_VALUE:
4890 	case PTR_TO_STACK:
4891 	case PTR_TO_CTX:
4892 	case PTR_TO_PACKET:
4893 	case PTR_TO_PACKET_META:
4894 	case PTR_TO_PACKET_END:
4895 	case PTR_TO_FLOW_KEYS:
4896 	case CONST_PTR_TO_MAP:
4897 	case PTR_TO_SOCKET:
4898 	case PTR_TO_SOCK_COMMON:
4899 	case PTR_TO_TCP_SOCK:
4900 	case PTR_TO_XDP_SOCK:
4901 	case PTR_TO_BTF_ID:
4902 	case PTR_TO_BUF:
4903 	case PTR_TO_MEM:
4904 	case PTR_TO_FUNC:
4905 	case PTR_TO_MAP_KEY:
4906 	case PTR_TO_ARENA:
4907 		return true;
4908 	default:
4909 		return false;
4910 	}
4911 }
4912 
4913 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4914 static bool register_is_null(struct bpf_reg_state *reg)
4915 {
4916 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4917 }
4918 
4919 /* check if register is a constant scalar value */
is_reg_const(struct bpf_reg_state * reg,bool subreg32)4920 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4921 {
4922 	return reg->type == SCALAR_VALUE &&
4923 	       tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4924 }
4925 
4926 /* assuming is_reg_const() is true, return constant value of a register */
reg_const_value(struct bpf_reg_state * reg,bool subreg32)4927 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4928 {
4929 	return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4930 }
4931 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)4932 static bool __is_pointer_value(bool allow_ptr_leaks,
4933 			       const struct bpf_reg_state *reg)
4934 {
4935 	if (allow_ptr_leaks)
4936 		return false;
4937 
4938 	return reg->type != SCALAR_VALUE;
4939 }
4940 
assign_scalar_id_before_mov(struct bpf_verifier_env * env,struct bpf_reg_state * src_reg)4941 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4942 					struct bpf_reg_state *src_reg)
4943 {
4944 	if (src_reg->type != SCALAR_VALUE)
4945 		return;
4946 
4947 	if (src_reg->id & BPF_ADD_CONST) {
4948 		/*
4949 		 * The verifier is processing rX = rY insn and
4950 		 * rY->id has special linked register already.
4951 		 * Cleared it, since multiple rX += const are not supported.
4952 		 */
4953 		src_reg->id = 0;
4954 		src_reg->off = 0;
4955 	}
4956 
4957 	if (!src_reg->id && !tnum_is_const(src_reg->var_off))
4958 		/* Ensure that src_reg has a valid ID that will be copied to
4959 		 * dst_reg and then will be used by sync_linked_regs() to
4960 		 * propagate min/max range.
4961 		 */
4962 		src_reg->id = ++env->id_gen;
4963 }
4964 
4965 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)4966 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4967 {
4968 	*dst = *src;
4969 }
4970 
save_register_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)4971 static void save_register_state(struct bpf_verifier_env *env,
4972 				struct bpf_func_state *state,
4973 				int spi, struct bpf_reg_state *reg,
4974 				int size)
4975 {
4976 	int i;
4977 
4978 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4979 
4980 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4981 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4982 
4983 	/* size < 8 bytes spill */
4984 	for (; i; i--)
4985 		mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
4986 }
4987 
is_bpf_st_mem(struct bpf_insn * insn)4988 static bool is_bpf_st_mem(struct bpf_insn *insn)
4989 {
4990 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4991 }
4992 
get_reg_width(struct bpf_reg_state * reg)4993 static int get_reg_width(struct bpf_reg_state *reg)
4994 {
4995 	return fls64(reg->umax_value);
4996 }
4997 
4998 /* 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)4999 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5000 					  struct bpf_func_state *state, int insn_idx, int off)
5001 {
5002 	struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5003 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
5004 	int i;
5005 
5006 	if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5007 		return;
5008 	/* access to the region [max_stack_depth .. fastcall_stack_off)
5009 	 * from something that is not a part of the fastcall pattern,
5010 	 * disable fastcall rewrites for current subprogram by setting
5011 	 * fastcall_stack_off to a value smaller than any possible offset.
5012 	 */
5013 	subprog->fastcall_stack_off = S16_MIN;
5014 	/* reset fastcall aux flags within subprogram,
5015 	 * happens at most once per subprogram
5016 	 */
5017 	for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5018 		aux[i].fastcall_spills_num = 0;
5019 		aux[i].fastcall_pattern = 0;
5020 	}
5021 }
5022 
5023 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5024  * stack boundary and alignment are checked in check_mem_access()
5025  */
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)5026 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5027 				       /* stack frame we're writing to */
5028 				       struct bpf_func_state *state,
5029 				       int off, int size, int value_regno,
5030 				       int insn_idx)
5031 {
5032 	struct bpf_func_state *cur; /* state of the current function */
5033 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5034 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5035 	struct bpf_reg_state *reg = NULL;
5036 	int insn_flags = insn_stack_access_flags(state->frameno, spi);
5037 
5038 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5039 	 * so it's aligned access and [off, off + size) are within stack limits
5040 	 */
5041 	if (!env->allow_ptr_leaks &&
5042 	    is_spilled_reg(&state->stack[spi]) &&
5043 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
5044 	    size != BPF_REG_SIZE) {
5045 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
5046 		return -EACCES;
5047 	}
5048 
5049 	cur = env->cur_state->frame[env->cur_state->curframe];
5050 	if (value_regno >= 0)
5051 		reg = &cur->regs[value_regno];
5052 	if (!env->bypass_spec_v4) {
5053 		bool sanitize = reg && is_spillable_regtype(reg->type);
5054 
5055 		for (i = 0; i < size; i++) {
5056 			u8 type = state->stack[spi].slot_type[i];
5057 
5058 			if (type != STACK_MISC && type != STACK_ZERO) {
5059 				sanitize = true;
5060 				break;
5061 			}
5062 		}
5063 
5064 		if (sanitize)
5065 			env->insn_aux_data[insn_idx].nospec_result = true;
5066 	}
5067 
5068 	err = destroy_if_dynptr_stack_slot(env, state, spi);
5069 	if (err)
5070 		return err;
5071 
5072 	if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5073 		/* only mark the slot as written if all 8 bytes were written
5074 		 * otherwise read propagation may incorrectly stop too soon
5075 		 * when stack slots are partially written.
5076 		 * This heuristic means that read propagation will be
5077 		 * conservative, since it will add reg_live_read marks
5078 		 * to stack slots all the way to first state when programs
5079 		 * writes+reads less than 8 bytes
5080 		 */
5081 		bpf_mark_stack_write(env, state->frameno, BIT(spi));
5082 	}
5083 
5084 	check_fastcall_stack_contract(env, state, insn_idx, off);
5085 	mark_stack_slot_scratched(env, spi);
5086 	if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5087 		bool reg_value_fits;
5088 
5089 		reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5090 		/* Make sure that reg had an ID to build a relation on spill. */
5091 		if (reg_value_fits)
5092 			assign_scalar_id_before_mov(env, reg);
5093 		save_register_state(env, state, spi, reg, size);
5094 		/* Break the relation on a narrowing spill. */
5095 		if (!reg_value_fits)
5096 			state->stack[spi].spilled_ptr.id = 0;
5097 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5098 		   env->bpf_capable) {
5099 		struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5100 
5101 		memset(tmp_reg, 0, sizeof(*tmp_reg));
5102 		__mark_reg_known(tmp_reg, insn->imm);
5103 		tmp_reg->type = SCALAR_VALUE;
5104 		save_register_state(env, state, spi, tmp_reg, size);
5105 	} else if (reg && is_spillable_regtype(reg->type)) {
5106 		/* register containing pointer is being spilled into stack */
5107 		if (size != BPF_REG_SIZE) {
5108 			verbose_linfo(env, insn_idx, "; ");
5109 			verbose(env, "invalid size of register spill\n");
5110 			return -EACCES;
5111 		}
5112 		if (state != cur && reg->type == PTR_TO_STACK) {
5113 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5114 			return -EINVAL;
5115 		}
5116 		save_register_state(env, state, spi, reg, size);
5117 	} else {
5118 		u8 type = STACK_MISC;
5119 
5120 		/* regular write of data into stack destroys any spilled ptr */
5121 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5122 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5123 		if (is_stack_slot_special(&state->stack[spi]))
5124 			for (i = 0; i < BPF_REG_SIZE; i++)
5125 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5126 
5127 		/* when we zero initialize stack slots mark them as such */
5128 		if ((reg && register_is_null(reg)) ||
5129 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5130 			/* STACK_ZERO case happened because register spill
5131 			 * wasn't properly aligned at the stack slot boundary,
5132 			 * so it's not a register spill anymore; force
5133 			 * originating register to be precise to make
5134 			 * STACK_ZERO correct for subsequent states
5135 			 */
5136 			err = mark_chain_precision(env, value_regno);
5137 			if (err)
5138 				return err;
5139 			type = STACK_ZERO;
5140 		}
5141 
5142 		/* Mark slots affected by this stack write. */
5143 		for (i = 0; i < size; i++)
5144 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5145 		insn_flags = 0; /* not a register spill */
5146 	}
5147 
5148 	if (insn_flags)
5149 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5150 	return 0;
5151 }
5152 
5153 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5154  * known to contain a variable offset.
5155  * This function checks whether the write is permitted and conservatively
5156  * tracks the effects of the write, considering that each stack slot in the
5157  * dynamic range is potentially written to.
5158  *
5159  * 'off' includes 'regno->off'.
5160  * 'value_regno' can be -1, meaning that an unknown value is being written to
5161  * the stack.
5162  *
5163  * Spilled pointers in range are not marked as written because we don't know
5164  * what's going to be actually written. This means that read propagation for
5165  * future reads cannot be terminated by this write.
5166  *
5167  * For privileged programs, uninitialized stack slots are considered
5168  * initialized by this write (even though we don't know exactly what offsets
5169  * are going to be written to). The idea is that we don't want the verifier to
5170  * reject future reads that access slots written to through variable offsets.
5171  */
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)5172 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5173 				     /* func where register points to */
5174 				     struct bpf_func_state *state,
5175 				     int ptr_regno, int off, int size,
5176 				     int value_regno, int insn_idx)
5177 {
5178 	struct bpf_func_state *cur; /* state of the current function */
5179 	int min_off, max_off;
5180 	int i, err;
5181 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5182 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5183 	bool writing_zero = false;
5184 	/* set if the fact that we're writing a zero is used to let any
5185 	 * stack slots remain STACK_ZERO
5186 	 */
5187 	bool zero_used = false;
5188 
5189 	cur = env->cur_state->frame[env->cur_state->curframe];
5190 	ptr_reg = &cur->regs[ptr_regno];
5191 	min_off = ptr_reg->smin_value + off;
5192 	max_off = ptr_reg->smax_value + off + size;
5193 	if (value_regno >= 0)
5194 		value_reg = &cur->regs[value_regno];
5195 	if ((value_reg && register_is_null(value_reg)) ||
5196 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5197 		writing_zero = true;
5198 
5199 	for (i = min_off; i < max_off; i++) {
5200 		int spi;
5201 
5202 		spi = __get_spi(i);
5203 		err = destroy_if_dynptr_stack_slot(env, state, spi);
5204 		if (err)
5205 			return err;
5206 	}
5207 
5208 	check_fastcall_stack_contract(env, state, insn_idx, min_off);
5209 	/* Variable offset writes destroy any spilled pointers in range. */
5210 	for (i = min_off; i < max_off; i++) {
5211 		u8 new_type, *stype;
5212 		int slot, spi;
5213 
5214 		slot = -i - 1;
5215 		spi = slot / BPF_REG_SIZE;
5216 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5217 		mark_stack_slot_scratched(env, spi);
5218 
5219 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5220 			/* Reject the write if range we may write to has not
5221 			 * been initialized beforehand. If we didn't reject
5222 			 * here, the ptr status would be erased below (even
5223 			 * though not all slots are actually overwritten),
5224 			 * possibly opening the door to leaks.
5225 			 *
5226 			 * We do however catch STACK_INVALID case below, and
5227 			 * only allow reading possibly uninitialized memory
5228 			 * later for CAP_PERFMON, as the write may not happen to
5229 			 * that slot.
5230 			 */
5231 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5232 				insn_idx, i);
5233 			return -EINVAL;
5234 		}
5235 
5236 		/* If writing_zero and the spi slot contains a spill of value 0,
5237 		 * maintain the spill type.
5238 		 */
5239 		if (writing_zero && *stype == STACK_SPILL &&
5240 		    is_spilled_scalar_reg(&state->stack[spi])) {
5241 			struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5242 
5243 			if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5244 				zero_used = true;
5245 				continue;
5246 			}
5247 		}
5248 
5249 		/* Erase all other spilled pointers. */
5250 		state->stack[spi].spilled_ptr.type = NOT_INIT;
5251 
5252 		/* Update the slot type. */
5253 		new_type = STACK_MISC;
5254 		if (writing_zero && *stype == STACK_ZERO) {
5255 			new_type = STACK_ZERO;
5256 			zero_used = true;
5257 		}
5258 		/* If the slot is STACK_INVALID, we check whether it's OK to
5259 		 * pretend that it will be initialized by this write. The slot
5260 		 * might not actually be written to, and so if we mark it as
5261 		 * initialized future reads might leak uninitialized memory.
5262 		 * For privileged programs, we will accept such reads to slots
5263 		 * that may or may not be written because, if we're reject
5264 		 * them, the error would be too confusing.
5265 		 */
5266 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5267 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5268 					insn_idx, i);
5269 			return -EINVAL;
5270 		}
5271 		*stype = new_type;
5272 	}
5273 	if (zero_used) {
5274 		/* backtracking doesn't work for STACK_ZERO yet. */
5275 		err = mark_chain_precision(env, value_regno);
5276 		if (err)
5277 			return err;
5278 	}
5279 	return 0;
5280 }
5281 
5282 /* When register 'dst_regno' is assigned some values from stack[min_off,
5283  * max_off), we set the register's type according to the types of the
5284  * respective stack slots. If all the stack values are known to be zeros, then
5285  * so is the destination reg. Otherwise, the register is considered to be
5286  * SCALAR. This function does not deal with register filling; the caller must
5287  * ensure that all spilled registers in the stack range have been marked as
5288  * read.
5289  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)5290 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5291 				/* func where src register points to */
5292 				struct bpf_func_state *ptr_state,
5293 				int min_off, int max_off, int dst_regno)
5294 {
5295 	struct bpf_verifier_state *vstate = env->cur_state;
5296 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5297 	int i, slot, spi;
5298 	u8 *stype;
5299 	int zeros = 0;
5300 
5301 	for (i = min_off; i < max_off; i++) {
5302 		slot = -i - 1;
5303 		spi = slot / BPF_REG_SIZE;
5304 		mark_stack_slot_scratched(env, spi);
5305 		stype = ptr_state->stack[spi].slot_type;
5306 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5307 			break;
5308 		zeros++;
5309 	}
5310 	if (zeros == max_off - min_off) {
5311 		/* Any access_size read into register is zero extended,
5312 		 * so the whole register == const_zero.
5313 		 */
5314 		__mark_reg_const_zero(env, &state->regs[dst_regno]);
5315 	} else {
5316 		/* have read misc data from the stack */
5317 		mark_reg_unknown(env, state->regs, dst_regno);
5318 	}
5319 }
5320 
5321 /* Read the stack at 'off' and put the results into the register indicated by
5322  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5323  * spilled reg.
5324  *
5325  * 'dst_regno' can be -1, meaning that the read value is not going to a
5326  * register.
5327  *
5328  * The access is assumed to be within the current stack bounds.
5329  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)5330 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5331 				      /* func where src register points to */
5332 				      struct bpf_func_state *reg_state,
5333 				      int off, int size, int dst_regno)
5334 {
5335 	struct bpf_verifier_state *vstate = env->cur_state;
5336 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5337 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5338 	struct bpf_reg_state *reg;
5339 	u8 *stype, type;
5340 	int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5341 	int err;
5342 
5343 	stype = reg_state->stack[spi].slot_type;
5344 	reg = &reg_state->stack[spi].spilled_ptr;
5345 
5346 	mark_stack_slot_scratched(env, spi);
5347 	check_fastcall_stack_contract(env, state, env->insn_idx, off);
5348 	err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5349 	if (err)
5350 		return err;
5351 
5352 	if (is_spilled_reg(&reg_state->stack[spi])) {
5353 		u8 spill_size = 1;
5354 
5355 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5356 			spill_size++;
5357 
5358 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5359 			if (reg->type != SCALAR_VALUE) {
5360 				verbose_linfo(env, env->insn_idx, "; ");
5361 				verbose(env, "invalid size of register fill\n");
5362 				return -EACCES;
5363 			}
5364 
5365 			if (dst_regno < 0)
5366 				return 0;
5367 
5368 			if (size <= spill_size &&
5369 			    bpf_stack_narrow_access_ok(off, size, spill_size)) {
5370 				/* The earlier check_reg_arg() has decided the
5371 				 * subreg_def for this insn.  Save it first.
5372 				 */
5373 				s32 subreg_def = state->regs[dst_regno].subreg_def;
5374 
5375 				copy_register_state(&state->regs[dst_regno], reg);
5376 				state->regs[dst_regno].subreg_def = subreg_def;
5377 
5378 				/* Break the relation on a narrowing fill.
5379 				 * coerce_reg_to_size will adjust the boundaries.
5380 				 */
5381 				if (get_reg_width(reg) > size * BITS_PER_BYTE)
5382 					state->regs[dst_regno].id = 0;
5383 			} else {
5384 				int spill_cnt = 0, zero_cnt = 0;
5385 
5386 				for (i = 0; i < size; i++) {
5387 					type = stype[(slot - i) % BPF_REG_SIZE];
5388 					if (type == STACK_SPILL) {
5389 						spill_cnt++;
5390 						continue;
5391 					}
5392 					if (type == STACK_MISC)
5393 						continue;
5394 					if (type == STACK_ZERO) {
5395 						zero_cnt++;
5396 						continue;
5397 					}
5398 					if (type == STACK_INVALID && env->allow_uninit_stack)
5399 						continue;
5400 					verbose(env, "invalid read from stack off %d+%d size %d\n",
5401 						off, i, size);
5402 					return -EACCES;
5403 				}
5404 
5405 				if (spill_cnt == size &&
5406 				    tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5407 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5408 					/* this IS register fill, so keep insn_flags */
5409 				} else if (zero_cnt == size) {
5410 					/* similarly to mark_reg_stack_read(), preserve zeroes */
5411 					__mark_reg_const_zero(env, &state->regs[dst_regno]);
5412 					insn_flags = 0; /* not restoring original register state */
5413 				} else {
5414 					mark_reg_unknown(env, state->regs, dst_regno);
5415 					insn_flags = 0; /* not restoring original register state */
5416 				}
5417 			}
5418 		} else if (dst_regno >= 0) {
5419 			/* restore register state from stack */
5420 			copy_register_state(&state->regs[dst_regno], reg);
5421 			/* mark reg as written since spilled pointer state likely
5422 			 * has its liveness marks cleared by is_state_visited()
5423 			 * which resets stack/reg liveness for state transitions
5424 			 */
5425 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5426 			/* If dst_regno==-1, the caller is asking us whether
5427 			 * it is acceptable to use this value as a SCALAR_VALUE
5428 			 * (e.g. for XADD).
5429 			 * We must not allow unprivileged callers to do that
5430 			 * with spilled pointers.
5431 			 */
5432 			verbose(env, "leaking pointer from stack off %d\n",
5433 				off);
5434 			return -EACCES;
5435 		}
5436 	} else {
5437 		for (i = 0; i < size; i++) {
5438 			type = stype[(slot - i) % BPF_REG_SIZE];
5439 			if (type == STACK_MISC)
5440 				continue;
5441 			if (type == STACK_ZERO)
5442 				continue;
5443 			if (type == STACK_INVALID && env->allow_uninit_stack)
5444 				continue;
5445 			verbose(env, "invalid read from stack off %d+%d size %d\n",
5446 				off, i, size);
5447 			return -EACCES;
5448 		}
5449 		if (dst_regno >= 0)
5450 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5451 		insn_flags = 0; /* we are not restoring spilled register */
5452 	}
5453 	if (insn_flags)
5454 		return push_jmp_history(env, env->cur_state, insn_flags, 0);
5455 	return 0;
5456 }
5457 
5458 enum bpf_access_src {
5459 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5460 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
5461 };
5462 
5463 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5464 					 int regno, int off, int access_size,
5465 					 bool zero_size_allowed,
5466 					 enum bpf_access_type type,
5467 					 struct bpf_call_arg_meta *meta);
5468 
reg_state(struct bpf_verifier_env * env,int regno)5469 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5470 {
5471 	return cur_regs(env) + regno;
5472 }
5473 
5474 /* Read the stack at 'ptr_regno + off' and put the result into the register
5475  * 'dst_regno'.
5476  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5477  * but not its variable offset.
5478  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5479  *
5480  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5481  * filling registers (i.e. reads of spilled register cannot be detected when
5482  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5483  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5484  * offset; for a fixed offset check_stack_read_fixed_off should be used
5485  * instead.
5486  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5487 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5488 				    int ptr_regno, int off, int size, int dst_regno)
5489 {
5490 	/* The state of the source register. */
5491 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5492 	struct bpf_func_state *ptr_state = func(env, reg);
5493 	int err;
5494 	int min_off, max_off;
5495 
5496 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5497 	 */
5498 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5499 					    false, BPF_READ, NULL);
5500 	if (err)
5501 		return err;
5502 
5503 	min_off = reg->smin_value + off;
5504 	max_off = reg->smax_value + off;
5505 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5506 	check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5507 	return 0;
5508 }
5509 
5510 /* check_stack_read dispatches to check_stack_read_fixed_off or
5511  * check_stack_read_var_off.
5512  *
5513  * The caller must ensure that the offset falls within the allocated stack
5514  * bounds.
5515  *
5516  * 'dst_regno' is a register which will receive the value from the stack. It
5517  * can be -1, meaning that the read value is not going to a register.
5518  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5519 static int check_stack_read(struct bpf_verifier_env *env,
5520 			    int ptr_regno, int off, int size,
5521 			    int dst_regno)
5522 {
5523 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5524 	struct bpf_func_state *state = func(env, reg);
5525 	int err;
5526 	/* Some accesses are only permitted with a static offset. */
5527 	bool var_off = !tnum_is_const(reg->var_off);
5528 
5529 	/* The offset is required to be static when reads don't go to a
5530 	 * register, in order to not leak pointers (see
5531 	 * check_stack_read_fixed_off).
5532 	 */
5533 	if (dst_regno < 0 && var_off) {
5534 		char tn_buf[48];
5535 
5536 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5537 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5538 			tn_buf, off, size);
5539 		return -EACCES;
5540 	}
5541 	/* Variable offset is prohibited for unprivileged mode for simplicity
5542 	 * since it requires corresponding support in Spectre masking for stack
5543 	 * ALU. See also retrieve_ptr_limit(). The check in
5544 	 * check_stack_access_for_ptr_arithmetic() called by
5545 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5546 	 * with variable offsets, therefore no check is required here. Further,
5547 	 * just checking it here would be insufficient as speculative stack
5548 	 * writes could still lead to unsafe speculative behaviour.
5549 	 */
5550 	if (!var_off) {
5551 		off += reg->var_off.value;
5552 		err = check_stack_read_fixed_off(env, state, off, size,
5553 						 dst_regno);
5554 	} else {
5555 		/* Variable offset stack reads need more conservative handling
5556 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5557 		 * branch.
5558 		 */
5559 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5560 					       dst_regno);
5561 	}
5562 	return err;
5563 }
5564 
5565 
5566 /* check_stack_write dispatches to check_stack_write_fixed_off or
5567  * check_stack_write_var_off.
5568  *
5569  * 'ptr_regno' is the register used as a pointer into the stack.
5570  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5571  * 'value_regno' is the register whose value we're writing to the stack. It can
5572  * be -1, meaning that we're not writing from a register.
5573  *
5574  * The caller must ensure that the offset falls within the maximum stack size.
5575  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5576 static int check_stack_write(struct bpf_verifier_env *env,
5577 			     int ptr_regno, int off, int size,
5578 			     int value_regno, int insn_idx)
5579 {
5580 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5581 	struct bpf_func_state *state = func(env, reg);
5582 	int err;
5583 
5584 	if (tnum_is_const(reg->var_off)) {
5585 		off += reg->var_off.value;
5586 		err = check_stack_write_fixed_off(env, state, off, size,
5587 						  value_regno, insn_idx);
5588 	} else {
5589 		/* Variable offset stack reads need more conservative handling
5590 		 * than fixed offset ones.
5591 		 */
5592 		err = check_stack_write_var_off(env, state,
5593 						ptr_regno, off, size,
5594 						value_regno, insn_idx);
5595 	}
5596 	return err;
5597 }
5598 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5599 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5600 				 int off, int size, enum bpf_access_type type)
5601 {
5602 	struct bpf_reg_state *regs = cur_regs(env);
5603 	struct bpf_map *map = regs[regno].map_ptr;
5604 	u32 cap = bpf_map_flags_to_cap(map);
5605 
5606 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5607 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5608 			map->value_size, off, size);
5609 		return -EACCES;
5610 	}
5611 
5612 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5613 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5614 			map->value_size, off, size);
5615 		return -EACCES;
5616 	}
5617 
5618 	return 0;
5619 }
5620 
5621 /* 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)5622 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5623 			      int off, int size, u32 mem_size,
5624 			      bool zero_size_allowed)
5625 {
5626 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5627 	struct bpf_reg_state *reg;
5628 
5629 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5630 		return 0;
5631 
5632 	reg = &cur_regs(env)[regno];
5633 	switch (reg->type) {
5634 	case PTR_TO_MAP_KEY:
5635 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5636 			mem_size, off, size);
5637 		break;
5638 	case PTR_TO_MAP_VALUE:
5639 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5640 			mem_size, off, size);
5641 		break;
5642 	case PTR_TO_PACKET:
5643 	case PTR_TO_PACKET_META:
5644 	case PTR_TO_PACKET_END:
5645 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5646 			off, size, regno, reg->id, off, mem_size);
5647 		break;
5648 	case PTR_TO_MEM:
5649 	default:
5650 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5651 			mem_size, off, size);
5652 	}
5653 
5654 	return -EACCES;
5655 }
5656 
5657 /* 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)5658 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5659 				   int off, int size, u32 mem_size,
5660 				   bool zero_size_allowed)
5661 {
5662 	struct bpf_verifier_state *vstate = env->cur_state;
5663 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5664 	struct bpf_reg_state *reg = &state->regs[regno];
5665 	int err;
5666 
5667 	/* We may have adjusted the register pointing to memory region, so we
5668 	 * need to try adding each of min_value and max_value to off
5669 	 * to make sure our theoretical access will be safe.
5670 	 *
5671 	 * The minimum value is only important with signed
5672 	 * comparisons where we can't assume the floor of a
5673 	 * value is 0.  If we are using signed variables for our
5674 	 * index'es we need to make sure that whatever we use
5675 	 * will have a set floor within our range.
5676 	 */
5677 	if (reg->smin_value < 0 &&
5678 	    (reg->smin_value == S64_MIN ||
5679 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5680 	      reg->smin_value + off < 0)) {
5681 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5682 			regno);
5683 		return -EACCES;
5684 	}
5685 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5686 				 mem_size, zero_size_allowed);
5687 	if (err) {
5688 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5689 			regno);
5690 		return err;
5691 	}
5692 
5693 	/* If we haven't set a max value then we need to bail since we can't be
5694 	 * sure we won't do bad things.
5695 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5696 	 */
5697 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5698 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5699 			regno);
5700 		return -EACCES;
5701 	}
5702 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5703 				 mem_size, zero_size_allowed);
5704 	if (err) {
5705 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5706 			regno);
5707 		return err;
5708 	}
5709 
5710 	return 0;
5711 }
5712 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5713 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5714 			       const struct bpf_reg_state *reg, int regno,
5715 			       bool fixed_off_ok)
5716 {
5717 	/* Access to this pointer-typed register or passing it to a helper
5718 	 * is only allowed in its original, unmodified form.
5719 	 */
5720 
5721 	if (reg->off < 0) {
5722 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5723 			reg_type_str(env, reg->type), regno, reg->off);
5724 		return -EACCES;
5725 	}
5726 
5727 	if (!fixed_off_ok && reg->off) {
5728 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5729 			reg_type_str(env, reg->type), regno, reg->off);
5730 		return -EACCES;
5731 	}
5732 
5733 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5734 		char tn_buf[48];
5735 
5736 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5737 		verbose(env, "variable %s access var_off=%s disallowed\n",
5738 			reg_type_str(env, reg->type), tn_buf);
5739 		return -EACCES;
5740 	}
5741 
5742 	return 0;
5743 }
5744 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5745 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5746 		             const struct bpf_reg_state *reg, int regno)
5747 {
5748 	return __check_ptr_off_reg(env, reg, regno, false);
5749 }
5750 
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5751 static int map_kptr_match_type(struct bpf_verifier_env *env,
5752 			       struct btf_field *kptr_field,
5753 			       struct bpf_reg_state *reg, u32 regno)
5754 {
5755 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5756 	int perm_flags;
5757 	const char *reg_name = "";
5758 
5759 	if (btf_is_kernel(reg->btf)) {
5760 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5761 
5762 		/* Only unreferenced case accepts untrusted pointers */
5763 		if (kptr_field->type == BPF_KPTR_UNREF)
5764 			perm_flags |= PTR_UNTRUSTED;
5765 	} else {
5766 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5767 		if (kptr_field->type == BPF_KPTR_PERCPU)
5768 			perm_flags |= MEM_PERCPU;
5769 	}
5770 
5771 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5772 		goto bad_type;
5773 
5774 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5775 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5776 
5777 	/* For ref_ptr case, release function check should ensure we get one
5778 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5779 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5780 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5781 	 * reg->off and reg->ref_obj_id are not needed here.
5782 	 */
5783 	if (__check_ptr_off_reg(env, reg, regno, true))
5784 		return -EACCES;
5785 
5786 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5787 	 * we also need to take into account the reg->off.
5788 	 *
5789 	 * We want to support cases like:
5790 	 *
5791 	 * struct foo {
5792 	 *         struct bar br;
5793 	 *         struct baz bz;
5794 	 * };
5795 	 *
5796 	 * struct foo *v;
5797 	 * v = func();	      // PTR_TO_BTF_ID
5798 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5799 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5800 	 *                    // first member type of struct after comparison fails
5801 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5802 	 *                    // to match type
5803 	 *
5804 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5805 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5806 	 * the struct to match type against first member of struct, i.e. reject
5807 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5808 	 * strict mode to true for type match.
5809 	 */
5810 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5811 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5812 				  kptr_field->type != BPF_KPTR_UNREF))
5813 		goto bad_type;
5814 	return 0;
5815 bad_type:
5816 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5817 		reg_type_str(env, reg->type), reg_name);
5818 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5819 	if (kptr_field->type == BPF_KPTR_UNREF)
5820 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5821 			targ_name);
5822 	else
5823 		verbose(env, "\n");
5824 	return -EINVAL;
5825 }
5826 
in_sleepable(struct bpf_verifier_env * env)5827 static bool in_sleepable(struct bpf_verifier_env *env)
5828 {
5829 	return env->prog->sleepable ||
5830 	       (env->cur_state && env->cur_state->in_sleepable);
5831 }
5832 
5833 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5834  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5835  */
in_rcu_cs(struct bpf_verifier_env * env)5836 static bool in_rcu_cs(struct bpf_verifier_env *env)
5837 {
5838 	return env->cur_state->active_rcu_lock ||
5839 	       env->cur_state->active_locks ||
5840 	       !in_sleepable(env);
5841 }
5842 
5843 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5844 BTF_SET_START(rcu_protected_types)
5845 #ifdef CONFIG_NET
BTF_ID(struct,prog_test_ref_kfunc)5846 BTF_ID(struct, prog_test_ref_kfunc)
5847 #endif
5848 #ifdef CONFIG_CGROUPS
5849 BTF_ID(struct, cgroup)
5850 #endif
5851 #ifdef CONFIG_BPF_JIT
5852 BTF_ID(struct, bpf_cpumask)
5853 #endif
5854 BTF_ID(struct, task_struct)
5855 #ifdef CONFIG_CRYPTO
5856 BTF_ID(struct, bpf_crypto_ctx)
5857 #endif
5858 BTF_SET_END(rcu_protected_types)
5859 
5860 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5861 {
5862 	if (!btf_is_kernel(btf))
5863 		return true;
5864 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5865 }
5866 
kptr_pointee_btf_record(struct btf_field * kptr_field)5867 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5868 {
5869 	struct btf_struct_meta *meta;
5870 
5871 	if (btf_is_kernel(kptr_field->kptr.btf))
5872 		return NULL;
5873 
5874 	meta = btf_find_struct_meta(kptr_field->kptr.btf,
5875 				    kptr_field->kptr.btf_id);
5876 
5877 	return meta ? meta->record : NULL;
5878 }
5879 
rcu_safe_kptr(const struct btf_field * field)5880 static bool rcu_safe_kptr(const struct btf_field *field)
5881 {
5882 	const struct btf_field_kptr *kptr = &field->kptr;
5883 
5884 	return field->type == BPF_KPTR_PERCPU ||
5885 	       (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5886 }
5887 
btf_ld_kptr_type(struct bpf_verifier_env * env,struct btf_field * kptr_field)5888 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5889 {
5890 	struct btf_record *rec;
5891 	u32 ret;
5892 
5893 	ret = PTR_MAYBE_NULL;
5894 	if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5895 		ret |= MEM_RCU;
5896 		if (kptr_field->type == BPF_KPTR_PERCPU)
5897 			ret |= MEM_PERCPU;
5898 		else if (!btf_is_kernel(kptr_field->kptr.btf))
5899 			ret |= MEM_ALLOC;
5900 
5901 		rec = kptr_pointee_btf_record(kptr_field);
5902 		if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5903 			ret |= NON_OWN_REF;
5904 	} else {
5905 		ret |= PTR_UNTRUSTED;
5906 	}
5907 
5908 	return ret;
5909 }
5910 
mark_uptr_ld_reg(struct bpf_verifier_env * env,u32 regno,struct btf_field * field)5911 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5912 			    struct btf_field *field)
5913 {
5914 	struct bpf_reg_state *reg;
5915 	const struct btf_type *t;
5916 
5917 	t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5918 	mark_reg_known_zero(env, cur_regs(env), regno);
5919 	reg = reg_state(env, regno);
5920 	reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5921 	reg->mem_size = t->size;
5922 	reg->id = ++env->id_gen;
5923 
5924 	return 0;
5925 }
5926 
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)5927 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5928 				 int value_regno, int insn_idx,
5929 				 struct btf_field *kptr_field)
5930 {
5931 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5932 	int class = BPF_CLASS(insn->code);
5933 	struct bpf_reg_state *val_reg;
5934 	int ret;
5935 
5936 	/* Things we already checked for in check_map_access and caller:
5937 	 *  - Reject cases where variable offset may touch kptr
5938 	 *  - size of access (must be BPF_DW)
5939 	 *  - tnum_is_const(reg->var_off)
5940 	 *  - kptr_field->offset == off + reg->var_off.value
5941 	 */
5942 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5943 	if (BPF_MODE(insn->code) != BPF_MEM) {
5944 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5945 		return -EACCES;
5946 	}
5947 
5948 	/* We only allow loading referenced kptr, since it will be marked as
5949 	 * untrusted, similar to unreferenced kptr.
5950 	 */
5951 	if (class != BPF_LDX &&
5952 	    (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5953 		verbose(env, "store to referenced kptr disallowed\n");
5954 		return -EACCES;
5955 	}
5956 	if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
5957 		verbose(env, "store to uptr disallowed\n");
5958 		return -EACCES;
5959 	}
5960 
5961 	if (class == BPF_LDX) {
5962 		if (kptr_field->type == BPF_UPTR)
5963 			return mark_uptr_ld_reg(env, value_regno, kptr_field);
5964 
5965 		/* We can simply mark the value_regno receiving the pointer
5966 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5967 		 */
5968 		ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
5969 				      kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5970 				      btf_ld_kptr_type(env, kptr_field));
5971 		if (ret < 0)
5972 			return ret;
5973 	} else if (class == BPF_STX) {
5974 		val_reg = reg_state(env, value_regno);
5975 		if (!register_is_null(val_reg) &&
5976 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5977 			return -EACCES;
5978 	} else if (class == BPF_ST) {
5979 		if (insn->imm) {
5980 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5981 				kptr_field->offset);
5982 			return -EACCES;
5983 		}
5984 	} else {
5985 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5986 		return -EACCES;
5987 	}
5988 	return 0;
5989 }
5990 
5991 /* 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)5992 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5993 			    int off, int size, bool zero_size_allowed,
5994 			    enum bpf_access_src src)
5995 {
5996 	struct bpf_verifier_state *vstate = env->cur_state;
5997 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5998 	struct bpf_reg_state *reg = &state->regs[regno];
5999 	struct bpf_map *map = reg->map_ptr;
6000 	struct btf_record *rec;
6001 	int err, i;
6002 
6003 	err = check_mem_region_access(env, regno, off, size, map->value_size,
6004 				      zero_size_allowed);
6005 	if (err)
6006 		return err;
6007 
6008 	if (IS_ERR_OR_NULL(map->record))
6009 		return 0;
6010 	rec = map->record;
6011 	for (i = 0; i < rec->cnt; i++) {
6012 		struct btf_field *field = &rec->fields[i];
6013 		u32 p = field->offset;
6014 
6015 		/* If any part of a field  can be touched by load/store, reject
6016 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
6017 		 * it is sufficient to check x1 < y2 && y1 < x2.
6018 		 */
6019 		if (reg->smin_value + off < p + field->size &&
6020 		    p < reg->umax_value + off + size) {
6021 			switch (field->type) {
6022 			case BPF_KPTR_UNREF:
6023 			case BPF_KPTR_REF:
6024 			case BPF_KPTR_PERCPU:
6025 			case BPF_UPTR:
6026 				if (src != ACCESS_DIRECT) {
6027 					verbose(env, "%s cannot be accessed indirectly by helper\n",
6028 						btf_field_type_name(field->type));
6029 					return -EACCES;
6030 				}
6031 				if (!tnum_is_const(reg->var_off)) {
6032 					verbose(env, "%s access cannot have variable offset\n",
6033 						btf_field_type_name(field->type));
6034 					return -EACCES;
6035 				}
6036 				if (p != off + reg->var_off.value) {
6037 					verbose(env, "%s access misaligned expected=%u off=%llu\n",
6038 						btf_field_type_name(field->type),
6039 						p, off + reg->var_off.value);
6040 					return -EACCES;
6041 				}
6042 				if (size != bpf_size_to_bytes(BPF_DW)) {
6043 					verbose(env, "%s access size must be BPF_DW\n",
6044 						btf_field_type_name(field->type));
6045 					return -EACCES;
6046 				}
6047 				break;
6048 			default:
6049 				verbose(env, "%s cannot be accessed directly by load/store\n",
6050 					btf_field_type_name(field->type));
6051 				return -EACCES;
6052 			}
6053 		}
6054 	}
6055 	return 0;
6056 }
6057 
6058 #define MAX_PACKET_OFF 0xffff
6059 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)6060 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6061 				       const struct bpf_call_arg_meta *meta,
6062 				       enum bpf_access_type t)
6063 {
6064 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6065 
6066 	switch (prog_type) {
6067 	/* Program types only with direct read access go here! */
6068 	case BPF_PROG_TYPE_LWT_IN:
6069 	case BPF_PROG_TYPE_LWT_OUT:
6070 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6071 	case BPF_PROG_TYPE_SK_REUSEPORT:
6072 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6073 	case BPF_PROG_TYPE_CGROUP_SKB:
6074 		if (t == BPF_WRITE)
6075 			return false;
6076 		fallthrough;
6077 
6078 	/* Program types with direct read + write access go here! */
6079 	case BPF_PROG_TYPE_SCHED_CLS:
6080 	case BPF_PROG_TYPE_SCHED_ACT:
6081 	case BPF_PROG_TYPE_XDP:
6082 	case BPF_PROG_TYPE_LWT_XMIT:
6083 	case BPF_PROG_TYPE_SK_SKB:
6084 	case BPF_PROG_TYPE_SK_MSG:
6085 		if (meta)
6086 			return meta->pkt_access;
6087 
6088 		env->seen_direct_write = true;
6089 		return true;
6090 
6091 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6092 		if (t == BPF_WRITE)
6093 			env->seen_direct_write = true;
6094 
6095 		return true;
6096 
6097 	default:
6098 		return false;
6099 	}
6100 }
6101 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)6102 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6103 			       int size, bool zero_size_allowed)
6104 {
6105 	struct bpf_reg_state *regs = cur_regs(env);
6106 	struct bpf_reg_state *reg = &regs[regno];
6107 	int err;
6108 
6109 	/* We may have added a variable offset to the packet pointer; but any
6110 	 * reg->range we have comes after that.  We are only checking the fixed
6111 	 * offset.
6112 	 */
6113 
6114 	/* We don't allow negative numbers, because we aren't tracking enough
6115 	 * detail to prove they're safe.
6116 	 */
6117 	if (reg->smin_value < 0) {
6118 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6119 			regno);
6120 		return -EACCES;
6121 	}
6122 
6123 	err = reg->range < 0 ? -EINVAL :
6124 	      __check_mem_access(env, regno, off, size, reg->range,
6125 				 zero_size_allowed);
6126 	if (err) {
6127 		verbose(env, "R%d offset is outside of the packet\n", regno);
6128 		return err;
6129 	}
6130 
6131 	/* __check_mem_access has made sure "off + size - 1" is within u16.
6132 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6133 	 * otherwise find_good_pkt_pointers would have refused to set range info
6134 	 * that __check_mem_access would have rejected this pkt access.
6135 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6136 	 */
6137 	env->prog->aux->max_pkt_offset =
6138 		max_t(u32, env->prog->aux->max_pkt_offset,
6139 		      off + reg->umax_value + size - 1);
6140 
6141 	return err;
6142 }
6143 
6144 /* 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)6145 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6146 			    enum bpf_access_type t, struct bpf_insn_access_aux *info)
6147 {
6148 	if (env->ops->is_valid_access &&
6149 	    env->ops->is_valid_access(off, size, t, env->prog, info)) {
6150 		/* A non zero info.ctx_field_size indicates that this field is a
6151 		 * candidate for later verifier transformation to load the whole
6152 		 * field and then apply a mask when accessed with a narrower
6153 		 * access than actual ctx access size. A zero info.ctx_field_size
6154 		 * will only allow for whole field access and rejects any other
6155 		 * type of narrower access.
6156 		 */
6157 		if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6158 			if (info->ref_obj_id &&
6159 			    !find_reference_state(env->cur_state, info->ref_obj_id)) {
6160 				verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6161 					off);
6162 				return -EACCES;
6163 			}
6164 		} else {
6165 			env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6166 		}
6167 		/* remember the offset of last byte accessed in ctx */
6168 		if (env->prog->aux->max_ctx_offset < off + size)
6169 			env->prog->aux->max_ctx_offset = off + size;
6170 		return 0;
6171 	}
6172 
6173 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6174 	return -EACCES;
6175 }
6176 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)6177 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6178 				  int size)
6179 {
6180 	if (size < 0 || off < 0 ||
6181 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
6182 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
6183 			off, size);
6184 		return -EACCES;
6185 	}
6186 	return 0;
6187 }
6188 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)6189 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6190 			     u32 regno, int off, int size,
6191 			     enum bpf_access_type t)
6192 {
6193 	struct bpf_reg_state *regs = cur_regs(env);
6194 	struct bpf_reg_state *reg = &regs[regno];
6195 	struct bpf_insn_access_aux info = {};
6196 	bool valid;
6197 
6198 	if (reg->smin_value < 0) {
6199 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6200 			regno);
6201 		return -EACCES;
6202 	}
6203 
6204 	switch (reg->type) {
6205 	case PTR_TO_SOCK_COMMON:
6206 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6207 		break;
6208 	case PTR_TO_SOCKET:
6209 		valid = bpf_sock_is_valid_access(off, size, t, &info);
6210 		break;
6211 	case PTR_TO_TCP_SOCK:
6212 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6213 		break;
6214 	case PTR_TO_XDP_SOCK:
6215 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6216 		break;
6217 	default:
6218 		valid = false;
6219 	}
6220 
6221 
6222 	if (valid) {
6223 		env->insn_aux_data[insn_idx].ctx_field_size =
6224 			info.ctx_field_size;
6225 		return 0;
6226 	}
6227 
6228 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
6229 		regno, reg_type_str(env, reg->type), off, size);
6230 
6231 	return -EACCES;
6232 }
6233 
is_pointer_value(struct bpf_verifier_env * env,int regno)6234 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6235 {
6236 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6237 }
6238 
is_ctx_reg(struct bpf_verifier_env * env,int regno)6239 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6240 {
6241 	const struct bpf_reg_state *reg = reg_state(env, regno);
6242 
6243 	return reg->type == PTR_TO_CTX;
6244 }
6245 
is_sk_reg(struct bpf_verifier_env * env,int regno)6246 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6247 {
6248 	const struct bpf_reg_state *reg = reg_state(env, regno);
6249 
6250 	return type_is_sk_pointer(reg->type);
6251 }
6252 
is_pkt_reg(struct bpf_verifier_env * env,int regno)6253 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6254 {
6255 	const struct bpf_reg_state *reg = reg_state(env, regno);
6256 
6257 	return type_is_pkt_pointer(reg->type);
6258 }
6259 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)6260 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6261 {
6262 	const struct bpf_reg_state *reg = reg_state(env, regno);
6263 
6264 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6265 	return reg->type == PTR_TO_FLOW_KEYS;
6266 }
6267 
is_arena_reg(struct bpf_verifier_env * env,int regno)6268 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6269 {
6270 	const struct bpf_reg_state *reg = reg_state(env, regno);
6271 
6272 	return reg->type == PTR_TO_ARENA;
6273 }
6274 
6275 /* Return false if @regno contains a pointer whose type isn't supported for
6276  * atomic instruction @insn.
6277  */
atomic_ptr_type_ok(struct bpf_verifier_env * env,int regno,struct bpf_insn * insn)6278 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6279 			       struct bpf_insn *insn)
6280 {
6281 	if (is_ctx_reg(env, regno))
6282 		return false;
6283 	if (is_pkt_reg(env, regno))
6284 		return false;
6285 	if (is_flow_key_reg(env, regno))
6286 		return false;
6287 	if (is_sk_reg(env, regno))
6288 		return false;
6289 	if (is_arena_reg(env, regno))
6290 		return bpf_jit_supports_insn(insn, true);
6291 
6292 	return true;
6293 }
6294 
6295 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6296 #ifdef CONFIG_NET
6297 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6298 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6299 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6300 #endif
6301 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
6302 };
6303 
is_trusted_reg(const struct bpf_reg_state * reg)6304 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6305 {
6306 	/* A referenced register is always trusted. */
6307 	if (reg->ref_obj_id)
6308 		return true;
6309 
6310 	/* Types listed in the reg2btf_ids are always trusted */
6311 	if (reg2btf_ids[base_type(reg->type)] &&
6312 	    !bpf_type_has_unsafe_modifiers(reg->type))
6313 		return true;
6314 
6315 	/* If a register is not referenced, it is trusted if it has the
6316 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6317 	 * other type modifiers may be safe, but we elect to take an opt-in
6318 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6319 	 * not.
6320 	 *
6321 	 * Eventually, we should make PTR_TRUSTED the single source of truth
6322 	 * for whether a register is trusted.
6323 	 */
6324 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6325 	       !bpf_type_has_unsafe_modifiers(reg->type);
6326 }
6327 
is_rcu_reg(const struct bpf_reg_state * reg)6328 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6329 {
6330 	return reg->type & MEM_RCU;
6331 }
6332 
clear_trusted_flags(enum bpf_type_flag * flag)6333 static void clear_trusted_flags(enum bpf_type_flag *flag)
6334 {
6335 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6336 }
6337 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)6338 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6339 				   const struct bpf_reg_state *reg,
6340 				   int off, int size, bool strict)
6341 {
6342 	struct tnum reg_off;
6343 	int ip_align;
6344 
6345 	/* Byte size accesses are always allowed. */
6346 	if (!strict || size == 1)
6347 		return 0;
6348 
6349 	/* For platforms that do not have a Kconfig enabling
6350 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6351 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
6352 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6353 	 * to this code only in strict mode where we want to emulate
6354 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
6355 	 * unconditional IP align value of '2'.
6356 	 */
6357 	ip_align = 2;
6358 
6359 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6360 	if (!tnum_is_aligned(reg_off, size)) {
6361 		char tn_buf[48];
6362 
6363 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6364 		verbose(env,
6365 			"misaligned packet access off %d+%s+%d+%d size %d\n",
6366 			ip_align, tn_buf, reg->off, off, size);
6367 		return -EACCES;
6368 	}
6369 
6370 	return 0;
6371 }
6372 
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)6373 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6374 				       const struct bpf_reg_state *reg,
6375 				       const char *pointer_desc,
6376 				       int off, int size, bool strict)
6377 {
6378 	struct tnum reg_off;
6379 
6380 	/* Byte size accesses are always allowed. */
6381 	if (!strict || size == 1)
6382 		return 0;
6383 
6384 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6385 	if (!tnum_is_aligned(reg_off, size)) {
6386 		char tn_buf[48];
6387 
6388 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6389 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6390 			pointer_desc, tn_buf, reg->off, off, size);
6391 		return -EACCES;
6392 	}
6393 
6394 	return 0;
6395 }
6396 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)6397 static int check_ptr_alignment(struct bpf_verifier_env *env,
6398 			       const struct bpf_reg_state *reg, int off,
6399 			       int size, bool strict_alignment_once)
6400 {
6401 	bool strict = env->strict_alignment || strict_alignment_once;
6402 	const char *pointer_desc = "";
6403 
6404 	switch (reg->type) {
6405 	case PTR_TO_PACKET:
6406 	case PTR_TO_PACKET_META:
6407 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
6408 		 * right in front, treat it the very same way.
6409 		 */
6410 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
6411 	case PTR_TO_FLOW_KEYS:
6412 		pointer_desc = "flow keys ";
6413 		break;
6414 	case PTR_TO_MAP_KEY:
6415 		pointer_desc = "key ";
6416 		break;
6417 	case PTR_TO_MAP_VALUE:
6418 		pointer_desc = "value ";
6419 		break;
6420 	case PTR_TO_CTX:
6421 		pointer_desc = "context ";
6422 		break;
6423 	case PTR_TO_STACK:
6424 		pointer_desc = "stack ";
6425 		/* The stack spill tracking logic in check_stack_write_fixed_off()
6426 		 * and check_stack_read_fixed_off() relies on stack accesses being
6427 		 * aligned.
6428 		 */
6429 		strict = true;
6430 		break;
6431 	case PTR_TO_SOCKET:
6432 		pointer_desc = "sock ";
6433 		break;
6434 	case PTR_TO_SOCK_COMMON:
6435 		pointer_desc = "sock_common ";
6436 		break;
6437 	case PTR_TO_TCP_SOCK:
6438 		pointer_desc = "tcp_sock ";
6439 		break;
6440 	case PTR_TO_XDP_SOCK:
6441 		pointer_desc = "xdp_sock ";
6442 		break;
6443 	case PTR_TO_ARENA:
6444 		return 0;
6445 	default:
6446 		break;
6447 	}
6448 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6449 					   strict);
6450 }
6451 
bpf_enable_priv_stack(struct bpf_prog * prog)6452 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6453 {
6454 	if (!bpf_jit_supports_private_stack())
6455 		return NO_PRIV_STACK;
6456 
6457 	/* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6458 	 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6459 	 * explicitly.
6460 	 */
6461 	switch (prog->type) {
6462 	case BPF_PROG_TYPE_KPROBE:
6463 	case BPF_PROG_TYPE_TRACEPOINT:
6464 	case BPF_PROG_TYPE_PERF_EVENT:
6465 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6466 		return PRIV_STACK_ADAPTIVE;
6467 	case BPF_PROG_TYPE_TRACING:
6468 	case BPF_PROG_TYPE_LSM:
6469 	case BPF_PROG_TYPE_STRUCT_OPS:
6470 		if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6471 			return PRIV_STACK_ADAPTIVE;
6472 		fallthrough;
6473 	default:
6474 		break;
6475 	}
6476 
6477 	return NO_PRIV_STACK;
6478 }
6479 
round_up_stack_depth(struct bpf_verifier_env * env,int stack_depth)6480 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6481 {
6482 	if (env->prog->jit_requested)
6483 		return round_up(stack_depth, 16);
6484 
6485 	/* round up to 32-bytes, since this is granularity
6486 	 * of interpreter stack size
6487 	 */
6488 	return round_up(max_t(u32, stack_depth, 1), 32);
6489 }
6490 
6491 /* starting from main bpf function walk all instructions of the function
6492  * and recursively walk all callees that given function can call.
6493  * Ignore jump and exit insns.
6494  * Since recursion is prevented by check_cfg() this algorithm
6495  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6496  */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx,bool priv_stack_supported)6497 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6498 					 bool priv_stack_supported)
6499 {
6500 	struct bpf_subprog_info *subprog = env->subprog_info;
6501 	struct bpf_insn *insn = env->prog->insnsi;
6502 	int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6503 	bool tail_call_reachable = false;
6504 	int ret_insn[MAX_CALL_FRAMES];
6505 	int ret_prog[MAX_CALL_FRAMES];
6506 	int j;
6507 
6508 	i = subprog[idx].start;
6509 	if (!priv_stack_supported)
6510 		subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6511 process_func:
6512 	/* protect against potential stack overflow that might happen when
6513 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6514 	 * depth for such case down to 256 so that the worst case scenario
6515 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
6516 	 * 8k).
6517 	 *
6518 	 * To get the idea what might happen, see an example:
6519 	 * func1 -> sub rsp, 128
6520 	 *  subfunc1 -> sub rsp, 256
6521 	 *  tailcall1 -> add rsp, 256
6522 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6523 	 *   subfunc2 -> sub rsp, 64
6524 	 *   subfunc22 -> sub rsp, 128
6525 	 *   tailcall2 -> add rsp, 128
6526 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6527 	 *
6528 	 * tailcall will unwind the current stack frame but it will not get rid
6529 	 * of caller's stack as shown on the example above.
6530 	 */
6531 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
6532 		verbose(env,
6533 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6534 			depth);
6535 		return -EACCES;
6536 	}
6537 
6538 	subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6539 	if (priv_stack_supported) {
6540 		/* Request private stack support only if the subprog stack
6541 		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6542 		 * avoid jit penalty if the stack usage is small.
6543 		 */
6544 		if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6545 		    subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6546 			subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6547 	}
6548 
6549 	if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6550 		if (subprog_depth > MAX_BPF_STACK) {
6551 			verbose(env, "stack size of subprog %d is %d. Too large\n",
6552 				idx, subprog_depth);
6553 			return -EACCES;
6554 		}
6555 	} else {
6556 		depth += subprog_depth;
6557 		if (depth > MAX_BPF_STACK) {
6558 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
6559 				frame + 1, depth);
6560 			return -EACCES;
6561 		}
6562 	}
6563 continue_func:
6564 	subprog_end = subprog[idx + 1].start;
6565 	for (; i < subprog_end; i++) {
6566 		int next_insn, sidx;
6567 
6568 		if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6569 			bool err = false;
6570 
6571 			if (!is_bpf_throw_kfunc(insn + i))
6572 				continue;
6573 			if (subprog[idx].is_cb)
6574 				err = true;
6575 			for (int c = 0; c < frame && !err; c++) {
6576 				if (subprog[ret_prog[c]].is_cb) {
6577 					err = true;
6578 					break;
6579 				}
6580 			}
6581 			if (!err)
6582 				continue;
6583 			verbose(env,
6584 				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6585 				i, idx);
6586 			return -EINVAL;
6587 		}
6588 
6589 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6590 			continue;
6591 		/* remember insn and function to return to */
6592 		ret_insn[frame] = i + 1;
6593 		ret_prog[frame] = idx;
6594 
6595 		/* find the callee */
6596 		next_insn = i + insn[i].imm + 1;
6597 		sidx = find_subprog(env, next_insn);
6598 		if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6599 			return -EFAULT;
6600 		if (subprog[sidx].is_async_cb) {
6601 			if (subprog[sidx].has_tail_call) {
6602 				verifier_bug(env, "subprog has tail_call and async cb");
6603 				return -EFAULT;
6604 			}
6605 			/* async callbacks don't increase bpf prog stack size unless called directly */
6606 			if (!bpf_pseudo_call(insn + i))
6607 				continue;
6608 			if (subprog[sidx].is_exception_cb) {
6609 				verbose(env, "insn %d cannot call exception cb directly", i);
6610 				return -EINVAL;
6611 			}
6612 		}
6613 		i = next_insn;
6614 		idx = sidx;
6615 		if (!priv_stack_supported)
6616 			subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6617 
6618 		if (subprog[idx].has_tail_call)
6619 			tail_call_reachable = true;
6620 
6621 		frame++;
6622 		if (frame >= MAX_CALL_FRAMES) {
6623 			verbose(env, "the call stack of %d frames is too deep !\n",
6624 				frame);
6625 			return -E2BIG;
6626 		}
6627 		goto process_func;
6628 	}
6629 	/* if tail call got detected across bpf2bpf calls then mark each of the
6630 	 * currently present subprog frames as tail call reachable subprogs;
6631 	 * this info will be utilized by JIT so that we will be preserving the
6632 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
6633 	 */
6634 	if (tail_call_reachable)
6635 		for (j = 0; j < frame; j++) {
6636 			if (subprog[ret_prog[j]].is_exception_cb) {
6637 				verbose(env, "cannot tail call within exception cb\n");
6638 				return -EINVAL;
6639 			}
6640 			subprog[ret_prog[j]].tail_call_reachable = true;
6641 		}
6642 	if (subprog[0].tail_call_reachable)
6643 		env->prog->aux->tail_call_reachable = true;
6644 
6645 	/* end of for() loop means the last insn of the 'subprog'
6646 	 * was reached. Doesn't matter whether it was JA or EXIT
6647 	 */
6648 	if (frame == 0)
6649 		return 0;
6650 	if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6651 		depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6652 	frame--;
6653 	i = ret_insn[frame];
6654 	idx = ret_prog[frame];
6655 	goto continue_func;
6656 }
6657 
check_max_stack_depth(struct bpf_verifier_env * env)6658 static int check_max_stack_depth(struct bpf_verifier_env *env)
6659 {
6660 	enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6661 	struct bpf_subprog_info *si = env->subprog_info;
6662 	bool priv_stack_supported;
6663 	int ret;
6664 
6665 	for (int i = 0; i < env->subprog_cnt; i++) {
6666 		if (si[i].has_tail_call) {
6667 			priv_stack_mode = NO_PRIV_STACK;
6668 			break;
6669 		}
6670 	}
6671 
6672 	if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6673 		priv_stack_mode = bpf_enable_priv_stack(env->prog);
6674 
6675 	/* All async_cb subprogs use normal kernel stack. If a particular
6676 	 * subprog appears in both main prog and async_cb subtree, that
6677 	 * subprog will use normal kernel stack to avoid potential nesting.
6678 	 * The reverse subprog traversal ensures when main prog subtree is
6679 	 * checked, the subprogs appearing in async_cb subtrees are already
6680 	 * marked as using normal kernel stack, so stack size checking can
6681 	 * be done properly.
6682 	 */
6683 	for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6684 		if (!i || si[i].is_async_cb) {
6685 			priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6686 			ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6687 			if (ret < 0)
6688 				return ret;
6689 		}
6690 	}
6691 
6692 	for (int i = 0; i < env->subprog_cnt; i++) {
6693 		if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6694 			env->prog->aux->jits_use_priv_stack = true;
6695 			break;
6696 		}
6697 	}
6698 
6699 	return 0;
6700 }
6701 
6702 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)6703 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6704 				  const struct bpf_insn *insn, int idx)
6705 {
6706 	int start = idx + insn->imm + 1, subprog;
6707 
6708 	subprog = find_subprog(env, start);
6709 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6710 		return -EFAULT;
6711 	return env->subprog_info[subprog].stack_depth;
6712 }
6713 #endif
6714 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)6715 static int __check_buffer_access(struct bpf_verifier_env *env,
6716 				 const char *buf_info,
6717 				 const struct bpf_reg_state *reg,
6718 				 int regno, int off, int size)
6719 {
6720 	if (off < 0) {
6721 		verbose(env,
6722 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6723 			regno, buf_info, off, size);
6724 		return -EACCES;
6725 	}
6726 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6727 		char tn_buf[48];
6728 
6729 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6730 		verbose(env,
6731 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6732 			regno, off, tn_buf);
6733 		return -EACCES;
6734 	}
6735 
6736 	return 0;
6737 }
6738 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)6739 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6740 				  const struct bpf_reg_state *reg,
6741 				  int regno, int off, int size)
6742 {
6743 	int err;
6744 
6745 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6746 	if (err)
6747 		return err;
6748 
6749 	if (off + size > env->prog->aux->max_tp_access)
6750 		env->prog->aux->max_tp_access = off + size;
6751 
6752 	return 0;
6753 }
6754 
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)6755 static int check_buffer_access(struct bpf_verifier_env *env,
6756 			       const struct bpf_reg_state *reg,
6757 			       int regno, int off, int size,
6758 			       bool zero_size_allowed,
6759 			       u32 *max_access)
6760 {
6761 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6762 	int err;
6763 
6764 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6765 	if (err)
6766 		return err;
6767 
6768 	if (off + size > *max_access)
6769 		*max_access = off + size;
6770 
6771 	return 0;
6772 }
6773 
6774 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6775 static void zext_32_to_64(struct bpf_reg_state *reg)
6776 {
6777 	reg->var_off = tnum_subreg(reg->var_off);
6778 	__reg_assign_32_into_64(reg);
6779 }
6780 
6781 /* truncate register to smaller size (in bytes)
6782  * must be called with size < BPF_REG_SIZE
6783  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6784 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6785 {
6786 	u64 mask;
6787 
6788 	/* clear high bits in bit representation */
6789 	reg->var_off = tnum_cast(reg->var_off, size);
6790 
6791 	/* fix arithmetic bounds */
6792 	mask = ((u64)1 << (size * 8)) - 1;
6793 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6794 		reg->umin_value &= mask;
6795 		reg->umax_value &= mask;
6796 	} else {
6797 		reg->umin_value = 0;
6798 		reg->umax_value = mask;
6799 	}
6800 	reg->smin_value = reg->umin_value;
6801 	reg->smax_value = reg->umax_value;
6802 
6803 	/* If size is smaller than 32bit register the 32bit register
6804 	 * values are also truncated so we push 64-bit bounds into
6805 	 * 32-bit bounds. Above were truncated < 32-bits already.
6806 	 */
6807 	if (size < 4)
6808 		__mark_reg32_unbounded(reg);
6809 
6810 	reg_bounds_sync(reg);
6811 }
6812 
set_sext64_default_val(struct bpf_reg_state * reg,int size)6813 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6814 {
6815 	if (size == 1) {
6816 		reg->smin_value = reg->s32_min_value = S8_MIN;
6817 		reg->smax_value = reg->s32_max_value = S8_MAX;
6818 	} else if (size == 2) {
6819 		reg->smin_value = reg->s32_min_value = S16_MIN;
6820 		reg->smax_value = reg->s32_max_value = S16_MAX;
6821 	} else {
6822 		/* size == 4 */
6823 		reg->smin_value = reg->s32_min_value = S32_MIN;
6824 		reg->smax_value = reg->s32_max_value = S32_MAX;
6825 	}
6826 	reg->umin_value = reg->u32_min_value = 0;
6827 	reg->umax_value = U64_MAX;
6828 	reg->u32_max_value = U32_MAX;
6829 	reg->var_off = tnum_unknown;
6830 }
6831 
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6832 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6833 {
6834 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6835 	u64 top_smax_value, top_smin_value;
6836 	u64 num_bits = size * 8;
6837 
6838 	if (tnum_is_const(reg->var_off)) {
6839 		u64_cval = reg->var_off.value;
6840 		if (size == 1)
6841 			reg->var_off = tnum_const((s8)u64_cval);
6842 		else if (size == 2)
6843 			reg->var_off = tnum_const((s16)u64_cval);
6844 		else
6845 			/* size == 4 */
6846 			reg->var_off = tnum_const((s32)u64_cval);
6847 
6848 		u64_cval = reg->var_off.value;
6849 		reg->smax_value = reg->smin_value = u64_cval;
6850 		reg->umax_value = reg->umin_value = u64_cval;
6851 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6852 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6853 		return;
6854 	}
6855 
6856 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6857 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6858 
6859 	if (top_smax_value != top_smin_value)
6860 		goto out;
6861 
6862 	/* find the s64_min and s64_min after sign extension */
6863 	if (size == 1) {
6864 		init_s64_max = (s8)reg->smax_value;
6865 		init_s64_min = (s8)reg->smin_value;
6866 	} else if (size == 2) {
6867 		init_s64_max = (s16)reg->smax_value;
6868 		init_s64_min = (s16)reg->smin_value;
6869 	} else {
6870 		init_s64_max = (s32)reg->smax_value;
6871 		init_s64_min = (s32)reg->smin_value;
6872 	}
6873 
6874 	s64_max = max(init_s64_max, init_s64_min);
6875 	s64_min = min(init_s64_max, init_s64_min);
6876 
6877 	/* both of s64_max/s64_min positive or negative */
6878 	if ((s64_max >= 0) == (s64_min >= 0)) {
6879 		reg->s32_min_value = reg->smin_value = s64_min;
6880 		reg->s32_max_value = reg->smax_value = s64_max;
6881 		reg->u32_min_value = reg->umin_value = s64_min;
6882 		reg->u32_max_value = reg->umax_value = s64_max;
6883 		reg->var_off = tnum_range(s64_min, s64_max);
6884 		return;
6885 	}
6886 
6887 out:
6888 	set_sext64_default_val(reg, size);
6889 }
6890 
set_sext32_default_val(struct bpf_reg_state * reg,int size)6891 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6892 {
6893 	if (size == 1) {
6894 		reg->s32_min_value = S8_MIN;
6895 		reg->s32_max_value = S8_MAX;
6896 	} else {
6897 		/* size == 2 */
6898 		reg->s32_min_value = S16_MIN;
6899 		reg->s32_max_value = S16_MAX;
6900 	}
6901 	reg->u32_min_value = 0;
6902 	reg->u32_max_value = U32_MAX;
6903 	reg->var_off = tnum_subreg(tnum_unknown);
6904 }
6905 
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6906 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6907 {
6908 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6909 	u32 top_smax_value, top_smin_value;
6910 	u32 num_bits = size * 8;
6911 
6912 	if (tnum_is_const(reg->var_off)) {
6913 		u32_val = reg->var_off.value;
6914 		if (size == 1)
6915 			reg->var_off = tnum_const((s8)u32_val);
6916 		else
6917 			reg->var_off = tnum_const((s16)u32_val);
6918 
6919 		u32_val = reg->var_off.value;
6920 		reg->s32_min_value = reg->s32_max_value = u32_val;
6921 		reg->u32_min_value = reg->u32_max_value = u32_val;
6922 		return;
6923 	}
6924 
6925 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6926 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6927 
6928 	if (top_smax_value != top_smin_value)
6929 		goto out;
6930 
6931 	/* find the s32_min and s32_min after sign extension */
6932 	if (size == 1) {
6933 		init_s32_max = (s8)reg->s32_max_value;
6934 		init_s32_min = (s8)reg->s32_min_value;
6935 	} else {
6936 		/* size == 2 */
6937 		init_s32_max = (s16)reg->s32_max_value;
6938 		init_s32_min = (s16)reg->s32_min_value;
6939 	}
6940 	s32_max = max(init_s32_max, init_s32_min);
6941 	s32_min = min(init_s32_max, init_s32_min);
6942 
6943 	if ((s32_min >= 0) == (s32_max >= 0)) {
6944 		reg->s32_min_value = s32_min;
6945 		reg->s32_max_value = s32_max;
6946 		reg->u32_min_value = (u32)s32_min;
6947 		reg->u32_max_value = (u32)s32_max;
6948 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6949 		return;
6950 	}
6951 
6952 out:
6953 	set_sext32_default_val(reg, size);
6954 }
6955 
bpf_map_is_rdonly(const struct bpf_map * map)6956 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6957 {
6958 	/* A map is considered read-only if the following condition are true:
6959 	 *
6960 	 * 1) BPF program side cannot change any of the map content. The
6961 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6962 	 *    and was set at map creation time.
6963 	 * 2) The map value(s) have been initialized from user space by a
6964 	 *    loader and then "frozen", such that no new map update/delete
6965 	 *    operations from syscall side are possible for the rest of
6966 	 *    the map's lifetime from that point onwards.
6967 	 * 3) Any parallel/pending map update/delete operations from syscall
6968 	 *    side have been completed. Only after that point, it's safe to
6969 	 *    assume that map value(s) are immutable.
6970 	 */
6971 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6972 	       READ_ONCE(map->frozen) &&
6973 	       !bpf_map_write_active(map);
6974 }
6975 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)6976 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6977 			       bool is_ldsx)
6978 {
6979 	void *ptr;
6980 	u64 addr;
6981 	int err;
6982 
6983 	err = map->ops->map_direct_value_addr(map, &addr, off);
6984 	if (err)
6985 		return err;
6986 	ptr = (void *)(long)addr + off;
6987 
6988 	switch (size) {
6989 	case sizeof(u8):
6990 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6991 		break;
6992 	case sizeof(u16):
6993 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6994 		break;
6995 	case sizeof(u32):
6996 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6997 		break;
6998 	case sizeof(u64):
6999 		*val = *(u64 *)ptr;
7000 		break;
7001 	default:
7002 		return -EINVAL;
7003 	}
7004 	return 0;
7005 }
7006 
7007 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
7008 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
7009 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
7010 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
7011 
7012 /*
7013  * Allow list few fields as RCU trusted or full trusted.
7014  * This logic doesn't allow mix tagging and will be removed once GCC supports
7015  * btf_type_tag.
7016  */
7017 
7018 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)7019 BTF_TYPE_SAFE_RCU(struct task_struct) {
7020 	const cpumask_t *cpus_ptr;
7021 	struct css_set __rcu *cgroups;
7022 	struct task_struct __rcu *real_parent;
7023 	struct task_struct *group_leader;
7024 };
7025 
BTF_TYPE_SAFE_RCU(struct cgroup)7026 BTF_TYPE_SAFE_RCU(struct cgroup) {
7027 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7028 	struct kernfs_node *kn;
7029 };
7030 
BTF_TYPE_SAFE_RCU(struct css_set)7031 BTF_TYPE_SAFE_RCU(struct css_set) {
7032 	struct cgroup *dfl_cgrp;
7033 };
7034 
BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)7035 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7036 	struct cgroup *cgroup;
7037 };
7038 
7039 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)7040 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7041 	struct file __rcu *exe_file;
7042 };
7043 
7044 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7045  * because bpf prog accessible sockets are SOCK_RCU_FREE.
7046  */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)7047 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7048 	struct sock *sk;
7049 };
7050 
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)7051 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7052 	struct sock *sk;
7053 };
7054 
7055 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)7056 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7057 	struct seq_file *seq;
7058 };
7059 
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)7060 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7061 	struct bpf_iter_meta *meta;
7062 	struct task_struct *task;
7063 };
7064 
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)7065 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7066 	struct file *file;
7067 };
7068 
BTF_TYPE_SAFE_TRUSTED(struct file)7069 BTF_TYPE_SAFE_TRUSTED(struct file) {
7070 	struct inode *f_inode;
7071 };
7072 
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)7073 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7074 	struct inode *d_inode;
7075 };
7076 
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)7077 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7078 	struct sock *sk;
7079 };
7080 
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7081 static bool type_is_rcu(struct bpf_verifier_env *env,
7082 			struct bpf_reg_state *reg,
7083 			const char *field_name, u32 btf_id)
7084 {
7085 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7086 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7087 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7088 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7089 
7090 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7091 }
7092 
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7093 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7094 				struct bpf_reg_state *reg,
7095 				const char *field_name, u32 btf_id)
7096 {
7097 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7098 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7099 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7100 
7101 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7102 }
7103 
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7104 static bool type_is_trusted(struct bpf_verifier_env *env,
7105 			    struct bpf_reg_state *reg,
7106 			    const char *field_name, u32 btf_id)
7107 {
7108 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7109 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7110 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7111 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7112 
7113 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7114 }
7115 
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7116 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7117 				    struct bpf_reg_state *reg,
7118 				    const char *field_name, u32 btf_id)
7119 {
7120 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7121 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7122 
7123 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7124 					  "__safe_trusted_or_null");
7125 }
7126 
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)7127 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7128 				   struct bpf_reg_state *regs,
7129 				   int regno, int off, int size,
7130 				   enum bpf_access_type atype,
7131 				   int value_regno)
7132 {
7133 	struct bpf_reg_state *reg = regs + regno;
7134 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7135 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7136 	const char *field_name = NULL;
7137 	enum bpf_type_flag flag = 0;
7138 	u32 btf_id = 0;
7139 	int ret;
7140 
7141 	if (!env->allow_ptr_leaks) {
7142 		verbose(env,
7143 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7144 			tname);
7145 		return -EPERM;
7146 	}
7147 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7148 		verbose(env,
7149 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7150 			tname);
7151 		return -EINVAL;
7152 	}
7153 	if (off < 0) {
7154 		verbose(env,
7155 			"R%d is ptr_%s invalid negative access: off=%d\n",
7156 			regno, tname, off);
7157 		return -EACCES;
7158 	}
7159 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7160 		char tn_buf[48];
7161 
7162 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7163 		verbose(env,
7164 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7165 			regno, tname, off, tn_buf);
7166 		return -EACCES;
7167 	}
7168 
7169 	if (reg->type & MEM_USER) {
7170 		verbose(env,
7171 			"R%d is ptr_%s access user memory: off=%d\n",
7172 			regno, tname, off);
7173 		return -EACCES;
7174 	}
7175 
7176 	if (reg->type & MEM_PERCPU) {
7177 		verbose(env,
7178 			"R%d is ptr_%s access percpu memory: off=%d\n",
7179 			regno, tname, off);
7180 		return -EACCES;
7181 	}
7182 
7183 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7184 		if (!btf_is_kernel(reg->btf)) {
7185 			verifier_bug(env, "reg->btf must be kernel btf");
7186 			return -EFAULT;
7187 		}
7188 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7189 	} else {
7190 		/* Writes are permitted with default btf_struct_access for
7191 		 * program allocated objects (which always have ref_obj_id > 0),
7192 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7193 		 */
7194 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7195 			verbose(env, "only read is supported\n");
7196 			return -EACCES;
7197 		}
7198 
7199 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7200 		    !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7201 			verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7202 			return -EFAULT;
7203 		}
7204 
7205 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7206 	}
7207 
7208 	if (ret < 0)
7209 		return ret;
7210 
7211 	if (ret != PTR_TO_BTF_ID) {
7212 		/* just mark; */
7213 
7214 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7215 		/* If this is an untrusted pointer, all pointers formed by walking it
7216 		 * also inherit the untrusted flag.
7217 		 */
7218 		flag = PTR_UNTRUSTED;
7219 
7220 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7221 		/* By default any pointer obtained from walking a trusted pointer is no
7222 		 * longer trusted, unless the field being accessed has explicitly been
7223 		 * marked as inheriting its parent's state of trust (either full or RCU).
7224 		 * For example:
7225 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
7226 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
7227 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7228 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7229 		 *
7230 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
7231 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
7232 		 */
7233 		if (type_is_trusted(env, reg, field_name, btf_id)) {
7234 			flag |= PTR_TRUSTED;
7235 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7236 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7237 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7238 			if (type_is_rcu(env, reg, field_name, btf_id)) {
7239 				/* ignore __rcu tag and mark it MEM_RCU */
7240 				flag |= MEM_RCU;
7241 			} else if (flag & MEM_RCU ||
7242 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7243 				/* __rcu tagged pointers can be NULL */
7244 				flag |= MEM_RCU | PTR_MAYBE_NULL;
7245 
7246 				/* We always trust them */
7247 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7248 				    flag & PTR_UNTRUSTED)
7249 					flag &= ~PTR_UNTRUSTED;
7250 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
7251 				/* keep as-is */
7252 			} else {
7253 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7254 				clear_trusted_flags(&flag);
7255 			}
7256 		} else {
7257 			/*
7258 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
7259 			 * aggressively mark as untrusted otherwise such
7260 			 * pointers will be plain PTR_TO_BTF_ID without flags
7261 			 * and will be allowed to be passed into helpers for
7262 			 * compat reasons.
7263 			 */
7264 			flag = PTR_UNTRUSTED;
7265 		}
7266 	} else {
7267 		/* Old compat. Deprecated */
7268 		clear_trusted_flags(&flag);
7269 	}
7270 
7271 	if (atype == BPF_READ && value_regno >= 0) {
7272 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7273 		if (ret < 0)
7274 			return ret;
7275 	}
7276 
7277 	return 0;
7278 }
7279 
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)7280 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7281 				   struct bpf_reg_state *regs,
7282 				   int regno, int off, int size,
7283 				   enum bpf_access_type atype,
7284 				   int value_regno)
7285 {
7286 	struct bpf_reg_state *reg = regs + regno;
7287 	struct bpf_map *map = reg->map_ptr;
7288 	struct bpf_reg_state map_reg;
7289 	enum bpf_type_flag flag = 0;
7290 	const struct btf_type *t;
7291 	const char *tname;
7292 	u32 btf_id;
7293 	int ret;
7294 
7295 	if (!btf_vmlinux) {
7296 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7297 		return -ENOTSUPP;
7298 	}
7299 
7300 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7301 		verbose(env, "map_ptr access not supported for map type %d\n",
7302 			map->map_type);
7303 		return -ENOTSUPP;
7304 	}
7305 
7306 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7307 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7308 
7309 	if (!env->allow_ptr_leaks) {
7310 		verbose(env,
7311 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7312 			tname);
7313 		return -EPERM;
7314 	}
7315 
7316 	if (off < 0) {
7317 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
7318 			regno, tname, off);
7319 		return -EACCES;
7320 	}
7321 
7322 	if (atype != BPF_READ) {
7323 		verbose(env, "only read from %s is supported\n", tname);
7324 		return -EACCES;
7325 	}
7326 
7327 	/* Simulate access to a PTR_TO_BTF_ID */
7328 	memset(&map_reg, 0, sizeof(map_reg));
7329 	ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7330 			      btf_vmlinux, *map->ops->map_btf_id, 0);
7331 	if (ret < 0)
7332 		return ret;
7333 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7334 	if (ret < 0)
7335 		return ret;
7336 
7337 	if (value_regno >= 0) {
7338 		ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7339 		if (ret < 0)
7340 			return ret;
7341 	}
7342 
7343 	return 0;
7344 }
7345 
7346 /* Check that the stack access at the given offset is within bounds. The
7347  * maximum valid offset is -1.
7348  *
7349  * The minimum valid offset is -MAX_BPF_STACK for writes, and
7350  * -state->allocated_stack for reads.
7351  */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)7352 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7353                                           s64 off,
7354                                           struct bpf_func_state *state,
7355                                           enum bpf_access_type t)
7356 {
7357 	int min_valid_off;
7358 
7359 	if (t == BPF_WRITE || env->allow_uninit_stack)
7360 		min_valid_off = -MAX_BPF_STACK;
7361 	else
7362 		min_valid_off = -state->allocated_stack;
7363 
7364 	if (off < min_valid_off || off > -1)
7365 		return -EACCES;
7366 	return 0;
7367 }
7368 
7369 /* Check that the stack access at 'regno + off' falls within the maximum stack
7370  * bounds.
7371  *
7372  * 'off' includes `regno->offset`, but not its dynamic part (if any).
7373  */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_type type)7374 static int check_stack_access_within_bounds(
7375 		struct bpf_verifier_env *env,
7376 		int regno, int off, int access_size,
7377 		enum bpf_access_type type)
7378 {
7379 	struct bpf_reg_state *regs = cur_regs(env);
7380 	struct bpf_reg_state *reg = regs + regno;
7381 	struct bpf_func_state *state = func(env, reg);
7382 	s64 min_off, max_off;
7383 	int err;
7384 	char *err_extra;
7385 
7386 	if (type == BPF_READ)
7387 		err_extra = " read from";
7388 	else
7389 		err_extra = " write to";
7390 
7391 	if (tnum_is_const(reg->var_off)) {
7392 		min_off = (s64)reg->var_off.value + off;
7393 		max_off = min_off + access_size;
7394 	} else {
7395 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7396 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
7397 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7398 				err_extra, regno);
7399 			return -EACCES;
7400 		}
7401 		min_off = reg->smin_value + off;
7402 		max_off = reg->smax_value + off + access_size;
7403 	}
7404 
7405 	err = check_stack_slot_within_bounds(env, min_off, state, type);
7406 	if (!err && max_off > 0)
7407 		err = -EINVAL; /* out of stack access into non-negative offsets */
7408 	if (!err && access_size < 0)
7409 		/* access_size should not be negative (or overflow an int); others checks
7410 		 * along the way should have prevented such an access.
7411 		 */
7412 		err = -EFAULT; /* invalid negative access size; integer overflow? */
7413 
7414 	if (err) {
7415 		if (tnum_is_const(reg->var_off)) {
7416 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7417 				err_extra, regno, off, access_size);
7418 		} else {
7419 			char tn_buf[48];
7420 
7421 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7422 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7423 				err_extra, regno, tn_buf, off, access_size);
7424 		}
7425 		return err;
7426 	}
7427 
7428 	/* Note that there is no stack access with offset zero, so the needed stack
7429 	 * size is -min_off, not -min_off+1.
7430 	 */
7431 	return grow_stack_state(env, state, -min_off /* size */);
7432 }
7433 
get_func_retval_range(struct bpf_prog * prog,struct bpf_retval_range * range)7434 static bool get_func_retval_range(struct bpf_prog *prog,
7435 				  struct bpf_retval_range *range)
7436 {
7437 	if (prog->type == BPF_PROG_TYPE_LSM &&
7438 		prog->expected_attach_type == BPF_LSM_MAC &&
7439 		!bpf_lsm_get_retval_range(prog, range)) {
7440 		return true;
7441 	}
7442 	return false;
7443 }
7444 
7445 /* check whether memory at (regno + off) is accessible for t = (read | write)
7446  * if t==write, value_regno is a register which value is stored into memory
7447  * if t==read, value_regno is a register which will receive the value from memory
7448  * if t==write && value_regno==-1, some unknown value is stored into memory
7449  * if t==read && value_regno==-1, don't care what we read from memory
7450  */
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)7451 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7452 			    int off, int bpf_size, enum bpf_access_type t,
7453 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
7454 {
7455 	struct bpf_reg_state *regs = cur_regs(env);
7456 	struct bpf_reg_state *reg = regs + regno;
7457 	int size, err = 0;
7458 
7459 	size = bpf_size_to_bytes(bpf_size);
7460 	if (size < 0)
7461 		return size;
7462 
7463 	/* alignment checks will add in reg->off themselves */
7464 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7465 	if (err)
7466 		return err;
7467 
7468 	/* for access checks, reg->off is just part of off */
7469 	off += reg->off;
7470 
7471 	if (reg->type == PTR_TO_MAP_KEY) {
7472 		if (t == BPF_WRITE) {
7473 			verbose(env, "write to change key R%d not allowed\n", regno);
7474 			return -EACCES;
7475 		}
7476 
7477 		err = check_mem_region_access(env, regno, off, size,
7478 					      reg->map_ptr->key_size, false);
7479 		if (err)
7480 			return err;
7481 		if (value_regno >= 0)
7482 			mark_reg_unknown(env, regs, value_regno);
7483 	} else if (reg->type == PTR_TO_MAP_VALUE) {
7484 		struct btf_field *kptr_field = NULL;
7485 
7486 		if (t == BPF_WRITE && value_regno >= 0 &&
7487 		    is_pointer_value(env, value_regno)) {
7488 			verbose(env, "R%d leaks addr into map\n", value_regno);
7489 			return -EACCES;
7490 		}
7491 		err = check_map_access_type(env, regno, off, size, t);
7492 		if (err)
7493 			return err;
7494 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7495 		if (err)
7496 			return err;
7497 		if (tnum_is_const(reg->var_off))
7498 			kptr_field = btf_record_find(reg->map_ptr->record,
7499 						     off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7500 		if (kptr_field) {
7501 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7502 		} else if (t == BPF_READ && value_regno >= 0) {
7503 			struct bpf_map *map = reg->map_ptr;
7504 
7505 			/* if map is read-only, track its contents as scalars */
7506 			if (tnum_is_const(reg->var_off) &&
7507 			    bpf_map_is_rdonly(map) &&
7508 			    map->ops->map_direct_value_addr) {
7509 				int map_off = off + reg->var_off.value;
7510 				u64 val = 0;
7511 
7512 				err = bpf_map_direct_read(map, map_off, size,
7513 							  &val, is_ldsx);
7514 				if (err)
7515 					return err;
7516 
7517 				regs[value_regno].type = SCALAR_VALUE;
7518 				__mark_reg_known(&regs[value_regno], val);
7519 			} else {
7520 				mark_reg_unknown(env, regs, value_regno);
7521 			}
7522 		}
7523 	} else if (base_type(reg->type) == PTR_TO_MEM) {
7524 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7525 		bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7526 
7527 		if (type_may_be_null(reg->type)) {
7528 			verbose(env, "R%d invalid mem access '%s'\n", regno,
7529 				reg_type_str(env, reg->type));
7530 			return -EACCES;
7531 		}
7532 
7533 		if (t == BPF_WRITE && rdonly_mem) {
7534 			verbose(env, "R%d cannot write into %s\n",
7535 				regno, reg_type_str(env, reg->type));
7536 			return -EACCES;
7537 		}
7538 
7539 		if (t == BPF_WRITE && value_regno >= 0 &&
7540 		    is_pointer_value(env, value_regno)) {
7541 			verbose(env, "R%d leaks addr into mem\n", value_regno);
7542 			return -EACCES;
7543 		}
7544 
7545 		/*
7546 		 * Accesses to untrusted PTR_TO_MEM are done through probe
7547 		 * instructions, hence no need to check bounds in that case.
7548 		 */
7549 		if (!rdonly_untrusted)
7550 			err = check_mem_region_access(env, regno, off, size,
7551 						      reg->mem_size, false);
7552 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7553 			mark_reg_unknown(env, regs, value_regno);
7554 	} else if (reg->type == PTR_TO_CTX) {
7555 		struct bpf_retval_range range;
7556 		struct bpf_insn_access_aux info = {
7557 			.reg_type = SCALAR_VALUE,
7558 			.is_ldsx = is_ldsx,
7559 			.log = &env->log,
7560 		};
7561 
7562 		if (t == BPF_WRITE && value_regno >= 0 &&
7563 		    is_pointer_value(env, value_regno)) {
7564 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
7565 			return -EACCES;
7566 		}
7567 
7568 		err = check_ptr_off_reg(env, reg, regno);
7569 		if (err < 0)
7570 			return err;
7571 
7572 		err = check_ctx_access(env, insn_idx, off, size, t, &info);
7573 		if (err)
7574 			verbose_linfo(env, insn_idx, "; ");
7575 		if (!err && t == BPF_READ && value_regno >= 0) {
7576 			/* ctx access returns either a scalar, or a
7577 			 * PTR_TO_PACKET[_META,_END]. In the latter
7578 			 * case, we know the offset is zero.
7579 			 */
7580 			if (info.reg_type == SCALAR_VALUE) {
7581 				if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7582 					err = __mark_reg_s32_range(env, regs, value_regno,
7583 								   range.minval, range.maxval);
7584 					if (err)
7585 						return err;
7586 				} else {
7587 					mark_reg_unknown(env, regs, value_regno);
7588 				}
7589 			} else {
7590 				mark_reg_known_zero(env, regs,
7591 						    value_regno);
7592 				if (type_may_be_null(info.reg_type))
7593 					regs[value_regno].id = ++env->id_gen;
7594 				/* A load of ctx field could have different
7595 				 * actual load size with the one encoded in the
7596 				 * insn. When the dst is PTR, it is for sure not
7597 				 * a sub-register.
7598 				 */
7599 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7600 				if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7601 					regs[value_regno].btf = info.btf;
7602 					regs[value_regno].btf_id = info.btf_id;
7603 					regs[value_regno].ref_obj_id = info.ref_obj_id;
7604 				}
7605 			}
7606 			regs[value_regno].type = info.reg_type;
7607 		}
7608 
7609 	} else if (reg->type == PTR_TO_STACK) {
7610 		/* Basic bounds checks. */
7611 		err = check_stack_access_within_bounds(env, regno, off, size, t);
7612 		if (err)
7613 			return err;
7614 
7615 		if (t == BPF_READ)
7616 			err = check_stack_read(env, regno, off, size,
7617 					       value_regno);
7618 		else
7619 			err = check_stack_write(env, regno, off, size,
7620 						value_regno, insn_idx);
7621 	} else if (reg_is_pkt_pointer(reg)) {
7622 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7623 			verbose(env, "cannot write into packet\n");
7624 			return -EACCES;
7625 		}
7626 		if (t == BPF_WRITE && value_regno >= 0 &&
7627 		    is_pointer_value(env, value_regno)) {
7628 			verbose(env, "R%d leaks addr into packet\n",
7629 				value_regno);
7630 			return -EACCES;
7631 		}
7632 		err = check_packet_access(env, regno, off, size, false);
7633 		if (!err && t == BPF_READ && value_regno >= 0)
7634 			mark_reg_unknown(env, regs, value_regno);
7635 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
7636 		if (t == BPF_WRITE && value_regno >= 0 &&
7637 		    is_pointer_value(env, value_regno)) {
7638 			verbose(env, "R%d leaks addr into flow keys\n",
7639 				value_regno);
7640 			return -EACCES;
7641 		}
7642 
7643 		err = check_flow_keys_access(env, off, size);
7644 		if (!err && t == BPF_READ && value_regno >= 0)
7645 			mark_reg_unknown(env, regs, value_regno);
7646 	} else if (type_is_sk_pointer(reg->type)) {
7647 		if (t == BPF_WRITE) {
7648 			verbose(env, "R%d cannot write into %s\n",
7649 				regno, reg_type_str(env, reg->type));
7650 			return -EACCES;
7651 		}
7652 		err = check_sock_access(env, insn_idx, regno, off, size, t);
7653 		if (!err && value_regno >= 0)
7654 			mark_reg_unknown(env, regs, value_regno);
7655 	} else if (reg->type == PTR_TO_TP_BUFFER) {
7656 		err = check_tp_buffer_access(env, reg, regno, off, size);
7657 		if (!err && t == BPF_READ && value_regno >= 0)
7658 			mark_reg_unknown(env, regs, value_regno);
7659 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7660 		   !type_may_be_null(reg->type)) {
7661 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7662 					      value_regno);
7663 	} else if (reg->type == CONST_PTR_TO_MAP) {
7664 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7665 					      value_regno);
7666 	} else if (base_type(reg->type) == PTR_TO_BUF) {
7667 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
7668 		u32 *max_access;
7669 
7670 		if (rdonly_mem) {
7671 			if (t == BPF_WRITE) {
7672 				verbose(env, "R%d cannot write into %s\n",
7673 					regno, reg_type_str(env, reg->type));
7674 				return -EACCES;
7675 			}
7676 			max_access = &env->prog->aux->max_rdonly_access;
7677 		} else {
7678 			max_access = &env->prog->aux->max_rdwr_access;
7679 		}
7680 
7681 		err = check_buffer_access(env, reg, regno, off, size, false,
7682 					  max_access);
7683 
7684 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7685 			mark_reg_unknown(env, regs, value_regno);
7686 	} else if (reg->type == PTR_TO_ARENA) {
7687 		if (t == BPF_READ && value_regno >= 0)
7688 			mark_reg_unknown(env, regs, value_regno);
7689 	} else {
7690 		verbose(env, "R%d invalid mem access '%s'\n", regno,
7691 			reg_type_str(env, reg->type));
7692 		return -EACCES;
7693 	}
7694 
7695 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7696 	    regs[value_regno].type == SCALAR_VALUE) {
7697 		if (!is_ldsx)
7698 			/* b/h/w load zero-extends, mark upper bits as known 0 */
7699 			coerce_reg_to_size(&regs[value_regno], size);
7700 		else
7701 			coerce_reg_to_size_sx(&regs[value_regno], size);
7702 	}
7703 	return err;
7704 }
7705 
7706 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7707 			     bool allow_trust_mismatch);
7708 
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)7709 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7710 			  bool strict_alignment_once, bool is_ldsx,
7711 			  bool allow_trust_mismatch, const char *ctx)
7712 {
7713 	struct bpf_reg_state *regs = cur_regs(env);
7714 	enum bpf_reg_type src_reg_type;
7715 	int err;
7716 
7717 	/* check src operand */
7718 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7719 	if (err)
7720 		return err;
7721 
7722 	/* check dst operand */
7723 	err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7724 	if (err)
7725 		return err;
7726 
7727 	src_reg_type = regs[insn->src_reg].type;
7728 
7729 	/* Check if (src_reg + off) is readable. The state of dst_reg will be
7730 	 * updated by this call.
7731 	 */
7732 	err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7733 			       BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7734 			       strict_alignment_once, is_ldsx);
7735 	err = err ?: save_aux_ptr_type(env, src_reg_type,
7736 				       allow_trust_mismatch);
7737 	err = err ?: reg_bounds_sanity_check(env, &regs[insn->dst_reg], ctx);
7738 
7739 	return err;
7740 }
7741 
check_store_reg(struct bpf_verifier_env * env,struct bpf_insn * insn,bool strict_alignment_once)7742 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7743 			   bool strict_alignment_once)
7744 {
7745 	struct bpf_reg_state *regs = cur_regs(env);
7746 	enum bpf_reg_type dst_reg_type;
7747 	int err;
7748 
7749 	/* check src1 operand */
7750 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7751 	if (err)
7752 		return err;
7753 
7754 	/* check src2 operand */
7755 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7756 	if (err)
7757 		return err;
7758 
7759 	dst_reg_type = regs[insn->dst_reg].type;
7760 
7761 	/* Check if (dst_reg + off) is writeable. */
7762 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7763 			       BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7764 			       strict_alignment_once, false);
7765 	err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7766 
7767 	return err;
7768 }
7769 
check_atomic_rmw(struct bpf_verifier_env * env,struct bpf_insn * insn)7770 static int check_atomic_rmw(struct bpf_verifier_env *env,
7771 			    struct bpf_insn *insn)
7772 {
7773 	int load_reg;
7774 	int err;
7775 
7776 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7777 		verbose(env, "invalid atomic operand size\n");
7778 		return -EINVAL;
7779 	}
7780 
7781 	/* check src1 operand */
7782 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
7783 	if (err)
7784 		return err;
7785 
7786 	/* check src2 operand */
7787 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7788 	if (err)
7789 		return err;
7790 
7791 	if (insn->imm == BPF_CMPXCHG) {
7792 		/* Check comparison of R0 with memory location */
7793 		const u32 aux_reg = BPF_REG_0;
7794 
7795 		err = check_reg_arg(env, aux_reg, SRC_OP);
7796 		if (err)
7797 			return err;
7798 
7799 		if (is_pointer_value(env, aux_reg)) {
7800 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
7801 			return -EACCES;
7802 		}
7803 	}
7804 
7805 	if (is_pointer_value(env, insn->src_reg)) {
7806 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7807 		return -EACCES;
7808 	}
7809 
7810 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7811 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7812 			insn->dst_reg,
7813 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7814 		return -EACCES;
7815 	}
7816 
7817 	if (insn->imm & BPF_FETCH) {
7818 		if (insn->imm == BPF_CMPXCHG)
7819 			load_reg = BPF_REG_0;
7820 		else
7821 			load_reg = insn->src_reg;
7822 
7823 		/* check and record load of old value */
7824 		err = check_reg_arg(env, load_reg, DST_OP);
7825 		if (err)
7826 			return err;
7827 	} else {
7828 		/* This instruction accesses a memory location but doesn't
7829 		 * actually load it into a register.
7830 		 */
7831 		load_reg = -1;
7832 	}
7833 
7834 	/* Check whether we can read the memory, with second call for fetch
7835 	 * case to simulate the register fill.
7836 	 */
7837 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7838 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7839 	if (!err && load_reg >= 0)
7840 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7841 				       insn->off, BPF_SIZE(insn->code),
7842 				       BPF_READ, load_reg, true, false);
7843 	if (err)
7844 		return err;
7845 
7846 	if (is_arena_reg(env, insn->dst_reg)) {
7847 		err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7848 		if (err)
7849 			return err;
7850 	}
7851 	/* Check whether we can write into the same memory. */
7852 	err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7853 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7854 	if (err)
7855 		return err;
7856 	return 0;
7857 }
7858 
check_atomic_load(struct bpf_verifier_env * env,struct bpf_insn * insn)7859 static int check_atomic_load(struct bpf_verifier_env *env,
7860 			     struct bpf_insn *insn)
7861 {
7862 	int err;
7863 
7864 	err = check_load_mem(env, insn, true, false, false, "atomic_load");
7865 	if (err)
7866 		return err;
7867 
7868 	if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7869 		verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7870 			insn->src_reg,
7871 			reg_type_str(env, reg_state(env, insn->src_reg)->type));
7872 		return -EACCES;
7873 	}
7874 
7875 	return 0;
7876 }
7877 
check_atomic_store(struct bpf_verifier_env * env,struct bpf_insn * insn)7878 static int check_atomic_store(struct bpf_verifier_env *env,
7879 			      struct bpf_insn *insn)
7880 {
7881 	int err;
7882 
7883 	err = check_store_reg(env, insn, true);
7884 	if (err)
7885 		return err;
7886 
7887 	if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7888 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7889 			insn->dst_reg,
7890 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7891 		return -EACCES;
7892 	}
7893 
7894 	return 0;
7895 }
7896 
check_atomic(struct bpf_verifier_env * env,struct bpf_insn * insn)7897 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7898 {
7899 	switch (insn->imm) {
7900 	case BPF_ADD:
7901 	case BPF_ADD | BPF_FETCH:
7902 	case BPF_AND:
7903 	case BPF_AND | BPF_FETCH:
7904 	case BPF_OR:
7905 	case BPF_OR | BPF_FETCH:
7906 	case BPF_XOR:
7907 	case BPF_XOR | BPF_FETCH:
7908 	case BPF_XCHG:
7909 	case BPF_CMPXCHG:
7910 		return check_atomic_rmw(env, insn);
7911 	case BPF_LOAD_ACQ:
7912 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7913 			verbose(env,
7914 				"64-bit load-acquires are only supported on 64-bit arches\n");
7915 			return -EOPNOTSUPP;
7916 		}
7917 		return check_atomic_load(env, insn);
7918 	case BPF_STORE_REL:
7919 		if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
7920 			verbose(env,
7921 				"64-bit store-releases are only supported on 64-bit arches\n");
7922 			return -EOPNOTSUPP;
7923 		}
7924 		return check_atomic_store(env, insn);
7925 	default:
7926 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
7927 			insn->imm);
7928 		return -EINVAL;
7929 	}
7930 }
7931 
7932 /* When register 'regno' is used to read the stack (either directly or through
7933  * a helper function) make sure that it's within stack boundary and, depending
7934  * on the access type and privileges, that all elements of the stack are
7935  * initialized.
7936  *
7937  * 'off' includes 'regno->off', but not its dynamic part (if any).
7938  *
7939  * All registers that have been spilled on the stack in the slots within the
7940  * read offsets are marked as read.
7941  */
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)7942 static int check_stack_range_initialized(
7943 		struct bpf_verifier_env *env, int regno, int off,
7944 		int access_size, bool zero_size_allowed,
7945 		enum bpf_access_type type, struct bpf_call_arg_meta *meta)
7946 {
7947 	struct bpf_reg_state *reg = reg_state(env, regno);
7948 	struct bpf_func_state *state = func(env, reg);
7949 	int err, min_off, max_off, i, j, slot, spi;
7950 	/* Some accesses can write anything into the stack, others are
7951 	 * read-only.
7952 	 */
7953 	bool clobber = false;
7954 
7955 	if (access_size == 0 && !zero_size_allowed) {
7956 		verbose(env, "invalid zero-sized read\n");
7957 		return -EACCES;
7958 	}
7959 
7960 	if (type == BPF_WRITE)
7961 		clobber = true;
7962 
7963 	err = check_stack_access_within_bounds(env, regno, off, access_size, type);
7964 	if (err)
7965 		return err;
7966 
7967 
7968 	if (tnum_is_const(reg->var_off)) {
7969 		min_off = max_off = reg->var_off.value + off;
7970 	} else {
7971 		/* Variable offset is prohibited for unprivileged mode for
7972 		 * simplicity since it requires corresponding support in
7973 		 * Spectre masking for stack ALU.
7974 		 * See also retrieve_ptr_limit().
7975 		 */
7976 		if (!env->bypass_spec_v1) {
7977 			char tn_buf[48];
7978 
7979 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7980 			verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
7981 				regno, tn_buf);
7982 			return -EACCES;
7983 		}
7984 		/* Only initialized buffer on stack is allowed to be accessed
7985 		 * with variable offset. With uninitialized buffer it's hard to
7986 		 * guarantee that whole memory is marked as initialized on
7987 		 * helper return since specific bounds are unknown what may
7988 		 * cause uninitialized stack leaking.
7989 		 */
7990 		if (meta && meta->raw_mode)
7991 			meta = NULL;
7992 
7993 		min_off = reg->smin_value + off;
7994 		max_off = reg->smax_value + off;
7995 	}
7996 
7997 	if (meta && meta->raw_mode) {
7998 		/* Ensure we won't be overwriting dynptrs when simulating byte
7999 		 * by byte access in check_helper_call using meta.access_size.
8000 		 * This would be a problem if we have a helper in the future
8001 		 * which takes:
8002 		 *
8003 		 *	helper(uninit_mem, len, dynptr)
8004 		 *
8005 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8006 		 * may end up writing to dynptr itself when touching memory from
8007 		 * arg 1. This can be relaxed on a case by case basis for known
8008 		 * safe cases, but reject due to the possibilitiy of aliasing by
8009 		 * default.
8010 		 */
8011 		for (i = min_off; i < max_off + access_size; i++) {
8012 			int stack_off = -i - 1;
8013 
8014 			spi = __get_spi(i);
8015 			/* raw_mode may write past allocated_stack */
8016 			if (state->allocated_stack <= stack_off)
8017 				continue;
8018 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8019 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8020 				return -EACCES;
8021 			}
8022 		}
8023 		meta->access_size = access_size;
8024 		meta->regno = regno;
8025 		return 0;
8026 	}
8027 
8028 	for (i = min_off; i < max_off + access_size; i++) {
8029 		u8 *stype;
8030 
8031 		slot = -i - 1;
8032 		spi = slot / BPF_REG_SIZE;
8033 		if (state->allocated_stack <= slot) {
8034 			verbose(env, "allocated_stack too small\n");
8035 			return -EFAULT;
8036 		}
8037 
8038 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8039 		if (*stype == STACK_MISC)
8040 			goto mark;
8041 		if ((*stype == STACK_ZERO) ||
8042 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8043 			if (clobber) {
8044 				/* helper can write anything into the stack */
8045 				*stype = STACK_MISC;
8046 			}
8047 			goto mark;
8048 		}
8049 
8050 		if (is_spilled_reg(&state->stack[spi]) &&
8051 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8052 		     env->allow_ptr_leaks)) {
8053 			if (clobber) {
8054 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8055 				for (j = 0; j < BPF_REG_SIZE; j++)
8056 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8057 			}
8058 			goto mark;
8059 		}
8060 
8061 		if (tnum_is_const(reg->var_off)) {
8062 			verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8063 				regno, min_off, i - min_off, access_size);
8064 		} else {
8065 			char tn_buf[48];
8066 
8067 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8068 			verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8069 				regno, tn_buf, i - min_off, access_size);
8070 		}
8071 		return -EACCES;
8072 mark:
8073 		/* reading any byte out of 8-byte 'spill_slot' will cause
8074 		 * the whole slot to be marked as 'read'
8075 		 */
8076 		err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8077 		if (err)
8078 			return err;
8079 		/* We do not call bpf_mark_stack_write(), as we can not
8080 		 * be sure that whether stack slot is written to or not. Hence,
8081 		 * we must still conservatively propagate reads upwards even if
8082 		 * helper may write to the entire memory range.
8083 		 */
8084 	}
8085 	return 0;
8086 }
8087 
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)8088 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8089 				   int access_size, enum bpf_access_type access_type,
8090 				   bool zero_size_allowed,
8091 				   struct bpf_call_arg_meta *meta)
8092 {
8093 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8094 	u32 *max_access;
8095 
8096 	switch (base_type(reg->type)) {
8097 	case PTR_TO_PACKET:
8098 	case PTR_TO_PACKET_META:
8099 		return check_packet_access(env, regno, reg->off, access_size,
8100 					   zero_size_allowed);
8101 	case PTR_TO_MAP_KEY:
8102 		if (access_type == BPF_WRITE) {
8103 			verbose(env, "R%d cannot write into %s\n", regno,
8104 				reg_type_str(env, reg->type));
8105 			return -EACCES;
8106 		}
8107 		return check_mem_region_access(env, regno, reg->off, access_size,
8108 					       reg->map_ptr->key_size, false);
8109 	case PTR_TO_MAP_VALUE:
8110 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8111 			return -EACCES;
8112 		return check_map_access(env, regno, reg->off, access_size,
8113 					zero_size_allowed, ACCESS_HELPER);
8114 	case PTR_TO_MEM:
8115 		if (type_is_rdonly_mem(reg->type)) {
8116 			if (access_type == BPF_WRITE) {
8117 				verbose(env, "R%d cannot write into %s\n", regno,
8118 					reg_type_str(env, reg->type));
8119 				return -EACCES;
8120 			}
8121 		}
8122 		return check_mem_region_access(env, regno, reg->off,
8123 					       access_size, reg->mem_size,
8124 					       zero_size_allowed);
8125 	case PTR_TO_BUF:
8126 		if (type_is_rdonly_mem(reg->type)) {
8127 			if (access_type == BPF_WRITE) {
8128 				verbose(env, "R%d cannot write into %s\n", regno,
8129 					reg_type_str(env, reg->type));
8130 				return -EACCES;
8131 			}
8132 
8133 			max_access = &env->prog->aux->max_rdonly_access;
8134 		} else {
8135 			max_access = &env->prog->aux->max_rdwr_access;
8136 		}
8137 		return check_buffer_access(env, reg, regno, reg->off,
8138 					   access_size, zero_size_allowed,
8139 					   max_access);
8140 	case PTR_TO_STACK:
8141 		return check_stack_range_initialized(
8142 				env,
8143 				regno, reg->off, access_size,
8144 				zero_size_allowed, access_type, meta);
8145 	case PTR_TO_BTF_ID:
8146 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
8147 					       access_size, BPF_READ, -1);
8148 	case PTR_TO_CTX:
8149 		/* in case the function doesn't know how to access the context,
8150 		 * (because we are in a program of type SYSCALL for example), we
8151 		 * can not statically check its size.
8152 		 * Dynamically check it now.
8153 		 */
8154 		if (!env->ops->convert_ctx_access) {
8155 			int offset = access_size - 1;
8156 
8157 			/* Allow zero-byte read from PTR_TO_CTX */
8158 			if (access_size == 0)
8159 				return zero_size_allowed ? 0 : -EACCES;
8160 
8161 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8162 						access_type, -1, false, false);
8163 		}
8164 
8165 		fallthrough;
8166 	default: /* scalar_value or invalid ptr */
8167 		/* Allow zero-byte read from NULL, regardless of pointer type */
8168 		if (zero_size_allowed && access_size == 0 &&
8169 		    register_is_null(reg))
8170 			return 0;
8171 
8172 		verbose(env, "R%d type=%s ", regno,
8173 			reg_type_str(env, reg->type));
8174 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8175 		return -EACCES;
8176 	}
8177 }
8178 
8179 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8180  * size.
8181  *
8182  * @regno is the register containing the access size. regno-1 is the register
8183  * containing the pointer.
8184  */
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)8185 static int check_mem_size_reg(struct bpf_verifier_env *env,
8186 			      struct bpf_reg_state *reg, u32 regno,
8187 			      enum bpf_access_type access_type,
8188 			      bool zero_size_allowed,
8189 			      struct bpf_call_arg_meta *meta)
8190 {
8191 	int err;
8192 
8193 	/* This is used to refine r0 return value bounds for helpers
8194 	 * that enforce this value as an upper bound on return values.
8195 	 * See do_refine_retval_range() for helpers that can refine
8196 	 * the return value. C type of helper is u32 so we pull register
8197 	 * bound from umax_value however, if negative verifier errors
8198 	 * out. Only upper bounds can be learned because retval is an
8199 	 * int type and negative retvals are allowed.
8200 	 */
8201 	meta->msize_max_value = reg->umax_value;
8202 
8203 	/* The register is SCALAR_VALUE; the access check happens using
8204 	 * its boundaries. For unprivileged variable accesses, disable
8205 	 * raw mode so that the program is required to initialize all
8206 	 * the memory that the helper could just partially fill up.
8207 	 */
8208 	if (!tnum_is_const(reg->var_off))
8209 		meta = NULL;
8210 
8211 	if (reg->smin_value < 0) {
8212 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8213 			regno);
8214 		return -EACCES;
8215 	}
8216 
8217 	if (reg->umin_value == 0 && !zero_size_allowed) {
8218 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8219 			regno, reg->umin_value, reg->umax_value);
8220 		return -EACCES;
8221 	}
8222 
8223 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8224 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8225 			regno);
8226 		return -EACCES;
8227 	}
8228 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8229 				      access_type, zero_size_allowed, meta);
8230 	if (!err)
8231 		err = mark_chain_precision(env, regno);
8232 	return err;
8233 }
8234 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)8235 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8236 			 u32 regno, u32 mem_size)
8237 {
8238 	bool may_be_null = type_may_be_null(reg->type);
8239 	struct bpf_reg_state saved_reg;
8240 	int err;
8241 
8242 	if (register_is_null(reg))
8243 		return 0;
8244 
8245 	/* Assuming that the register contains a value check if the memory
8246 	 * access is safe. Temporarily save and restore the register's state as
8247 	 * the conversion shouldn't be visible to a caller.
8248 	 */
8249 	if (may_be_null) {
8250 		saved_reg = *reg;
8251 		mark_ptr_not_null_reg(reg);
8252 	}
8253 
8254 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8255 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8256 
8257 	if (may_be_null)
8258 		*reg = saved_reg;
8259 
8260 	return err;
8261 }
8262 
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)8263 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8264 				    u32 regno)
8265 {
8266 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8267 	bool may_be_null = type_may_be_null(mem_reg->type);
8268 	struct bpf_reg_state saved_reg;
8269 	struct bpf_call_arg_meta meta;
8270 	int err;
8271 
8272 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8273 
8274 	memset(&meta, 0, sizeof(meta));
8275 
8276 	if (may_be_null) {
8277 		saved_reg = *mem_reg;
8278 		mark_ptr_not_null_reg(mem_reg);
8279 	}
8280 
8281 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8282 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8283 
8284 	if (may_be_null)
8285 		*mem_reg = saved_reg;
8286 
8287 	return err;
8288 }
8289 
8290 enum {
8291 	PROCESS_SPIN_LOCK = (1 << 0),
8292 	PROCESS_RES_LOCK  = (1 << 1),
8293 	PROCESS_LOCK_IRQ  = (1 << 2),
8294 };
8295 
8296 /* Implementation details:
8297  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8298  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8299  * Two bpf_map_lookups (even with the same key) will have different reg->id.
8300  * Two separate bpf_obj_new will also have different reg->id.
8301  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8302  * clears reg->id after value_or_null->value transition, since the verifier only
8303  * cares about the range of access to valid map value pointer and doesn't care
8304  * about actual address of the map element.
8305  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8306  * reg->id > 0 after value_or_null->value transition. By doing so
8307  * two bpf_map_lookups will be considered two different pointers that
8308  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8309  * returned from bpf_obj_new.
8310  * The verifier allows taking only one bpf_spin_lock at a time to avoid
8311  * dead-locks.
8312  * Since only one bpf_spin_lock is allowed the checks are simpler than
8313  * reg_is_refcounted() logic. The verifier needs to remember only
8314  * one spin_lock instead of array of acquired_refs.
8315  * env->cur_state->active_locks remembers which map value element or allocated
8316  * object got locked and clears it after bpf_spin_unlock.
8317  */
process_spin_lock(struct bpf_verifier_env * env,int regno,int flags)8318 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8319 {
8320 	bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8321 	const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8322 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8323 	struct bpf_verifier_state *cur = env->cur_state;
8324 	bool is_const = tnum_is_const(reg->var_off);
8325 	bool is_irq = flags & PROCESS_LOCK_IRQ;
8326 	u64 val = reg->var_off.value;
8327 	struct bpf_map *map = NULL;
8328 	struct btf *btf = NULL;
8329 	struct btf_record *rec;
8330 	u32 spin_lock_off;
8331 	int err;
8332 
8333 	if (!is_const) {
8334 		verbose(env,
8335 			"R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8336 			regno, lock_str);
8337 		return -EINVAL;
8338 	}
8339 	if (reg->type == PTR_TO_MAP_VALUE) {
8340 		map = reg->map_ptr;
8341 		if (!map->btf) {
8342 			verbose(env,
8343 				"map '%s' has to have BTF in order to use %s_lock\n",
8344 				map->name, lock_str);
8345 			return -EINVAL;
8346 		}
8347 	} else {
8348 		btf = reg->btf;
8349 	}
8350 
8351 	rec = reg_btf_record(reg);
8352 	if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8353 		verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8354 			map ? map->name : "kptr", lock_str);
8355 		return -EINVAL;
8356 	}
8357 	spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8358 	if (spin_lock_off != val + reg->off) {
8359 		verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8360 			val + reg->off, lock_str, spin_lock_off);
8361 		return -EINVAL;
8362 	}
8363 	if (is_lock) {
8364 		void *ptr;
8365 		int type;
8366 
8367 		if (map)
8368 			ptr = map;
8369 		else
8370 			ptr = btf;
8371 
8372 		if (!is_res_lock && cur->active_locks) {
8373 			if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8374 				verbose(env,
8375 					"Locking two bpf_spin_locks are not allowed\n");
8376 				return -EINVAL;
8377 			}
8378 		} else if (is_res_lock && cur->active_locks) {
8379 			if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8380 				verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8381 				return -EINVAL;
8382 			}
8383 		}
8384 
8385 		if (is_res_lock && is_irq)
8386 			type = REF_TYPE_RES_LOCK_IRQ;
8387 		else if (is_res_lock)
8388 			type = REF_TYPE_RES_LOCK;
8389 		else
8390 			type = REF_TYPE_LOCK;
8391 		err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8392 		if (err < 0) {
8393 			verbose(env, "Failed to acquire lock state\n");
8394 			return err;
8395 		}
8396 	} else {
8397 		void *ptr;
8398 		int type;
8399 
8400 		if (map)
8401 			ptr = map;
8402 		else
8403 			ptr = btf;
8404 
8405 		if (!cur->active_locks) {
8406 			verbose(env, "%s_unlock without taking a lock\n", lock_str);
8407 			return -EINVAL;
8408 		}
8409 
8410 		if (is_res_lock && is_irq)
8411 			type = REF_TYPE_RES_LOCK_IRQ;
8412 		else if (is_res_lock)
8413 			type = REF_TYPE_RES_LOCK;
8414 		else
8415 			type = REF_TYPE_LOCK;
8416 		if (!find_lock_state(cur, type, reg->id, ptr)) {
8417 			verbose(env, "%s_unlock of different lock\n", lock_str);
8418 			return -EINVAL;
8419 		}
8420 		if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8421 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8422 			return -EINVAL;
8423 		}
8424 		if (release_lock_state(cur, type, reg->id, ptr)) {
8425 			verbose(env, "%s_unlock of different lock\n", lock_str);
8426 			return -EINVAL;
8427 		}
8428 
8429 		invalidate_non_owning_refs(env);
8430 	}
8431 	return 0;
8432 }
8433 
8434 /* Check if @regno is a pointer to a specific field in a map value */
check_map_field_pointer(struct bpf_verifier_env * env,u32 regno,enum btf_field_type field_type)8435 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8436 				   enum btf_field_type field_type)
8437 {
8438 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8439 	bool is_const = tnum_is_const(reg->var_off);
8440 	struct bpf_map *map = reg->map_ptr;
8441 	u64 val = reg->var_off.value;
8442 	const char *struct_name = btf_field_type_name(field_type);
8443 	int field_off = -1;
8444 
8445 	if (!is_const) {
8446 		verbose(env,
8447 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
8448 			regno, struct_name);
8449 		return -EINVAL;
8450 	}
8451 	if (!map->btf) {
8452 		verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8453 			struct_name);
8454 		return -EINVAL;
8455 	}
8456 	if (!btf_record_has_field(map->record, field_type)) {
8457 		verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8458 		return -EINVAL;
8459 	}
8460 	switch (field_type) {
8461 	case BPF_TIMER:
8462 		field_off = map->record->timer_off;
8463 		break;
8464 	case BPF_TASK_WORK:
8465 		field_off = map->record->task_work_off;
8466 		break;
8467 	default:
8468 		verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8469 		return -EINVAL;
8470 	}
8471 	if (field_off != val + reg->off) {
8472 		verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8473 			val + reg->off, struct_name, field_off);
8474 		return -EINVAL;
8475 	}
8476 	return 0;
8477 }
8478 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)8479 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8480 			      struct bpf_call_arg_meta *meta)
8481 {
8482 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8483 	struct bpf_map *map = reg->map_ptr;
8484 	int err;
8485 
8486 	err = check_map_field_pointer(env, regno, BPF_TIMER);
8487 	if (err)
8488 		return err;
8489 
8490 	if (meta->map_ptr) {
8491 		verifier_bug(env, "Two map pointers in a timer helper");
8492 		return -EFAULT;
8493 	}
8494 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8495 		verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8496 		return -EOPNOTSUPP;
8497 	}
8498 	meta->map_uid = reg->map_uid;
8499 	meta->map_ptr = map;
8500 	return 0;
8501 }
8502 
process_wq_func(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)8503 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8504 			   struct bpf_kfunc_call_arg_meta *meta)
8505 {
8506 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8507 	struct bpf_map *map = reg->map_ptr;
8508 	u64 val = reg->var_off.value;
8509 
8510 	if (map->record->wq_off != val + reg->off) {
8511 		verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n",
8512 			val + reg->off, map->record->wq_off);
8513 		return -EINVAL;
8514 	}
8515 	meta->map.uid = reg->map_uid;
8516 	meta->map.ptr = map;
8517 	return 0;
8518 }
8519 
process_task_work_func(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)8520 static int process_task_work_func(struct bpf_verifier_env *env, int regno,
8521 				  struct bpf_kfunc_call_arg_meta *meta)
8522 {
8523 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8524 	struct bpf_map *map = reg->map_ptr;
8525 	int err;
8526 
8527 	err = check_map_field_pointer(env, regno, BPF_TASK_WORK);
8528 	if (err)
8529 		return err;
8530 
8531 	if (meta->map.ptr) {
8532 		verifier_bug(env, "Two map pointers in a bpf_task_work helper");
8533 		return -EFAULT;
8534 	}
8535 	meta->map.uid = reg->map_uid;
8536 	meta->map.ptr = map;
8537 	return 0;
8538 }
8539 
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)8540 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8541 			     struct bpf_call_arg_meta *meta)
8542 {
8543 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8544 	struct btf_field *kptr_field;
8545 	struct bpf_map *map_ptr;
8546 	struct btf_record *rec;
8547 	u32 kptr_off;
8548 
8549 	if (type_is_ptr_alloc_obj(reg->type)) {
8550 		rec = reg_btf_record(reg);
8551 	} else { /* PTR_TO_MAP_VALUE */
8552 		map_ptr = reg->map_ptr;
8553 		if (!map_ptr->btf) {
8554 			verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8555 				map_ptr->name);
8556 			return -EINVAL;
8557 		}
8558 		rec = map_ptr->record;
8559 		meta->map_ptr = map_ptr;
8560 	}
8561 
8562 	if (!tnum_is_const(reg->var_off)) {
8563 		verbose(env,
8564 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8565 			regno);
8566 		return -EINVAL;
8567 	}
8568 
8569 	if (!btf_record_has_field(rec, BPF_KPTR)) {
8570 		verbose(env, "R%d has no valid kptr\n", regno);
8571 		return -EINVAL;
8572 	}
8573 
8574 	kptr_off = reg->off + reg->var_off.value;
8575 	kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8576 	if (!kptr_field) {
8577 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8578 		return -EACCES;
8579 	}
8580 	if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8581 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8582 		return -EACCES;
8583 	}
8584 	meta->kptr_field = kptr_field;
8585 	return 0;
8586 }
8587 
8588 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8589  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8590  *
8591  * In both cases we deal with the first 8 bytes, but need to mark the next 8
8592  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8593  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8594  *
8595  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8596  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8597  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8598  * mutate the view of the dynptr and also possibly destroy it. In the latter
8599  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8600  * memory that dynptr points to.
8601  *
8602  * The verifier will keep track both levels of mutation (bpf_dynptr's in
8603  * reg->type and the memory's in reg->dynptr.type), but there is no support for
8604  * readonly dynptr view yet, hence only the first case is tracked and checked.
8605  *
8606  * This is consistent with how C applies the const modifier to a struct object,
8607  * where the pointer itself inside bpf_dynptr becomes const but not what it
8608  * points to.
8609  *
8610  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8611  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8612  */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)8613 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8614 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
8615 {
8616 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8617 	int err;
8618 
8619 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8620 		verbose(env,
8621 			"arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8622 			regno - 1);
8623 		return -EINVAL;
8624 	}
8625 
8626 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8627 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8628 	 */
8629 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8630 		verifier_bug(env, "misconfigured dynptr helper type flags");
8631 		return -EFAULT;
8632 	}
8633 
8634 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
8635 	 *		 constructing a mutable bpf_dynptr object.
8636 	 *
8637 	 *		 Currently, this is only possible with PTR_TO_STACK
8638 	 *		 pointing to a region of at least 16 bytes which doesn't
8639 	 *		 contain an existing bpf_dynptr.
8640 	 *
8641 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8642 	 *		 mutated or destroyed. However, the memory it points to
8643 	 *		 may be mutated.
8644 	 *
8645 	 *  None       - Points to a initialized dynptr that can be mutated and
8646 	 *		 destroyed, including mutation of the memory it points
8647 	 *		 to.
8648 	 */
8649 	if (arg_type & MEM_UNINIT) {
8650 		int i;
8651 
8652 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
8653 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8654 			return -EINVAL;
8655 		}
8656 
8657 		/* we write BPF_DW bits (8 bytes) at a time */
8658 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8659 			err = check_mem_access(env, insn_idx, regno,
8660 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8661 			if (err)
8662 				return err;
8663 		}
8664 
8665 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8666 	} else /* MEM_RDONLY and None case from above */ {
8667 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8668 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8669 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8670 			return -EINVAL;
8671 		}
8672 
8673 		if (!is_dynptr_reg_valid_init(env, reg)) {
8674 			verbose(env,
8675 				"Expected an initialized dynptr as arg #%d\n",
8676 				regno - 1);
8677 			return -EINVAL;
8678 		}
8679 
8680 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8681 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8682 			verbose(env,
8683 				"Expected a dynptr of type %s as arg #%d\n",
8684 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8685 			return -EINVAL;
8686 		}
8687 
8688 		err = mark_dynptr_read(env, reg);
8689 	}
8690 	return err;
8691 }
8692 
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)8693 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8694 {
8695 	struct bpf_func_state *state = func(env, reg);
8696 
8697 	return state->stack[spi].spilled_ptr.ref_obj_id;
8698 }
8699 
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)8700 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8701 {
8702 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8703 }
8704 
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)8705 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8706 {
8707 	return meta->kfunc_flags & KF_ITER_NEW;
8708 }
8709 
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)8710 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8711 {
8712 	return meta->kfunc_flags & KF_ITER_NEXT;
8713 }
8714 
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)8715 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8716 {
8717 	return meta->kfunc_flags & KF_ITER_DESTROY;
8718 }
8719 
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg_idx,const struct btf_param * arg)8720 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8721 			      const struct btf_param *arg)
8722 {
8723 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
8724 	 * kfunc is iter state pointer
8725 	 */
8726 	if (is_iter_kfunc(meta))
8727 		return arg_idx == 0;
8728 
8729 	/* iter passed as an argument to a generic kfunc */
8730 	return btf_param_match_suffix(meta->btf, arg, "__iter");
8731 }
8732 
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)8733 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8734 			    struct bpf_kfunc_call_arg_meta *meta)
8735 {
8736 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8737 	const struct btf_type *t;
8738 	int spi, err, i, nr_slots, btf_id;
8739 
8740 	if (reg->type != PTR_TO_STACK) {
8741 		verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8742 		return -EINVAL;
8743 	}
8744 
8745 	/* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8746 	 * ensures struct convention, so we wouldn't need to do any BTF
8747 	 * validation here. But given iter state can be passed as a parameter
8748 	 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8749 	 * conservative here.
8750 	 */
8751 	btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8752 	if (btf_id < 0) {
8753 		verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8754 		return -EINVAL;
8755 	}
8756 	t = btf_type_by_id(meta->btf, btf_id);
8757 	nr_slots = t->size / BPF_REG_SIZE;
8758 
8759 	if (is_iter_new_kfunc(meta)) {
8760 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
8761 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8762 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8763 				iter_type_str(meta->btf, btf_id), regno - 1);
8764 			return -EINVAL;
8765 		}
8766 
8767 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8768 			err = check_mem_access(env, insn_idx, regno,
8769 					       i, BPF_DW, BPF_WRITE, -1, false, false);
8770 			if (err)
8771 				return err;
8772 		}
8773 
8774 		err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8775 		if (err)
8776 			return err;
8777 	} else {
8778 		/* iter_next() or iter_destroy(), as well as any kfunc
8779 		 * accepting iter argument, expect initialized iter state
8780 		 */
8781 		err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8782 		switch (err) {
8783 		case 0:
8784 			break;
8785 		case -EINVAL:
8786 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
8787 				iter_type_str(meta->btf, btf_id), regno - 1);
8788 			return err;
8789 		case -EPROTO:
8790 			verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8791 			return err;
8792 		default:
8793 			return err;
8794 		}
8795 
8796 		spi = iter_get_spi(env, reg, nr_slots);
8797 		if (spi < 0)
8798 			return spi;
8799 
8800 		err = mark_iter_read(env, reg, spi, nr_slots);
8801 		if (err)
8802 			return err;
8803 
8804 		/* remember meta->iter info for process_iter_next_call() */
8805 		meta->iter.spi = spi;
8806 		meta->iter.frameno = reg->frameno;
8807 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8808 
8809 		if (is_iter_destroy_kfunc(meta)) {
8810 			err = unmark_stack_slots_iter(env, reg, nr_slots);
8811 			if (err)
8812 				return err;
8813 		}
8814 	}
8815 
8816 	return 0;
8817 }
8818 
8819 /* Look for a previous loop entry at insn_idx: nearest parent state
8820  * stopped at insn_idx with callsites matching those in cur->frame.
8821  */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)8822 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8823 						  struct bpf_verifier_state *cur,
8824 						  int insn_idx)
8825 {
8826 	struct bpf_verifier_state_list *sl;
8827 	struct bpf_verifier_state *st;
8828 	struct list_head *pos, *head;
8829 
8830 	/* Explored states are pushed in stack order, most recent states come first */
8831 	head = explored_state(env, insn_idx);
8832 	list_for_each(pos, head) {
8833 		sl = container_of(pos, struct bpf_verifier_state_list, node);
8834 		/* If st->branches != 0 state is a part of current DFS verification path,
8835 		 * hence cur & st for a loop.
8836 		 */
8837 		st = &sl->state;
8838 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8839 		    st->dfs_depth < cur->dfs_depth)
8840 			return st;
8841 	}
8842 
8843 	return NULL;
8844 }
8845 
8846 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8847 static bool regs_exact(const struct bpf_reg_state *rold,
8848 		       const struct bpf_reg_state *rcur,
8849 		       struct bpf_idmap *idmap);
8850 
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)8851 static void maybe_widen_reg(struct bpf_verifier_env *env,
8852 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8853 			    struct bpf_idmap *idmap)
8854 {
8855 	if (rold->type != SCALAR_VALUE)
8856 		return;
8857 	if (rold->type != rcur->type)
8858 		return;
8859 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8860 		return;
8861 	__mark_reg_unknown(env, rcur);
8862 }
8863 
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)8864 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8865 				   struct bpf_verifier_state *old,
8866 				   struct bpf_verifier_state *cur)
8867 {
8868 	struct bpf_func_state *fold, *fcur;
8869 	int i, fr, num_slots;
8870 
8871 	reset_idmap_scratch(env);
8872 	for (fr = old->curframe; fr >= 0; fr--) {
8873 		fold = old->frame[fr];
8874 		fcur = cur->frame[fr];
8875 
8876 		for (i = 0; i < MAX_BPF_REG; i++)
8877 			maybe_widen_reg(env,
8878 					&fold->regs[i],
8879 					&fcur->regs[i],
8880 					&env->idmap_scratch);
8881 
8882 		num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
8883 				fcur->allocated_stack / BPF_REG_SIZE);
8884 		for (i = 0; i < num_slots; i++) {
8885 			if (!is_spilled_reg(&fold->stack[i]) ||
8886 			    !is_spilled_reg(&fcur->stack[i]))
8887 				continue;
8888 
8889 			maybe_widen_reg(env,
8890 					&fold->stack[i].spilled_ptr,
8891 					&fcur->stack[i].spilled_ptr,
8892 					&env->idmap_scratch);
8893 		}
8894 	}
8895 	return 0;
8896 }
8897 
get_iter_from_state(struct bpf_verifier_state * cur_st,struct bpf_kfunc_call_arg_meta * meta)8898 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8899 						 struct bpf_kfunc_call_arg_meta *meta)
8900 {
8901 	int iter_frameno = meta->iter.frameno;
8902 	int iter_spi = meta->iter.spi;
8903 
8904 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8905 }
8906 
8907 /* process_iter_next_call() is called when verifier gets to iterator's next
8908  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
8909  * to it as just "iter_next()" in comments below.
8910  *
8911  * BPF verifier relies on a crucial contract for any iter_next()
8912  * implementation: it should *eventually* return NULL, and once that happens
8913  * it should keep returning NULL. That is, once iterator exhausts elements to
8914  * iterate, it should never reset or spuriously return new elements.
8915  *
8916  * With the assumption of such contract, process_iter_next_call() simulates
8917  * a fork in the verifier state to validate loop logic correctness and safety
8918  * without having to simulate infinite amount of iterations.
8919  *
8920  * In current state, we first assume that iter_next() returned NULL and
8921  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
8922  * conditions we should not form an infinite loop and should eventually reach
8923  * exit.
8924  *
8925  * Besides that, we also fork current state and enqueue it for later
8926  * verification. In a forked state we keep iterator state as ACTIVE
8927  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
8928  * also bump iteration depth to prevent erroneous infinite loop detection
8929  * later on (see iter_active_depths_differ() comment for details). In this
8930  * state we assume that we'll eventually loop back to another iter_next()
8931  * calls (it could be in exactly same location or in some other instruction,
8932  * it doesn't matter, we don't make any unnecessary assumptions about this,
8933  * everything revolves around iterator state in a stack slot, not which
8934  * instruction is calling iter_next()). When that happens, we either will come
8935  * to iter_next() with equivalent state and can conclude that next iteration
8936  * will proceed in exactly the same way as we just verified, so it's safe to
8937  * assume that loop converges. If not, we'll go on another iteration
8938  * simulation with a different input state, until all possible starting states
8939  * are validated or we reach maximum number of instructions limit.
8940  *
8941  * This way, we will either exhaustively discover all possible input states
8942  * that iterator loop can start with and eventually will converge, or we'll
8943  * effectively regress into bounded loop simulation logic and either reach
8944  * maximum number of instructions if loop is not provably convergent, or there
8945  * is some statically known limit on number of iterations (e.g., if there is
8946  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8947  *
8948  * Iteration convergence logic in is_state_visited() relies on exact
8949  * states comparison, which ignores read and precision marks.
8950  * This is necessary because read and precision marks are not finalized
8951  * while in the loop. Exact comparison might preclude convergence for
8952  * simple programs like below:
8953  *
8954  *     i = 0;
8955  *     while(iter_next(&it))
8956  *       i++;
8957  *
8958  * At each iteration step i++ would produce a new distinct state and
8959  * eventually instruction processing limit would be reached.
8960  *
8961  * To avoid such behavior speculatively forget (widen) range for
8962  * imprecise scalar registers, if those registers were not precise at the
8963  * end of the previous iteration and do not match exactly.
8964  *
8965  * This is a conservative heuristic that allows to verify wide range of programs,
8966  * however it precludes verification of programs that conjure an
8967  * imprecise value on the first loop iteration and use it as precise on a second.
8968  * For example, the following safe program would fail to verify:
8969  *
8970  *     struct bpf_num_iter it;
8971  *     int arr[10];
8972  *     int i = 0, a = 0;
8973  *     bpf_iter_num_new(&it, 0, 10);
8974  *     while (bpf_iter_num_next(&it)) {
8975  *       if (a == 0) {
8976  *         a = 1;
8977  *         i = 7; // Because i changed verifier would forget
8978  *                // it's range on second loop entry.
8979  *       } else {
8980  *         arr[i] = 42; // This would fail to verify.
8981  *       }
8982  *     }
8983  *     bpf_iter_num_destroy(&it);
8984  */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)8985 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8986 				  struct bpf_kfunc_call_arg_meta *meta)
8987 {
8988 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8989 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8990 	struct bpf_reg_state *cur_iter, *queued_iter;
8991 
8992 	BTF_TYPE_EMIT(struct bpf_iter);
8993 
8994 	cur_iter = get_iter_from_state(cur_st, meta);
8995 
8996 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8997 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8998 		verifier_bug(env, "unexpected iterator state %d (%s)",
8999 			     cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9000 		return -EFAULT;
9001 	}
9002 
9003 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9004 		/* Because iter_next() call is a checkpoint is_state_visitied()
9005 		 * should guarantee parent state with same call sites and insn_idx.
9006 		 */
9007 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9008 		    !same_callsites(cur_st->parent, cur_st)) {
9009 			verifier_bug(env, "bad parent state for iter next call");
9010 			return -EFAULT;
9011 		}
9012 		/* Note cur_st->parent in the call below, it is necessary to skip
9013 		 * checkpoint created for cur_st by is_state_visited()
9014 		 * right at this instruction.
9015 		 */
9016 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9017 		/* branch out active iter state */
9018 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9019 		if (!queued_st)
9020 			return -ENOMEM;
9021 
9022 		queued_iter = get_iter_from_state(queued_st, meta);
9023 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9024 		queued_iter->iter.depth++;
9025 		if (prev_st)
9026 			widen_imprecise_scalars(env, prev_st, queued_st);
9027 
9028 		queued_fr = queued_st->frame[queued_st->curframe];
9029 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9030 	}
9031 
9032 	/* switch to DRAINED state, but keep the depth unchanged */
9033 	/* mark current iter state as drained and assume returned NULL */
9034 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9035 	__mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9036 
9037 	return 0;
9038 }
9039 
arg_type_is_mem_size(enum bpf_arg_type type)9040 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9041 {
9042 	return type == ARG_CONST_SIZE ||
9043 	       type == ARG_CONST_SIZE_OR_ZERO;
9044 }
9045 
arg_type_is_raw_mem(enum bpf_arg_type type)9046 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9047 {
9048 	return base_type(type) == ARG_PTR_TO_MEM &&
9049 	       type & MEM_UNINIT;
9050 }
9051 
arg_type_is_release(enum bpf_arg_type type)9052 static bool arg_type_is_release(enum bpf_arg_type type)
9053 {
9054 	return type & OBJ_RELEASE;
9055 }
9056 
arg_type_is_dynptr(enum bpf_arg_type type)9057 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9058 {
9059 	return base_type(type) == ARG_PTR_TO_DYNPTR;
9060 }
9061 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)9062 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9063 				 const struct bpf_call_arg_meta *meta,
9064 				 enum bpf_arg_type *arg_type)
9065 {
9066 	if (!meta->map_ptr) {
9067 		/* kernel subsystem misconfigured verifier */
9068 		verifier_bug(env, "invalid map_ptr to access map->type");
9069 		return -EFAULT;
9070 	}
9071 
9072 	switch (meta->map_ptr->map_type) {
9073 	case BPF_MAP_TYPE_SOCKMAP:
9074 	case BPF_MAP_TYPE_SOCKHASH:
9075 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9076 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9077 		} else {
9078 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
9079 			return -EINVAL;
9080 		}
9081 		break;
9082 	case BPF_MAP_TYPE_BLOOM_FILTER:
9083 		if (meta->func_id == BPF_FUNC_map_peek_elem)
9084 			*arg_type = ARG_PTR_TO_MAP_VALUE;
9085 		break;
9086 	default:
9087 		break;
9088 	}
9089 	return 0;
9090 }
9091 
9092 struct bpf_reg_types {
9093 	const enum bpf_reg_type types[10];
9094 	u32 *btf_id;
9095 };
9096 
9097 static const struct bpf_reg_types sock_types = {
9098 	.types = {
9099 		PTR_TO_SOCK_COMMON,
9100 		PTR_TO_SOCKET,
9101 		PTR_TO_TCP_SOCK,
9102 		PTR_TO_XDP_SOCK,
9103 	},
9104 };
9105 
9106 #ifdef CONFIG_NET
9107 static const struct bpf_reg_types btf_id_sock_common_types = {
9108 	.types = {
9109 		PTR_TO_SOCK_COMMON,
9110 		PTR_TO_SOCKET,
9111 		PTR_TO_TCP_SOCK,
9112 		PTR_TO_XDP_SOCK,
9113 		PTR_TO_BTF_ID,
9114 		PTR_TO_BTF_ID | PTR_TRUSTED,
9115 	},
9116 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9117 };
9118 #endif
9119 
9120 static const struct bpf_reg_types mem_types = {
9121 	.types = {
9122 		PTR_TO_STACK,
9123 		PTR_TO_PACKET,
9124 		PTR_TO_PACKET_META,
9125 		PTR_TO_MAP_KEY,
9126 		PTR_TO_MAP_VALUE,
9127 		PTR_TO_MEM,
9128 		PTR_TO_MEM | MEM_RINGBUF,
9129 		PTR_TO_BUF,
9130 		PTR_TO_BTF_ID | PTR_TRUSTED,
9131 	},
9132 };
9133 
9134 static const struct bpf_reg_types spin_lock_types = {
9135 	.types = {
9136 		PTR_TO_MAP_VALUE,
9137 		PTR_TO_BTF_ID | MEM_ALLOC,
9138 	}
9139 };
9140 
9141 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9142 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9143 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9144 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9145 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9146 static const struct bpf_reg_types btf_ptr_types = {
9147 	.types = {
9148 		PTR_TO_BTF_ID,
9149 		PTR_TO_BTF_ID | PTR_TRUSTED,
9150 		PTR_TO_BTF_ID | MEM_RCU,
9151 	},
9152 };
9153 static const struct bpf_reg_types percpu_btf_ptr_types = {
9154 	.types = {
9155 		PTR_TO_BTF_ID | MEM_PERCPU,
9156 		PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9157 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9158 	}
9159 };
9160 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9161 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9162 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9163 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9164 static const struct bpf_reg_types kptr_xchg_dest_types = {
9165 	.types = {
9166 		PTR_TO_MAP_VALUE,
9167 		PTR_TO_BTF_ID | MEM_ALLOC
9168 	}
9169 };
9170 static const struct bpf_reg_types dynptr_types = {
9171 	.types = {
9172 		PTR_TO_STACK,
9173 		CONST_PTR_TO_DYNPTR,
9174 	}
9175 };
9176 
9177 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9178 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
9179 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
9180 	[ARG_CONST_SIZE]		= &scalar_types,
9181 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
9182 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
9183 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
9184 	[ARG_PTR_TO_CTX]		= &context_types,
9185 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
9186 #ifdef CONFIG_NET
9187 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
9188 #endif
9189 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
9190 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
9191 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
9192 	[ARG_PTR_TO_MEM]		= &mem_types,
9193 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
9194 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
9195 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
9196 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
9197 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
9198 	[ARG_PTR_TO_TIMER]		= &timer_types,
9199 	[ARG_KPTR_XCHG_DEST]		= &kptr_xchg_dest_types,
9200 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
9201 };
9202 
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)9203 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9204 			  enum bpf_arg_type arg_type,
9205 			  const u32 *arg_btf_id,
9206 			  struct bpf_call_arg_meta *meta)
9207 {
9208 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9209 	enum bpf_reg_type expected, type = reg->type;
9210 	const struct bpf_reg_types *compatible;
9211 	int i, j;
9212 
9213 	compatible = compatible_reg_types[base_type(arg_type)];
9214 	if (!compatible) {
9215 		verifier_bug(env, "unsupported arg type %d", arg_type);
9216 		return -EFAULT;
9217 	}
9218 
9219 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9220 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9221 	 *
9222 	 * Same for MAYBE_NULL:
9223 	 *
9224 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9225 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9226 	 *
9227 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9228 	 *
9229 	 * Therefore we fold these flags depending on the arg_type before comparison.
9230 	 */
9231 	if (arg_type & MEM_RDONLY)
9232 		type &= ~MEM_RDONLY;
9233 	if (arg_type & PTR_MAYBE_NULL)
9234 		type &= ~PTR_MAYBE_NULL;
9235 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
9236 		type &= ~DYNPTR_TYPE_FLAG_MASK;
9237 
9238 	/* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9239 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9240 		type &= ~MEM_ALLOC;
9241 		type &= ~MEM_PERCPU;
9242 	}
9243 
9244 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9245 		expected = compatible->types[i];
9246 		if (expected == NOT_INIT)
9247 			break;
9248 
9249 		if (type == expected)
9250 			goto found;
9251 	}
9252 
9253 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9254 	for (j = 0; j + 1 < i; j++)
9255 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9256 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9257 	return -EACCES;
9258 
9259 found:
9260 	if (base_type(reg->type) != PTR_TO_BTF_ID)
9261 		return 0;
9262 
9263 	if (compatible == &mem_types) {
9264 		if (!(arg_type & MEM_RDONLY)) {
9265 			verbose(env,
9266 				"%s() may write into memory pointed by R%d type=%s\n",
9267 				func_id_name(meta->func_id),
9268 				regno, reg_type_str(env, reg->type));
9269 			return -EACCES;
9270 		}
9271 		return 0;
9272 	}
9273 
9274 	switch ((int)reg->type) {
9275 	case PTR_TO_BTF_ID:
9276 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9277 	case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9278 	case PTR_TO_BTF_ID | MEM_RCU:
9279 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9280 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9281 	{
9282 		/* For bpf_sk_release, it needs to match against first member
9283 		 * 'struct sock_common', hence make an exception for it. This
9284 		 * allows bpf_sk_release to work for multiple socket types.
9285 		 */
9286 		bool strict_type_match = arg_type_is_release(arg_type) &&
9287 					 meta->func_id != BPF_FUNC_sk_release;
9288 
9289 		if (type_may_be_null(reg->type) &&
9290 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9291 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9292 			return -EACCES;
9293 		}
9294 
9295 		if (!arg_btf_id) {
9296 			if (!compatible->btf_id) {
9297 				verifier_bug(env, "missing arg compatible BTF ID");
9298 				return -EFAULT;
9299 			}
9300 			arg_btf_id = compatible->btf_id;
9301 		}
9302 
9303 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
9304 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9305 				return -EACCES;
9306 		} else {
9307 			if (arg_btf_id == BPF_PTR_POISON) {
9308 				verbose(env, "verifier internal error:");
9309 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9310 					regno);
9311 				return -EACCES;
9312 			}
9313 
9314 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9315 						  btf_vmlinux, *arg_btf_id,
9316 						  strict_type_match)) {
9317 				verbose(env, "R%d is of type %s but %s is expected\n",
9318 					regno, btf_type_name(reg->btf, reg->btf_id),
9319 					btf_type_name(btf_vmlinux, *arg_btf_id));
9320 				return -EACCES;
9321 			}
9322 		}
9323 		break;
9324 	}
9325 	case PTR_TO_BTF_ID | MEM_ALLOC:
9326 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9327 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9328 		    meta->func_id != BPF_FUNC_kptr_xchg) {
9329 			verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9330 			return -EFAULT;
9331 		}
9332 		/* Check if local kptr in src arg matches kptr in dst arg */
9333 		if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9334 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9335 				return -EACCES;
9336 		}
9337 		break;
9338 	case PTR_TO_BTF_ID | MEM_PERCPU:
9339 	case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9340 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9341 		/* Handled by helper specific checks */
9342 		break;
9343 	default:
9344 		verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9345 		return -EFAULT;
9346 	}
9347 	return 0;
9348 }
9349 
9350 static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)9351 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9352 {
9353 	struct btf_field *field;
9354 	struct btf_record *rec;
9355 
9356 	rec = reg_btf_record(reg);
9357 	if (!rec)
9358 		return NULL;
9359 
9360 	field = btf_record_find(rec, off, fields);
9361 	if (!field)
9362 		return NULL;
9363 
9364 	return field;
9365 }
9366 
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)9367 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9368 				  const struct bpf_reg_state *reg, int regno,
9369 				  enum bpf_arg_type arg_type)
9370 {
9371 	u32 type = reg->type;
9372 
9373 	/* When referenced register is passed to release function, its fixed
9374 	 * offset must be 0.
9375 	 *
9376 	 * We will check arg_type_is_release reg has ref_obj_id when storing
9377 	 * meta->release_regno.
9378 	 */
9379 	if (arg_type_is_release(arg_type)) {
9380 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9381 		 * may not directly point to the object being released, but to
9382 		 * dynptr pointing to such object, which might be at some offset
9383 		 * on the stack. In that case, we simply to fallback to the
9384 		 * default handling.
9385 		 */
9386 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9387 			return 0;
9388 
9389 		/* Doing check_ptr_off_reg check for the offset will catch this
9390 		 * because fixed_off_ok is false, but checking here allows us
9391 		 * to give the user a better error message.
9392 		 */
9393 		if (reg->off) {
9394 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9395 				regno);
9396 			return -EINVAL;
9397 		}
9398 		return __check_ptr_off_reg(env, reg, regno, false);
9399 	}
9400 
9401 	switch (type) {
9402 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
9403 	case PTR_TO_STACK:
9404 	case PTR_TO_PACKET:
9405 	case PTR_TO_PACKET_META:
9406 	case PTR_TO_MAP_KEY:
9407 	case PTR_TO_MAP_VALUE:
9408 	case PTR_TO_MEM:
9409 	case PTR_TO_MEM | MEM_RDONLY:
9410 	case PTR_TO_MEM | MEM_RINGBUF:
9411 	case PTR_TO_BUF:
9412 	case PTR_TO_BUF | MEM_RDONLY:
9413 	case PTR_TO_ARENA:
9414 	case SCALAR_VALUE:
9415 		return 0;
9416 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9417 	 * fixed offset.
9418 	 */
9419 	case PTR_TO_BTF_ID:
9420 	case PTR_TO_BTF_ID | MEM_ALLOC:
9421 	case PTR_TO_BTF_ID | PTR_TRUSTED:
9422 	case PTR_TO_BTF_ID | MEM_RCU:
9423 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9424 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9425 		/* When referenced PTR_TO_BTF_ID is passed to release function,
9426 		 * its fixed offset must be 0. In the other cases, fixed offset
9427 		 * can be non-zero. This was already checked above. So pass
9428 		 * fixed_off_ok as true to allow fixed offset for all other
9429 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9430 		 * still need to do checks instead of returning.
9431 		 */
9432 		return __check_ptr_off_reg(env, reg, regno, true);
9433 	default:
9434 		return __check_ptr_off_reg(env, reg, regno, false);
9435 	}
9436 }
9437 
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)9438 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9439 						const struct bpf_func_proto *fn,
9440 						struct bpf_reg_state *regs)
9441 {
9442 	struct bpf_reg_state *state = NULL;
9443 	int i;
9444 
9445 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9446 		if (arg_type_is_dynptr(fn->arg_type[i])) {
9447 			if (state) {
9448 				verbose(env, "verifier internal error: multiple dynptr args\n");
9449 				return NULL;
9450 			}
9451 			state = &regs[BPF_REG_1 + i];
9452 		}
9453 
9454 	if (!state)
9455 		verbose(env, "verifier internal error: no dynptr arg found\n");
9456 
9457 	return state;
9458 }
9459 
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9460 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9461 {
9462 	struct bpf_func_state *state = func(env, reg);
9463 	int spi;
9464 
9465 	if (reg->type == CONST_PTR_TO_DYNPTR)
9466 		return reg->id;
9467 	spi = dynptr_get_spi(env, reg);
9468 	if (spi < 0)
9469 		return spi;
9470 	return state->stack[spi].spilled_ptr.id;
9471 }
9472 
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9473 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9474 {
9475 	struct bpf_func_state *state = func(env, reg);
9476 	int spi;
9477 
9478 	if (reg->type == CONST_PTR_TO_DYNPTR)
9479 		return reg->ref_obj_id;
9480 	spi = dynptr_get_spi(env, reg);
9481 	if (spi < 0)
9482 		return spi;
9483 	return state->stack[spi].spilled_ptr.ref_obj_id;
9484 }
9485 
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9486 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9487 					    struct bpf_reg_state *reg)
9488 {
9489 	struct bpf_func_state *state = func(env, reg);
9490 	int spi;
9491 
9492 	if (reg->type == CONST_PTR_TO_DYNPTR)
9493 		return reg->dynptr.type;
9494 
9495 	spi = __get_spi(reg->off);
9496 	if (spi < 0) {
9497 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9498 		return BPF_DYNPTR_TYPE_INVALID;
9499 	}
9500 
9501 	return state->stack[spi].spilled_ptr.dynptr.type;
9502 }
9503 
check_reg_const_str(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)9504 static int check_reg_const_str(struct bpf_verifier_env *env,
9505 			       struct bpf_reg_state *reg, u32 regno)
9506 {
9507 	struct bpf_map *map = reg->map_ptr;
9508 	int err;
9509 	int map_off;
9510 	u64 map_addr;
9511 	char *str_ptr;
9512 
9513 	if (reg->type != PTR_TO_MAP_VALUE)
9514 		return -EINVAL;
9515 
9516 	if (!bpf_map_is_rdonly(map)) {
9517 		verbose(env, "R%d does not point to a readonly map'\n", regno);
9518 		return -EACCES;
9519 	}
9520 
9521 	if (!tnum_is_const(reg->var_off)) {
9522 		verbose(env, "R%d is not a constant address'\n", regno);
9523 		return -EACCES;
9524 	}
9525 
9526 	if (!map->ops->map_direct_value_addr) {
9527 		verbose(env, "no direct value access support for this map type\n");
9528 		return -EACCES;
9529 	}
9530 
9531 	err = check_map_access(env, regno, reg->off,
9532 			       map->value_size - reg->off, false,
9533 			       ACCESS_HELPER);
9534 	if (err)
9535 		return err;
9536 
9537 	map_off = reg->off + reg->var_off.value;
9538 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9539 	if (err) {
9540 		verbose(env, "direct value access on string failed\n");
9541 		return err;
9542 	}
9543 
9544 	str_ptr = (char *)(long)(map_addr);
9545 	if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9546 		verbose(env, "string is not zero-terminated\n");
9547 		return -EINVAL;
9548 	}
9549 	return 0;
9550 }
9551 
9552 /* 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)9553 static int get_constant_map_key(struct bpf_verifier_env *env,
9554 				struct bpf_reg_state *key,
9555 				u32 key_size,
9556 				s64 *value)
9557 {
9558 	struct bpf_func_state *state = func(env, key);
9559 	struct bpf_reg_state *reg;
9560 	int slot, spi, off;
9561 	int spill_size = 0;
9562 	int zero_size = 0;
9563 	int stack_off;
9564 	int i, err;
9565 	u8 *stype;
9566 
9567 	if (!env->bpf_capable)
9568 		return -EOPNOTSUPP;
9569 	if (key->type != PTR_TO_STACK)
9570 		return -EOPNOTSUPP;
9571 	if (!tnum_is_const(key->var_off))
9572 		return -EOPNOTSUPP;
9573 
9574 	stack_off = key->off + key->var_off.value;
9575 	slot = -stack_off - 1;
9576 	spi = slot / BPF_REG_SIZE;
9577 	off = slot % BPF_REG_SIZE;
9578 	stype = state->stack[spi].slot_type;
9579 
9580 	/* First handle precisely tracked STACK_ZERO */
9581 	for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9582 		zero_size++;
9583 	if (zero_size >= key_size) {
9584 		*value = 0;
9585 		return 0;
9586 	}
9587 
9588 	/* Check that stack contains a scalar spill of expected size */
9589 	if (!is_spilled_scalar_reg(&state->stack[spi]))
9590 		return -EOPNOTSUPP;
9591 	for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9592 		spill_size++;
9593 	if (spill_size != key_size)
9594 		return -EOPNOTSUPP;
9595 
9596 	reg = &state->stack[spi].spilled_ptr;
9597 	if (!tnum_is_const(reg->var_off))
9598 		/* Stack value not statically known */
9599 		return -EOPNOTSUPP;
9600 
9601 	/* We are relying on a constant value. So mark as precise
9602 	 * to prevent pruning on it.
9603 	 */
9604 	bt_set_frame_slot(&env->bt, key->frameno, spi);
9605 	err = mark_chain_precision_batch(env, env->cur_state);
9606 	if (err < 0)
9607 		return err;
9608 
9609 	*value = reg->var_off.value;
9610 	return 0;
9611 }
9612 
9613 static bool can_elide_value_nullness(enum bpf_map_type type);
9614 
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)9615 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9616 			  struct bpf_call_arg_meta *meta,
9617 			  const struct bpf_func_proto *fn,
9618 			  int insn_idx)
9619 {
9620 	u32 regno = BPF_REG_1 + arg;
9621 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
9622 	enum bpf_arg_type arg_type = fn->arg_type[arg];
9623 	enum bpf_reg_type type = reg->type;
9624 	u32 *arg_btf_id = NULL;
9625 	u32 key_size;
9626 	int err = 0;
9627 
9628 	if (arg_type == ARG_DONTCARE)
9629 		return 0;
9630 
9631 	err = check_reg_arg(env, regno, SRC_OP);
9632 	if (err)
9633 		return err;
9634 
9635 	if (arg_type == ARG_ANYTHING) {
9636 		if (is_pointer_value(env, regno)) {
9637 			verbose(env, "R%d leaks addr into helper function\n",
9638 				regno);
9639 			return -EACCES;
9640 		}
9641 		return 0;
9642 	}
9643 
9644 	if (type_is_pkt_pointer(type) &&
9645 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9646 		verbose(env, "helper access to the packet is not allowed\n");
9647 		return -EACCES;
9648 	}
9649 
9650 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9651 		err = resolve_map_arg_type(env, meta, &arg_type);
9652 		if (err)
9653 			return err;
9654 	}
9655 
9656 	if (register_is_null(reg) && type_may_be_null(arg_type))
9657 		/* A NULL register has a SCALAR_VALUE type, so skip
9658 		 * type checking.
9659 		 */
9660 		goto skip_type_check;
9661 
9662 	/* arg_btf_id and arg_size are in a union. */
9663 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9664 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9665 		arg_btf_id = fn->arg_btf_id[arg];
9666 
9667 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9668 	if (err)
9669 		return err;
9670 
9671 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
9672 	if (err)
9673 		return err;
9674 
9675 skip_type_check:
9676 	if (arg_type_is_release(arg_type)) {
9677 		if (arg_type_is_dynptr(arg_type)) {
9678 			struct bpf_func_state *state = func(env, reg);
9679 			int spi;
9680 
9681 			/* Only dynptr created on stack can be released, thus
9682 			 * the get_spi and stack state checks for spilled_ptr
9683 			 * should only be done before process_dynptr_func for
9684 			 * PTR_TO_STACK.
9685 			 */
9686 			if (reg->type == PTR_TO_STACK) {
9687 				spi = dynptr_get_spi(env, reg);
9688 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9689 					verbose(env, "arg %d is an unacquired reference\n", regno);
9690 					return -EINVAL;
9691 				}
9692 			} else {
9693 				verbose(env, "cannot release unowned const bpf_dynptr\n");
9694 				return -EINVAL;
9695 			}
9696 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
9697 			verbose(env, "R%d must be referenced when passed to release function\n",
9698 				regno);
9699 			return -EINVAL;
9700 		}
9701 		if (meta->release_regno) {
9702 			verifier_bug(env, "more than one release argument");
9703 			return -EFAULT;
9704 		}
9705 		meta->release_regno = regno;
9706 	}
9707 
9708 	if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9709 		if (meta->ref_obj_id) {
9710 			verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9711 				regno, reg->ref_obj_id,
9712 				meta->ref_obj_id);
9713 			return -EACCES;
9714 		}
9715 		meta->ref_obj_id = reg->ref_obj_id;
9716 	}
9717 
9718 	switch (base_type(arg_type)) {
9719 	case ARG_CONST_MAP_PTR:
9720 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9721 		if (meta->map_ptr) {
9722 			/* Use map_uid (which is unique id of inner map) to reject:
9723 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9724 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9725 			 * if (inner_map1 && inner_map2) {
9726 			 *     timer = bpf_map_lookup_elem(inner_map1);
9727 			 *     if (timer)
9728 			 *         // mismatch would have been allowed
9729 			 *         bpf_timer_init(timer, inner_map2);
9730 			 * }
9731 			 *
9732 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
9733 			 */
9734 			if (meta->map_ptr != reg->map_ptr ||
9735 			    meta->map_uid != reg->map_uid) {
9736 				verbose(env,
9737 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9738 					meta->map_uid, reg->map_uid);
9739 				return -EINVAL;
9740 			}
9741 		}
9742 		meta->map_ptr = reg->map_ptr;
9743 		meta->map_uid = reg->map_uid;
9744 		break;
9745 	case ARG_PTR_TO_MAP_KEY:
9746 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
9747 		 * check that [key, key + map->key_size) are within
9748 		 * stack limits and initialized
9749 		 */
9750 		if (!meta->map_ptr) {
9751 			/* in function declaration map_ptr must come before
9752 			 * map_key, so that it's verified and known before
9753 			 * we have to check map_key here. Otherwise it means
9754 			 * that kernel subsystem misconfigured verifier
9755 			 */
9756 			verifier_bug(env, "invalid map_ptr to access map->key");
9757 			return -EFAULT;
9758 		}
9759 		key_size = meta->map_ptr->key_size;
9760 		err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9761 		if (err)
9762 			return err;
9763 		if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9764 			err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9765 			if (err < 0) {
9766 				meta->const_map_key = -1;
9767 				if (err == -EOPNOTSUPP)
9768 					err = 0;
9769 				else
9770 					return err;
9771 			}
9772 		}
9773 		break;
9774 	case ARG_PTR_TO_MAP_VALUE:
9775 		if (type_may_be_null(arg_type) && register_is_null(reg))
9776 			return 0;
9777 
9778 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
9779 		 * check [value, value + map->value_size) validity
9780 		 */
9781 		if (!meta->map_ptr) {
9782 			/* kernel subsystem misconfigured verifier */
9783 			verifier_bug(env, "invalid map_ptr to access map->value");
9784 			return -EFAULT;
9785 		}
9786 		meta->raw_mode = arg_type & MEM_UNINIT;
9787 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9788 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9789 					      false, meta);
9790 		break;
9791 	case ARG_PTR_TO_PERCPU_BTF_ID:
9792 		if (!reg->btf_id) {
9793 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9794 			return -EACCES;
9795 		}
9796 		meta->ret_btf = reg->btf;
9797 		meta->ret_btf_id = reg->btf_id;
9798 		break;
9799 	case ARG_PTR_TO_SPIN_LOCK:
9800 		if (in_rbtree_lock_required_cb(env)) {
9801 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9802 			return -EACCES;
9803 		}
9804 		if (meta->func_id == BPF_FUNC_spin_lock) {
9805 			err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9806 			if (err)
9807 				return err;
9808 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
9809 			err = process_spin_lock(env, regno, 0);
9810 			if (err)
9811 				return err;
9812 		} else {
9813 			verifier_bug(env, "spin lock arg on unexpected helper");
9814 			return -EFAULT;
9815 		}
9816 		break;
9817 	case ARG_PTR_TO_TIMER:
9818 		err = process_timer_func(env, regno, meta);
9819 		if (err)
9820 			return err;
9821 		break;
9822 	case ARG_PTR_TO_FUNC:
9823 		meta->subprogno = reg->subprogno;
9824 		break;
9825 	case ARG_PTR_TO_MEM:
9826 		/* The access to this pointer is only checked when we hit the
9827 		 * next is_mem_size argument below.
9828 		 */
9829 		meta->raw_mode = arg_type & MEM_UNINIT;
9830 		if (arg_type & MEM_FIXED_SIZE) {
9831 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9832 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9833 						      false, meta);
9834 			if (err)
9835 				return err;
9836 			if (arg_type & MEM_ALIGNED)
9837 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9838 		}
9839 		break;
9840 	case ARG_CONST_SIZE:
9841 		err = check_mem_size_reg(env, reg, regno,
9842 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9843 					 BPF_WRITE : BPF_READ,
9844 					 false, meta);
9845 		break;
9846 	case ARG_CONST_SIZE_OR_ZERO:
9847 		err = check_mem_size_reg(env, reg, regno,
9848 					 fn->arg_type[arg - 1] & MEM_WRITE ?
9849 					 BPF_WRITE : BPF_READ,
9850 					 true, meta);
9851 		break;
9852 	case ARG_PTR_TO_DYNPTR:
9853 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9854 		if (err)
9855 			return err;
9856 		break;
9857 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9858 		if (!tnum_is_const(reg->var_off)) {
9859 			verbose(env, "R%d is not a known constant'\n",
9860 				regno);
9861 			return -EACCES;
9862 		}
9863 		meta->mem_size = reg->var_off.value;
9864 		err = mark_chain_precision(env, regno);
9865 		if (err)
9866 			return err;
9867 		break;
9868 	case ARG_PTR_TO_CONST_STR:
9869 	{
9870 		err = check_reg_const_str(env, reg, regno);
9871 		if (err)
9872 			return err;
9873 		break;
9874 	}
9875 	case ARG_KPTR_XCHG_DEST:
9876 		err = process_kptr_func(env, regno, meta);
9877 		if (err)
9878 			return err;
9879 		break;
9880 	}
9881 
9882 	return err;
9883 }
9884 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)9885 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9886 {
9887 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
9888 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9889 
9890 	if (func_id != BPF_FUNC_map_update_elem &&
9891 	    func_id != BPF_FUNC_map_delete_elem)
9892 		return false;
9893 
9894 	/* It's not possible to get access to a locked struct sock in these
9895 	 * contexts, so updating is safe.
9896 	 */
9897 	switch (type) {
9898 	case BPF_PROG_TYPE_TRACING:
9899 		if (eatype == BPF_TRACE_ITER)
9900 			return true;
9901 		break;
9902 	case BPF_PROG_TYPE_SOCK_OPS:
9903 		/* map_update allowed only via dedicated helpers with event type checks */
9904 		if (func_id == BPF_FUNC_map_delete_elem)
9905 			return true;
9906 		break;
9907 	case BPF_PROG_TYPE_SOCKET_FILTER:
9908 	case BPF_PROG_TYPE_SCHED_CLS:
9909 	case BPF_PROG_TYPE_SCHED_ACT:
9910 	case BPF_PROG_TYPE_XDP:
9911 	case BPF_PROG_TYPE_SK_REUSEPORT:
9912 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
9913 	case BPF_PROG_TYPE_SK_LOOKUP:
9914 		return true;
9915 	default:
9916 		break;
9917 	}
9918 
9919 	verbose(env, "cannot update sockmap in this context\n");
9920 	return false;
9921 }
9922 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)9923 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
9924 {
9925 	return env->prog->jit_requested &&
9926 	       bpf_jit_supports_subprog_tailcalls();
9927 }
9928 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)9929 static int check_map_func_compatibility(struct bpf_verifier_env *env,
9930 					struct bpf_map *map, int func_id)
9931 {
9932 	if (!map)
9933 		return 0;
9934 
9935 	/* We need a two way check, first is from map perspective ... */
9936 	switch (map->map_type) {
9937 	case BPF_MAP_TYPE_PROG_ARRAY:
9938 		if (func_id != BPF_FUNC_tail_call)
9939 			goto error;
9940 		break;
9941 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
9942 		if (func_id != BPF_FUNC_perf_event_read &&
9943 		    func_id != BPF_FUNC_perf_event_output &&
9944 		    func_id != BPF_FUNC_skb_output &&
9945 		    func_id != BPF_FUNC_perf_event_read_value &&
9946 		    func_id != BPF_FUNC_xdp_output)
9947 			goto error;
9948 		break;
9949 	case BPF_MAP_TYPE_RINGBUF:
9950 		if (func_id != BPF_FUNC_ringbuf_output &&
9951 		    func_id != BPF_FUNC_ringbuf_reserve &&
9952 		    func_id != BPF_FUNC_ringbuf_query &&
9953 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
9954 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
9955 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
9956 			goto error;
9957 		break;
9958 	case BPF_MAP_TYPE_USER_RINGBUF:
9959 		if (func_id != BPF_FUNC_user_ringbuf_drain)
9960 			goto error;
9961 		break;
9962 	case BPF_MAP_TYPE_STACK_TRACE:
9963 		if (func_id != BPF_FUNC_get_stackid)
9964 			goto error;
9965 		break;
9966 	case BPF_MAP_TYPE_CGROUP_ARRAY:
9967 		if (func_id != BPF_FUNC_skb_under_cgroup &&
9968 		    func_id != BPF_FUNC_current_task_under_cgroup)
9969 			goto error;
9970 		break;
9971 	case BPF_MAP_TYPE_CGROUP_STORAGE:
9972 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
9973 		if (func_id != BPF_FUNC_get_local_storage)
9974 			goto error;
9975 		break;
9976 	case BPF_MAP_TYPE_DEVMAP:
9977 	case BPF_MAP_TYPE_DEVMAP_HASH:
9978 		if (func_id != BPF_FUNC_redirect_map &&
9979 		    func_id != BPF_FUNC_map_lookup_elem)
9980 			goto error;
9981 		break;
9982 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
9983 	 * appear.
9984 	 */
9985 	case BPF_MAP_TYPE_CPUMAP:
9986 		if (func_id != BPF_FUNC_redirect_map)
9987 			goto error;
9988 		break;
9989 	case BPF_MAP_TYPE_XSKMAP:
9990 		if (func_id != BPF_FUNC_redirect_map &&
9991 		    func_id != BPF_FUNC_map_lookup_elem)
9992 			goto error;
9993 		break;
9994 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
9995 	case BPF_MAP_TYPE_HASH_OF_MAPS:
9996 		if (func_id != BPF_FUNC_map_lookup_elem)
9997 			goto error;
9998 		break;
9999 	case BPF_MAP_TYPE_SOCKMAP:
10000 		if (func_id != BPF_FUNC_sk_redirect_map &&
10001 		    func_id != BPF_FUNC_sock_map_update &&
10002 		    func_id != BPF_FUNC_msg_redirect_map &&
10003 		    func_id != BPF_FUNC_sk_select_reuseport &&
10004 		    func_id != BPF_FUNC_map_lookup_elem &&
10005 		    !may_update_sockmap(env, func_id))
10006 			goto error;
10007 		break;
10008 	case BPF_MAP_TYPE_SOCKHASH:
10009 		if (func_id != BPF_FUNC_sk_redirect_hash &&
10010 		    func_id != BPF_FUNC_sock_hash_update &&
10011 		    func_id != BPF_FUNC_msg_redirect_hash &&
10012 		    func_id != BPF_FUNC_sk_select_reuseport &&
10013 		    func_id != BPF_FUNC_map_lookup_elem &&
10014 		    !may_update_sockmap(env, func_id))
10015 			goto error;
10016 		break;
10017 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10018 		if (func_id != BPF_FUNC_sk_select_reuseport)
10019 			goto error;
10020 		break;
10021 	case BPF_MAP_TYPE_QUEUE:
10022 	case BPF_MAP_TYPE_STACK:
10023 		if (func_id != BPF_FUNC_map_peek_elem &&
10024 		    func_id != BPF_FUNC_map_pop_elem &&
10025 		    func_id != BPF_FUNC_map_push_elem)
10026 			goto error;
10027 		break;
10028 	case BPF_MAP_TYPE_SK_STORAGE:
10029 		if (func_id != BPF_FUNC_sk_storage_get &&
10030 		    func_id != BPF_FUNC_sk_storage_delete &&
10031 		    func_id != BPF_FUNC_kptr_xchg)
10032 			goto error;
10033 		break;
10034 	case BPF_MAP_TYPE_INODE_STORAGE:
10035 		if (func_id != BPF_FUNC_inode_storage_get &&
10036 		    func_id != BPF_FUNC_inode_storage_delete &&
10037 		    func_id != BPF_FUNC_kptr_xchg)
10038 			goto error;
10039 		break;
10040 	case BPF_MAP_TYPE_TASK_STORAGE:
10041 		if (func_id != BPF_FUNC_task_storage_get &&
10042 		    func_id != BPF_FUNC_task_storage_delete &&
10043 		    func_id != BPF_FUNC_kptr_xchg)
10044 			goto error;
10045 		break;
10046 	case BPF_MAP_TYPE_CGRP_STORAGE:
10047 		if (func_id != BPF_FUNC_cgrp_storage_get &&
10048 		    func_id != BPF_FUNC_cgrp_storage_delete &&
10049 		    func_id != BPF_FUNC_kptr_xchg)
10050 			goto error;
10051 		break;
10052 	case BPF_MAP_TYPE_BLOOM_FILTER:
10053 		if (func_id != BPF_FUNC_map_peek_elem &&
10054 		    func_id != BPF_FUNC_map_push_elem)
10055 			goto error;
10056 		break;
10057 	default:
10058 		break;
10059 	}
10060 
10061 	/* ... and second from the function itself. */
10062 	switch (func_id) {
10063 	case BPF_FUNC_tail_call:
10064 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10065 			goto error;
10066 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10067 			verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10068 			return -EINVAL;
10069 		}
10070 		break;
10071 	case BPF_FUNC_perf_event_read:
10072 	case BPF_FUNC_perf_event_output:
10073 	case BPF_FUNC_perf_event_read_value:
10074 	case BPF_FUNC_skb_output:
10075 	case BPF_FUNC_xdp_output:
10076 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10077 			goto error;
10078 		break;
10079 	case BPF_FUNC_ringbuf_output:
10080 	case BPF_FUNC_ringbuf_reserve:
10081 	case BPF_FUNC_ringbuf_query:
10082 	case BPF_FUNC_ringbuf_reserve_dynptr:
10083 	case BPF_FUNC_ringbuf_submit_dynptr:
10084 	case BPF_FUNC_ringbuf_discard_dynptr:
10085 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10086 			goto error;
10087 		break;
10088 	case BPF_FUNC_user_ringbuf_drain:
10089 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10090 			goto error;
10091 		break;
10092 	case BPF_FUNC_get_stackid:
10093 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10094 			goto error;
10095 		break;
10096 	case BPF_FUNC_current_task_under_cgroup:
10097 	case BPF_FUNC_skb_under_cgroup:
10098 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10099 			goto error;
10100 		break;
10101 	case BPF_FUNC_redirect_map:
10102 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10103 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10104 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
10105 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
10106 			goto error;
10107 		break;
10108 	case BPF_FUNC_sk_redirect_map:
10109 	case BPF_FUNC_msg_redirect_map:
10110 	case BPF_FUNC_sock_map_update:
10111 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10112 			goto error;
10113 		break;
10114 	case BPF_FUNC_sk_redirect_hash:
10115 	case BPF_FUNC_msg_redirect_hash:
10116 	case BPF_FUNC_sock_hash_update:
10117 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10118 			goto error;
10119 		break;
10120 	case BPF_FUNC_get_local_storage:
10121 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10122 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10123 			goto error;
10124 		break;
10125 	case BPF_FUNC_sk_select_reuseport:
10126 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10127 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10128 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
10129 			goto error;
10130 		break;
10131 	case BPF_FUNC_map_pop_elem:
10132 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10133 		    map->map_type != BPF_MAP_TYPE_STACK)
10134 			goto error;
10135 		break;
10136 	case BPF_FUNC_map_peek_elem:
10137 	case BPF_FUNC_map_push_elem:
10138 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10139 		    map->map_type != BPF_MAP_TYPE_STACK &&
10140 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10141 			goto error;
10142 		break;
10143 	case BPF_FUNC_map_lookup_percpu_elem:
10144 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10145 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10146 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10147 			goto error;
10148 		break;
10149 	case BPF_FUNC_sk_storage_get:
10150 	case BPF_FUNC_sk_storage_delete:
10151 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10152 			goto error;
10153 		break;
10154 	case BPF_FUNC_inode_storage_get:
10155 	case BPF_FUNC_inode_storage_delete:
10156 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10157 			goto error;
10158 		break;
10159 	case BPF_FUNC_task_storage_get:
10160 	case BPF_FUNC_task_storage_delete:
10161 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10162 			goto error;
10163 		break;
10164 	case BPF_FUNC_cgrp_storage_get:
10165 	case BPF_FUNC_cgrp_storage_delete:
10166 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10167 			goto error;
10168 		break;
10169 	default:
10170 		break;
10171 	}
10172 
10173 	return 0;
10174 error:
10175 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
10176 		map->map_type, func_id_name(func_id), func_id);
10177 	return -EINVAL;
10178 }
10179 
check_raw_mode_ok(const struct bpf_func_proto * fn)10180 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10181 {
10182 	int count = 0;
10183 
10184 	if (arg_type_is_raw_mem(fn->arg1_type))
10185 		count++;
10186 	if (arg_type_is_raw_mem(fn->arg2_type))
10187 		count++;
10188 	if (arg_type_is_raw_mem(fn->arg3_type))
10189 		count++;
10190 	if (arg_type_is_raw_mem(fn->arg4_type))
10191 		count++;
10192 	if (arg_type_is_raw_mem(fn->arg5_type))
10193 		count++;
10194 
10195 	/* We only support one arg being in raw mode at the moment,
10196 	 * which is sufficient for the helper functions we have
10197 	 * right now.
10198 	 */
10199 	return count <= 1;
10200 }
10201 
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)10202 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10203 {
10204 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10205 	bool has_size = fn->arg_size[arg] != 0;
10206 	bool is_next_size = false;
10207 
10208 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10209 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10210 
10211 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10212 		return is_next_size;
10213 
10214 	return has_size == is_next_size || is_next_size == is_fixed;
10215 }
10216 
check_arg_pair_ok(const struct bpf_func_proto * fn)10217 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10218 {
10219 	/* bpf_xxx(..., buf, len) call will access 'len'
10220 	 * bytes from memory 'buf'. Both arg types need
10221 	 * to be paired, so make sure there's no buggy
10222 	 * helper function specification.
10223 	 */
10224 	if (arg_type_is_mem_size(fn->arg1_type) ||
10225 	    check_args_pair_invalid(fn, 0) ||
10226 	    check_args_pair_invalid(fn, 1) ||
10227 	    check_args_pair_invalid(fn, 2) ||
10228 	    check_args_pair_invalid(fn, 3) ||
10229 	    check_args_pair_invalid(fn, 4))
10230 		return false;
10231 
10232 	return true;
10233 }
10234 
check_btf_id_ok(const struct bpf_func_proto * fn)10235 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10236 {
10237 	int i;
10238 
10239 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10240 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10241 			return !!fn->arg_btf_id[i];
10242 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10243 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
10244 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10245 		    /* arg_btf_id and arg_size are in a union. */
10246 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10247 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10248 			return false;
10249 	}
10250 
10251 	return true;
10252 }
10253 
check_func_proto(const struct bpf_func_proto * fn,int func_id)10254 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10255 {
10256 	return check_raw_mode_ok(fn) &&
10257 	       check_arg_pair_ok(fn) &&
10258 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
10259 }
10260 
10261 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10262  * are now invalid, so turn them into unknown SCALAR_VALUE.
10263  *
10264  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10265  * since these slices point to packet data.
10266  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)10267 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10268 {
10269 	struct bpf_func_state *state;
10270 	struct bpf_reg_state *reg;
10271 
10272 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10273 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10274 			mark_reg_invalid(env, reg);
10275 	}));
10276 }
10277 
10278 enum {
10279 	AT_PKT_END = -1,
10280 	BEYOND_PKT_END = -2,
10281 };
10282 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)10283 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10284 {
10285 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10286 	struct bpf_reg_state *reg = &state->regs[regn];
10287 
10288 	if (reg->type != PTR_TO_PACKET)
10289 		/* PTR_TO_PACKET_META is not supported yet */
10290 		return;
10291 
10292 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10293 	 * How far beyond pkt_end it goes is unknown.
10294 	 * if (!range_open) it's the case of pkt >= pkt_end
10295 	 * if (range_open) it's the case of pkt > pkt_end
10296 	 * hence this pointer is at least 1 byte bigger than pkt_end
10297 	 */
10298 	if (range_open)
10299 		reg->range = BEYOND_PKT_END;
10300 	else
10301 		reg->range = AT_PKT_END;
10302 }
10303 
release_reference_nomark(struct bpf_verifier_state * state,int ref_obj_id)10304 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10305 {
10306 	int i;
10307 
10308 	for (i = 0; i < state->acquired_refs; i++) {
10309 		if (state->refs[i].type != REF_TYPE_PTR)
10310 			continue;
10311 		if (state->refs[i].id == ref_obj_id) {
10312 			release_reference_state(state, i);
10313 			return 0;
10314 		}
10315 	}
10316 	return -EINVAL;
10317 }
10318 
10319 /* The pointer with the specified id has released its reference to kernel
10320  * resources. Identify all copies of the same pointer and clear the reference.
10321  *
10322  * This is the release function corresponding to acquire_reference(). Idempotent.
10323  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)10324 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10325 {
10326 	struct bpf_verifier_state *vstate = env->cur_state;
10327 	struct bpf_func_state *state;
10328 	struct bpf_reg_state *reg;
10329 	int err;
10330 
10331 	err = release_reference_nomark(vstate, ref_obj_id);
10332 	if (err)
10333 		return err;
10334 
10335 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10336 		if (reg->ref_obj_id == ref_obj_id)
10337 			mark_reg_invalid(env, reg);
10338 	}));
10339 
10340 	return 0;
10341 }
10342 
invalidate_non_owning_refs(struct bpf_verifier_env * env)10343 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10344 {
10345 	struct bpf_func_state *unused;
10346 	struct bpf_reg_state *reg;
10347 
10348 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10349 		if (type_is_non_owning_ref(reg->type))
10350 			mark_reg_invalid(env, reg);
10351 	}));
10352 }
10353 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)10354 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10355 				    struct bpf_reg_state *regs)
10356 {
10357 	int i;
10358 
10359 	/* after the call registers r0 - r5 were scratched */
10360 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10361 		mark_reg_not_init(env, regs, caller_saved[i]);
10362 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10363 	}
10364 }
10365 
10366 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10367 				   struct bpf_func_state *caller,
10368 				   struct bpf_func_state *callee,
10369 				   int insn_idx);
10370 
10371 static bool is_task_work_add_kfunc(u32 func_id);
10372 
10373 static int set_callee_state(struct bpf_verifier_env *env,
10374 			    struct bpf_func_state *caller,
10375 			    struct bpf_func_state *callee, int insn_idx);
10376 
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)10377 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10378 			    set_callee_state_fn set_callee_state_cb,
10379 			    struct bpf_verifier_state *state)
10380 {
10381 	struct bpf_func_state *caller, *callee;
10382 	int err;
10383 
10384 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10385 		verbose(env, "the call stack of %d frames is too deep\n",
10386 			state->curframe + 2);
10387 		return -E2BIG;
10388 	}
10389 
10390 	if (state->frame[state->curframe + 1]) {
10391 		verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10392 		return -EFAULT;
10393 	}
10394 
10395 	caller = state->frame[state->curframe];
10396 	callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10397 	if (!callee)
10398 		return -ENOMEM;
10399 	state->frame[state->curframe + 1] = callee;
10400 
10401 	/* callee cannot access r0, r6 - r9 for reading and has to write
10402 	 * into its own stack before reading from it.
10403 	 * callee can read/write into caller's stack
10404 	 */
10405 	init_func_state(env, callee,
10406 			/* remember the callsite, it will be used by bpf_exit */
10407 			callsite,
10408 			state->curframe + 1 /* frameno within this callchain */,
10409 			subprog /* subprog number within this prog */);
10410 	err = set_callee_state_cb(env, caller, callee, callsite);
10411 	if (err)
10412 		goto err_out;
10413 
10414 	/* only increment it after check_reg_arg() finished */
10415 	state->curframe++;
10416 
10417 	return 0;
10418 
10419 err_out:
10420 	free_func_state(callee);
10421 	state->frame[state->curframe + 1] = NULL;
10422 	return err;
10423 }
10424 
btf_check_func_arg_match(struct bpf_verifier_env * env,int subprog,const struct btf * btf,struct bpf_reg_state * regs)10425 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10426 				    const struct btf *btf,
10427 				    struct bpf_reg_state *regs)
10428 {
10429 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
10430 	struct bpf_verifier_log *log = &env->log;
10431 	u32 i;
10432 	int ret;
10433 
10434 	ret = btf_prepare_func_args(env, subprog);
10435 	if (ret)
10436 		return ret;
10437 
10438 	/* check that BTF function arguments match actual types that the
10439 	 * verifier sees.
10440 	 */
10441 	for (i = 0; i < sub->arg_cnt; i++) {
10442 		u32 regno = i + 1;
10443 		struct bpf_reg_state *reg = &regs[regno];
10444 		struct bpf_subprog_arg_info *arg = &sub->args[i];
10445 
10446 		if (arg->arg_type == ARG_ANYTHING) {
10447 			if (reg->type != SCALAR_VALUE) {
10448 				bpf_log(log, "R%d is not a scalar\n", regno);
10449 				return -EINVAL;
10450 			}
10451 		} else if (arg->arg_type & PTR_UNTRUSTED) {
10452 			/*
10453 			 * Anything is allowed for untrusted arguments, as these are
10454 			 * read-only and probe read instructions would protect against
10455 			 * invalid memory access.
10456 			 */
10457 		} else if (arg->arg_type == ARG_PTR_TO_CTX) {
10458 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10459 			if (ret < 0)
10460 				return ret;
10461 			/* If function expects ctx type in BTF check that caller
10462 			 * is passing PTR_TO_CTX.
10463 			 */
10464 			if (reg->type != PTR_TO_CTX) {
10465 				bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10466 				return -EINVAL;
10467 			}
10468 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10469 			ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10470 			if (ret < 0)
10471 				return ret;
10472 			if (check_mem_reg(env, reg, regno, arg->mem_size))
10473 				return -EINVAL;
10474 			if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10475 				bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10476 				return -EINVAL;
10477 			}
10478 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10479 			/*
10480 			 * Can pass any value and the kernel won't crash, but
10481 			 * only PTR_TO_ARENA or SCALAR make sense. Everything
10482 			 * else is a bug in the bpf program. Point it out to
10483 			 * the user at the verification time instead of
10484 			 * run-time debug nightmare.
10485 			 */
10486 			if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10487 				bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10488 				return -EINVAL;
10489 			}
10490 		} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10491 			ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10492 			if (ret)
10493 				return ret;
10494 
10495 			ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10496 			if (ret)
10497 				return ret;
10498 		} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10499 			struct bpf_call_arg_meta meta;
10500 			int err;
10501 
10502 			if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10503 				continue;
10504 
10505 			memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10506 			err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10507 			err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10508 			if (err)
10509 				return err;
10510 		} else {
10511 			verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10512 			return -EFAULT;
10513 		}
10514 	}
10515 
10516 	return 0;
10517 }
10518 
10519 /* Compare BTF of a function call with given bpf_reg_state.
10520  * Returns:
10521  * EFAULT - there is a verifier bug. Abort verification.
10522  * EINVAL - there is a type mismatch or BTF is not available.
10523  * 0 - BTF matches with what bpf_reg_state expects.
10524  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10525  */
btf_check_subprog_call(struct bpf_verifier_env * env,int subprog,struct bpf_reg_state * regs)10526 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10527 				  struct bpf_reg_state *regs)
10528 {
10529 	struct bpf_prog *prog = env->prog;
10530 	struct btf *btf = prog->aux->btf;
10531 	u32 btf_id;
10532 	int err;
10533 
10534 	if (!prog->aux->func_info)
10535 		return -EINVAL;
10536 
10537 	btf_id = prog->aux->func_info[subprog].type_id;
10538 	if (!btf_id)
10539 		return -EFAULT;
10540 
10541 	if (prog->aux->func_info_aux[subprog].unreliable)
10542 		return -EINVAL;
10543 
10544 	err = btf_check_func_arg_match(env, subprog, btf, regs);
10545 	/* Compiler optimizations can remove arguments from static functions
10546 	 * or mismatched type can be passed into a global function.
10547 	 * In such cases mark the function as unreliable from BTF point of view.
10548 	 */
10549 	if (err)
10550 		prog->aux->func_info_aux[subprog].unreliable = true;
10551 	return err;
10552 }
10553 
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)10554 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10555 			      int insn_idx, int subprog,
10556 			      set_callee_state_fn set_callee_state_cb)
10557 {
10558 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
10559 	struct bpf_func_state *caller, *callee;
10560 	int err;
10561 
10562 	caller = state->frame[state->curframe];
10563 	err = btf_check_subprog_call(env, subprog, caller->regs);
10564 	if (err == -EFAULT)
10565 		return err;
10566 
10567 	/* set_callee_state is used for direct subprog calls, but we are
10568 	 * interested in validating only BPF helpers that can call subprogs as
10569 	 * callbacks
10570 	 */
10571 	env->subprog_info[subprog].is_cb = true;
10572 	if (bpf_pseudo_kfunc_call(insn) &&
10573 	    !is_callback_calling_kfunc(insn->imm)) {
10574 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10575 			     func_id_name(insn->imm), insn->imm);
10576 		return -EFAULT;
10577 	} else if (!bpf_pseudo_kfunc_call(insn) &&
10578 		   !is_callback_calling_function(insn->imm)) { /* helper */
10579 		verifier_bug(env, "helper %s#%d not marked as callback-calling",
10580 			     func_id_name(insn->imm), insn->imm);
10581 		return -EFAULT;
10582 	}
10583 
10584 	if (is_async_callback_calling_insn(insn)) {
10585 		struct bpf_verifier_state *async_cb;
10586 
10587 		/* there is no real recursion here. timer and workqueue callbacks are async */
10588 		env->subprog_info[subprog].is_async_cb = true;
10589 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10590 					 insn_idx, subprog,
10591 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm) ||
10592 					 is_task_work_add_kfunc(insn->imm));
10593 		if (!async_cb)
10594 			return -EFAULT;
10595 		callee = async_cb->frame[0];
10596 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
10597 
10598 		/* Convert bpf_timer_set_callback() args into timer callback args */
10599 		err = set_callee_state_cb(env, caller, callee, insn_idx);
10600 		if (err)
10601 			return err;
10602 
10603 		return 0;
10604 	}
10605 
10606 	/* for callback functions enqueue entry to callback and
10607 	 * proceed with next instruction within current frame.
10608 	 */
10609 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10610 	if (!callback_state)
10611 		return -ENOMEM;
10612 
10613 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10614 			       callback_state);
10615 	if (err)
10616 		return err;
10617 
10618 	callback_state->callback_unroll_depth++;
10619 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10620 	caller->callback_depth = 0;
10621 	return 0;
10622 }
10623 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)10624 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10625 			   int *insn_idx)
10626 {
10627 	struct bpf_verifier_state *state = env->cur_state;
10628 	struct bpf_func_state *caller;
10629 	int err, subprog, target_insn;
10630 
10631 	target_insn = *insn_idx + insn->imm + 1;
10632 	subprog = find_subprog(env, target_insn);
10633 	if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10634 			    target_insn))
10635 		return -EFAULT;
10636 
10637 	caller = state->frame[state->curframe];
10638 	err = btf_check_subprog_call(env, subprog, caller->regs);
10639 	if (err == -EFAULT)
10640 		return err;
10641 	if (subprog_is_global(env, subprog)) {
10642 		const char *sub_name = subprog_name(env, subprog);
10643 
10644 		if (env->cur_state->active_locks) {
10645 			verbose(env, "global function calls are not allowed while holding a lock,\n"
10646 				     "use static function instead\n");
10647 			return -EINVAL;
10648 		}
10649 
10650 		if (env->subprog_info[subprog].might_sleep &&
10651 		    (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks ||
10652 		     env->cur_state->active_irq_id || !in_sleepable(env))) {
10653 			verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10654 				     "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10655 				     "a non-sleepable BPF program context\n");
10656 			return -EINVAL;
10657 		}
10658 
10659 		if (err) {
10660 			verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10661 				subprog, sub_name);
10662 			return err;
10663 		}
10664 
10665 		verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10666 			subprog, sub_name);
10667 		if (env->subprog_info[subprog].changes_pkt_data)
10668 			clear_all_pkt_pointers(env);
10669 		/* mark global subprog for verifying after main prog */
10670 		subprog_aux(env, subprog)->called = true;
10671 		clear_caller_saved_regs(env, caller->regs);
10672 
10673 		/* All global functions return a 64-bit SCALAR_VALUE */
10674 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
10675 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10676 
10677 		/* continue with next insn after call */
10678 		return 0;
10679 	}
10680 
10681 	/* for regular function entry setup new frame and continue
10682 	 * from that frame.
10683 	 */
10684 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10685 	if (err)
10686 		return err;
10687 
10688 	clear_caller_saved_regs(env, caller->regs);
10689 
10690 	/* and go analyze first insn of the callee */
10691 	*insn_idx = env->subprog_info[subprog].start - 1;
10692 
10693 	bpf_reset_live_stack_callchain(env);
10694 
10695 	if (env->log.level & BPF_LOG_LEVEL) {
10696 		verbose(env, "caller:\n");
10697 		print_verifier_state(env, state, caller->frameno, true);
10698 		verbose(env, "callee:\n");
10699 		print_verifier_state(env, state, state->curframe, true);
10700 	}
10701 
10702 	return 0;
10703 }
10704 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)10705 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10706 				   struct bpf_func_state *caller,
10707 				   struct bpf_func_state *callee)
10708 {
10709 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10710 	 *      void *callback_ctx, u64 flags);
10711 	 * callback_fn(struct bpf_map *map, void *key, void *value,
10712 	 *      void *callback_ctx);
10713 	 */
10714 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10715 
10716 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10717 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10718 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10719 
10720 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10721 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10722 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10723 
10724 	/* pointer to stack or null */
10725 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10726 
10727 	/* unused */
10728 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10729 	return 0;
10730 }
10731 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10732 static int set_callee_state(struct bpf_verifier_env *env,
10733 			    struct bpf_func_state *caller,
10734 			    struct bpf_func_state *callee, int insn_idx)
10735 {
10736 	int i;
10737 
10738 	/* copy r1 - r5 args that callee can access.  The copy includes parent
10739 	 * pointers, which connects us up to the liveness chain
10740 	 */
10741 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10742 		callee->regs[i] = caller->regs[i];
10743 	return 0;
10744 }
10745 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10746 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10747 				       struct bpf_func_state *caller,
10748 				       struct bpf_func_state *callee,
10749 				       int insn_idx)
10750 {
10751 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10752 	struct bpf_map *map;
10753 	int err;
10754 
10755 	/* valid map_ptr and poison value does not matter */
10756 	map = insn_aux->map_ptr_state.map_ptr;
10757 	if (!map->ops->map_set_for_each_callback_args ||
10758 	    !map->ops->map_for_each_callback) {
10759 		verbose(env, "callback function not allowed for map\n");
10760 		return -ENOTSUPP;
10761 	}
10762 
10763 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10764 	if (err)
10765 		return err;
10766 
10767 	callee->in_callback_fn = true;
10768 	callee->callback_ret_range = retval_range(0, 1);
10769 	return 0;
10770 }
10771 
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10772 static int set_loop_callback_state(struct bpf_verifier_env *env,
10773 				   struct bpf_func_state *caller,
10774 				   struct bpf_func_state *callee,
10775 				   int insn_idx)
10776 {
10777 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10778 	 *	    u64 flags);
10779 	 * callback_fn(u64 index, void *callback_ctx);
10780 	 */
10781 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10782 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10783 
10784 	/* unused */
10785 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10786 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10787 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10788 
10789 	callee->in_callback_fn = true;
10790 	callee->callback_ret_range = retval_range(0, 1);
10791 	return 0;
10792 }
10793 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10794 static int set_timer_callback_state(struct bpf_verifier_env *env,
10795 				    struct bpf_func_state *caller,
10796 				    struct bpf_func_state *callee,
10797 				    int insn_idx)
10798 {
10799 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10800 
10801 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10802 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10803 	 */
10804 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10805 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10806 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10807 
10808 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10809 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10810 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10811 
10812 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10813 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10814 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10815 
10816 	/* unused */
10817 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10818 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10819 	callee->in_async_callback_fn = true;
10820 	callee->callback_ret_range = retval_range(0, 0);
10821 	return 0;
10822 }
10823 
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10824 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10825 				       struct bpf_func_state *caller,
10826 				       struct bpf_func_state *callee,
10827 				       int insn_idx)
10828 {
10829 	/* bpf_find_vma(struct task_struct *task, u64 addr,
10830 	 *               void *callback_fn, void *callback_ctx, u64 flags)
10831 	 * (callback_fn)(struct task_struct *task,
10832 	 *               struct vm_area_struct *vma, void *callback_ctx);
10833 	 */
10834 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10835 
10836 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10837 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10838 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
10839 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10840 
10841 	/* pointer to stack or null */
10842 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10843 
10844 	/* unused */
10845 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10846 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10847 	callee->in_callback_fn = true;
10848 	callee->callback_ret_range = retval_range(0, 1);
10849 	return 0;
10850 }
10851 
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10852 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10853 					   struct bpf_func_state *caller,
10854 					   struct bpf_func_state *callee,
10855 					   int insn_idx)
10856 {
10857 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10858 	 *			  callback_ctx, u64 flags);
10859 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10860 	 */
10861 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10862 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10863 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10864 
10865 	/* unused */
10866 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10867 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10868 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10869 
10870 	callee->in_callback_fn = true;
10871 	callee->callback_ret_range = retval_range(0, 1);
10872 	return 0;
10873 }
10874 
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10875 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10876 					 struct bpf_func_state *caller,
10877 					 struct bpf_func_state *callee,
10878 					 int insn_idx)
10879 {
10880 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10881 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10882 	 *
10883 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10884 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10885 	 * by this point, so look at 'root'
10886 	 */
10887 	struct btf_field *field;
10888 
10889 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10890 				      BPF_RB_ROOT);
10891 	if (!field || !field->graph_root.value_btf_id)
10892 		return -EFAULT;
10893 
10894 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10895 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10896 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10897 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10898 
10899 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10900 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10901 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10902 	callee->in_callback_fn = true;
10903 	callee->callback_ret_range = retval_range(0, 1);
10904 	return 0;
10905 }
10906 
set_task_work_schedule_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10907 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
10908 						 struct bpf_func_state *caller,
10909 						 struct bpf_func_state *callee,
10910 						 int insn_idx)
10911 {
10912 	struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
10913 
10914 	/*
10915 	 * callback_fn(struct bpf_map *map, void *key, void *value);
10916 	 */
10917 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10918 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10919 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
10920 
10921 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10922 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10923 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
10924 
10925 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10926 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10927 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
10928 
10929 	/* unused */
10930 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10931 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10932 	callee->in_async_callback_fn = true;
10933 	callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
10934 	return 0;
10935 }
10936 
10937 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
10938 
10939 /* Are we currently verifying the callback for a rbtree helper that must
10940  * be called with lock held? If so, no need to complain about unreleased
10941  * lock
10942  */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)10943 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
10944 {
10945 	struct bpf_verifier_state *state = env->cur_state;
10946 	struct bpf_insn *insn = env->prog->insnsi;
10947 	struct bpf_func_state *callee;
10948 	int kfunc_btf_id;
10949 
10950 	if (!state->curframe)
10951 		return false;
10952 
10953 	callee = state->frame[state->curframe];
10954 
10955 	if (!callee->in_callback_fn)
10956 		return false;
10957 
10958 	kfunc_btf_id = insn[callee->callsite].imm;
10959 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
10960 }
10961 
retval_range_within(struct bpf_retval_range range,const struct bpf_reg_state * reg,bool return_32bit)10962 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
10963 				bool return_32bit)
10964 {
10965 	if (return_32bit)
10966 		return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
10967 	else
10968 		return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
10969 }
10970 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)10971 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
10972 {
10973 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
10974 	struct bpf_func_state *caller, *callee;
10975 	struct bpf_reg_state *r0;
10976 	bool in_callback_fn;
10977 	int err;
10978 
10979 	callee = state->frame[state->curframe];
10980 	r0 = &callee->regs[BPF_REG_0];
10981 	if (r0->type == PTR_TO_STACK) {
10982 		/* technically it's ok to return caller's stack pointer
10983 		 * (or caller's caller's pointer) back to the caller,
10984 		 * since these pointers are valid. Only current stack
10985 		 * pointer will be invalid as soon as function exits,
10986 		 * but let's be conservative
10987 		 */
10988 		verbose(env, "cannot return stack pointer to the caller\n");
10989 		return -EINVAL;
10990 	}
10991 
10992 	caller = state->frame[state->curframe - 1];
10993 	if (callee->in_callback_fn) {
10994 		if (r0->type != SCALAR_VALUE) {
10995 			verbose(env, "R0 not a scalar value\n");
10996 			return -EACCES;
10997 		}
10998 
10999 		/* we are going to rely on register's precise value */
11000 		err = mark_chain_precision(env, BPF_REG_0);
11001 		if (err)
11002 			return err;
11003 
11004 		/* enforce R0 return value range, and bpf_callback_t returns 64bit */
11005 		if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11006 			verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11007 					       "At callback return", "R0");
11008 			return -EINVAL;
11009 		}
11010 		if (!bpf_calls_callback(env, callee->callsite)) {
11011 			verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11012 				     *insn_idx, callee->callsite);
11013 			return -EFAULT;
11014 		}
11015 	} else {
11016 		/* return to the caller whatever r0 had in the callee */
11017 		caller->regs[BPF_REG_0] = *r0;
11018 	}
11019 
11020 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11021 	 * there function call logic would reschedule callback visit. If iteration
11022 	 * converges is_state_visited() would prune that visit eventually.
11023 	 */
11024 	in_callback_fn = callee->in_callback_fn;
11025 	if (in_callback_fn)
11026 		*insn_idx = callee->callsite;
11027 	else
11028 		*insn_idx = callee->callsite + 1;
11029 
11030 	if (env->log.level & BPF_LOG_LEVEL) {
11031 		verbose(env, "returning from callee:\n");
11032 		print_verifier_state(env, state, callee->frameno, true);
11033 		verbose(env, "to caller at %d:\n", *insn_idx);
11034 		print_verifier_state(env, state, caller->frameno, true);
11035 	}
11036 	/* clear everything in the callee. In case of exceptional exits using
11037 	 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11038 	free_func_state(callee);
11039 	state->frame[state->curframe--] = NULL;
11040 
11041 	/* for callbacks widen imprecise scalars to make programs like below verify:
11042 	 *
11043 	 *   struct ctx { int i; }
11044 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11045 	 *   ...
11046 	 *   struct ctx = { .i = 0; }
11047 	 *   bpf_loop(100, cb, &ctx, 0);
11048 	 *
11049 	 * This is similar to what is done in process_iter_next_call() for open
11050 	 * coded iterators.
11051 	 */
11052 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11053 	if (prev_st) {
11054 		err = widen_imprecise_scalars(env, prev_st, state);
11055 		if (err)
11056 			return err;
11057 	}
11058 	return 0;
11059 }
11060 
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)11061 static int do_refine_retval_range(struct bpf_verifier_env *env,
11062 				  struct bpf_reg_state *regs, int ret_type,
11063 				  int func_id,
11064 				  struct bpf_call_arg_meta *meta)
11065 {
11066 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
11067 
11068 	if (ret_type != RET_INTEGER)
11069 		return 0;
11070 
11071 	switch (func_id) {
11072 	case BPF_FUNC_get_stack:
11073 	case BPF_FUNC_get_task_stack:
11074 	case BPF_FUNC_probe_read_str:
11075 	case BPF_FUNC_probe_read_kernel_str:
11076 	case BPF_FUNC_probe_read_user_str:
11077 		ret_reg->smax_value = meta->msize_max_value;
11078 		ret_reg->s32_max_value = meta->msize_max_value;
11079 		ret_reg->smin_value = -MAX_ERRNO;
11080 		ret_reg->s32_min_value = -MAX_ERRNO;
11081 		reg_bounds_sync(ret_reg);
11082 		break;
11083 	case BPF_FUNC_get_smp_processor_id:
11084 		ret_reg->umax_value = nr_cpu_ids - 1;
11085 		ret_reg->u32_max_value = nr_cpu_ids - 1;
11086 		ret_reg->smax_value = nr_cpu_ids - 1;
11087 		ret_reg->s32_max_value = nr_cpu_ids - 1;
11088 		ret_reg->umin_value = 0;
11089 		ret_reg->u32_min_value = 0;
11090 		ret_reg->smin_value = 0;
11091 		ret_reg->s32_min_value = 0;
11092 		reg_bounds_sync(ret_reg);
11093 		break;
11094 	}
11095 
11096 	return reg_bounds_sanity_check(env, ret_reg, "retval");
11097 }
11098 
11099 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11100 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11101 		int func_id, int insn_idx)
11102 {
11103 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11104 	struct bpf_map *map = meta->map_ptr;
11105 
11106 	if (func_id != BPF_FUNC_tail_call &&
11107 	    func_id != BPF_FUNC_map_lookup_elem &&
11108 	    func_id != BPF_FUNC_map_update_elem &&
11109 	    func_id != BPF_FUNC_map_delete_elem &&
11110 	    func_id != BPF_FUNC_map_push_elem &&
11111 	    func_id != BPF_FUNC_map_pop_elem &&
11112 	    func_id != BPF_FUNC_map_peek_elem &&
11113 	    func_id != BPF_FUNC_for_each_map_elem &&
11114 	    func_id != BPF_FUNC_redirect_map &&
11115 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
11116 		return 0;
11117 
11118 	if (map == NULL) {
11119 		verifier_bug(env, "expected map for helper call");
11120 		return -EFAULT;
11121 	}
11122 
11123 	/* In case of read-only, some additional restrictions
11124 	 * need to be applied in order to prevent altering the
11125 	 * state of the map from program side.
11126 	 */
11127 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11128 	    (func_id == BPF_FUNC_map_delete_elem ||
11129 	     func_id == BPF_FUNC_map_update_elem ||
11130 	     func_id == BPF_FUNC_map_push_elem ||
11131 	     func_id == BPF_FUNC_map_pop_elem)) {
11132 		verbose(env, "write into map forbidden\n");
11133 		return -EACCES;
11134 	}
11135 
11136 	if (!aux->map_ptr_state.map_ptr)
11137 		bpf_map_ptr_store(aux, meta->map_ptr,
11138 				  !meta->map_ptr->bypass_spec_v1, false);
11139 	else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11140 		bpf_map_ptr_store(aux, meta->map_ptr,
11141 				  !meta->map_ptr->bypass_spec_v1, true);
11142 	return 0;
11143 }
11144 
11145 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11146 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11147 		int func_id, int insn_idx)
11148 {
11149 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11150 	struct bpf_reg_state *regs = cur_regs(env), *reg;
11151 	struct bpf_map *map = meta->map_ptr;
11152 	u64 val, max;
11153 	int err;
11154 
11155 	if (func_id != BPF_FUNC_tail_call)
11156 		return 0;
11157 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11158 		verbose(env, "expected prog array map for tail call");
11159 		return -EINVAL;
11160 	}
11161 
11162 	reg = &regs[BPF_REG_3];
11163 	val = reg->var_off.value;
11164 	max = map->max_entries;
11165 
11166 	if (!(is_reg_const(reg, false) && val < max)) {
11167 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11168 		return 0;
11169 	}
11170 
11171 	err = mark_chain_precision(env, BPF_REG_3);
11172 	if (err)
11173 		return err;
11174 	if (bpf_map_key_unseen(aux))
11175 		bpf_map_key_store(aux, val);
11176 	else if (!bpf_map_key_poisoned(aux) &&
11177 		  bpf_map_key_immediate(aux) != val)
11178 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11179 	return 0;
11180 }
11181 
check_reference_leak(struct bpf_verifier_env * env,bool exception_exit)11182 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11183 {
11184 	struct bpf_verifier_state *state = env->cur_state;
11185 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11186 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11187 	bool refs_lingering = false;
11188 	int i;
11189 
11190 	if (!exception_exit && cur_func(env)->frameno)
11191 		return 0;
11192 
11193 	for (i = 0; i < state->acquired_refs; i++) {
11194 		if (state->refs[i].type != REF_TYPE_PTR)
11195 			continue;
11196 		/* Allow struct_ops programs to return a referenced kptr back to
11197 		 * kernel. Type checks are performed later in check_return_code.
11198 		 */
11199 		if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11200 		    reg->ref_obj_id == state->refs[i].id)
11201 			continue;
11202 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11203 			state->refs[i].id, state->refs[i].insn_idx);
11204 		refs_lingering = true;
11205 	}
11206 	return refs_lingering ? -EINVAL : 0;
11207 }
11208 
check_resource_leak(struct bpf_verifier_env * env,bool exception_exit,bool check_lock,const char * prefix)11209 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11210 {
11211 	int err;
11212 
11213 	if (check_lock && env->cur_state->active_locks) {
11214 		verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11215 		return -EINVAL;
11216 	}
11217 
11218 	err = check_reference_leak(env, exception_exit);
11219 	if (err) {
11220 		verbose(env, "%s would lead to reference leak\n", prefix);
11221 		return err;
11222 	}
11223 
11224 	if (check_lock && env->cur_state->active_irq_id) {
11225 		verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11226 		return -EINVAL;
11227 	}
11228 
11229 	if (check_lock && env->cur_state->active_rcu_lock) {
11230 		verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11231 		return -EINVAL;
11232 	}
11233 
11234 	if (check_lock && env->cur_state->active_preempt_locks) {
11235 		verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11236 		return -EINVAL;
11237 	}
11238 
11239 	return 0;
11240 }
11241 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)11242 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11243 				   struct bpf_reg_state *regs)
11244 {
11245 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
11246 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
11247 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
11248 	struct bpf_bprintf_data data = {};
11249 	int err, fmt_map_off, num_args;
11250 	u64 fmt_addr;
11251 	char *fmt;
11252 
11253 	/* data must be an array of u64 */
11254 	if (data_len_reg->var_off.value % 8)
11255 		return -EINVAL;
11256 	num_args = data_len_reg->var_off.value / 8;
11257 
11258 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11259 	 * and map_direct_value_addr is set.
11260 	 */
11261 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11262 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11263 						  fmt_map_off);
11264 	if (err) {
11265 		verbose(env, "failed to retrieve map value address\n");
11266 		return -EFAULT;
11267 	}
11268 	fmt = (char *)(long)fmt_addr + fmt_map_off;
11269 
11270 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11271 	 * can focus on validating the format specifiers.
11272 	 */
11273 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11274 	if (err < 0)
11275 		verbose(env, "Invalid format string\n");
11276 
11277 	return err;
11278 }
11279 
check_get_func_ip(struct bpf_verifier_env * env)11280 static int check_get_func_ip(struct bpf_verifier_env *env)
11281 {
11282 	enum bpf_prog_type type = resolve_prog_type(env->prog);
11283 	int func_id = BPF_FUNC_get_func_ip;
11284 
11285 	if (type == BPF_PROG_TYPE_TRACING) {
11286 		if (!bpf_prog_has_trampoline(env->prog)) {
11287 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11288 				func_id_name(func_id), func_id);
11289 			return -ENOTSUPP;
11290 		}
11291 		return 0;
11292 	} else if (type == BPF_PROG_TYPE_KPROBE) {
11293 		return 0;
11294 	}
11295 
11296 	verbose(env, "func %s#%d not supported for program type %d\n",
11297 		func_id_name(func_id), func_id, type);
11298 	return -ENOTSUPP;
11299 }
11300 
cur_aux(const struct bpf_verifier_env * env)11301 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11302 {
11303 	return &env->insn_aux_data[env->insn_idx];
11304 }
11305 
loop_flag_is_zero(struct bpf_verifier_env * env)11306 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11307 {
11308 	struct bpf_reg_state *regs = cur_regs(env);
11309 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
11310 	bool reg_is_null = register_is_null(reg);
11311 
11312 	if (reg_is_null)
11313 		mark_chain_precision(env, BPF_REG_4);
11314 
11315 	return reg_is_null;
11316 }
11317 
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)11318 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11319 {
11320 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11321 
11322 	if (!state->initialized) {
11323 		state->initialized = 1;
11324 		state->fit_for_inline = loop_flag_is_zero(env);
11325 		state->callback_subprogno = subprogno;
11326 		return;
11327 	}
11328 
11329 	if (!state->fit_for_inline)
11330 		return;
11331 
11332 	state->fit_for_inline = (loop_flag_is_zero(env) &&
11333 				 state->callback_subprogno == subprogno);
11334 }
11335 
11336 /* Returns whether or not the given map type can potentially elide
11337  * lookup return value nullness check. This is possible if the key
11338  * is statically known.
11339  */
can_elide_value_nullness(enum bpf_map_type type)11340 static bool can_elide_value_nullness(enum bpf_map_type type)
11341 {
11342 	switch (type) {
11343 	case BPF_MAP_TYPE_ARRAY:
11344 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11345 		return true;
11346 	default:
11347 		return false;
11348 	}
11349 }
11350 
get_helper_proto(struct bpf_verifier_env * env,int func_id,const struct bpf_func_proto ** ptr)11351 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11352 			    const struct bpf_func_proto **ptr)
11353 {
11354 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11355 		return -ERANGE;
11356 
11357 	if (!env->ops->get_func_proto)
11358 		return -EINVAL;
11359 
11360 	*ptr = env->ops->get_func_proto(func_id, env->prog);
11361 	return *ptr && (*ptr)->func ? 0 : -EINVAL;
11362 }
11363 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11364 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11365 			     int *insn_idx_p)
11366 {
11367 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11368 	bool returns_cpu_specific_alloc_ptr = false;
11369 	const struct bpf_func_proto *fn = NULL;
11370 	enum bpf_return_type ret_type;
11371 	enum bpf_type_flag ret_flag;
11372 	struct bpf_reg_state *regs;
11373 	struct bpf_call_arg_meta meta;
11374 	int insn_idx = *insn_idx_p;
11375 	bool changes_data;
11376 	int i, err, func_id;
11377 
11378 	/* find function prototype */
11379 	func_id = insn->imm;
11380 	err = get_helper_proto(env, insn->imm, &fn);
11381 	if (err == -ERANGE) {
11382 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11383 		return -EINVAL;
11384 	}
11385 
11386 	if (err) {
11387 		verbose(env, "program of this type cannot use helper %s#%d\n",
11388 			func_id_name(func_id), func_id);
11389 		return err;
11390 	}
11391 
11392 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
11393 	if (!env->prog->gpl_compatible && fn->gpl_only) {
11394 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11395 		return -EINVAL;
11396 	}
11397 
11398 	if (fn->allowed && !fn->allowed(env->prog)) {
11399 		verbose(env, "helper call is not allowed in probe\n");
11400 		return -EINVAL;
11401 	}
11402 
11403 	if (!in_sleepable(env) && fn->might_sleep) {
11404 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
11405 		return -EINVAL;
11406 	}
11407 
11408 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
11409 	changes_data = bpf_helper_changes_pkt_data(func_id);
11410 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11411 		verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11412 		return -EFAULT;
11413 	}
11414 
11415 	memset(&meta, 0, sizeof(meta));
11416 	meta.pkt_access = fn->pkt_access;
11417 
11418 	err = check_func_proto(fn, func_id);
11419 	if (err) {
11420 		verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11421 		return err;
11422 	}
11423 
11424 	if (env->cur_state->active_rcu_lock) {
11425 		if (fn->might_sleep) {
11426 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11427 				func_id_name(func_id), func_id);
11428 			return -EINVAL;
11429 		}
11430 
11431 		if (in_sleepable(env) && is_storage_get_function(func_id))
11432 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11433 	}
11434 
11435 	if (env->cur_state->active_preempt_locks) {
11436 		if (fn->might_sleep) {
11437 			verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11438 				func_id_name(func_id), func_id);
11439 			return -EINVAL;
11440 		}
11441 
11442 		if (in_sleepable(env) && is_storage_get_function(func_id))
11443 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11444 	}
11445 
11446 	if (env->cur_state->active_irq_id) {
11447 		if (fn->might_sleep) {
11448 			verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11449 				func_id_name(func_id), func_id);
11450 			return -EINVAL;
11451 		}
11452 
11453 		if (in_sleepable(env) && is_storage_get_function(func_id))
11454 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
11455 	}
11456 
11457 	meta.func_id = func_id;
11458 	/* check args */
11459 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11460 		err = check_func_arg(env, i, &meta, fn, insn_idx);
11461 		if (err)
11462 			return err;
11463 	}
11464 
11465 	err = record_func_map(env, &meta, func_id, insn_idx);
11466 	if (err)
11467 		return err;
11468 
11469 	err = record_func_key(env, &meta, func_id, insn_idx);
11470 	if (err)
11471 		return err;
11472 
11473 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
11474 	 * is inferred from register state.
11475 	 */
11476 	for (i = 0; i < meta.access_size; i++) {
11477 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11478 				       BPF_WRITE, -1, false, false);
11479 		if (err)
11480 			return err;
11481 	}
11482 
11483 	regs = cur_regs(env);
11484 
11485 	if (meta.release_regno) {
11486 		err = -EINVAL;
11487 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
11488 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
11489 		 * is safe to do directly.
11490 		 */
11491 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11492 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
11493 				verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
11494 				return -EFAULT;
11495 			}
11496 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
11497 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11498 			u32 ref_obj_id = meta.ref_obj_id;
11499 			bool in_rcu = in_rcu_cs(env);
11500 			struct bpf_func_state *state;
11501 			struct bpf_reg_state *reg;
11502 
11503 			err = release_reference_nomark(env->cur_state, ref_obj_id);
11504 			if (!err) {
11505 				bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11506 					if (reg->ref_obj_id == ref_obj_id) {
11507 						if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11508 							reg->ref_obj_id = 0;
11509 							reg->type &= ~MEM_ALLOC;
11510 							reg->type |= MEM_RCU;
11511 						} else {
11512 							mark_reg_invalid(env, reg);
11513 						}
11514 					}
11515 				}));
11516 			}
11517 		} else if (meta.ref_obj_id) {
11518 			err = release_reference(env, meta.ref_obj_id);
11519 		} else if (register_is_null(&regs[meta.release_regno])) {
11520 			/* meta.ref_obj_id can only be 0 if register that is meant to be
11521 			 * released is NULL, which must be > R0.
11522 			 */
11523 			err = 0;
11524 		}
11525 		if (err) {
11526 			verbose(env, "func %s#%d reference has not been acquired before\n",
11527 				func_id_name(func_id), func_id);
11528 			return err;
11529 		}
11530 	}
11531 
11532 	switch (func_id) {
11533 	case BPF_FUNC_tail_call:
11534 		err = check_resource_leak(env, false, true, "tail_call");
11535 		if (err)
11536 			return err;
11537 		break;
11538 	case BPF_FUNC_get_local_storage:
11539 		/* check that flags argument in get_local_storage(map, flags) is 0,
11540 		 * this is required because get_local_storage() can't return an error.
11541 		 */
11542 		if (!register_is_null(&regs[BPF_REG_2])) {
11543 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11544 			return -EINVAL;
11545 		}
11546 		break;
11547 	case BPF_FUNC_for_each_map_elem:
11548 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11549 					 set_map_elem_callback_state);
11550 		break;
11551 	case BPF_FUNC_timer_set_callback:
11552 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11553 					 set_timer_callback_state);
11554 		break;
11555 	case BPF_FUNC_find_vma:
11556 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11557 					 set_find_vma_callback_state);
11558 		break;
11559 	case BPF_FUNC_snprintf:
11560 		err = check_bpf_snprintf_call(env, regs);
11561 		break;
11562 	case BPF_FUNC_loop:
11563 		update_loop_inline_state(env, meta.subprogno);
11564 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
11565 		 * is finished, thus mark it precise.
11566 		 */
11567 		err = mark_chain_precision(env, BPF_REG_1);
11568 		if (err)
11569 			return err;
11570 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11571 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11572 						 set_loop_callback_state);
11573 		} else {
11574 			cur_func(env)->callback_depth = 0;
11575 			if (env->log.level & BPF_LOG_LEVEL2)
11576 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
11577 					env->cur_state->curframe);
11578 		}
11579 		break;
11580 	case BPF_FUNC_dynptr_from_mem:
11581 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11582 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11583 				reg_type_str(env, regs[BPF_REG_1].type));
11584 			return -EACCES;
11585 		}
11586 		break;
11587 	case BPF_FUNC_set_retval:
11588 		if (prog_type == BPF_PROG_TYPE_LSM &&
11589 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11590 			if (!env->prog->aux->attach_func_proto->type) {
11591 				/* Make sure programs that attach to void
11592 				 * hooks don't try to modify return value.
11593 				 */
11594 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11595 				return -EINVAL;
11596 			}
11597 		}
11598 		break;
11599 	case BPF_FUNC_dynptr_data:
11600 	{
11601 		struct bpf_reg_state *reg;
11602 		int id, ref_obj_id;
11603 
11604 		reg = get_dynptr_arg_reg(env, fn, regs);
11605 		if (!reg)
11606 			return -EFAULT;
11607 
11608 
11609 		if (meta.dynptr_id) {
11610 			verifier_bug(env, "meta.dynptr_id already set");
11611 			return -EFAULT;
11612 		}
11613 		if (meta.ref_obj_id) {
11614 			verifier_bug(env, "meta.ref_obj_id already set");
11615 			return -EFAULT;
11616 		}
11617 
11618 		id = dynptr_id(env, reg);
11619 		if (id < 0) {
11620 			verifier_bug(env, "failed to obtain dynptr id");
11621 			return id;
11622 		}
11623 
11624 		ref_obj_id = dynptr_ref_obj_id(env, reg);
11625 		if (ref_obj_id < 0) {
11626 			verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11627 			return ref_obj_id;
11628 		}
11629 
11630 		meta.dynptr_id = id;
11631 		meta.ref_obj_id = ref_obj_id;
11632 
11633 		break;
11634 	}
11635 	case BPF_FUNC_dynptr_write:
11636 	{
11637 		enum bpf_dynptr_type dynptr_type;
11638 		struct bpf_reg_state *reg;
11639 
11640 		reg = get_dynptr_arg_reg(env, fn, regs);
11641 		if (!reg)
11642 			return -EFAULT;
11643 
11644 		dynptr_type = dynptr_get_type(env, reg);
11645 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11646 			return -EFAULT;
11647 
11648 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11649 		    dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11650 			/* this will trigger clear_all_pkt_pointers(), which will
11651 			 * invalidate all dynptr slices associated with the skb
11652 			 */
11653 			changes_data = true;
11654 
11655 		break;
11656 	}
11657 	case BPF_FUNC_per_cpu_ptr:
11658 	case BPF_FUNC_this_cpu_ptr:
11659 	{
11660 		struct bpf_reg_state *reg = &regs[BPF_REG_1];
11661 		const struct btf_type *type;
11662 
11663 		if (reg->type & MEM_RCU) {
11664 			type = btf_type_by_id(reg->btf, reg->btf_id);
11665 			if (!type || !btf_type_is_struct(type)) {
11666 				verbose(env, "Helper has invalid btf/btf_id in R1\n");
11667 				return -EFAULT;
11668 			}
11669 			returns_cpu_specific_alloc_ptr = true;
11670 			env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11671 		}
11672 		break;
11673 	}
11674 	case BPF_FUNC_user_ringbuf_drain:
11675 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11676 					 set_user_ringbuf_callback_state);
11677 		break;
11678 	}
11679 
11680 	if (err)
11681 		return err;
11682 
11683 	/* reset caller saved regs */
11684 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
11685 		mark_reg_not_init(env, regs, caller_saved[i]);
11686 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11687 	}
11688 
11689 	/* helper call returns 64-bit value. */
11690 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11691 
11692 	/* update return register (already marked as written above) */
11693 	ret_type = fn->ret_type;
11694 	ret_flag = type_flag(ret_type);
11695 
11696 	switch (base_type(ret_type)) {
11697 	case RET_INTEGER:
11698 		/* sets type to SCALAR_VALUE */
11699 		mark_reg_unknown(env, regs, BPF_REG_0);
11700 		break;
11701 	case RET_VOID:
11702 		regs[BPF_REG_0].type = NOT_INIT;
11703 		break;
11704 	case RET_PTR_TO_MAP_VALUE:
11705 		/* There is no offset yet applied, variable or fixed */
11706 		mark_reg_known_zero(env, regs, BPF_REG_0);
11707 		/* remember map_ptr, so that check_map_access()
11708 		 * can check 'value_size' boundary of memory access
11709 		 * to map element returned from bpf_map_lookup_elem()
11710 		 */
11711 		if (meta.map_ptr == NULL) {
11712 			verifier_bug(env, "unexpected null map_ptr");
11713 			return -EFAULT;
11714 		}
11715 
11716 		if (func_id == BPF_FUNC_map_lookup_elem &&
11717 		    can_elide_value_nullness(meta.map_ptr->map_type) &&
11718 		    meta.const_map_key >= 0 &&
11719 		    meta.const_map_key < meta.map_ptr->max_entries)
11720 			ret_flag &= ~PTR_MAYBE_NULL;
11721 
11722 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
11723 		regs[BPF_REG_0].map_uid = meta.map_uid;
11724 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11725 		if (!type_may_be_null(ret_flag) &&
11726 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11727 			regs[BPF_REG_0].id = ++env->id_gen;
11728 		}
11729 		break;
11730 	case RET_PTR_TO_SOCKET:
11731 		mark_reg_known_zero(env, regs, BPF_REG_0);
11732 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11733 		break;
11734 	case RET_PTR_TO_SOCK_COMMON:
11735 		mark_reg_known_zero(env, regs, BPF_REG_0);
11736 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11737 		break;
11738 	case RET_PTR_TO_TCP_SOCK:
11739 		mark_reg_known_zero(env, regs, BPF_REG_0);
11740 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11741 		break;
11742 	case RET_PTR_TO_MEM:
11743 		mark_reg_known_zero(env, regs, BPF_REG_0);
11744 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11745 		regs[BPF_REG_0].mem_size = meta.mem_size;
11746 		break;
11747 	case RET_PTR_TO_MEM_OR_BTF_ID:
11748 	{
11749 		const struct btf_type *t;
11750 
11751 		mark_reg_known_zero(env, regs, BPF_REG_0);
11752 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11753 		if (!btf_type_is_struct(t)) {
11754 			u32 tsize;
11755 			const struct btf_type *ret;
11756 			const char *tname;
11757 
11758 			/* resolve the type size of ksym. */
11759 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11760 			if (IS_ERR(ret)) {
11761 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11762 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
11763 					tname, PTR_ERR(ret));
11764 				return -EINVAL;
11765 			}
11766 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11767 			regs[BPF_REG_0].mem_size = tsize;
11768 		} else {
11769 			if (returns_cpu_specific_alloc_ptr) {
11770 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11771 			} else {
11772 				/* MEM_RDONLY may be carried from ret_flag, but it
11773 				 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11774 				 * it will confuse the check of PTR_TO_BTF_ID in
11775 				 * check_mem_access().
11776 				 */
11777 				ret_flag &= ~MEM_RDONLY;
11778 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11779 			}
11780 
11781 			regs[BPF_REG_0].btf = meta.ret_btf;
11782 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11783 		}
11784 		break;
11785 	}
11786 	case RET_PTR_TO_BTF_ID:
11787 	{
11788 		struct btf *ret_btf;
11789 		int ret_btf_id;
11790 
11791 		mark_reg_known_zero(env, regs, BPF_REG_0);
11792 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11793 		if (func_id == BPF_FUNC_kptr_xchg) {
11794 			ret_btf = meta.kptr_field->kptr.btf;
11795 			ret_btf_id = meta.kptr_field->kptr.btf_id;
11796 			if (!btf_is_kernel(ret_btf)) {
11797 				regs[BPF_REG_0].type |= MEM_ALLOC;
11798 				if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11799 					regs[BPF_REG_0].type |= MEM_PERCPU;
11800 			}
11801 		} else {
11802 			if (fn->ret_btf_id == BPF_PTR_POISON) {
11803 				verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11804 					     func_id_name(func_id));
11805 				return -EFAULT;
11806 			}
11807 			ret_btf = btf_vmlinux;
11808 			ret_btf_id = *fn->ret_btf_id;
11809 		}
11810 		if (ret_btf_id == 0) {
11811 			verbose(env, "invalid return type %u of func %s#%d\n",
11812 				base_type(ret_type), func_id_name(func_id),
11813 				func_id);
11814 			return -EINVAL;
11815 		}
11816 		regs[BPF_REG_0].btf = ret_btf;
11817 		regs[BPF_REG_0].btf_id = ret_btf_id;
11818 		break;
11819 	}
11820 	default:
11821 		verbose(env, "unknown return type %u of func %s#%d\n",
11822 			base_type(ret_type), func_id_name(func_id), func_id);
11823 		return -EINVAL;
11824 	}
11825 
11826 	if (type_may_be_null(regs[BPF_REG_0].type))
11827 		regs[BPF_REG_0].id = ++env->id_gen;
11828 
11829 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11830 		verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11831 			     func_id_name(func_id), func_id);
11832 		return -EFAULT;
11833 	}
11834 
11835 	if (is_dynptr_ref_function(func_id))
11836 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11837 
11838 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11839 		/* For release_reference() */
11840 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11841 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
11842 		int id = acquire_reference(env, insn_idx);
11843 
11844 		if (id < 0)
11845 			return id;
11846 		/* For mark_ptr_or_null_reg() */
11847 		regs[BPF_REG_0].id = id;
11848 		/* For release_reference() */
11849 		regs[BPF_REG_0].ref_obj_id = id;
11850 	}
11851 
11852 	err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11853 	if (err)
11854 		return err;
11855 
11856 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11857 	if (err)
11858 		return err;
11859 
11860 	if ((func_id == BPF_FUNC_get_stack ||
11861 	     func_id == BPF_FUNC_get_task_stack) &&
11862 	    !env->prog->has_callchain_buf) {
11863 		const char *err_str;
11864 
11865 #ifdef CONFIG_PERF_EVENTS
11866 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
11867 		err_str = "cannot get callchain buffer for func %s#%d\n";
11868 #else
11869 		err = -ENOTSUPP;
11870 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11871 #endif
11872 		if (err) {
11873 			verbose(env, err_str, func_id_name(func_id), func_id);
11874 			return err;
11875 		}
11876 
11877 		env->prog->has_callchain_buf = true;
11878 	}
11879 
11880 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11881 		env->prog->call_get_stack = true;
11882 
11883 	if (func_id == BPF_FUNC_get_func_ip) {
11884 		if (check_get_func_ip(env))
11885 			return -ENOTSUPP;
11886 		env->prog->call_get_func_ip = true;
11887 	}
11888 
11889 	if (changes_data)
11890 		clear_all_pkt_pointers(env);
11891 	return 0;
11892 }
11893 
11894 /* mark_btf_func_reg_size() is used when the reg size is determined by
11895  * the BTF func_proto's return value size and argument.
11896  */
__mark_btf_func_reg_size(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,size_t reg_size)11897 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
11898 				     u32 regno, size_t reg_size)
11899 {
11900 	struct bpf_reg_state *reg = &regs[regno];
11901 
11902 	if (regno == BPF_REG_0) {
11903 		/* Function return value */
11904 		reg->subreg_def = reg_size == sizeof(u64) ?
11905 			DEF_NOT_SUBREG : env->insn_idx + 1;
11906 	} else if (reg_size == sizeof(u64)) {
11907 		/* Function argument */
11908 		mark_insn_zext(env, reg);
11909 	}
11910 }
11911 
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)11912 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
11913 				   size_t reg_size)
11914 {
11915 	return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
11916 }
11917 
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)11918 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
11919 {
11920 	return meta->kfunc_flags & KF_ACQUIRE;
11921 }
11922 
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)11923 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
11924 {
11925 	return meta->kfunc_flags & KF_RELEASE;
11926 }
11927 
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)11928 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
11929 {
11930 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
11931 }
11932 
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)11933 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
11934 {
11935 	return meta->kfunc_flags & KF_SLEEPABLE;
11936 }
11937 
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)11938 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
11939 {
11940 	return meta->kfunc_flags & KF_DESTRUCTIVE;
11941 }
11942 
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)11943 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
11944 {
11945 	return meta->kfunc_flags & KF_RCU;
11946 }
11947 
is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta * meta)11948 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
11949 {
11950 	return meta->kfunc_flags & KF_RCU_PROTECTED;
11951 }
11952 
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)11953 static bool is_kfunc_arg_mem_size(const struct btf *btf,
11954 				  const struct btf_param *arg,
11955 				  const struct bpf_reg_state *reg)
11956 {
11957 	const struct btf_type *t;
11958 
11959 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11960 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11961 		return false;
11962 
11963 	return btf_param_match_suffix(btf, arg, "__sz");
11964 }
11965 
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)11966 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
11967 					const struct btf_param *arg,
11968 					const struct bpf_reg_state *reg)
11969 {
11970 	const struct btf_type *t;
11971 
11972 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
11973 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
11974 		return false;
11975 
11976 	return btf_param_match_suffix(btf, arg, "__szk");
11977 }
11978 
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)11979 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
11980 {
11981 	return btf_param_match_suffix(btf, arg, "__opt");
11982 }
11983 
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)11984 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
11985 {
11986 	return btf_param_match_suffix(btf, arg, "__k");
11987 }
11988 
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)11989 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
11990 {
11991 	return btf_param_match_suffix(btf, arg, "__ign");
11992 }
11993 
is_kfunc_arg_map(const struct btf * btf,const struct btf_param * arg)11994 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
11995 {
11996 	return btf_param_match_suffix(btf, arg, "__map");
11997 }
11998 
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)11999 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12000 {
12001 	return btf_param_match_suffix(btf, arg, "__alloc");
12002 }
12003 
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)12004 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12005 {
12006 	return btf_param_match_suffix(btf, arg, "__uninit");
12007 }
12008 
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)12009 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12010 {
12011 	return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12012 }
12013 
is_kfunc_arg_nullable(const struct btf * btf,const struct btf_param * arg)12014 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12015 {
12016 	return btf_param_match_suffix(btf, arg, "__nullable");
12017 }
12018 
is_kfunc_arg_const_str(const struct btf * btf,const struct btf_param * arg)12019 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12020 {
12021 	return btf_param_match_suffix(btf, arg, "__str");
12022 }
12023 
is_kfunc_arg_irq_flag(const struct btf * btf,const struct btf_param * arg)12024 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12025 {
12026 	return btf_param_match_suffix(btf, arg, "__irq_flag");
12027 }
12028 
is_kfunc_arg_prog(const struct btf * btf,const struct btf_param * arg)12029 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12030 {
12031 	return btf_param_match_suffix(btf, arg, "__prog");
12032 }
12033 
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)12034 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12035 					  const struct btf_param *arg,
12036 					  const char *name)
12037 {
12038 	int len, target_len = strlen(name);
12039 	const char *param_name;
12040 
12041 	param_name = btf_name_by_offset(btf, arg->name_off);
12042 	if (str_is_empty(param_name))
12043 		return false;
12044 	len = strlen(param_name);
12045 	if (len != target_len)
12046 		return false;
12047 	if (strcmp(param_name, name))
12048 		return false;
12049 
12050 	return true;
12051 }
12052 
12053 enum {
12054 	KF_ARG_DYNPTR_ID,
12055 	KF_ARG_LIST_HEAD_ID,
12056 	KF_ARG_LIST_NODE_ID,
12057 	KF_ARG_RB_ROOT_ID,
12058 	KF_ARG_RB_NODE_ID,
12059 	KF_ARG_WORKQUEUE_ID,
12060 	KF_ARG_RES_SPIN_LOCK_ID,
12061 	KF_ARG_TASK_WORK_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 BTF_ID(struct, bpf_task_work)
12073 
12074 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12075 				    const struct btf_param *arg, int type)
12076 {
12077 	const struct btf_type *t;
12078 	u32 res_id;
12079 
12080 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
12081 	if (!t)
12082 		return false;
12083 	if (!btf_type_is_ptr(t))
12084 		return false;
12085 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
12086 	if (!t)
12087 		return false;
12088 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12089 }
12090 
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)12091 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12092 {
12093 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12094 }
12095 
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)12096 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12097 {
12098 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12099 }
12100 
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)12101 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12102 {
12103 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12104 }
12105 
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)12106 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12107 {
12108 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12109 }
12110 
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)12111 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12112 {
12113 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12114 }
12115 
is_kfunc_arg_wq(const struct btf * btf,const struct btf_param * arg)12116 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12117 {
12118 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12119 }
12120 
is_kfunc_arg_task_work(const struct btf * btf,const struct btf_param * arg)12121 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12122 {
12123 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12124 }
12125 
is_kfunc_arg_res_spin_lock(const struct btf * btf,const struct btf_param * arg)12126 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12127 {
12128 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12129 }
12130 
is_rbtree_node_type(const struct btf_type * t)12131 static bool is_rbtree_node_type(const struct btf_type *t)
12132 {
12133 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12134 }
12135 
is_list_node_type(const struct btf_type * t)12136 static bool is_list_node_type(const struct btf_type *t)
12137 {
12138 	return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12139 }
12140 
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)12141 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12142 				  const struct btf_param *arg)
12143 {
12144 	const struct btf_type *t;
12145 
12146 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12147 	if (!t)
12148 		return false;
12149 
12150 	return true;
12151 }
12152 
12153 /* 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)12154 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12155 					const struct btf *btf,
12156 					const struct btf_type *t, int rec)
12157 {
12158 	const struct btf_type *member_type;
12159 	const struct btf_member *member;
12160 	u32 i;
12161 
12162 	if (!btf_type_is_struct(t))
12163 		return false;
12164 
12165 	for_each_member(i, t, member) {
12166 		const struct btf_array *array;
12167 
12168 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12169 		if (btf_type_is_struct(member_type)) {
12170 			if (rec >= 3) {
12171 				verbose(env, "max struct nesting depth exceeded\n");
12172 				return false;
12173 			}
12174 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12175 				return false;
12176 			continue;
12177 		}
12178 		if (btf_type_is_array(member_type)) {
12179 			array = btf_array(member_type);
12180 			if (!array->nelems)
12181 				return false;
12182 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12183 			if (!btf_type_is_scalar(member_type))
12184 				return false;
12185 			continue;
12186 		}
12187 		if (!btf_type_is_scalar(member_type))
12188 			return false;
12189 	}
12190 	return true;
12191 }
12192 
12193 enum kfunc_ptr_arg_type {
12194 	KF_ARG_PTR_TO_CTX,
12195 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
12196 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12197 	KF_ARG_PTR_TO_DYNPTR,
12198 	KF_ARG_PTR_TO_ITER,
12199 	KF_ARG_PTR_TO_LIST_HEAD,
12200 	KF_ARG_PTR_TO_LIST_NODE,
12201 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
12202 	KF_ARG_PTR_TO_MEM,
12203 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
12204 	KF_ARG_PTR_TO_CALLBACK,
12205 	KF_ARG_PTR_TO_RB_ROOT,
12206 	KF_ARG_PTR_TO_RB_NODE,
12207 	KF_ARG_PTR_TO_NULL,
12208 	KF_ARG_PTR_TO_CONST_STR,
12209 	KF_ARG_PTR_TO_MAP,
12210 	KF_ARG_PTR_TO_WORKQUEUE,
12211 	KF_ARG_PTR_TO_IRQ_FLAG,
12212 	KF_ARG_PTR_TO_RES_SPIN_LOCK,
12213 	KF_ARG_PTR_TO_TASK_WORK,
12214 };
12215 
12216 enum special_kfunc_type {
12217 	KF_bpf_obj_new_impl,
12218 	KF_bpf_obj_drop_impl,
12219 	KF_bpf_refcount_acquire_impl,
12220 	KF_bpf_list_push_front_impl,
12221 	KF_bpf_list_push_back_impl,
12222 	KF_bpf_list_pop_front,
12223 	KF_bpf_list_pop_back,
12224 	KF_bpf_list_front,
12225 	KF_bpf_list_back,
12226 	KF_bpf_cast_to_kern_ctx,
12227 	KF_bpf_rdonly_cast,
12228 	KF_bpf_rcu_read_lock,
12229 	KF_bpf_rcu_read_unlock,
12230 	KF_bpf_rbtree_remove,
12231 	KF_bpf_rbtree_add_impl,
12232 	KF_bpf_rbtree_first,
12233 	KF_bpf_rbtree_root,
12234 	KF_bpf_rbtree_left,
12235 	KF_bpf_rbtree_right,
12236 	KF_bpf_dynptr_from_skb,
12237 	KF_bpf_dynptr_from_xdp,
12238 	KF_bpf_dynptr_from_skb_meta,
12239 	KF_bpf_xdp_pull_data,
12240 	KF_bpf_dynptr_slice,
12241 	KF_bpf_dynptr_slice_rdwr,
12242 	KF_bpf_dynptr_clone,
12243 	KF_bpf_percpu_obj_new_impl,
12244 	KF_bpf_percpu_obj_drop_impl,
12245 	KF_bpf_throw,
12246 	KF_bpf_wq_set_callback_impl,
12247 	KF_bpf_preempt_disable,
12248 	KF_bpf_preempt_enable,
12249 	KF_bpf_iter_css_task_new,
12250 	KF_bpf_session_cookie,
12251 	KF_bpf_get_kmem_cache,
12252 	KF_bpf_local_irq_save,
12253 	KF_bpf_local_irq_restore,
12254 	KF_bpf_iter_num_new,
12255 	KF_bpf_iter_num_next,
12256 	KF_bpf_iter_num_destroy,
12257 	KF_bpf_set_dentry_xattr,
12258 	KF_bpf_remove_dentry_xattr,
12259 	KF_bpf_res_spin_lock,
12260 	KF_bpf_res_spin_unlock,
12261 	KF_bpf_res_spin_lock_irqsave,
12262 	KF_bpf_res_spin_unlock_irqrestore,
12263 	KF___bpf_trap,
12264 	KF_bpf_task_work_schedule_signal_impl,
12265 	KF_bpf_task_work_schedule_resume_impl,
12266 };
12267 
12268 BTF_ID_LIST(special_kfunc_list)
BTF_ID(func,bpf_obj_new_impl)12269 BTF_ID(func, bpf_obj_new_impl)
12270 BTF_ID(func, bpf_obj_drop_impl)
12271 BTF_ID(func, bpf_refcount_acquire_impl)
12272 BTF_ID(func, bpf_list_push_front_impl)
12273 BTF_ID(func, bpf_list_push_back_impl)
12274 BTF_ID(func, bpf_list_pop_front)
12275 BTF_ID(func, bpf_list_pop_back)
12276 BTF_ID(func, bpf_list_front)
12277 BTF_ID(func, bpf_list_back)
12278 BTF_ID(func, bpf_cast_to_kern_ctx)
12279 BTF_ID(func, bpf_rdonly_cast)
12280 BTF_ID(func, bpf_rcu_read_lock)
12281 BTF_ID(func, bpf_rcu_read_unlock)
12282 BTF_ID(func, bpf_rbtree_remove)
12283 BTF_ID(func, bpf_rbtree_add_impl)
12284 BTF_ID(func, bpf_rbtree_first)
12285 BTF_ID(func, bpf_rbtree_root)
12286 BTF_ID(func, bpf_rbtree_left)
12287 BTF_ID(func, bpf_rbtree_right)
12288 #ifdef CONFIG_NET
12289 BTF_ID(func, bpf_dynptr_from_skb)
12290 BTF_ID(func, bpf_dynptr_from_xdp)
12291 BTF_ID(func, bpf_dynptr_from_skb_meta)
12292 BTF_ID(func, bpf_xdp_pull_data)
12293 #else
12294 BTF_ID_UNUSED
12295 BTF_ID_UNUSED
12296 BTF_ID_UNUSED
12297 BTF_ID_UNUSED
12298 #endif
12299 BTF_ID(func, bpf_dynptr_slice)
12300 BTF_ID(func, bpf_dynptr_slice_rdwr)
12301 BTF_ID(func, bpf_dynptr_clone)
12302 BTF_ID(func, bpf_percpu_obj_new_impl)
12303 BTF_ID(func, bpf_percpu_obj_drop_impl)
12304 BTF_ID(func, bpf_throw)
12305 BTF_ID(func, bpf_wq_set_callback_impl)
12306 BTF_ID(func, bpf_preempt_disable)
12307 BTF_ID(func, bpf_preempt_enable)
12308 #ifdef CONFIG_CGROUPS
12309 BTF_ID(func, bpf_iter_css_task_new)
12310 #else
12311 BTF_ID_UNUSED
12312 #endif
12313 #ifdef CONFIG_BPF_EVENTS
12314 BTF_ID(func, bpf_session_cookie)
12315 #else
12316 BTF_ID_UNUSED
12317 #endif
12318 BTF_ID(func, bpf_get_kmem_cache)
12319 BTF_ID(func, bpf_local_irq_save)
12320 BTF_ID(func, bpf_local_irq_restore)
12321 BTF_ID(func, bpf_iter_num_new)
12322 BTF_ID(func, bpf_iter_num_next)
12323 BTF_ID(func, bpf_iter_num_destroy)
12324 #ifdef CONFIG_BPF_LSM
12325 BTF_ID(func, bpf_set_dentry_xattr)
12326 BTF_ID(func, bpf_remove_dentry_xattr)
12327 #else
12328 BTF_ID_UNUSED
12329 BTF_ID_UNUSED
12330 #endif
12331 BTF_ID(func, bpf_res_spin_lock)
12332 BTF_ID(func, bpf_res_spin_unlock)
12333 BTF_ID(func, bpf_res_spin_lock_irqsave)
12334 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12335 BTF_ID(func, __bpf_trap)
12336 BTF_ID(func, bpf_task_work_schedule_signal_impl)
12337 BTF_ID(func, bpf_task_work_schedule_resume_impl)
12338 
12339 static bool is_task_work_add_kfunc(u32 func_id)
12340 {
12341 	return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal_impl] ||
12342 	       func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume_impl];
12343 }
12344 
is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta * meta)12345 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12346 {
12347 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12348 	    meta->arg_owning_ref) {
12349 		return false;
12350 	}
12351 
12352 	return meta->kfunc_flags & KF_RET_NULL;
12353 }
12354 
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)12355 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12356 {
12357 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12358 }
12359 
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)12360 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12361 {
12362 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12363 }
12364 
is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta * meta)12365 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12366 {
12367 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12368 }
12369 
is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta * meta)12370 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12371 {
12372 	return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12373 }
12374 
is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta * meta)12375 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12376 {
12377 	return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12378 }
12379 
12380 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)12381 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12382 		       struct bpf_kfunc_call_arg_meta *meta,
12383 		       const struct btf_type *t, const struct btf_type *ref_t,
12384 		       const char *ref_tname, const struct btf_param *args,
12385 		       int argno, int nargs)
12386 {
12387 	u32 regno = argno + 1;
12388 	struct bpf_reg_state *regs = cur_regs(env);
12389 	struct bpf_reg_state *reg = &regs[regno];
12390 	bool arg_mem_size = false;
12391 
12392 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12393 		return KF_ARG_PTR_TO_CTX;
12394 
12395 	/* In this function, we verify the kfunc's BTF as per the argument type,
12396 	 * leaving the rest of the verification with respect to the register
12397 	 * type to our caller. When a set of conditions hold in the BTF type of
12398 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12399 	 */
12400 	if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12401 		return KF_ARG_PTR_TO_CTX;
12402 
12403 	if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12404 		return KF_ARG_PTR_TO_NULL;
12405 
12406 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12407 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12408 
12409 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12410 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12411 
12412 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12413 		return KF_ARG_PTR_TO_DYNPTR;
12414 
12415 	if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12416 		return KF_ARG_PTR_TO_ITER;
12417 
12418 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12419 		return KF_ARG_PTR_TO_LIST_HEAD;
12420 
12421 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12422 		return KF_ARG_PTR_TO_LIST_NODE;
12423 
12424 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12425 		return KF_ARG_PTR_TO_RB_ROOT;
12426 
12427 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12428 		return KF_ARG_PTR_TO_RB_NODE;
12429 
12430 	if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12431 		return KF_ARG_PTR_TO_CONST_STR;
12432 
12433 	if (is_kfunc_arg_map(meta->btf, &args[argno]))
12434 		return KF_ARG_PTR_TO_MAP;
12435 
12436 	if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12437 		return KF_ARG_PTR_TO_WORKQUEUE;
12438 
12439 	if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12440 		return KF_ARG_PTR_TO_TASK_WORK;
12441 
12442 	if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12443 		return KF_ARG_PTR_TO_IRQ_FLAG;
12444 
12445 	if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12446 		return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12447 
12448 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12449 		if (!btf_type_is_struct(ref_t)) {
12450 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12451 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12452 			return -EINVAL;
12453 		}
12454 		return KF_ARG_PTR_TO_BTF_ID;
12455 	}
12456 
12457 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12458 		return KF_ARG_PTR_TO_CALLBACK;
12459 
12460 	if (argno + 1 < nargs &&
12461 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
12462 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
12463 		arg_mem_size = true;
12464 
12465 	/* This is the catch all argument type of register types supported by
12466 	 * check_helper_mem_access. However, we only allow when argument type is
12467 	 * pointer to scalar, or struct composed (recursively) of scalars. When
12468 	 * arg_mem_size is true, the pointer can be void *.
12469 	 */
12470 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12471 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12472 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12473 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12474 		return -EINVAL;
12475 	}
12476 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12477 }
12478 
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)12479 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12480 					struct bpf_reg_state *reg,
12481 					const struct btf_type *ref_t,
12482 					const char *ref_tname, u32 ref_id,
12483 					struct bpf_kfunc_call_arg_meta *meta,
12484 					int argno)
12485 {
12486 	const struct btf_type *reg_ref_t;
12487 	bool strict_type_match = false;
12488 	const struct btf *reg_btf;
12489 	const char *reg_ref_tname;
12490 	bool taking_projection;
12491 	bool struct_same;
12492 	u32 reg_ref_id;
12493 
12494 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
12495 		reg_btf = reg->btf;
12496 		reg_ref_id = reg->btf_id;
12497 	} else {
12498 		reg_btf = btf_vmlinux;
12499 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12500 	}
12501 
12502 	/* Enforce strict type matching for calls to kfuncs that are acquiring
12503 	 * or releasing a reference, or are no-cast aliases. We do _not_
12504 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12505 	 * as we want to enable BPF programs to pass types that are bitwise
12506 	 * equivalent without forcing them to explicitly cast with something
12507 	 * like bpf_cast_to_kern_ctx().
12508 	 *
12509 	 * For example, say we had a type like the following:
12510 	 *
12511 	 * struct bpf_cpumask {
12512 	 *	cpumask_t cpumask;
12513 	 *	refcount_t usage;
12514 	 * };
12515 	 *
12516 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12517 	 * to a struct cpumask, so it would be safe to pass a struct
12518 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12519 	 *
12520 	 * The philosophy here is similar to how we allow scalars of different
12521 	 * types to be passed to kfuncs as long as the size is the same. The
12522 	 * only difference here is that we're simply allowing
12523 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12524 	 * resolve types.
12525 	 */
12526 	if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12527 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12528 		strict_type_match = true;
12529 
12530 	WARN_ON_ONCE(is_kfunc_release(meta) &&
12531 		     (reg->off || !tnum_is_const(reg->var_off) ||
12532 		      reg->var_off.value));
12533 
12534 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
12535 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12536 	struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12537 	/* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12538 	 * actually use it -- it must cast to the underlying type. So we allow
12539 	 * caller to pass in the underlying type.
12540 	 */
12541 	taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12542 	if (!taking_projection && !struct_same) {
12543 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12544 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12545 			btf_type_str(reg_ref_t), reg_ref_tname);
12546 		return -EINVAL;
12547 	}
12548 	return 0;
12549 }
12550 
process_irq_flag(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)12551 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12552 			     struct bpf_kfunc_call_arg_meta *meta)
12553 {
12554 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
12555 	int err, kfunc_class = IRQ_NATIVE_KFUNC;
12556 	bool irq_save;
12557 
12558 	if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12559 	    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12560 		irq_save = true;
12561 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12562 			kfunc_class = IRQ_LOCK_KFUNC;
12563 	} else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12564 		   meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12565 		irq_save = false;
12566 		if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12567 			kfunc_class = IRQ_LOCK_KFUNC;
12568 	} else {
12569 		verifier_bug(env, "unknown irq flags kfunc");
12570 		return -EFAULT;
12571 	}
12572 
12573 	if (irq_save) {
12574 		if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12575 			verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12576 			return -EINVAL;
12577 		}
12578 
12579 		err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12580 		if (err)
12581 			return err;
12582 
12583 		err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12584 		if (err)
12585 			return err;
12586 	} else {
12587 		err = is_irq_flag_reg_valid_init(env, reg);
12588 		if (err) {
12589 			verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12590 			return err;
12591 		}
12592 
12593 		err = mark_irq_flag_read(env, reg);
12594 		if (err)
12595 			return err;
12596 
12597 		err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12598 		if (err)
12599 			return err;
12600 	}
12601 	return 0;
12602 }
12603 
12604 
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12605 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12606 {
12607 	struct btf_record *rec = reg_btf_record(reg);
12608 
12609 	if (!env->cur_state->active_locks) {
12610 		verifier_bug(env, "%s w/o active lock", __func__);
12611 		return -EFAULT;
12612 	}
12613 
12614 	if (type_flag(reg->type) & NON_OWN_REF) {
12615 		verifier_bug(env, "NON_OWN_REF already set");
12616 		return -EFAULT;
12617 	}
12618 
12619 	reg->type |= NON_OWN_REF;
12620 	if (rec->refcount_off >= 0)
12621 		reg->type |= MEM_RCU;
12622 
12623 	return 0;
12624 }
12625 
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)12626 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12627 {
12628 	struct bpf_verifier_state *state = env->cur_state;
12629 	struct bpf_func_state *unused;
12630 	struct bpf_reg_state *reg;
12631 	int i;
12632 
12633 	if (!ref_obj_id) {
12634 		verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12635 		return -EFAULT;
12636 	}
12637 
12638 	for (i = 0; i < state->acquired_refs; i++) {
12639 		if (state->refs[i].id != ref_obj_id)
12640 			continue;
12641 
12642 		/* Clear ref_obj_id here so release_reference doesn't clobber
12643 		 * the whole reg
12644 		 */
12645 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12646 			if (reg->ref_obj_id == ref_obj_id) {
12647 				reg->ref_obj_id = 0;
12648 				ref_set_non_owning(env, reg);
12649 			}
12650 		}));
12651 		return 0;
12652 	}
12653 
12654 	verifier_bug(env, "ref state missing for ref_obj_id");
12655 	return -EFAULT;
12656 }
12657 
12658 /* Implementation details:
12659  *
12660  * Each register points to some region of memory, which we define as an
12661  * allocation. Each allocation may embed a bpf_spin_lock which protects any
12662  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12663  * allocation. The lock and the data it protects are colocated in the same
12664  * memory region.
12665  *
12666  * Hence, everytime a register holds a pointer value pointing to such
12667  * allocation, the verifier preserves a unique reg->id for it.
12668  *
12669  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12670  * bpf_spin_lock is called.
12671  *
12672  * To enable this, lock state in the verifier captures two values:
12673  *	active_lock.ptr = Register's type specific pointer
12674  *	active_lock.id  = A unique ID for each register pointer value
12675  *
12676  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12677  * supported register types.
12678  *
12679  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12680  * allocated objects is the reg->btf pointer.
12681  *
12682  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12683  * can establish the provenance of the map value statically for each distinct
12684  * lookup into such maps. They always contain a single map value hence unique
12685  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12686  *
12687  * So, in case of global variables, they use array maps with max_entries = 1,
12688  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12689  * into the same map value as max_entries is 1, as described above).
12690  *
12691  * In case of inner map lookups, the inner map pointer has same map_ptr as the
12692  * outer map pointer (in verifier context), but each lookup into an inner map
12693  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12694  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12695  * will get different reg->id assigned to each lookup, hence different
12696  * active_lock.id.
12697  *
12698  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12699  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12700  * returned from bpf_obj_new. Each allocation receives a new reg->id.
12701  */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12702 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12703 {
12704 	struct bpf_reference_state *s;
12705 	void *ptr;
12706 	u32 id;
12707 
12708 	switch ((int)reg->type) {
12709 	case PTR_TO_MAP_VALUE:
12710 		ptr = reg->map_ptr;
12711 		break;
12712 	case PTR_TO_BTF_ID | MEM_ALLOC:
12713 		ptr = reg->btf;
12714 		break;
12715 	default:
12716 		verifier_bug(env, "unknown reg type for lock check");
12717 		return -EFAULT;
12718 	}
12719 	id = reg->id;
12720 
12721 	if (!env->cur_state->active_locks)
12722 		return -EINVAL;
12723 	s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12724 	if (!s) {
12725 		verbose(env, "held lock and object are not in the same allocation\n");
12726 		return -EINVAL;
12727 	}
12728 	return 0;
12729 }
12730 
is_bpf_list_api_kfunc(u32 btf_id)12731 static bool is_bpf_list_api_kfunc(u32 btf_id)
12732 {
12733 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12734 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12735 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12736 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12737 	       btf_id == special_kfunc_list[KF_bpf_list_front] ||
12738 	       btf_id == special_kfunc_list[KF_bpf_list_back];
12739 }
12740 
is_bpf_rbtree_api_kfunc(u32 btf_id)12741 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12742 {
12743 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12744 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12745 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12746 	       btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12747 	       btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12748 	       btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12749 }
12750 
is_bpf_iter_num_api_kfunc(u32 btf_id)12751 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12752 {
12753 	return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12754 	       btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12755 	       btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12756 }
12757 
is_bpf_graph_api_kfunc(u32 btf_id)12758 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12759 {
12760 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12761 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12762 }
12763 
is_bpf_res_spin_lock_kfunc(u32 btf_id)12764 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12765 {
12766 	return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12767 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12768 	       btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12769 	       btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12770 }
12771 
kfunc_spin_allowed(u32 btf_id)12772 static bool kfunc_spin_allowed(u32 btf_id)
12773 {
12774 	return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12775 	       is_bpf_res_spin_lock_kfunc(btf_id);
12776 }
12777 
is_sync_callback_calling_kfunc(u32 btf_id)12778 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12779 {
12780 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12781 }
12782 
is_async_callback_calling_kfunc(u32 btf_id)12783 static bool is_async_callback_calling_kfunc(u32 btf_id)
12784 {
12785 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12786 	       is_task_work_add_kfunc(btf_id);
12787 }
12788 
is_bpf_throw_kfunc(struct bpf_insn * insn)12789 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12790 {
12791 	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12792 	       insn->imm == special_kfunc_list[KF_bpf_throw];
12793 }
12794 
is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)12795 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12796 {
12797 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12798 }
12799 
is_callback_calling_kfunc(u32 btf_id)12800 static bool is_callback_calling_kfunc(u32 btf_id)
12801 {
12802 	return is_sync_callback_calling_kfunc(btf_id) ||
12803 	       is_async_callback_calling_kfunc(btf_id);
12804 }
12805 
is_rbtree_lock_required_kfunc(u32 btf_id)12806 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12807 {
12808 	return is_bpf_rbtree_api_kfunc(btf_id);
12809 }
12810 
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)12811 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12812 					  enum btf_field_type head_field_type,
12813 					  u32 kfunc_btf_id)
12814 {
12815 	bool ret;
12816 
12817 	switch (head_field_type) {
12818 	case BPF_LIST_HEAD:
12819 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12820 		break;
12821 	case BPF_RB_ROOT:
12822 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12823 		break;
12824 	default:
12825 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12826 			btf_field_type_name(head_field_type));
12827 		return false;
12828 	}
12829 
12830 	if (!ret)
12831 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12832 			btf_field_type_name(head_field_type));
12833 	return ret;
12834 }
12835 
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)12836 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12837 					  enum btf_field_type node_field_type,
12838 					  u32 kfunc_btf_id)
12839 {
12840 	bool ret;
12841 
12842 	switch (node_field_type) {
12843 	case BPF_LIST_NODE:
12844 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12845 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12846 		break;
12847 	case BPF_RB_NODE:
12848 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12849 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12850 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12851 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12852 		break;
12853 	default:
12854 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12855 			btf_field_type_name(node_field_type));
12856 		return false;
12857 	}
12858 
12859 	if (!ret)
12860 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12861 			btf_field_type_name(node_field_type));
12862 	return ret;
12863 }
12864 
12865 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)12866 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12867 				   struct bpf_reg_state *reg, u32 regno,
12868 				   struct bpf_kfunc_call_arg_meta *meta,
12869 				   enum btf_field_type head_field_type,
12870 				   struct btf_field **head_field)
12871 {
12872 	const char *head_type_name;
12873 	struct btf_field *field;
12874 	struct btf_record *rec;
12875 	u32 head_off;
12876 
12877 	if (meta->btf != btf_vmlinux) {
12878 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12879 		return -EFAULT;
12880 	}
12881 
12882 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
12883 		return -EFAULT;
12884 
12885 	head_type_name = btf_field_type_name(head_field_type);
12886 	if (!tnum_is_const(reg->var_off)) {
12887 		verbose(env,
12888 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12889 			regno, head_type_name);
12890 		return -EINVAL;
12891 	}
12892 
12893 	rec = reg_btf_record(reg);
12894 	head_off = reg->off + reg->var_off.value;
12895 	field = btf_record_find(rec, head_off, head_field_type);
12896 	if (!field) {
12897 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
12898 		return -EINVAL;
12899 	}
12900 
12901 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
12902 	if (check_reg_allocation_locked(env, reg)) {
12903 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
12904 			rec->spin_lock_off, head_type_name);
12905 		return -EINVAL;
12906 	}
12907 
12908 	if (*head_field) {
12909 		verifier_bug(env, "repeating %s arg", head_type_name);
12910 		return -EFAULT;
12911 	}
12912 	*head_field = field;
12913 	return 0;
12914 }
12915 
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)12916 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
12917 					   struct bpf_reg_state *reg, u32 regno,
12918 					   struct bpf_kfunc_call_arg_meta *meta)
12919 {
12920 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
12921 							  &meta->arg_list_head.field);
12922 }
12923 
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)12924 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
12925 					     struct bpf_reg_state *reg, u32 regno,
12926 					     struct bpf_kfunc_call_arg_meta *meta)
12927 {
12928 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
12929 							  &meta->arg_rbtree_root.field);
12930 }
12931 
12932 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)12933 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
12934 				   struct bpf_reg_state *reg, u32 regno,
12935 				   struct bpf_kfunc_call_arg_meta *meta,
12936 				   enum btf_field_type head_field_type,
12937 				   enum btf_field_type node_field_type,
12938 				   struct btf_field **node_field)
12939 {
12940 	const char *node_type_name;
12941 	const struct btf_type *et, *t;
12942 	struct btf_field *field;
12943 	u32 node_off;
12944 
12945 	if (meta->btf != btf_vmlinux) {
12946 		verifier_bug(env, "unexpected btf mismatch in kfunc call");
12947 		return -EFAULT;
12948 	}
12949 
12950 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
12951 		return -EFAULT;
12952 
12953 	node_type_name = btf_field_type_name(node_field_type);
12954 	if (!tnum_is_const(reg->var_off)) {
12955 		verbose(env,
12956 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
12957 			regno, node_type_name);
12958 		return -EINVAL;
12959 	}
12960 
12961 	node_off = reg->off + reg->var_off.value;
12962 	field = reg_find_field_offset(reg, node_off, node_field_type);
12963 	if (!field) {
12964 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
12965 		return -EINVAL;
12966 	}
12967 
12968 	field = *node_field;
12969 
12970 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
12971 	t = btf_type_by_id(reg->btf, reg->btf_id);
12972 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
12973 				  field->graph_root.value_btf_id, true)) {
12974 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
12975 			"in struct %s, but arg is at offset=%d in struct %s\n",
12976 			btf_field_type_name(head_field_type),
12977 			btf_field_type_name(node_field_type),
12978 			field->graph_root.node_offset,
12979 			btf_name_by_offset(field->graph_root.btf, et->name_off),
12980 			node_off, btf_name_by_offset(reg->btf, t->name_off));
12981 		return -EINVAL;
12982 	}
12983 	meta->arg_btf = reg->btf;
12984 	meta->arg_btf_id = reg->btf_id;
12985 
12986 	if (node_off != field->graph_root.node_offset) {
12987 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
12988 			node_off, btf_field_type_name(node_field_type),
12989 			field->graph_root.node_offset,
12990 			btf_name_by_offset(field->graph_root.btf, et->name_off));
12991 		return -EINVAL;
12992 	}
12993 
12994 	return 0;
12995 }
12996 
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)12997 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
12998 					   struct bpf_reg_state *reg, u32 regno,
12999 					   struct bpf_kfunc_call_arg_meta *meta)
13000 {
13001 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13002 						  BPF_LIST_HEAD, BPF_LIST_NODE,
13003 						  &meta->arg_list_head.field);
13004 }
13005 
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)13006 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13007 					     struct bpf_reg_state *reg, u32 regno,
13008 					     struct bpf_kfunc_call_arg_meta *meta)
13009 {
13010 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13011 						  BPF_RB_ROOT, BPF_RB_NODE,
13012 						  &meta->arg_rbtree_root.field);
13013 }
13014 
13015 /*
13016  * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13017  * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13018  * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13019  * them can only be attached to some specific hook points.
13020  */
check_css_task_iter_allowlist(struct bpf_verifier_env * env)13021 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13022 {
13023 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13024 
13025 	switch (prog_type) {
13026 	case BPF_PROG_TYPE_LSM:
13027 		return true;
13028 	case BPF_PROG_TYPE_TRACING:
13029 		if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13030 			return true;
13031 		fallthrough;
13032 	default:
13033 		return in_sleepable(env);
13034 	}
13035 }
13036 
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)13037 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13038 			    int insn_idx)
13039 {
13040 	const char *func_name = meta->func_name, *ref_tname;
13041 	const struct btf *btf = meta->btf;
13042 	const struct btf_param *args;
13043 	struct btf_record *rec;
13044 	u32 i, nargs;
13045 	int ret;
13046 
13047 	args = (const struct btf_param *)(meta->func_proto + 1);
13048 	nargs = btf_type_vlen(meta->func_proto);
13049 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13050 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13051 			MAX_BPF_FUNC_REG_ARGS);
13052 		return -EINVAL;
13053 	}
13054 
13055 	/* Check that BTF function arguments match actual types that the
13056 	 * verifier sees.
13057 	 */
13058 	for (i = 0; i < nargs; i++) {
13059 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
13060 		const struct btf_type *t, *ref_t, *resolve_ret;
13061 		enum bpf_arg_type arg_type = ARG_DONTCARE;
13062 		u32 regno = i + 1, ref_id, type_size;
13063 		bool is_ret_buf_sz = false;
13064 		int kf_arg_type;
13065 
13066 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13067 
13068 		if (is_kfunc_arg_ignore(btf, &args[i]))
13069 			continue;
13070 
13071 		if (is_kfunc_arg_prog(btf, &args[i])) {
13072 			/* Used to reject repeated use of __prog. */
13073 			if (meta->arg_prog) {
13074 				verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13075 				return -EFAULT;
13076 			}
13077 			meta->arg_prog = true;
13078 			cur_aux(env)->arg_prog = regno;
13079 			continue;
13080 		}
13081 
13082 		if (btf_type_is_scalar(t)) {
13083 			if (reg->type != SCALAR_VALUE) {
13084 				verbose(env, "R%d is not a scalar\n", regno);
13085 				return -EINVAL;
13086 			}
13087 
13088 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13089 				if (meta->arg_constant.found) {
13090 					verifier_bug(env, "only one constant argument permitted");
13091 					return -EFAULT;
13092 				}
13093 				if (!tnum_is_const(reg->var_off)) {
13094 					verbose(env, "R%d must be a known constant\n", regno);
13095 					return -EINVAL;
13096 				}
13097 				ret = mark_chain_precision(env, regno);
13098 				if (ret < 0)
13099 					return ret;
13100 				meta->arg_constant.found = true;
13101 				meta->arg_constant.value = reg->var_off.value;
13102 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13103 				meta->r0_rdonly = true;
13104 				is_ret_buf_sz = true;
13105 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13106 				is_ret_buf_sz = true;
13107 			}
13108 
13109 			if (is_ret_buf_sz) {
13110 				if (meta->r0_size) {
13111 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13112 					return -EINVAL;
13113 				}
13114 
13115 				if (!tnum_is_const(reg->var_off)) {
13116 					verbose(env, "R%d is not a const\n", regno);
13117 					return -EINVAL;
13118 				}
13119 
13120 				meta->r0_size = reg->var_off.value;
13121 				ret = mark_chain_precision(env, regno);
13122 				if (ret)
13123 					return ret;
13124 			}
13125 			continue;
13126 		}
13127 
13128 		if (!btf_type_is_ptr(t)) {
13129 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13130 			return -EINVAL;
13131 		}
13132 
13133 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13134 		    (register_is_null(reg) || type_may_be_null(reg->type)) &&
13135 			!is_kfunc_arg_nullable(meta->btf, &args[i])) {
13136 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13137 			return -EACCES;
13138 		}
13139 
13140 		if (reg->ref_obj_id) {
13141 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
13142 				verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13143 					     regno, reg->ref_obj_id,
13144 					     meta->ref_obj_id);
13145 				return -EFAULT;
13146 			}
13147 			meta->ref_obj_id = reg->ref_obj_id;
13148 			if (is_kfunc_release(meta))
13149 				meta->release_regno = regno;
13150 		}
13151 
13152 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13153 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13154 
13155 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13156 		if (kf_arg_type < 0)
13157 			return kf_arg_type;
13158 
13159 		switch (kf_arg_type) {
13160 		case KF_ARG_PTR_TO_NULL:
13161 			continue;
13162 		case KF_ARG_PTR_TO_MAP:
13163 			if (!reg->map_ptr) {
13164 				verbose(env, "pointer in R%d isn't map pointer\n", regno);
13165 				return -EINVAL;
13166 			}
13167 			if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13168 					      reg->map_ptr->record->task_work_off >= 0)) {
13169 				/* Use map_uid (which is unique id of inner map) to reject:
13170 				 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13171 				 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13172 				 * if (inner_map1 && inner_map2) {
13173 				 *     wq = bpf_map_lookup_elem(inner_map1);
13174 				 *     if (wq)
13175 				 *         // mismatch would have been allowed
13176 				 *         bpf_wq_init(wq, inner_map2);
13177 				 * }
13178 				 *
13179 				 * Comparing map_ptr is enough to distinguish normal and outer maps.
13180 				 */
13181 				if (meta->map.ptr != reg->map_ptr ||
13182 				    meta->map.uid != reg->map_uid) {
13183 					if (reg->map_ptr->record->task_work_off >= 0) {
13184 						verbose(env,
13185 							"bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13186 							meta->map.uid, reg->map_uid);
13187 						return -EINVAL;
13188 					}
13189 					verbose(env,
13190 						"workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13191 						meta->map.uid, reg->map_uid);
13192 					return -EINVAL;
13193 				}
13194 			}
13195 			meta->map.ptr = reg->map_ptr;
13196 			meta->map.uid = reg->map_uid;
13197 			fallthrough;
13198 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13199 		case KF_ARG_PTR_TO_BTF_ID:
13200 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13201 				break;
13202 
13203 			if (!is_trusted_reg(reg)) {
13204 				if (!is_kfunc_rcu(meta)) {
13205 					verbose(env, "R%d must be referenced or trusted\n", regno);
13206 					return -EINVAL;
13207 				}
13208 				if (!is_rcu_reg(reg)) {
13209 					verbose(env, "R%d must be a rcu pointer\n", regno);
13210 					return -EINVAL;
13211 				}
13212 			}
13213 			fallthrough;
13214 		case KF_ARG_PTR_TO_CTX:
13215 		case KF_ARG_PTR_TO_DYNPTR:
13216 		case KF_ARG_PTR_TO_ITER:
13217 		case KF_ARG_PTR_TO_LIST_HEAD:
13218 		case KF_ARG_PTR_TO_LIST_NODE:
13219 		case KF_ARG_PTR_TO_RB_ROOT:
13220 		case KF_ARG_PTR_TO_RB_NODE:
13221 		case KF_ARG_PTR_TO_MEM:
13222 		case KF_ARG_PTR_TO_MEM_SIZE:
13223 		case KF_ARG_PTR_TO_CALLBACK:
13224 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13225 		case KF_ARG_PTR_TO_CONST_STR:
13226 		case KF_ARG_PTR_TO_WORKQUEUE:
13227 		case KF_ARG_PTR_TO_TASK_WORK:
13228 		case KF_ARG_PTR_TO_IRQ_FLAG:
13229 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13230 			break;
13231 		default:
13232 			verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13233 			return -EFAULT;
13234 		}
13235 
13236 		if (is_kfunc_release(meta) && reg->ref_obj_id)
13237 			arg_type |= OBJ_RELEASE;
13238 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13239 		if (ret < 0)
13240 			return ret;
13241 
13242 		switch (kf_arg_type) {
13243 		case KF_ARG_PTR_TO_CTX:
13244 			if (reg->type != PTR_TO_CTX) {
13245 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13246 					i, reg_type_str(env, reg->type));
13247 				return -EINVAL;
13248 			}
13249 
13250 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13251 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13252 				if (ret < 0)
13253 					return -EINVAL;
13254 				meta->ret_btf_id  = ret;
13255 			}
13256 			break;
13257 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13258 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13259 				if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13260 					verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13261 					return -EINVAL;
13262 				}
13263 			} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13264 				if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13265 					verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13266 					return -EINVAL;
13267 				}
13268 			} else {
13269 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13270 				return -EINVAL;
13271 			}
13272 			if (!reg->ref_obj_id) {
13273 				verbose(env, "allocated object must be referenced\n");
13274 				return -EINVAL;
13275 			}
13276 			if (meta->btf == btf_vmlinux) {
13277 				meta->arg_btf = reg->btf;
13278 				meta->arg_btf_id = reg->btf_id;
13279 			}
13280 			break;
13281 		case KF_ARG_PTR_TO_DYNPTR:
13282 		{
13283 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13284 			int clone_ref_obj_id = 0;
13285 
13286 			if (reg->type == CONST_PTR_TO_DYNPTR)
13287 				dynptr_arg_type |= MEM_RDONLY;
13288 
13289 			if (is_kfunc_arg_uninit(btf, &args[i]))
13290 				dynptr_arg_type |= MEM_UNINIT;
13291 
13292 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13293 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
13294 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13295 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
13296 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13297 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13298 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13299 				   (dynptr_arg_type & MEM_UNINIT)) {
13300 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13301 
13302 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13303 					verifier_bug(env, "no dynptr type for parent of clone");
13304 					return -EFAULT;
13305 				}
13306 
13307 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13308 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13309 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13310 					verifier_bug(env, "missing ref obj id for parent of clone");
13311 					return -EFAULT;
13312 				}
13313 			}
13314 
13315 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13316 			if (ret < 0)
13317 				return ret;
13318 
13319 			if (!(dynptr_arg_type & MEM_UNINIT)) {
13320 				int id = dynptr_id(env, reg);
13321 
13322 				if (id < 0) {
13323 					verifier_bug(env, "failed to obtain dynptr id");
13324 					return id;
13325 				}
13326 				meta->initialized_dynptr.id = id;
13327 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13328 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13329 			}
13330 
13331 			break;
13332 		}
13333 		case KF_ARG_PTR_TO_ITER:
13334 			if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13335 				if (!check_css_task_iter_allowlist(env)) {
13336 					verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13337 					return -EINVAL;
13338 				}
13339 			}
13340 			ret = process_iter_arg(env, regno, insn_idx, meta);
13341 			if (ret < 0)
13342 				return ret;
13343 			break;
13344 		case KF_ARG_PTR_TO_LIST_HEAD:
13345 			if (reg->type != PTR_TO_MAP_VALUE &&
13346 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13347 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13348 				return -EINVAL;
13349 			}
13350 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13351 				verbose(env, "allocated object must be referenced\n");
13352 				return -EINVAL;
13353 			}
13354 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13355 			if (ret < 0)
13356 				return ret;
13357 			break;
13358 		case KF_ARG_PTR_TO_RB_ROOT:
13359 			if (reg->type != PTR_TO_MAP_VALUE &&
13360 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13361 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13362 				return -EINVAL;
13363 			}
13364 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13365 				verbose(env, "allocated object must be referenced\n");
13366 				return -EINVAL;
13367 			}
13368 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13369 			if (ret < 0)
13370 				return ret;
13371 			break;
13372 		case KF_ARG_PTR_TO_LIST_NODE:
13373 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13374 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
13375 				return -EINVAL;
13376 			}
13377 			if (!reg->ref_obj_id) {
13378 				verbose(env, "allocated object must be referenced\n");
13379 				return -EINVAL;
13380 			}
13381 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13382 			if (ret < 0)
13383 				return ret;
13384 			break;
13385 		case KF_ARG_PTR_TO_RB_NODE:
13386 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13387 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13388 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
13389 					return -EINVAL;
13390 				}
13391 				if (!reg->ref_obj_id) {
13392 					verbose(env, "allocated object must be referenced\n");
13393 					return -EINVAL;
13394 				}
13395 			} else {
13396 				if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13397 					verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13398 					return -EINVAL;
13399 				}
13400 				if (in_rbtree_lock_required_cb(env)) {
13401 					verbose(env, "%s not allowed in rbtree cb\n", func_name);
13402 					return -EINVAL;
13403 				}
13404 			}
13405 
13406 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13407 			if (ret < 0)
13408 				return ret;
13409 			break;
13410 		case KF_ARG_PTR_TO_MAP:
13411 			/* If argument has '__map' suffix expect 'struct bpf_map *' */
13412 			ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13413 			ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13414 			ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13415 			fallthrough;
13416 		case KF_ARG_PTR_TO_BTF_ID:
13417 			/* Only base_type is checked, further checks are done here */
13418 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13419 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13420 			    !reg2btf_ids[base_type(reg->type)]) {
13421 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13422 				verbose(env, "expected %s or socket\n",
13423 					reg_type_str(env, base_type(reg->type) |
13424 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13425 				return -EINVAL;
13426 			}
13427 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13428 			if (ret < 0)
13429 				return ret;
13430 			break;
13431 		case KF_ARG_PTR_TO_MEM:
13432 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13433 			if (IS_ERR(resolve_ret)) {
13434 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13435 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13436 				return -EINVAL;
13437 			}
13438 			ret = check_mem_reg(env, reg, regno, type_size);
13439 			if (ret < 0)
13440 				return ret;
13441 			break;
13442 		case KF_ARG_PTR_TO_MEM_SIZE:
13443 		{
13444 			struct bpf_reg_state *buff_reg = &regs[regno];
13445 			const struct btf_param *buff_arg = &args[i];
13446 			struct bpf_reg_state *size_reg = &regs[regno + 1];
13447 			const struct btf_param *size_arg = &args[i + 1];
13448 
13449 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13450 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13451 				if (ret < 0) {
13452 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13453 					return ret;
13454 				}
13455 			}
13456 
13457 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13458 				if (meta->arg_constant.found) {
13459 					verifier_bug(env, "only one constant argument permitted");
13460 					return -EFAULT;
13461 				}
13462 				if (!tnum_is_const(size_reg->var_off)) {
13463 					verbose(env, "R%d must be a known constant\n", regno + 1);
13464 					return -EINVAL;
13465 				}
13466 				meta->arg_constant.found = true;
13467 				meta->arg_constant.value = size_reg->var_off.value;
13468 			}
13469 
13470 			/* Skip next '__sz' or '__szk' argument */
13471 			i++;
13472 			break;
13473 		}
13474 		case KF_ARG_PTR_TO_CALLBACK:
13475 			if (reg->type != PTR_TO_FUNC) {
13476 				verbose(env, "arg%d expected pointer to func\n", i);
13477 				return -EINVAL;
13478 			}
13479 			meta->subprogno = reg->subprogno;
13480 			break;
13481 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13482 			if (!type_is_ptr_alloc_obj(reg->type)) {
13483 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13484 				return -EINVAL;
13485 			}
13486 			if (!type_is_non_owning_ref(reg->type))
13487 				meta->arg_owning_ref = true;
13488 
13489 			rec = reg_btf_record(reg);
13490 			if (!rec) {
13491 				verifier_bug(env, "Couldn't find btf_record");
13492 				return -EFAULT;
13493 			}
13494 
13495 			if (rec->refcount_off < 0) {
13496 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13497 				return -EINVAL;
13498 			}
13499 
13500 			meta->arg_btf = reg->btf;
13501 			meta->arg_btf_id = reg->btf_id;
13502 			break;
13503 		case KF_ARG_PTR_TO_CONST_STR:
13504 			if (reg->type != PTR_TO_MAP_VALUE) {
13505 				verbose(env, "arg#%d doesn't point to a const string\n", i);
13506 				return -EINVAL;
13507 			}
13508 			ret = check_reg_const_str(env, reg, regno);
13509 			if (ret)
13510 				return ret;
13511 			break;
13512 		case KF_ARG_PTR_TO_WORKQUEUE:
13513 			if (reg->type != PTR_TO_MAP_VALUE) {
13514 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13515 				return -EINVAL;
13516 			}
13517 			ret = process_wq_func(env, regno, meta);
13518 			if (ret < 0)
13519 				return ret;
13520 			break;
13521 		case KF_ARG_PTR_TO_TASK_WORK:
13522 			if (reg->type != PTR_TO_MAP_VALUE) {
13523 				verbose(env, "arg#%d doesn't point to a map value\n", i);
13524 				return -EINVAL;
13525 			}
13526 			ret = process_task_work_func(env, regno, meta);
13527 			if (ret < 0)
13528 				return ret;
13529 			break;
13530 		case KF_ARG_PTR_TO_IRQ_FLAG:
13531 			if (reg->type != PTR_TO_STACK) {
13532 				verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13533 				return -EINVAL;
13534 			}
13535 			ret = process_irq_flag(env, regno, meta);
13536 			if (ret < 0)
13537 				return ret;
13538 			break;
13539 		case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13540 		{
13541 			int flags = PROCESS_RES_LOCK;
13542 
13543 			if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13544 				verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13545 				return -EINVAL;
13546 			}
13547 
13548 			if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13549 				return -EFAULT;
13550 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13551 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13552 				flags |= PROCESS_SPIN_LOCK;
13553 			if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13554 			    meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13555 				flags |= PROCESS_LOCK_IRQ;
13556 			ret = process_spin_lock(env, regno, flags);
13557 			if (ret < 0)
13558 				return ret;
13559 			break;
13560 		}
13561 		}
13562 	}
13563 
13564 	if (is_kfunc_release(meta) && !meta->release_regno) {
13565 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13566 			func_name);
13567 		return -EINVAL;
13568 	}
13569 
13570 	return 0;
13571 }
13572 
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)13573 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13574 			    struct bpf_insn *insn,
13575 			    struct bpf_kfunc_call_arg_meta *meta,
13576 			    const char **kfunc_name)
13577 {
13578 	const struct btf_type *func, *func_proto;
13579 	u32 func_id, *kfunc_flags;
13580 	const char *func_name;
13581 	struct btf *desc_btf;
13582 
13583 	if (kfunc_name)
13584 		*kfunc_name = NULL;
13585 
13586 	if (!insn->imm)
13587 		return -EINVAL;
13588 
13589 	desc_btf = find_kfunc_desc_btf(env, insn->off);
13590 	if (IS_ERR(desc_btf))
13591 		return PTR_ERR(desc_btf);
13592 
13593 	func_id = insn->imm;
13594 	func = btf_type_by_id(desc_btf, func_id);
13595 	func_name = btf_name_by_offset(desc_btf, func->name_off);
13596 	if (kfunc_name)
13597 		*kfunc_name = func_name;
13598 	func_proto = btf_type_by_id(desc_btf, func->type);
13599 
13600 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13601 	if (!kfunc_flags) {
13602 		return -EACCES;
13603 	}
13604 
13605 	memset(meta, 0, sizeof(*meta));
13606 	meta->btf = desc_btf;
13607 	meta->func_id = func_id;
13608 	meta->kfunc_flags = *kfunc_flags;
13609 	meta->func_proto = func_proto;
13610 	meta->func_name = func_name;
13611 
13612 	return 0;
13613 }
13614 
13615 /* check special kfuncs and return:
13616  *  1  - not fall-through to 'else' branch, continue verification
13617  *  0  - fall-through to 'else' branch
13618  * < 0 - not fall-through to 'else' branch, return error
13619  */
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)13620 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13621 			       struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13622 			       const struct btf_type *ptr_type, struct btf *desc_btf)
13623 {
13624 	const struct btf_type *ret_t;
13625 	int err = 0;
13626 
13627 	if (meta->btf != btf_vmlinux)
13628 		return 0;
13629 
13630 	if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13631 	    meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13632 		struct btf_struct_meta *struct_meta;
13633 		struct btf *ret_btf;
13634 		u32 ret_btf_id;
13635 
13636 		if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13637 			return -ENOMEM;
13638 
13639 		if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13640 			verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13641 			return -EINVAL;
13642 		}
13643 
13644 		ret_btf = env->prog->aux->btf;
13645 		ret_btf_id = meta->arg_constant.value;
13646 
13647 		/* This may be NULL due to user not supplying a BTF */
13648 		if (!ret_btf) {
13649 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13650 			return -EINVAL;
13651 		}
13652 
13653 		ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13654 		if (!ret_t || !__btf_type_is_struct(ret_t)) {
13655 			verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13656 			return -EINVAL;
13657 		}
13658 
13659 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13660 			if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13661 				verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13662 					ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13663 				return -EINVAL;
13664 			}
13665 
13666 			if (!bpf_global_percpu_ma_set) {
13667 				mutex_lock(&bpf_percpu_ma_lock);
13668 				if (!bpf_global_percpu_ma_set) {
13669 					/* Charge memory allocated with bpf_global_percpu_ma to
13670 					 * root memcg. The obj_cgroup for root memcg is NULL.
13671 					 */
13672 					err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13673 					if (!err)
13674 						bpf_global_percpu_ma_set = true;
13675 				}
13676 				mutex_unlock(&bpf_percpu_ma_lock);
13677 				if (err)
13678 					return err;
13679 			}
13680 
13681 			mutex_lock(&bpf_percpu_ma_lock);
13682 			err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13683 			mutex_unlock(&bpf_percpu_ma_lock);
13684 			if (err)
13685 				return err;
13686 		}
13687 
13688 		struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13689 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13690 			if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13691 				verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13692 				return -EINVAL;
13693 			}
13694 
13695 			if (struct_meta) {
13696 				verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13697 				return -EINVAL;
13698 			}
13699 		}
13700 
13701 		mark_reg_known_zero(env, regs, BPF_REG_0);
13702 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13703 		regs[BPF_REG_0].btf = ret_btf;
13704 		regs[BPF_REG_0].btf_id = ret_btf_id;
13705 		if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13706 			regs[BPF_REG_0].type |= MEM_PERCPU;
13707 
13708 		insn_aux->obj_new_size = ret_t->size;
13709 		insn_aux->kptr_struct_meta = struct_meta;
13710 	} else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13711 		mark_reg_known_zero(env, regs, BPF_REG_0);
13712 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13713 		regs[BPF_REG_0].btf = meta->arg_btf;
13714 		regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13715 
13716 		insn_aux->kptr_struct_meta =
13717 			btf_find_struct_meta(meta->arg_btf,
13718 					     meta->arg_btf_id);
13719 	} else if (is_list_node_type(ptr_type)) {
13720 		struct btf_field *field = meta->arg_list_head.field;
13721 
13722 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13723 	} else if (is_rbtree_node_type(ptr_type)) {
13724 		struct btf_field *field = meta->arg_rbtree_root.field;
13725 
13726 		mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13727 	} else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13728 		mark_reg_known_zero(env, regs, BPF_REG_0);
13729 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13730 		regs[BPF_REG_0].btf = desc_btf;
13731 		regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13732 	} else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13733 		ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13734 		if (!ret_t) {
13735 			verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13736 				meta->arg_constant.value);
13737 			return -EINVAL;
13738 		} else if (btf_type_is_struct(ret_t)) {
13739 			mark_reg_known_zero(env, regs, BPF_REG_0);
13740 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13741 			regs[BPF_REG_0].btf = desc_btf;
13742 			regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13743 		} else if (btf_type_is_void(ret_t)) {
13744 			mark_reg_known_zero(env, regs, BPF_REG_0);
13745 			regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13746 			regs[BPF_REG_0].mem_size = 0;
13747 		} else {
13748 			verbose(env,
13749 				"kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13750 			return -EINVAL;
13751 		}
13752 	} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13753 		   meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13754 		enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13755 
13756 		mark_reg_known_zero(env, regs, BPF_REG_0);
13757 
13758 		if (!meta->arg_constant.found) {
13759 			verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13760 			return -EFAULT;
13761 		}
13762 
13763 		regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13764 
13765 		/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13766 		regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13767 
13768 		if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13769 			regs[BPF_REG_0].type |= MEM_RDONLY;
13770 		} else {
13771 			/* this will set env->seen_direct_write to true */
13772 			if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13773 				verbose(env, "the prog does not allow writes to packet data\n");
13774 				return -EINVAL;
13775 			}
13776 		}
13777 
13778 		if (!meta->initialized_dynptr.id) {
13779 			verifier_bug(env, "no dynptr id");
13780 			return -EFAULT;
13781 		}
13782 		regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13783 
13784 		/* we don't need to set BPF_REG_0's ref obj id
13785 		 * because packet slices are not refcounted (see
13786 		 * dynptr_type_refcounted)
13787 		 */
13788 	} else {
13789 		return 0;
13790 	}
13791 
13792 	return 1;
13793 }
13794 
13795 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13796 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)13797 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13798 			    int *insn_idx_p)
13799 {
13800 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13801 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
13802 	struct bpf_reg_state *regs = cur_regs(env);
13803 	const char *func_name, *ptr_type_name;
13804 	const struct btf_type *t, *ptr_type;
13805 	struct bpf_kfunc_call_arg_meta meta;
13806 	struct bpf_insn_aux_data *insn_aux;
13807 	int err, insn_idx = *insn_idx_p;
13808 	const struct btf_param *args;
13809 	struct btf *desc_btf;
13810 
13811 	/* skip for now, but return error when we find this in fixup_kfunc_call */
13812 	if (!insn->imm)
13813 		return 0;
13814 
13815 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13816 	if (err == -EACCES && func_name)
13817 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
13818 	if (err)
13819 		return err;
13820 	desc_btf = meta.btf;
13821 	insn_aux = &env->insn_aux_data[insn_idx];
13822 
13823 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13824 
13825 	if (!insn->off &&
13826 	    (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13827 	     insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13828 		struct bpf_verifier_state *branch;
13829 		struct bpf_reg_state *regs;
13830 
13831 		branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13832 		if (!branch) {
13833 			verbose(env, "failed to push state for failed lock acquisition\n");
13834 			return -ENOMEM;
13835 		}
13836 
13837 		regs = branch->frame[branch->curframe]->regs;
13838 
13839 		/* Clear r0-r5 registers in forked state */
13840 		for (i = 0; i < CALLER_SAVED_REGS; i++)
13841 			mark_reg_not_init(env, regs, caller_saved[i]);
13842 
13843 		mark_reg_unknown(env, regs, BPF_REG_0);
13844 		err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13845 		if (err) {
13846 			verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13847 			return err;
13848 		}
13849 		__mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13850 	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13851 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13852 		return -EFAULT;
13853 	}
13854 
13855 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13856 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13857 		return -EACCES;
13858 	}
13859 
13860 	sleepable = is_kfunc_sleepable(&meta);
13861 	if (sleepable && !in_sleepable(env)) {
13862 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13863 		return -EACCES;
13864 	}
13865 
13866 	/* Check the arguments */
13867 	err = check_kfunc_args(env, &meta, insn_idx);
13868 	if (err < 0)
13869 		return err;
13870 
13871 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13872 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13873 					 set_rbtree_add_callback_state);
13874 		if (err) {
13875 			verbose(env, "kfunc %s#%d failed callback verification\n",
13876 				func_name, meta.func_id);
13877 			return err;
13878 		}
13879 	}
13880 
13881 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
13882 		meta.r0_size = sizeof(u64);
13883 		meta.r0_rdonly = false;
13884 	}
13885 
13886 	if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
13887 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13888 					 set_timer_callback_state);
13889 		if (err) {
13890 			verbose(env, "kfunc %s#%d failed callback verification\n",
13891 				func_name, meta.func_id);
13892 			return err;
13893 		}
13894 	}
13895 
13896 	if (is_task_work_add_kfunc(meta.func_id)) {
13897 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
13898 					 set_task_work_schedule_callback_state);
13899 		if (err) {
13900 			verbose(env, "kfunc %s#%d failed callback verification\n",
13901 				func_name, meta.func_id);
13902 			return err;
13903 		}
13904 	}
13905 
13906 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
13907 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
13908 
13909 	preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
13910 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
13911 
13912 	if (env->cur_state->active_rcu_lock) {
13913 		struct bpf_func_state *state;
13914 		struct bpf_reg_state *reg;
13915 		u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
13916 
13917 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
13918 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
13919 			return -EACCES;
13920 		}
13921 
13922 		if (rcu_lock) {
13923 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
13924 			return -EINVAL;
13925 		} else if (rcu_unlock) {
13926 			bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
13927 				if (reg->type & MEM_RCU) {
13928 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
13929 					reg->type |= PTR_UNTRUSTED;
13930 				}
13931 			}));
13932 			env->cur_state->active_rcu_lock = false;
13933 		} else if (sleepable) {
13934 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
13935 			return -EACCES;
13936 		}
13937 	} else if (rcu_lock) {
13938 		env->cur_state->active_rcu_lock = true;
13939 	} else if (rcu_unlock) {
13940 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
13941 		return -EINVAL;
13942 	}
13943 
13944 	if (env->cur_state->active_preempt_locks) {
13945 		if (preempt_disable) {
13946 			env->cur_state->active_preempt_locks++;
13947 		} else if (preempt_enable) {
13948 			env->cur_state->active_preempt_locks--;
13949 		} else if (sleepable) {
13950 			verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
13951 			return -EACCES;
13952 		}
13953 	} else if (preempt_disable) {
13954 		env->cur_state->active_preempt_locks++;
13955 	} else if (preempt_enable) {
13956 		verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
13957 		return -EINVAL;
13958 	}
13959 
13960 	if (env->cur_state->active_irq_id && sleepable) {
13961 		verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
13962 		return -EACCES;
13963 	}
13964 
13965 	if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
13966 		verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
13967 		return -EACCES;
13968 	}
13969 
13970 	/* In case of release function, we get register number of refcounted
13971 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
13972 	 */
13973 	if (meta.release_regno) {
13974 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
13975 		if (err) {
13976 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13977 				func_name, meta.func_id);
13978 			return err;
13979 		}
13980 	}
13981 
13982 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
13983 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
13984 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13985 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
13986 		insn_aux->insert_off = regs[BPF_REG_2].off;
13987 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
13988 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
13989 		if (err) {
13990 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
13991 				func_name, meta.func_id);
13992 			return err;
13993 		}
13994 
13995 		err = release_reference(env, release_ref_obj_id);
13996 		if (err) {
13997 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
13998 				func_name, meta.func_id);
13999 			return err;
14000 		}
14001 	}
14002 
14003 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14004 		if (!bpf_jit_supports_exceptions()) {
14005 			verbose(env, "JIT does not support calling kfunc %s#%d\n",
14006 				func_name, meta.func_id);
14007 			return -ENOTSUPP;
14008 		}
14009 		env->seen_exception = true;
14010 
14011 		/* In the case of the default callback, the cookie value passed
14012 		 * to bpf_throw becomes the return value of the program.
14013 		 */
14014 		if (!env->exception_callback_subprog) {
14015 			err = check_return_code(env, BPF_REG_1, "R1");
14016 			if (err < 0)
14017 				return err;
14018 		}
14019 	}
14020 
14021 	for (i = 0; i < CALLER_SAVED_REGS; i++)
14022 		mark_reg_not_init(env, regs, caller_saved[i]);
14023 
14024 	/* Check return type */
14025 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14026 
14027 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14028 		/* Only exception is bpf_obj_new_impl */
14029 		if (meta.btf != btf_vmlinux ||
14030 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14031 		     meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14032 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14033 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14034 			return -EINVAL;
14035 		}
14036 	}
14037 
14038 	if (btf_type_is_scalar(t)) {
14039 		mark_reg_unknown(env, regs, BPF_REG_0);
14040 		if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14041 		    meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14042 			__mark_reg_const_zero(env, &regs[BPF_REG_0]);
14043 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14044 	} else if (btf_type_is_ptr(t)) {
14045 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14046 		err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14047 		if (err) {
14048 			if (err < 0)
14049 				return err;
14050 		} else if (btf_type_is_void(ptr_type)) {
14051 			/* kfunc returning 'void *' is equivalent to returning scalar */
14052 			mark_reg_unknown(env, regs, BPF_REG_0);
14053 		} else if (!__btf_type_is_struct(ptr_type)) {
14054 			if (!meta.r0_size) {
14055 				__u32 sz;
14056 
14057 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14058 					meta.r0_size = sz;
14059 					meta.r0_rdonly = true;
14060 				}
14061 			}
14062 			if (!meta.r0_size) {
14063 				ptr_type_name = btf_name_by_offset(desc_btf,
14064 								   ptr_type->name_off);
14065 				verbose(env,
14066 					"kernel function %s returns pointer type %s %s is not supported\n",
14067 					func_name,
14068 					btf_type_str(ptr_type),
14069 					ptr_type_name);
14070 				return -EINVAL;
14071 			}
14072 
14073 			mark_reg_known_zero(env, regs, BPF_REG_0);
14074 			regs[BPF_REG_0].type = PTR_TO_MEM;
14075 			regs[BPF_REG_0].mem_size = meta.r0_size;
14076 
14077 			if (meta.r0_rdonly)
14078 				regs[BPF_REG_0].type |= MEM_RDONLY;
14079 
14080 			/* Ensures we don't access the memory after a release_reference() */
14081 			if (meta.ref_obj_id)
14082 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14083 
14084 			if (is_kfunc_rcu_protected(&meta))
14085 				regs[BPF_REG_0].type |= MEM_RCU;
14086 		} else {
14087 			mark_reg_known_zero(env, regs, BPF_REG_0);
14088 			regs[BPF_REG_0].btf = desc_btf;
14089 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14090 			regs[BPF_REG_0].btf_id = ptr_type_id;
14091 
14092 			if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14093 				regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14094 			else if (is_kfunc_rcu_protected(&meta))
14095 				regs[BPF_REG_0].type |= MEM_RCU;
14096 
14097 			if (is_iter_next_kfunc(&meta)) {
14098 				struct bpf_reg_state *cur_iter;
14099 
14100 				cur_iter = get_iter_from_state(env->cur_state, &meta);
14101 
14102 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14103 					regs[BPF_REG_0].type |= MEM_RCU;
14104 				else
14105 					regs[BPF_REG_0].type |= PTR_TRUSTED;
14106 			}
14107 		}
14108 
14109 		if (is_kfunc_ret_null(&meta)) {
14110 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14111 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14112 			regs[BPF_REG_0].id = ++env->id_gen;
14113 		}
14114 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14115 		if (is_kfunc_acquire(&meta)) {
14116 			int id = acquire_reference(env, insn_idx);
14117 
14118 			if (id < 0)
14119 				return id;
14120 			if (is_kfunc_ret_null(&meta))
14121 				regs[BPF_REG_0].id = id;
14122 			regs[BPF_REG_0].ref_obj_id = id;
14123 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14124 			ref_set_non_owning(env, &regs[BPF_REG_0]);
14125 		}
14126 
14127 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
14128 			regs[BPF_REG_0].id = ++env->id_gen;
14129 	} else if (btf_type_is_void(t)) {
14130 		if (meta.btf == btf_vmlinux) {
14131 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14132 			    meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14133 				insn_aux->kptr_struct_meta =
14134 					btf_find_struct_meta(meta.arg_btf,
14135 							     meta.arg_btf_id);
14136 			}
14137 		}
14138 	}
14139 
14140 	if (is_kfunc_pkt_changing(&meta))
14141 		clear_all_pkt_pointers(env);
14142 
14143 	nargs = btf_type_vlen(meta.func_proto);
14144 	args = (const struct btf_param *)(meta.func_proto + 1);
14145 	for (i = 0; i < nargs; i++) {
14146 		u32 regno = i + 1;
14147 
14148 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14149 		if (btf_type_is_ptr(t))
14150 			mark_btf_func_reg_size(env, regno, sizeof(void *));
14151 		else
14152 			/* scalar. ensured by btf_check_kfunc_arg_match() */
14153 			mark_btf_func_reg_size(env, regno, t->size);
14154 	}
14155 
14156 	if (is_iter_next_kfunc(&meta)) {
14157 		err = process_iter_next_call(env, insn_idx, &meta);
14158 		if (err)
14159 			return err;
14160 	}
14161 
14162 	return 0;
14163 }
14164 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)14165 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14166 				  const struct bpf_reg_state *reg,
14167 				  enum bpf_reg_type type)
14168 {
14169 	bool known = tnum_is_const(reg->var_off);
14170 	s64 val = reg->var_off.value;
14171 	s64 smin = reg->smin_value;
14172 
14173 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14174 		verbose(env, "math between %s pointer and %lld is not allowed\n",
14175 			reg_type_str(env, type), val);
14176 		return false;
14177 	}
14178 
14179 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14180 		verbose(env, "%s pointer offset %d is not allowed\n",
14181 			reg_type_str(env, type), reg->off);
14182 		return false;
14183 	}
14184 
14185 	if (smin == S64_MIN) {
14186 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14187 			reg_type_str(env, type));
14188 		return false;
14189 	}
14190 
14191 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14192 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
14193 			smin, reg_type_str(env, type));
14194 		return false;
14195 	}
14196 
14197 	return true;
14198 }
14199 
14200 enum {
14201 	REASON_BOUNDS	= -1,
14202 	REASON_TYPE	= -2,
14203 	REASON_PATHS	= -3,
14204 	REASON_LIMIT	= -4,
14205 	REASON_STACK	= -5,
14206 };
14207 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)14208 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14209 			      u32 *alu_limit, bool mask_to_left)
14210 {
14211 	u32 max = 0, ptr_limit = 0;
14212 
14213 	switch (ptr_reg->type) {
14214 	case PTR_TO_STACK:
14215 		/* Offset 0 is out-of-bounds, but acceptable start for the
14216 		 * left direction, see BPF_REG_FP. Also, unknown scalar
14217 		 * offset where we would need to deal with min/max bounds is
14218 		 * currently prohibited for unprivileged.
14219 		 */
14220 		max = MAX_BPF_STACK + mask_to_left;
14221 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14222 		break;
14223 	case PTR_TO_MAP_VALUE:
14224 		max = ptr_reg->map_ptr->value_size;
14225 		ptr_limit = (mask_to_left ?
14226 			     ptr_reg->smin_value :
14227 			     ptr_reg->umax_value) + ptr_reg->off;
14228 		break;
14229 	default:
14230 		return REASON_TYPE;
14231 	}
14232 
14233 	if (ptr_limit >= max)
14234 		return REASON_LIMIT;
14235 	*alu_limit = ptr_limit;
14236 	return 0;
14237 }
14238 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)14239 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14240 				    const struct bpf_insn *insn)
14241 {
14242 	return env->bypass_spec_v1 ||
14243 		BPF_SRC(insn->code) == BPF_K ||
14244 		cur_aux(env)->nospec;
14245 }
14246 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)14247 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14248 				       u32 alu_state, u32 alu_limit)
14249 {
14250 	/* If we arrived here from different branches with different
14251 	 * state or limits to sanitize, then this won't work.
14252 	 */
14253 	if (aux->alu_state &&
14254 	    (aux->alu_state != alu_state ||
14255 	     aux->alu_limit != alu_limit))
14256 		return REASON_PATHS;
14257 
14258 	/* Corresponding fixup done in do_misc_fixups(). */
14259 	aux->alu_state = alu_state;
14260 	aux->alu_limit = alu_limit;
14261 	return 0;
14262 }
14263 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)14264 static int sanitize_val_alu(struct bpf_verifier_env *env,
14265 			    struct bpf_insn *insn)
14266 {
14267 	struct bpf_insn_aux_data *aux = cur_aux(env);
14268 
14269 	if (can_skip_alu_sanitation(env, insn))
14270 		return 0;
14271 
14272 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14273 }
14274 
sanitize_needed(u8 opcode)14275 static bool sanitize_needed(u8 opcode)
14276 {
14277 	return opcode == BPF_ADD || opcode == BPF_SUB;
14278 }
14279 
14280 struct bpf_sanitize_info {
14281 	struct bpf_insn_aux_data aux;
14282 	bool mask_to_left;
14283 };
14284 
14285 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)14286 sanitize_speculative_path(struct bpf_verifier_env *env,
14287 			  const struct bpf_insn *insn,
14288 			  u32 next_idx, u32 curr_idx)
14289 {
14290 	struct bpf_verifier_state *branch;
14291 	struct bpf_reg_state *regs;
14292 
14293 	branch = push_stack(env, next_idx, curr_idx, true);
14294 	if (branch && insn) {
14295 		regs = branch->frame[branch->curframe]->regs;
14296 		if (BPF_SRC(insn->code) == BPF_K) {
14297 			mark_reg_unknown(env, regs, insn->dst_reg);
14298 		} else if (BPF_SRC(insn->code) == BPF_X) {
14299 			mark_reg_unknown(env, regs, insn->dst_reg);
14300 			mark_reg_unknown(env, regs, insn->src_reg);
14301 		}
14302 	}
14303 	return branch;
14304 }
14305 
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)14306 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14307 			    struct bpf_insn *insn,
14308 			    const struct bpf_reg_state *ptr_reg,
14309 			    const struct bpf_reg_state *off_reg,
14310 			    struct bpf_reg_state *dst_reg,
14311 			    struct bpf_sanitize_info *info,
14312 			    const bool commit_window)
14313 {
14314 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14315 	struct bpf_verifier_state *vstate = env->cur_state;
14316 	bool off_is_imm = tnum_is_const(off_reg->var_off);
14317 	bool off_is_neg = off_reg->smin_value < 0;
14318 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
14319 	u8 opcode = BPF_OP(insn->code);
14320 	u32 alu_state, alu_limit;
14321 	struct bpf_reg_state tmp;
14322 	bool ret;
14323 	int err;
14324 
14325 	if (can_skip_alu_sanitation(env, insn))
14326 		return 0;
14327 
14328 	/* We already marked aux for masking from non-speculative
14329 	 * paths, thus we got here in the first place. We only care
14330 	 * to explore bad access from here.
14331 	 */
14332 	if (vstate->speculative)
14333 		goto do_sim;
14334 
14335 	if (!commit_window) {
14336 		if (!tnum_is_const(off_reg->var_off) &&
14337 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14338 			return REASON_BOUNDS;
14339 
14340 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
14341 				     (opcode == BPF_SUB && !off_is_neg);
14342 	}
14343 
14344 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14345 	if (err < 0)
14346 		return err;
14347 
14348 	if (commit_window) {
14349 		/* In commit phase we narrow the masking window based on
14350 		 * the observed pointer move after the simulated operation.
14351 		 */
14352 		alu_state = info->aux.alu_state;
14353 		alu_limit = abs(info->aux.alu_limit - alu_limit);
14354 	} else {
14355 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14356 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14357 		alu_state |= ptr_is_dst_reg ?
14358 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14359 
14360 		/* Limit pruning on unknown scalars to enable deep search for
14361 		 * potential masking differences from other program paths.
14362 		 */
14363 		if (!off_is_imm)
14364 			env->explore_alu_limits = true;
14365 	}
14366 
14367 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14368 	if (err < 0)
14369 		return err;
14370 do_sim:
14371 	/* If we're in commit phase, we're done here given we already
14372 	 * pushed the truncated dst_reg into the speculative verification
14373 	 * stack.
14374 	 *
14375 	 * Also, when register is a known constant, we rewrite register-based
14376 	 * operation to immediate-based, and thus do not need masking (and as
14377 	 * a consequence, do not need to simulate the zero-truncation either).
14378 	 */
14379 	if (commit_window || off_is_imm)
14380 		return 0;
14381 
14382 	/* Simulate and find potential out-of-bounds access under
14383 	 * speculative execution from truncation as a result of
14384 	 * masking when off was not within expected range. If off
14385 	 * sits in dst, then we temporarily need to move ptr there
14386 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14387 	 * for cases where we use K-based arithmetic in one direction
14388 	 * and truncated reg-based in the other in order to explore
14389 	 * bad access.
14390 	 */
14391 	if (!ptr_is_dst_reg) {
14392 		tmp = *dst_reg;
14393 		copy_register_state(dst_reg, ptr_reg);
14394 	}
14395 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
14396 					env->insn_idx);
14397 	if (!ptr_is_dst_reg && ret)
14398 		*dst_reg = tmp;
14399 	return !ret ? REASON_STACK : 0;
14400 }
14401 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)14402 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14403 {
14404 	struct bpf_verifier_state *vstate = env->cur_state;
14405 
14406 	/* If we simulate paths under speculation, we don't update the
14407 	 * insn as 'seen' such that when we verify unreachable paths in
14408 	 * the non-speculative domain, sanitize_dead_code() can still
14409 	 * rewrite/sanitize them.
14410 	 */
14411 	if (!vstate->speculative)
14412 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14413 }
14414 
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)14415 static int sanitize_err(struct bpf_verifier_env *env,
14416 			const struct bpf_insn *insn, int reason,
14417 			const struct bpf_reg_state *off_reg,
14418 			const struct bpf_reg_state *dst_reg)
14419 {
14420 	static const char *err = "pointer arithmetic with it prohibited for !root";
14421 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14422 	u32 dst = insn->dst_reg, src = insn->src_reg;
14423 
14424 	switch (reason) {
14425 	case REASON_BOUNDS:
14426 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14427 			off_reg == dst_reg ? dst : src, err);
14428 		break;
14429 	case REASON_TYPE:
14430 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14431 			off_reg == dst_reg ? src : dst, err);
14432 		break;
14433 	case REASON_PATHS:
14434 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14435 			dst, op, err);
14436 		break;
14437 	case REASON_LIMIT:
14438 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14439 			dst, op, err);
14440 		break;
14441 	case REASON_STACK:
14442 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14443 			dst, err);
14444 		return -ENOMEM;
14445 	default:
14446 		verifier_bug(env, "unknown reason (%d)", reason);
14447 		break;
14448 	}
14449 
14450 	return -EACCES;
14451 }
14452 
14453 /* check that stack access falls within stack limits and that 'reg' doesn't
14454  * have a variable offset.
14455  *
14456  * Variable offset is prohibited for unprivileged mode for simplicity since it
14457  * requires corresponding support in Spectre masking for stack ALU.  See also
14458  * retrieve_ptr_limit().
14459  *
14460  *
14461  * 'off' includes 'reg->off'.
14462  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)14463 static int check_stack_access_for_ptr_arithmetic(
14464 				struct bpf_verifier_env *env,
14465 				int regno,
14466 				const struct bpf_reg_state *reg,
14467 				int off)
14468 {
14469 	if (!tnum_is_const(reg->var_off)) {
14470 		char tn_buf[48];
14471 
14472 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14473 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14474 			regno, tn_buf, off);
14475 		return -EACCES;
14476 	}
14477 
14478 	if (off >= 0 || off < -MAX_BPF_STACK) {
14479 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
14480 			"prohibited for !root; off=%d\n", regno, off);
14481 		return -EACCES;
14482 	}
14483 
14484 	return 0;
14485 }
14486 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)14487 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14488 				 const struct bpf_insn *insn,
14489 				 const struct bpf_reg_state *dst_reg)
14490 {
14491 	u32 dst = insn->dst_reg;
14492 
14493 	/* For unprivileged we require that resulting offset must be in bounds
14494 	 * in order to be able to sanitize access later on.
14495 	 */
14496 	if (env->bypass_spec_v1)
14497 		return 0;
14498 
14499 	switch (dst_reg->type) {
14500 	case PTR_TO_STACK:
14501 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14502 					dst_reg->off + dst_reg->var_off.value))
14503 			return -EACCES;
14504 		break;
14505 	case PTR_TO_MAP_VALUE:
14506 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14507 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14508 				"prohibited for !root\n", dst);
14509 			return -EACCES;
14510 		}
14511 		break;
14512 	default:
14513 		return -EOPNOTSUPP;
14514 	}
14515 
14516 	return 0;
14517 }
14518 
14519 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14520  * Caller should also handle BPF_MOV case separately.
14521  * If we return -EACCES, caller may want to try again treating pointer as a
14522  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
14523  */
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)14524 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14525 				   struct bpf_insn *insn,
14526 				   const struct bpf_reg_state *ptr_reg,
14527 				   const struct bpf_reg_state *off_reg)
14528 {
14529 	struct bpf_verifier_state *vstate = env->cur_state;
14530 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14531 	struct bpf_reg_state *regs = state->regs, *dst_reg;
14532 	bool known = tnum_is_const(off_reg->var_off);
14533 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14534 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14535 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14536 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14537 	struct bpf_sanitize_info info = {};
14538 	u8 opcode = BPF_OP(insn->code);
14539 	u32 dst = insn->dst_reg;
14540 	int ret, bounds_ret;
14541 
14542 	dst_reg = &regs[dst];
14543 
14544 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14545 	    smin_val > smax_val || umin_val > umax_val) {
14546 		/* Taint dst register if offset had invalid bounds derived from
14547 		 * e.g. dead branches.
14548 		 */
14549 		__mark_reg_unknown(env, dst_reg);
14550 		return 0;
14551 	}
14552 
14553 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
14554 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
14555 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14556 			__mark_reg_unknown(env, dst_reg);
14557 			return 0;
14558 		}
14559 
14560 		verbose(env,
14561 			"R%d 32-bit pointer arithmetic prohibited\n",
14562 			dst);
14563 		return -EACCES;
14564 	}
14565 
14566 	if (ptr_reg->type & PTR_MAYBE_NULL) {
14567 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14568 			dst, reg_type_str(env, ptr_reg->type));
14569 		return -EACCES;
14570 	}
14571 
14572 	/*
14573 	 * Accesses to untrusted PTR_TO_MEM are done through probe
14574 	 * instructions, hence no need to track offsets.
14575 	 */
14576 	if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14577 		return 0;
14578 
14579 	switch (base_type(ptr_reg->type)) {
14580 	case PTR_TO_CTX:
14581 	case PTR_TO_MAP_VALUE:
14582 	case PTR_TO_MAP_KEY:
14583 	case PTR_TO_STACK:
14584 	case PTR_TO_PACKET_META:
14585 	case PTR_TO_PACKET:
14586 	case PTR_TO_TP_BUFFER:
14587 	case PTR_TO_BTF_ID:
14588 	case PTR_TO_MEM:
14589 	case PTR_TO_BUF:
14590 	case PTR_TO_FUNC:
14591 	case CONST_PTR_TO_DYNPTR:
14592 		break;
14593 	case PTR_TO_FLOW_KEYS:
14594 		if (known)
14595 			break;
14596 		fallthrough;
14597 	case CONST_PTR_TO_MAP:
14598 		/* smin_val represents the known value */
14599 		if (known && smin_val == 0 && opcode == BPF_ADD)
14600 			break;
14601 		fallthrough;
14602 	default:
14603 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14604 			dst, reg_type_str(env, ptr_reg->type));
14605 		return -EACCES;
14606 	}
14607 
14608 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14609 	 * The id may be overwritten later if we create a new variable offset.
14610 	 */
14611 	dst_reg->type = ptr_reg->type;
14612 	dst_reg->id = ptr_reg->id;
14613 
14614 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14615 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14616 		return -EINVAL;
14617 
14618 	/* pointer types do not carry 32-bit bounds at the moment. */
14619 	__mark_reg32_unbounded(dst_reg);
14620 
14621 	if (sanitize_needed(opcode)) {
14622 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14623 				       &info, false);
14624 		if (ret < 0)
14625 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14626 	}
14627 
14628 	switch (opcode) {
14629 	case BPF_ADD:
14630 		/* We can take a fixed offset as long as it doesn't overflow
14631 		 * the s32 'off' field
14632 		 */
14633 		if (known && (ptr_reg->off + smin_val ==
14634 			      (s64)(s32)(ptr_reg->off + smin_val))) {
14635 			/* pointer += K.  Accumulate it into fixed offset */
14636 			dst_reg->smin_value = smin_ptr;
14637 			dst_reg->smax_value = smax_ptr;
14638 			dst_reg->umin_value = umin_ptr;
14639 			dst_reg->umax_value = umax_ptr;
14640 			dst_reg->var_off = ptr_reg->var_off;
14641 			dst_reg->off = ptr_reg->off + smin_val;
14642 			dst_reg->raw = ptr_reg->raw;
14643 			break;
14644 		}
14645 		/* A new variable offset is created.  Note that off_reg->off
14646 		 * == 0, since it's a scalar.
14647 		 * dst_reg gets the pointer type and since some positive
14648 		 * integer value was added to the pointer, give it a new 'id'
14649 		 * if it's a PTR_TO_PACKET.
14650 		 * this creates a new 'base' pointer, off_reg (variable) gets
14651 		 * added into the variable offset, and we copy the fixed offset
14652 		 * from ptr_reg.
14653 		 */
14654 		if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14655 		    check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14656 			dst_reg->smin_value = S64_MIN;
14657 			dst_reg->smax_value = S64_MAX;
14658 		}
14659 		if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14660 		    check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14661 			dst_reg->umin_value = 0;
14662 			dst_reg->umax_value = U64_MAX;
14663 		}
14664 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14665 		dst_reg->off = ptr_reg->off;
14666 		dst_reg->raw = ptr_reg->raw;
14667 		if (reg_is_pkt_pointer(ptr_reg)) {
14668 			dst_reg->id = ++env->id_gen;
14669 			/* something was added to pkt_ptr, set range to zero */
14670 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14671 		}
14672 		break;
14673 	case BPF_SUB:
14674 		if (dst_reg == off_reg) {
14675 			/* scalar -= pointer.  Creates an unknown scalar */
14676 			verbose(env, "R%d tried to subtract pointer from scalar\n",
14677 				dst);
14678 			return -EACCES;
14679 		}
14680 		/* We don't allow subtraction from FP, because (according to
14681 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
14682 		 * be able to deal with it.
14683 		 */
14684 		if (ptr_reg->type == PTR_TO_STACK) {
14685 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
14686 				dst);
14687 			return -EACCES;
14688 		}
14689 		if (known && (ptr_reg->off - smin_val ==
14690 			      (s64)(s32)(ptr_reg->off - smin_val))) {
14691 			/* pointer -= K.  Subtract it from fixed offset */
14692 			dst_reg->smin_value = smin_ptr;
14693 			dst_reg->smax_value = smax_ptr;
14694 			dst_reg->umin_value = umin_ptr;
14695 			dst_reg->umax_value = umax_ptr;
14696 			dst_reg->var_off = ptr_reg->var_off;
14697 			dst_reg->id = ptr_reg->id;
14698 			dst_reg->off = ptr_reg->off - smin_val;
14699 			dst_reg->raw = ptr_reg->raw;
14700 			break;
14701 		}
14702 		/* A new variable offset is created.  If the subtrahend is known
14703 		 * nonnegative, then any reg->range we had before is still good.
14704 		 */
14705 		if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14706 		    check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14707 			/* Overflow possible, we know nothing */
14708 			dst_reg->smin_value = S64_MIN;
14709 			dst_reg->smax_value = S64_MAX;
14710 		}
14711 		if (umin_ptr < umax_val) {
14712 			/* Overflow possible, we know nothing */
14713 			dst_reg->umin_value = 0;
14714 			dst_reg->umax_value = U64_MAX;
14715 		} else {
14716 			/* Cannot overflow (as long as bounds are consistent) */
14717 			dst_reg->umin_value = umin_ptr - umax_val;
14718 			dst_reg->umax_value = umax_ptr - umin_val;
14719 		}
14720 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14721 		dst_reg->off = ptr_reg->off;
14722 		dst_reg->raw = ptr_reg->raw;
14723 		if (reg_is_pkt_pointer(ptr_reg)) {
14724 			dst_reg->id = ++env->id_gen;
14725 			/* something was added to pkt_ptr, set range to zero */
14726 			if (smin_val < 0)
14727 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14728 		}
14729 		break;
14730 	case BPF_AND:
14731 	case BPF_OR:
14732 	case BPF_XOR:
14733 		/* bitwise ops on pointers are troublesome, prohibit. */
14734 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14735 			dst, bpf_alu_string[opcode >> 4]);
14736 		return -EACCES;
14737 	default:
14738 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
14739 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14740 			dst, bpf_alu_string[opcode >> 4]);
14741 		return -EACCES;
14742 	}
14743 
14744 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14745 		return -EINVAL;
14746 	reg_bounds_sync(dst_reg);
14747 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14748 	if (bounds_ret == -EACCES)
14749 		return bounds_ret;
14750 	if (sanitize_needed(opcode)) {
14751 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14752 				       &info, true);
14753 		if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14754 				    && !env->cur_state->speculative
14755 				    && bounds_ret
14756 				    && !ret,
14757 				    env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14758 			return -EFAULT;
14759 		}
14760 		if (ret < 0)
14761 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
14762 	}
14763 
14764 	return 0;
14765 }
14766 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14767 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14768 				 struct bpf_reg_state *src_reg)
14769 {
14770 	s32 *dst_smin = &dst_reg->s32_min_value;
14771 	s32 *dst_smax = &dst_reg->s32_max_value;
14772 	u32 *dst_umin = &dst_reg->u32_min_value;
14773 	u32 *dst_umax = &dst_reg->u32_max_value;
14774 	u32 umin_val = src_reg->u32_min_value;
14775 	u32 umax_val = src_reg->u32_max_value;
14776 	bool min_overflow, max_overflow;
14777 
14778 	if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14779 	    check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14780 		*dst_smin = S32_MIN;
14781 		*dst_smax = S32_MAX;
14782 	}
14783 
14784 	/* If either all additions overflow or no additions overflow, then
14785 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14786 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14787 	 * the output bounds to unbounded.
14788 	 */
14789 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14790 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14791 
14792 	if (!min_overflow && max_overflow) {
14793 		*dst_umin = 0;
14794 		*dst_umax = U32_MAX;
14795 	}
14796 }
14797 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14798 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14799 			       struct bpf_reg_state *src_reg)
14800 {
14801 	s64 *dst_smin = &dst_reg->smin_value;
14802 	s64 *dst_smax = &dst_reg->smax_value;
14803 	u64 *dst_umin = &dst_reg->umin_value;
14804 	u64 *dst_umax = &dst_reg->umax_value;
14805 	u64 umin_val = src_reg->umin_value;
14806 	u64 umax_val = src_reg->umax_value;
14807 	bool min_overflow, max_overflow;
14808 
14809 	if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14810 	    check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14811 		*dst_smin = S64_MIN;
14812 		*dst_smax = S64_MAX;
14813 	}
14814 
14815 	/* If either all additions overflow or no additions overflow, then
14816 	 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14817 	 * dst_umax + src_umax. Otherwise (some additions overflow), set
14818 	 * the output bounds to unbounded.
14819 	 */
14820 	min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14821 	max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14822 
14823 	if (!min_overflow && max_overflow) {
14824 		*dst_umin = 0;
14825 		*dst_umax = U64_MAX;
14826 	}
14827 }
14828 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14829 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14830 				 struct bpf_reg_state *src_reg)
14831 {
14832 	s32 *dst_smin = &dst_reg->s32_min_value;
14833 	s32 *dst_smax = &dst_reg->s32_max_value;
14834 	u32 *dst_umin = &dst_reg->u32_min_value;
14835 	u32 *dst_umax = &dst_reg->u32_max_value;
14836 	u32 umin_val = src_reg->u32_min_value;
14837 	u32 umax_val = src_reg->u32_max_value;
14838 	bool min_underflow, max_underflow;
14839 
14840 	if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14841 	    check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14842 		/* Overflow possible, we know nothing */
14843 		*dst_smin = S32_MIN;
14844 		*dst_smax = S32_MAX;
14845 	}
14846 
14847 	/* If either all subtractions underflow or no subtractions
14848 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14849 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14850 	 * underflow), set the output bounds to unbounded.
14851 	 */
14852 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14853 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14854 
14855 	if (min_underflow && !max_underflow) {
14856 		*dst_umin = 0;
14857 		*dst_umax = U32_MAX;
14858 	}
14859 }
14860 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14861 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14862 			       struct bpf_reg_state *src_reg)
14863 {
14864 	s64 *dst_smin = &dst_reg->smin_value;
14865 	s64 *dst_smax = &dst_reg->smax_value;
14866 	u64 *dst_umin = &dst_reg->umin_value;
14867 	u64 *dst_umax = &dst_reg->umax_value;
14868 	u64 umin_val = src_reg->umin_value;
14869 	u64 umax_val = src_reg->umax_value;
14870 	bool min_underflow, max_underflow;
14871 
14872 	if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
14873 	    check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
14874 		/* Overflow possible, we know nothing */
14875 		*dst_smin = S64_MIN;
14876 		*dst_smax = S64_MAX;
14877 	}
14878 
14879 	/* If either all subtractions underflow or no subtractions
14880 	 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14881 	 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14882 	 * underflow), set the output bounds to unbounded.
14883 	 */
14884 	min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14885 	max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14886 
14887 	if (min_underflow && !max_underflow) {
14888 		*dst_umin = 0;
14889 		*dst_umax = U64_MAX;
14890 	}
14891 }
14892 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14893 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
14894 				 struct bpf_reg_state *src_reg)
14895 {
14896 	s32 *dst_smin = &dst_reg->s32_min_value;
14897 	s32 *dst_smax = &dst_reg->s32_max_value;
14898 	u32 *dst_umin = &dst_reg->u32_min_value;
14899 	u32 *dst_umax = &dst_reg->u32_max_value;
14900 	s32 tmp_prod[4];
14901 
14902 	if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
14903 	    check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
14904 		/* Overflow possible, we know nothing */
14905 		*dst_umin = 0;
14906 		*dst_umax = U32_MAX;
14907 	}
14908 	if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
14909 	    check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
14910 	    check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
14911 	    check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
14912 		/* Overflow possible, we know nothing */
14913 		*dst_smin = S32_MIN;
14914 		*dst_smax = S32_MAX;
14915 	} else {
14916 		*dst_smin = min_array(tmp_prod, 4);
14917 		*dst_smax = max_array(tmp_prod, 4);
14918 	}
14919 }
14920 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14921 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
14922 			       struct bpf_reg_state *src_reg)
14923 {
14924 	s64 *dst_smin = &dst_reg->smin_value;
14925 	s64 *dst_smax = &dst_reg->smax_value;
14926 	u64 *dst_umin = &dst_reg->umin_value;
14927 	u64 *dst_umax = &dst_reg->umax_value;
14928 	s64 tmp_prod[4];
14929 
14930 	if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
14931 	    check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
14932 		/* Overflow possible, we know nothing */
14933 		*dst_umin = 0;
14934 		*dst_umax = U64_MAX;
14935 	}
14936 	if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
14937 	    check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
14938 	    check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
14939 	    check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
14940 		/* Overflow possible, we know nothing */
14941 		*dst_smin = S64_MIN;
14942 		*dst_smax = S64_MAX;
14943 	} else {
14944 		*dst_smin = min_array(tmp_prod, 4);
14945 		*dst_smax = max_array(tmp_prod, 4);
14946 	}
14947 }
14948 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14949 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
14950 				 struct bpf_reg_state *src_reg)
14951 {
14952 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
14953 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
14954 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
14955 	u32 umax_val = src_reg->u32_max_value;
14956 
14957 	if (src_known && dst_known) {
14958 		__mark_reg32_known(dst_reg, var32_off.value);
14959 		return;
14960 	}
14961 
14962 	/* We get our minimum from the var_off, since that's inherently
14963 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14964 	 */
14965 	dst_reg->u32_min_value = var32_off.value;
14966 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
14967 
14968 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
14969 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
14970 	 */
14971 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
14972 		dst_reg->s32_min_value = dst_reg->u32_min_value;
14973 		dst_reg->s32_max_value = dst_reg->u32_max_value;
14974 	} else {
14975 		dst_reg->s32_min_value = S32_MIN;
14976 		dst_reg->s32_max_value = S32_MAX;
14977 	}
14978 }
14979 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14980 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
14981 			       struct bpf_reg_state *src_reg)
14982 {
14983 	bool src_known = tnum_is_const(src_reg->var_off);
14984 	bool dst_known = tnum_is_const(dst_reg->var_off);
14985 	u64 umax_val = src_reg->umax_value;
14986 
14987 	if (src_known && dst_known) {
14988 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
14989 		return;
14990 	}
14991 
14992 	/* We get our minimum from the var_off, since that's inherently
14993 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
14994 	 */
14995 	dst_reg->umin_value = dst_reg->var_off.value;
14996 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
14997 
14998 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
14999 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15000 	 */
15001 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15002 		dst_reg->smin_value = dst_reg->umin_value;
15003 		dst_reg->smax_value = dst_reg->umax_value;
15004 	} else {
15005 		dst_reg->smin_value = S64_MIN;
15006 		dst_reg->smax_value = S64_MAX;
15007 	}
15008 	/* We may learn something more from the var_off */
15009 	__update_reg_bounds(dst_reg);
15010 }
15011 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15012 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15013 				struct bpf_reg_state *src_reg)
15014 {
15015 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15016 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15017 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15018 	u32 umin_val = src_reg->u32_min_value;
15019 
15020 	if (src_known && dst_known) {
15021 		__mark_reg32_known(dst_reg, var32_off.value);
15022 		return;
15023 	}
15024 
15025 	/* We get our maximum from the var_off, and our minimum is the
15026 	 * maximum of the operands' minima
15027 	 */
15028 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15029 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15030 
15031 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15032 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15033 	 */
15034 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15035 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15036 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15037 	} else {
15038 		dst_reg->s32_min_value = S32_MIN;
15039 		dst_reg->s32_max_value = S32_MAX;
15040 	}
15041 }
15042 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15043 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15044 			      struct bpf_reg_state *src_reg)
15045 {
15046 	bool src_known = tnum_is_const(src_reg->var_off);
15047 	bool dst_known = tnum_is_const(dst_reg->var_off);
15048 	u64 umin_val = src_reg->umin_value;
15049 
15050 	if (src_known && dst_known) {
15051 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15052 		return;
15053 	}
15054 
15055 	/* We get our maximum from the var_off, and our minimum is the
15056 	 * maximum of the operands' minima
15057 	 */
15058 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15059 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15060 
15061 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15062 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15063 	 */
15064 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15065 		dst_reg->smin_value = dst_reg->umin_value;
15066 		dst_reg->smax_value = dst_reg->umax_value;
15067 	} else {
15068 		dst_reg->smin_value = S64_MIN;
15069 		dst_reg->smax_value = S64_MAX;
15070 	}
15071 	/* We may learn something more from the var_off */
15072 	__update_reg_bounds(dst_reg);
15073 }
15074 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15075 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15076 				 struct bpf_reg_state *src_reg)
15077 {
15078 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
15079 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15080 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15081 
15082 	if (src_known && dst_known) {
15083 		__mark_reg32_known(dst_reg, var32_off.value);
15084 		return;
15085 	}
15086 
15087 	/* We get both minimum and maximum from the var32_off. */
15088 	dst_reg->u32_min_value = var32_off.value;
15089 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15090 
15091 	/* Safe to set s32 bounds by casting u32 result into s32 when u32
15092 	 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15093 	 */
15094 	if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15095 		dst_reg->s32_min_value = dst_reg->u32_min_value;
15096 		dst_reg->s32_max_value = dst_reg->u32_max_value;
15097 	} else {
15098 		dst_reg->s32_min_value = S32_MIN;
15099 		dst_reg->s32_max_value = S32_MAX;
15100 	}
15101 }
15102 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15103 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15104 			       struct bpf_reg_state *src_reg)
15105 {
15106 	bool src_known = tnum_is_const(src_reg->var_off);
15107 	bool dst_known = tnum_is_const(dst_reg->var_off);
15108 
15109 	if (src_known && dst_known) {
15110 		/* dst_reg->var_off.value has been updated earlier */
15111 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
15112 		return;
15113 	}
15114 
15115 	/* We get both minimum and maximum from the var_off. */
15116 	dst_reg->umin_value = dst_reg->var_off.value;
15117 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15118 
15119 	/* Safe to set s64 bounds by casting u64 result into s64 when u64
15120 	 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15121 	 */
15122 	if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15123 		dst_reg->smin_value = dst_reg->umin_value;
15124 		dst_reg->smax_value = dst_reg->umax_value;
15125 	} else {
15126 		dst_reg->smin_value = S64_MIN;
15127 		dst_reg->smax_value = S64_MAX;
15128 	}
15129 
15130 	__update_reg_bounds(dst_reg);
15131 }
15132 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15133 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15134 				   u64 umin_val, u64 umax_val)
15135 {
15136 	/* We lose all sign bit information (except what we can pick
15137 	 * up from var_off)
15138 	 */
15139 	dst_reg->s32_min_value = S32_MIN;
15140 	dst_reg->s32_max_value = S32_MAX;
15141 	/* If we might shift our top bit out, then we know nothing */
15142 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15143 		dst_reg->u32_min_value = 0;
15144 		dst_reg->u32_max_value = U32_MAX;
15145 	} else {
15146 		dst_reg->u32_min_value <<= umin_val;
15147 		dst_reg->u32_max_value <<= umax_val;
15148 	}
15149 }
15150 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15151 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15152 				 struct bpf_reg_state *src_reg)
15153 {
15154 	u32 umax_val = src_reg->u32_max_value;
15155 	u32 umin_val = src_reg->u32_min_value;
15156 	/* u32 alu operation will zext upper bits */
15157 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15158 
15159 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15160 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15161 	/* Not required but being careful mark reg64 bounds as unknown so
15162 	 * that we are forced to pick them up from tnum and zext later and
15163 	 * if some path skips this step we are still safe.
15164 	 */
15165 	__mark_reg64_unbounded(dst_reg);
15166 	__update_reg32_bounds(dst_reg);
15167 }
15168 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15169 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15170 				   u64 umin_val, u64 umax_val)
15171 {
15172 	/* Special case <<32 because it is a common compiler pattern to sign
15173 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15174 	 * positive we know this shift will also be positive so we can track
15175 	 * bounds correctly. Otherwise we lose all sign bit information except
15176 	 * what we can pick up from var_off. Perhaps we can generalize this
15177 	 * later to shifts of any length.
15178 	 */
15179 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15180 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15181 	else
15182 		dst_reg->smax_value = S64_MAX;
15183 
15184 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15185 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15186 	else
15187 		dst_reg->smin_value = S64_MIN;
15188 
15189 	/* If we might shift our top bit out, then we know nothing */
15190 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15191 		dst_reg->umin_value = 0;
15192 		dst_reg->umax_value = U64_MAX;
15193 	} else {
15194 		dst_reg->umin_value <<= umin_val;
15195 		dst_reg->umax_value <<= umax_val;
15196 	}
15197 }
15198 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15199 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15200 			       struct bpf_reg_state *src_reg)
15201 {
15202 	u64 umax_val = src_reg->umax_value;
15203 	u64 umin_val = src_reg->umin_value;
15204 
15205 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
15206 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15207 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15208 
15209 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15210 	/* We may learn something more from the var_off */
15211 	__update_reg_bounds(dst_reg);
15212 }
15213 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15214 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15215 				 struct bpf_reg_state *src_reg)
15216 {
15217 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
15218 	u32 umax_val = src_reg->u32_max_value;
15219 	u32 umin_val = src_reg->u32_min_value;
15220 
15221 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15222 	 * be negative, then either:
15223 	 * 1) src_reg might be zero, so the sign bit of the result is
15224 	 *    unknown, so we lose our signed bounds
15225 	 * 2) it's known negative, thus the unsigned bounds capture the
15226 	 *    signed bounds
15227 	 * 3) the signed bounds cross zero, so they tell us nothing
15228 	 *    about the result
15229 	 * If the value in dst_reg is known nonnegative, then again the
15230 	 * unsigned bounds capture the signed bounds.
15231 	 * Thus, in all cases it suffices to blow away our signed bounds
15232 	 * and rely on inferring new ones from the unsigned bounds and
15233 	 * var_off of the result.
15234 	 */
15235 	dst_reg->s32_min_value = S32_MIN;
15236 	dst_reg->s32_max_value = S32_MAX;
15237 
15238 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
15239 	dst_reg->u32_min_value >>= umax_val;
15240 	dst_reg->u32_max_value >>= umin_val;
15241 
15242 	__mark_reg64_unbounded(dst_reg);
15243 	__update_reg32_bounds(dst_reg);
15244 }
15245 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15246 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15247 			       struct bpf_reg_state *src_reg)
15248 {
15249 	u64 umax_val = src_reg->umax_value;
15250 	u64 umin_val = src_reg->umin_value;
15251 
15252 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
15253 	 * be negative, then either:
15254 	 * 1) src_reg might be zero, so the sign bit of the result is
15255 	 *    unknown, so we lose our signed bounds
15256 	 * 2) it's known negative, thus the unsigned bounds capture the
15257 	 *    signed bounds
15258 	 * 3) the signed bounds cross zero, so they tell us nothing
15259 	 *    about the result
15260 	 * If the value in dst_reg is known nonnegative, then again the
15261 	 * unsigned bounds capture the signed bounds.
15262 	 * Thus, in all cases it suffices to blow away our signed bounds
15263 	 * and rely on inferring new ones from the unsigned bounds and
15264 	 * var_off of the result.
15265 	 */
15266 	dst_reg->smin_value = S64_MIN;
15267 	dst_reg->smax_value = S64_MAX;
15268 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15269 	dst_reg->umin_value >>= umax_val;
15270 	dst_reg->umax_value >>= umin_val;
15271 
15272 	/* Its not easy to operate on alu32 bounds here because it depends
15273 	 * on bits being shifted in. Take easy way out and mark unbounded
15274 	 * so we can recalculate later from tnum.
15275 	 */
15276 	__mark_reg32_unbounded(dst_reg);
15277 	__update_reg_bounds(dst_reg);
15278 }
15279 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15280 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15281 				  struct bpf_reg_state *src_reg)
15282 {
15283 	u64 umin_val = src_reg->u32_min_value;
15284 
15285 	/* Upon reaching here, src_known is true and
15286 	 * umax_val is equal to umin_val.
15287 	 */
15288 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15289 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15290 
15291 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15292 
15293 	/* blow away the dst_reg umin_value/umax_value and rely on
15294 	 * dst_reg var_off to refine the result.
15295 	 */
15296 	dst_reg->u32_min_value = 0;
15297 	dst_reg->u32_max_value = U32_MAX;
15298 
15299 	__mark_reg64_unbounded(dst_reg);
15300 	__update_reg32_bounds(dst_reg);
15301 }
15302 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15303 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15304 				struct bpf_reg_state *src_reg)
15305 {
15306 	u64 umin_val = src_reg->umin_value;
15307 
15308 	/* Upon reaching here, src_known is true and umax_val is equal
15309 	 * to umin_val.
15310 	 */
15311 	dst_reg->smin_value >>= umin_val;
15312 	dst_reg->smax_value >>= umin_val;
15313 
15314 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15315 
15316 	/* blow away the dst_reg umin_value/umax_value and rely on
15317 	 * dst_reg var_off to refine the result.
15318 	 */
15319 	dst_reg->umin_value = 0;
15320 	dst_reg->umax_value = U64_MAX;
15321 
15322 	/* Its not easy to operate on alu32 bounds here because it depends
15323 	 * on bits being shifted in from upper 32-bits. Take easy way out
15324 	 * and mark unbounded so we can recalculate later from tnum.
15325 	 */
15326 	__mark_reg32_unbounded(dst_reg);
15327 	__update_reg_bounds(dst_reg);
15328 }
15329 
is_safe_to_compute_dst_reg_range(struct bpf_insn * insn,const struct bpf_reg_state * src_reg)15330 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15331 					     const struct bpf_reg_state *src_reg)
15332 {
15333 	bool src_is_const = false;
15334 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15335 
15336 	if (insn_bitness == 32) {
15337 		if (tnum_subreg_is_const(src_reg->var_off)
15338 		    && src_reg->s32_min_value == src_reg->s32_max_value
15339 		    && src_reg->u32_min_value == src_reg->u32_max_value)
15340 			src_is_const = true;
15341 	} else {
15342 		if (tnum_is_const(src_reg->var_off)
15343 		    && src_reg->smin_value == src_reg->smax_value
15344 		    && src_reg->umin_value == src_reg->umax_value)
15345 			src_is_const = true;
15346 	}
15347 
15348 	switch (BPF_OP(insn->code)) {
15349 	case BPF_ADD:
15350 	case BPF_SUB:
15351 	case BPF_NEG:
15352 	case BPF_AND:
15353 	case BPF_XOR:
15354 	case BPF_OR:
15355 	case BPF_MUL:
15356 		return true;
15357 
15358 	/* Shift operators range is only computable if shift dimension operand
15359 	 * is a constant. Shifts greater than 31 or 63 are undefined. This
15360 	 * includes shifts by a negative number.
15361 	 */
15362 	case BPF_LSH:
15363 	case BPF_RSH:
15364 	case BPF_ARSH:
15365 		return (src_is_const && src_reg->umax_value < insn_bitness);
15366 	default:
15367 		return false;
15368 	}
15369 }
15370 
15371 /* WARNING: This function does calculations on 64-bit values, but the actual
15372  * execution may occur on 32-bit values. Therefore, things like bitshifts
15373  * need extra checks in the 32-bit case.
15374  */
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)15375 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15376 				      struct bpf_insn *insn,
15377 				      struct bpf_reg_state *dst_reg,
15378 				      struct bpf_reg_state src_reg)
15379 {
15380 	u8 opcode = BPF_OP(insn->code);
15381 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15382 	int ret;
15383 
15384 	if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15385 		__mark_reg_unknown(env, dst_reg);
15386 		return 0;
15387 	}
15388 
15389 	if (sanitize_needed(opcode)) {
15390 		ret = sanitize_val_alu(env, insn);
15391 		if (ret < 0)
15392 			return sanitize_err(env, insn, ret, NULL, NULL);
15393 	}
15394 
15395 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15396 	 * There are two classes of instructions: The first class we track both
15397 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
15398 	 * greatest amount of precision when alu operations are mixed with jmp32
15399 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15400 	 * and BPF_OR. This is possible because these ops have fairly easy to
15401 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15402 	 * See alu32 verifier tests for examples. The second class of
15403 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15404 	 * with regards to tracking sign/unsigned bounds because the bits may
15405 	 * cross subreg boundaries in the alu64 case. When this happens we mark
15406 	 * the reg unbounded in the subreg bound space and use the resulting
15407 	 * tnum to calculate an approximation of the sign/unsigned bounds.
15408 	 */
15409 	switch (opcode) {
15410 	case BPF_ADD:
15411 		scalar32_min_max_add(dst_reg, &src_reg);
15412 		scalar_min_max_add(dst_reg, &src_reg);
15413 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15414 		break;
15415 	case BPF_SUB:
15416 		scalar32_min_max_sub(dst_reg, &src_reg);
15417 		scalar_min_max_sub(dst_reg, &src_reg);
15418 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15419 		break;
15420 	case BPF_NEG:
15421 		env->fake_reg[0] = *dst_reg;
15422 		__mark_reg_known(dst_reg, 0);
15423 		scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15424 		scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15425 		dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15426 		break;
15427 	case BPF_MUL:
15428 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15429 		scalar32_min_max_mul(dst_reg, &src_reg);
15430 		scalar_min_max_mul(dst_reg, &src_reg);
15431 		break;
15432 	case BPF_AND:
15433 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15434 		scalar32_min_max_and(dst_reg, &src_reg);
15435 		scalar_min_max_and(dst_reg, &src_reg);
15436 		break;
15437 	case BPF_OR:
15438 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15439 		scalar32_min_max_or(dst_reg, &src_reg);
15440 		scalar_min_max_or(dst_reg, &src_reg);
15441 		break;
15442 	case BPF_XOR:
15443 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15444 		scalar32_min_max_xor(dst_reg, &src_reg);
15445 		scalar_min_max_xor(dst_reg, &src_reg);
15446 		break;
15447 	case BPF_LSH:
15448 		if (alu32)
15449 			scalar32_min_max_lsh(dst_reg, &src_reg);
15450 		else
15451 			scalar_min_max_lsh(dst_reg, &src_reg);
15452 		break;
15453 	case BPF_RSH:
15454 		if (alu32)
15455 			scalar32_min_max_rsh(dst_reg, &src_reg);
15456 		else
15457 			scalar_min_max_rsh(dst_reg, &src_reg);
15458 		break;
15459 	case BPF_ARSH:
15460 		if (alu32)
15461 			scalar32_min_max_arsh(dst_reg, &src_reg);
15462 		else
15463 			scalar_min_max_arsh(dst_reg, &src_reg);
15464 		break;
15465 	default:
15466 		break;
15467 	}
15468 
15469 	/* ALU32 ops are zero extended into 64bit register */
15470 	if (alu32)
15471 		zext_32_to_64(dst_reg);
15472 	reg_bounds_sync(dst_reg);
15473 	return 0;
15474 }
15475 
15476 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15477  * and var_off.
15478  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)15479 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15480 				   struct bpf_insn *insn)
15481 {
15482 	struct bpf_verifier_state *vstate = env->cur_state;
15483 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
15484 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15485 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15486 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15487 	u8 opcode = BPF_OP(insn->code);
15488 	int err;
15489 
15490 	dst_reg = &regs[insn->dst_reg];
15491 	src_reg = NULL;
15492 
15493 	if (dst_reg->type == PTR_TO_ARENA) {
15494 		struct bpf_insn_aux_data *aux = cur_aux(env);
15495 
15496 		if (BPF_CLASS(insn->code) == BPF_ALU64)
15497 			/*
15498 			 * 32-bit operations zero upper bits automatically.
15499 			 * 64-bit operations need to be converted to 32.
15500 			 */
15501 			aux->needs_zext = true;
15502 
15503 		/* Any arithmetic operations are allowed on arena pointers */
15504 		return 0;
15505 	}
15506 
15507 	if (dst_reg->type != SCALAR_VALUE)
15508 		ptr_reg = dst_reg;
15509 
15510 	if (BPF_SRC(insn->code) == BPF_X) {
15511 		src_reg = &regs[insn->src_reg];
15512 		if (src_reg->type != SCALAR_VALUE) {
15513 			if (dst_reg->type != SCALAR_VALUE) {
15514 				/* Combining two pointers by any ALU op yields
15515 				 * an arbitrary scalar. Disallow all math except
15516 				 * pointer subtraction
15517 				 */
15518 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15519 					mark_reg_unknown(env, regs, insn->dst_reg);
15520 					return 0;
15521 				}
15522 				verbose(env, "R%d pointer %s pointer prohibited\n",
15523 					insn->dst_reg,
15524 					bpf_alu_string[opcode >> 4]);
15525 				return -EACCES;
15526 			} else {
15527 				/* scalar += pointer
15528 				 * This is legal, but we have to reverse our
15529 				 * src/dest handling in computing the range
15530 				 */
15531 				err = mark_chain_precision(env, insn->dst_reg);
15532 				if (err)
15533 					return err;
15534 				return adjust_ptr_min_max_vals(env, insn,
15535 							       src_reg, dst_reg);
15536 			}
15537 		} else if (ptr_reg) {
15538 			/* pointer += scalar */
15539 			err = mark_chain_precision(env, insn->src_reg);
15540 			if (err)
15541 				return err;
15542 			return adjust_ptr_min_max_vals(env, insn,
15543 						       dst_reg, src_reg);
15544 		} else if (dst_reg->precise) {
15545 			/* if dst_reg is precise, src_reg should be precise as well */
15546 			err = mark_chain_precision(env, insn->src_reg);
15547 			if (err)
15548 				return err;
15549 		}
15550 	} else {
15551 		/* Pretend the src is a reg with a known value, since we only
15552 		 * need to be able to read from this state.
15553 		 */
15554 		off_reg.type = SCALAR_VALUE;
15555 		__mark_reg_known(&off_reg, insn->imm);
15556 		src_reg = &off_reg;
15557 		if (ptr_reg) /* pointer += K */
15558 			return adjust_ptr_min_max_vals(env, insn,
15559 						       ptr_reg, src_reg);
15560 	}
15561 
15562 	/* Got here implies adding two SCALAR_VALUEs */
15563 	if (WARN_ON_ONCE(ptr_reg)) {
15564 		print_verifier_state(env, vstate, vstate->curframe, true);
15565 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
15566 		return -EFAULT;
15567 	}
15568 	if (WARN_ON(!src_reg)) {
15569 		print_verifier_state(env, vstate, vstate->curframe, true);
15570 		verbose(env, "verifier internal error: no src_reg\n");
15571 		return -EFAULT;
15572 	}
15573 	err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15574 	if (err)
15575 		return err;
15576 	/*
15577 	 * Compilers can generate the code
15578 	 * r1 = r2
15579 	 * r1 += 0x1
15580 	 * if r2 < 1000 goto ...
15581 	 * use r1 in memory access
15582 	 * So for 64-bit alu remember constant delta between r2 and r1 and
15583 	 * update r1 after 'if' condition.
15584 	 */
15585 	if (env->bpf_capable &&
15586 	    BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15587 	    dst_reg->id && is_reg_const(src_reg, false)) {
15588 		u64 val = reg_const_value(src_reg, false);
15589 
15590 		if ((dst_reg->id & BPF_ADD_CONST) ||
15591 		    /* prevent overflow in sync_linked_regs() later */
15592 		    val > (u32)S32_MAX) {
15593 			/*
15594 			 * If the register already went through rX += val
15595 			 * we cannot accumulate another val into rx->off.
15596 			 */
15597 			dst_reg->off = 0;
15598 			dst_reg->id = 0;
15599 		} else {
15600 			dst_reg->id |= BPF_ADD_CONST;
15601 			dst_reg->off = val;
15602 		}
15603 	} else {
15604 		/*
15605 		 * Make sure ID is cleared otherwise dst_reg min/max could be
15606 		 * incorrectly propagated into other registers by sync_linked_regs()
15607 		 */
15608 		dst_reg->id = 0;
15609 	}
15610 	return 0;
15611 }
15612 
15613 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)15614 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15615 {
15616 	struct bpf_reg_state *regs = cur_regs(env);
15617 	u8 opcode = BPF_OP(insn->code);
15618 	int err;
15619 
15620 	if (opcode == BPF_END || opcode == BPF_NEG) {
15621 		if (opcode == BPF_NEG) {
15622 			if (BPF_SRC(insn->code) != BPF_K ||
15623 			    insn->src_reg != BPF_REG_0 ||
15624 			    insn->off != 0 || insn->imm != 0) {
15625 				verbose(env, "BPF_NEG uses reserved fields\n");
15626 				return -EINVAL;
15627 			}
15628 		} else {
15629 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15630 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15631 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
15632 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
15633 				verbose(env, "BPF_END uses reserved fields\n");
15634 				return -EINVAL;
15635 			}
15636 		}
15637 
15638 		/* check src operand */
15639 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15640 		if (err)
15641 			return err;
15642 
15643 		if (is_pointer_value(env, insn->dst_reg)) {
15644 			verbose(env, "R%d pointer arithmetic prohibited\n",
15645 				insn->dst_reg);
15646 			return -EACCES;
15647 		}
15648 
15649 		/* check dest operand */
15650 		if (opcode == BPF_NEG &&
15651 		    regs[insn->dst_reg].type == SCALAR_VALUE) {
15652 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15653 			err = err ?: adjust_scalar_min_max_vals(env, insn,
15654 							 &regs[insn->dst_reg],
15655 							 regs[insn->dst_reg]);
15656 		} else {
15657 			err = check_reg_arg(env, insn->dst_reg, DST_OP);
15658 		}
15659 		if (err)
15660 			return err;
15661 
15662 	} else if (opcode == BPF_MOV) {
15663 
15664 		if (BPF_SRC(insn->code) == BPF_X) {
15665 			if (BPF_CLASS(insn->code) == BPF_ALU) {
15666 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15667 				    insn->imm) {
15668 					verbose(env, "BPF_MOV uses reserved fields\n");
15669 					return -EINVAL;
15670 				}
15671 			} else if (insn->off == BPF_ADDR_SPACE_CAST) {
15672 				if (insn->imm != 1 && insn->imm != 1u << 16) {
15673 					verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15674 					return -EINVAL;
15675 				}
15676 				if (!env->prog->aux->arena) {
15677 					verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15678 					return -EINVAL;
15679 				}
15680 			} else {
15681 				if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15682 				     insn->off != 32) || insn->imm) {
15683 					verbose(env, "BPF_MOV uses reserved fields\n");
15684 					return -EINVAL;
15685 				}
15686 			}
15687 
15688 			/* check src operand */
15689 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15690 			if (err)
15691 				return err;
15692 		} else {
15693 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15694 				verbose(env, "BPF_MOV uses reserved fields\n");
15695 				return -EINVAL;
15696 			}
15697 		}
15698 
15699 		/* check dest operand, mark as required later */
15700 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15701 		if (err)
15702 			return err;
15703 
15704 		if (BPF_SRC(insn->code) == BPF_X) {
15705 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
15706 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15707 
15708 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15709 				if (insn->imm) {
15710 					/* off == BPF_ADDR_SPACE_CAST */
15711 					mark_reg_unknown(env, regs, insn->dst_reg);
15712 					if (insn->imm == 1) { /* cast from as(1) to as(0) */
15713 						dst_reg->type = PTR_TO_ARENA;
15714 						/* PTR_TO_ARENA is 32-bit */
15715 						dst_reg->subreg_def = env->insn_idx + 1;
15716 					}
15717 				} else if (insn->off == 0) {
15718 					/* case: R1 = R2
15719 					 * copy register state to dest reg
15720 					 */
15721 					assign_scalar_id_before_mov(env, src_reg);
15722 					copy_register_state(dst_reg, src_reg);
15723 					dst_reg->subreg_def = DEF_NOT_SUBREG;
15724 				} else {
15725 					/* case: R1 = (s8, s16 s32)R2 */
15726 					if (is_pointer_value(env, insn->src_reg)) {
15727 						verbose(env,
15728 							"R%d sign-extension part of pointer\n",
15729 							insn->src_reg);
15730 						return -EACCES;
15731 					} else if (src_reg->type == SCALAR_VALUE) {
15732 						bool no_sext;
15733 
15734 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15735 						if (no_sext)
15736 							assign_scalar_id_before_mov(env, src_reg);
15737 						copy_register_state(dst_reg, src_reg);
15738 						if (!no_sext)
15739 							dst_reg->id = 0;
15740 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15741 						dst_reg->subreg_def = DEF_NOT_SUBREG;
15742 					} else {
15743 						mark_reg_unknown(env, regs, insn->dst_reg);
15744 					}
15745 				}
15746 			} else {
15747 				/* R1 = (u32) R2 */
15748 				if (is_pointer_value(env, insn->src_reg)) {
15749 					verbose(env,
15750 						"R%d partial copy of pointer\n",
15751 						insn->src_reg);
15752 					return -EACCES;
15753 				} else if (src_reg->type == SCALAR_VALUE) {
15754 					if (insn->off == 0) {
15755 						bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15756 
15757 						if (is_src_reg_u32)
15758 							assign_scalar_id_before_mov(env, src_reg);
15759 						copy_register_state(dst_reg, src_reg);
15760 						/* Make sure ID is cleared if src_reg is not in u32
15761 						 * range otherwise dst_reg min/max could be incorrectly
15762 						 * propagated into src_reg by sync_linked_regs()
15763 						 */
15764 						if (!is_src_reg_u32)
15765 							dst_reg->id = 0;
15766 						dst_reg->subreg_def = env->insn_idx + 1;
15767 					} else {
15768 						/* case: W1 = (s8, s16)W2 */
15769 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15770 
15771 						if (no_sext)
15772 							assign_scalar_id_before_mov(env, src_reg);
15773 						copy_register_state(dst_reg, src_reg);
15774 						if (!no_sext)
15775 							dst_reg->id = 0;
15776 						dst_reg->subreg_def = env->insn_idx + 1;
15777 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15778 					}
15779 				} else {
15780 					mark_reg_unknown(env, regs,
15781 							 insn->dst_reg);
15782 				}
15783 				zext_32_to_64(dst_reg);
15784 				reg_bounds_sync(dst_reg);
15785 			}
15786 		} else {
15787 			/* case: R = imm
15788 			 * remember the value we stored into this reg
15789 			 */
15790 			/* clear any state __mark_reg_known doesn't set */
15791 			mark_reg_unknown(env, regs, insn->dst_reg);
15792 			regs[insn->dst_reg].type = SCALAR_VALUE;
15793 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
15794 				__mark_reg_known(regs + insn->dst_reg,
15795 						 insn->imm);
15796 			} else {
15797 				__mark_reg_known(regs + insn->dst_reg,
15798 						 (u32)insn->imm);
15799 			}
15800 		}
15801 
15802 	} else if (opcode > BPF_END) {
15803 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15804 		return -EINVAL;
15805 
15806 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
15807 
15808 		if (BPF_SRC(insn->code) == BPF_X) {
15809 			if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
15810 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15811 				verbose(env, "BPF_ALU uses reserved fields\n");
15812 				return -EINVAL;
15813 			}
15814 			/* check src1 operand */
15815 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
15816 			if (err)
15817 				return err;
15818 		} else {
15819 			if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
15820 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15821 				verbose(env, "BPF_ALU uses reserved fields\n");
15822 				return -EINVAL;
15823 			}
15824 		}
15825 
15826 		/* check src2 operand */
15827 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15828 		if (err)
15829 			return err;
15830 
15831 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15832 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15833 			verbose(env, "div by zero\n");
15834 			return -EINVAL;
15835 		}
15836 
15837 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15838 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15839 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15840 
15841 			if (insn->imm < 0 || insn->imm >= size) {
15842 				verbose(env, "invalid shift %d\n", insn->imm);
15843 				return -EINVAL;
15844 			}
15845 		}
15846 
15847 		/* check dest operand */
15848 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15849 		err = err ?: adjust_reg_min_max_vals(env, insn);
15850 		if (err)
15851 			return err;
15852 	}
15853 
15854 	return reg_bounds_sanity_check(env, &regs[insn->dst_reg], "alu");
15855 }
15856 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)15857 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15858 				   struct bpf_reg_state *dst_reg,
15859 				   enum bpf_reg_type type,
15860 				   bool range_right_open)
15861 {
15862 	struct bpf_func_state *state;
15863 	struct bpf_reg_state *reg;
15864 	int new_range;
15865 
15866 	if (dst_reg->off < 0 ||
15867 	    (dst_reg->off == 0 && range_right_open))
15868 		/* This doesn't give us any range */
15869 		return;
15870 
15871 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
15872 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
15873 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
15874 		 * than pkt_end, but that's because it's also less than pkt.
15875 		 */
15876 		return;
15877 
15878 	new_range = dst_reg->off;
15879 	if (range_right_open)
15880 		new_range++;
15881 
15882 	/* Examples for register markings:
15883 	 *
15884 	 * pkt_data in dst register:
15885 	 *
15886 	 *   r2 = r3;
15887 	 *   r2 += 8;
15888 	 *   if (r2 > pkt_end) goto <handle exception>
15889 	 *   <access okay>
15890 	 *
15891 	 *   r2 = r3;
15892 	 *   r2 += 8;
15893 	 *   if (r2 < pkt_end) goto <access okay>
15894 	 *   <handle exception>
15895 	 *
15896 	 *   Where:
15897 	 *     r2 == dst_reg, pkt_end == src_reg
15898 	 *     r2=pkt(id=n,off=8,r=0)
15899 	 *     r3=pkt(id=n,off=0,r=0)
15900 	 *
15901 	 * pkt_data in src register:
15902 	 *
15903 	 *   r2 = r3;
15904 	 *   r2 += 8;
15905 	 *   if (pkt_end >= r2) goto <access okay>
15906 	 *   <handle exception>
15907 	 *
15908 	 *   r2 = r3;
15909 	 *   r2 += 8;
15910 	 *   if (pkt_end <= r2) goto <handle exception>
15911 	 *   <access okay>
15912 	 *
15913 	 *   Where:
15914 	 *     pkt_end == dst_reg, r2 == src_reg
15915 	 *     r2=pkt(id=n,off=8,r=0)
15916 	 *     r3=pkt(id=n,off=0,r=0)
15917 	 *
15918 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
15919 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
15920 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
15921 	 * the check.
15922 	 */
15923 
15924 	/* If our ids match, then we must have the same max_value.  And we
15925 	 * don't care about the other reg's fixed offset, since if it's too big
15926 	 * the range won't allow anything.
15927 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
15928 	 */
15929 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
15930 		if (reg->type == type && reg->id == dst_reg->id)
15931 			/* keep the maximum range already checked */
15932 			reg->range = max(reg->range, new_range);
15933 	}));
15934 }
15935 
15936 /*
15937  * <reg1> <op> <reg2>, currently assuming reg2 is a constant
15938  */
is_scalar_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)15939 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
15940 				  u8 opcode, bool is_jmp32)
15941 {
15942 	struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
15943 	struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
15944 	u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
15945 	u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
15946 	s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
15947 	s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
15948 	u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
15949 	u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
15950 	s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
15951 	s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
15952 
15953 	switch (opcode) {
15954 	case BPF_JEQ:
15955 		/* constants, umin/umax and smin/smax checks would be
15956 		 * redundant in this case because they all should match
15957 		 */
15958 		if (tnum_is_const(t1) && tnum_is_const(t2))
15959 			return t1.value == t2.value;
15960 		if (!tnum_overlap(t1, t2))
15961 			return 0;
15962 		/* non-overlapping ranges */
15963 		if (umin1 > umax2 || umax1 < umin2)
15964 			return 0;
15965 		if (smin1 > smax2 || smax1 < smin2)
15966 			return 0;
15967 		if (!is_jmp32) {
15968 			/* if 64-bit ranges are inconclusive, see if we can
15969 			 * utilize 32-bit subrange knowledge to eliminate
15970 			 * branches that can't be taken a priori
15971 			 */
15972 			if (reg1->u32_min_value > reg2->u32_max_value ||
15973 			    reg1->u32_max_value < reg2->u32_min_value)
15974 				return 0;
15975 			if (reg1->s32_min_value > reg2->s32_max_value ||
15976 			    reg1->s32_max_value < reg2->s32_min_value)
15977 				return 0;
15978 		}
15979 		break;
15980 	case BPF_JNE:
15981 		/* constants, umin/umax and smin/smax checks would be
15982 		 * redundant in this case because they all should match
15983 		 */
15984 		if (tnum_is_const(t1) && tnum_is_const(t2))
15985 			return t1.value != t2.value;
15986 		if (!tnum_overlap(t1, t2))
15987 			return 1;
15988 		/* non-overlapping ranges */
15989 		if (umin1 > umax2 || umax1 < umin2)
15990 			return 1;
15991 		if (smin1 > smax2 || smax1 < smin2)
15992 			return 1;
15993 		if (!is_jmp32) {
15994 			/* if 64-bit ranges are inconclusive, see if we can
15995 			 * utilize 32-bit subrange knowledge to eliminate
15996 			 * branches that can't be taken a priori
15997 			 */
15998 			if (reg1->u32_min_value > reg2->u32_max_value ||
15999 			    reg1->u32_max_value < reg2->u32_min_value)
16000 				return 1;
16001 			if (reg1->s32_min_value > reg2->s32_max_value ||
16002 			    reg1->s32_max_value < reg2->s32_min_value)
16003 				return 1;
16004 		}
16005 		break;
16006 	case BPF_JSET:
16007 		if (!is_reg_const(reg2, is_jmp32)) {
16008 			swap(reg1, reg2);
16009 			swap(t1, t2);
16010 		}
16011 		if (!is_reg_const(reg2, is_jmp32))
16012 			return -1;
16013 		if ((~t1.mask & t1.value) & t2.value)
16014 			return 1;
16015 		if (!((t1.mask | t1.value) & t2.value))
16016 			return 0;
16017 		break;
16018 	case BPF_JGT:
16019 		if (umin1 > umax2)
16020 			return 1;
16021 		else if (umax1 <= umin2)
16022 			return 0;
16023 		break;
16024 	case BPF_JSGT:
16025 		if (smin1 > smax2)
16026 			return 1;
16027 		else if (smax1 <= smin2)
16028 			return 0;
16029 		break;
16030 	case BPF_JLT:
16031 		if (umax1 < umin2)
16032 			return 1;
16033 		else if (umin1 >= umax2)
16034 			return 0;
16035 		break;
16036 	case BPF_JSLT:
16037 		if (smax1 < smin2)
16038 			return 1;
16039 		else if (smin1 >= smax2)
16040 			return 0;
16041 		break;
16042 	case BPF_JGE:
16043 		if (umin1 >= umax2)
16044 			return 1;
16045 		else if (umax1 < umin2)
16046 			return 0;
16047 		break;
16048 	case BPF_JSGE:
16049 		if (smin1 >= smax2)
16050 			return 1;
16051 		else if (smax1 < smin2)
16052 			return 0;
16053 		break;
16054 	case BPF_JLE:
16055 		if (umax1 <= umin2)
16056 			return 1;
16057 		else if (umin1 > umax2)
16058 			return 0;
16059 		break;
16060 	case BPF_JSLE:
16061 		if (smax1 <= smin2)
16062 			return 1;
16063 		else if (smin1 > smax2)
16064 			return 0;
16065 		break;
16066 	}
16067 
16068 	return -1;
16069 }
16070 
flip_opcode(u32 opcode)16071 static int flip_opcode(u32 opcode)
16072 {
16073 	/* How can we transform "a <op> b" into "b <op> a"? */
16074 	static const u8 opcode_flip[16] = {
16075 		/* these stay the same */
16076 		[BPF_JEQ  >> 4] = BPF_JEQ,
16077 		[BPF_JNE  >> 4] = BPF_JNE,
16078 		[BPF_JSET >> 4] = BPF_JSET,
16079 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
16080 		[BPF_JGE  >> 4] = BPF_JLE,
16081 		[BPF_JGT  >> 4] = BPF_JLT,
16082 		[BPF_JLE  >> 4] = BPF_JGE,
16083 		[BPF_JLT  >> 4] = BPF_JGT,
16084 		[BPF_JSGE >> 4] = BPF_JSLE,
16085 		[BPF_JSGT >> 4] = BPF_JSLT,
16086 		[BPF_JSLE >> 4] = BPF_JSGE,
16087 		[BPF_JSLT >> 4] = BPF_JSGT
16088 	};
16089 	return opcode_flip[opcode >> 4];
16090 }
16091 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)16092 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16093 				   struct bpf_reg_state *src_reg,
16094 				   u8 opcode)
16095 {
16096 	struct bpf_reg_state *pkt;
16097 
16098 	if (src_reg->type == PTR_TO_PACKET_END) {
16099 		pkt = dst_reg;
16100 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
16101 		pkt = src_reg;
16102 		opcode = flip_opcode(opcode);
16103 	} else {
16104 		return -1;
16105 	}
16106 
16107 	if (pkt->range >= 0)
16108 		return -1;
16109 
16110 	switch (opcode) {
16111 	case BPF_JLE:
16112 		/* pkt <= pkt_end */
16113 		fallthrough;
16114 	case BPF_JGT:
16115 		/* pkt > pkt_end */
16116 		if (pkt->range == BEYOND_PKT_END)
16117 			/* pkt has at last one extra byte beyond pkt_end */
16118 			return opcode == BPF_JGT;
16119 		break;
16120 	case BPF_JLT:
16121 		/* pkt < pkt_end */
16122 		fallthrough;
16123 	case BPF_JGE:
16124 		/* pkt >= pkt_end */
16125 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16126 			return opcode == BPF_JGE;
16127 		break;
16128 	}
16129 	return -1;
16130 }
16131 
16132 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16133  * and return:
16134  *  1 - branch will be taken and "goto target" will be executed
16135  *  0 - branch will not be taken and fall-through to next insn
16136  * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16137  *      range [0,10]
16138  */
is_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16139 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16140 			   u8 opcode, bool is_jmp32)
16141 {
16142 	if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16143 		return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16144 
16145 	if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16146 		u64 val;
16147 
16148 		/* arrange that reg2 is a scalar, and reg1 is a pointer */
16149 		if (!is_reg_const(reg2, is_jmp32)) {
16150 			opcode = flip_opcode(opcode);
16151 			swap(reg1, reg2);
16152 		}
16153 		/* and ensure that reg2 is a constant */
16154 		if (!is_reg_const(reg2, is_jmp32))
16155 			return -1;
16156 
16157 		if (!reg_not_null(reg1))
16158 			return -1;
16159 
16160 		/* If pointer is valid tests against zero will fail so we can
16161 		 * use this to direct branch taken.
16162 		 */
16163 		val = reg_const_value(reg2, is_jmp32);
16164 		if (val != 0)
16165 			return -1;
16166 
16167 		switch (opcode) {
16168 		case BPF_JEQ:
16169 			return 0;
16170 		case BPF_JNE:
16171 			return 1;
16172 		default:
16173 			return -1;
16174 		}
16175 	}
16176 
16177 	/* now deal with two scalars, but not necessarily constants */
16178 	return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16179 }
16180 
16181 /* Opcode that corresponds to a *false* branch condition.
16182  * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16183  */
rev_opcode(u8 opcode)16184 static u8 rev_opcode(u8 opcode)
16185 {
16186 	switch (opcode) {
16187 	case BPF_JEQ:		return BPF_JNE;
16188 	case BPF_JNE:		return BPF_JEQ;
16189 	/* JSET doesn't have it's reverse opcode in BPF, so add
16190 	 * BPF_X flag to denote the reverse of that operation
16191 	 */
16192 	case BPF_JSET:		return BPF_JSET | BPF_X;
16193 	case BPF_JSET | BPF_X:	return BPF_JSET;
16194 	case BPF_JGE:		return BPF_JLT;
16195 	case BPF_JGT:		return BPF_JLE;
16196 	case BPF_JLE:		return BPF_JGT;
16197 	case BPF_JLT:		return BPF_JGE;
16198 	case BPF_JSGE:		return BPF_JSLT;
16199 	case BPF_JSGT:		return BPF_JSLE;
16200 	case BPF_JSLE:		return BPF_JSGT;
16201 	case BPF_JSLT:		return BPF_JSGE;
16202 	default:		return 0;
16203 	}
16204 }
16205 
16206 /* 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)16207 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16208 				u8 opcode, bool is_jmp32)
16209 {
16210 	struct tnum t;
16211 	u64 val;
16212 
16213 	/* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16214 	switch (opcode) {
16215 	case BPF_JGE:
16216 	case BPF_JGT:
16217 	case BPF_JSGE:
16218 	case BPF_JSGT:
16219 		opcode = flip_opcode(opcode);
16220 		swap(reg1, reg2);
16221 		break;
16222 	default:
16223 		break;
16224 	}
16225 
16226 	switch (opcode) {
16227 	case BPF_JEQ:
16228 		if (is_jmp32) {
16229 			reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16230 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16231 			reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16232 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16233 			reg2->u32_min_value = reg1->u32_min_value;
16234 			reg2->u32_max_value = reg1->u32_max_value;
16235 			reg2->s32_min_value = reg1->s32_min_value;
16236 			reg2->s32_max_value = reg1->s32_max_value;
16237 
16238 			t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16239 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16240 			reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16241 		} else {
16242 			reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16243 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16244 			reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16245 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16246 			reg2->umin_value = reg1->umin_value;
16247 			reg2->umax_value = reg1->umax_value;
16248 			reg2->smin_value = reg1->smin_value;
16249 			reg2->smax_value = reg1->smax_value;
16250 
16251 			reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16252 			reg2->var_off = reg1->var_off;
16253 		}
16254 		break;
16255 	case BPF_JNE:
16256 		if (!is_reg_const(reg2, is_jmp32))
16257 			swap(reg1, reg2);
16258 		if (!is_reg_const(reg2, is_jmp32))
16259 			break;
16260 
16261 		/* try to recompute the bound of reg1 if reg2 is a const and
16262 		 * is exactly the edge of reg1.
16263 		 */
16264 		val = reg_const_value(reg2, is_jmp32);
16265 		if (is_jmp32) {
16266 			/* u32_min_value is not equal to 0xffffffff at this point,
16267 			 * because otherwise u32_max_value is 0xffffffff as well,
16268 			 * in such a case both reg1 and reg2 would be constants,
16269 			 * jump would be predicted and reg_set_min_max() won't
16270 			 * be called.
16271 			 *
16272 			 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16273 			 * below.
16274 			 */
16275 			if (reg1->u32_min_value == (u32)val)
16276 				reg1->u32_min_value++;
16277 			if (reg1->u32_max_value == (u32)val)
16278 				reg1->u32_max_value--;
16279 			if (reg1->s32_min_value == (s32)val)
16280 				reg1->s32_min_value++;
16281 			if (reg1->s32_max_value == (s32)val)
16282 				reg1->s32_max_value--;
16283 		} else {
16284 			if (reg1->umin_value == (u64)val)
16285 				reg1->umin_value++;
16286 			if (reg1->umax_value == (u64)val)
16287 				reg1->umax_value--;
16288 			if (reg1->smin_value == (s64)val)
16289 				reg1->smin_value++;
16290 			if (reg1->smax_value == (s64)val)
16291 				reg1->smax_value--;
16292 		}
16293 		break;
16294 	case BPF_JSET:
16295 		if (!is_reg_const(reg2, is_jmp32))
16296 			swap(reg1, reg2);
16297 		if (!is_reg_const(reg2, is_jmp32))
16298 			break;
16299 		val = reg_const_value(reg2, is_jmp32);
16300 		/* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16301 		 * requires single bit to learn something useful. E.g., if we
16302 		 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16303 		 * are actually set? We can learn something definite only if
16304 		 * it's a single-bit value to begin with.
16305 		 *
16306 		 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16307 		 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16308 		 * bit 1 is set, which we can readily use in adjustments.
16309 		 */
16310 		if (!is_power_of_2(val))
16311 			break;
16312 		if (is_jmp32) {
16313 			t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16314 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16315 		} else {
16316 			reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16317 		}
16318 		break;
16319 	case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16320 		if (!is_reg_const(reg2, is_jmp32))
16321 			swap(reg1, reg2);
16322 		if (!is_reg_const(reg2, is_jmp32))
16323 			break;
16324 		val = reg_const_value(reg2, is_jmp32);
16325 		/* Forget the ranges before narrowing tnums, to avoid invariant
16326 		 * violations if we're on a dead branch.
16327 		 */
16328 		__mark_reg_unbounded(reg1);
16329 		if (is_jmp32) {
16330 			t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16331 			reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16332 		} else {
16333 			reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16334 		}
16335 		break;
16336 	case BPF_JLE:
16337 		if (is_jmp32) {
16338 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16339 			reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16340 		} else {
16341 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16342 			reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16343 		}
16344 		break;
16345 	case BPF_JLT:
16346 		if (is_jmp32) {
16347 			reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16348 			reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16349 		} else {
16350 			reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16351 			reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16352 		}
16353 		break;
16354 	case BPF_JSLE:
16355 		if (is_jmp32) {
16356 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16357 			reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16358 		} else {
16359 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16360 			reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16361 		}
16362 		break;
16363 	case BPF_JSLT:
16364 		if (is_jmp32) {
16365 			reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16366 			reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16367 		} else {
16368 			reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16369 			reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16370 		}
16371 		break;
16372 	default:
16373 		return;
16374 	}
16375 }
16376 
16377 /* Adjusts the register min/max values in the case that the dst_reg and
16378  * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16379  * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16380  * Technically we can do similar adjustments for pointers to the same object,
16381  * but we don't support that right now.
16382  */
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)16383 static int reg_set_min_max(struct bpf_verifier_env *env,
16384 			   struct bpf_reg_state *true_reg1,
16385 			   struct bpf_reg_state *true_reg2,
16386 			   struct bpf_reg_state *false_reg1,
16387 			   struct bpf_reg_state *false_reg2,
16388 			   u8 opcode, bool is_jmp32)
16389 {
16390 	int err;
16391 
16392 	/* If either register is a pointer, we can't learn anything about its
16393 	 * variable offset from the compare (unless they were a pointer into
16394 	 * the same object, but we don't bother with that).
16395 	 */
16396 	if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16397 		return 0;
16398 
16399 	/* fallthrough (FALSE) branch */
16400 	regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16401 	reg_bounds_sync(false_reg1);
16402 	reg_bounds_sync(false_reg2);
16403 
16404 	/* jump (TRUE) branch */
16405 	regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16406 	reg_bounds_sync(true_reg1);
16407 	reg_bounds_sync(true_reg2);
16408 
16409 	err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16410 	err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16411 	err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16412 	err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16413 	return err;
16414 }
16415 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)16416 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16417 				 struct bpf_reg_state *reg, u32 id,
16418 				 bool is_null)
16419 {
16420 	if (type_may_be_null(reg->type) && reg->id == id &&
16421 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16422 		/* Old offset (both fixed and variable parts) should have been
16423 		 * known-zero, because we don't allow pointer arithmetic on
16424 		 * pointers that might be NULL. If we see this happening, don't
16425 		 * convert the register.
16426 		 *
16427 		 * But in some cases, some helpers that return local kptrs
16428 		 * advance offset for the returned pointer. In those cases, it
16429 		 * is fine to expect to see reg->off.
16430 		 */
16431 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16432 			return;
16433 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16434 		    WARN_ON_ONCE(reg->off))
16435 			return;
16436 
16437 		if (is_null) {
16438 			reg->type = SCALAR_VALUE;
16439 			/* We don't need id and ref_obj_id from this point
16440 			 * onwards anymore, thus we should better reset it,
16441 			 * so that state pruning has chances to take effect.
16442 			 */
16443 			reg->id = 0;
16444 			reg->ref_obj_id = 0;
16445 
16446 			return;
16447 		}
16448 
16449 		mark_ptr_not_null_reg(reg);
16450 
16451 		if (!reg_may_point_to_spin_lock(reg)) {
16452 			/* For not-NULL ptr, reg->ref_obj_id will be reset
16453 			 * in release_reference().
16454 			 *
16455 			 * reg->id is still used by spin_lock ptr. Other
16456 			 * than spin_lock ptr type, reg->id can be reset.
16457 			 */
16458 			reg->id = 0;
16459 		}
16460 	}
16461 }
16462 
16463 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16464  * be folded together at some point.
16465  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)16466 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16467 				  bool is_null)
16468 {
16469 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
16470 	struct bpf_reg_state *regs = state->regs, *reg;
16471 	u32 ref_obj_id = regs[regno].ref_obj_id;
16472 	u32 id = regs[regno].id;
16473 
16474 	if (ref_obj_id && ref_obj_id == id && is_null)
16475 		/* regs[regno] is in the " == NULL" branch.
16476 		 * No one could have freed the reference state before
16477 		 * doing the NULL check.
16478 		 */
16479 		WARN_ON_ONCE(release_reference_nomark(vstate, id));
16480 
16481 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16482 		mark_ptr_or_null_reg(state, reg, id, is_null);
16483 	}));
16484 }
16485 
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)16486 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16487 				   struct bpf_reg_state *dst_reg,
16488 				   struct bpf_reg_state *src_reg,
16489 				   struct bpf_verifier_state *this_branch,
16490 				   struct bpf_verifier_state *other_branch)
16491 {
16492 	if (BPF_SRC(insn->code) != BPF_X)
16493 		return false;
16494 
16495 	/* Pointers are always 64-bit. */
16496 	if (BPF_CLASS(insn->code) == BPF_JMP32)
16497 		return false;
16498 
16499 	switch (BPF_OP(insn->code)) {
16500 	case BPF_JGT:
16501 		if ((dst_reg->type == PTR_TO_PACKET &&
16502 		     src_reg->type == PTR_TO_PACKET_END) ||
16503 		    (dst_reg->type == PTR_TO_PACKET_META &&
16504 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16505 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16506 			find_good_pkt_pointers(this_branch, dst_reg,
16507 					       dst_reg->type, false);
16508 			mark_pkt_end(other_branch, insn->dst_reg, true);
16509 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16510 			    src_reg->type == PTR_TO_PACKET) ||
16511 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16512 			    src_reg->type == PTR_TO_PACKET_META)) {
16513 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
16514 			find_good_pkt_pointers(other_branch, src_reg,
16515 					       src_reg->type, true);
16516 			mark_pkt_end(this_branch, insn->src_reg, false);
16517 		} else {
16518 			return false;
16519 		}
16520 		break;
16521 	case BPF_JLT:
16522 		if ((dst_reg->type == PTR_TO_PACKET &&
16523 		     src_reg->type == PTR_TO_PACKET_END) ||
16524 		    (dst_reg->type == PTR_TO_PACKET_META &&
16525 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16526 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16527 			find_good_pkt_pointers(other_branch, dst_reg,
16528 					       dst_reg->type, true);
16529 			mark_pkt_end(this_branch, insn->dst_reg, false);
16530 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16531 			    src_reg->type == PTR_TO_PACKET) ||
16532 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16533 			    src_reg->type == PTR_TO_PACKET_META)) {
16534 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
16535 			find_good_pkt_pointers(this_branch, src_reg,
16536 					       src_reg->type, false);
16537 			mark_pkt_end(other_branch, insn->src_reg, true);
16538 		} else {
16539 			return false;
16540 		}
16541 		break;
16542 	case BPF_JGE:
16543 		if ((dst_reg->type == PTR_TO_PACKET &&
16544 		     src_reg->type == PTR_TO_PACKET_END) ||
16545 		    (dst_reg->type == PTR_TO_PACKET_META &&
16546 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16547 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16548 			find_good_pkt_pointers(this_branch, dst_reg,
16549 					       dst_reg->type, true);
16550 			mark_pkt_end(other_branch, insn->dst_reg, false);
16551 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16552 			    src_reg->type == PTR_TO_PACKET) ||
16553 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16554 			    src_reg->type == PTR_TO_PACKET_META)) {
16555 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16556 			find_good_pkt_pointers(other_branch, src_reg,
16557 					       src_reg->type, false);
16558 			mark_pkt_end(this_branch, insn->src_reg, true);
16559 		} else {
16560 			return false;
16561 		}
16562 		break;
16563 	case BPF_JLE:
16564 		if ((dst_reg->type == PTR_TO_PACKET &&
16565 		     src_reg->type == PTR_TO_PACKET_END) ||
16566 		    (dst_reg->type == PTR_TO_PACKET_META &&
16567 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16568 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16569 			find_good_pkt_pointers(other_branch, dst_reg,
16570 					       dst_reg->type, false);
16571 			mark_pkt_end(this_branch, insn->dst_reg, true);
16572 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
16573 			    src_reg->type == PTR_TO_PACKET) ||
16574 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16575 			    src_reg->type == PTR_TO_PACKET_META)) {
16576 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16577 			find_good_pkt_pointers(this_branch, src_reg,
16578 					       src_reg->type, true);
16579 			mark_pkt_end(other_branch, insn->src_reg, false);
16580 		} else {
16581 			return false;
16582 		}
16583 		break;
16584 	default:
16585 		return false;
16586 	}
16587 
16588 	return true;
16589 }
16590 
__collect_linked_regs(struct linked_regs * reg_set,struct bpf_reg_state * reg,u32 id,u32 frameno,u32 spi_or_reg,bool is_reg)16591 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16592 				  u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16593 {
16594 	struct linked_reg *e;
16595 
16596 	if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16597 		return;
16598 
16599 	e = linked_regs_push(reg_set);
16600 	if (e) {
16601 		e->frameno = frameno;
16602 		e->is_reg = is_reg;
16603 		e->regno = spi_or_reg;
16604 	} else {
16605 		reg->id = 0;
16606 	}
16607 }
16608 
16609 /* For all R being scalar registers or spilled scalar registers
16610  * in verifier state, save R in linked_regs if R->id == id.
16611  * If there are too many Rs sharing same id, reset id for leftover Rs.
16612  */
collect_linked_regs(struct bpf_verifier_state * vstate,u32 id,struct linked_regs * linked_regs)16613 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16614 				struct linked_regs *linked_regs)
16615 {
16616 	struct bpf_func_state *func;
16617 	struct bpf_reg_state *reg;
16618 	int i, j;
16619 
16620 	id = id & ~BPF_ADD_CONST;
16621 	for (i = vstate->curframe; i >= 0; i--) {
16622 		func = vstate->frame[i];
16623 		for (j = 0; j < BPF_REG_FP; j++) {
16624 			reg = &func->regs[j];
16625 			__collect_linked_regs(linked_regs, reg, id, i, j, true);
16626 		}
16627 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16628 			if (!is_spilled_reg(&func->stack[j]))
16629 				continue;
16630 			reg = &func->stack[j].spilled_ptr;
16631 			__collect_linked_regs(linked_regs, reg, id, i, j, false);
16632 		}
16633 	}
16634 }
16635 
16636 /* For all R in linked_regs, copy known_reg range into R
16637  * if R->id == known_reg->id.
16638  */
sync_linked_regs(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg,struct linked_regs * linked_regs)16639 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16640 			     struct linked_regs *linked_regs)
16641 {
16642 	struct bpf_reg_state fake_reg;
16643 	struct bpf_reg_state *reg;
16644 	struct linked_reg *e;
16645 	int i;
16646 
16647 	for (i = 0; i < linked_regs->cnt; ++i) {
16648 		e = &linked_regs->entries[i];
16649 		reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16650 				: &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16651 		if (reg->type != SCALAR_VALUE || reg == known_reg)
16652 			continue;
16653 		if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16654 			continue;
16655 		if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16656 		    reg->off == known_reg->off) {
16657 			s32 saved_subreg_def = reg->subreg_def;
16658 
16659 			copy_register_state(reg, known_reg);
16660 			reg->subreg_def = saved_subreg_def;
16661 		} else {
16662 			s32 saved_subreg_def = reg->subreg_def;
16663 			s32 saved_off = reg->off;
16664 
16665 			fake_reg.type = SCALAR_VALUE;
16666 			__mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16667 
16668 			/* reg = known_reg; reg += delta */
16669 			copy_register_state(reg, known_reg);
16670 			/*
16671 			 * Must preserve off, id and add_const flag,
16672 			 * otherwise another sync_linked_regs() will be incorrect.
16673 			 */
16674 			reg->off = saved_off;
16675 			reg->subreg_def = saved_subreg_def;
16676 
16677 			scalar32_min_max_add(reg, &fake_reg);
16678 			scalar_min_max_add(reg, &fake_reg);
16679 			reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16680 		}
16681 	}
16682 }
16683 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)16684 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16685 			     struct bpf_insn *insn, int *insn_idx)
16686 {
16687 	struct bpf_verifier_state *this_branch = env->cur_state;
16688 	struct bpf_verifier_state *other_branch;
16689 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16690 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16691 	struct bpf_reg_state *eq_branch_regs;
16692 	struct linked_regs linked_regs = {};
16693 	u8 opcode = BPF_OP(insn->code);
16694 	int insn_flags = 0;
16695 	bool is_jmp32;
16696 	int pred = -1;
16697 	int err;
16698 
16699 	/* Only conditional jumps are expected to reach here. */
16700 	if (opcode == BPF_JA || opcode > BPF_JCOND) {
16701 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16702 		return -EINVAL;
16703 	}
16704 
16705 	if (opcode == BPF_JCOND) {
16706 		struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16707 		int idx = *insn_idx;
16708 
16709 		if (insn->code != (BPF_JMP | BPF_JCOND) ||
16710 		    insn->src_reg != BPF_MAY_GOTO ||
16711 		    insn->dst_reg || insn->imm) {
16712 			verbose(env, "invalid may_goto imm %d\n", insn->imm);
16713 			return -EINVAL;
16714 		}
16715 		prev_st = find_prev_entry(env, cur_st->parent, idx);
16716 
16717 		/* branch out 'fallthrough' insn as a new state to explore */
16718 		queued_st = push_stack(env, idx + 1, idx, false);
16719 		if (!queued_st)
16720 			return -ENOMEM;
16721 
16722 		queued_st->may_goto_depth++;
16723 		if (prev_st)
16724 			widen_imprecise_scalars(env, prev_st, queued_st);
16725 		*insn_idx += insn->off;
16726 		return 0;
16727 	}
16728 
16729 	/* check src2 operand */
16730 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16731 	if (err)
16732 		return err;
16733 
16734 	dst_reg = &regs[insn->dst_reg];
16735 	if (BPF_SRC(insn->code) == BPF_X) {
16736 		if (insn->imm != 0) {
16737 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16738 			return -EINVAL;
16739 		}
16740 
16741 		/* check src1 operand */
16742 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
16743 		if (err)
16744 			return err;
16745 
16746 		src_reg = &regs[insn->src_reg];
16747 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16748 		    is_pointer_value(env, insn->src_reg)) {
16749 			verbose(env, "R%d pointer comparison prohibited\n",
16750 				insn->src_reg);
16751 			return -EACCES;
16752 		}
16753 
16754 		if (src_reg->type == PTR_TO_STACK)
16755 			insn_flags |= INSN_F_SRC_REG_STACK;
16756 		if (dst_reg->type == PTR_TO_STACK)
16757 			insn_flags |= INSN_F_DST_REG_STACK;
16758 	} else {
16759 		if (insn->src_reg != BPF_REG_0) {
16760 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16761 			return -EINVAL;
16762 		}
16763 		src_reg = &env->fake_reg[0];
16764 		memset(src_reg, 0, sizeof(*src_reg));
16765 		src_reg->type = SCALAR_VALUE;
16766 		__mark_reg_known(src_reg, insn->imm);
16767 
16768 		if (dst_reg->type == PTR_TO_STACK)
16769 			insn_flags |= INSN_F_DST_REG_STACK;
16770 	}
16771 
16772 	if (insn_flags) {
16773 		err = push_jmp_history(env, this_branch, insn_flags, 0);
16774 		if (err)
16775 			return err;
16776 	}
16777 
16778 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16779 	pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16780 	if (pred >= 0) {
16781 		/* If we get here with a dst_reg pointer type it is because
16782 		 * above is_branch_taken() special cased the 0 comparison.
16783 		 */
16784 		if (!__is_pointer_value(false, dst_reg))
16785 			err = mark_chain_precision(env, insn->dst_reg);
16786 		if (BPF_SRC(insn->code) == BPF_X && !err &&
16787 		    !__is_pointer_value(false, src_reg))
16788 			err = mark_chain_precision(env, insn->src_reg);
16789 		if (err)
16790 			return err;
16791 	}
16792 
16793 	if (pred == 1) {
16794 		/* Only follow the goto, ignore fall-through. If needed, push
16795 		 * the fall-through branch for simulation under speculative
16796 		 * execution.
16797 		 */
16798 		if (!env->bypass_spec_v1 &&
16799 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
16800 					       *insn_idx))
16801 			return -EFAULT;
16802 		if (env->log.level & BPF_LOG_LEVEL)
16803 			print_insn_state(env, this_branch, this_branch->curframe);
16804 		*insn_idx += insn->off;
16805 		return 0;
16806 	} else if (pred == 0) {
16807 		/* Only follow the fall-through branch, since that's where the
16808 		 * program will go. If needed, push the goto branch for
16809 		 * simulation under speculative execution.
16810 		 */
16811 		if (!env->bypass_spec_v1 &&
16812 		    !sanitize_speculative_path(env, insn,
16813 					       *insn_idx + insn->off + 1,
16814 					       *insn_idx))
16815 			return -EFAULT;
16816 		if (env->log.level & BPF_LOG_LEVEL)
16817 			print_insn_state(env, this_branch, this_branch->curframe);
16818 		return 0;
16819 	}
16820 
16821 	/* Push scalar registers sharing same ID to jump history,
16822 	 * do this before creating 'other_branch', so that both
16823 	 * 'this_branch' and 'other_branch' share this history
16824 	 * if parent state is created.
16825 	 */
16826 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16827 		collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16828 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16829 		collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16830 	if (linked_regs.cnt > 1) {
16831 		err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16832 		if (err)
16833 			return err;
16834 	}
16835 
16836 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
16837 				  false);
16838 	if (!other_branch)
16839 		return -EFAULT;
16840 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
16841 
16842 	if (BPF_SRC(insn->code) == BPF_X) {
16843 		err = reg_set_min_max(env,
16844 				      &other_branch_regs[insn->dst_reg],
16845 				      &other_branch_regs[insn->src_reg],
16846 				      dst_reg, src_reg, opcode, is_jmp32);
16847 	} else /* BPF_SRC(insn->code) == BPF_K */ {
16848 		/* reg_set_min_max() can mangle the fake_reg. Make a copy
16849 		 * so that these are two different memory locations. The
16850 		 * src_reg is not used beyond here in context of K.
16851 		 */
16852 		memcpy(&env->fake_reg[1], &env->fake_reg[0],
16853 		       sizeof(env->fake_reg[0]));
16854 		err = reg_set_min_max(env,
16855 				      &other_branch_regs[insn->dst_reg],
16856 				      &env->fake_reg[0],
16857 				      dst_reg, &env->fake_reg[1],
16858 				      opcode, is_jmp32);
16859 	}
16860 	if (err)
16861 		return err;
16862 
16863 	if (BPF_SRC(insn->code) == BPF_X &&
16864 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
16865 	    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
16866 		sync_linked_regs(this_branch, src_reg, &linked_regs);
16867 		sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
16868 	}
16869 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
16870 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
16871 		sync_linked_regs(this_branch, dst_reg, &linked_regs);
16872 		sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
16873 	}
16874 
16875 	/* if one pointer register is compared to another pointer
16876 	 * register check if PTR_MAYBE_NULL could be lifted.
16877 	 * E.g. register A - maybe null
16878 	 *      register B - not null
16879 	 * for JNE A, B, ... - A is not null in the false branch;
16880 	 * for JEQ A, B, ... - A is not null in the true branch.
16881 	 *
16882 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
16883 	 * not need to be null checked by the BPF program, i.e.,
16884 	 * could be null even without PTR_MAYBE_NULL marking, so
16885 	 * only propagate nullness when neither reg is that type.
16886 	 */
16887 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
16888 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
16889 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
16890 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
16891 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
16892 		eq_branch_regs = NULL;
16893 		switch (opcode) {
16894 		case BPF_JEQ:
16895 			eq_branch_regs = other_branch_regs;
16896 			break;
16897 		case BPF_JNE:
16898 			eq_branch_regs = regs;
16899 			break;
16900 		default:
16901 			/* do nothing */
16902 			break;
16903 		}
16904 		if (eq_branch_regs) {
16905 			if (type_may_be_null(src_reg->type))
16906 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
16907 			else
16908 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
16909 		}
16910 	}
16911 
16912 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
16913 	 * NOTE: these optimizations below are related with pointer comparison
16914 	 *       which will never be JMP32.
16915 	 */
16916 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
16917 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
16918 	    type_may_be_null(dst_reg->type)) {
16919 		/* Mark all identical registers in each branch as either
16920 		 * safe or unknown depending R == 0 or R != 0 conditional.
16921 		 */
16922 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
16923 				      opcode == BPF_JNE);
16924 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
16925 				      opcode == BPF_JEQ);
16926 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
16927 					   this_branch, other_branch) &&
16928 		   is_pointer_value(env, insn->dst_reg)) {
16929 		verbose(env, "R%d pointer comparison prohibited\n",
16930 			insn->dst_reg);
16931 		return -EACCES;
16932 	}
16933 	if (env->log.level & BPF_LOG_LEVEL)
16934 		print_insn_state(env, this_branch, this_branch->curframe);
16935 	return 0;
16936 }
16937 
16938 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)16939 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
16940 {
16941 	struct bpf_insn_aux_data *aux = cur_aux(env);
16942 	struct bpf_reg_state *regs = cur_regs(env);
16943 	struct bpf_reg_state *dst_reg;
16944 	struct bpf_map *map;
16945 	int err;
16946 
16947 	if (BPF_SIZE(insn->code) != BPF_DW) {
16948 		verbose(env, "invalid BPF_LD_IMM insn\n");
16949 		return -EINVAL;
16950 	}
16951 	if (insn->off != 0) {
16952 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
16953 		return -EINVAL;
16954 	}
16955 
16956 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
16957 	if (err)
16958 		return err;
16959 
16960 	dst_reg = &regs[insn->dst_reg];
16961 	if (insn->src_reg == 0) {
16962 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
16963 
16964 		dst_reg->type = SCALAR_VALUE;
16965 		__mark_reg_known(&regs[insn->dst_reg], imm);
16966 		return 0;
16967 	}
16968 
16969 	/* All special src_reg cases are listed below. From this point onwards
16970 	 * we either succeed and assign a corresponding dst_reg->type after
16971 	 * zeroing the offset, or fail and reject the program.
16972 	 */
16973 	mark_reg_known_zero(env, regs, insn->dst_reg);
16974 
16975 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
16976 		dst_reg->type = aux->btf_var.reg_type;
16977 		switch (base_type(dst_reg->type)) {
16978 		case PTR_TO_MEM:
16979 			dst_reg->mem_size = aux->btf_var.mem_size;
16980 			break;
16981 		case PTR_TO_BTF_ID:
16982 			dst_reg->btf = aux->btf_var.btf;
16983 			dst_reg->btf_id = aux->btf_var.btf_id;
16984 			break;
16985 		default:
16986 			verifier_bug(env, "pseudo btf id: unexpected dst reg type");
16987 			return -EFAULT;
16988 		}
16989 		return 0;
16990 	}
16991 
16992 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
16993 		struct bpf_prog_aux *aux = env->prog->aux;
16994 		u32 subprogno = find_subprog(env,
16995 					     env->insn_idx + insn->imm + 1);
16996 
16997 		if (!aux->func_info) {
16998 			verbose(env, "missing btf func_info\n");
16999 			return -EINVAL;
17000 		}
17001 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17002 			verbose(env, "callback function not static\n");
17003 			return -EINVAL;
17004 		}
17005 
17006 		dst_reg->type = PTR_TO_FUNC;
17007 		dst_reg->subprogno = subprogno;
17008 		return 0;
17009 	}
17010 
17011 	map = env->used_maps[aux->map_index];
17012 	dst_reg->map_ptr = map;
17013 
17014 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17015 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17016 		if (map->map_type == BPF_MAP_TYPE_ARENA) {
17017 			__mark_reg_unknown(env, dst_reg);
17018 			return 0;
17019 		}
17020 		dst_reg->type = PTR_TO_MAP_VALUE;
17021 		dst_reg->off = aux->map_off;
17022 		WARN_ON_ONCE(map->max_entries != 1);
17023 		/* We want reg->id to be same (0) as map_value is not distinct */
17024 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17025 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17026 		dst_reg->type = CONST_PTR_TO_MAP;
17027 	} else {
17028 		verifier_bug(env, "unexpected src reg value for ldimm64");
17029 		return -EFAULT;
17030 	}
17031 
17032 	return 0;
17033 }
17034 
may_access_skb(enum bpf_prog_type type)17035 static bool may_access_skb(enum bpf_prog_type type)
17036 {
17037 	switch (type) {
17038 	case BPF_PROG_TYPE_SOCKET_FILTER:
17039 	case BPF_PROG_TYPE_SCHED_CLS:
17040 	case BPF_PROG_TYPE_SCHED_ACT:
17041 		return true;
17042 	default:
17043 		return false;
17044 	}
17045 }
17046 
17047 /* verify safety of LD_ABS|LD_IND instructions:
17048  * - they can only appear in the programs where ctx == skb
17049  * - since they are wrappers of function calls, they scratch R1-R5 registers,
17050  *   preserve R6-R9, and store return value into R0
17051  *
17052  * Implicit input:
17053  *   ctx == skb == R6 == CTX
17054  *
17055  * Explicit input:
17056  *   SRC == any register
17057  *   IMM == 32-bit immediate
17058  *
17059  * Output:
17060  *   R0 - 8/16/32-bit skb data converted to cpu endianness
17061  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)17062 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17063 {
17064 	struct bpf_reg_state *regs = cur_regs(env);
17065 	static const int ctx_reg = BPF_REG_6;
17066 	u8 mode = BPF_MODE(insn->code);
17067 	int i, err;
17068 
17069 	if (!may_access_skb(resolve_prog_type(env->prog))) {
17070 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17071 		return -EINVAL;
17072 	}
17073 
17074 	if (!env->ops->gen_ld_abs) {
17075 		verifier_bug(env, "gen_ld_abs is null");
17076 		return -EFAULT;
17077 	}
17078 
17079 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17080 	    BPF_SIZE(insn->code) == BPF_DW ||
17081 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17082 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17083 		return -EINVAL;
17084 	}
17085 
17086 	/* check whether implicit source operand (register R6) is readable */
17087 	err = check_reg_arg(env, ctx_reg, SRC_OP);
17088 	if (err)
17089 		return err;
17090 
17091 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17092 	 * gen_ld_abs() may terminate the program at runtime, leading to
17093 	 * reference leak.
17094 	 */
17095 	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17096 	if (err)
17097 		return err;
17098 
17099 	if (regs[ctx_reg].type != PTR_TO_CTX) {
17100 		verbose(env,
17101 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17102 		return -EINVAL;
17103 	}
17104 
17105 	if (mode == BPF_IND) {
17106 		/* check explicit source operand */
17107 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
17108 		if (err)
17109 			return err;
17110 	}
17111 
17112 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
17113 	if (err < 0)
17114 		return err;
17115 
17116 	/* reset caller saved regs to unreadable */
17117 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
17118 		mark_reg_not_init(env, regs, caller_saved[i]);
17119 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17120 	}
17121 
17122 	/* mark destination R0 register as readable, since it contains
17123 	 * the value fetched from the packet.
17124 	 * Already marked as written above.
17125 	 */
17126 	mark_reg_unknown(env, regs, BPF_REG_0);
17127 	/* ld_abs load up to 32-bit skb data. */
17128 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17129 	return 0;
17130 }
17131 
check_return_code(struct bpf_verifier_env * env,int regno,const char * reg_name)17132 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17133 {
17134 	const char *exit_ctx = "At program exit";
17135 	struct tnum enforce_attach_type_range = tnum_unknown;
17136 	const struct bpf_prog *prog = env->prog;
17137 	struct bpf_reg_state *reg = reg_state(env, regno);
17138 	struct bpf_retval_range range = retval_range(0, 1);
17139 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17140 	int err;
17141 	struct bpf_func_state *frame = env->cur_state->frame[0];
17142 	const bool is_subprog = frame->subprogno;
17143 	bool return_32bit = false;
17144 	const struct btf_type *reg_type, *ret_type = NULL;
17145 
17146 	/* LSM and struct_ops func-ptr's return type could be "void" */
17147 	if (!is_subprog || frame->in_exception_callback_fn) {
17148 		switch (prog_type) {
17149 		case BPF_PROG_TYPE_LSM:
17150 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
17151 				/* See below, can be 0 or 0-1 depending on hook. */
17152 				break;
17153 			if (!prog->aux->attach_func_proto->type)
17154 				return 0;
17155 			break;
17156 		case BPF_PROG_TYPE_STRUCT_OPS:
17157 			if (!prog->aux->attach_func_proto->type)
17158 				return 0;
17159 
17160 			if (frame->in_exception_callback_fn)
17161 				break;
17162 
17163 			/* Allow a struct_ops program to return a referenced kptr if it
17164 			 * matches the operator's return type and is in its unmodified
17165 			 * form. A scalar zero (i.e., a null pointer) is also allowed.
17166 			 */
17167 			reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17168 			ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17169 							prog->aux->attach_func_proto->type,
17170 							NULL);
17171 			if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17172 				return __check_ptr_off_reg(env, reg, regno, false);
17173 			break;
17174 		default:
17175 			break;
17176 		}
17177 	}
17178 
17179 	/* eBPF calling convention is such that R0 is used
17180 	 * to return the value from eBPF program.
17181 	 * Make sure that it's readable at this time
17182 	 * of bpf_exit, which means that program wrote
17183 	 * something into it earlier
17184 	 */
17185 	err = check_reg_arg(env, regno, SRC_OP);
17186 	if (err)
17187 		return err;
17188 
17189 	if (is_pointer_value(env, regno)) {
17190 		verbose(env, "R%d leaks addr as return value\n", regno);
17191 		return -EACCES;
17192 	}
17193 
17194 	if (frame->in_async_callback_fn) {
17195 		exit_ctx = "At async callback return";
17196 		range = frame->callback_ret_range;
17197 		goto enforce_retval;
17198 	}
17199 
17200 	if (is_subprog && !frame->in_exception_callback_fn) {
17201 		if (reg->type != SCALAR_VALUE) {
17202 			verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17203 				regno, reg_type_str(env, reg->type));
17204 			return -EINVAL;
17205 		}
17206 		return 0;
17207 	}
17208 
17209 	switch (prog_type) {
17210 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17211 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17212 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17213 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17214 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17215 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17216 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17217 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17218 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17219 		    env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17220 			range = retval_range(1, 1);
17221 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17222 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17223 			range = retval_range(0, 3);
17224 		break;
17225 	case BPF_PROG_TYPE_CGROUP_SKB:
17226 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17227 			range = retval_range(0, 3);
17228 			enforce_attach_type_range = tnum_range(2, 3);
17229 		}
17230 		break;
17231 	case BPF_PROG_TYPE_CGROUP_SOCK:
17232 	case BPF_PROG_TYPE_SOCK_OPS:
17233 	case BPF_PROG_TYPE_CGROUP_DEVICE:
17234 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
17235 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17236 		break;
17237 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17238 		if (!env->prog->aux->attach_btf_id)
17239 			return 0;
17240 		range = retval_range(0, 0);
17241 		break;
17242 	case BPF_PROG_TYPE_TRACING:
17243 		switch (env->prog->expected_attach_type) {
17244 		case BPF_TRACE_FENTRY:
17245 		case BPF_TRACE_FEXIT:
17246 			range = retval_range(0, 0);
17247 			break;
17248 		case BPF_TRACE_RAW_TP:
17249 		case BPF_MODIFY_RETURN:
17250 			return 0;
17251 		case BPF_TRACE_ITER:
17252 			break;
17253 		default:
17254 			return -ENOTSUPP;
17255 		}
17256 		break;
17257 	case BPF_PROG_TYPE_KPROBE:
17258 		switch (env->prog->expected_attach_type) {
17259 		case BPF_TRACE_KPROBE_SESSION:
17260 		case BPF_TRACE_UPROBE_SESSION:
17261 			range = retval_range(0, 1);
17262 			break;
17263 		default:
17264 			return 0;
17265 		}
17266 		break;
17267 	case BPF_PROG_TYPE_SK_LOOKUP:
17268 		range = retval_range(SK_DROP, SK_PASS);
17269 		break;
17270 
17271 	case BPF_PROG_TYPE_LSM:
17272 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17273 			/* no range found, any return value is allowed */
17274 			if (!get_func_retval_range(env->prog, &range))
17275 				return 0;
17276 			/* no restricted range, any return value is allowed */
17277 			if (range.minval == S32_MIN && range.maxval == S32_MAX)
17278 				return 0;
17279 			return_32bit = true;
17280 		} else if (!env->prog->aux->attach_func_proto->type) {
17281 			/* Make sure programs that attach to void
17282 			 * hooks don't try to modify return value.
17283 			 */
17284 			range = retval_range(1, 1);
17285 		}
17286 		break;
17287 
17288 	case BPF_PROG_TYPE_NETFILTER:
17289 		range = retval_range(NF_DROP, NF_ACCEPT);
17290 		break;
17291 	case BPF_PROG_TYPE_STRUCT_OPS:
17292 		if (!ret_type)
17293 			return 0;
17294 		range = retval_range(0, 0);
17295 		break;
17296 	case BPF_PROG_TYPE_EXT:
17297 		/* freplace program can return anything as its return value
17298 		 * depends on the to-be-replaced kernel func or bpf program.
17299 		 */
17300 	default:
17301 		return 0;
17302 	}
17303 
17304 enforce_retval:
17305 	if (reg->type != SCALAR_VALUE) {
17306 		verbose(env, "%s the register R%d is not a known value (%s)\n",
17307 			exit_ctx, regno, reg_type_str(env, reg->type));
17308 		return -EINVAL;
17309 	}
17310 
17311 	err = mark_chain_precision(env, regno);
17312 	if (err)
17313 		return err;
17314 
17315 	if (!retval_range_within(range, reg, return_32bit)) {
17316 		verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17317 		if (!is_subprog &&
17318 		    prog->expected_attach_type == BPF_LSM_CGROUP &&
17319 		    prog_type == BPF_PROG_TYPE_LSM &&
17320 		    !prog->aux->attach_func_proto->type)
17321 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17322 		return -EINVAL;
17323 	}
17324 
17325 	if (!tnum_is_unknown(enforce_attach_type_range) &&
17326 	    tnum_in(enforce_attach_type_range, reg->var_off))
17327 		env->prog->enforce_expected_attach_type = 1;
17328 	return 0;
17329 }
17330 
mark_subprog_changes_pkt_data(struct bpf_verifier_env * env,int off)17331 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17332 {
17333 	struct bpf_subprog_info *subprog;
17334 
17335 	subprog = bpf_find_containing_subprog(env, off);
17336 	subprog->changes_pkt_data = true;
17337 }
17338 
mark_subprog_might_sleep(struct bpf_verifier_env * env,int off)17339 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17340 {
17341 	struct bpf_subprog_info *subprog;
17342 
17343 	subprog = bpf_find_containing_subprog(env, off);
17344 	subprog->might_sleep = true;
17345 }
17346 
17347 /* 't' is an index of a call-site.
17348  * 'w' is a callee entry point.
17349  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17350  * Rely on DFS traversal order and absence of recursive calls to guarantee that
17351  * callee's change_pkt_data marks would be correct at that moment.
17352  */
merge_callee_effects(struct bpf_verifier_env * env,int t,int w)17353 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17354 {
17355 	struct bpf_subprog_info *caller, *callee;
17356 
17357 	caller = bpf_find_containing_subprog(env, t);
17358 	callee = bpf_find_containing_subprog(env, w);
17359 	caller->changes_pkt_data |= callee->changes_pkt_data;
17360 	caller->might_sleep |= callee->might_sleep;
17361 }
17362 
17363 /* non-recursive DFS pseudo code
17364  * 1  procedure DFS-iterative(G,v):
17365  * 2      label v as discovered
17366  * 3      let S be a stack
17367  * 4      S.push(v)
17368  * 5      while S is not empty
17369  * 6            t <- S.peek()
17370  * 7            if t is what we're looking for:
17371  * 8                return t
17372  * 9            for all edges e in G.adjacentEdges(t) do
17373  * 10               if edge e is already labelled
17374  * 11                   continue with the next edge
17375  * 12               w <- G.adjacentVertex(t,e)
17376  * 13               if vertex w is not discovered and not explored
17377  * 14                   label e as tree-edge
17378  * 15                   label w as discovered
17379  * 16                   S.push(w)
17380  * 17                   continue at 5
17381  * 18               else if vertex w is discovered
17382  * 19                   label e as back-edge
17383  * 20               else
17384  * 21                   // vertex w is explored
17385  * 22                   label e as forward- or cross-edge
17386  * 23           label t as explored
17387  * 24           S.pop()
17388  *
17389  * convention:
17390  * 0x10 - discovered
17391  * 0x11 - discovered and fall-through edge labelled
17392  * 0x12 - discovered and fall-through and branch edges labelled
17393  * 0x20 - explored
17394  */
17395 
17396 enum {
17397 	DISCOVERED = 0x10,
17398 	EXPLORED = 0x20,
17399 	FALLTHROUGH = 1,
17400 	BRANCH = 2,
17401 };
17402 
mark_prune_point(struct bpf_verifier_env * env,int idx)17403 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17404 {
17405 	env->insn_aux_data[idx].prune_point = true;
17406 }
17407 
is_prune_point(struct bpf_verifier_env * env,int insn_idx)17408 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17409 {
17410 	return env->insn_aux_data[insn_idx].prune_point;
17411 }
17412 
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)17413 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17414 {
17415 	env->insn_aux_data[idx].force_checkpoint = true;
17416 }
17417 
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)17418 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17419 {
17420 	return env->insn_aux_data[insn_idx].force_checkpoint;
17421 }
17422 
mark_calls_callback(struct bpf_verifier_env * env,int idx)17423 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17424 {
17425 	env->insn_aux_data[idx].calls_callback = true;
17426 }
17427 
bpf_calls_callback(struct bpf_verifier_env * env,int insn_idx)17428 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17429 {
17430 	return env->insn_aux_data[insn_idx].calls_callback;
17431 }
17432 
17433 enum {
17434 	DONE_EXPLORING = 0,
17435 	KEEP_EXPLORING = 1,
17436 };
17437 
17438 /* t, w, e - match pseudo-code above:
17439  * t - index of current instruction
17440  * w - next instruction
17441  * e - edge
17442  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)17443 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17444 {
17445 	int *insn_stack = env->cfg.insn_stack;
17446 	int *insn_state = env->cfg.insn_state;
17447 
17448 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17449 		return DONE_EXPLORING;
17450 
17451 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17452 		return DONE_EXPLORING;
17453 
17454 	if (w < 0 || w >= env->prog->len) {
17455 		verbose_linfo(env, t, "%d: ", t);
17456 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
17457 		return -EINVAL;
17458 	}
17459 
17460 	if (e == BRANCH) {
17461 		/* mark branch target for state pruning */
17462 		mark_prune_point(env, w);
17463 		mark_jmp_point(env, w);
17464 	}
17465 
17466 	if (insn_state[w] == 0) {
17467 		/* tree-edge */
17468 		insn_state[t] = DISCOVERED | e;
17469 		insn_state[w] = DISCOVERED;
17470 		if (env->cfg.cur_stack >= env->prog->len)
17471 			return -E2BIG;
17472 		insn_stack[env->cfg.cur_stack++] = w;
17473 		return KEEP_EXPLORING;
17474 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17475 		if (env->bpf_capable)
17476 			return DONE_EXPLORING;
17477 		verbose_linfo(env, t, "%d: ", t);
17478 		verbose_linfo(env, w, "%d: ", w);
17479 		verbose(env, "back-edge from insn %d to %d\n", t, w);
17480 		return -EINVAL;
17481 	} else if (insn_state[w] == EXPLORED) {
17482 		/* forward- or cross-edge */
17483 		insn_state[t] = DISCOVERED | e;
17484 	} else {
17485 		verifier_bug(env, "insn state internal bug");
17486 		return -EFAULT;
17487 	}
17488 	return DONE_EXPLORING;
17489 }
17490 
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)17491 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17492 				struct bpf_verifier_env *env,
17493 				bool visit_callee)
17494 {
17495 	int ret, insn_sz;
17496 	int w;
17497 
17498 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17499 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17500 	if (ret)
17501 		return ret;
17502 
17503 	mark_prune_point(env, t + insn_sz);
17504 	/* when we exit from subprog, we need to record non-linear history */
17505 	mark_jmp_point(env, t + insn_sz);
17506 
17507 	if (visit_callee) {
17508 		w = t + insns[t].imm + 1;
17509 		mark_prune_point(env, t);
17510 		merge_callee_effects(env, t, w);
17511 		ret = push_insn(t, w, BRANCH, env);
17512 	}
17513 	return ret;
17514 }
17515 
17516 /* Bitmask with 1s for all caller saved registers */
17517 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17518 
17519 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17520  * replacement patch is presumed to follow bpf_fastcall contract
17521  * (see mark_fastcall_pattern_for_call() below).
17522  */
verifier_inlines_helper_call(struct bpf_verifier_env * env,s32 imm)17523 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17524 {
17525 	switch (imm) {
17526 #ifdef CONFIG_X86_64
17527 	case BPF_FUNC_get_smp_processor_id:
17528 		return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17529 #endif
17530 	default:
17531 		return false;
17532 	}
17533 }
17534 
17535 struct call_summary {
17536 	u8 num_params;
17537 	bool is_void;
17538 	bool fastcall;
17539 };
17540 
17541 /* If @call is a kfunc or helper call, fills @cs and returns true,
17542  * otherwise returns false.
17543  */
get_call_summary(struct bpf_verifier_env * env,struct bpf_insn * call,struct call_summary * cs)17544 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17545 			     struct call_summary *cs)
17546 {
17547 	struct bpf_kfunc_call_arg_meta meta;
17548 	const struct bpf_func_proto *fn;
17549 	int i;
17550 
17551 	if (bpf_helper_call(call)) {
17552 
17553 		if (get_helper_proto(env, call->imm, &fn) < 0)
17554 			/* error would be reported later */
17555 			return false;
17556 		cs->fastcall = fn->allow_fastcall &&
17557 			       (verifier_inlines_helper_call(env, call->imm) ||
17558 				bpf_jit_inlines_helper_call(call->imm));
17559 		cs->is_void = fn->ret_type == RET_VOID;
17560 		cs->num_params = 0;
17561 		for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17562 			if (fn->arg_type[i] == ARG_DONTCARE)
17563 				break;
17564 			cs->num_params++;
17565 		}
17566 		return true;
17567 	}
17568 
17569 	if (bpf_pseudo_kfunc_call(call)) {
17570 		int err;
17571 
17572 		err = fetch_kfunc_meta(env, call, &meta, NULL);
17573 		if (err < 0)
17574 			/* error would be reported later */
17575 			return false;
17576 		cs->num_params = btf_type_vlen(meta.func_proto);
17577 		cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17578 		cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17579 		return true;
17580 	}
17581 
17582 	return false;
17583 }
17584 
17585 /* LLVM define a bpf_fastcall function attribute.
17586  * This attribute means that function scratches only some of
17587  * the caller saved registers defined by ABI.
17588  * For BPF the set of such registers could be defined as follows:
17589  * - R0 is scratched only if function is non-void;
17590  * - R1-R5 are scratched only if corresponding parameter type is defined
17591  *   in the function prototype.
17592  *
17593  * The contract between kernel and clang allows to simultaneously use
17594  * such functions and maintain backwards compatibility with old
17595  * kernels that don't understand bpf_fastcall calls:
17596  *
17597  * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17598  *   registers are not scratched by the call;
17599  *
17600  * - as a post-processing step, clang visits each bpf_fastcall call and adds
17601  *   spill/fill for every live r0-r5;
17602  *
17603  * - stack offsets used for the spill/fill are allocated as lowest
17604  *   stack offsets in whole function and are not used for any other
17605  *   purposes;
17606  *
17607  * - when kernel loads a program, it looks for such patterns
17608  *   (bpf_fastcall function surrounded by spills/fills) and checks if
17609  *   spill/fill stack offsets are used exclusively in fastcall patterns;
17610  *
17611  * - if so, and if verifier or current JIT inlines the call to the
17612  *   bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17613  *   spill/fill pairs;
17614  *
17615  * - when old kernel loads a program, presence of spill/fill pairs
17616  *   keeps BPF program valid, albeit slightly less efficient.
17617  *
17618  * For example:
17619  *
17620  *   r1 = 1;
17621  *   r2 = 2;
17622  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17623  *   *(u64 *)(r10 - 16) = r2;            r2 = 2;
17624  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17625  *   r2 = *(u64 *)(r10 - 16);            r0 = r1;
17626  *   r1 = *(u64 *)(r10 - 8);             r0 += r2;
17627  *   r0 = r1;                            exit;
17628  *   r0 += r2;
17629  *   exit;
17630  *
17631  * The purpose of mark_fastcall_pattern_for_call is to:
17632  * - look for such patterns;
17633  * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17634  * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17635  * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17636  *   at which bpf_fastcall spill/fill stack slots start;
17637  * - update env->subprog_info[*]->keep_fastcall_stack.
17638  *
17639  * The .fastcall_pattern and .fastcall_stack_off are used by
17640  * check_fastcall_stack_contract() to check if every stack access to
17641  * fastcall spill/fill stack slot originates from spill/fill
17642  * instructions, members of fastcall patterns.
17643  *
17644  * If such condition holds true for a subprogram, fastcall patterns could
17645  * be rewritten by remove_fastcall_spills_fills().
17646  * Otherwise bpf_fastcall patterns are not changed in the subprogram
17647  * (code, presumably, generated by an older clang version).
17648  *
17649  * For example, it is *not* safe to remove spill/fill below:
17650  *
17651  *   r1 = 1;
17652  *   *(u64 *)(r10 - 8)  = r1;            r1 = 1;
17653  *   call %[to_be_inlined]         -->   call %[to_be_inlined]
17654  *   r1 = *(u64 *)(r10 - 8);             r0 = *(u64 *)(r10 - 8);  <---- wrong !!!
17655  *   r0 = *(u64 *)(r10 - 8);             r0 += r1;
17656  *   r0 += r1;                           exit;
17657  *   exit;
17658  */
mark_fastcall_pattern_for_call(struct bpf_verifier_env * env,struct bpf_subprog_info * subprog,int insn_idx,s16 lowest_off)17659 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17660 					   struct bpf_subprog_info *subprog,
17661 					   int insn_idx, s16 lowest_off)
17662 {
17663 	struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17664 	struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17665 	u32 clobbered_regs_mask;
17666 	struct call_summary cs;
17667 	u32 expected_regs_mask;
17668 	s16 off;
17669 	int i;
17670 
17671 	if (!get_call_summary(env, call, &cs))
17672 		return;
17673 
17674 	/* A bitmask specifying which caller saved registers are clobbered
17675 	 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17676 	 * bpf_fastcall contract:
17677 	 * - includes R0 if function is non-void;
17678 	 * - includes R1-R5 if corresponding parameter has is described
17679 	 *   in the function prototype.
17680 	 */
17681 	clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17682 	/* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17683 	expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17684 
17685 	/* match pairs of form:
17686 	 *
17687 	 * *(u64 *)(r10 - Y) = rX   (where Y % 8 == 0)
17688 	 * ...
17689 	 * call %[to_be_inlined]
17690 	 * ...
17691 	 * rX = *(u64 *)(r10 - Y)
17692 	 */
17693 	for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17694 		if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17695 			break;
17696 		stx = &insns[insn_idx - i];
17697 		ldx = &insns[insn_idx + i];
17698 		/* must be a stack spill/fill pair */
17699 		if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17700 		    ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17701 		    stx->dst_reg != BPF_REG_10 ||
17702 		    ldx->src_reg != BPF_REG_10)
17703 			break;
17704 		/* must be a spill/fill for the same reg */
17705 		if (stx->src_reg != ldx->dst_reg)
17706 			break;
17707 		/* must be one of the previously unseen registers */
17708 		if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17709 			break;
17710 		/* must be a spill/fill for the same expected offset,
17711 		 * no need to check offset alignment, BPF_DW stack access
17712 		 * is always 8-byte aligned.
17713 		 */
17714 		if (stx->off != off || ldx->off != off)
17715 			break;
17716 		expected_regs_mask &= ~BIT(stx->src_reg);
17717 		env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17718 		env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17719 	}
17720 	if (i == 1)
17721 		return;
17722 
17723 	/* Conditionally set 'fastcall_spills_num' to allow forward
17724 	 * compatibility when more helper functions are marked as
17725 	 * bpf_fastcall at compile time than current kernel supports, e.g:
17726 	 *
17727 	 *   1: *(u64 *)(r10 - 8) = r1
17728 	 *   2: call A                  ;; assume A is bpf_fastcall for current kernel
17729 	 *   3: r1 = *(u64 *)(r10 - 8)
17730 	 *   4: *(u64 *)(r10 - 8) = r1
17731 	 *   5: call B                  ;; assume B is not bpf_fastcall for current kernel
17732 	 *   6: r1 = *(u64 *)(r10 - 8)
17733 	 *
17734 	 * There is no need to block bpf_fastcall rewrite for such program.
17735 	 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17736 	 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17737 	 * does not remove spill/fill pair {4,6}.
17738 	 */
17739 	if (cs.fastcall)
17740 		env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17741 	else
17742 		subprog->keep_fastcall_stack = 1;
17743 	subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17744 }
17745 
mark_fastcall_patterns(struct bpf_verifier_env * env)17746 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17747 {
17748 	struct bpf_subprog_info *subprog = env->subprog_info;
17749 	struct bpf_insn *insn;
17750 	s16 lowest_off;
17751 	int s, i;
17752 
17753 	for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17754 		/* find lowest stack spill offset used in this subprog */
17755 		lowest_off = 0;
17756 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17757 			insn = env->prog->insnsi + i;
17758 			if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17759 			    insn->dst_reg != BPF_REG_10)
17760 				continue;
17761 			lowest_off = min(lowest_off, insn->off);
17762 		}
17763 		/* use this offset to find fastcall patterns */
17764 		for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17765 			insn = env->prog->insnsi + i;
17766 			if (insn->code != (BPF_JMP | BPF_CALL))
17767 				continue;
17768 			mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17769 		}
17770 	}
17771 	return 0;
17772 }
17773 
17774 /* Visits the instruction at index t and returns one of the following:
17775  *  < 0 - an error occurred
17776  *  DONE_EXPLORING - the instruction was fully explored
17777  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
17778  */
visit_insn(int t,struct bpf_verifier_env * env)17779 static int visit_insn(int t, struct bpf_verifier_env *env)
17780 {
17781 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
17782 	int ret, off, insn_sz;
17783 
17784 	if (bpf_pseudo_func(insn))
17785 		return visit_func_call_insn(t, insns, env, true);
17786 
17787 	/* All non-branch instructions have a single fall-through edge. */
17788 	if (BPF_CLASS(insn->code) != BPF_JMP &&
17789 	    BPF_CLASS(insn->code) != BPF_JMP32) {
17790 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
17791 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
17792 	}
17793 
17794 	switch (BPF_OP(insn->code)) {
17795 	case BPF_EXIT:
17796 		return DONE_EXPLORING;
17797 
17798 	case BPF_CALL:
17799 		if (is_async_callback_calling_insn(insn))
17800 			/* Mark this call insn as a prune point to trigger
17801 			 * is_state_visited() check before call itself is
17802 			 * processed by __check_func_call(). Otherwise new
17803 			 * async state will be pushed for further exploration.
17804 			 */
17805 			mark_prune_point(env, t);
17806 		/* For functions that invoke callbacks it is not known how many times
17807 		 * callback would be called. Verifier models callback calling functions
17808 		 * by repeatedly visiting callback bodies and returning to origin call
17809 		 * instruction.
17810 		 * In order to stop such iteration verifier needs to identify when a
17811 		 * state identical some state from a previous iteration is reached.
17812 		 * Check below forces creation of checkpoint before callback calling
17813 		 * instruction to allow search for such identical states.
17814 		 */
17815 		if (is_sync_callback_calling_insn(insn)) {
17816 			mark_calls_callback(env, t);
17817 			mark_force_checkpoint(env, t);
17818 			mark_prune_point(env, t);
17819 			mark_jmp_point(env, t);
17820 		}
17821 		if (bpf_helper_call(insn)) {
17822 			const struct bpf_func_proto *fp;
17823 
17824 			ret = get_helper_proto(env, insn->imm, &fp);
17825 			/* If called in a non-sleepable context program will be
17826 			 * rejected anyway, so we should end up with precise
17827 			 * sleepable marks on subprogs, except for dead code
17828 			 * elimination.
17829 			 */
17830 			if (ret == 0 && fp->might_sleep)
17831 				mark_subprog_might_sleep(env, t);
17832 			if (bpf_helper_changes_pkt_data(insn->imm))
17833 				mark_subprog_changes_pkt_data(env, t);
17834 		} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17835 			struct bpf_kfunc_call_arg_meta meta;
17836 
17837 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
17838 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
17839 				mark_prune_point(env, t);
17840 				/* Checking and saving state checkpoints at iter_next() call
17841 				 * is crucial for fast convergence of open-coded iterator loop
17842 				 * logic, so we need to force it. If we don't do that,
17843 				 * is_state_visited() might skip saving a checkpoint, causing
17844 				 * unnecessarily long sequence of not checkpointed
17845 				 * instructions and jumps, leading to exhaustion of jump
17846 				 * history buffer, and potentially other undesired outcomes.
17847 				 * It is expected that with correct open-coded iterators
17848 				 * convergence will happen quickly, so we don't run a risk of
17849 				 * exhausting memory.
17850 				 */
17851 				mark_force_checkpoint(env, t);
17852 			}
17853 			/* Same as helpers, if called in a non-sleepable context
17854 			 * program will be rejected anyway, so we should end up
17855 			 * with precise sleepable marks on subprogs, except for
17856 			 * dead code elimination.
17857 			 */
17858 			if (ret == 0 && is_kfunc_sleepable(&meta))
17859 				mark_subprog_might_sleep(env, t);
17860 			if (ret == 0 && is_kfunc_pkt_changing(&meta))
17861 				mark_subprog_changes_pkt_data(env, t);
17862 		}
17863 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
17864 
17865 	case BPF_JA:
17866 		if (BPF_SRC(insn->code) != BPF_K)
17867 			return -EINVAL;
17868 
17869 		if (BPF_CLASS(insn->code) == BPF_JMP)
17870 			off = insn->off;
17871 		else
17872 			off = insn->imm;
17873 
17874 		/* unconditional jump with single edge */
17875 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
17876 		if (ret)
17877 			return ret;
17878 
17879 		mark_prune_point(env, t + off + 1);
17880 		mark_jmp_point(env, t + off + 1);
17881 
17882 		return ret;
17883 
17884 	default:
17885 		/* conditional jump with two edges */
17886 		mark_prune_point(env, t);
17887 		if (is_may_goto_insn(insn))
17888 			mark_force_checkpoint(env, t);
17889 
17890 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
17891 		if (ret)
17892 			return ret;
17893 
17894 		return push_insn(t, t + insn->off + 1, BRANCH, env);
17895 	}
17896 }
17897 
17898 /* non-recursive depth-first-search to detect loops in BPF program
17899  * loop == back-edge in directed graph
17900  */
check_cfg(struct bpf_verifier_env * env)17901 static int check_cfg(struct bpf_verifier_env *env)
17902 {
17903 	int insn_cnt = env->prog->len;
17904 	int *insn_stack, *insn_state;
17905 	int ex_insn_beg, i, ret = 0;
17906 
17907 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17908 	if (!insn_state)
17909 		return -ENOMEM;
17910 
17911 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
17912 	if (!insn_stack) {
17913 		kvfree(insn_state);
17914 		return -ENOMEM;
17915 	}
17916 
17917 	ex_insn_beg = env->exception_callback_subprog
17918 		      ? env->subprog_info[env->exception_callback_subprog].start
17919 		      : 0;
17920 
17921 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
17922 	insn_stack[0] = 0; /* 0 is the first instruction */
17923 	env->cfg.cur_stack = 1;
17924 
17925 walk_cfg:
17926 	while (env->cfg.cur_stack > 0) {
17927 		int t = insn_stack[env->cfg.cur_stack - 1];
17928 
17929 		ret = visit_insn(t, env);
17930 		switch (ret) {
17931 		case DONE_EXPLORING:
17932 			insn_state[t] = EXPLORED;
17933 			env->cfg.cur_stack--;
17934 			break;
17935 		case KEEP_EXPLORING:
17936 			break;
17937 		default:
17938 			if (ret > 0) {
17939 				verifier_bug(env, "visit_insn internal bug");
17940 				ret = -EFAULT;
17941 			}
17942 			goto err_free;
17943 		}
17944 	}
17945 
17946 	if (env->cfg.cur_stack < 0) {
17947 		verifier_bug(env, "pop stack internal bug");
17948 		ret = -EFAULT;
17949 		goto err_free;
17950 	}
17951 
17952 	if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
17953 		insn_state[ex_insn_beg] = DISCOVERED;
17954 		insn_stack[0] = ex_insn_beg;
17955 		env->cfg.cur_stack = 1;
17956 		goto walk_cfg;
17957 	}
17958 
17959 	for (i = 0; i < insn_cnt; i++) {
17960 		struct bpf_insn *insn = &env->prog->insnsi[i];
17961 
17962 		if (insn_state[i] != EXPLORED) {
17963 			verbose(env, "unreachable insn %d\n", i);
17964 			ret = -EINVAL;
17965 			goto err_free;
17966 		}
17967 		if (bpf_is_ldimm64(insn)) {
17968 			if (insn_state[i + 1] != 0) {
17969 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
17970 				ret = -EINVAL;
17971 				goto err_free;
17972 			}
17973 			i++; /* skip second half of ldimm64 */
17974 		}
17975 	}
17976 	ret = 0; /* cfg looks good */
17977 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
17978 	env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
17979 
17980 err_free:
17981 	kvfree(insn_state);
17982 	kvfree(insn_stack);
17983 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
17984 	return ret;
17985 }
17986 
17987 /*
17988  * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
17989  * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
17990  * with indices of 'i' instructions in postorder.
17991  */
compute_postorder(struct bpf_verifier_env * env)17992 static int compute_postorder(struct bpf_verifier_env *env)
17993 {
17994 	u32 cur_postorder, i, top, stack_sz, s, succ_cnt, succ[2];
17995 	int *stack = NULL, *postorder = NULL, *state = NULL;
17996 
17997 	postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17998 	state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
17999 	stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18000 	if (!postorder || !state || !stack) {
18001 		kvfree(postorder);
18002 		kvfree(state);
18003 		kvfree(stack);
18004 		return -ENOMEM;
18005 	}
18006 	cur_postorder = 0;
18007 	for (i = 0; i < env->subprog_cnt; i++) {
18008 		env->subprog_info[i].postorder_start = cur_postorder;
18009 		stack[0] = env->subprog_info[i].start;
18010 		stack_sz = 1;
18011 		do {
18012 			top = stack[stack_sz - 1];
18013 			state[top] |= DISCOVERED;
18014 			if (state[top] & EXPLORED) {
18015 				postorder[cur_postorder++] = top;
18016 				stack_sz--;
18017 				continue;
18018 			}
18019 			succ_cnt = bpf_insn_successors(env->prog, top, succ);
18020 			for (s = 0; s < succ_cnt; ++s) {
18021 				if (!state[succ[s]]) {
18022 					stack[stack_sz++] = succ[s];
18023 					state[succ[s]] |= DISCOVERED;
18024 				}
18025 			}
18026 			state[top] |= EXPLORED;
18027 		} while (stack_sz);
18028 	}
18029 	env->subprog_info[i].postorder_start = cur_postorder;
18030 	env->cfg.insn_postorder = postorder;
18031 	env->cfg.cur_postorder = cur_postorder;
18032 	kvfree(stack);
18033 	kvfree(state);
18034 	return 0;
18035 }
18036 
check_abnormal_return(struct bpf_verifier_env * env)18037 static int check_abnormal_return(struct bpf_verifier_env *env)
18038 {
18039 	int i;
18040 
18041 	for (i = 1; i < env->subprog_cnt; i++) {
18042 		if (env->subprog_info[i].has_ld_abs) {
18043 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18044 			return -EINVAL;
18045 		}
18046 		if (env->subprog_info[i].has_tail_call) {
18047 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18048 			return -EINVAL;
18049 		}
18050 	}
18051 	return 0;
18052 }
18053 
18054 /* The minimum supported BTF func info size */
18055 #define MIN_BPF_FUNCINFO_SIZE	8
18056 #define MAX_FUNCINFO_REC_SIZE	252
18057 
check_btf_func_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18058 static int check_btf_func_early(struct bpf_verifier_env *env,
18059 				const union bpf_attr *attr,
18060 				bpfptr_t uattr)
18061 {
18062 	u32 krec_size = sizeof(struct bpf_func_info);
18063 	const struct btf_type *type, *func_proto;
18064 	u32 i, nfuncs, urec_size, min_size;
18065 	struct bpf_func_info *krecord;
18066 	struct bpf_prog *prog;
18067 	const struct btf *btf;
18068 	u32 prev_offset = 0;
18069 	bpfptr_t urecord;
18070 	int ret = -ENOMEM;
18071 
18072 	nfuncs = attr->func_info_cnt;
18073 	if (!nfuncs) {
18074 		if (check_abnormal_return(env))
18075 			return -EINVAL;
18076 		return 0;
18077 	}
18078 
18079 	urec_size = attr->func_info_rec_size;
18080 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18081 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
18082 	    urec_size % sizeof(u32)) {
18083 		verbose(env, "invalid func info rec size %u\n", urec_size);
18084 		return -EINVAL;
18085 	}
18086 
18087 	prog = env->prog;
18088 	btf = prog->aux->btf;
18089 
18090 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18091 	min_size = min_t(u32, krec_size, urec_size);
18092 
18093 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18094 	if (!krecord)
18095 		return -ENOMEM;
18096 
18097 	for (i = 0; i < nfuncs; i++) {
18098 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18099 		if (ret) {
18100 			if (ret == -E2BIG) {
18101 				verbose(env, "nonzero tailing record in func info");
18102 				/* set the size kernel expects so loader can zero
18103 				 * out the rest of the record.
18104 				 */
18105 				if (copy_to_bpfptr_offset(uattr,
18106 							  offsetof(union bpf_attr, func_info_rec_size),
18107 							  &min_size, sizeof(min_size)))
18108 					ret = -EFAULT;
18109 			}
18110 			goto err_free;
18111 		}
18112 
18113 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18114 			ret = -EFAULT;
18115 			goto err_free;
18116 		}
18117 
18118 		/* check insn_off */
18119 		ret = -EINVAL;
18120 		if (i == 0) {
18121 			if (krecord[i].insn_off) {
18122 				verbose(env,
18123 					"nonzero insn_off %u for the first func info record",
18124 					krecord[i].insn_off);
18125 				goto err_free;
18126 			}
18127 		} else if (krecord[i].insn_off <= prev_offset) {
18128 			verbose(env,
18129 				"same or smaller insn offset (%u) than previous func info record (%u)",
18130 				krecord[i].insn_off, prev_offset);
18131 			goto err_free;
18132 		}
18133 
18134 		/* check type_id */
18135 		type = btf_type_by_id(btf, krecord[i].type_id);
18136 		if (!type || !btf_type_is_func(type)) {
18137 			verbose(env, "invalid type id %d in func info",
18138 				krecord[i].type_id);
18139 			goto err_free;
18140 		}
18141 
18142 		func_proto = btf_type_by_id(btf, type->type);
18143 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18144 			/* btf_func_check() already verified it during BTF load */
18145 			goto err_free;
18146 
18147 		prev_offset = krecord[i].insn_off;
18148 		bpfptr_add(&urecord, urec_size);
18149 	}
18150 
18151 	prog->aux->func_info = krecord;
18152 	prog->aux->func_info_cnt = nfuncs;
18153 	return 0;
18154 
18155 err_free:
18156 	kvfree(krecord);
18157 	return ret;
18158 }
18159 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18160 static int check_btf_func(struct bpf_verifier_env *env,
18161 			  const union bpf_attr *attr,
18162 			  bpfptr_t uattr)
18163 {
18164 	const struct btf_type *type, *func_proto, *ret_type;
18165 	u32 i, nfuncs, urec_size;
18166 	struct bpf_func_info *krecord;
18167 	struct bpf_func_info_aux *info_aux = NULL;
18168 	struct bpf_prog *prog;
18169 	const struct btf *btf;
18170 	bpfptr_t urecord;
18171 	bool scalar_return;
18172 	int ret = -ENOMEM;
18173 
18174 	nfuncs = attr->func_info_cnt;
18175 	if (!nfuncs) {
18176 		if (check_abnormal_return(env))
18177 			return -EINVAL;
18178 		return 0;
18179 	}
18180 	if (nfuncs != env->subprog_cnt) {
18181 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18182 		return -EINVAL;
18183 	}
18184 
18185 	urec_size = attr->func_info_rec_size;
18186 
18187 	prog = env->prog;
18188 	btf = prog->aux->btf;
18189 
18190 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18191 
18192 	krecord = prog->aux->func_info;
18193 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18194 	if (!info_aux)
18195 		return -ENOMEM;
18196 
18197 	for (i = 0; i < nfuncs; i++) {
18198 		/* check insn_off */
18199 		ret = -EINVAL;
18200 
18201 		if (env->subprog_info[i].start != krecord[i].insn_off) {
18202 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18203 			goto err_free;
18204 		}
18205 
18206 		/* Already checked type_id */
18207 		type = btf_type_by_id(btf, krecord[i].type_id);
18208 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18209 		/* Already checked func_proto */
18210 		func_proto = btf_type_by_id(btf, type->type);
18211 
18212 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18213 		scalar_return =
18214 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18215 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18216 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18217 			goto err_free;
18218 		}
18219 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18220 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18221 			goto err_free;
18222 		}
18223 
18224 		bpfptr_add(&urecord, urec_size);
18225 	}
18226 
18227 	prog->aux->func_info_aux = info_aux;
18228 	return 0;
18229 
18230 err_free:
18231 	kfree(info_aux);
18232 	return ret;
18233 }
18234 
adjust_btf_func(struct bpf_verifier_env * env)18235 static void adjust_btf_func(struct bpf_verifier_env *env)
18236 {
18237 	struct bpf_prog_aux *aux = env->prog->aux;
18238 	int i;
18239 
18240 	if (!aux->func_info)
18241 		return;
18242 
18243 	/* func_info is not available for hidden subprogs */
18244 	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18245 		aux->func_info[i].insn_off = env->subprog_info[i].start;
18246 }
18247 
18248 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
18249 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
18250 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18251 static int check_btf_line(struct bpf_verifier_env *env,
18252 			  const union bpf_attr *attr,
18253 			  bpfptr_t uattr)
18254 {
18255 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18256 	struct bpf_subprog_info *sub;
18257 	struct bpf_line_info *linfo;
18258 	struct bpf_prog *prog;
18259 	const struct btf *btf;
18260 	bpfptr_t ulinfo;
18261 	int err;
18262 
18263 	nr_linfo = attr->line_info_cnt;
18264 	if (!nr_linfo)
18265 		return 0;
18266 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18267 		return -EINVAL;
18268 
18269 	rec_size = attr->line_info_rec_size;
18270 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18271 	    rec_size > MAX_LINEINFO_REC_SIZE ||
18272 	    rec_size & (sizeof(u32) - 1))
18273 		return -EINVAL;
18274 
18275 	/* Need to zero it in case the userspace may
18276 	 * pass in a smaller bpf_line_info object.
18277 	 */
18278 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18279 			 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18280 	if (!linfo)
18281 		return -ENOMEM;
18282 
18283 	prog = env->prog;
18284 	btf = prog->aux->btf;
18285 
18286 	s = 0;
18287 	sub = env->subprog_info;
18288 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18289 	expected_size = sizeof(struct bpf_line_info);
18290 	ncopy = min_t(u32, expected_size, rec_size);
18291 	for (i = 0; i < nr_linfo; i++) {
18292 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18293 		if (err) {
18294 			if (err == -E2BIG) {
18295 				verbose(env, "nonzero tailing record in line_info");
18296 				if (copy_to_bpfptr_offset(uattr,
18297 							  offsetof(union bpf_attr, line_info_rec_size),
18298 							  &expected_size, sizeof(expected_size)))
18299 					err = -EFAULT;
18300 			}
18301 			goto err_free;
18302 		}
18303 
18304 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18305 			err = -EFAULT;
18306 			goto err_free;
18307 		}
18308 
18309 		/*
18310 		 * Check insn_off to ensure
18311 		 * 1) strictly increasing AND
18312 		 * 2) bounded by prog->len
18313 		 *
18314 		 * The linfo[0].insn_off == 0 check logically falls into
18315 		 * the later "missing bpf_line_info for func..." case
18316 		 * because the first linfo[0].insn_off must be the
18317 		 * first sub also and the first sub must have
18318 		 * subprog_info[0].start == 0.
18319 		 */
18320 		if ((i && linfo[i].insn_off <= prev_offset) ||
18321 		    linfo[i].insn_off >= prog->len) {
18322 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18323 				i, linfo[i].insn_off, prev_offset,
18324 				prog->len);
18325 			err = -EINVAL;
18326 			goto err_free;
18327 		}
18328 
18329 		if (!prog->insnsi[linfo[i].insn_off].code) {
18330 			verbose(env,
18331 				"Invalid insn code at line_info[%u].insn_off\n",
18332 				i);
18333 			err = -EINVAL;
18334 			goto err_free;
18335 		}
18336 
18337 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18338 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18339 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18340 			err = -EINVAL;
18341 			goto err_free;
18342 		}
18343 
18344 		if (s != env->subprog_cnt) {
18345 			if (linfo[i].insn_off == sub[s].start) {
18346 				sub[s].linfo_idx = i;
18347 				s++;
18348 			} else if (sub[s].start < linfo[i].insn_off) {
18349 				verbose(env, "missing bpf_line_info for func#%u\n", s);
18350 				err = -EINVAL;
18351 				goto err_free;
18352 			}
18353 		}
18354 
18355 		prev_offset = linfo[i].insn_off;
18356 		bpfptr_add(&ulinfo, rec_size);
18357 	}
18358 
18359 	if (s != env->subprog_cnt) {
18360 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18361 			env->subprog_cnt - s, s);
18362 		err = -EINVAL;
18363 		goto err_free;
18364 	}
18365 
18366 	prog->aux->linfo = linfo;
18367 	prog->aux->nr_linfo = nr_linfo;
18368 
18369 	return 0;
18370 
18371 err_free:
18372 	kvfree(linfo);
18373 	return err;
18374 }
18375 
18376 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
18377 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
18378 
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18379 static int check_core_relo(struct bpf_verifier_env *env,
18380 			   const union bpf_attr *attr,
18381 			   bpfptr_t uattr)
18382 {
18383 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18384 	struct bpf_core_relo core_relo = {};
18385 	struct bpf_prog *prog = env->prog;
18386 	const struct btf *btf = prog->aux->btf;
18387 	struct bpf_core_ctx ctx = {
18388 		.log = &env->log,
18389 		.btf = btf,
18390 	};
18391 	bpfptr_t u_core_relo;
18392 	int err;
18393 
18394 	nr_core_relo = attr->core_relo_cnt;
18395 	if (!nr_core_relo)
18396 		return 0;
18397 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18398 		return -EINVAL;
18399 
18400 	rec_size = attr->core_relo_rec_size;
18401 	if (rec_size < MIN_CORE_RELO_SIZE ||
18402 	    rec_size > MAX_CORE_RELO_SIZE ||
18403 	    rec_size % sizeof(u32))
18404 		return -EINVAL;
18405 
18406 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18407 	expected_size = sizeof(struct bpf_core_relo);
18408 	ncopy = min_t(u32, expected_size, rec_size);
18409 
18410 	/* Unlike func_info and line_info, copy and apply each CO-RE
18411 	 * relocation record one at a time.
18412 	 */
18413 	for (i = 0; i < nr_core_relo; i++) {
18414 		/* future proofing when sizeof(bpf_core_relo) changes */
18415 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18416 		if (err) {
18417 			if (err == -E2BIG) {
18418 				verbose(env, "nonzero tailing record in core_relo");
18419 				if (copy_to_bpfptr_offset(uattr,
18420 							  offsetof(union bpf_attr, core_relo_rec_size),
18421 							  &expected_size, sizeof(expected_size)))
18422 					err = -EFAULT;
18423 			}
18424 			break;
18425 		}
18426 
18427 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18428 			err = -EFAULT;
18429 			break;
18430 		}
18431 
18432 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18433 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18434 				i, core_relo.insn_off, prog->len);
18435 			err = -EINVAL;
18436 			break;
18437 		}
18438 
18439 		err = bpf_core_apply(&ctx, &core_relo, i,
18440 				     &prog->insnsi[core_relo.insn_off / 8]);
18441 		if (err)
18442 			break;
18443 		bpfptr_add(&u_core_relo, rec_size);
18444 	}
18445 	return err;
18446 }
18447 
check_btf_info_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18448 static int check_btf_info_early(struct bpf_verifier_env *env,
18449 				const union bpf_attr *attr,
18450 				bpfptr_t uattr)
18451 {
18452 	struct btf *btf;
18453 	int err;
18454 
18455 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18456 		if (check_abnormal_return(env))
18457 			return -EINVAL;
18458 		return 0;
18459 	}
18460 
18461 	btf = btf_get_by_fd(attr->prog_btf_fd);
18462 	if (IS_ERR(btf))
18463 		return PTR_ERR(btf);
18464 	if (btf_is_kernel(btf)) {
18465 		btf_put(btf);
18466 		return -EACCES;
18467 	}
18468 	env->prog->aux->btf = btf;
18469 
18470 	err = check_btf_func_early(env, attr, uattr);
18471 	if (err)
18472 		return err;
18473 	return 0;
18474 }
18475 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18476 static int check_btf_info(struct bpf_verifier_env *env,
18477 			  const union bpf_attr *attr,
18478 			  bpfptr_t uattr)
18479 {
18480 	int err;
18481 
18482 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
18483 		if (check_abnormal_return(env))
18484 			return -EINVAL;
18485 		return 0;
18486 	}
18487 
18488 	err = check_btf_func(env, attr, uattr);
18489 	if (err)
18490 		return err;
18491 
18492 	err = check_btf_line(env, attr, uattr);
18493 	if (err)
18494 		return err;
18495 
18496 	err = check_core_relo(env, attr, uattr);
18497 	if (err)
18498 		return err;
18499 
18500 	return 0;
18501 }
18502 
18503 /* check %cur's range satisfies %old's */
range_within(const struct bpf_reg_state * old,const struct bpf_reg_state * cur)18504 static bool range_within(const struct bpf_reg_state *old,
18505 			 const struct bpf_reg_state *cur)
18506 {
18507 	return old->umin_value <= cur->umin_value &&
18508 	       old->umax_value >= cur->umax_value &&
18509 	       old->smin_value <= cur->smin_value &&
18510 	       old->smax_value >= cur->smax_value &&
18511 	       old->u32_min_value <= cur->u32_min_value &&
18512 	       old->u32_max_value >= cur->u32_max_value &&
18513 	       old->s32_min_value <= cur->s32_min_value &&
18514 	       old->s32_max_value >= cur->s32_max_value;
18515 }
18516 
18517 /* If in the old state two registers had the same id, then they need to have
18518  * the same id in the new state as well.  But that id could be different from
18519  * the old state, so we need to track the mapping from old to new ids.
18520  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18521  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
18522  * regs with a different old id could still have new id 9, we don't care about
18523  * that.
18524  * So we look through our idmap to see if this old id has been seen before.  If
18525  * so, we require the new id to match; otherwise, we add the id pair to the map.
18526  */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18527 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18528 {
18529 	struct bpf_id_pair *map = idmap->map;
18530 	unsigned int i;
18531 
18532 	/* either both IDs should be set or both should be zero */
18533 	if (!!old_id != !!cur_id)
18534 		return false;
18535 
18536 	if (old_id == 0) /* cur_id == 0 as well */
18537 		return true;
18538 
18539 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18540 		if (!map[i].old) {
18541 			/* Reached an empty slot; haven't seen this id before */
18542 			map[i].old = old_id;
18543 			map[i].cur = cur_id;
18544 			return true;
18545 		}
18546 		if (map[i].old == old_id)
18547 			return map[i].cur == cur_id;
18548 		if (map[i].cur == cur_id)
18549 			return false;
18550 	}
18551 	/* We ran out of idmap slots, which should be impossible */
18552 	WARN_ON_ONCE(1);
18553 	return false;
18554 }
18555 
18556 /* Similar to check_ids(), but allocate a unique temporary ID
18557  * for 'old_id' or 'cur_id' of zero.
18558  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18559  */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18560 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18561 {
18562 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18563 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18564 
18565 	return check_ids(old_id, cur_id, idmap);
18566 }
18567 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st,u32 ip)18568 static void clean_func_state(struct bpf_verifier_env *env,
18569 			     struct bpf_func_state *st,
18570 			     u32 ip)
18571 {
18572 	u16 live_regs = env->insn_aux_data[ip].live_regs_before;
18573 	int i, j;
18574 
18575 	for (i = 0; i < BPF_REG_FP; i++) {
18576 		/* liveness must not touch this register anymore */
18577 		if (!(live_regs & BIT(i)))
18578 			/* since the register is unused, clear its state
18579 			 * to make further comparison simpler
18580 			 */
18581 			__mark_reg_not_init(env, &st->regs[i]);
18582 	}
18583 
18584 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18585 		if (!bpf_stack_slot_alive(env, st->frameno, i)) {
18586 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18587 			for (j = 0; j < BPF_REG_SIZE; j++)
18588 				st->stack[i].slot_type[j] = STACK_INVALID;
18589 		}
18590 	}
18591 }
18592 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)18593 static void clean_verifier_state(struct bpf_verifier_env *env,
18594 				 struct bpf_verifier_state *st)
18595 {
18596 	int i, ip;
18597 
18598 	bpf_live_stack_query_init(env, st);
18599 	st->cleaned = true;
18600 	for (i = 0; i <= st->curframe; i++) {
18601 		ip = frame_insn_idx(st, i);
18602 		clean_func_state(env, st->frame[i], ip);
18603 	}
18604 }
18605 
18606 /* the parentage chains form a tree.
18607  * the verifier states are added to state lists at given insn and
18608  * pushed into state stack for future exploration.
18609  * when the verifier reaches bpf_exit insn some of the verifier states
18610  * stored in the state lists have their final liveness state already,
18611  * but a lot of states will get revised from liveness point of view when
18612  * the verifier explores other branches.
18613  * Example:
18614  * 1: *(u64)(r10 - 8) = 1
18615  * 2: if r1 == 100 goto pc+1
18616  * 3: *(u64)(r10 - 8) = 2
18617  * 4: r0 = *(u64)(r10 - 8)
18618  * 5: exit
18619  * when the verifier reaches exit insn the stack slot -8 in the state list of
18620  * insn 2 is not yet marked alive. Then the verifier pops the other_branch
18621  * of insn 2 and goes exploring further. After the insn 4 read, liveness
18622  * analysis would propagate read mark for -8 at insn 2.
18623  *
18624  * Since the verifier pushes the branch states as it sees them while exploring
18625  * the program the condition of walking the branch instruction for the second
18626  * time means that all states below this branch were already explored and
18627  * their final liveness marks are already propagated.
18628  * Hence when the verifier completes the search of state list in is_state_visited()
18629  * we can call this clean_live_states() function to clear dead the registers and stack
18630  * slots to simplify state merging.
18631  *
18632  * Important note here that walking the same branch instruction in the callee
18633  * doesn't meant that the states are DONE. The verifier has to compare
18634  * the callsites
18635  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)18636 static void clean_live_states(struct bpf_verifier_env *env, int insn,
18637 			      struct bpf_verifier_state *cur)
18638 {
18639 	struct bpf_verifier_state_list *sl;
18640 	struct list_head *pos, *head;
18641 
18642 	head = explored_state(env, insn);
18643 	list_for_each(pos, head) {
18644 		sl = container_of(pos, struct bpf_verifier_state_list, node);
18645 		if (sl->state.branches)
18646 			continue;
18647 		if (sl->state.insn_idx != insn ||
18648 		    !same_callsites(&sl->state, cur))
18649 			continue;
18650 		if (sl->state.cleaned)
18651 			/* all regs in this state in all frames were already marked */
18652 			continue;
18653 		if (incomplete_read_marks(env, &sl->state))
18654 			continue;
18655 		clean_verifier_state(env, &sl->state);
18656 	}
18657 }
18658 
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)18659 static bool regs_exact(const struct bpf_reg_state *rold,
18660 		       const struct bpf_reg_state *rcur,
18661 		       struct bpf_idmap *idmap)
18662 {
18663 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18664 	       check_ids(rold->id, rcur->id, idmap) &&
18665 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18666 }
18667 
18668 enum exact_level {
18669 	NOT_EXACT,
18670 	EXACT,
18671 	RANGE_WITHIN
18672 };
18673 
18674 /* 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)18675 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
18676 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
18677 		    enum exact_level exact)
18678 {
18679 	if (exact == EXACT)
18680 		return regs_exact(rold, rcur, idmap);
18681 
18682 	if (rold->type == NOT_INIT) {
18683 		if (exact == NOT_EXACT || rcur->type == NOT_INIT)
18684 			/* explored state can't have used this */
18685 			return true;
18686 	}
18687 
18688 	/* Enforce that register types have to match exactly, including their
18689 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
18690 	 * rule.
18691 	 *
18692 	 * One can make a point that using a pointer register as unbounded
18693 	 * SCALAR would be technically acceptable, but this could lead to
18694 	 * pointer leaks because scalars are allowed to leak while pointers
18695 	 * are not. We could make this safe in special cases if root is
18696 	 * calling us, but it's probably not worth the hassle.
18697 	 *
18698 	 * Also, register types that are *not* MAYBE_NULL could technically be
18699 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
18700 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
18701 	 * to the same map).
18702 	 * However, if the old MAYBE_NULL register then got NULL checked,
18703 	 * doing so could have affected others with the same id, and we can't
18704 	 * check for that because we lost the id when we converted to
18705 	 * a non-MAYBE_NULL variant.
18706 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
18707 	 * non-MAYBE_NULL registers as well.
18708 	 */
18709 	if (rold->type != rcur->type)
18710 		return false;
18711 
18712 	switch (base_type(rold->type)) {
18713 	case SCALAR_VALUE:
18714 		if (env->explore_alu_limits) {
18715 			/* explore_alu_limits disables tnum_in() and range_within()
18716 			 * logic and requires everything to be strict
18717 			 */
18718 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
18719 			       check_scalar_ids(rold->id, rcur->id, idmap);
18720 		}
18721 		if (!rold->precise && exact == NOT_EXACT)
18722 			return true;
18723 		if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
18724 			return false;
18725 		if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
18726 			return false;
18727 		/* Why check_ids() for scalar registers?
18728 		 *
18729 		 * Consider the following BPF code:
18730 		 *   1: r6 = ... unbound scalar, ID=a ...
18731 		 *   2: r7 = ... unbound scalar, ID=b ...
18732 		 *   3: if (r6 > r7) goto +1
18733 		 *   4: r6 = r7
18734 		 *   5: if (r6 > X) goto ...
18735 		 *   6: ... memory operation using r7 ...
18736 		 *
18737 		 * First verification path is [1-6]:
18738 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
18739 		 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
18740 		 *   r7 <= X, because r6 and r7 share same id.
18741 		 * Next verification path is [1-4, 6].
18742 		 *
18743 		 * Instruction (6) would be reached in two states:
18744 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
18745 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
18746 		 *
18747 		 * Use check_ids() to distinguish these states.
18748 		 * ---
18749 		 * Also verify that new value satisfies old value range knowledge.
18750 		 */
18751 		return range_within(rold, rcur) &&
18752 		       tnum_in(rold->var_off, rcur->var_off) &&
18753 		       check_scalar_ids(rold->id, rcur->id, idmap);
18754 	case PTR_TO_MAP_KEY:
18755 	case PTR_TO_MAP_VALUE:
18756 	case PTR_TO_MEM:
18757 	case PTR_TO_BUF:
18758 	case PTR_TO_TP_BUFFER:
18759 		/* If the new min/max/var_off satisfy the old ones and
18760 		 * everything else matches, we are OK.
18761 		 */
18762 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
18763 		       range_within(rold, rcur) &&
18764 		       tnum_in(rold->var_off, rcur->var_off) &&
18765 		       check_ids(rold->id, rcur->id, idmap) &&
18766 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
18767 	case PTR_TO_PACKET_META:
18768 	case PTR_TO_PACKET:
18769 		/* We must have at least as much range as the old ptr
18770 		 * did, so that any accesses which were safe before are
18771 		 * still safe.  This is true even if old range < old off,
18772 		 * since someone could have accessed through (ptr - k), or
18773 		 * even done ptr -= k in a register, to get a safe access.
18774 		 */
18775 		if (rold->range > rcur->range)
18776 			return false;
18777 		/* If the offsets don't match, we can't trust our alignment;
18778 		 * nor can we be sure that we won't fall out of range.
18779 		 */
18780 		if (rold->off != rcur->off)
18781 			return false;
18782 		/* id relations must be preserved */
18783 		if (!check_ids(rold->id, rcur->id, idmap))
18784 			return false;
18785 		/* new val must satisfy old val knowledge */
18786 		return range_within(rold, rcur) &&
18787 		       tnum_in(rold->var_off, rcur->var_off);
18788 	case PTR_TO_STACK:
18789 		/* two stack pointers are equal only if they're pointing to
18790 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
18791 		 */
18792 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
18793 	case PTR_TO_ARENA:
18794 		return true;
18795 	default:
18796 		return regs_exact(rold, rcur, idmap);
18797 	}
18798 }
18799 
18800 static struct bpf_reg_state unbound_reg;
18801 
unbound_reg_init(void)18802 static __init int unbound_reg_init(void)
18803 {
18804 	__mark_reg_unknown_imprecise(&unbound_reg);
18805 	return 0;
18806 }
18807 late_initcall(unbound_reg_init);
18808 
is_stack_all_misc(struct bpf_verifier_env * env,struct bpf_stack_state * stack)18809 static bool is_stack_all_misc(struct bpf_verifier_env *env,
18810 			      struct bpf_stack_state *stack)
18811 {
18812 	u32 i;
18813 
18814 	for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
18815 		if ((stack->slot_type[i] == STACK_MISC) ||
18816 		    (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
18817 			continue;
18818 		return false;
18819 	}
18820 
18821 	return true;
18822 }
18823 
scalar_reg_for_stack(struct bpf_verifier_env * env,struct bpf_stack_state * stack)18824 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
18825 						  struct bpf_stack_state *stack)
18826 {
18827 	if (is_spilled_scalar_reg64(stack))
18828 		return &stack->spilled_ptr;
18829 
18830 	if (is_stack_all_misc(env, stack))
18831 		return &unbound_reg;
18832 
18833 	return NULL;
18834 }
18835 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,enum exact_level exact)18836 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
18837 		      struct bpf_func_state *cur, struct bpf_idmap *idmap,
18838 		      enum exact_level exact)
18839 {
18840 	int i, spi;
18841 
18842 	/* walk slots of the explored stack and ignore any additional
18843 	 * slots in the current stack, since explored(safe) state
18844 	 * didn't use them
18845 	 */
18846 	for (i = 0; i < old->allocated_stack; i++) {
18847 		struct bpf_reg_state *old_reg, *cur_reg;
18848 
18849 		spi = i / BPF_REG_SIZE;
18850 
18851 		if (exact != NOT_EXACT &&
18852 		    (i >= cur->allocated_stack ||
18853 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18854 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
18855 			return false;
18856 
18857 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
18858 			continue;
18859 
18860 		if (env->allow_uninit_stack &&
18861 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
18862 			continue;
18863 
18864 		/* explored stack has more populated slots than current stack
18865 		 * and these slots were used
18866 		 */
18867 		if (i >= cur->allocated_stack)
18868 			return false;
18869 
18870 		/* 64-bit scalar spill vs all slots MISC and vice versa.
18871 		 * Load from all slots MISC produces unbound scalar.
18872 		 * Construct a fake register for such stack and call
18873 		 * regsafe() to ensure scalar ids are compared.
18874 		 */
18875 		old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
18876 		cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
18877 		if (old_reg && cur_reg) {
18878 			if (!regsafe(env, old_reg, cur_reg, idmap, exact))
18879 				return false;
18880 			i += BPF_REG_SIZE - 1;
18881 			continue;
18882 		}
18883 
18884 		/* if old state was safe with misc data in the stack
18885 		 * it will be safe with zero-initialized stack.
18886 		 * The opposite is not true
18887 		 */
18888 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
18889 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
18890 			continue;
18891 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
18892 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
18893 			/* Ex: old explored (safe) state has STACK_SPILL in
18894 			 * this stack slot, but current has STACK_MISC ->
18895 			 * this verifier states are not equivalent,
18896 			 * return false to continue verification of this path
18897 			 */
18898 			return false;
18899 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
18900 			continue;
18901 		/* Both old and cur are having same slot_type */
18902 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
18903 		case STACK_SPILL:
18904 			/* when explored and current stack slot are both storing
18905 			 * spilled registers, check that stored pointers types
18906 			 * are the same as well.
18907 			 * Ex: explored safe path could have stored
18908 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
18909 			 * but current path has stored:
18910 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
18911 			 * such verifier states are not equivalent.
18912 			 * return false to continue verification of this path
18913 			 */
18914 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
18915 				     &cur->stack[spi].spilled_ptr, idmap, exact))
18916 				return false;
18917 			break;
18918 		case STACK_DYNPTR:
18919 			old_reg = &old->stack[spi].spilled_ptr;
18920 			cur_reg = &cur->stack[spi].spilled_ptr;
18921 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
18922 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
18923 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18924 				return false;
18925 			break;
18926 		case STACK_ITER:
18927 			old_reg = &old->stack[spi].spilled_ptr;
18928 			cur_reg = &cur->stack[spi].spilled_ptr;
18929 			/* iter.depth is not compared between states as it
18930 			 * doesn't matter for correctness and would otherwise
18931 			 * prevent convergence; we maintain it only to prevent
18932 			 * infinite loop check triggering, see
18933 			 * iter_active_depths_differ()
18934 			 */
18935 			if (old_reg->iter.btf != cur_reg->iter.btf ||
18936 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
18937 			    old_reg->iter.state != cur_reg->iter.state ||
18938 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
18939 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
18940 				return false;
18941 			break;
18942 		case STACK_IRQ_FLAG:
18943 			old_reg = &old->stack[spi].spilled_ptr;
18944 			cur_reg = &cur->stack[spi].spilled_ptr;
18945 			if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
18946 			    old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
18947 				return false;
18948 			break;
18949 		case STACK_MISC:
18950 		case STACK_ZERO:
18951 		case STACK_INVALID:
18952 			continue;
18953 		/* Ensure that new unhandled slot types return false by default */
18954 		default:
18955 			return false;
18956 		}
18957 	}
18958 	return true;
18959 }
18960 
refsafe(struct bpf_verifier_state * old,struct bpf_verifier_state * cur,struct bpf_idmap * idmap)18961 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
18962 		    struct bpf_idmap *idmap)
18963 {
18964 	int i;
18965 
18966 	if (old->acquired_refs != cur->acquired_refs)
18967 		return false;
18968 
18969 	if (old->active_locks != cur->active_locks)
18970 		return false;
18971 
18972 	if (old->active_preempt_locks != cur->active_preempt_locks)
18973 		return false;
18974 
18975 	if (old->active_rcu_lock != cur->active_rcu_lock)
18976 		return false;
18977 
18978 	if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
18979 		return false;
18980 
18981 	if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
18982 	    old->active_lock_ptr != cur->active_lock_ptr)
18983 		return false;
18984 
18985 	for (i = 0; i < old->acquired_refs; i++) {
18986 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
18987 		    old->refs[i].type != cur->refs[i].type)
18988 			return false;
18989 		switch (old->refs[i].type) {
18990 		case REF_TYPE_PTR:
18991 		case REF_TYPE_IRQ:
18992 			break;
18993 		case REF_TYPE_LOCK:
18994 		case REF_TYPE_RES_LOCK:
18995 		case REF_TYPE_RES_LOCK_IRQ:
18996 			if (old->refs[i].ptr != cur->refs[i].ptr)
18997 				return false;
18998 			break;
18999 		default:
19000 			WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
19001 			return false;
19002 		}
19003 	}
19004 
19005 	return true;
19006 }
19007 
19008 /* compare two verifier states
19009  *
19010  * all states stored in state_list are known to be valid, since
19011  * verifier reached 'bpf_exit' instruction through them
19012  *
19013  * this function is called when verifier exploring different branches of
19014  * execution popped from the state stack. If it sees an old state that has
19015  * more strict register state and more strict stack state then this execution
19016  * branch doesn't need to be explored further, since verifier already
19017  * concluded that more strict state leads to valid finish.
19018  *
19019  * Therefore two states are equivalent if register state is more conservative
19020  * and explored stack state is more conservative than the current one.
19021  * Example:
19022  *       explored                   current
19023  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19024  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19025  *
19026  * In other words if current stack state (one being explored) has more
19027  * valid slots than old one that already passed validation, it means
19028  * the verifier can stop exploring and conclude that current state is valid too
19029  *
19030  * Similarly with registers. If explored state has register type as invalid
19031  * whereas register type in current state is meaningful, it means that
19032  * the current state will reach 'bpf_exit' instruction safely
19033  */
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)19034 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19035 			      struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19036 {
19037 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19038 	u16 i;
19039 
19040 	if (old->callback_depth > cur->callback_depth)
19041 		return false;
19042 
19043 	for (i = 0; i < MAX_BPF_REG; i++)
19044 		if (((1 << i) & live_regs) &&
19045 		    !regsafe(env, &old->regs[i], &cur->regs[i],
19046 			     &env->idmap_scratch, exact))
19047 			return false;
19048 
19049 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19050 		return false;
19051 
19052 	return true;
19053 }
19054 
reset_idmap_scratch(struct bpf_verifier_env * env)19055 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19056 {
19057 	env->idmap_scratch.tmp_id_gen = env->id_gen;
19058 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19059 }
19060 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,enum exact_level exact)19061 static bool states_equal(struct bpf_verifier_env *env,
19062 			 struct bpf_verifier_state *old,
19063 			 struct bpf_verifier_state *cur,
19064 			 enum exact_level exact)
19065 {
19066 	u32 insn_idx;
19067 	int i;
19068 
19069 	if (old->curframe != cur->curframe)
19070 		return false;
19071 
19072 	reset_idmap_scratch(env);
19073 
19074 	/* Verification state from speculative execution simulation
19075 	 * must never prune a non-speculative execution one.
19076 	 */
19077 	if (old->speculative && !cur->speculative)
19078 		return false;
19079 
19080 	if (old->in_sleepable != cur->in_sleepable)
19081 		return false;
19082 
19083 	if (!refsafe(old, cur, &env->idmap_scratch))
19084 		return false;
19085 
19086 	/* for states to be equal callsites have to be the same
19087 	 * and all frame states need to be equivalent
19088 	 */
19089 	for (i = 0; i <= old->curframe; i++) {
19090 		insn_idx = frame_insn_idx(old, i);
19091 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
19092 			return false;
19093 		if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19094 			return false;
19095 	}
19096 	return true;
19097 }
19098 
19099 /* find precise scalars in the previous equivalent state and
19100  * propagate them into the current state
19101  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool * changed)19102 static int propagate_precision(struct bpf_verifier_env *env,
19103 			       const struct bpf_verifier_state *old,
19104 			       struct bpf_verifier_state *cur,
19105 			       bool *changed)
19106 {
19107 	struct bpf_reg_state *state_reg;
19108 	struct bpf_func_state *state;
19109 	int i, err = 0, fr;
19110 	bool first;
19111 
19112 	for (fr = old->curframe; fr >= 0; fr--) {
19113 		state = old->frame[fr];
19114 		state_reg = state->regs;
19115 		first = true;
19116 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19117 			if (state_reg->type != SCALAR_VALUE ||
19118 			    !state_reg->precise)
19119 				continue;
19120 			if (env->log.level & BPF_LOG_LEVEL2) {
19121 				if (first)
19122 					verbose(env, "frame %d: propagating r%d", fr, i);
19123 				else
19124 					verbose(env, ",r%d", i);
19125 			}
19126 			bt_set_frame_reg(&env->bt, fr, i);
19127 			first = false;
19128 		}
19129 
19130 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19131 			if (!is_spilled_reg(&state->stack[i]))
19132 				continue;
19133 			state_reg = &state->stack[i].spilled_ptr;
19134 			if (state_reg->type != SCALAR_VALUE ||
19135 			    !state_reg->precise)
19136 				continue;
19137 			if (env->log.level & BPF_LOG_LEVEL2) {
19138 				if (first)
19139 					verbose(env, "frame %d: propagating fp%d",
19140 						fr, (-i - 1) * BPF_REG_SIZE);
19141 				else
19142 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19143 			}
19144 			bt_set_frame_slot(&env->bt, fr, i);
19145 			first = false;
19146 		}
19147 		if (!first)
19148 			verbose(env, "\n");
19149 	}
19150 
19151 	err = __mark_chain_precision(env, cur, -1, changed);
19152 	if (err < 0)
19153 		return err;
19154 
19155 	return 0;
19156 }
19157 
19158 #define MAX_BACKEDGE_ITERS 64
19159 
19160 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19161  * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19162  * then free visit->backedges.
19163  * After execution of this function incomplete_read_marks() will return false
19164  * for all states corresponding to @visit->callchain.
19165  */
propagate_backedges(struct bpf_verifier_env * env,struct bpf_scc_visit * visit)19166 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19167 {
19168 	struct bpf_scc_backedge *backedge;
19169 	struct bpf_verifier_state *st;
19170 	bool changed;
19171 	int i, err;
19172 
19173 	i = 0;
19174 	do {
19175 		if (i++ > MAX_BACKEDGE_ITERS) {
19176 			if (env->log.level & BPF_LOG_LEVEL2)
19177 				verbose(env, "%s: too many iterations\n", __func__);
19178 			for (backedge = visit->backedges; backedge; backedge = backedge->next)
19179 				mark_all_scalars_precise(env, &backedge->state);
19180 			break;
19181 		}
19182 		changed = false;
19183 		for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19184 			st = &backedge->state;
19185 			err = propagate_precision(env, st->equal_state, st, &changed);
19186 			if (err)
19187 				return err;
19188 		}
19189 	} while (changed);
19190 
19191 	free_backedges(visit);
19192 	return 0;
19193 }
19194 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19195 static bool states_maybe_looping(struct bpf_verifier_state *old,
19196 				 struct bpf_verifier_state *cur)
19197 {
19198 	struct bpf_func_state *fold, *fcur;
19199 	int i, fr = cur->curframe;
19200 
19201 	if (old->curframe != fr)
19202 		return false;
19203 
19204 	fold = old->frame[fr];
19205 	fcur = cur->frame[fr];
19206 	for (i = 0; i < MAX_BPF_REG; i++)
19207 		if (memcmp(&fold->regs[i], &fcur->regs[i],
19208 			   offsetof(struct bpf_reg_state, frameno)))
19209 			return false;
19210 	return true;
19211 }
19212 
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)19213 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19214 {
19215 	return env->insn_aux_data[insn_idx].is_iter_next;
19216 }
19217 
19218 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19219  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19220  * states to match, which otherwise would look like an infinite loop. So while
19221  * iter_next() calls are taken care of, we still need to be careful and
19222  * prevent erroneous and too eager declaration of "infinite loop", when
19223  * iterators are involved.
19224  *
19225  * Here's a situation in pseudo-BPF assembly form:
19226  *
19227  *   0: again:                          ; set up iter_next() call args
19228  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
19229  *   2:   call bpf_iter_num_next        ; this is iter_next() call
19230  *   3:   if r0 == 0 goto done
19231  *   4:   ... something useful here ...
19232  *   5:   goto again                    ; another iteration
19233  *   6: done:
19234  *   7:   r1 = &it
19235  *   8:   call bpf_iter_num_destroy     ; clean up iter state
19236  *   9:   exit
19237  *
19238  * This is a typical loop. Let's assume that we have a prune point at 1:,
19239  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19240  * again`, assuming other heuristics don't get in a way).
19241  *
19242  * When we first time come to 1:, let's say we have some state X. We proceed
19243  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19244  * Now we come back to validate that forked ACTIVE state. We proceed through
19245  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19246  * are converging. But the problem is that we don't know that yet, as this
19247  * convergence has to happen at iter_next() call site only. So if nothing is
19248  * done, at 1: verifier will use bounded loop logic and declare infinite
19249  * looping (and would be *technically* correct, if not for iterator's
19250  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19251  * don't want that. So what we do in process_iter_next_call() when we go on
19252  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19253  * a different iteration. So when we suspect an infinite loop, we additionally
19254  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19255  * pretend we are not looping and wait for next iter_next() call.
19256  *
19257  * This only applies to ACTIVE state. In DRAINED state we don't expect to
19258  * loop, because that would actually mean infinite loop, as DRAINED state is
19259  * "sticky", and so we'll keep returning into the same instruction with the
19260  * same state (at least in one of possible code paths).
19261  *
19262  * This approach allows to keep infinite loop heuristic even in the face of
19263  * active iterator. E.g., C snippet below is and will be detected as
19264  * infinitely looping:
19265  *
19266  *   struct bpf_iter_num it;
19267  *   int *p, x;
19268  *
19269  *   bpf_iter_num_new(&it, 0, 10);
19270  *   while ((p = bpf_iter_num_next(&t))) {
19271  *       x = p;
19272  *       while (x--) {} // <<-- infinite loop here
19273  *   }
19274  *
19275  */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19276 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19277 {
19278 	struct bpf_reg_state *slot, *cur_slot;
19279 	struct bpf_func_state *state;
19280 	int i, fr;
19281 
19282 	for (fr = old->curframe; fr >= 0; fr--) {
19283 		state = old->frame[fr];
19284 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19285 			if (state->stack[i].slot_type[0] != STACK_ITER)
19286 				continue;
19287 
19288 			slot = &state->stack[i].spilled_ptr;
19289 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19290 				continue;
19291 
19292 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19293 			if (cur_slot->iter.depth != slot->iter.depth)
19294 				return true;
19295 		}
19296 	}
19297 	return false;
19298 }
19299 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)19300 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19301 {
19302 	struct bpf_verifier_state_list *new_sl;
19303 	struct bpf_verifier_state_list *sl;
19304 	struct bpf_verifier_state *cur = env->cur_state, *new;
19305 	bool force_new_state, add_new_state, loop;
19306 	int n, err, states_cnt = 0;
19307 	struct list_head *pos, *tmp, *head;
19308 
19309 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19310 			  /* Avoid accumulating infinitely long jmp history */
19311 			  cur->jmp_history_cnt > 40;
19312 
19313 	/* bpf progs typically have pruning point every 4 instructions
19314 	 * http://vger.kernel.org/bpfconf2019.html#session-1
19315 	 * Do not add new state for future pruning if the verifier hasn't seen
19316 	 * at least 2 jumps and at least 8 instructions.
19317 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19318 	 * In tests that amounts to up to 50% reduction into total verifier
19319 	 * memory consumption and 20% verifier time speedup.
19320 	 */
19321 	add_new_state = force_new_state;
19322 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19323 	    env->insn_processed - env->prev_insn_processed >= 8)
19324 		add_new_state = true;
19325 
19326 	clean_live_states(env, insn_idx, cur);
19327 
19328 	loop = false;
19329 	head = explored_state(env, insn_idx);
19330 	list_for_each_safe(pos, tmp, head) {
19331 		sl = container_of(pos, struct bpf_verifier_state_list, node);
19332 		states_cnt++;
19333 		if (sl->state.insn_idx != insn_idx)
19334 			continue;
19335 
19336 		if (sl->state.branches) {
19337 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19338 
19339 			if (frame->in_async_callback_fn &&
19340 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19341 				/* Different async_entry_cnt means that the verifier is
19342 				 * processing another entry into async callback.
19343 				 * Seeing the same state is not an indication of infinite
19344 				 * loop or infinite recursion.
19345 				 * But finding the same state doesn't mean that it's safe
19346 				 * to stop processing the current state. The previous state
19347 				 * hasn't yet reached bpf_exit, since state.branches > 0.
19348 				 * Checking in_async_callback_fn alone is not enough either.
19349 				 * Since the verifier still needs to catch infinite loops
19350 				 * inside async callbacks.
19351 				 */
19352 				goto skip_inf_loop_check;
19353 			}
19354 			/* BPF open-coded iterators loop detection is special.
19355 			 * states_maybe_looping() logic is too simplistic in detecting
19356 			 * states that *might* be equivalent, because it doesn't know
19357 			 * about ID remapping, so don't even perform it.
19358 			 * See process_iter_next_call() and iter_active_depths_differ()
19359 			 * for overview of the logic. When current and one of parent
19360 			 * states are detected as equivalent, it's a good thing: we prove
19361 			 * convergence and can stop simulating further iterations.
19362 			 * It's safe to assume that iterator loop will finish, taking into
19363 			 * account iter_next() contract of eventually returning
19364 			 * sticky NULL result.
19365 			 *
19366 			 * Note, that states have to be compared exactly in this case because
19367 			 * read and precision marks might not be finalized inside the loop.
19368 			 * E.g. as in the program below:
19369 			 *
19370 			 *     1. r7 = -16
19371 			 *     2. r6 = bpf_get_prandom_u32()
19372 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
19373 			 *     4.   if (r6 != 42) {
19374 			 *     5.     r7 = -32
19375 			 *     6.     r6 = bpf_get_prandom_u32()
19376 			 *     7.     continue
19377 			 *     8.   }
19378 			 *     9.   r0 = r10
19379 			 *    10.   r0 += r7
19380 			 *    11.   r8 = *(u64 *)(r0 + 0)
19381 			 *    12.   r6 = bpf_get_prandom_u32()
19382 			 *    13. }
19383 			 *
19384 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
19385 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19386 			 * not have read or precision mark for r7 yet, thus inexact states
19387 			 * comparison would discard current state with r7=-32
19388 			 * => unsafe memory access at 11 would not be caught.
19389 			 */
19390 			if (is_iter_next_insn(env, insn_idx)) {
19391 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19392 					struct bpf_func_state *cur_frame;
19393 					struct bpf_reg_state *iter_state, *iter_reg;
19394 					int spi;
19395 
19396 					cur_frame = cur->frame[cur->curframe];
19397 					/* btf_check_iter_kfuncs() enforces that
19398 					 * iter state pointer is always the first arg
19399 					 */
19400 					iter_reg = &cur_frame->regs[BPF_REG_1];
19401 					/* current state is valid due to states_equal(),
19402 					 * so we can assume valid iter and reg state,
19403 					 * no need for extra (re-)validations
19404 					 */
19405 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19406 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19407 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19408 						loop = true;
19409 						goto hit;
19410 					}
19411 				}
19412 				goto skip_inf_loop_check;
19413 			}
19414 			if (is_may_goto_insn_at(env, insn_idx)) {
19415 				if (sl->state.may_goto_depth != cur->may_goto_depth &&
19416 				    states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19417 					loop = true;
19418 					goto hit;
19419 				}
19420 			}
19421 			if (bpf_calls_callback(env, insn_idx)) {
19422 				if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19423 					goto hit;
19424 				goto skip_inf_loop_check;
19425 			}
19426 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
19427 			if (states_maybe_looping(&sl->state, cur) &&
19428 			    states_equal(env, &sl->state, cur, EXACT) &&
19429 			    !iter_active_depths_differ(&sl->state, cur) &&
19430 			    sl->state.may_goto_depth == cur->may_goto_depth &&
19431 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19432 				verbose_linfo(env, insn_idx, "; ");
19433 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19434 				verbose(env, "cur state:");
19435 				print_verifier_state(env, cur, cur->curframe, true);
19436 				verbose(env, "old state:");
19437 				print_verifier_state(env, &sl->state, cur->curframe, true);
19438 				return -EINVAL;
19439 			}
19440 			/* if the verifier is processing a loop, avoid adding new state
19441 			 * too often, since different loop iterations have distinct
19442 			 * states and may not help future pruning.
19443 			 * This threshold shouldn't be too low to make sure that
19444 			 * a loop with large bound will be rejected quickly.
19445 			 * The most abusive loop will be:
19446 			 * r1 += 1
19447 			 * if r1 < 1000000 goto pc-2
19448 			 * 1M insn_procssed limit / 100 == 10k peak states.
19449 			 * This threshold shouldn't be too high either, since states
19450 			 * at the end of the loop are likely to be useful in pruning.
19451 			 */
19452 skip_inf_loop_check:
19453 			if (!force_new_state &&
19454 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
19455 			    env->insn_processed - env->prev_insn_processed < 100)
19456 				add_new_state = false;
19457 			goto miss;
19458 		}
19459 		/* See comments for mark_all_regs_read_and_precise() */
19460 		loop = incomplete_read_marks(env, &sl->state);
19461 		if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19462 hit:
19463 			sl->hit_cnt++;
19464 
19465 			/* if previous state reached the exit with precision and
19466 			 * current state is equivalent to it (except precision marks)
19467 			 * the precision needs to be propagated back in
19468 			 * the current state.
19469 			 */
19470 			err = 0;
19471 			if (is_jmp_point(env, env->insn_idx))
19472 				err = push_jmp_history(env, cur, 0, 0);
19473 			err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19474 			if (err)
19475 				return err;
19476 			/* When processing iterator based loops above propagate_liveness and
19477 			 * propagate_precision calls are not sufficient to transfer all relevant
19478 			 * read and precision marks. E.g. consider the following case:
19479 			 *
19480 			 *  .-> A --.  Assume the states are visited in the order A, B, C.
19481 			 *  |   |   |  Assume that state B reaches a state equivalent to state A.
19482 			 *  |   v   v  At this point, state C is not processed yet, so state A
19483 			 *  '-- B   C  has not received any read or precision marks from C.
19484 			 *             Thus, marks propagated from A to B are incomplete.
19485 			 *
19486 			 * The verifier mitigates this by performing the following steps:
19487 			 *
19488 			 * - Prior to the main verification pass, strongly connected components
19489 			 *   (SCCs) are computed over the program's control flow graph,
19490 			 *   intraprocedurally.
19491 			 *
19492 			 * - During the main verification pass, `maybe_enter_scc()` checks
19493 			 *   whether the current verifier state is entering an SCC. If so, an
19494 			 *   instance of a `bpf_scc_visit` object is created, and the state
19495 			 *   entering the SCC is recorded as the entry state.
19496 			 *
19497 			 * - This instance is associated not with the SCC itself, but with a
19498 			 *   `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19499 			 *   the SCC and the SCC id. See `compute_scc_callchain()`.
19500 			 *
19501 			 * - When a verification path encounters a `states_equal(...,
19502 			 *   RANGE_WITHIN)` condition, there exists a call chain describing the
19503 			 *   current state and a corresponding `bpf_scc_visit` instance. A copy
19504 			 *   of the current state is created and added to
19505 			 *   `bpf_scc_visit->backedges`.
19506 			 *
19507 			 * - When a verification path terminates, `maybe_exit_scc()` is called
19508 			 *   from `update_branch_counts()`. For states with `branches == 0`, it
19509 			 *   checks whether the state is the entry state of any `bpf_scc_visit`
19510 			 *   instance. If it is, this indicates that all paths originating from
19511 			 *   this SCC visit have been explored. `propagate_backedges()` is then
19512 			 *   called, which propagates read and precision marks through the
19513 			 *   backedges until a fixed point is reached.
19514 			 *   (In the earlier example, this would propagate marks from A to B,
19515 			 *    from C to A, and then again from A to B.)
19516 			 *
19517 			 * A note on callchains
19518 			 * --------------------
19519 			 *
19520 			 * Consider the following example:
19521 			 *
19522 			 *     void foo() { loop { ... SCC#1 ... } }
19523 			 *     void main() {
19524 			 *       A: foo();
19525 			 *       B: ...
19526 			 *       C: foo();
19527 			 *     }
19528 			 *
19529 			 * Here, there are two distinct callchains leading to SCC#1:
19530 			 * - (A, SCC#1)
19531 			 * - (C, SCC#1)
19532 			 *
19533 			 * Each callchain identifies a separate `bpf_scc_visit` instance that
19534 			 * accumulates backedge states. The `propagate_{liveness,precision}()`
19535 			 * functions traverse the parent state of each backedge state, which
19536 			 * means these parent states must remain valid (i.e., not freed) while
19537 			 * the corresponding `bpf_scc_visit` instance exists.
19538 			 *
19539 			 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19540 			 * callchains would break this invariant:
19541 			 * - States explored during `C: foo()` would contribute backedges to
19542 			 *   SCC#1, but SCC#1 would only be exited once the exploration of
19543 			 *   `A: foo()` completes.
19544 			 * - By that time, the states explored between `A: foo()` and `C: foo()`
19545 			 *   (i.e., `B: ...`) may have already been freed, causing the parent
19546 			 *   links for states from `C: foo()` to become invalid.
19547 			 */
19548 			if (loop) {
19549 				struct bpf_scc_backedge *backedge;
19550 
19551 				backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19552 				if (!backedge)
19553 					return -ENOMEM;
19554 				err = copy_verifier_state(&backedge->state, cur);
19555 				backedge->state.equal_state = &sl->state;
19556 				backedge->state.insn_idx = insn_idx;
19557 				err = err ?: add_scc_backedge(env, &sl->state, backedge);
19558 				if (err) {
19559 					free_verifier_state(&backedge->state, false);
19560 					kfree(backedge);
19561 					return err;
19562 				}
19563 			}
19564 			return 1;
19565 		}
19566 miss:
19567 		/* when new state is not going to be added do not increase miss count.
19568 		 * Otherwise several loop iterations will remove the state
19569 		 * recorded earlier. The goal of these heuristics is to have
19570 		 * states from some iterations of the loop (some in the beginning
19571 		 * and some at the end) to help pruning.
19572 		 */
19573 		if (add_new_state)
19574 			sl->miss_cnt++;
19575 		/* heuristic to determine whether this state is beneficial
19576 		 * to keep checking from state equivalence point of view.
19577 		 * Higher numbers increase max_states_per_insn and verification time,
19578 		 * but do not meaningfully decrease insn_processed.
19579 		 * 'n' controls how many times state could miss before eviction.
19580 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
19581 		 * too early would hinder iterator convergence.
19582 		 */
19583 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19584 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
19585 			/* the state is unlikely to be useful. Remove it to
19586 			 * speed up verification
19587 			 */
19588 			sl->in_free_list = true;
19589 			list_del(&sl->node);
19590 			list_add(&sl->node, &env->free_list);
19591 			env->free_list_size++;
19592 			env->explored_states_size--;
19593 			maybe_free_verifier_state(env, sl);
19594 		}
19595 	}
19596 
19597 	if (env->max_states_per_insn < states_cnt)
19598 		env->max_states_per_insn = states_cnt;
19599 
19600 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
19601 		return 0;
19602 
19603 	if (!add_new_state)
19604 		return 0;
19605 
19606 	/* There were no equivalent states, remember the current one.
19607 	 * Technically the current state is not proven to be safe yet,
19608 	 * but it will either reach outer most bpf_exit (which means it's safe)
19609 	 * or it will be rejected. When there are no loops the verifier won't be
19610 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
19611 	 * again on the way to bpf_exit.
19612 	 * When looping the sl->state.branches will be > 0 and this state
19613 	 * will not be considered for equivalence until branches == 0.
19614 	 */
19615 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
19616 	if (!new_sl)
19617 		return -ENOMEM;
19618 	env->total_states++;
19619 	env->explored_states_size++;
19620 	update_peak_states(env);
19621 	env->prev_jmps_processed = env->jmps_processed;
19622 	env->prev_insn_processed = env->insn_processed;
19623 
19624 	/* forget precise markings we inherited, see __mark_chain_precision */
19625 	if (env->bpf_capable)
19626 		mark_all_scalars_imprecise(env, cur);
19627 
19628 	/* add new state to the head of linked list */
19629 	new = &new_sl->state;
19630 	err = copy_verifier_state(new, cur);
19631 	if (err) {
19632 		free_verifier_state(new, false);
19633 		kfree(new_sl);
19634 		return err;
19635 	}
19636 	new->insn_idx = insn_idx;
19637 	verifier_bug_if(new->branches != 1, env,
19638 			"%s:branches_to_explore=%d insn %d",
19639 			__func__, new->branches, insn_idx);
19640 	err = maybe_enter_scc(env, new);
19641 	if (err) {
19642 		free_verifier_state(new, false);
19643 		kfree(new_sl);
19644 		return err;
19645 	}
19646 
19647 	cur->parent = new;
19648 	cur->first_insn_idx = insn_idx;
19649 	cur->dfs_depth = new->dfs_depth + 1;
19650 	clear_jmp_history(cur);
19651 	list_add(&new_sl->node, head);
19652 	return 0;
19653 }
19654 
19655 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)19656 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
19657 {
19658 	switch (base_type(type)) {
19659 	case PTR_TO_CTX:
19660 	case PTR_TO_SOCKET:
19661 	case PTR_TO_SOCK_COMMON:
19662 	case PTR_TO_TCP_SOCK:
19663 	case PTR_TO_XDP_SOCK:
19664 	case PTR_TO_BTF_ID:
19665 	case PTR_TO_ARENA:
19666 		return false;
19667 	default:
19668 		return true;
19669 	}
19670 }
19671 
19672 /* If an instruction was previously used with particular pointer types, then we
19673  * need to be careful to avoid cases such as the below, where it may be ok
19674  * for one branch accessing the pointer, but not ok for the other branch:
19675  *
19676  * R1 = sock_ptr
19677  * goto X;
19678  * ...
19679  * R1 = some_other_valid_ptr;
19680  * goto X;
19681  * ...
19682  * R2 = *(u32 *)(R1 + 0);
19683  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)19684 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
19685 {
19686 	return src != prev && (!reg_type_mismatch_ok(src) ||
19687 			       !reg_type_mismatch_ok(prev));
19688 }
19689 
is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)19690 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
19691 {
19692 	switch (base_type(type)) {
19693 	case PTR_TO_MEM:
19694 	case PTR_TO_BTF_ID:
19695 		return true;
19696 	default:
19697 		return false;
19698 	}
19699 }
19700 
is_ptr_to_mem(enum bpf_reg_type type)19701 static bool is_ptr_to_mem(enum bpf_reg_type type)
19702 {
19703 	return base_type(type) == PTR_TO_MEM;
19704 }
19705 
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_mismatch)19706 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
19707 			     bool allow_trust_mismatch)
19708 {
19709 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
19710 	enum bpf_reg_type merged_type;
19711 
19712 	if (*prev_type == NOT_INIT) {
19713 		/* Saw a valid insn
19714 		 * dst_reg = *(u32 *)(src_reg + off)
19715 		 * save type to validate intersecting paths
19716 		 */
19717 		*prev_type = type;
19718 	} else if (reg_type_mismatch(type, *prev_type)) {
19719 		/* Abuser program is trying to use the same insn
19720 		 * dst_reg = *(u32*) (src_reg + off)
19721 		 * with different pointer types:
19722 		 * src_reg == ctx in one branch and
19723 		 * src_reg == stack|map in some other branch.
19724 		 * Reject it.
19725 		 */
19726 		if (allow_trust_mismatch &&
19727 		    is_ptr_to_mem_or_btf_id(type) &&
19728 		    is_ptr_to_mem_or_btf_id(*prev_type)) {
19729 			/*
19730 			 * Have to support a use case when one path through
19731 			 * the program yields TRUSTED pointer while another
19732 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
19733 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
19734 			 * Same behavior of MEM_RDONLY flag.
19735 			 */
19736 			if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
19737 				merged_type = PTR_TO_MEM;
19738 			else
19739 				merged_type = PTR_TO_BTF_ID;
19740 			if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
19741 				merged_type |= PTR_UNTRUSTED;
19742 			if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
19743 				merged_type |= MEM_RDONLY;
19744 			*prev_type = merged_type;
19745 		} else {
19746 			verbose(env, "same insn cannot be used with different pointers\n");
19747 			return -EINVAL;
19748 		}
19749 	}
19750 
19751 	return 0;
19752 }
19753 
19754 enum {
19755 	PROCESS_BPF_EXIT = 1
19756 };
19757 
process_bpf_exit_full(struct bpf_verifier_env * env,bool * do_print_state,bool exception_exit)19758 static int process_bpf_exit_full(struct bpf_verifier_env *env,
19759 				 bool *do_print_state,
19760 				 bool exception_exit)
19761 {
19762 	/* We must do check_reference_leak here before
19763 	 * prepare_func_exit to handle the case when
19764 	 * state->curframe > 0, it may be a callback function,
19765 	 * for which reference_state must match caller reference
19766 	 * state when it exits.
19767 	 */
19768 	int err = check_resource_leak(env, exception_exit,
19769 				      !env->cur_state->curframe,
19770 				      "BPF_EXIT instruction in main prog");
19771 	if (err)
19772 		return err;
19773 
19774 	/* The side effect of the prepare_func_exit which is
19775 	 * being skipped is that it frees bpf_func_state.
19776 	 * Typically, process_bpf_exit will only be hit with
19777 	 * outermost exit. copy_verifier_state in pop_stack will
19778 	 * handle freeing of any extra bpf_func_state left over
19779 	 * from not processing all nested function exits. We
19780 	 * also skip return code checks as they are not needed
19781 	 * for exceptional exits.
19782 	 */
19783 	if (exception_exit)
19784 		return PROCESS_BPF_EXIT;
19785 
19786 	if (env->cur_state->curframe) {
19787 		err = bpf_update_live_stack(env);
19788 		if (err)
19789 			return err;
19790 		/* exit from nested function */
19791 		err = prepare_func_exit(env, &env->insn_idx);
19792 		if (err)
19793 			return err;
19794 		*do_print_state = true;
19795 		return 0;
19796 	}
19797 
19798 	err = check_return_code(env, BPF_REG_0, "R0");
19799 	if (err)
19800 		return err;
19801 	return PROCESS_BPF_EXIT;
19802 }
19803 
do_check_insn(struct bpf_verifier_env * env,bool * do_print_state)19804 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
19805 {
19806 	int err;
19807 	struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
19808 	u8 class = BPF_CLASS(insn->code);
19809 
19810 	if (class == BPF_ALU || class == BPF_ALU64) {
19811 		err = check_alu_op(env, insn);
19812 		if (err)
19813 			return err;
19814 
19815 	} else if (class == BPF_LDX) {
19816 		bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
19817 
19818 		/* Check for reserved fields is already done in
19819 		 * resolve_pseudo_ldimm64().
19820 		 */
19821 		err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
19822 		if (err)
19823 			return err;
19824 	} else if (class == BPF_STX) {
19825 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
19826 			err = check_atomic(env, insn);
19827 			if (err)
19828 				return err;
19829 			env->insn_idx++;
19830 			return 0;
19831 		}
19832 
19833 		if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
19834 			verbose(env, "BPF_STX uses reserved fields\n");
19835 			return -EINVAL;
19836 		}
19837 
19838 		err = check_store_reg(env, insn, false);
19839 		if (err)
19840 			return err;
19841 	} else if (class == BPF_ST) {
19842 		enum bpf_reg_type dst_reg_type;
19843 
19844 		if (BPF_MODE(insn->code) != BPF_MEM ||
19845 		    insn->src_reg != BPF_REG_0) {
19846 			verbose(env, "BPF_ST uses reserved fields\n");
19847 			return -EINVAL;
19848 		}
19849 		/* check src operand */
19850 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
19851 		if (err)
19852 			return err;
19853 
19854 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
19855 
19856 		/* check that memory (dst_reg + off) is writeable */
19857 		err = check_mem_access(env, env->insn_idx, insn->dst_reg,
19858 				       insn->off, BPF_SIZE(insn->code),
19859 				       BPF_WRITE, -1, false, false);
19860 		if (err)
19861 			return err;
19862 
19863 		err = save_aux_ptr_type(env, dst_reg_type, false);
19864 		if (err)
19865 			return err;
19866 	} else if (class == BPF_JMP || class == BPF_JMP32) {
19867 		u8 opcode = BPF_OP(insn->code);
19868 
19869 		env->jmps_processed++;
19870 		if (opcode == BPF_CALL) {
19871 			if (BPF_SRC(insn->code) != BPF_K ||
19872 			    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
19873 			     insn->off != 0) ||
19874 			    (insn->src_reg != BPF_REG_0 &&
19875 			     insn->src_reg != BPF_PSEUDO_CALL &&
19876 			     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
19877 			    insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
19878 				verbose(env, "BPF_CALL uses reserved fields\n");
19879 				return -EINVAL;
19880 			}
19881 
19882 			if (env->cur_state->active_locks) {
19883 				if ((insn->src_reg == BPF_REG_0 &&
19884 				     insn->imm != BPF_FUNC_spin_unlock) ||
19885 				    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
19886 				     (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
19887 					verbose(env,
19888 						"function calls are not allowed while holding a lock\n");
19889 					return -EINVAL;
19890 				}
19891 			}
19892 			if (insn->src_reg == BPF_PSEUDO_CALL) {
19893 				err = check_func_call(env, insn, &env->insn_idx);
19894 			} else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19895 				err = check_kfunc_call(env, insn, &env->insn_idx);
19896 				if (!err && is_bpf_throw_kfunc(insn))
19897 					return process_bpf_exit_full(env, do_print_state, true);
19898 			} else {
19899 				err = check_helper_call(env, insn, &env->insn_idx);
19900 			}
19901 			if (err)
19902 				return err;
19903 
19904 			mark_reg_scratched(env, BPF_REG_0);
19905 		} else if (opcode == BPF_JA) {
19906 			if (BPF_SRC(insn->code) != BPF_K ||
19907 			    insn->src_reg != BPF_REG_0 ||
19908 			    insn->dst_reg != BPF_REG_0 ||
19909 			    (class == BPF_JMP && insn->imm != 0) ||
19910 			    (class == BPF_JMP32 && insn->off != 0)) {
19911 				verbose(env, "BPF_JA uses reserved fields\n");
19912 				return -EINVAL;
19913 			}
19914 
19915 			if (class == BPF_JMP)
19916 				env->insn_idx += insn->off + 1;
19917 			else
19918 				env->insn_idx += insn->imm + 1;
19919 			return 0;
19920 		} else if (opcode == BPF_EXIT) {
19921 			if (BPF_SRC(insn->code) != BPF_K ||
19922 			    insn->imm != 0 ||
19923 			    insn->src_reg != BPF_REG_0 ||
19924 			    insn->dst_reg != BPF_REG_0 ||
19925 			    class == BPF_JMP32) {
19926 				verbose(env, "BPF_EXIT uses reserved fields\n");
19927 				return -EINVAL;
19928 			}
19929 			return process_bpf_exit_full(env, do_print_state, false);
19930 		} else {
19931 			err = check_cond_jmp_op(env, insn, &env->insn_idx);
19932 			if (err)
19933 				return err;
19934 		}
19935 	} else if (class == BPF_LD) {
19936 		u8 mode = BPF_MODE(insn->code);
19937 
19938 		if (mode == BPF_ABS || mode == BPF_IND) {
19939 			err = check_ld_abs(env, insn);
19940 			if (err)
19941 				return err;
19942 
19943 		} else if (mode == BPF_IMM) {
19944 			err = check_ld_imm(env, insn);
19945 			if (err)
19946 				return err;
19947 
19948 			env->insn_idx++;
19949 			sanitize_mark_insn_seen(env);
19950 		} else {
19951 			verbose(env, "invalid BPF_LD mode\n");
19952 			return -EINVAL;
19953 		}
19954 	} else {
19955 		verbose(env, "unknown insn class %d\n", class);
19956 		return -EINVAL;
19957 	}
19958 
19959 	env->insn_idx++;
19960 	return 0;
19961 }
19962 
do_check(struct bpf_verifier_env * env)19963 static int do_check(struct bpf_verifier_env *env)
19964 {
19965 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19966 	struct bpf_verifier_state *state = env->cur_state;
19967 	struct bpf_insn *insns = env->prog->insnsi;
19968 	int insn_cnt = env->prog->len;
19969 	bool do_print_state = false;
19970 	int prev_insn_idx = -1;
19971 
19972 	for (;;) {
19973 		struct bpf_insn *insn;
19974 		struct bpf_insn_aux_data *insn_aux;
19975 		int err, marks_err;
19976 
19977 		/* reset current history entry on each new instruction */
19978 		env->cur_hist_ent = NULL;
19979 
19980 		env->prev_insn_idx = prev_insn_idx;
19981 		if (env->insn_idx >= insn_cnt) {
19982 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
19983 				env->insn_idx, insn_cnt);
19984 			return -EFAULT;
19985 		}
19986 
19987 		insn = &insns[env->insn_idx];
19988 		insn_aux = &env->insn_aux_data[env->insn_idx];
19989 
19990 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
19991 			verbose(env,
19992 				"BPF program is too large. Processed %d insn\n",
19993 				env->insn_processed);
19994 			return -E2BIG;
19995 		}
19996 
19997 		state->last_insn_idx = env->prev_insn_idx;
19998 		state->insn_idx = env->insn_idx;
19999 
20000 		if (is_prune_point(env, env->insn_idx)) {
20001 			err = is_state_visited(env, env->insn_idx);
20002 			if (err < 0)
20003 				return err;
20004 			if (err == 1) {
20005 				/* found equivalent state, can prune the search */
20006 				if (env->log.level & BPF_LOG_LEVEL) {
20007 					if (do_print_state)
20008 						verbose(env, "\nfrom %d to %d%s: safe\n",
20009 							env->prev_insn_idx, env->insn_idx,
20010 							env->cur_state->speculative ?
20011 							" (speculative execution)" : "");
20012 					else
20013 						verbose(env, "%d: safe\n", env->insn_idx);
20014 				}
20015 				goto process_bpf_exit;
20016 			}
20017 		}
20018 
20019 		if (is_jmp_point(env, env->insn_idx)) {
20020 			err = push_jmp_history(env, state, 0, 0);
20021 			if (err)
20022 				return err;
20023 		}
20024 
20025 		if (signal_pending(current))
20026 			return -EAGAIN;
20027 
20028 		if (need_resched())
20029 			cond_resched();
20030 
20031 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20032 			verbose(env, "\nfrom %d to %d%s:",
20033 				env->prev_insn_idx, env->insn_idx,
20034 				env->cur_state->speculative ?
20035 				" (speculative execution)" : "");
20036 			print_verifier_state(env, state, state->curframe, true);
20037 			do_print_state = false;
20038 		}
20039 
20040 		if (env->log.level & BPF_LOG_LEVEL) {
20041 			if (verifier_state_scratched(env))
20042 				print_insn_state(env, state, state->curframe);
20043 
20044 			verbose_linfo(env, env->insn_idx, "; ");
20045 			env->prev_log_pos = env->log.end_pos;
20046 			verbose(env, "%d: ", env->insn_idx);
20047 			verbose_insn(env, insn);
20048 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20049 			env->prev_log_pos = env->log.end_pos;
20050 		}
20051 
20052 		if (bpf_prog_is_offloaded(env->prog->aux)) {
20053 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20054 							   env->prev_insn_idx);
20055 			if (err)
20056 				return err;
20057 		}
20058 
20059 		sanitize_mark_insn_seen(env);
20060 		prev_insn_idx = env->insn_idx;
20061 
20062 		/* Reduce verification complexity by stopping speculative path
20063 		 * verification when a nospec is encountered.
20064 		 */
20065 		if (state->speculative && insn_aux->nospec)
20066 			goto process_bpf_exit;
20067 
20068 		err = bpf_reset_stack_write_marks(env, env->insn_idx);
20069 		if (err)
20070 			return err;
20071 		err = do_check_insn(env, &do_print_state);
20072 		if (err >= 0 || error_recoverable_with_nospec(err)) {
20073 			marks_err = bpf_commit_stack_write_marks(env);
20074 			if (marks_err)
20075 				return marks_err;
20076 		}
20077 		if (error_recoverable_with_nospec(err) && state->speculative) {
20078 			/* Prevent this speculative path from ever reaching the
20079 			 * insn that would have been unsafe to execute.
20080 			 */
20081 			insn_aux->nospec = true;
20082 			/* If it was an ADD/SUB insn, potentially remove any
20083 			 * markings for alu sanitization.
20084 			 */
20085 			insn_aux->alu_state = 0;
20086 			goto process_bpf_exit;
20087 		} else if (err < 0) {
20088 			return err;
20089 		} else if (err == PROCESS_BPF_EXIT) {
20090 			goto process_bpf_exit;
20091 		}
20092 		WARN_ON_ONCE(err);
20093 
20094 		if (state->speculative && insn_aux->nospec_result) {
20095 			/* If we are on a path that performed a jump-op, this
20096 			 * may skip a nospec patched-in after the jump. This can
20097 			 * currently never happen because nospec_result is only
20098 			 * used for the write-ops
20099 			 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20100 			 * never skip the following insn. Still, add a warning
20101 			 * to document this in case nospec_result is used
20102 			 * elsewhere in the future.
20103 			 *
20104 			 * All non-branch instructions have a single
20105 			 * fall-through edge. For these, nospec_result should
20106 			 * already work.
20107 			 */
20108 			if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20109 					    BPF_CLASS(insn->code) == BPF_JMP32, env,
20110 					    "speculation barrier after jump instruction may not have the desired effect"))
20111 				return -EFAULT;
20112 process_bpf_exit:
20113 			mark_verifier_state_scratched(env);
20114 			err = update_branch_counts(env, env->cur_state);
20115 			if (err)
20116 				return err;
20117 			err = bpf_update_live_stack(env);
20118 			if (err)
20119 				return err;
20120 			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20121 					pop_log);
20122 			if (err < 0) {
20123 				if (err != -ENOENT)
20124 					return err;
20125 				break;
20126 			} else {
20127 				do_print_state = true;
20128 				continue;
20129 			}
20130 		}
20131 	}
20132 
20133 	return 0;
20134 }
20135 
find_btf_percpu_datasec(struct btf * btf)20136 static int find_btf_percpu_datasec(struct btf *btf)
20137 {
20138 	const struct btf_type *t;
20139 	const char *tname;
20140 	int i, n;
20141 
20142 	/*
20143 	 * Both vmlinux and module each have their own ".data..percpu"
20144 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20145 	 * types to look at only module's own BTF types.
20146 	 */
20147 	n = btf_nr_types(btf);
20148 	if (btf_is_module(btf))
20149 		i = btf_nr_types(btf_vmlinux);
20150 	else
20151 		i = 1;
20152 
20153 	for(; i < n; i++) {
20154 		t = btf_type_by_id(btf, i);
20155 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20156 			continue;
20157 
20158 		tname = btf_name_by_offset(btf, t->name_off);
20159 		if (!strcmp(tname, ".data..percpu"))
20160 			return i;
20161 	}
20162 
20163 	return -ENOENT;
20164 }
20165 
20166 /*
20167  * Add btf to the used_btfs array and return the index. (If the btf was
20168  * already added, then just return the index.) Upon successful insertion
20169  * increase btf refcnt, and, if present, also refcount the corresponding
20170  * kernel module.
20171  */
__add_used_btf(struct bpf_verifier_env * env,struct btf * btf)20172 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20173 {
20174 	struct btf_mod_pair *btf_mod;
20175 	int i;
20176 
20177 	/* check whether we recorded this BTF (and maybe module) already */
20178 	for (i = 0; i < env->used_btf_cnt; i++)
20179 		if (env->used_btfs[i].btf == btf)
20180 			return i;
20181 
20182 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
20183 		verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20184 			MAX_USED_BTFS);
20185 		return -E2BIG;
20186 	}
20187 
20188 	btf_get(btf);
20189 
20190 	btf_mod = &env->used_btfs[env->used_btf_cnt];
20191 	btf_mod->btf = btf;
20192 	btf_mod->module = NULL;
20193 
20194 	/* if we reference variables from kernel module, bump its refcount */
20195 	if (btf_is_module(btf)) {
20196 		btf_mod->module = btf_try_get_module(btf);
20197 		if (!btf_mod->module) {
20198 			btf_put(btf);
20199 			return -ENXIO;
20200 		}
20201 	}
20202 
20203 	return env->used_btf_cnt++;
20204 }
20205 
20206 /* 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)20207 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20208 				 struct bpf_insn *insn,
20209 				 struct bpf_insn_aux_data *aux,
20210 				 struct btf *btf)
20211 {
20212 	const struct btf_var_secinfo *vsi;
20213 	const struct btf_type *datasec;
20214 	const struct btf_type *t;
20215 	const char *sym_name;
20216 	bool percpu = false;
20217 	u32 type, id = insn->imm;
20218 	s32 datasec_id;
20219 	u64 addr;
20220 	int i;
20221 
20222 	t = btf_type_by_id(btf, id);
20223 	if (!t) {
20224 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20225 		return -ENOENT;
20226 	}
20227 
20228 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20229 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20230 		return -EINVAL;
20231 	}
20232 
20233 	sym_name = btf_name_by_offset(btf, t->name_off);
20234 	addr = kallsyms_lookup_name(sym_name);
20235 	if (!addr) {
20236 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20237 			sym_name);
20238 		return -ENOENT;
20239 	}
20240 	insn[0].imm = (u32)addr;
20241 	insn[1].imm = addr >> 32;
20242 
20243 	if (btf_type_is_func(t)) {
20244 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20245 		aux->btf_var.mem_size = 0;
20246 		return 0;
20247 	}
20248 
20249 	datasec_id = find_btf_percpu_datasec(btf);
20250 	if (datasec_id > 0) {
20251 		datasec = btf_type_by_id(btf, datasec_id);
20252 		for_each_vsi(i, datasec, vsi) {
20253 			if (vsi->type == id) {
20254 				percpu = true;
20255 				break;
20256 			}
20257 		}
20258 	}
20259 
20260 	type = t->type;
20261 	t = btf_type_skip_modifiers(btf, type, NULL);
20262 	if (percpu) {
20263 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20264 		aux->btf_var.btf = btf;
20265 		aux->btf_var.btf_id = type;
20266 	} else if (!btf_type_is_struct(t)) {
20267 		const struct btf_type *ret;
20268 		const char *tname;
20269 		u32 tsize;
20270 
20271 		/* resolve the type size of ksym. */
20272 		ret = btf_resolve_size(btf, t, &tsize);
20273 		if (IS_ERR(ret)) {
20274 			tname = btf_name_by_offset(btf, t->name_off);
20275 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20276 				tname, PTR_ERR(ret));
20277 			return -EINVAL;
20278 		}
20279 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20280 		aux->btf_var.mem_size = tsize;
20281 	} else {
20282 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
20283 		aux->btf_var.btf = btf;
20284 		aux->btf_var.btf_id = type;
20285 	}
20286 
20287 	return 0;
20288 }
20289 
check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux)20290 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20291 			       struct bpf_insn *insn,
20292 			       struct bpf_insn_aux_data *aux)
20293 {
20294 	struct btf *btf;
20295 	int btf_fd;
20296 	int err;
20297 
20298 	btf_fd = insn[1].imm;
20299 	if (btf_fd) {
20300 		CLASS(fd, f)(btf_fd);
20301 
20302 		btf = __btf_get_by_fd(f);
20303 		if (IS_ERR(btf)) {
20304 			verbose(env, "invalid module BTF object FD specified.\n");
20305 			return -EINVAL;
20306 		}
20307 	} else {
20308 		if (!btf_vmlinux) {
20309 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20310 			return -EINVAL;
20311 		}
20312 		btf = btf_vmlinux;
20313 	}
20314 
20315 	err = __check_pseudo_btf_id(env, insn, aux, btf);
20316 	if (err)
20317 		return err;
20318 
20319 	err = __add_used_btf(env, btf);
20320 	if (err < 0)
20321 		return err;
20322 	return 0;
20323 }
20324 
is_tracing_prog_type(enum bpf_prog_type type)20325 static bool is_tracing_prog_type(enum bpf_prog_type type)
20326 {
20327 	switch (type) {
20328 	case BPF_PROG_TYPE_KPROBE:
20329 	case BPF_PROG_TYPE_TRACEPOINT:
20330 	case BPF_PROG_TYPE_PERF_EVENT:
20331 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
20332 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20333 		return true;
20334 	default:
20335 		return false;
20336 	}
20337 }
20338 
bpf_map_is_cgroup_storage(struct bpf_map * map)20339 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20340 {
20341 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20342 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20343 }
20344 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)20345 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20346 					struct bpf_map *map,
20347 					struct bpf_prog *prog)
20348 
20349 {
20350 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
20351 
20352 	if (map->excl_prog_sha &&
20353 	    memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20354 		verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20355 		return -EACCES;
20356 	}
20357 
20358 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20359 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
20360 		if (is_tracing_prog_type(prog_type)) {
20361 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20362 			return -EINVAL;
20363 		}
20364 	}
20365 
20366 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20367 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20368 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20369 			return -EINVAL;
20370 		}
20371 
20372 		if (is_tracing_prog_type(prog_type)) {
20373 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20374 			return -EINVAL;
20375 		}
20376 	}
20377 
20378 	if (btf_record_has_field(map->record, BPF_TIMER)) {
20379 		if (is_tracing_prog_type(prog_type)) {
20380 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
20381 			return -EINVAL;
20382 		}
20383 	}
20384 
20385 	if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20386 		if (is_tracing_prog_type(prog_type)) {
20387 			verbose(env, "tracing progs cannot use bpf_wq yet\n");
20388 			return -EINVAL;
20389 		}
20390 	}
20391 
20392 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20393 	    !bpf_offload_prog_map_match(prog, map)) {
20394 		verbose(env, "offload device mismatch between prog and map\n");
20395 		return -EINVAL;
20396 	}
20397 
20398 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20399 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20400 		return -EINVAL;
20401 	}
20402 
20403 	if (prog->sleepable)
20404 		switch (map->map_type) {
20405 		case BPF_MAP_TYPE_HASH:
20406 		case BPF_MAP_TYPE_LRU_HASH:
20407 		case BPF_MAP_TYPE_ARRAY:
20408 		case BPF_MAP_TYPE_PERCPU_HASH:
20409 		case BPF_MAP_TYPE_PERCPU_ARRAY:
20410 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20411 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20412 		case BPF_MAP_TYPE_HASH_OF_MAPS:
20413 		case BPF_MAP_TYPE_RINGBUF:
20414 		case BPF_MAP_TYPE_USER_RINGBUF:
20415 		case BPF_MAP_TYPE_INODE_STORAGE:
20416 		case BPF_MAP_TYPE_SK_STORAGE:
20417 		case BPF_MAP_TYPE_TASK_STORAGE:
20418 		case BPF_MAP_TYPE_CGRP_STORAGE:
20419 		case BPF_MAP_TYPE_QUEUE:
20420 		case BPF_MAP_TYPE_STACK:
20421 		case BPF_MAP_TYPE_ARENA:
20422 			break;
20423 		default:
20424 			verbose(env,
20425 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20426 			return -EINVAL;
20427 		}
20428 
20429 	if (bpf_map_is_cgroup_storage(map) &&
20430 	    bpf_cgroup_storage_assign(env->prog->aux, map)) {
20431 		verbose(env, "only one cgroup storage of each type is allowed\n");
20432 		return -EBUSY;
20433 	}
20434 
20435 	if (map->map_type == BPF_MAP_TYPE_ARENA) {
20436 		if (env->prog->aux->arena) {
20437 			verbose(env, "Only one arena per program\n");
20438 			return -EBUSY;
20439 		}
20440 		if (!env->allow_ptr_leaks || !env->bpf_capable) {
20441 			verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20442 			return -EPERM;
20443 		}
20444 		if (!env->prog->jit_requested) {
20445 			verbose(env, "JIT is required to use arena\n");
20446 			return -EOPNOTSUPP;
20447 		}
20448 		if (!bpf_jit_supports_arena()) {
20449 			verbose(env, "JIT doesn't support arena\n");
20450 			return -EOPNOTSUPP;
20451 		}
20452 		env->prog->aux->arena = (void *)map;
20453 		if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20454 			verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20455 			return -EINVAL;
20456 		}
20457 	}
20458 
20459 	return 0;
20460 }
20461 
__add_used_map(struct bpf_verifier_env * env,struct bpf_map * map)20462 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20463 {
20464 	int i, err;
20465 
20466 	/* check whether we recorded this map already */
20467 	for (i = 0; i < env->used_map_cnt; i++)
20468 		if (env->used_maps[i] == map)
20469 			return i;
20470 
20471 	if (env->used_map_cnt >= MAX_USED_MAPS) {
20472 		verbose(env, "The total number of maps per program has reached the limit of %u\n",
20473 			MAX_USED_MAPS);
20474 		return -E2BIG;
20475 	}
20476 
20477 	err = check_map_prog_compatibility(env, map, env->prog);
20478 	if (err)
20479 		return err;
20480 
20481 	if (env->prog->sleepable)
20482 		atomic64_inc(&map->sleepable_refcnt);
20483 
20484 	/* hold the map. If the program is rejected by verifier,
20485 	 * the map will be released by release_maps() or it
20486 	 * will be used by the valid program until it's unloaded
20487 	 * and all maps are released in bpf_free_used_maps()
20488 	 */
20489 	bpf_map_inc(map);
20490 
20491 	env->used_maps[env->used_map_cnt++] = map;
20492 
20493 	return env->used_map_cnt - 1;
20494 }
20495 
20496 /* Add map behind fd to used maps list, if it's not already there, and return
20497  * its index.
20498  * Returns <0 on error, or >= 0 index, on success.
20499  */
add_used_map(struct bpf_verifier_env * env,int fd)20500 static int add_used_map(struct bpf_verifier_env *env, int fd)
20501 {
20502 	struct bpf_map *map;
20503 	CLASS(fd, f)(fd);
20504 
20505 	map = __bpf_map_get(f);
20506 	if (IS_ERR(map)) {
20507 		verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
20508 		return PTR_ERR(map);
20509 	}
20510 
20511 	return __add_used_map(env, map);
20512 }
20513 
20514 /* find and rewrite pseudo imm in ld_imm64 instructions:
20515  *
20516  * 1. if it accesses map FD, replace it with actual map pointer.
20517  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
20518  *
20519  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
20520  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)20521 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
20522 {
20523 	struct bpf_insn *insn = env->prog->insnsi;
20524 	int insn_cnt = env->prog->len;
20525 	int i, err;
20526 
20527 	err = bpf_prog_calc_tag(env->prog);
20528 	if (err)
20529 		return err;
20530 
20531 	for (i = 0; i < insn_cnt; i++, insn++) {
20532 		if (BPF_CLASS(insn->code) == BPF_LDX &&
20533 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
20534 		    insn->imm != 0)) {
20535 			verbose(env, "BPF_LDX uses reserved fields\n");
20536 			return -EINVAL;
20537 		}
20538 
20539 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
20540 			struct bpf_insn_aux_data *aux;
20541 			struct bpf_map *map;
20542 			int map_idx;
20543 			u64 addr;
20544 			u32 fd;
20545 
20546 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
20547 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
20548 			    insn[1].off != 0) {
20549 				verbose(env, "invalid bpf_ld_imm64 insn\n");
20550 				return -EINVAL;
20551 			}
20552 
20553 			if (insn[0].src_reg == 0)
20554 				/* valid generic load 64-bit imm */
20555 				goto next_insn;
20556 
20557 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
20558 				aux = &env->insn_aux_data[i];
20559 				err = check_pseudo_btf_id(env, insn, aux);
20560 				if (err)
20561 					return err;
20562 				goto next_insn;
20563 			}
20564 
20565 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
20566 				aux = &env->insn_aux_data[i];
20567 				aux->ptr_type = PTR_TO_FUNC;
20568 				goto next_insn;
20569 			}
20570 
20571 			/* In final convert_pseudo_ld_imm64() step, this is
20572 			 * converted into regular 64-bit imm load insn.
20573 			 */
20574 			switch (insn[0].src_reg) {
20575 			case BPF_PSEUDO_MAP_VALUE:
20576 			case BPF_PSEUDO_MAP_IDX_VALUE:
20577 				break;
20578 			case BPF_PSEUDO_MAP_FD:
20579 			case BPF_PSEUDO_MAP_IDX:
20580 				if (insn[1].imm == 0)
20581 					break;
20582 				fallthrough;
20583 			default:
20584 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
20585 				return -EINVAL;
20586 			}
20587 
20588 			switch (insn[0].src_reg) {
20589 			case BPF_PSEUDO_MAP_IDX_VALUE:
20590 			case BPF_PSEUDO_MAP_IDX:
20591 				if (bpfptr_is_null(env->fd_array)) {
20592 					verbose(env, "fd_idx without fd_array is invalid\n");
20593 					return -EPROTO;
20594 				}
20595 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
20596 							    insn[0].imm * sizeof(fd),
20597 							    sizeof(fd)))
20598 					return -EFAULT;
20599 				break;
20600 			default:
20601 				fd = insn[0].imm;
20602 				break;
20603 			}
20604 
20605 			map_idx = add_used_map(env, fd);
20606 			if (map_idx < 0)
20607 				return map_idx;
20608 			map = env->used_maps[map_idx];
20609 
20610 			aux = &env->insn_aux_data[i];
20611 			aux->map_index = map_idx;
20612 
20613 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
20614 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
20615 				addr = (unsigned long)map;
20616 			} else {
20617 				u32 off = insn[1].imm;
20618 
20619 				if (off >= BPF_MAX_VAR_OFF) {
20620 					verbose(env, "direct value offset of %u is not allowed\n", off);
20621 					return -EINVAL;
20622 				}
20623 
20624 				if (!map->ops->map_direct_value_addr) {
20625 					verbose(env, "no direct value access support for this map type\n");
20626 					return -EINVAL;
20627 				}
20628 
20629 				err = map->ops->map_direct_value_addr(map, &addr, off);
20630 				if (err) {
20631 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
20632 						map->value_size, off);
20633 					return err;
20634 				}
20635 
20636 				aux->map_off = off;
20637 				addr += off;
20638 			}
20639 
20640 			insn[0].imm = (u32)addr;
20641 			insn[1].imm = addr >> 32;
20642 
20643 next_insn:
20644 			insn++;
20645 			i++;
20646 			continue;
20647 		}
20648 
20649 		/* Basic sanity check before we invest more work here. */
20650 		if (!bpf_opcode_in_insntable(insn->code)) {
20651 			verbose(env, "unknown opcode %02x\n", insn->code);
20652 			return -EINVAL;
20653 		}
20654 	}
20655 
20656 	/* now all pseudo BPF_LD_IMM64 instructions load valid
20657 	 * 'struct bpf_map *' into a register instead of user map_fd.
20658 	 * These pointers will be used later by verifier to validate map access.
20659 	 */
20660 	return 0;
20661 }
20662 
20663 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)20664 static void release_maps(struct bpf_verifier_env *env)
20665 {
20666 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
20667 			     env->used_map_cnt);
20668 }
20669 
20670 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)20671 static void release_btfs(struct bpf_verifier_env *env)
20672 {
20673 	__bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
20674 }
20675 
20676 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)20677 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
20678 {
20679 	struct bpf_insn *insn = env->prog->insnsi;
20680 	int insn_cnt = env->prog->len;
20681 	int i;
20682 
20683 	for (i = 0; i < insn_cnt; i++, insn++) {
20684 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
20685 			continue;
20686 		if (insn->src_reg == BPF_PSEUDO_FUNC)
20687 			continue;
20688 		insn->src_reg = 0;
20689 	}
20690 }
20691 
20692 /* single env->prog->insni[off] instruction was replaced with the range
20693  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
20694  * [0, off) and [off, end) to new locations, so the patched range stays zero
20695  */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_prog * new_prog,u32 off,u32 cnt)20696 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
20697 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
20698 {
20699 	struct bpf_insn_aux_data *data = env->insn_aux_data;
20700 	struct bpf_insn *insn = new_prog->insnsi;
20701 	u32 old_seen = data[off].seen;
20702 	u32 prog_len;
20703 	int i;
20704 
20705 	/* aux info at OFF always needs adjustment, no matter fast path
20706 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
20707 	 * original insn at old prog.
20708 	 */
20709 	data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
20710 
20711 	if (cnt == 1)
20712 		return;
20713 	prog_len = new_prog->len;
20714 
20715 	memmove(data + off + cnt - 1, data + off,
20716 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
20717 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
20718 	for (i = off; i < off + cnt - 1; i++) {
20719 		/* Expand insni[off]'s seen count to the patched range. */
20720 		data[i].seen = old_seen;
20721 		data[i].zext_dst = insn_has_def32(insn + i);
20722 	}
20723 }
20724 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)20725 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
20726 {
20727 	int i;
20728 
20729 	if (len == 1)
20730 		return;
20731 	/* NOTE: fake 'exit' subprog should be updated as well. */
20732 	for (i = 0; i <= env->subprog_cnt; i++) {
20733 		if (env->subprog_info[i].start <= off)
20734 			continue;
20735 		env->subprog_info[i].start += len - 1;
20736 	}
20737 }
20738 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)20739 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
20740 {
20741 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
20742 	int i, sz = prog->aux->size_poke_tab;
20743 	struct bpf_jit_poke_descriptor *desc;
20744 
20745 	for (i = 0; i < sz; i++) {
20746 		desc = &tab[i];
20747 		if (desc->insn_idx <= off)
20748 			continue;
20749 		desc->insn_idx += len - 1;
20750 	}
20751 }
20752 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)20753 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
20754 					    const struct bpf_insn *patch, u32 len)
20755 {
20756 	struct bpf_prog *new_prog;
20757 	struct bpf_insn_aux_data *new_data = NULL;
20758 
20759 	if (len > 1) {
20760 		new_data = vrealloc(env->insn_aux_data,
20761 				    array_size(env->prog->len + len - 1,
20762 					       sizeof(struct bpf_insn_aux_data)),
20763 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
20764 		if (!new_data)
20765 			return NULL;
20766 
20767 		env->insn_aux_data = new_data;
20768 	}
20769 
20770 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
20771 	if (IS_ERR(new_prog)) {
20772 		if (PTR_ERR(new_prog) == -ERANGE)
20773 			verbose(env,
20774 				"insn %d cannot be patched due to 16-bit range\n",
20775 				env->insn_aux_data[off].orig_idx);
20776 		return NULL;
20777 	}
20778 	adjust_insn_aux_data(env, new_prog, off, len);
20779 	adjust_subprog_starts(env, off, len);
20780 	adjust_poke_descs(new_prog, off, len);
20781 	return new_prog;
20782 }
20783 
20784 /*
20785  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
20786  * jump offset by 'delta'.
20787  */
adjust_jmp_off(struct bpf_prog * prog,u32 tgt_idx,u32 delta)20788 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
20789 {
20790 	struct bpf_insn *insn = prog->insnsi;
20791 	u32 insn_cnt = prog->len, i;
20792 	s32 imm;
20793 	s16 off;
20794 
20795 	for (i = 0; i < insn_cnt; i++, insn++) {
20796 		u8 code = insn->code;
20797 
20798 		if (tgt_idx <= i && i < tgt_idx + delta)
20799 			continue;
20800 
20801 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
20802 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
20803 			continue;
20804 
20805 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
20806 			if (i + 1 + insn->imm != tgt_idx)
20807 				continue;
20808 			if (check_add_overflow(insn->imm, delta, &imm))
20809 				return -ERANGE;
20810 			insn->imm = imm;
20811 		} else {
20812 			if (i + 1 + insn->off != tgt_idx)
20813 				continue;
20814 			if (check_add_overflow(insn->off, delta, &off))
20815 				return -ERANGE;
20816 			insn->off = off;
20817 		}
20818 	}
20819 	return 0;
20820 }
20821 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)20822 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
20823 					      u32 off, u32 cnt)
20824 {
20825 	int i, j;
20826 
20827 	/* find first prog starting at or after off (first to remove) */
20828 	for (i = 0; i < env->subprog_cnt; i++)
20829 		if (env->subprog_info[i].start >= off)
20830 			break;
20831 	/* find first prog starting at or after off + cnt (first to stay) */
20832 	for (j = i; j < env->subprog_cnt; j++)
20833 		if (env->subprog_info[j].start >= off + cnt)
20834 			break;
20835 	/* if j doesn't start exactly at off + cnt, we are just removing
20836 	 * the front of previous prog
20837 	 */
20838 	if (env->subprog_info[j].start != off + cnt)
20839 		j--;
20840 
20841 	if (j > i) {
20842 		struct bpf_prog_aux *aux = env->prog->aux;
20843 		int move;
20844 
20845 		/* move fake 'exit' subprog as well */
20846 		move = env->subprog_cnt + 1 - j;
20847 
20848 		memmove(env->subprog_info + i,
20849 			env->subprog_info + j,
20850 			sizeof(*env->subprog_info) * move);
20851 		env->subprog_cnt -= j - i;
20852 
20853 		/* remove func_info */
20854 		if (aux->func_info) {
20855 			move = aux->func_info_cnt - j;
20856 
20857 			memmove(aux->func_info + i,
20858 				aux->func_info + j,
20859 				sizeof(*aux->func_info) * move);
20860 			aux->func_info_cnt -= j - i;
20861 			/* func_info->insn_off is set after all code rewrites,
20862 			 * in adjust_btf_func() - no need to adjust
20863 			 */
20864 		}
20865 	} else {
20866 		/* convert i from "first prog to remove" to "first to adjust" */
20867 		if (env->subprog_info[i].start == off)
20868 			i++;
20869 	}
20870 
20871 	/* update fake 'exit' subprog as well */
20872 	for (; i <= env->subprog_cnt; i++)
20873 		env->subprog_info[i].start -= cnt;
20874 
20875 	return 0;
20876 }
20877 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)20878 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
20879 				      u32 cnt)
20880 {
20881 	struct bpf_prog *prog = env->prog;
20882 	u32 i, l_off, l_cnt, nr_linfo;
20883 	struct bpf_line_info *linfo;
20884 
20885 	nr_linfo = prog->aux->nr_linfo;
20886 	if (!nr_linfo)
20887 		return 0;
20888 
20889 	linfo = prog->aux->linfo;
20890 
20891 	/* find first line info to remove, count lines to be removed */
20892 	for (i = 0; i < nr_linfo; i++)
20893 		if (linfo[i].insn_off >= off)
20894 			break;
20895 
20896 	l_off = i;
20897 	l_cnt = 0;
20898 	for (; i < nr_linfo; i++)
20899 		if (linfo[i].insn_off < off + cnt)
20900 			l_cnt++;
20901 		else
20902 			break;
20903 
20904 	/* First live insn doesn't match first live linfo, it needs to "inherit"
20905 	 * last removed linfo.  prog is already modified, so prog->len == off
20906 	 * means no live instructions after (tail of the program was removed).
20907 	 */
20908 	if (prog->len != off && l_cnt &&
20909 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
20910 		l_cnt--;
20911 		linfo[--i].insn_off = off + cnt;
20912 	}
20913 
20914 	/* remove the line info which refer to the removed instructions */
20915 	if (l_cnt) {
20916 		memmove(linfo + l_off, linfo + i,
20917 			sizeof(*linfo) * (nr_linfo - i));
20918 
20919 		prog->aux->nr_linfo -= l_cnt;
20920 		nr_linfo = prog->aux->nr_linfo;
20921 	}
20922 
20923 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
20924 	for (i = l_off; i < nr_linfo; i++)
20925 		linfo[i].insn_off -= cnt;
20926 
20927 	/* fix up all subprogs (incl. 'exit') which start >= off */
20928 	for (i = 0; i <= env->subprog_cnt; i++)
20929 		if (env->subprog_info[i].linfo_idx > l_off) {
20930 			/* program may have started in the removed region but
20931 			 * may not be fully removed
20932 			 */
20933 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
20934 				env->subprog_info[i].linfo_idx -= l_cnt;
20935 			else
20936 				env->subprog_info[i].linfo_idx = l_off;
20937 		}
20938 
20939 	return 0;
20940 }
20941 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)20942 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
20943 {
20944 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20945 	unsigned int orig_prog_len = env->prog->len;
20946 	int err;
20947 
20948 	if (bpf_prog_is_offloaded(env->prog->aux))
20949 		bpf_prog_offload_remove_insns(env, off, cnt);
20950 
20951 	err = bpf_remove_insns(env->prog, off, cnt);
20952 	if (err)
20953 		return err;
20954 
20955 	err = adjust_subprog_starts_after_remove(env, off, cnt);
20956 	if (err)
20957 		return err;
20958 
20959 	err = bpf_adj_linfo_after_remove(env, off, cnt);
20960 	if (err)
20961 		return err;
20962 
20963 	memmove(aux_data + off,	aux_data + off + cnt,
20964 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
20965 
20966 	return 0;
20967 }
20968 
20969 /* The verifier does more data flow analysis than llvm and will not
20970  * explore branches that are dead at run time. Malicious programs can
20971  * have dead code too. Therefore replace all dead at-run-time code
20972  * with 'ja -1'.
20973  *
20974  * Just nops are not optimal, e.g. if they would sit at the end of the
20975  * program and through another bug we would manage to jump there, then
20976  * we'd execute beyond program memory otherwise. Returning exception
20977  * code also wouldn't work since we can have subprogs where the dead
20978  * code could be located.
20979  */
sanitize_dead_code(struct bpf_verifier_env * env)20980 static void sanitize_dead_code(struct bpf_verifier_env *env)
20981 {
20982 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
20983 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
20984 	struct bpf_insn *insn = env->prog->insnsi;
20985 	const int insn_cnt = env->prog->len;
20986 	int i;
20987 
20988 	for (i = 0; i < insn_cnt; i++) {
20989 		if (aux_data[i].seen)
20990 			continue;
20991 		memcpy(insn + i, &trap, sizeof(trap));
20992 		aux_data[i].zext_dst = false;
20993 	}
20994 }
20995 
insn_is_cond_jump(u8 code)20996 static bool insn_is_cond_jump(u8 code)
20997 {
20998 	u8 op;
20999 
21000 	op = BPF_OP(code);
21001 	if (BPF_CLASS(code) == BPF_JMP32)
21002 		return op != BPF_JA;
21003 
21004 	if (BPF_CLASS(code) != BPF_JMP)
21005 		return false;
21006 
21007 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21008 }
21009 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)21010 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21011 {
21012 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21013 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21014 	struct bpf_insn *insn = env->prog->insnsi;
21015 	const int insn_cnt = env->prog->len;
21016 	int i;
21017 
21018 	for (i = 0; i < insn_cnt; i++, insn++) {
21019 		if (!insn_is_cond_jump(insn->code))
21020 			continue;
21021 
21022 		if (!aux_data[i + 1].seen)
21023 			ja.off = insn->off;
21024 		else if (!aux_data[i + 1 + insn->off].seen)
21025 			ja.off = 0;
21026 		else
21027 			continue;
21028 
21029 		if (bpf_prog_is_offloaded(env->prog->aux))
21030 			bpf_prog_offload_replace_insn(env, i, &ja);
21031 
21032 		memcpy(insn, &ja, sizeof(ja));
21033 	}
21034 }
21035 
opt_remove_dead_code(struct bpf_verifier_env * env)21036 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21037 {
21038 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21039 	int insn_cnt = env->prog->len;
21040 	int i, err;
21041 
21042 	for (i = 0; i < insn_cnt; i++) {
21043 		int j;
21044 
21045 		j = 0;
21046 		while (i + j < insn_cnt && !aux_data[i + j].seen)
21047 			j++;
21048 		if (!j)
21049 			continue;
21050 
21051 		err = verifier_remove_insns(env, i, j);
21052 		if (err)
21053 			return err;
21054 		insn_cnt = env->prog->len;
21055 	}
21056 
21057 	return 0;
21058 }
21059 
21060 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21061 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21062 
opt_remove_nops(struct bpf_verifier_env * env)21063 static int opt_remove_nops(struct bpf_verifier_env *env)
21064 {
21065 	struct bpf_insn *insn = env->prog->insnsi;
21066 	int insn_cnt = env->prog->len;
21067 	bool is_may_goto_0, is_ja;
21068 	int i, err;
21069 
21070 	for (i = 0; i < insn_cnt; i++) {
21071 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21072 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21073 
21074 		if (!is_may_goto_0 && !is_ja)
21075 			continue;
21076 
21077 		err = verifier_remove_insns(env, i, 1);
21078 		if (err)
21079 			return err;
21080 		insn_cnt--;
21081 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21082 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21083 	}
21084 
21085 	return 0;
21086 }
21087 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)21088 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21089 					 const union bpf_attr *attr)
21090 {
21091 	struct bpf_insn *patch;
21092 	/* use env->insn_buf as two independent buffers */
21093 	struct bpf_insn *zext_patch = env->insn_buf;
21094 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21095 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
21096 	int i, patch_len, delta = 0, len = env->prog->len;
21097 	struct bpf_insn *insns = env->prog->insnsi;
21098 	struct bpf_prog *new_prog;
21099 	bool rnd_hi32;
21100 
21101 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21102 	zext_patch[1] = BPF_ZEXT_REG(0);
21103 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21104 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21105 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21106 	for (i = 0; i < len; i++) {
21107 		int adj_idx = i + delta;
21108 		struct bpf_insn insn;
21109 		int load_reg;
21110 
21111 		insn = insns[adj_idx];
21112 		load_reg = insn_def_regno(&insn);
21113 		if (!aux[adj_idx].zext_dst) {
21114 			u8 code, class;
21115 			u32 imm_rnd;
21116 
21117 			if (!rnd_hi32)
21118 				continue;
21119 
21120 			code = insn.code;
21121 			class = BPF_CLASS(code);
21122 			if (load_reg == -1)
21123 				continue;
21124 
21125 			/* NOTE: arg "reg" (the fourth one) is only used for
21126 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
21127 			 *       here.
21128 			 */
21129 			if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21130 				if (class == BPF_LD &&
21131 				    BPF_MODE(code) == BPF_IMM)
21132 					i++;
21133 				continue;
21134 			}
21135 
21136 			/* ctx load could be transformed into wider load. */
21137 			if (class == BPF_LDX &&
21138 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
21139 				continue;
21140 
21141 			imm_rnd = get_random_u32();
21142 			rnd_hi32_patch[0] = insn;
21143 			rnd_hi32_patch[1].imm = imm_rnd;
21144 			rnd_hi32_patch[3].dst_reg = load_reg;
21145 			patch = rnd_hi32_patch;
21146 			patch_len = 4;
21147 			goto apply_patch_buffer;
21148 		}
21149 
21150 		/* Add in an zero-extend instruction if a) the JIT has requested
21151 		 * it or b) it's a CMPXCHG.
21152 		 *
21153 		 * The latter is because: BPF_CMPXCHG always loads a value into
21154 		 * R0, therefore always zero-extends. However some archs'
21155 		 * equivalent instruction only does this load when the
21156 		 * comparison is successful. This detail of CMPXCHG is
21157 		 * orthogonal to the general zero-extension behaviour of the
21158 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
21159 		 */
21160 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21161 			continue;
21162 
21163 		/* Zero-extension is done by the caller. */
21164 		if (bpf_pseudo_kfunc_call(&insn))
21165 			continue;
21166 
21167 		if (verifier_bug_if(load_reg == -1, env,
21168 				    "zext_dst is set, but no reg is defined"))
21169 			return -EFAULT;
21170 
21171 		zext_patch[0] = insn;
21172 		zext_patch[1].dst_reg = load_reg;
21173 		zext_patch[1].src_reg = load_reg;
21174 		patch = zext_patch;
21175 		patch_len = 2;
21176 apply_patch_buffer:
21177 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21178 		if (!new_prog)
21179 			return -ENOMEM;
21180 		env->prog = new_prog;
21181 		insns = new_prog->insnsi;
21182 		aux = env->insn_aux_data;
21183 		delta += patch_len - 1;
21184 	}
21185 
21186 	return 0;
21187 }
21188 
21189 /* convert load instructions that access fields of a context type into a
21190  * sequence of instructions that access fields of the underlying structure:
21191  *     struct __sk_buff    -> struct sk_buff
21192  *     struct bpf_sock_ops -> struct sock
21193  */
convert_ctx_accesses(struct bpf_verifier_env * env)21194 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21195 {
21196 	struct bpf_subprog_info *subprogs = env->subprog_info;
21197 	const struct bpf_verifier_ops *ops = env->ops;
21198 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21199 	const int insn_cnt = env->prog->len;
21200 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
21201 	struct bpf_insn *insn_buf = env->insn_buf;
21202 	struct bpf_insn *insn;
21203 	u32 target_size, size_default, off;
21204 	struct bpf_prog *new_prog;
21205 	enum bpf_access_type type;
21206 	bool is_narrower_load;
21207 	int epilogue_idx = 0;
21208 
21209 	if (ops->gen_epilogue) {
21210 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21211 						 -(subprogs[0].stack_depth + 8));
21212 		if (epilogue_cnt >= INSN_BUF_SIZE) {
21213 			verifier_bug(env, "epilogue is too long");
21214 			return -EFAULT;
21215 		} else if (epilogue_cnt) {
21216 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
21217 			cnt = 0;
21218 			subprogs[0].stack_depth += 8;
21219 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21220 						      -subprogs[0].stack_depth);
21221 			insn_buf[cnt++] = env->prog->insnsi[0];
21222 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21223 			if (!new_prog)
21224 				return -ENOMEM;
21225 			env->prog = new_prog;
21226 			delta += cnt - 1;
21227 
21228 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21229 			if (ret < 0)
21230 				return ret;
21231 		}
21232 	}
21233 
21234 	if (ops->gen_prologue || env->seen_direct_write) {
21235 		if (!ops->gen_prologue) {
21236 			verifier_bug(env, "gen_prologue is null");
21237 			return -EFAULT;
21238 		}
21239 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21240 					env->prog);
21241 		if (cnt >= INSN_BUF_SIZE) {
21242 			verifier_bug(env, "prologue is too long");
21243 			return -EFAULT;
21244 		} else if (cnt) {
21245 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21246 			if (!new_prog)
21247 				return -ENOMEM;
21248 
21249 			env->prog = new_prog;
21250 			delta += cnt - 1;
21251 
21252 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21253 			if (ret < 0)
21254 				return ret;
21255 		}
21256 	}
21257 
21258 	if (delta)
21259 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21260 
21261 	if (bpf_prog_is_offloaded(env->prog->aux))
21262 		return 0;
21263 
21264 	insn = env->prog->insnsi + delta;
21265 
21266 	for (i = 0; i < insn_cnt; i++, insn++) {
21267 		bpf_convert_ctx_access_t convert_ctx_access;
21268 		u8 mode;
21269 
21270 		if (env->insn_aux_data[i + delta].nospec) {
21271 			WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21272 			struct bpf_insn *patch = insn_buf;
21273 
21274 			*patch++ = BPF_ST_NOSPEC();
21275 			*patch++ = *insn;
21276 			cnt = patch - insn_buf;
21277 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21278 			if (!new_prog)
21279 				return -ENOMEM;
21280 
21281 			delta    += cnt - 1;
21282 			env->prog = new_prog;
21283 			insn      = new_prog->insnsi + i + delta;
21284 			/* This can not be easily merged with the
21285 			 * nospec_result-case, because an insn may require a
21286 			 * nospec before and after itself. Therefore also do not
21287 			 * 'continue' here but potentially apply further
21288 			 * patching to insn. *insn should equal patch[1] now.
21289 			 */
21290 		}
21291 
21292 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21293 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21294 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21295 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21296 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21297 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21298 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21299 			type = BPF_READ;
21300 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21301 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21302 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21303 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21304 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21305 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21306 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21307 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21308 			type = BPF_WRITE;
21309 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21310 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21311 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21312 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21313 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21314 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21315 			env->prog->aux->num_exentries++;
21316 			continue;
21317 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21318 			   epilogue_cnt &&
21319 			   i + delta < subprogs[1].start) {
21320 			/* Generate epilogue for the main prog */
21321 			if (epilogue_idx) {
21322 				/* jump back to the earlier generated epilogue */
21323 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21324 				cnt = 1;
21325 			} else {
21326 				memcpy(insn_buf, epilogue_buf,
21327 				       epilogue_cnt * sizeof(*epilogue_buf));
21328 				cnt = epilogue_cnt;
21329 				/* epilogue_idx cannot be 0. It must have at
21330 				 * least one ctx ptr saving insn before the
21331 				 * epilogue.
21332 				 */
21333 				epilogue_idx = i + delta;
21334 			}
21335 			goto patch_insn_buf;
21336 		} else {
21337 			continue;
21338 		}
21339 
21340 		if (type == BPF_WRITE &&
21341 		    env->insn_aux_data[i + delta].nospec_result) {
21342 			/* nospec_result is only used to mitigate Spectre v4 and
21343 			 * to limit verification-time for Spectre v1.
21344 			 */
21345 			struct bpf_insn *patch = insn_buf;
21346 
21347 			*patch++ = *insn;
21348 			*patch++ = BPF_ST_NOSPEC();
21349 			cnt = patch - insn_buf;
21350 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21351 			if (!new_prog)
21352 				return -ENOMEM;
21353 
21354 			delta    += cnt - 1;
21355 			env->prog = new_prog;
21356 			insn      = new_prog->insnsi + i + delta;
21357 			continue;
21358 		}
21359 
21360 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21361 		case PTR_TO_CTX:
21362 			if (!ops->convert_ctx_access)
21363 				continue;
21364 			convert_ctx_access = ops->convert_ctx_access;
21365 			break;
21366 		case PTR_TO_SOCKET:
21367 		case PTR_TO_SOCK_COMMON:
21368 			convert_ctx_access = bpf_sock_convert_ctx_access;
21369 			break;
21370 		case PTR_TO_TCP_SOCK:
21371 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21372 			break;
21373 		case PTR_TO_XDP_SOCK:
21374 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21375 			break;
21376 		case PTR_TO_BTF_ID:
21377 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21378 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21379 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21380 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21381 		 * any faults for loads into such types. BPF_WRITE is disallowed
21382 		 * for this case.
21383 		 */
21384 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21385 		case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21386 			if (type == BPF_READ) {
21387 				if (BPF_MODE(insn->code) == BPF_MEM)
21388 					insn->code = BPF_LDX | BPF_PROBE_MEM |
21389 						     BPF_SIZE((insn)->code);
21390 				else
21391 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21392 						     BPF_SIZE((insn)->code);
21393 				env->prog->aux->num_exentries++;
21394 			}
21395 			continue;
21396 		case PTR_TO_ARENA:
21397 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
21398 				if (!bpf_jit_supports_insn(insn, true)) {
21399 					verbose(env, "sign extending loads from arena are not supported yet\n");
21400 					return -EOPNOTSUPP;
21401 				}
21402 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
21403 			} else {
21404 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21405 			}
21406 			env->prog->aux->num_exentries++;
21407 			continue;
21408 		default:
21409 			continue;
21410 		}
21411 
21412 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21413 		size = BPF_LDST_BYTES(insn);
21414 		mode = BPF_MODE(insn->code);
21415 
21416 		/* If the read access is a narrower load of the field,
21417 		 * convert to a 4/8-byte load, to minimum program type specific
21418 		 * convert_ctx_access changes. If conversion is successful,
21419 		 * we will apply proper mask to the result.
21420 		 */
21421 		is_narrower_load = size < ctx_field_size;
21422 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21423 		off = insn->off;
21424 		if (is_narrower_load) {
21425 			u8 size_code;
21426 
21427 			if (type == BPF_WRITE) {
21428 				verifier_bug(env, "narrow ctx access misconfigured");
21429 				return -EFAULT;
21430 			}
21431 
21432 			size_code = BPF_H;
21433 			if (ctx_field_size == 4)
21434 				size_code = BPF_W;
21435 			else if (ctx_field_size == 8)
21436 				size_code = BPF_DW;
21437 
21438 			insn->off = off & ~(size_default - 1);
21439 			insn->code = BPF_LDX | BPF_MEM | size_code;
21440 		}
21441 
21442 		target_size = 0;
21443 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
21444 					 &target_size);
21445 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
21446 		    (ctx_field_size && !target_size)) {
21447 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
21448 			return -EFAULT;
21449 		}
21450 
21451 		if (is_narrower_load && size < target_size) {
21452 			u8 shift = bpf_ctx_narrow_access_offset(
21453 				off, size, size_default) * 8;
21454 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
21455 				verifier_bug(env, "narrow ctx load misconfigured");
21456 				return -EFAULT;
21457 			}
21458 			if (ctx_field_size <= 4) {
21459 				if (shift)
21460 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
21461 									insn->dst_reg,
21462 									shift);
21463 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21464 								(1 << size * 8) - 1);
21465 			} else {
21466 				if (shift)
21467 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
21468 									insn->dst_reg,
21469 									shift);
21470 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
21471 								(1ULL << size * 8) - 1);
21472 			}
21473 		}
21474 		if (mode == BPF_MEMSX)
21475 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
21476 						       insn->dst_reg, insn->dst_reg,
21477 						       size * 8, 0);
21478 
21479 patch_insn_buf:
21480 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21481 		if (!new_prog)
21482 			return -ENOMEM;
21483 
21484 		delta += cnt - 1;
21485 
21486 		/* keep walking new program and skip insns we just inserted */
21487 		env->prog = new_prog;
21488 		insn      = new_prog->insnsi + i + delta;
21489 	}
21490 
21491 	return 0;
21492 }
21493 
jit_subprogs(struct bpf_verifier_env * env)21494 static int jit_subprogs(struct bpf_verifier_env *env)
21495 {
21496 	struct bpf_prog *prog = env->prog, **func, *tmp;
21497 	int i, j, subprog_start, subprog_end = 0, len, subprog;
21498 	struct bpf_map *map_ptr;
21499 	struct bpf_insn *insn;
21500 	void *old_bpf_func;
21501 	int err, num_exentries;
21502 
21503 	if (env->subprog_cnt <= 1)
21504 		return 0;
21505 
21506 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21507 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
21508 			continue;
21509 
21510 		/* Upon error here we cannot fall back to interpreter but
21511 		 * need a hard reject of the program. Thus -EFAULT is
21512 		 * propagated in any case.
21513 		 */
21514 		subprog = find_subprog(env, i + insn->imm + 1);
21515 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
21516 				    i + insn->imm + 1))
21517 			return -EFAULT;
21518 		/* temporarily remember subprog id inside insn instead of
21519 		 * aux_data, since next loop will split up all insns into funcs
21520 		 */
21521 		insn->off = subprog;
21522 		/* remember original imm in case JIT fails and fallback
21523 		 * to interpreter will be needed
21524 		 */
21525 		env->insn_aux_data[i].call_imm = insn->imm;
21526 		/* point imm to __bpf_call_base+1 from JITs point of view */
21527 		insn->imm = 1;
21528 		if (bpf_pseudo_func(insn)) {
21529 #if defined(MODULES_VADDR)
21530 			u64 addr = MODULES_VADDR;
21531 #else
21532 			u64 addr = VMALLOC_START;
21533 #endif
21534 			/* jit (e.g. x86_64) may emit fewer instructions
21535 			 * if it learns a u32 imm is the same as a u64 imm.
21536 			 * Set close enough to possible prog address.
21537 			 */
21538 			insn[0].imm = (u32)addr;
21539 			insn[1].imm = addr >> 32;
21540 		}
21541 	}
21542 
21543 	err = bpf_prog_alloc_jited_linfo(prog);
21544 	if (err)
21545 		goto out_undo_insn;
21546 
21547 	err = -ENOMEM;
21548 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
21549 	if (!func)
21550 		goto out_undo_insn;
21551 
21552 	for (i = 0; i < env->subprog_cnt; i++) {
21553 		subprog_start = subprog_end;
21554 		subprog_end = env->subprog_info[i + 1].start;
21555 
21556 		len = subprog_end - subprog_start;
21557 		/* bpf_prog_run() doesn't call subprogs directly,
21558 		 * hence main prog stats include the runtime of subprogs.
21559 		 * subprogs don't have IDs and not reachable via prog_get_next_id
21560 		 * func[i]->stats will never be accessed and stays NULL
21561 		 */
21562 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
21563 		if (!func[i])
21564 			goto out_free;
21565 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
21566 		       len * sizeof(struct bpf_insn));
21567 		func[i]->type = prog->type;
21568 		func[i]->len = len;
21569 		if (bpf_prog_calc_tag(func[i]))
21570 			goto out_free;
21571 		func[i]->is_func = 1;
21572 		func[i]->sleepable = prog->sleepable;
21573 		func[i]->aux->func_idx = i;
21574 		/* Below members will be freed only at prog->aux */
21575 		func[i]->aux->btf = prog->aux->btf;
21576 		func[i]->aux->func_info = prog->aux->func_info;
21577 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
21578 		func[i]->aux->poke_tab = prog->aux->poke_tab;
21579 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
21580 		func[i]->aux->main_prog_aux = prog->aux;
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_MEM32SX ||
21612 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
21613 				num_exentries++;
21614 			if ((BPF_CLASS(insn->code) == BPF_STX ||
21615 			     BPF_CLASS(insn->code) == BPF_ST) &&
21616 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
21617 				num_exentries++;
21618 			if (BPF_CLASS(insn->code) == BPF_STX &&
21619 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
21620 				num_exentries++;
21621 		}
21622 		func[i]->aux->num_exentries = num_exentries;
21623 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
21624 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
21625 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
21626 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
21627 		if (!i)
21628 			func[i]->aux->exception_boundary = env->seen_exception;
21629 		func[i] = bpf_int_jit_compile(func[i]);
21630 		if (!func[i]->jited) {
21631 			err = -ENOTSUPP;
21632 			goto out_free;
21633 		}
21634 		cond_resched();
21635 	}
21636 
21637 	/* at this point all bpf functions were successfully JITed
21638 	 * now populate all bpf_calls with correct addresses and
21639 	 * run last pass of JIT
21640 	 */
21641 	for (i = 0; i < env->subprog_cnt; i++) {
21642 		insn = func[i]->insnsi;
21643 		for (j = 0; j < func[i]->len; j++, insn++) {
21644 			if (bpf_pseudo_func(insn)) {
21645 				subprog = insn->off;
21646 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
21647 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
21648 				continue;
21649 			}
21650 			if (!bpf_pseudo_call(insn))
21651 				continue;
21652 			subprog = insn->off;
21653 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
21654 		}
21655 
21656 		/* we use the aux data to keep a list of the start addresses
21657 		 * of the JITed images for each function in the program
21658 		 *
21659 		 * for some architectures, such as powerpc64, the imm field
21660 		 * might not be large enough to hold the offset of the start
21661 		 * address of the callee's JITed image from __bpf_call_base
21662 		 *
21663 		 * in such cases, we can lookup the start address of a callee
21664 		 * by using its subprog id, available from the off field of
21665 		 * the call instruction, as an index for this list
21666 		 */
21667 		func[i]->aux->func = func;
21668 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21669 		func[i]->aux->real_func_cnt = env->subprog_cnt;
21670 	}
21671 	for (i = 0; i < env->subprog_cnt; i++) {
21672 		old_bpf_func = func[i]->bpf_func;
21673 		tmp = bpf_int_jit_compile(func[i]);
21674 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
21675 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
21676 			err = -ENOTSUPP;
21677 			goto out_free;
21678 		}
21679 		cond_resched();
21680 	}
21681 
21682 	/* finally lock prog and jit images for all functions and
21683 	 * populate kallsysm. Begin at the first subprogram, since
21684 	 * bpf_prog_load will add the kallsyms for the main program.
21685 	 */
21686 	for (i = 1; i < env->subprog_cnt; i++) {
21687 		err = bpf_prog_lock_ro(func[i]);
21688 		if (err)
21689 			goto out_free;
21690 	}
21691 
21692 	for (i = 1; i < env->subprog_cnt; i++)
21693 		bpf_prog_kallsyms_add(func[i]);
21694 
21695 	/* Last step: make now unused interpreter insns from main
21696 	 * prog consistent for later dump requests, so they can
21697 	 * later look the same as if they were interpreted only.
21698 	 */
21699 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21700 		if (bpf_pseudo_func(insn)) {
21701 			insn[0].imm = env->insn_aux_data[i].call_imm;
21702 			insn[1].imm = insn->off;
21703 			insn->off = 0;
21704 			continue;
21705 		}
21706 		if (!bpf_pseudo_call(insn))
21707 			continue;
21708 		insn->off = env->insn_aux_data[i].call_imm;
21709 		subprog = find_subprog(env, i + insn->off + 1);
21710 		insn->imm = subprog;
21711 	}
21712 
21713 	prog->jited = 1;
21714 	prog->bpf_func = func[0]->bpf_func;
21715 	prog->jited_len = func[0]->jited_len;
21716 	prog->aux->extable = func[0]->aux->extable;
21717 	prog->aux->num_exentries = func[0]->aux->num_exentries;
21718 	prog->aux->func = func;
21719 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
21720 	prog->aux->real_func_cnt = env->subprog_cnt;
21721 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
21722 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
21723 	bpf_prog_jit_attempt_done(prog);
21724 	return 0;
21725 out_free:
21726 	/* We failed JIT'ing, so at this point we need to unregister poke
21727 	 * descriptors from subprogs, so that kernel is not attempting to
21728 	 * patch it anymore as we're freeing the subprog JIT memory.
21729 	 */
21730 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
21731 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
21732 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
21733 	}
21734 	/* At this point we're guaranteed that poke descriptors are not
21735 	 * live anymore. We can just unlink its descriptor table as it's
21736 	 * released with the main prog.
21737 	 */
21738 	for (i = 0; i < env->subprog_cnt; i++) {
21739 		if (!func[i])
21740 			continue;
21741 		func[i]->aux->poke_tab = NULL;
21742 		bpf_jit_free(func[i]);
21743 	}
21744 	kfree(func);
21745 out_undo_insn:
21746 	/* cleanup main prog to be interpreted */
21747 	prog->jit_requested = 0;
21748 	prog->blinding_requested = 0;
21749 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
21750 		if (!bpf_pseudo_call(insn))
21751 			continue;
21752 		insn->off = 0;
21753 		insn->imm = env->insn_aux_data[i].call_imm;
21754 	}
21755 	bpf_prog_jit_attempt_done(prog);
21756 	return err;
21757 }
21758 
fixup_call_args(struct bpf_verifier_env * env)21759 static int fixup_call_args(struct bpf_verifier_env *env)
21760 {
21761 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21762 	struct bpf_prog *prog = env->prog;
21763 	struct bpf_insn *insn = prog->insnsi;
21764 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
21765 	int i, depth;
21766 #endif
21767 	int err = 0;
21768 
21769 	if (env->prog->jit_requested &&
21770 	    !bpf_prog_is_offloaded(env->prog->aux)) {
21771 		err = jit_subprogs(env);
21772 		if (err == 0)
21773 			return 0;
21774 		if (err == -EFAULT)
21775 			return err;
21776 	}
21777 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
21778 	if (has_kfunc_call) {
21779 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
21780 		return -EINVAL;
21781 	}
21782 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
21783 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
21784 		 * have to be rejected, since interpreter doesn't support them yet.
21785 		 */
21786 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
21787 		return -EINVAL;
21788 	}
21789 	for (i = 0; i < prog->len; i++, insn++) {
21790 		if (bpf_pseudo_func(insn)) {
21791 			/* When JIT fails the progs with callback calls
21792 			 * have to be rejected, since interpreter doesn't support them yet.
21793 			 */
21794 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
21795 			return -EINVAL;
21796 		}
21797 
21798 		if (!bpf_pseudo_call(insn))
21799 			continue;
21800 		depth = get_callee_stack_depth(env, insn, i);
21801 		if (depth < 0)
21802 			return depth;
21803 		bpf_patch_call_args(insn, depth);
21804 	}
21805 	err = 0;
21806 #endif
21807 	return err;
21808 }
21809 
21810 /* 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)21811 static void specialize_kfunc(struct bpf_verifier_env *env,
21812 			     u32 func_id, u16 offset, unsigned long *addr)
21813 {
21814 	struct bpf_prog *prog = env->prog;
21815 	bool seen_direct_write;
21816 	void *xdp_kfunc;
21817 	bool is_rdonly;
21818 
21819 	if (bpf_dev_bound_kfunc_id(func_id)) {
21820 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
21821 		if (xdp_kfunc) {
21822 			*addr = (unsigned long)xdp_kfunc;
21823 			return;
21824 		}
21825 		/* fallback to default kfunc when not supported by netdev */
21826 	}
21827 
21828 	if (offset)
21829 		return;
21830 
21831 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
21832 		seen_direct_write = env->seen_direct_write;
21833 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
21834 
21835 		if (is_rdonly)
21836 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
21837 
21838 		/* restore env->seen_direct_write to its original value, since
21839 		 * may_access_direct_pkt_data mutates it
21840 		 */
21841 		env->seen_direct_write = seen_direct_write;
21842 	}
21843 
21844 	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
21845 	    bpf_lsm_has_d_inode_locked(prog))
21846 		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
21847 
21848 	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
21849 	    bpf_lsm_has_d_inode_locked(prog))
21850 		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
21851 }
21852 
__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)21853 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
21854 					    u16 struct_meta_reg,
21855 					    u16 node_offset_reg,
21856 					    struct bpf_insn *insn,
21857 					    struct bpf_insn *insn_buf,
21858 					    int *cnt)
21859 {
21860 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
21861 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
21862 
21863 	insn_buf[0] = addr[0];
21864 	insn_buf[1] = addr[1];
21865 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
21866 	insn_buf[3] = *insn;
21867 	*cnt = 4;
21868 }
21869 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)21870 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
21871 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
21872 {
21873 	const struct bpf_kfunc_desc *desc;
21874 
21875 	if (!insn->imm) {
21876 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
21877 		return -EINVAL;
21878 	}
21879 
21880 	*cnt = 0;
21881 
21882 	/* insn->imm has the btf func_id. Replace it with an offset relative to
21883 	 * __bpf_call_base, unless the JIT needs to call functions that are
21884 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
21885 	 */
21886 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
21887 	if (!desc) {
21888 		verifier_bug(env, "kernel function descriptor not found for func_id %u",
21889 			     insn->imm);
21890 		return -EFAULT;
21891 	}
21892 
21893 	if (!bpf_jit_supports_far_kfunc_call())
21894 		insn->imm = BPF_CALL_IMM(desc->addr);
21895 	if (insn->off)
21896 		return 0;
21897 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
21898 	    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
21899 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21900 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21901 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
21902 
21903 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
21904 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21905 				     insn_idx);
21906 			return -EFAULT;
21907 		}
21908 
21909 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
21910 		insn_buf[1] = addr[0];
21911 		insn_buf[2] = addr[1];
21912 		insn_buf[3] = *insn;
21913 		*cnt = 4;
21914 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
21915 		   desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
21916 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
21917 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21918 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
21919 
21920 		if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
21921 			verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
21922 				     insn_idx);
21923 			return -EFAULT;
21924 		}
21925 
21926 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
21927 		    !kptr_struct_meta) {
21928 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21929 				     insn_idx);
21930 			return -EFAULT;
21931 		}
21932 
21933 		insn_buf[0] = addr[0];
21934 		insn_buf[1] = addr[1];
21935 		insn_buf[2] = *insn;
21936 		*cnt = 3;
21937 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
21938 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
21939 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21940 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
21941 		int struct_meta_reg = BPF_REG_3;
21942 		int node_offset_reg = BPF_REG_4;
21943 
21944 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
21945 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
21946 			struct_meta_reg = BPF_REG_4;
21947 			node_offset_reg = BPF_REG_5;
21948 		}
21949 
21950 		if (!kptr_struct_meta) {
21951 			verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
21952 				     insn_idx);
21953 			return -EFAULT;
21954 		}
21955 
21956 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
21957 						node_offset_reg, insn, insn_buf, cnt);
21958 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
21959 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
21960 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
21961 		*cnt = 1;
21962 	}
21963 
21964 	if (env->insn_aux_data[insn_idx].arg_prog) {
21965 		u32 regno = env->insn_aux_data[insn_idx].arg_prog;
21966 		struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
21967 		int idx = *cnt;
21968 
21969 		insn_buf[idx++] = ld_addrs[0];
21970 		insn_buf[idx++] = ld_addrs[1];
21971 		insn_buf[idx++] = *insn;
21972 		*cnt = idx;
21973 	}
21974 	return 0;
21975 }
21976 
21977 /* 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)21978 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
21979 {
21980 	struct bpf_subprog_info *info = env->subprog_info;
21981 	int cnt = env->subprog_cnt;
21982 	struct bpf_prog *prog;
21983 
21984 	/* We only reserve one slot for hidden subprogs in subprog_info. */
21985 	if (env->hidden_subprog_cnt) {
21986 		verifier_bug(env, "only one hidden subprog supported");
21987 		return -EFAULT;
21988 	}
21989 	/* We're not patching any existing instruction, just appending the new
21990 	 * ones for the hidden subprog. Hence all of the adjustment operations
21991 	 * in bpf_patch_insn_data are no-ops.
21992 	 */
21993 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
21994 	if (!prog)
21995 		return -ENOMEM;
21996 	env->prog = prog;
21997 	info[cnt + 1].start = info[cnt].start;
21998 	info[cnt].start = prog->len - len + 1;
21999 	env->subprog_cnt++;
22000 	env->hidden_subprog_cnt++;
22001 	return 0;
22002 }
22003 
22004 /* Do various post-verification rewrites in a single program pass.
22005  * These rewrites simplify JIT and interpreter implementations.
22006  */
do_misc_fixups(struct bpf_verifier_env * env)22007 static int do_misc_fixups(struct bpf_verifier_env *env)
22008 {
22009 	struct bpf_prog *prog = env->prog;
22010 	enum bpf_attach_type eatype = prog->expected_attach_type;
22011 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
22012 	struct bpf_insn *insn = prog->insnsi;
22013 	const struct bpf_func_proto *fn;
22014 	const int insn_cnt = prog->len;
22015 	const struct bpf_map_ops *ops;
22016 	struct bpf_insn_aux_data *aux;
22017 	struct bpf_insn *insn_buf = env->insn_buf;
22018 	struct bpf_prog *new_prog;
22019 	struct bpf_map *map_ptr;
22020 	int i, ret, cnt, delta = 0, cur_subprog = 0;
22021 	struct bpf_subprog_info *subprogs = env->subprog_info;
22022 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
22023 	u16 stack_depth_extra = 0;
22024 
22025 	if (env->seen_exception && !env->exception_callback_subprog) {
22026 		struct bpf_insn *patch = insn_buf;
22027 
22028 		*patch++ = env->prog->insnsi[insn_cnt - 1];
22029 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22030 		*patch++ = BPF_EXIT_INSN();
22031 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22032 		if (ret < 0)
22033 			return ret;
22034 		prog = env->prog;
22035 		insn = prog->insnsi;
22036 
22037 		env->exception_callback_subprog = env->subprog_cnt - 1;
22038 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22039 		mark_subprog_exc_cb(env, env->exception_callback_subprog);
22040 	}
22041 
22042 	for (i = 0; i < insn_cnt;) {
22043 		if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22044 			if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22045 			    (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22046 				/* convert to 32-bit mov that clears upper 32-bit */
22047 				insn->code = BPF_ALU | BPF_MOV | BPF_X;
22048 				/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22049 				insn->off = 0;
22050 				insn->imm = 0;
22051 			} /* cast from as(0) to as(1) should be handled by JIT */
22052 			goto next_insn;
22053 		}
22054 
22055 		if (env->insn_aux_data[i + delta].needs_zext)
22056 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22057 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22058 
22059 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22060 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22061 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22062 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22063 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22064 		    insn->off == 1 && insn->imm == -1) {
22065 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22066 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22067 			struct bpf_insn *patch = insn_buf;
22068 
22069 			if (isdiv)
22070 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22071 							BPF_NEG | BPF_K, insn->dst_reg,
22072 							0, 0, 0);
22073 			else
22074 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22075 
22076 			cnt = patch - insn_buf;
22077 
22078 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22079 			if (!new_prog)
22080 				return -ENOMEM;
22081 
22082 			delta    += cnt - 1;
22083 			env->prog = prog = new_prog;
22084 			insn      = new_prog->insnsi + i + delta;
22085 			goto next_insn;
22086 		}
22087 
22088 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22089 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22090 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22091 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22092 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22093 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22094 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22095 			bool is_sdiv = isdiv && insn->off == 1;
22096 			bool is_smod = !isdiv && insn->off == 1;
22097 			struct bpf_insn *patch = insn_buf;
22098 
22099 			if (is_sdiv) {
22100 				/* [R,W]x sdiv 0 -> 0
22101 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
22102 				 * INT_MIN sdiv -1 -> INT_MIN
22103 				 */
22104 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22105 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22106 							BPF_ADD | BPF_K, BPF_REG_AX,
22107 							0, 0, 1);
22108 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22109 							BPF_JGT | BPF_K, BPF_REG_AX,
22110 							0, 4, 1);
22111 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22112 							BPF_JEQ | BPF_K, BPF_REG_AX,
22113 							0, 1, 0);
22114 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22115 							BPF_MOV | BPF_K, insn->dst_reg,
22116 							0, 0, 0);
22117 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22118 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22119 							BPF_NEG | BPF_K, insn->dst_reg,
22120 							0, 0, 0);
22121 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22122 				*patch++ = *insn;
22123 				cnt = patch - insn_buf;
22124 			} else if (is_smod) {
22125 				/* [R,W]x mod 0 -> [R,W]x */
22126 				/* [R,W]x mod -1 -> 0 */
22127 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22128 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22129 							BPF_ADD | BPF_K, BPF_REG_AX,
22130 							0, 0, 1);
22131 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22132 							BPF_JGT | BPF_K, BPF_REG_AX,
22133 							0, 3, 1);
22134 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22135 							BPF_JEQ | BPF_K, BPF_REG_AX,
22136 							0, 3 + (is64 ? 0 : 1), 1);
22137 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22138 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22139 				*patch++ = *insn;
22140 
22141 				if (!is64) {
22142 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22143 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22144 				}
22145 				cnt = patch - insn_buf;
22146 			} else if (isdiv) {
22147 				/* [R,W]x div 0 -> 0 */
22148 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22149 							BPF_JNE | BPF_K, insn->src_reg,
22150 							0, 2, 0);
22151 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22152 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22153 				*patch++ = *insn;
22154 				cnt = patch - insn_buf;
22155 			} else {
22156 				/* [R,W]x mod 0 -> [R,W]x */
22157 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22158 							BPF_JEQ | BPF_K, insn->src_reg,
22159 							0, 1 + (is64 ? 0 : 1), 0);
22160 				*patch++ = *insn;
22161 
22162 				if (!is64) {
22163 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22164 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22165 				}
22166 				cnt = patch - insn_buf;
22167 			}
22168 
22169 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22170 			if (!new_prog)
22171 				return -ENOMEM;
22172 
22173 			delta    += cnt - 1;
22174 			env->prog = prog = new_prog;
22175 			insn      = new_prog->insnsi + i + delta;
22176 			goto next_insn;
22177 		}
22178 
22179 		/* Make it impossible to de-reference a userspace address */
22180 		if (BPF_CLASS(insn->code) == BPF_LDX &&
22181 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22182 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22183 			struct bpf_insn *patch = insn_buf;
22184 			u64 uaddress_limit = bpf_arch_uaddress_limit();
22185 
22186 			if (!uaddress_limit)
22187 				goto next_insn;
22188 
22189 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22190 			if (insn->off)
22191 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22192 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22193 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22194 			*patch++ = *insn;
22195 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22196 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22197 
22198 			cnt = patch - insn_buf;
22199 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22200 			if (!new_prog)
22201 				return -ENOMEM;
22202 
22203 			delta    += cnt - 1;
22204 			env->prog = prog = new_prog;
22205 			insn      = new_prog->insnsi + i + delta;
22206 			goto next_insn;
22207 		}
22208 
22209 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22210 		if (BPF_CLASS(insn->code) == BPF_LD &&
22211 		    (BPF_MODE(insn->code) == BPF_ABS ||
22212 		     BPF_MODE(insn->code) == BPF_IND)) {
22213 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
22214 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22215 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
22216 				return -EFAULT;
22217 			}
22218 
22219 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22220 			if (!new_prog)
22221 				return -ENOMEM;
22222 
22223 			delta    += cnt - 1;
22224 			env->prog = prog = new_prog;
22225 			insn      = new_prog->insnsi + i + delta;
22226 			goto next_insn;
22227 		}
22228 
22229 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
22230 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22231 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22232 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22233 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22234 			struct bpf_insn *patch = insn_buf;
22235 			bool issrc, isneg, isimm;
22236 			u32 off_reg;
22237 
22238 			aux = &env->insn_aux_data[i + delta];
22239 			if (!aux->alu_state ||
22240 			    aux->alu_state == BPF_ALU_NON_POINTER)
22241 				goto next_insn;
22242 
22243 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22244 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22245 				BPF_ALU_SANITIZE_SRC;
22246 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22247 
22248 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
22249 			if (isimm) {
22250 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22251 			} else {
22252 				if (isneg)
22253 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22254 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22255 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22256 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22257 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22258 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22259 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22260 			}
22261 			if (!issrc)
22262 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22263 			insn->src_reg = BPF_REG_AX;
22264 			if (isneg)
22265 				insn->code = insn->code == code_add ?
22266 					     code_sub : code_add;
22267 			*patch++ = *insn;
22268 			if (issrc && isneg && !isimm)
22269 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22270 			cnt = patch - insn_buf;
22271 
22272 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22273 			if (!new_prog)
22274 				return -ENOMEM;
22275 
22276 			delta    += cnt - 1;
22277 			env->prog = prog = new_prog;
22278 			insn      = new_prog->insnsi + i + delta;
22279 			goto next_insn;
22280 		}
22281 
22282 		if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22283 			int stack_off_cnt = -stack_depth - 16;
22284 
22285 			/*
22286 			 * Two 8 byte slots, depth-16 stores the count, and
22287 			 * depth-8 stores the start timestamp of the loop.
22288 			 *
22289 			 * The starting value of count is BPF_MAX_TIMED_LOOPS
22290 			 * (0xffff).  Every iteration loads it and subs it by 1,
22291 			 * until the value becomes 0 in AX (thus, 1 in stack),
22292 			 * after which we call arch_bpf_timed_may_goto, which
22293 			 * either sets AX to 0xffff to keep looping, or to 0
22294 			 * upon timeout. AX is then stored into the stack. In
22295 			 * the next iteration, we either see 0 and break out, or
22296 			 * continue iterating until the next time value is 0
22297 			 * after subtraction, rinse and repeat.
22298 			 */
22299 			stack_depth_extra = 16;
22300 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22301 			if (insn->off >= 0)
22302 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22303 			else
22304 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22305 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22306 			insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22307 			/*
22308 			 * AX is used as an argument to pass in stack_off_cnt
22309 			 * (to add to r10/fp), and also as the return value of
22310 			 * the call to arch_bpf_timed_may_goto.
22311 			 */
22312 			insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22313 			insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22314 			insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22315 			cnt = 7;
22316 
22317 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22318 			if (!new_prog)
22319 				return -ENOMEM;
22320 
22321 			delta += cnt - 1;
22322 			env->prog = prog = new_prog;
22323 			insn = new_prog->insnsi + i + delta;
22324 			goto next_insn;
22325 		} else if (is_may_goto_insn(insn)) {
22326 			int stack_off = -stack_depth - 8;
22327 
22328 			stack_depth_extra = 8;
22329 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22330 			if (insn->off >= 0)
22331 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22332 			else
22333 				insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22334 			insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22335 			insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22336 			cnt = 4;
22337 
22338 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22339 			if (!new_prog)
22340 				return -ENOMEM;
22341 
22342 			delta += cnt - 1;
22343 			env->prog = prog = new_prog;
22344 			insn = new_prog->insnsi + i + delta;
22345 			goto next_insn;
22346 		}
22347 
22348 		if (insn->code != (BPF_JMP | BPF_CALL))
22349 			goto next_insn;
22350 		if (insn->src_reg == BPF_PSEUDO_CALL)
22351 			goto next_insn;
22352 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22353 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22354 			if (ret)
22355 				return ret;
22356 			if (cnt == 0)
22357 				goto next_insn;
22358 
22359 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22360 			if (!new_prog)
22361 				return -ENOMEM;
22362 
22363 			delta	 += cnt - 1;
22364 			env->prog = prog = new_prog;
22365 			insn	  = new_prog->insnsi + i + delta;
22366 			goto next_insn;
22367 		}
22368 
22369 		/* Skip inlining the helper call if the JIT does it. */
22370 		if (bpf_jit_inlines_helper_call(insn->imm))
22371 			goto next_insn;
22372 
22373 		if (insn->imm == BPF_FUNC_get_route_realm)
22374 			prog->dst_needed = 1;
22375 		if (insn->imm == BPF_FUNC_get_prandom_u32)
22376 			bpf_user_rnd_init_once();
22377 		if (insn->imm == BPF_FUNC_override_return)
22378 			prog->kprobe_override = 1;
22379 		if (insn->imm == BPF_FUNC_tail_call) {
22380 			/* If we tail call into other programs, we
22381 			 * cannot make any assumptions since they can
22382 			 * be replaced dynamically during runtime in
22383 			 * the program array.
22384 			 */
22385 			prog->cb_access = 1;
22386 			if (!allow_tail_call_in_subprogs(env))
22387 				prog->aux->stack_depth = MAX_BPF_STACK;
22388 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22389 
22390 			/* mark bpf_tail_call as different opcode to avoid
22391 			 * conditional branch in the interpreter for every normal
22392 			 * call and to prevent accidental JITing by JIT compiler
22393 			 * that doesn't support bpf_tail_call yet
22394 			 */
22395 			insn->imm = 0;
22396 			insn->code = BPF_JMP | BPF_TAIL_CALL;
22397 
22398 			aux = &env->insn_aux_data[i + delta];
22399 			if (env->bpf_capable && !prog->blinding_requested &&
22400 			    prog->jit_requested &&
22401 			    !bpf_map_key_poisoned(aux) &&
22402 			    !bpf_map_ptr_poisoned(aux) &&
22403 			    !bpf_map_ptr_unpriv(aux)) {
22404 				struct bpf_jit_poke_descriptor desc = {
22405 					.reason = BPF_POKE_REASON_TAIL_CALL,
22406 					.tail_call.map = aux->map_ptr_state.map_ptr,
22407 					.tail_call.key = bpf_map_key_immediate(aux),
22408 					.insn_idx = i + delta,
22409 				};
22410 
22411 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
22412 				if (ret < 0) {
22413 					verbose(env, "adding tail call poke descriptor failed\n");
22414 					return ret;
22415 				}
22416 
22417 				insn->imm = ret + 1;
22418 				goto next_insn;
22419 			}
22420 
22421 			if (!bpf_map_ptr_unpriv(aux))
22422 				goto next_insn;
22423 
22424 			/* instead of changing every JIT dealing with tail_call
22425 			 * emit two extra insns:
22426 			 * if (index >= max_entries) goto out;
22427 			 * index &= array->index_mask;
22428 			 * to avoid out-of-bounds cpu speculation
22429 			 */
22430 			if (bpf_map_ptr_poisoned(aux)) {
22431 				verbose(env, "tail_call abusing map_ptr\n");
22432 				return -EINVAL;
22433 			}
22434 
22435 			map_ptr = aux->map_ptr_state.map_ptr;
22436 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
22437 						  map_ptr->max_entries, 2);
22438 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
22439 						    container_of(map_ptr,
22440 								 struct bpf_array,
22441 								 map)->index_mask);
22442 			insn_buf[2] = *insn;
22443 			cnt = 3;
22444 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22445 			if (!new_prog)
22446 				return -ENOMEM;
22447 
22448 			delta    += cnt - 1;
22449 			env->prog = prog = new_prog;
22450 			insn      = new_prog->insnsi + i + delta;
22451 			goto next_insn;
22452 		}
22453 
22454 		if (insn->imm == BPF_FUNC_timer_set_callback) {
22455 			/* The verifier will process callback_fn as many times as necessary
22456 			 * with different maps and the register states prepared by
22457 			 * set_timer_callback_state will be accurate.
22458 			 *
22459 			 * The following use case is valid:
22460 			 *   map1 is shared by prog1, prog2, prog3.
22461 			 *   prog1 calls bpf_timer_init for some map1 elements
22462 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
22463 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
22464 			 *   prog3 calls bpf_timer_start for some map1 elements.
22465 			 *     Those that were not both bpf_timer_init-ed and
22466 			 *     bpf_timer_set_callback-ed will return -EINVAL.
22467 			 */
22468 			struct bpf_insn ld_addrs[2] = {
22469 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
22470 			};
22471 
22472 			insn_buf[0] = ld_addrs[0];
22473 			insn_buf[1] = ld_addrs[1];
22474 			insn_buf[2] = *insn;
22475 			cnt = 3;
22476 
22477 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22478 			if (!new_prog)
22479 				return -ENOMEM;
22480 
22481 			delta    += cnt - 1;
22482 			env->prog = prog = new_prog;
22483 			insn      = new_prog->insnsi + i + delta;
22484 			goto patch_call_imm;
22485 		}
22486 
22487 		if (is_storage_get_function(insn->imm)) {
22488 			if (!in_sleepable(env) ||
22489 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
22490 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
22491 			else
22492 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
22493 			insn_buf[1] = *insn;
22494 			cnt = 2;
22495 
22496 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22497 			if (!new_prog)
22498 				return -ENOMEM;
22499 
22500 			delta += cnt - 1;
22501 			env->prog = prog = new_prog;
22502 			insn = new_prog->insnsi + i + delta;
22503 			goto patch_call_imm;
22504 		}
22505 
22506 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
22507 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
22508 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
22509 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
22510 			 */
22511 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
22512 			insn_buf[1] = *insn;
22513 			cnt = 2;
22514 
22515 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22516 			if (!new_prog)
22517 				return -ENOMEM;
22518 
22519 			delta += cnt - 1;
22520 			env->prog = prog = new_prog;
22521 			insn = new_prog->insnsi + i + delta;
22522 			goto patch_call_imm;
22523 		}
22524 
22525 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
22526 		 * and other inlining handlers are currently limited to 64 bit
22527 		 * only.
22528 		 */
22529 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22530 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
22531 		     insn->imm == BPF_FUNC_map_update_elem ||
22532 		     insn->imm == BPF_FUNC_map_delete_elem ||
22533 		     insn->imm == BPF_FUNC_map_push_elem   ||
22534 		     insn->imm == BPF_FUNC_map_pop_elem    ||
22535 		     insn->imm == BPF_FUNC_map_peek_elem   ||
22536 		     insn->imm == BPF_FUNC_redirect_map    ||
22537 		     insn->imm == BPF_FUNC_for_each_map_elem ||
22538 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
22539 			aux = &env->insn_aux_data[i + delta];
22540 			if (bpf_map_ptr_poisoned(aux))
22541 				goto patch_call_imm;
22542 
22543 			map_ptr = aux->map_ptr_state.map_ptr;
22544 			ops = map_ptr->ops;
22545 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
22546 			    ops->map_gen_lookup) {
22547 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
22548 				if (cnt == -EOPNOTSUPP)
22549 					goto patch_map_ops_generic;
22550 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
22551 					verifier_bug(env, "%d insns generated for map lookup", cnt);
22552 					return -EFAULT;
22553 				}
22554 
22555 				new_prog = bpf_patch_insn_data(env, i + delta,
22556 							       insn_buf, cnt);
22557 				if (!new_prog)
22558 					return -ENOMEM;
22559 
22560 				delta    += cnt - 1;
22561 				env->prog = prog = new_prog;
22562 				insn      = new_prog->insnsi + i + delta;
22563 				goto next_insn;
22564 			}
22565 
22566 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
22567 				     (void *(*)(struct bpf_map *map, void *key))NULL));
22568 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
22569 				     (long (*)(struct bpf_map *map, void *key))NULL));
22570 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
22571 				     (long (*)(struct bpf_map *map, void *key, void *value,
22572 					      u64 flags))NULL));
22573 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
22574 				     (long (*)(struct bpf_map *map, void *value,
22575 					      u64 flags))NULL));
22576 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
22577 				     (long (*)(struct bpf_map *map, void *value))NULL));
22578 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
22579 				     (long (*)(struct bpf_map *map, void *value))NULL));
22580 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
22581 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
22582 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
22583 				     (long (*)(struct bpf_map *map,
22584 					      bpf_callback_t callback_fn,
22585 					      void *callback_ctx,
22586 					      u64 flags))NULL));
22587 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
22588 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
22589 
22590 patch_map_ops_generic:
22591 			switch (insn->imm) {
22592 			case BPF_FUNC_map_lookup_elem:
22593 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
22594 				goto next_insn;
22595 			case BPF_FUNC_map_update_elem:
22596 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
22597 				goto next_insn;
22598 			case BPF_FUNC_map_delete_elem:
22599 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
22600 				goto next_insn;
22601 			case BPF_FUNC_map_push_elem:
22602 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
22603 				goto next_insn;
22604 			case BPF_FUNC_map_pop_elem:
22605 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
22606 				goto next_insn;
22607 			case BPF_FUNC_map_peek_elem:
22608 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
22609 				goto next_insn;
22610 			case BPF_FUNC_redirect_map:
22611 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
22612 				goto next_insn;
22613 			case BPF_FUNC_for_each_map_elem:
22614 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
22615 				goto next_insn;
22616 			case BPF_FUNC_map_lookup_percpu_elem:
22617 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
22618 				goto next_insn;
22619 			}
22620 
22621 			goto patch_call_imm;
22622 		}
22623 
22624 		/* Implement bpf_jiffies64 inline. */
22625 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22626 		    insn->imm == BPF_FUNC_jiffies64) {
22627 			struct bpf_insn ld_jiffies_addr[2] = {
22628 				BPF_LD_IMM64(BPF_REG_0,
22629 					     (unsigned long)&jiffies),
22630 			};
22631 
22632 			insn_buf[0] = ld_jiffies_addr[0];
22633 			insn_buf[1] = ld_jiffies_addr[1];
22634 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
22635 						  BPF_REG_0, 0);
22636 			cnt = 3;
22637 
22638 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
22639 						       cnt);
22640 			if (!new_prog)
22641 				return -ENOMEM;
22642 
22643 			delta    += cnt - 1;
22644 			env->prog = prog = new_prog;
22645 			insn      = new_prog->insnsi + i + delta;
22646 			goto next_insn;
22647 		}
22648 
22649 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
22650 		/* Implement bpf_get_smp_processor_id() inline. */
22651 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
22652 		    verifier_inlines_helper_call(env, insn->imm)) {
22653 			/* BPF_FUNC_get_smp_processor_id inlining is an
22654 			 * optimization, so if cpu_number is ever
22655 			 * changed in some incompatible and hard to support
22656 			 * way, it's fine to back out this inlining logic
22657 			 */
22658 #ifdef CONFIG_SMP
22659 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
22660 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
22661 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
22662 			cnt = 3;
22663 #else
22664 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
22665 			cnt = 1;
22666 #endif
22667 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22668 			if (!new_prog)
22669 				return -ENOMEM;
22670 
22671 			delta    += cnt - 1;
22672 			env->prog = prog = new_prog;
22673 			insn      = new_prog->insnsi + i + delta;
22674 			goto next_insn;
22675 		}
22676 #endif
22677 		/* Implement bpf_get_func_arg inline. */
22678 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22679 		    insn->imm == BPF_FUNC_get_func_arg) {
22680 			/* Load nr_args from ctx - 8 */
22681 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22682 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
22683 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
22684 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
22685 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
22686 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22687 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
22688 			insn_buf[7] = BPF_JMP_A(1);
22689 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22690 			cnt = 9;
22691 
22692 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22693 			if (!new_prog)
22694 				return -ENOMEM;
22695 
22696 			delta    += cnt - 1;
22697 			env->prog = prog = new_prog;
22698 			insn      = new_prog->insnsi + i + delta;
22699 			goto next_insn;
22700 		}
22701 
22702 		/* Implement bpf_get_func_ret inline. */
22703 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22704 		    insn->imm == BPF_FUNC_get_func_ret) {
22705 			if (eatype == BPF_TRACE_FEXIT ||
22706 			    eatype == BPF_MODIFY_RETURN) {
22707 				/* Load nr_args from ctx - 8 */
22708 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22709 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
22710 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
22711 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
22712 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
22713 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
22714 				cnt = 6;
22715 			} else {
22716 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
22717 				cnt = 1;
22718 			}
22719 
22720 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22721 			if (!new_prog)
22722 				return -ENOMEM;
22723 
22724 			delta    += cnt - 1;
22725 			env->prog = prog = new_prog;
22726 			insn      = new_prog->insnsi + i + delta;
22727 			goto next_insn;
22728 		}
22729 
22730 		/* Implement get_func_arg_cnt inline. */
22731 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22732 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
22733 			/* Load nr_args from ctx - 8 */
22734 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
22735 
22736 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22737 			if (!new_prog)
22738 				return -ENOMEM;
22739 
22740 			env->prog = prog = new_prog;
22741 			insn      = new_prog->insnsi + i + delta;
22742 			goto next_insn;
22743 		}
22744 
22745 		/* Implement bpf_get_func_ip inline. */
22746 		if (prog_type == BPF_PROG_TYPE_TRACING &&
22747 		    insn->imm == BPF_FUNC_get_func_ip) {
22748 			/* Load IP address from ctx - 16 */
22749 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
22750 
22751 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
22752 			if (!new_prog)
22753 				return -ENOMEM;
22754 
22755 			env->prog = prog = new_prog;
22756 			insn      = new_prog->insnsi + i + delta;
22757 			goto next_insn;
22758 		}
22759 
22760 		/* Implement bpf_get_branch_snapshot inline. */
22761 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
22762 		    prog->jit_requested && BITS_PER_LONG == 64 &&
22763 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
22764 			/* We are dealing with the following func protos:
22765 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
22766 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
22767 			 */
22768 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
22769 
22770 			/* struct perf_branch_entry is part of UAPI and is
22771 			 * used as an array element, so extremely unlikely to
22772 			 * ever grow or shrink
22773 			 */
22774 			BUILD_BUG_ON(br_entry_size != 24);
22775 
22776 			/* if (unlikely(flags)) return -EINVAL */
22777 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
22778 
22779 			/* Transform size (bytes) into number of entries (cnt = size / 24).
22780 			 * But to avoid expensive division instruction, we implement
22781 			 * divide-by-3 through multiplication, followed by further
22782 			 * division by 8 through 3-bit right shift.
22783 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
22784 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
22785 			 *
22786 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
22787 			 */
22788 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
22789 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
22790 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
22791 
22792 			/* call perf_snapshot_branch_stack implementation */
22793 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
22794 			/* if (entry_cnt == 0) return -ENOENT */
22795 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
22796 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
22797 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
22798 			insn_buf[7] = BPF_JMP_A(3);
22799 			/* return -EINVAL; */
22800 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
22801 			insn_buf[9] = BPF_JMP_A(1);
22802 			/* return -ENOENT; */
22803 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
22804 			cnt = 11;
22805 
22806 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22807 			if (!new_prog)
22808 				return -ENOMEM;
22809 
22810 			delta    += cnt - 1;
22811 			env->prog = prog = new_prog;
22812 			insn      = new_prog->insnsi + i + delta;
22813 			goto next_insn;
22814 		}
22815 
22816 		/* Implement bpf_kptr_xchg inline */
22817 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
22818 		    insn->imm == BPF_FUNC_kptr_xchg &&
22819 		    bpf_jit_supports_ptr_xchg()) {
22820 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
22821 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
22822 			cnt = 2;
22823 
22824 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22825 			if (!new_prog)
22826 				return -ENOMEM;
22827 
22828 			delta    += cnt - 1;
22829 			env->prog = prog = new_prog;
22830 			insn      = new_prog->insnsi + i + delta;
22831 			goto next_insn;
22832 		}
22833 patch_call_imm:
22834 		fn = env->ops->get_func_proto(insn->imm, env->prog);
22835 		/* all functions that have prototype and verifier allowed
22836 		 * programs to call them, must be real in-kernel functions
22837 		 */
22838 		if (!fn->func) {
22839 			verifier_bug(env,
22840 				     "not inlined functions %s#%d is missing func",
22841 				     func_id_name(insn->imm), insn->imm);
22842 			return -EFAULT;
22843 		}
22844 		insn->imm = fn->func - __bpf_call_base;
22845 next_insn:
22846 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
22847 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
22848 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
22849 
22850 			stack_depth = subprogs[cur_subprog].stack_depth;
22851 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
22852 				verbose(env, "stack size %d(extra %d) is too large\n",
22853 					stack_depth, stack_depth_extra);
22854 				return -EINVAL;
22855 			}
22856 			cur_subprog++;
22857 			stack_depth = subprogs[cur_subprog].stack_depth;
22858 			stack_depth_extra = 0;
22859 		}
22860 		i++;
22861 		insn++;
22862 	}
22863 
22864 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
22865 	for (i = 0; i < env->subprog_cnt; i++) {
22866 		int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
22867 		int subprog_start = subprogs[i].start;
22868 		int stack_slots = subprogs[i].stack_extra / 8;
22869 		int slots = delta, cnt = 0;
22870 
22871 		if (!stack_slots)
22872 			continue;
22873 		/* We need two slots in case timed may_goto is supported. */
22874 		if (stack_slots > slots) {
22875 			verifier_bug(env, "stack_slots supports may_goto only");
22876 			return -EFAULT;
22877 		}
22878 
22879 		stack_depth = subprogs[i].stack_depth;
22880 		if (bpf_jit_supports_timed_may_goto()) {
22881 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22882 						     BPF_MAX_TIMED_LOOPS);
22883 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
22884 		} else {
22885 			/* Add ST insn to subprog prologue to init extra stack */
22886 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
22887 						     BPF_MAX_LOOPS);
22888 		}
22889 		/* Copy first actual insn to preserve it */
22890 		insn_buf[cnt++] = env->prog->insnsi[subprog_start];
22891 
22892 		new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
22893 		if (!new_prog)
22894 			return -ENOMEM;
22895 		env->prog = prog = new_prog;
22896 		/*
22897 		 * If may_goto is a first insn of a prog there could be a jmp
22898 		 * insn that points to it, hence adjust all such jmps to point
22899 		 * to insn after BPF_ST that inits may_goto count.
22900 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
22901 		 */
22902 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
22903 	}
22904 
22905 	/* Since poke tab is now finalized, publish aux to tracker. */
22906 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
22907 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
22908 		if (!map_ptr->ops->map_poke_track ||
22909 		    !map_ptr->ops->map_poke_untrack ||
22910 		    !map_ptr->ops->map_poke_run) {
22911 			verifier_bug(env, "poke tab is misconfigured");
22912 			return -EFAULT;
22913 		}
22914 
22915 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
22916 		if (ret < 0) {
22917 			verbose(env, "tracking tail call prog failed\n");
22918 			return ret;
22919 		}
22920 	}
22921 
22922 	sort_kfunc_descs_by_imm_off(env->prog);
22923 
22924 	return 0;
22925 }
22926 
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * total_cnt)22927 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
22928 					int position,
22929 					s32 stack_base,
22930 					u32 callback_subprogno,
22931 					u32 *total_cnt)
22932 {
22933 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
22934 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
22935 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
22936 	int reg_loop_max = BPF_REG_6;
22937 	int reg_loop_cnt = BPF_REG_7;
22938 	int reg_loop_ctx = BPF_REG_8;
22939 
22940 	struct bpf_insn *insn_buf = env->insn_buf;
22941 	struct bpf_prog *new_prog;
22942 	u32 callback_start;
22943 	u32 call_insn_offset;
22944 	s32 callback_offset;
22945 	u32 cnt = 0;
22946 
22947 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
22948 	 * be careful to modify this code in sync.
22949 	 */
22950 
22951 	/* Return error and jump to the end of the patch if
22952 	 * expected number of iterations is too big.
22953 	 */
22954 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
22955 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
22956 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
22957 	/* spill R6, R7, R8 to use these as loop vars */
22958 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
22959 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
22960 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
22961 	/* initialize loop vars */
22962 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
22963 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
22964 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
22965 	/* loop header,
22966 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
22967 	 */
22968 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
22969 	/* callback call,
22970 	 * correct callback offset would be set after patching
22971 	 */
22972 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
22973 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
22974 	insn_buf[cnt++] = BPF_CALL_REL(0);
22975 	/* increment loop counter */
22976 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
22977 	/* jump to loop header if callback returned 0 */
22978 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
22979 	/* return value of bpf_loop,
22980 	 * set R0 to the number of iterations
22981 	 */
22982 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
22983 	/* restore original values of R6, R7, R8 */
22984 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
22985 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
22986 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
22987 
22988 	*total_cnt = cnt;
22989 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
22990 	if (!new_prog)
22991 		return new_prog;
22992 
22993 	/* callback start is known only after patching */
22994 	callback_start = env->subprog_info[callback_subprogno].start;
22995 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
22996 	call_insn_offset = position + 12;
22997 	callback_offset = callback_start - call_insn_offset - 1;
22998 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
22999 
23000 	return new_prog;
23001 }
23002 
is_bpf_loop_call(struct bpf_insn * insn)23003 static bool is_bpf_loop_call(struct bpf_insn *insn)
23004 {
23005 	return insn->code == (BPF_JMP | BPF_CALL) &&
23006 		insn->src_reg == 0 &&
23007 		insn->imm == BPF_FUNC_loop;
23008 }
23009 
23010 /* For all sub-programs in the program (including main) check
23011  * insn_aux_data to see if there are bpf_loop calls that require
23012  * inlining. If such calls are found the calls are replaced with a
23013  * sequence of instructions produced by `inline_bpf_loop` function and
23014  * subprog stack_depth is increased by the size of 3 registers.
23015  * This stack space is used to spill values of the R6, R7, R8.  These
23016  * registers are used to store the loop bound, counter and context
23017  * variables.
23018  */
optimize_bpf_loop(struct bpf_verifier_env * env)23019 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23020 {
23021 	struct bpf_subprog_info *subprogs = env->subprog_info;
23022 	int i, cur_subprog = 0, cnt, delta = 0;
23023 	struct bpf_insn *insn = env->prog->insnsi;
23024 	int insn_cnt = env->prog->len;
23025 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
23026 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23027 	u16 stack_depth_extra = 0;
23028 
23029 	for (i = 0; i < insn_cnt; i++, insn++) {
23030 		struct bpf_loop_inline_state *inline_state =
23031 			&env->insn_aux_data[i + delta].loop_inline_state;
23032 
23033 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23034 			struct bpf_prog *new_prog;
23035 
23036 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23037 			new_prog = inline_bpf_loop(env,
23038 						   i + delta,
23039 						   -(stack_depth + stack_depth_extra),
23040 						   inline_state->callback_subprogno,
23041 						   &cnt);
23042 			if (!new_prog)
23043 				return -ENOMEM;
23044 
23045 			delta     += cnt - 1;
23046 			env->prog  = new_prog;
23047 			insn       = new_prog->insnsi + i + delta;
23048 		}
23049 
23050 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23051 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
23052 			cur_subprog++;
23053 			stack_depth = subprogs[cur_subprog].stack_depth;
23054 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23055 			stack_depth_extra = 0;
23056 		}
23057 	}
23058 
23059 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23060 
23061 	return 0;
23062 }
23063 
23064 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23065  * adjust subprograms stack depth when possible.
23066  */
remove_fastcall_spills_fills(struct bpf_verifier_env * env)23067 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23068 {
23069 	struct bpf_subprog_info *subprog = env->subprog_info;
23070 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
23071 	struct bpf_insn *insn = env->prog->insnsi;
23072 	int insn_cnt = env->prog->len;
23073 	u32 spills_num;
23074 	bool modified = false;
23075 	int i, j;
23076 
23077 	for (i = 0; i < insn_cnt; i++, insn++) {
23078 		if (aux[i].fastcall_spills_num > 0) {
23079 			spills_num = aux[i].fastcall_spills_num;
23080 			/* NOPs would be removed by opt_remove_nops() */
23081 			for (j = 1; j <= spills_num; ++j) {
23082 				*(insn - j) = NOP;
23083 				*(insn + j) = NOP;
23084 			}
23085 			modified = true;
23086 		}
23087 		if ((subprog + 1)->start == i + 1) {
23088 			if (modified && !subprog->keep_fastcall_stack)
23089 				subprog->stack_depth = -subprog->fastcall_stack_off;
23090 			subprog++;
23091 			modified = false;
23092 		}
23093 	}
23094 
23095 	return 0;
23096 }
23097 
free_states(struct bpf_verifier_env * env)23098 static void free_states(struct bpf_verifier_env *env)
23099 {
23100 	struct bpf_verifier_state_list *sl;
23101 	struct list_head *head, *pos, *tmp;
23102 	struct bpf_scc_info *info;
23103 	int i, j;
23104 
23105 	free_verifier_state(env->cur_state, true);
23106 	env->cur_state = NULL;
23107 	while (!pop_stack(env, NULL, NULL, false));
23108 
23109 	list_for_each_safe(pos, tmp, &env->free_list) {
23110 		sl = container_of(pos, struct bpf_verifier_state_list, node);
23111 		free_verifier_state(&sl->state, false);
23112 		kfree(sl);
23113 	}
23114 	INIT_LIST_HEAD(&env->free_list);
23115 
23116 	for (i = 0; i < env->scc_cnt; ++i) {
23117 		info = env->scc_info[i];
23118 		if (!info)
23119 			continue;
23120 		for (j = 0; j < info->num_visits; j++)
23121 			free_backedges(&info->visits[j]);
23122 		kvfree(info);
23123 		env->scc_info[i] = NULL;
23124 	}
23125 
23126 	if (!env->explored_states)
23127 		return;
23128 
23129 	for (i = 0; i < state_htab_size(env); i++) {
23130 		head = &env->explored_states[i];
23131 
23132 		list_for_each_safe(pos, tmp, head) {
23133 			sl = container_of(pos, struct bpf_verifier_state_list, node);
23134 			free_verifier_state(&sl->state, false);
23135 			kfree(sl);
23136 		}
23137 		INIT_LIST_HEAD(&env->explored_states[i]);
23138 	}
23139 }
23140 
do_check_common(struct bpf_verifier_env * env,int subprog)23141 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23142 {
23143 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23144 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
23145 	struct bpf_prog_aux *aux = env->prog->aux;
23146 	struct bpf_verifier_state *state;
23147 	struct bpf_reg_state *regs;
23148 	int ret, i;
23149 
23150 	env->prev_linfo = NULL;
23151 	env->pass_cnt++;
23152 
23153 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23154 	if (!state)
23155 		return -ENOMEM;
23156 	state->curframe = 0;
23157 	state->speculative = false;
23158 	state->branches = 1;
23159 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23160 	if (!state->frame[0]) {
23161 		kfree(state);
23162 		return -ENOMEM;
23163 	}
23164 	env->cur_state = state;
23165 	init_func_state(env, state->frame[0],
23166 			BPF_MAIN_FUNC /* callsite */,
23167 			0 /* frameno */,
23168 			subprog);
23169 	state->first_insn_idx = env->subprog_info[subprog].start;
23170 	state->last_insn_idx = -1;
23171 
23172 	regs = state->frame[state->curframe]->regs;
23173 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23174 		const char *sub_name = subprog_name(env, subprog);
23175 		struct bpf_subprog_arg_info *arg;
23176 		struct bpf_reg_state *reg;
23177 
23178 		verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23179 		ret = btf_prepare_func_args(env, subprog);
23180 		if (ret)
23181 			goto out;
23182 
23183 		if (subprog_is_exc_cb(env, subprog)) {
23184 			state->frame[0]->in_exception_callback_fn = true;
23185 			/* We have already ensured that the callback returns an integer, just
23186 			 * like all global subprogs. We need to determine it only has a single
23187 			 * scalar argument.
23188 			 */
23189 			if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23190 				verbose(env, "exception cb only supports single integer argument\n");
23191 				ret = -EINVAL;
23192 				goto out;
23193 			}
23194 		}
23195 		for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23196 			arg = &sub->args[i - BPF_REG_1];
23197 			reg = &regs[i];
23198 
23199 			if (arg->arg_type == ARG_PTR_TO_CTX) {
23200 				reg->type = PTR_TO_CTX;
23201 				mark_reg_known_zero(env, regs, i);
23202 			} else if (arg->arg_type == ARG_ANYTHING) {
23203 				reg->type = SCALAR_VALUE;
23204 				mark_reg_unknown(env, regs, i);
23205 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23206 				/* assume unspecial LOCAL dynptr type */
23207 				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23208 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23209 				reg->type = PTR_TO_MEM;
23210 				reg->type |= arg->arg_type &
23211 					     (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23212 				mark_reg_known_zero(env, regs, i);
23213 				reg->mem_size = arg->mem_size;
23214 				if (arg->arg_type & PTR_MAYBE_NULL)
23215 					reg->id = ++env->id_gen;
23216 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23217 				reg->type = PTR_TO_BTF_ID;
23218 				if (arg->arg_type & PTR_MAYBE_NULL)
23219 					reg->type |= PTR_MAYBE_NULL;
23220 				if (arg->arg_type & PTR_UNTRUSTED)
23221 					reg->type |= PTR_UNTRUSTED;
23222 				if (arg->arg_type & PTR_TRUSTED)
23223 					reg->type |= PTR_TRUSTED;
23224 				mark_reg_known_zero(env, regs, i);
23225 				reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23226 				reg->btf_id = arg->btf_id;
23227 				reg->id = ++env->id_gen;
23228 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23229 				/* caller can pass either PTR_TO_ARENA or SCALAR */
23230 				mark_reg_unknown(env, regs, i);
23231 			} else {
23232 				verifier_bug(env, "unhandled arg#%d type %d",
23233 					     i - BPF_REG_1, arg->arg_type);
23234 				ret = -EFAULT;
23235 				goto out;
23236 			}
23237 		}
23238 	} else {
23239 		/* if main BPF program has associated BTF info, validate that
23240 		 * it's matching expected signature, and otherwise mark BTF
23241 		 * info for main program as unreliable
23242 		 */
23243 		if (env->prog->aux->func_info_aux) {
23244 			ret = btf_prepare_func_args(env, 0);
23245 			if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23246 				env->prog->aux->func_info_aux[0].unreliable = true;
23247 		}
23248 
23249 		/* 1st arg to a function */
23250 		regs[BPF_REG_1].type = PTR_TO_CTX;
23251 		mark_reg_known_zero(env, regs, BPF_REG_1);
23252 	}
23253 
23254 	/* Acquire references for struct_ops program arguments tagged with "__ref" */
23255 	if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23256 		for (i = 0; i < aux->ctx_arg_info_size; i++)
23257 			aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23258 							  acquire_reference(env, 0) : 0;
23259 	}
23260 
23261 	ret = do_check(env);
23262 out:
23263 	if (!ret && pop_log)
23264 		bpf_vlog_reset(&env->log, 0);
23265 	free_states(env);
23266 	return ret;
23267 }
23268 
23269 /* Lazily verify all global functions based on their BTF, if they are called
23270  * from main BPF program or any of subprograms transitively.
23271  * BPF global subprogs called from dead code are not validated.
23272  * All callable global functions must pass verification.
23273  * Otherwise the whole program is rejected.
23274  * Consider:
23275  * int bar(int);
23276  * int foo(int f)
23277  * {
23278  *    return bar(f);
23279  * }
23280  * int bar(int b)
23281  * {
23282  *    ...
23283  * }
23284  * foo() will be verified first for R1=any_scalar_value. During verification it
23285  * will be assumed that bar() already verified successfully and call to bar()
23286  * from foo() will be checked for type match only. Later bar() will be verified
23287  * independently to check that it's safe for R1=any_scalar_value.
23288  */
do_check_subprogs(struct bpf_verifier_env * env)23289 static int do_check_subprogs(struct bpf_verifier_env *env)
23290 {
23291 	struct bpf_prog_aux *aux = env->prog->aux;
23292 	struct bpf_func_info_aux *sub_aux;
23293 	int i, ret, new_cnt;
23294 
23295 	if (!aux->func_info)
23296 		return 0;
23297 
23298 	/* exception callback is presumed to be always called */
23299 	if (env->exception_callback_subprog)
23300 		subprog_aux(env, env->exception_callback_subprog)->called = true;
23301 
23302 again:
23303 	new_cnt = 0;
23304 	for (i = 1; i < env->subprog_cnt; i++) {
23305 		if (!subprog_is_global(env, i))
23306 			continue;
23307 
23308 		sub_aux = subprog_aux(env, i);
23309 		if (!sub_aux->called || sub_aux->verified)
23310 			continue;
23311 
23312 		env->insn_idx = env->subprog_info[i].start;
23313 		WARN_ON_ONCE(env->insn_idx == 0);
23314 		ret = do_check_common(env, i);
23315 		if (ret) {
23316 			return ret;
23317 		} else if (env->log.level & BPF_LOG_LEVEL) {
23318 			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23319 				i, subprog_name(env, i));
23320 		}
23321 
23322 		/* We verified new global subprog, it might have called some
23323 		 * more global subprogs that we haven't verified yet, so we
23324 		 * need to do another pass over subprogs to verify those.
23325 		 */
23326 		sub_aux->verified = true;
23327 		new_cnt++;
23328 	}
23329 
23330 	/* We can't loop forever as we verify at least one global subprog on
23331 	 * each pass.
23332 	 */
23333 	if (new_cnt)
23334 		goto again;
23335 
23336 	return 0;
23337 }
23338 
do_check_main(struct bpf_verifier_env * env)23339 static int do_check_main(struct bpf_verifier_env *env)
23340 {
23341 	int ret;
23342 
23343 	env->insn_idx = 0;
23344 	ret = do_check_common(env, 0);
23345 	if (!ret)
23346 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23347 	return ret;
23348 }
23349 
23350 
print_verification_stats(struct bpf_verifier_env * env)23351 static void print_verification_stats(struct bpf_verifier_env *env)
23352 {
23353 	int i;
23354 
23355 	if (env->log.level & BPF_LOG_STATS) {
23356 		verbose(env, "verification time %lld usec\n",
23357 			div_u64(env->verification_time, 1000));
23358 		verbose(env, "stack depth ");
23359 		for (i = 0; i < env->subprog_cnt; i++) {
23360 			u32 depth = env->subprog_info[i].stack_depth;
23361 
23362 			verbose(env, "%d", depth);
23363 			if (i + 1 < env->subprog_cnt)
23364 				verbose(env, "+");
23365 		}
23366 		verbose(env, "\n");
23367 	}
23368 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23369 		"total_states %d peak_states %d mark_read %d\n",
23370 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23371 		env->max_states_per_insn, env->total_states,
23372 		env->peak_states, env->longest_mark_read_walk);
23373 }
23374 
bpf_prog_ctx_arg_info_init(struct bpf_prog * prog,const struct bpf_ctx_arg_aux * info,u32 cnt)23375 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23376 			       const struct bpf_ctx_arg_aux *info, u32 cnt)
23377 {
23378 	prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23379 	prog->aux->ctx_arg_info_size = cnt;
23380 
23381 	return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23382 }
23383 
check_struct_ops_btf_id(struct bpf_verifier_env * env)23384 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23385 {
23386 	const struct btf_type *t, *func_proto;
23387 	const struct bpf_struct_ops_desc *st_ops_desc;
23388 	const struct bpf_struct_ops *st_ops;
23389 	const struct btf_member *member;
23390 	struct bpf_prog *prog = env->prog;
23391 	bool has_refcounted_arg = false;
23392 	u32 btf_id, member_idx, member_off;
23393 	struct btf *btf;
23394 	const char *mname;
23395 	int i, err;
23396 
23397 	if (!prog->gpl_compatible) {
23398 		verbose(env, "struct ops programs must have a GPL compatible license\n");
23399 		return -EINVAL;
23400 	}
23401 
23402 	if (!prog->aux->attach_btf_id)
23403 		return -ENOTSUPP;
23404 
23405 	btf = prog->aux->attach_btf;
23406 	if (btf_is_module(btf)) {
23407 		/* Make sure st_ops is valid through the lifetime of env */
23408 		env->attach_btf_mod = btf_try_get_module(btf);
23409 		if (!env->attach_btf_mod) {
23410 			verbose(env, "struct_ops module %s is not found\n",
23411 				btf_get_name(btf));
23412 			return -ENOTSUPP;
23413 		}
23414 	}
23415 
23416 	btf_id = prog->aux->attach_btf_id;
23417 	st_ops_desc = bpf_struct_ops_find(btf, btf_id);
23418 	if (!st_ops_desc) {
23419 		verbose(env, "attach_btf_id %u is not a supported struct\n",
23420 			btf_id);
23421 		return -ENOTSUPP;
23422 	}
23423 	st_ops = st_ops_desc->st_ops;
23424 
23425 	t = st_ops_desc->type;
23426 	member_idx = prog->expected_attach_type;
23427 	if (member_idx >= btf_type_vlen(t)) {
23428 		verbose(env, "attach to invalid member idx %u of struct %s\n",
23429 			member_idx, st_ops->name);
23430 		return -EINVAL;
23431 	}
23432 
23433 	member = &btf_type_member(t)[member_idx];
23434 	mname = btf_name_by_offset(btf, member->name_off);
23435 	func_proto = btf_type_resolve_func_ptr(btf, member->type,
23436 					       NULL);
23437 	if (!func_proto) {
23438 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
23439 			mname, member_idx, st_ops->name);
23440 		return -EINVAL;
23441 	}
23442 
23443 	member_off = __btf_member_bit_offset(t, member) / 8;
23444 	err = bpf_struct_ops_supported(st_ops, member_off);
23445 	if (err) {
23446 		verbose(env, "attach to unsupported member %s of struct %s\n",
23447 			mname, st_ops->name);
23448 		return err;
23449 	}
23450 
23451 	if (st_ops->check_member) {
23452 		err = st_ops->check_member(t, member, prog);
23453 
23454 		if (err) {
23455 			verbose(env, "attach to unsupported member %s of struct %s\n",
23456 				mname, st_ops->name);
23457 			return err;
23458 		}
23459 	}
23460 
23461 	if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
23462 		verbose(env, "Private stack not supported by jit\n");
23463 		return -EACCES;
23464 	}
23465 
23466 	for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
23467 		if (st_ops_desc->arg_info[member_idx].info->refcounted) {
23468 			has_refcounted_arg = true;
23469 			break;
23470 		}
23471 	}
23472 
23473 	/* Tail call is not allowed for programs with refcounted arguments since we
23474 	 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
23475 	 */
23476 	for (i = 0; i < env->subprog_cnt; i++) {
23477 		if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
23478 			verbose(env, "program with __ref argument cannot tail call\n");
23479 			return -EINVAL;
23480 		}
23481 	}
23482 
23483 	prog->aux->st_ops = st_ops;
23484 	prog->aux->attach_st_ops_member_off = member_off;
23485 
23486 	prog->aux->attach_func_proto = func_proto;
23487 	prog->aux->attach_func_name = mname;
23488 	env->ops = st_ops->verifier_ops;
23489 
23490 	return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
23491 					  st_ops_desc->arg_info[member_idx].cnt);
23492 }
23493 #define SECURITY_PREFIX "security_"
23494 
check_attach_modify_return(unsigned long addr,const char * func_name)23495 static int check_attach_modify_return(unsigned long addr, const char *func_name)
23496 {
23497 	if (within_error_injection_list(addr) ||
23498 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
23499 		return 0;
23500 
23501 	return -EINVAL;
23502 }
23503 
23504 /* list of non-sleepable functions that are otherwise on
23505  * ALLOW_ERROR_INJECTION list
23506  */
23507 BTF_SET_START(btf_non_sleepable_error_inject)
23508 /* Three functions below can be called from sleepable and non-sleepable context.
23509  * Assume non-sleepable from bpf safety point of view.
23510  */
BTF_ID(func,__filemap_add_folio)23511 BTF_ID(func, __filemap_add_folio)
23512 #ifdef CONFIG_FAIL_PAGE_ALLOC
23513 BTF_ID(func, should_fail_alloc_page)
23514 #endif
23515 #ifdef CONFIG_FAILSLAB
23516 BTF_ID(func, should_failslab)
23517 #endif
23518 BTF_SET_END(btf_non_sleepable_error_inject)
23519 
23520 static int check_non_sleepable_error_inject(u32 btf_id)
23521 {
23522 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
23523 }
23524 
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)23525 int bpf_check_attach_target(struct bpf_verifier_log *log,
23526 			    const struct bpf_prog *prog,
23527 			    const struct bpf_prog *tgt_prog,
23528 			    u32 btf_id,
23529 			    struct bpf_attach_target_info *tgt_info)
23530 {
23531 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
23532 	bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
23533 	char trace_symbol[KSYM_SYMBOL_LEN];
23534 	const char prefix[] = "btf_trace_";
23535 	struct bpf_raw_event_map *btp;
23536 	int ret = 0, subprog = -1, i;
23537 	const struct btf_type *t;
23538 	bool conservative = true;
23539 	const char *tname, *fname;
23540 	struct btf *btf;
23541 	long addr = 0;
23542 	struct module *mod = NULL;
23543 
23544 	if (!btf_id) {
23545 		bpf_log(log, "Tracing programs must provide btf_id\n");
23546 		return -EINVAL;
23547 	}
23548 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
23549 	if (!btf) {
23550 		bpf_log(log,
23551 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
23552 		return -EINVAL;
23553 	}
23554 	t = btf_type_by_id(btf, btf_id);
23555 	if (!t) {
23556 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
23557 		return -EINVAL;
23558 	}
23559 	tname = btf_name_by_offset(btf, t->name_off);
23560 	if (!tname) {
23561 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
23562 		return -EINVAL;
23563 	}
23564 	if (tgt_prog) {
23565 		struct bpf_prog_aux *aux = tgt_prog->aux;
23566 		bool tgt_changes_pkt_data;
23567 		bool tgt_might_sleep;
23568 
23569 		if (bpf_prog_is_dev_bound(prog->aux) &&
23570 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
23571 			bpf_log(log, "Target program bound device mismatch");
23572 			return -EINVAL;
23573 		}
23574 
23575 		for (i = 0; i < aux->func_info_cnt; i++)
23576 			if (aux->func_info[i].type_id == btf_id) {
23577 				subprog = i;
23578 				break;
23579 			}
23580 		if (subprog == -1) {
23581 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
23582 			return -EINVAL;
23583 		}
23584 		if (aux->func && aux->func[subprog]->aux->exception_cb) {
23585 			bpf_log(log,
23586 				"%s programs cannot attach to exception callback\n",
23587 				prog_extension ? "Extension" : "FENTRY/FEXIT");
23588 			return -EINVAL;
23589 		}
23590 		conservative = aux->func_info_aux[subprog].unreliable;
23591 		if (prog_extension) {
23592 			if (conservative) {
23593 				bpf_log(log,
23594 					"Cannot replace static functions\n");
23595 				return -EINVAL;
23596 			}
23597 			if (!prog->jit_requested) {
23598 				bpf_log(log,
23599 					"Extension programs should be JITed\n");
23600 				return -EINVAL;
23601 			}
23602 			tgt_changes_pkt_data = aux->func
23603 					       ? aux->func[subprog]->aux->changes_pkt_data
23604 					       : aux->changes_pkt_data;
23605 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
23606 				bpf_log(log,
23607 					"Extension program changes packet data, while original does not\n");
23608 				return -EINVAL;
23609 			}
23610 
23611 			tgt_might_sleep = aux->func
23612 					  ? aux->func[subprog]->aux->might_sleep
23613 					  : aux->might_sleep;
23614 			if (prog->aux->might_sleep && !tgt_might_sleep) {
23615 				bpf_log(log,
23616 					"Extension program may sleep, while original does not\n");
23617 				return -EINVAL;
23618 			}
23619 		}
23620 		if (!tgt_prog->jited) {
23621 			bpf_log(log, "Can attach to only JITed progs\n");
23622 			return -EINVAL;
23623 		}
23624 		if (prog_tracing) {
23625 			if (aux->attach_tracing_prog) {
23626 				/*
23627 				 * Target program is an fentry/fexit which is already attached
23628 				 * to another tracing program. More levels of nesting
23629 				 * attachment are not allowed.
23630 				 */
23631 				bpf_log(log, "Cannot nest tracing program attach more than once\n");
23632 				return -EINVAL;
23633 			}
23634 		} else if (tgt_prog->type == prog->type) {
23635 			/*
23636 			 * To avoid potential call chain cycles, prevent attaching of a
23637 			 * program extension to another extension. It's ok to attach
23638 			 * fentry/fexit to extension program.
23639 			 */
23640 			bpf_log(log, "Cannot recursively attach\n");
23641 			return -EINVAL;
23642 		}
23643 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
23644 		    prog_extension &&
23645 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
23646 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
23647 			/* Program extensions can extend all program types
23648 			 * except fentry/fexit. The reason is the following.
23649 			 * The fentry/fexit programs are used for performance
23650 			 * analysis, stats and can be attached to any program
23651 			 * type. When extension program is replacing XDP function
23652 			 * it is necessary to allow performance analysis of all
23653 			 * functions. Both original XDP program and its program
23654 			 * extension. Hence attaching fentry/fexit to
23655 			 * BPF_PROG_TYPE_EXT is allowed. If extending of
23656 			 * fentry/fexit was allowed it would be possible to create
23657 			 * long call chain fentry->extension->fentry->extension
23658 			 * beyond reasonable stack size. Hence extending fentry
23659 			 * is not allowed.
23660 			 */
23661 			bpf_log(log, "Cannot extend fentry/fexit\n");
23662 			return -EINVAL;
23663 		}
23664 	} else {
23665 		if (prog_extension) {
23666 			bpf_log(log, "Cannot replace kernel functions\n");
23667 			return -EINVAL;
23668 		}
23669 	}
23670 
23671 	switch (prog->expected_attach_type) {
23672 	case BPF_TRACE_RAW_TP:
23673 		if (tgt_prog) {
23674 			bpf_log(log,
23675 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
23676 			return -EINVAL;
23677 		}
23678 		if (!btf_type_is_typedef(t)) {
23679 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
23680 				btf_id);
23681 			return -EINVAL;
23682 		}
23683 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
23684 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
23685 				btf_id, tname);
23686 			return -EINVAL;
23687 		}
23688 		tname += sizeof(prefix) - 1;
23689 
23690 		/* The func_proto of "btf_trace_##tname" is generated from typedef without argument
23691 		 * names. Thus using bpf_raw_event_map to get argument names.
23692 		 */
23693 		btp = bpf_get_raw_tracepoint(tname);
23694 		if (!btp)
23695 			return -EINVAL;
23696 		fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
23697 					trace_symbol);
23698 		bpf_put_raw_tracepoint(btp);
23699 
23700 		if (fname)
23701 			ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
23702 
23703 		if (!fname || ret < 0) {
23704 			bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
23705 				prefix, tname);
23706 			t = btf_type_by_id(btf, t->type);
23707 			if (!btf_type_is_ptr(t))
23708 				/* should never happen in valid vmlinux build */
23709 				return -EINVAL;
23710 		} else {
23711 			t = btf_type_by_id(btf, ret);
23712 			if (!btf_type_is_func(t))
23713 				/* should never happen in valid vmlinux build */
23714 				return -EINVAL;
23715 		}
23716 
23717 		t = btf_type_by_id(btf, t->type);
23718 		if (!btf_type_is_func_proto(t))
23719 			/* should never happen in valid vmlinux build */
23720 			return -EINVAL;
23721 
23722 		break;
23723 	case BPF_TRACE_ITER:
23724 		if (!btf_type_is_func(t)) {
23725 			bpf_log(log, "attach_btf_id %u is not a function\n",
23726 				btf_id);
23727 			return -EINVAL;
23728 		}
23729 		t = btf_type_by_id(btf, t->type);
23730 		if (!btf_type_is_func_proto(t))
23731 			return -EINVAL;
23732 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23733 		if (ret)
23734 			return ret;
23735 		break;
23736 	default:
23737 		if (!prog_extension)
23738 			return -EINVAL;
23739 		fallthrough;
23740 	case BPF_MODIFY_RETURN:
23741 	case BPF_LSM_MAC:
23742 	case BPF_LSM_CGROUP:
23743 	case BPF_TRACE_FENTRY:
23744 	case BPF_TRACE_FEXIT:
23745 		if (!btf_type_is_func(t)) {
23746 			bpf_log(log, "attach_btf_id %u is not a function\n",
23747 				btf_id);
23748 			return -EINVAL;
23749 		}
23750 		if (prog_extension &&
23751 		    btf_check_type_match(log, prog, btf, t))
23752 			return -EINVAL;
23753 		t = btf_type_by_id(btf, t->type);
23754 		if (!btf_type_is_func_proto(t))
23755 			return -EINVAL;
23756 
23757 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
23758 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
23759 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
23760 			return -EINVAL;
23761 
23762 		if (tgt_prog && conservative)
23763 			t = NULL;
23764 
23765 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
23766 		if (ret < 0)
23767 			return ret;
23768 
23769 		if (tgt_prog) {
23770 			if (subprog == 0)
23771 				addr = (long) tgt_prog->bpf_func;
23772 			else
23773 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
23774 		} else {
23775 			if (btf_is_module(btf)) {
23776 				mod = btf_try_get_module(btf);
23777 				if (mod)
23778 					addr = find_kallsyms_symbol_value(mod, tname);
23779 				else
23780 					addr = 0;
23781 			} else {
23782 				addr = kallsyms_lookup_name(tname);
23783 			}
23784 			if (!addr) {
23785 				module_put(mod);
23786 				bpf_log(log,
23787 					"The address of function %s cannot be found\n",
23788 					tname);
23789 				return -ENOENT;
23790 			}
23791 		}
23792 
23793 		if (prog->sleepable) {
23794 			ret = -EINVAL;
23795 			switch (prog->type) {
23796 			case BPF_PROG_TYPE_TRACING:
23797 
23798 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
23799 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
23800 				 */
23801 				if (!check_non_sleepable_error_inject(btf_id) &&
23802 				    within_error_injection_list(addr))
23803 					ret = 0;
23804 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
23805 				 * in the fmodret id set with the KF_SLEEPABLE flag.
23806 				 */
23807 				else {
23808 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
23809 										prog);
23810 
23811 					if (flags && (*flags & KF_SLEEPABLE))
23812 						ret = 0;
23813 				}
23814 				break;
23815 			case BPF_PROG_TYPE_LSM:
23816 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
23817 				 * Only some of them are sleepable.
23818 				 */
23819 				if (bpf_lsm_is_sleepable_hook(btf_id))
23820 					ret = 0;
23821 				break;
23822 			default:
23823 				break;
23824 			}
23825 			if (ret) {
23826 				module_put(mod);
23827 				bpf_log(log, "%s is not sleepable\n", tname);
23828 				return ret;
23829 			}
23830 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
23831 			if (tgt_prog) {
23832 				module_put(mod);
23833 				bpf_log(log, "can't modify return codes of BPF programs\n");
23834 				return -EINVAL;
23835 			}
23836 			ret = -EINVAL;
23837 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
23838 			    !check_attach_modify_return(addr, tname))
23839 				ret = 0;
23840 			if (ret) {
23841 				module_put(mod);
23842 				bpf_log(log, "%s() is not modifiable\n", tname);
23843 				return ret;
23844 			}
23845 		}
23846 
23847 		break;
23848 	}
23849 	tgt_info->tgt_addr = addr;
23850 	tgt_info->tgt_name = tname;
23851 	tgt_info->tgt_type = t;
23852 	tgt_info->tgt_mod = mod;
23853 	return 0;
23854 }
23855 
BTF_SET_START(btf_id_deny)23856 BTF_SET_START(btf_id_deny)
23857 BTF_ID_UNUSED
23858 #ifdef CONFIG_SMP
23859 BTF_ID(func, ___migrate_enable)
23860 BTF_ID(func, migrate_disable)
23861 BTF_ID(func, migrate_enable)
23862 #endif
23863 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
23864 BTF_ID(func, rcu_read_unlock_strict)
23865 #endif
23866 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
23867 BTF_ID(func, preempt_count_add)
23868 BTF_ID(func, preempt_count_sub)
23869 #endif
23870 #ifdef CONFIG_PREEMPT_RCU
23871 BTF_ID(func, __rcu_read_lock)
23872 BTF_ID(func, __rcu_read_unlock)
23873 #endif
23874 BTF_SET_END(btf_id_deny)
23875 
23876 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
23877  * Currently, we must manually list all __noreturn functions here. Once a more
23878  * robust solution is implemented, this workaround can be removed.
23879  */
23880 BTF_SET_START(noreturn_deny)
23881 #ifdef CONFIG_IA32_EMULATION
23882 BTF_ID(func, __ia32_sys_exit)
23883 BTF_ID(func, __ia32_sys_exit_group)
23884 #endif
23885 #ifdef CONFIG_KUNIT
23886 BTF_ID(func, __kunit_abort)
23887 BTF_ID(func, kunit_try_catch_throw)
23888 #endif
23889 #ifdef CONFIG_MODULES
23890 BTF_ID(func, __module_put_and_kthread_exit)
23891 #endif
23892 #ifdef CONFIG_X86_64
23893 BTF_ID(func, __x64_sys_exit)
23894 BTF_ID(func, __x64_sys_exit_group)
23895 #endif
23896 BTF_ID(func, do_exit)
23897 BTF_ID(func, do_group_exit)
23898 BTF_ID(func, kthread_complete_and_exit)
23899 BTF_ID(func, kthread_exit)
23900 BTF_ID(func, make_task_dead)
23901 BTF_SET_END(noreturn_deny)
23902 
23903 static bool can_be_sleepable(struct bpf_prog *prog)
23904 {
23905 	if (prog->type == BPF_PROG_TYPE_TRACING) {
23906 		switch (prog->expected_attach_type) {
23907 		case BPF_TRACE_FENTRY:
23908 		case BPF_TRACE_FEXIT:
23909 		case BPF_MODIFY_RETURN:
23910 		case BPF_TRACE_ITER:
23911 			return true;
23912 		default:
23913 			return false;
23914 		}
23915 	}
23916 	return prog->type == BPF_PROG_TYPE_LSM ||
23917 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
23918 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
23919 }
23920 
check_attach_btf_id(struct bpf_verifier_env * env)23921 static int check_attach_btf_id(struct bpf_verifier_env *env)
23922 {
23923 	struct bpf_prog *prog = env->prog;
23924 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
23925 	struct bpf_attach_target_info tgt_info = {};
23926 	u32 btf_id = prog->aux->attach_btf_id;
23927 	struct bpf_trampoline *tr;
23928 	int ret;
23929 	u64 key;
23930 
23931 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
23932 		if (prog->sleepable)
23933 			/* attach_btf_id checked to be zero already */
23934 			return 0;
23935 		verbose(env, "Syscall programs can only be sleepable\n");
23936 		return -EINVAL;
23937 	}
23938 
23939 	if (prog->sleepable && !can_be_sleepable(prog)) {
23940 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
23941 		return -EINVAL;
23942 	}
23943 
23944 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
23945 		return check_struct_ops_btf_id(env);
23946 
23947 	if (prog->type != BPF_PROG_TYPE_TRACING &&
23948 	    prog->type != BPF_PROG_TYPE_LSM &&
23949 	    prog->type != BPF_PROG_TYPE_EXT)
23950 		return 0;
23951 
23952 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
23953 	if (ret)
23954 		return ret;
23955 
23956 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
23957 		/* to make freplace equivalent to their targets, they need to
23958 		 * inherit env->ops and expected_attach_type for the rest of the
23959 		 * verification
23960 		 */
23961 		env->ops = bpf_verifier_ops[tgt_prog->type];
23962 		prog->expected_attach_type = tgt_prog->expected_attach_type;
23963 	}
23964 
23965 	/* store info about the attachment target that will be used later */
23966 	prog->aux->attach_func_proto = tgt_info.tgt_type;
23967 	prog->aux->attach_func_name = tgt_info.tgt_name;
23968 	prog->aux->mod = tgt_info.tgt_mod;
23969 
23970 	if (tgt_prog) {
23971 		prog->aux->saved_dst_prog_type = tgt_prog->type;
23972 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
23973 	}
23974 
23975 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
23976 		prog->aux->attach_btf_trace = true;
23977 		return 0;
23978 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
23979 		return bpf_iter_prog_supported(prog);
23980 	}
23981 
23982 	if (prog->type == BPF_PROG_TYPE_LSM) {
23983 		ret = bpf_lsm_verify_prog(&env->log, prog);
23984 		if (ret < 0)
23985 			return ret;
23986 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
23987 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
23988 		verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
23989 			tgt_info.tgt_name);
23990 		return -EINVAL;
23991 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
23992 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
23993 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
23994 		verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
23995 			tgt_info.tgt_name);
23996 		return -EINVAL;
23997 	}
23998 
23999 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
24000 	tr = bpf_trampoline_get(key, &tgt_info);
24001 	if (!tr)
24002 		return -ENOMEM;
24003 
24004 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24005 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24006 
24007 	prog->aux->dst_trampoline = tr;
24008 	return 0;
24009 }
24010 
bpf_get_btf_vmlinux(void)24011 struct btf *bpf_get_btf_vmlinux(void)
24012 {
24013 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24014 		mutex_lock(&bpf_verifier_lock);
24015 		if (!btf_vmlinux)
24016 			btf_vmlinux = btf_parse_vmlinux();
24017 		mutex_unlock(&bpf_verifier_lock);
24018 	}
24019 	return btf_vmlinux;
24020 }
24021 
24022 /*
24023  * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24024  * this case expect that every file descriptor in the array is either a map or
24025  * a BTF. Everything else is considered to be trash.
24026  */
add_fd_from_fd_array(struct bpf_verifier_env * env,int fd)24027 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24028 {
24029 	struct bpf_map *map;
24030 	struct btf *btf;
24031 	CLASS(fd, f)(fd);
24032 	int err;
24033 
24034 	map = __bpf_map_get(f);
24035 	if (!IS_ERR(map)) {
24036 		err = __add_used_map(env, map);
24037 		if (err < 0)
24038 			return err;
24039 		return 0;
24040 	}
24041 
24042 	btf = __btf_get_by_fd(f);
24043 	if (!IS_ERR(btf)) {
24044 		err = __add_used_btf(env, btf);
24045 		if (err < 0)
24046 			return err;
24047 		return 0;
24048 	}
24049 
24050 	verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24051 	return PTR_ERR(map);
24052 }
24053 
process_fd_array(struct bpf_verifier_env * env,union bpf_attr * attr,bpfptr_t uattr)24054 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24055 {
24056 	size_t size = sizeof(int);
24057 	int ret;
24058 	int fd;
24059 	u32 i;
24060 
24061 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24062 
24063 	/*
24064 	 * The only difference between old (no fd_array_cnt is given) and new
24065 	 * APIs is that in the latter case the fd_array is expected to be
24066 	 * continuous and is scanned for map fds right away
24067 	 */
24068 	if (!attr->fd_array_cnt)
24069 		return 0;
24070 
24071 	/* Check for integer overflow */
24072 	if (attr->fd_array_cnt >= (U32_MAX / size)) {
24073 		verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24074 		return -EINVAL;
24075 	}
24076 
24077 	for (i = 0; i < attr->fd_array_cnt; i++) {
24078 		if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24079 			return -EFAULT;
24080 
24081 		ret = add_fd_from_fd_array(env, fd);
24082 		if (ret)
24083 			return ret;
24084 	}
24085 
24086 	return 0;
24087 }
24088 
24089 /* Each field is a register bitmask */
24090 struct insn_live_regs {
24091 	u16 use;	/* registers read by instruction */
24092 	u16 def;	/* registers written by instruction */
24093 	u16 in;		/* registers that may be alive before instruction */
24094 	u16 out;	/* registers that may be alive after instruction */
24095 };
24096 
24097 /* Bitmask with 1s for all caller saved registers */
24098 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24099 
24100 /* 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)24101 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24102 				   struct bpf_insn *insn,
24103 				   struct insn_live_regs *info)
24104 {
24105 	struct call_summary cs;
24106 	u8 class = BPF_CLASS(insn->code);
24107 	u8 code = BPF_OP(insn->code);
24108 	u8 mode = BPF_MODE(insn->code);
24109 	u16 src = BIT(insn->src_reg);
24110 	u16 dst = BIT(insn->dst_reg);
24111 	u16 r0  = BIT(0);
24112 	u16 def = 0;
24113 	u16 use = 0xffff;
24114 
24115 	switch (class) {
24116 	case BPF_LD:
24117 		switch (mode) {
24118 		case BPF_IMM:
24119 			if (BPF_SIZE(insn->code) == BPF_DW) {
24120 				def = dst;
24121 				use = 0;
24122 			}
24123 			break;
24124 		case BPF_LD | BPF_ABS:
24125 		case BPF_LD | BPF_IND:
24126 			/* stick with defaults */
24127 			break;
24128 		}
24129 		break;
24130 	case BPF_LDX:
24131 		switch (mode) {
24132 		case BPF_MEM:
24133 		case BPF_MEMSX:
24134 			def = dst;
24135 			use = src;
24136 			break;
24137 		}
24138 		break;
24139 	case BPF_ST:
24140 		switch (mode) {
24141 		case BPF_MEM:
24142 			def = 0;
24143 			use = dst;
24144 			break;
24145 		}
24146 		break;
24147 	case BPF_STX:
24148 		switch (mode) {
24149 		case BPF_MEM:
24150 			def = 0;
24151 			use = dst | src;
24152 			break;
24153 		case BPF_ATOMIC:
24154 			switch (insn->imm) {
24155 			case BPF_CMPXCHG:
24156 				use = r0 | dst | src;
24157 				def = r0;
24158 				break;
24159 			case BPF_LOAD_ACQ:
24160 				def = dst;
24161 				use = src;
24162 				break;
24163 			case BPF_STORE_REL:
24164 				def = 0;
24165 				use = dst | src;
24166 				break;
24167 			default:
24168 				use = dst | src;
24169 				if (insn->imm & BPF_FETCH)
24170 					def = src;
24171 				else
24172 					def = 0;
24173 			}
24174 			break;
24175 		}
24176 		break;
24177 	case BPF_ALU:
24178 	case BPF_ALU64:
24179 		switch (code) {
24180 		case BPF_END:
24181 			use = dst;
24182 			def = dst;
24183 			break;
24184 		case BPF_MOV:
24185 			def = dst;
24186 			if (BPF_SRC(insn->code) == BPF_K)
24187 				use = 0;
24188 			else
24189 				use = src;
24190 			break;
24191 		default:
24192 			def = dst;
24193 			if (BPF_SRC(insn->code) == BPF_K)
24194 				use = dst;
24195 			else
24196 				use = dst | src;
24197 		}
24198 		break;
24199 	case BPF_JMP:
24200 	case BPF_JMP32:
24201 		switch (code) {
24202 		case BPF_JA:
24203 		case BPF_JCOND:
24204 			def = 0;
24205 			use = 0;
24206 			break;
24207 		case BPF_EXIT:
24208 			def = 0;
24209 			use = r0;
24210 			break;
24211 		case BPF_CALL:
24212 			def = ALL_CALLER_SAVED_REGS;
24213 			use = def & ~BIT(BPF_REG_0);
24214 			if (get_call_summary(env, insn, &cs))
24215 				use = GENMASK(cs.num_params, 1);
24216 			break;
24217 		default:
24218 			def = 0;
24219 			if (BPF_SRC(insn->code) == BPF_K)
24220 				use = dst;
24221 			else
24222 				use = dst | src;
24223 		}
24224 		break;
24225 	}
24226 
24227 	info->def = def;
24228 	info->use = use;
24229 }
24230 
24231 /* Compute may-live registers after each instruction in the program.
24232  * The register is live after the instruction I if it is read by some
24233  * instruction S following I during program execution and is not
24234  * overwritten between I and S.
24235  *
24236  * Store result in env->insn_aux_data[i].live_regs.
24237  */
compute_live_registers(struct bpf_verifier_env * env)24238 static int compute_live_registers(struct bpf_verifier_env *env)
24239 {
24240 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24241 	struct bpf_insn *insns = env->prog->insnsi;
24242 	struct insn_live_regs *state;
24243 	int insn_cnt = env->prog->len;
24244 	int err = 0, i, j;
24245 	bool changed;
24246 
24247 	/* Use the following algorithm:
24248 	 * - define the following:
24249 	 *   - I.use : a set of all registers read by instruction I;
24250 	 *   - I.def : a set of all registers written by instruction I;
24251 	 *   - I.in  : a set of all registers that may be alive before I execution;
24252 	 *   - I.out : a set of all registers that may be alive after I execution;
24253 	 *   - insn_successors(I): a set of instructions S that might immediately
24254 	 *                         follow I for some program execution;
24255 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24256 	 * - visit each instruction in a postorder and update
24257 	 *   state[i].in, state[i].out as follows:
24258 	 *
24259 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
24260 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
24261 	 *
24262 	 *   (where U stands for set union, / stands for set difference)
24263 	 * - repeat the computation while {in,out} fields changes for
24264 	 *   any instruction.
24265 	 */
24266 	state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24267 	if (!state) {
24268 		err = -ENOMEM;
24269 		goto out;
24270 	}
24271 
24272 	for (i = 0; i < insn_cnt; ++i)
24273 		compute_insn_live_regs(env, &insns[i], &state[i]);
24274 
24275 	changed = true;
24276 	while (changed) {
24277 		changed = false;
24278 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
24279 			int insn_idx = env->cfg.insn_postorder[i];
24280 			struct insn_live_regs *live = &state[insn_idx];
24281 			int succ_num;
24282 			u32 succ[2];
24283 			u16 new_out = 0;
24284 			u16 new_in = 0;
24285 
24286 			succ_num = bpf_insn_successors(env->prog, insn_idx, succ);
24287 			for (int s = 0; s < succ_num; ++s)
24288 				new_out |= state[succ[s]].in;
24289 			new_in = (new_out & ~live->def) | live->use;
24290 			if (new_out != live->out || new_in != live->in) {
24291 				live->in = new_in;
24292 				live->out = new_out;
24293 				changed = true;
24294 			}
24295 		}
24296 	}
24297 
24298 	for (i = 0; i < insn_cnt; ++i)
24299 		insn_aux[i].live_regs_before = state[i].in;
24300 
24301 	if (env->log.level & BPF_LOG_LEVEL2) {
24302 		verbose(env, "Live regs before insn:\n");
24303 		for (i = 0; i < insn_cnt; ++i) {
24304 			if (env->insn_aux_data[i].scc)
24305 				verbose(env, "%3d ", env->insn_aux_data[i].scc);
24306 			else
24307 				verbose(env, "    ");
24308 			verbose(env, "%3d: ", i);
24309 			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24310 				if (insn_aux[i].live_regs_before & BIT(j))
24311 					verbose(env, "%d", j);
24312 				else
24313 					verbose(env, ".");
24314 			verbose(env, " ");
24315 			verbose_insn(env, &insns[i]);
24316 			if (bpf_is_ldimm64(&insns[i]))
24317 				i++;
24318 		}
24319 	}
24320 
24321 out:
24322 	kvfree(state);
24323 	return err;
24324 }
24325 
24326 /*
24327  * Compute strongly connected components (SCCs) on the CFG.
24328  * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24329  * If instruction is a sole member of its SCC and there are no self edges,
24330  * assign it SCC number of zero.
24331  * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24332  */
compute_scc(struct bpf_verifier_env * env)24333 static int compute_scc(struct bpf_verifier_env *env)
24334 {
24335 	const u32 NOT_ON_STACK = U32_MAX;
24336 
24337 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
24338 	const u32 insn_cnt = env->prog->len;
24339 	int stack_sz, dfs_sz, err = 0;
24340 	u32 *stack, *pre, *low, *dfs;
24341 	u32 succ_cnt, i, j, t, w;
24342 	u32 next_preorder_num;
24343 	u32 next_scc_id;
24344 	bool assign_scc;
24345 	u32 succ[2];
24346 
24347 	next_preorder_num = 1;
24348 	next_scc_id = 1;
24349 	/*
24350 	 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24351 	 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24352 	 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24353 	 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24354 	 */
24355 	stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24356 	pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24357 	low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24358 	dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24359 	if (!stack || !pre || !low || !dfs) {
24360 		err = -ENOMEM;
24361 		goto exit;
24362 	}
24363 	/*
24364 	 * References:
24365 	 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24366 	 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24367 	 *
24368 	 * The algorithm maintains the following invariant:
24369 	 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24370 	 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24371 	 *
24372 	 * Consequently:
24373 	 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24374 	 *   such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24375 	 *   and thus there is an SCC (loop) containing both 'u' and 'v'.
24376 	 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24377 	 *   and 'v' can be considered the root of some SCC.
24378 	 *
24379 	 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24380 	 *
24381 	 *    NOT_ON_STACK = insn_cnt + 1
24382 	 *    pre = [0] * insn_cnt
24383 	 *    low = [0] * insn_cnt
24384 	 *    scc = [0] * insn_cnt
24385 	 *    stack = []
24386 	 *
24387 	 *    next_preorder_num = 1
24388 	 *    next_scc_id = 1
24389 	 *
24390 	 *    def recur(w):
24391 	 *        nonlocal next_preorder_num
24392 	 *        nonlocal next_scc_id
24393 	 *
24394 	 *        pre[w] = next_preorder_num
24395 	 *        low[w] = next_preorder_num
24396 	 *        next_preorder_num += 1
24397 	 *        stack.append(w)
24398 	 *        for s in successors(w):
24399 	 *            # Note: for classic algorithm the block below should look as:
24400 	 *            #
24401 	 *            # if pre[s] == 0:
24402 	 *            #     recur(s)
24403 	 *            #	    low[w] = min(low[w], low[s])
24404 	 *            # elif low[s] != NOT_ON_STACK:
24405 	 *            #     low[w] = min(low[w], pre[s])
24406 	 *            #
24407 	 *            # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
24408 	 *            # does not break the invariant and makes itartive version of the algorithm
24409 	 *            # simpler. See 'Algorithm #3' from [2].
24410 	 *
24411 	 *            # 's' not yet visited
24412 	 *            if pre[s] == 0:
24413 	 *                recur(s)
24414 	 *            # if 's' is on stack, pick lowest reachable preorder number from it;
24415 	 *            # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
24416 	 *            # so 'min' would be a noop.
24417 	 *            low[w] = min(low[w], low[s])
24418 	 *
24419 	 *        if low[w] == pre[w]:
24420 	 *            # 'w' is the root of an SCC, pop all vertices
24421 	 *            # below 'w' on stack and assign same SCC to them.
24422 	 *            while True:
24423 	 *                t = stack.pop()
24424 	 *                low[t] = NOT_ON_STACK
24425 	 *                scc[t] = next_scc_id
24426 	 *                if t == w:
24427 	 *                    break
24428 	 *            next_scc_id += 1
24429 	 *
24430 	 *    for i in range(0, insn_cnt):
24431 	 *        if pre[i] == 0:
24432 	 *            recur(i)
24433 	 *
24434 	 * Below implementation replaces explicit recursion with array 'dfs'.
24435 	 */
24436 	for (i = 0; i < insn_cnt; i++) {
24437 		if (pre[i])
24438 			continue;
24439 		stack_sz = 0;
24440 		dfs_sz = 1;
24441 		dfs[0] = i;
24442 dfs_continue:
24443 		while (dfs_sz) {
24444 			w = dfs[dfs_sz - 1];
24445 			if (pre[w] == 0) {
24446 				low[w] = next_preorder_num;
24447 				pre[w] = next_preorder_num;
24448 				next_preorder_num++;
24449 				stack[stack_sz++] = w;
24450 			}
24451 			/* Visit 'w' successors */
24452 			succ_cnt = bpf_insn_successors(env->prog, w, succ);
24453 			for (j = 0; j < succ_cnt; ++j) {
24454 				if (pre[succ[j]]) {
24455 					low[w] = min(low[w], low[succ[j]]);
24456 				} else {
24457 					dfs[dfs_sz++] = succ[j];
24458 					goto dfs_continue;
24459 				}
24460 			}
24461 			/*
24462 			 * Preserve the invariant: if some vertex above in the stack
24463 			 * is reachable from 'w', keep 'w' on the stack.
24464 			 */
24465 			if (low[w] < pre[w]) {
24466 				dfs_sz--;
24467 				goto dfs_continue;
24468 			}
24469 			/*
24470 			 * Assign SCC number only if component has two or more elements,
24471 			 * or if component has a self reference.
24472 			 */
24473 			assign_scc = stack[stack_sz - 1] != w;
24474 			for (j = 0; j < succ_cnt; ++j) {
24475 				if (succ[j] == w) {
24476 					assign_scc = true;
24477 					break;
24478 				}
24479 			}
24480 			/* Pop component elements from stack */
24481 			do {
24482 				t = stack[--stack_sz];
24483 				low[t] = NOT_ON_STACK;
24484 				if (assign_scc)
24485 					aux[t].scc = next_scc_id;
24486 			} while (t != w);
24487 			if (assign_scc)
24488 				next_scc_id++;
24489 			dfs_sz--;
24490 		}
24491 	}
24492 	env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
24493 	if (!env->scc_info) {
24494 		err = -ENOMEM;
24495 		goto exit;
24496 	}
24497 	env->scc_cnt = next_scc_id;
24498 exit:
24499 	kvfree(stack);
24500 	kvfree(pre);
24501 	kvfree(low);
24502 	kvfree(dfs);
24503 	return err;
24504 }
24505 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)24506 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
24507 {
24508 	u64 start_time = ktime_get_ns();
24509 	struct bpf_verifier_env *env;
24510 	int i, len, ret = -EINVAL, err;
24511 	u32 log_true_size;
24512 	bool is_priv;
24513 
24514 	BTF_TYPE_EMIT(enum bpf_features);
24515 
24516 	/* no program is valid */
24517 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
24518 		return -EINVAL;
24519 
24520 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
24521 	 * allocate/free it every time bpf_check() is called
24522 	 */
24523 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
24524 	if (!env)
24525 		return -ENOMEM;
24526 
24527 	env->bt.env = env;
24528 
24529 	len = (*prog)->len;
24530 	env->insn_aux_data =
24531 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
24532 	ret = -ENOMEM;
24533 	if (!env->insn_aux_data)
24534 		goto err_free_env;
24535 	for (i = 0; i < len; i++)
24536 		env->insn_aux_data[i].orig_idx = i;
24537 	env->prog = *prog;
24538 	env->ops = bpf_verifier_ops[env->prog->type];
24539 
24540 	env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
24541 	env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
24542 	env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
24543 	env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
24544 	env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
24545 
24546 	bpf_get_btf_vmlinux();
24547 
24548 	/* grab the mutex to protect few globals used by verifier */
24549 	if (!is_priv)
24550 		mutex_lock(&bpf_verifier_lock);
24551 
24552 	/* user could have requested verbose verifier output
24553 	 * and supplied buffer to store the verification trace
24554 	 */
24555 	ret = bpf_vlog_init(&env->log, attr->log_level,
24556 			    (char __user *) (unsigned long) attr->log_buf,
24557 			    attr->log_size);
24558 	if (ret)
24559 		goto err_unlock;
24560 
24561 	ret = process_fd_array(env, attr, uattr);
24562 	if (ret)
24563 		goto skip_full_check;
24564 
24565 	mark_verifier_state_clean(env);
24566 
24567 	if (IS_ERR(btf_vmlinux)) {
24568 		/* Either gcc or pahole or kernel are broken. */
24569 		verbose(env, "in-kernel BTF is malformed\n");
24570 		ret = PTR_ERR(btf_vmlinux);
24571 		goto skip_full_check;
24572 	}
24573 
24574 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
24575 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
24576 		env->strict_alignment = true;
24577 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
24578 		env->strict_alignment = false;
24579 
24580 	if (is_priv)
24581 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
24582 	env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
24583 
24584 	env->explored_states = kvcalloc(state_htab_size(env),
24585 				       sizeof(struct list_head),
24586 				       GFP_KERNEL_ACCOUNT);
24587 	ret = -ENOMEM;
24588 	if (!env->explored_states)
24589 		goto skip_full_check;
24590 
24591 	for (i = 0; i < state_htab_size(env); i++)
24592 		INIT_LIST_HEAD(&env->explored_states[i]);
24593 	INIT_LIST_HEAD(&env->free_list);
24594 
24595 	ret = check_btf_info_early(env, attr, uattr);
24596 	if (ret < 0)
24597 		goto skip_full_check;
24598 
24599 	ret = add_subprog_and_kfunc(env);
24600 	if (ret < 0)
24601 		goto skip_full_check;
24602 
24603 	ret = check_subprogs(env);
24604 	if (ret < 0)
24605 		goto skip_full_check;
24606 
24607 	ret = check_btf_info(env, attr, uattr);
24608 	if (ret < 0)
24609 		goto skip_full_check;
24610 
24611 	ret = resolve_pseudo_ldimm64(env);
24612 	if (ret < 0)
24613 		goto skip_full_check;
24614 
24615 	if (bpf_prog_is_offloaded(env->prog->aux)) {
24616 		ret = bpf_prog_offload_verifier_prep(env->prog);
24617 		if (ret)
24618 			goto skip_full_check;
24619 	}
24620 
24621 	ret = check_cfg(env);
24622 	if (ret < 0)
24623 		goto skip_full_check;
24624 
24625 	ret = compute_postorder(env);
24626 	if (ret < 0)
24627 		goto skip_full_check;
24628 
24629 	ret = bpf_stack_liveness_init(env);
24630 	if (ret)
24631 		goto skip_full_check;
24632 
24633 	ret = check_attach_btf_id(env);
24634 	if (ret)
24635 		goto skip_full_check;
24636 
24637 	ret = compute_scc(env);
24638 	if (ret < 0)
24639 		goto skip_full_check;
24640 
24641 	ret = compute_live_registers(env);
24642 	if (ret < 0)
24643 		goto skip_full_check;
24644 
24645 	ret = mark_fastcall_patterns(env);
24646 	if (ret < 0)
24647 		goto skip_full_check;
24648 
24649 	ret = do_check_main(env);
24650 	ret = ret ?: do_check_subprogs(env);
24651 
24652 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
24653 		ret = bpf_prog_offload_finalize(env);
24654 
24655 skip_full_check:
24656 	kvfree(env->explored_states);
24657 
24658 	/* might decrease stack depth, keep it before passes that
24659 	 * allocate additional slots.
24660 	 */
24661 	if (ret == 0)
24662 		ret = remove_fastcall_spills_fills(env);
24663 
24664 	if (ret == 0)
24665 		ret = check_max_stack_depth(env);
24666 
24667 	/* instruction rewrites happen after this point */
24668 	if (ret == 0)
24669 		ret = optimize_bpf_loop(env);
24670 
24671 	if (is_priv) {
24672 		if (ret == 0)
24673 			opt_hard_wire_dead_code_branches(env);
24674 		if (ret == 0)
24675 			ret = opt_remove_dead_code(env);
24676 		if (ret == 0)
24677 			ret = opt_remove_nops(env);
24678 	} else {
24679 		if (ret == 0)
24680 			sanitize_dead_code(env);
24681 	}
24682 
24683 	if (ret == 0)
24684 		/* program is valid, convert *(u32*)(ctx + off) accesses */
24685 		ret = convert_ctx_accesses(env);
24686 
24687 	if (ret == 0)
24688 		ret = do_misc_fixups(env);
24689 
24690 	/* do 32-bit optimization after insn patching has done so those patched
24691 	 * insns could be handled correctly.
24692 	 */
24693 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
24694 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
24695 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
24696 								     : false;
24697 	}
24698 
24699 	if (ret == 0)
24700 		ret = fixup_call_args(env);
24701 
24702 	env->verification_time = ktime_get_ns() - start_time;
24703 	print_verification_stats(env);
24704 	env->prog->aux->verified_insns = env->insn_processed;
24705 
24706 	/* preserve original error even if log finalization is successful */
24707 	err = bpf_vlog_finalize(&env->log, &log_true_size);
24708 	if (err)
24709 		ret = err;
24710 
24711 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
24712 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
24713 				  &log_true_size, sizeof(log_true_size))) {
24714 		ret = -EFAULT;
24715 		goto err_release_maps;
24716 	}
24717 
24718 	if (ret)
24719 		goto err_release_maps;
24720 
24721 	if (env->used_map_cnt) {
24722 		/* if program passed verifier, update used_maps in bpf_prog_info */
24723 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
24724 							  sizeof(env->used_maps[0]),
24725 							  GFP_KERNEL_ACCOUNT);
24726 
24727 		if (!env->prog->aux->used_maps) {
24728 			ret = -ENOMEM;
24729 			goto err_release_maps;
24730 		}
24731 
24732 		memcpy(env->prog->aux->used_maps, env->used_maps,
24733 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
24734 		env->prog->aux->used_map_cnt = env->used_map_cnt;
24735 	}
24736 	if (env->used_btf_cnt) {
24737 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
24738 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
24739 							  sizeof(env->used_btfs[0]),
24740 							  GFP_KERNEL_ACCOUNT);
24741 		if (!env->prog->aux->used_btfs) {
24742 			ret = -ENOMEM;
24743 			goto err_release_maps;
24744 		}
24745 
24746 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
24747 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
24748 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
24749 	}
24750 	if (env->used_map_cnt || env->used_btf_cnt) {
24751 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
24752 		 * bpf_ld_imm64 instructions
24753 		 */
24754 		convert_pseudo_ld_imm64(env);
24755 	}
24756 
24757 	adjust_btf_func(env);
24758 
24759 err_release_maps:
24760 	if (!env->prog->aux->used_maps)
24761 		/* if we didn't copy map pointers into bpf_prog_info, release
24762 		 * them now. Otherwise free_used_maps() will release them.
24763 		 */
24764 		release_maps(env);
24765 	if (!env->prog->aux->used_btfs)
24766 		release_btfs(env);
24767 
24768 	/* extension progs temporarily inherit the attach_type of their targets
24769 	   for verification purposes, so set it back to zero before returning
24770 	 */
24771 	if (env->prog->type == BPF_PROG_TYPE_EXT)
24772 		env->prog->expected_attach_type = 0;
24773 
24774 	*prog = env->prog;
24775 
24776 	module_put(env->attach_btf_mod);
24777 err_unlock:
24778 	if (!is_priv)
24779 		mutex_unlock(&bpf_verifier_lock);
24780 	vfree(env->insn_aux_data);
24781 err_free_env:
24782 	bpf_stack_liveness_free(env);
24783 	kvfree(env->cfg.insn_postorder);
24784 	kvfree(env->scc_info);
24785 	kvfree(env);
24786 	return ret;
24787 }
24788