xref: /openbmc/linux/kernel/bpf/verifier.c (revision 4d75f5c664195b970e1cd2fd25b65b5eff257a0a)
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 <net/xdp.h>
30 
31 #include "disasm.h"
32 
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 	[_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43 
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168 
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 	/* verifer state is 'st'
172 	 * before processing instruction 'insn_idx'
173 	 * and after processing instruction 'prev_insn_idx'
174 	 */
175 	struct bpf_verifier_state st;
176 	int insn_idx;
177 	int prev_insn_idx;
178 	struct bpf_verifier_stack_elem *next;
179 	/* length of verifier log at the time this state was pushed on stack */
180 	u32 log_pos;
181 };
182 
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184 #define BPF_COMPLEXITY_LIMIT_STATES	64
185 
186 #define BPF_MAP_KEY_POISON	(1ULL << 63)
187 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188 
189 #define BPF_MAP_PTR_UNPRIV	1UL
190 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191 					  POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193 
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 			      struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 			     u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213 
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 			      const struct bpf_map *map, bool unpriv)
216 {
217 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 	unpriv |= bpf_map_ptr_unpriv(aux);
219 	aux->map_ptr_state = (unsigned long)map |
220 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237 
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 	bool poisoned = bpf_map_key_poisoned(aux);
241 
242 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245 
bpf_helper_call(const struct bpf_insn * insn)246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 	return insn->code == (BPF_JMP | BPF_CALL) &&
249 	       insn->src_reg == 0;
250 }
251 
bpf_pseudo_call(const struct bpf_insn * insn)252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 	return insn->code == (BPF_JMP | BPF_CALL) &&
255 	       insn->src_reg == BPF_PSEUDO_CALL;
256 }
257 
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 	return insn->code == (BPF_JMP | BPF_CALL) &&
261 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263 
264 struct bpf_call_arg_meta {
265 	struct bpf_map *map_ptr;
266 	bool raw_mode;
267 	bool pkt_access;
268 	u8 release_regno;
269 	int regno;
270 	int access_size;
271 	int mem_size;
272 	u64 msize_max_value;
273 	int ref_obj_id;
274 	int dynptr_id;
275 	int map_uid;
276 	int func_id;
277 	struct btf *btf;
278 	u32 btf_id;
279 	struct btf *ret_btf;
280 	u32 ret_btf_id;
281 	u32 subprogno;
282 	struct btf_field *kptr_field;
283 };
284 
285 struct bpf_kfunc_call_arg_meta {
286 	/* In parameters */
287 	struct btf *btf;
288 	u32 func_id;
289 	u32 kfunc_flags;
290 	const struct btf_type *func_proto;
291 	const char *func_name;
292 	/* Out parameters */
293 	u32 ref_obj_id;
294 	u8 release_regno;
295 	bool r0_rdonly;
296 	u32 ret_btf_id;
297 	u64 r0_size;
298 	u32 subprogno;
299 	struct {
300 		u64 value;
301 		bool found;
302 	} arg_constant;
303 
304 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 	 * generally to pass info about user-defined local kptr types to later
306 	 * verification logic
307 	 *   bpf_obj_drop
308 	 *     Record the local kptr type to be drop'd
309 	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 	 *     Record the local kptr type to be refcount_incr'd and use
311 	 *     arg_owning_ref to determine whether refcount_acquire should be
312 	 *     fallible
313 	 */
314 	struct btf *arg_btf;
315 	u32 arg_btf_id;
316 	bool arg_owning_ref;
317 
318 	struct {
319 		struct btf_field *field;
320 	} arg_list_head;
321 	struct {
322 		struct btf_field *field;
323 	} arg_rbtree_root;
324 	struct {
325 		enum bpf_dynptr_type type;
326 		u32 id;
327 		u32 ref_obj_id;
328 	} initialized_dynptr;
329 	struct {
330 		u8 spi;
331 		u8 frameno;
332 	} iter;
333 	u64 mem_size;
334 };
335 
336 struct btf *btf_vmlinux;
337 
338 static DEFINE_MUTEX(bpf_verifier_lock);
339 
340 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 	const struct bpf_line_info *linfo;
344 	const struct bpf_prog *prog;
345 	u32 i, nr_linfo;
346 
347 	prog = env->prog;
348 	nr_linfo = prog->aux->nr_linfo;
349 
350 	if (!nr_linfo || insn_off >= prog->len)
351 		return NULL;
352 
353 	linfo = prog->aux->linfo;
354 	for (i = 1; i < nr_linfo; i++)
355 		if (insn_off < linfo[i].insn_off)
356 			break;
357 
358 	return &linfo[i - 1];
359 }
360 
verbose(void * private_data,const char * fmt,...)361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 	struct bpf_verifier_env *env = private_data;
364 	va_list args;
365 
366 	if (!bpf_verifier_log_needed(&env->log))
367 		return;
368 
369 	va_start(args, fmt);
370 	bpf_verifier_vlog(&env->log, fmt, args);
371 	va_end(args);
372 }
373 
ltrim(const char * s)374 static const char *ltrim(const char *s)
375 {
376 	while (isspace(*s))
377 		s++;
378 
379 	return s;
380 }
381 
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 					 u32 insn_off,
384 					 const char *prefix_fmt, ...)
385 {
386 	const struct bpf_line_info *linfo;
387 
388 	if (!bpf_verifier_log_needed(&env->log))
389 		return;
390 
391 	linfo = find_linfo(env, insn_off);
392 	if (!linfo || linfo == env->prev_linfo)
393 		return;
394 
395 	if (prefix_fmt) {
396 		va_list args;
397 
398 		va_start(args, prefix_fmt);
399 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 		va_end(args);
401 	}
402 
403 	verbose(env, "%s\n",
404 		ltrim(btf_name_by_offset(env->prog->aux->btf,
405 					 linfo->line_off)));
406 
407 	env->prev_linfo = linfo;
408 }
409 
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct tnum * range,const char * ctx,const char * reg_name)410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 				   struct bpf_reg_state *reg,
412 				   struct tnum *range, const char *ctx,
413 				   const char *reg_name)
414 {
415 	char tn_buf[48];
416 
417 	verbose(env, "At %s the register %s ", ctx, reg_name);
418 	if (!tnum_is_unknown(reg->var_off)) {
419 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 		verbose(env, "has value %s", tn_buf);
421 	} else {
422 		verbose(env, "has unknown scalar value");
423 	}
424 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 	verbose(env, " should have been in %s\n", tn_buf);
426 }
427 
type_is_pkt_pointer(enum bpf_reg_type type)428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 	type = base_type(type);
431 	return type == PTR_TO_PACKET ||
432 	       type == PTR_TO_PACKET_META;
433 }
434 
type_is_sk_pointer(enum bpf_reg_type type)435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 	return type == PTR_TO_SOCKET ||
438 		type == PTR_TO_SOCK_COMMON ||
439 		type == PTR_TO_TCP_SOCK ||
440 		type == PTR_TO_XDP_SOCK;
441 }
442 
type_may_be_null(u32 type)443 static bool type_may_be_null(u32 type)
444 {
445 	return type & PTR_MAYBE_NULL;
446 }
447 
reg_not_null(const struct bpf_reg_state * reg)448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 	enum bpf_reg_type type;
451 
452 	type = reg->type;
453 	if (type_may_be_null(type))
454 		return false;
455 
456 	type = base_type(type);
457 	return type == PTR_TO_SOCKET ||
458 		type == PTR_TO_TCP_SOCK ||
459 		type == PTR_TO_MAP_VALUE ||
460 		type == PTR_TO_MAP_KEY ||
461 		type == PTR_TO_SOCK_COMMON ||
462 		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 		type == PTR_TO_MEM;
464 }
465 
type_is_ptr_alloc_obj(u32 type)466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470 
type_is_non_owning_ref(u32 type)471 static bool type_is_non_owning_ref(u32 type)
472 {
473 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475 
reg_btf_record(const struct bpf_reg_state * reg)476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 	struct btf_record *rec = NULL;
479 	struct btf_struct_meta *meta;
480 
481 	if (reg->type == PTR_TO_MAP_VALUE) {
482 		rec = reg->map_ptr->record;
483 	} else if (type_is_ptr_alloc_obj(reg->type)) {
484 		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 		if (meta)
486 			rec = meta->record;
487 	}
488 	return rec;
489 }
490 
subprog_is_global(const struct bpf_verifier_env * env,int subprog)491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494 
495 	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502 
type_is_rdonly_mem(u32 type)503 static bool type_is_rdonly_mem(u32 type)
504 {
505 	return type & MEM_RDONLY;
506 }
507 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)508 static bool is_acquire_function(enum bpf_func_id func_id,
509 				const struct bpf_map *map)
510 {
511 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512 
513 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 	    func_id == BPF_FUNC_sk_lookup_udp ||
515 	    func_id == BPF_FUNC_skc_lookup_tcp ||
516 	    func_id == BPF_FUNC_ringbuf_reserve ||
517 	    func_id == BPF_FUNC_kptr_xchg)
518 		return true;
519 
520 	if (func_id == BPF_FUNC_map_lookup_elem &&
521 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 	     map_type == BPF_MAP_TYPE_SOCKHASH))
523 		return true;
524 
525 	return false;
526 }
527 
is_ptr_cast_function(enum bpf_func_id func_id)528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 	return func_id == BPF_FUNC_tcp_sock ||
531 		func_id == BPF_FUNC_sk_fullsock ||
532 		func_id == BPF_FUNC_skc_to_tcp_sock ||
533 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 		func_id == BPF_FUNC_skc_to_udp6_sock ||
535 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539 
is_dynptr_ref_function(enum bpf_func_id func_id)540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 	return func_id == BPF_FUNC_dynptr_data;
543 }
544 
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546 
is_sync_callback_calling_function(enum bpf_func_id func_id)547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 	return func_id == BPF_FUNC_for_each_map_elem ||
550 	       func_id == BPF_FUNC_find_vma ||
551 	       func_id == BPF_FUNC_loop ||
552 	       func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554 
is_async_callback_calling_function(enum bpf_func_id func_id)555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 	return func_id == BPF_FUNC_timer_set_callback;
558 }
559 
is_callback_calling_function(enum bpf_func_id func_id)560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 	return is_sync_callback_calling_function(func_id) ||
563 	       is_async_callback_calling_function(func_id);
564 }
565 
is_sync_callback_calling_insn(struct bpf_insn * insn)566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571 
is_storage_get_function(enum bpf_func_id func_id)572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 	return func_id == BPF_FUNC_sk_storage_get ||
575 	       func_id == BPF_FUNC_inode_storage_get ||
576 	       func_id == BPF_FUNC_task_storage_get ||
577 	       func_id == BPF_FUNC_cgrp_storage_get;
578 }
579 
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 					const struct bpf_map *map)
582 {
583 	int ref_obj_uses = 0;
584 
585 	if (is_ptr_cast_function(func_id))
586 		ref_obj_uses++;
587 	if (is_acquire_function(func_id, map))
588 		ref_obj_uses++;
589 	if (is_dynptr_ref_function(func_id))
590 		ref_obj_uses++;
591 
592 	return ref_obj_uses > 1;
593 }
594 
is_cmpxchg_insn(const struct bpf_insn * insn)595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 	return BPF_CLASS(insn->code) == BPF_STX &&
598 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599 	       insn->imm == BPF_CMPXCHG;
600 }
601 
602 /* string representation of 'enum bpf_reg_type'
603  *
604  * Note that reg_type_str() can not appear more than once in a single verbose()
605  * statement.
606  */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 				enum bpf_reg_type type)
609 {
610 	char postfix[16] = {0}, prefix[64] = {0};
611 	static const char * const str[] = {
612 		[NOT_INIT]		= "?",
613 		[SCALAR_VALUE]		= "scalar",
614 		[PTR_TO_CTX]		= "ctx",
615 		[CONST_PTR_TO_MAP]	= "map_ptr",
616 		[PTR_TO_MAP_VALUE]	= "map_value",
617 		[PTR_TO_STACK]		= "fp",
618 		[PTR_TO_PACKET]		= "pkt",
619 		[PTR_TO_PACKET_META]	= "pkt_meta",
620 		[PTR_TO_PACKET_END]	= "pkt_end",
621 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622 		[PTR_TO_SOCKET]		= "sock",
623 		[PTR_TO_SOCK_COMMON]	= "sock_common",
624 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627 		[PTR_TO_BTF_ID]		= "ptr_",
628 		[PTR_TO_MEM]		= "mem",
629 		[PTR_TO_BUF]		= "buf",
630 		[PTR_TO_FUNC]		= "func",
631 		[PTR_TO_MAP_KEY]	= "map_key",
632 		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633 	};
634 
635 	if (type & PTR_MAYBE_NULL) {
636 		if (base_type(type) == PTR_TO_BTF_ID)
637 			strncpy(postfix, "or_null_", 16);
638 		else
639 			strncpy(postfix, "_or_null", 16);
640 	}
641 
642 	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 		 type & MEM_RDONLY ? "rdonly_" : "",
644 		 type & MEM_RINGBUF ? "ringbuf_" : "",
645 		 type & MEM_USER ? "user_" : "",
646 		 type & MEM_PERCPU ? "percpu_" : "",
647 		 type & MEM_RCU ? "rcu_" : "",
648 		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 		 type & PTR_TRUSTED ? "trusted_" : ""
650 	);
651 
652 	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 		 prefix, str[base_type(type)], postfix);
654 	return env->tmp_str_buf;
655 }
656 
657 static char slot_type_char[] = {
658 	[STACK_INVALID]	= '?',
659 	[STACK_SPILL]	= 'r',
660 	[STACK_MISC]	= 'm',
661 	[STACK_ZERO]	= '0',
662 	[STACK_DYNPTR]	= 'd',
663 	[STACK_ITER]	= 'i',
664 };
665 
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)666 static void print_liveness(struct bpf_verifier_env *env,
667 			   enum bpf_reg_liveness live)
668 {
669 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 	    verbose(env, "_");
671 	if (live & REG_LIVE_READ)
672 		verbose(env, "r");
673 	if (live & REG_LIVE_WRITTEN)
674 		verbose(env, "w");
675 	if (live & REG_LIVE_DONE)
676 		verbose(env, "D");
677 }
678 
__get_spi(s32 off)679 static int __get_spi(s32 off)
680 {
681 	return (-off - 1) / BPF_REG_SIZE;
682 }
683 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 				   const struct bpf_reg_state *reg)
686 {
687 	struct bpf_verifier_state *cur = env->cur_state;
688 
689 	return cur->frame[reg->frameno];
690 }
691 
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695 
696        /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 	* within [0, allocated_stack).
698 	*
699 	* Please note that the spi grows downwards. For example, a dynptr
700 	* takes the size of two stack slots; the first slot will be at
701 	* spi and the second slot will be at spi - 1.
702 	*/
703        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705 
stack_slot_obj_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * obj_kind,int nr_slots)706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 			          const char *obj_kind, int nr_slots)
708 {
709 	int off, spi;
710 
711 	if (!tnum_is_const(reg->var_off)) {
712 		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 		return -EINVAL;
714 	}
715 
716 	off = reg->off + reg->var_off.value;
717 	if (off % BPF_REG_SIZE) {
718 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 		return -EINVAL;
720 	}
721 
722 	spi = __get_spi(off);
723 	if (spi + 1 < nr_slots) {
724 		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 		return -EINVAL;
726 	}
727 
728 	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 		return -ERANGE;
730 	return spi;
731 }
732 
dynptr_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737 
iter_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742 
btf_type_name(const struct btf * btf,u32 id)743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747 
dynptr_type_str(enum bpf_dynptr_type type)748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 	switch (type) {
751 	case BPF_DYNPTR_TYPE_LOCAL:
752 		return "local";
753 	case BPF_DYNPTR_TYPE_RINGBUF:
754 		return "ringbuf";
755 	case BPF_DYNPTR_TYPE_SKB:
756 		return "skb";
757 	case BPF_DYNPTR_TYPE_XDP:
758 		return "xdp";
759 	case BPF_DYNPTR_TYPE_INVALID:
760 		return "<invalid>";
761 	default:
762 		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 		return "<unknown>";
764 	}
765 }
766 
iter_type_str(const struct btf * btf,u32 btf_id)767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 	if (!btf || btf_id == 0)
770 		return "<invalid>";
771 
772 	/* we already validated that type is valid and has conforming name */
773 	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775 
iter_state_str(enum bpf_iter_state state)776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 	switch (state) {
779 	case BPF_ITER_STATE_ACTIVE:
780 		return "active";
781 	case BPF_ITER_STATE_DRAINED:
782 		return "drained";
783 	case BPF_ITER_STATE_INVALID:
784 		return "<invalid>";
785 	default:
786 		WARN_ONCE(1, "unknown iter state %d\n", state);
787 		return "<unknown>";
788 	}
789 }
790 
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 	env->scratched_regs |= 1U << regno;
794 }
795 
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 	env->scratched_stack_slots |= 1ULL << spi;
799 }
800 
reg_scratched(const struct bpf_verifier_env * env,u32 regno)801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 	return (env->scratched_regs >> regno) & 1;
804 }
805 
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 	return (env->scratched_stack_slots >> regno) & 1;
809 }
810 
verifier_state_scratched(const struct bpf_verifier_env * env)811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 	return env->scratched_regs || env->scratched_stack_slots;
814 }
815 
mark_verifier_state_clean(struct bpf_verifier_env * env)816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 	env->scratched_regs = 0U;
819 	env->scratched_stack_slots = 0ULL;
820 }
821 
822 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 	env->scratched_regs = ~0U;
826 	env->scratched_stack_slots = ~0ULL;
827 }
828 
arg_to_dynptr_type(enum bpf_arg_type arg_type)829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 	case DYNPTR_TYPE_LOCAL:
833 		return BPF_DYNPTR_TYPE_LOCAL;
834 	case DYNPTR_TYPE_RINGBUF:
835 		return BPF_DYNPTR_TYPE_RINGBUF;
836 	case DYNPTR_TYPE_SKB:
837 		return BPF_DYNPTR_TYPE_SKB;
838 	case DYNPTR_TYPE_XDP:
839 		return BPF_DYNPTR_TYPE_XDP;
840 	default:
841 		return BPF_DYNPTR_TYPE_INVALID;
842 	}
843 }
844 
get_dynptr_type_flag(enum bpf_dynptr_type type)845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 	switch (type) {
848 	case BPF_DYNPTR_TYPE_LOCAL:
849 		return DYNPTR_TYPE_LOCAL;
850 	case BPF_DYNPTR_TYPE_RINGBUF:
851 		return DYNPTR_TYPE_RINGBUF;
852 	case BPF_DYNPTR_TYPE_SKB:
853 		return DYNPTR_TYPE_SKB;
854 	case BPF_DYNPTR_TYPE_XDP:
855 		return DYNPTR_TYPE_XDP;
856 	default:
857 		return 0;
858 	}
859 }
860 
dynptr_type_refcounted(enum bpf_dynptr_type type)861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 	return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865 
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 			      enum bpf_dynptr_type type,
868 			      bool first_slot, int dynptr_id);
869 
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 				struct bpf_reg_state *reg);
872 
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 				   struct bpf_reg_state *sreg1,
875 				   struct bpf_reg_state *sreg2,
876 				   enum bpf_dynptr_type type)
877 {
878 	int id = ++env->id_gen;
879 
880 	__mark_dynptr_reg(sreg1, type, true, id);
881 	__mark_dynptr_reg(sreg2, type, false, id);
882 }
883 
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 			       struct bpf_reg_state *reg,
886 			       enum bpf_dynptr_type type)
887 {
888 	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890 
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 				        struct bpf_func_state *state, int spi);
893 
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)894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 	struct bpf_func_state *state = func(env, reg);
898 	enum bpf_dynptr_type type;
899 	int spi, i, err;
900 
901 	spi = dynptr_get_spi(env, reg);
902 	if (spi < 0)
903 		return spi;
904 
905 	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 	 * to ensure that for the following example:
908 	 *	[d1][d1][d2][d2]
909 	 * spi    3   2   1   0
910 	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 	 * case they do belong to same dynptr, second call won't see slot_type
912 	 * as STACK_DYNPTR and will simply skip destruction.
913 	 */
914 	err = destroy_if_dynptr_stack_slot(env, state, spi);
915 	if (err)
916 		return err;
917 	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 	if (err)
919 		return err;
920 
921 	for (i = 0; i < BPF_REG_SIZE; i++) {
922 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 	}
925 
926 	type = arg_to_dynptr_type(arg_type);
927 	if (type == BPF_DYNPTR_TYPE_INVALID)
928 		return -EINVAL;
929 
930 	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 			       &state->stack[spi - 1].spilled_ptr, type);
932 
933 	if (dynptr_type_refcounted(type)) {
934 		/* The id is used to track proper releasing */
935 		int id;
936 
937 		if (clone_ref_obj_id)
938 			id = clone_ref_obj_id;
939 		else
940 			id = acquire_reference_state(env, insn_idx);
941 
942 		if (id < 0)
943 			return id;
944 
945 		state->stack[spi].spilled_ptr.ref_obj_id = id;
946 		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 	}
948 
949 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951 
952 	return 0;
953 }
954 
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 	int i;
958 
959 	for (i = 0; i < BPF_REG_SIZE; i++) {
960 		state->stack[spi].slot_type[i] = STACK_INVALID;
961 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 	}
963 
964 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966 
967 	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 	 *
969 	 * While we don't allow reading STACK_INVALID, it is still possible to
970 	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 	 * helpers or insns can do partial read of that part without failing,
972 	 * but check_stack_range_initialized, check_stack_read_var_off, and
973 	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 	 * the slot conservatively. Hence we need to prevent those liveness
975 	 * marking walks.
976 	 *
977 	 * This was not a problem before because STACK_INVALID is only set by
978 	 * default (where the default reg state has its reg->parent as NULL), or
979 	 * in clean_live_states after REG_LIVE_DONE (at which point
980 	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 	 * verifier state exploration (like we did above). Hence, for our case
982 	 * parentage chain will still be live (i.e. reg->parent may be
983 	 * non-NULL), while earlier reg->parent was NULL, so we need
984 	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 	 * done later on reads or by mark_dynptr_read as well to unnecessary
986 	 * mark registers in verifier state.
987 	 */
988 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991 
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 	struct bpf_func_state *state = func(env, reg);
995 	int spi, ref_obj_id, i;
996 
997 	spi = dynptr_get_spi(env, reg);
998 	if (spi < 0)
999 		return spi;
1000 
1001 	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 		invalidate_dynptr(env, state, spi);
1003 		return 0;
1004 	}
1005 
1006 	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007 
1008 	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009 	 * two things:
1010 	 *
1011 	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 	 * 2) Any slices derived from this dynptr.
1013 	 */
1014 
1015 	/* Invalidate any slices associated with this dynptr */
1016 	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017 
1018 	/* Invalidate any dynptr clones */
1019 	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 			continue;
1022 
1023 		/* it should always be the case that if the ref obj id
1024 		 * matches then the stack slot also belongs to a
1025 		 * dynptr
1026 		 */
1027 		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 			return -EFAULT;
1030 		}
1031 		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 			invalidate_dynptr(env, state, i);
1033 	}
1034 
1035 	return 0;
1036 }
1037 
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 			       struct bpf_reg_state *reg);
1040 
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 	if (!env->allow_ptr_leaks)
1044 		__mark_reg_not_init(env, reg);
1045 	else
1046 		__mark_reg_unknown(env, reg);
1047 }
1048 
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 				        struct bpf_func_state *state, int spi)
1051 {
1052 	struct bpf_func_state *fstate;
1053 	struct bpf_reg_state *dreg;
1054 	int i, dynptr_id;
1055 
1056 	/* We always ensure that STACK_DYNPTR is never set partially,
1057 	 * hence just checking for slot_type[0] is enough. This is
1058 	 * different for STACK_SPILL, where it may be only set for
1059 	 * 1 byte, so code has to use is_spilled_reg.
1060 	 */
1061 	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 		return 0;
1063 
1064 	/* Reposition spi to first slot */
1065 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 		spi = spi + 1;
1067 
1068 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 		verbose(env, "cannot overwrite referenced dynptr\n");
1070 		return -EINVAL;
1071 	}
1072 
1073 	mark_stack_slot_scratched(env, spi);
1074 	mark_stack_slot_scratched(env, spi - 1);
1075 
1076 	/* Writing partially to one dynptr stack slot destroys both. */
1077 	for (i = 0; i < BPF_REG_SIZE; i++) {
1078 		state->stack[spi].slot_type[i] = STACK_INVALID;
1079 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 	}
1081 
1082 	dynptr_id = state->stack[spi].spilled_ptr.id;
1083 	/* Invalidate any slices associated with this dynptr */
1084 	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 			continue;
1088 		if (dreg->dynptr_id == dynptr_id)
1089 			mark_reg_invalid(env, dreg);
1090 	}));
1091 
1092 	/* Do not release reference state, we are destroying dynptr on stack,
1093 	 * not using some helper to release it. Just reset register.
1094 	 */
1095 	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097 
1098 	/* Same reason as unmark_stack_slots_dynptr above */
1099 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101 
1102 	return 0;
1103 }
1104 
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 	int spi;
1108 
1109 	if (reg->type == CONST_PTR_TO_DYNPTR)
1110 		return false;
1111 
1112 	spi = dynptr_get_spi(env, reg);
1113 
1114 	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 	 * error because this just means the stack state hasn't been updated yet.
1116 	 * We will do check_mem_access to check and update stack bounds later.
1117 	 */
1118 	if (spi < 0 && spi != -ERANGE)
1119 		return false;
1120 
1121 	/* We don't need to check if the stack slots are marked by previous
1122 	 * dynptr initializations because we allow overwriting existing unreferenced
1123 	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 	 * touching are completely destructed before we reinitialize them for a new
1126 	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 	 * instead of delaying it until the end where the user will get "Unreleased
1128 	 * reference" error.
1129 	 */
1130 	return true;
1131 }
1132 
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 	struct bpf_func_state *state = func(env, reg);
1136 	int i, spi;
1137 
1138 	/* This already represents first slot of initialized bpf_dynptr.
1139 	 *
1140 	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 	 * check_func_arg_reg_off's logic, so we don't need to check its
1142 	 * offset and alignment.
1143 	 */
1144 	if (reg->type == CONST_PTR_TO_DYNPTR)
1145 		return true;
1146 
1147 	spi = dynptr_get_spi(env, reg);
1148 	if (spi < 0)
1149 		return false;
1150 	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 		return false;
1152 
1153 	for (i = 0; i < BPF_REG_SIZE; i++) {
1154 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 				    enum bpf_arg_type arg_type)
1164 {
1165 	struct bpf_func_state *state = func(env, reg);
1166 	enum bpf_dynptr_type dynptr_type;
1167 	int spi;
1168 
1169 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 	if (arg_type == ARG_PTR_TO_DYNPTR)
1171 		return true;
1172 
1173 	dynptr_type = arg_to_dynptr_type(arg_type);
1174 	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 		return reg->dynptr.type == dynptr_type;
1176 	} else {
1177 		spi = dynptr_get_spi(env, reg);
1178 		if (spi < 0)
1179 			return false;
1180 		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 	}
1182 }
1183 
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185 
mark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int insn_idx,struct btf * btf,u32 btf_id,int nr_slots)1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 				 struct bpf_reg_state *reg, int insn_idx,
1188 				 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 	struct bpf_func_state *state = func(env, reg);
1191 	int spi, i, j, id;
1192 
1193 	spi = iter_get_spi(env, reg, nr_slots);
1194 	if (spi < 0)
1195 		return spi;
1196 
1197 	id = acquire_reference_state(env, insn_idx);
1198 	if (id < 0)
1199 		return id;
1200 
1201 	for (i = 0; i < nr_slots; i++) {
1202 		struct bpf_stack_state *slot = &state->stack[spi - i];
1203 		struct bpf_reg_state *st = &slot->spilled_ptr;
1204 
1205 		__mark_reg_known_zero(st);
1206 		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 		st->live |= REG_LIVE_WRITTEN;
1208 		st->ref_obj_id = i == 0 ? id : 0;
1209 		st->iter.btf = btf;
1210 		st->iter.btf_id = btf_id;
1211 		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 		st->iter.depth = 0;
1213 
1214 		for (j = 0; j < BPF_REG_SIZE; j++)
1215 			slot->slot_type[j] = STACK_ITER;
1216 
1217 		mark_stack_slot_scratched(env, spi - i);
1218 	}
1219 
1220 	return 0;
1221 }
1222 
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 				   struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 	struct bpf_func_state *state = func(env, reg);
1227 	int spi, i, j;
1228 
1229 	spi = iter_get_spi(env, reg, nr_slots);
1230 	if (spi < 0)
1231 		return spi;
1232 
1233 	for (i = 0; i < nr_slots; i++) {
1234 		struct bpf_stack_state *slot = &state->stack[spi - i];
1235 		struct bpf_reg_state *st = &slot->spilled_ptr;
1236 
1237 		if (i == 0)
1238 			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239 
1240 		__mark_reg_not_init(env, st);
1241 
1242 		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 		st->live |= REG_LIVE_WRITTEN;
1244 
1245 		for (j = 0; j < BPF_REG_SIZE; j++)
1246 			slot->slot_type[j] = STACK_INVALID;
1247 
1248 		mark_stack_slot_scratched(env, spi - i);
1249 	}
1250 
1251 	return 0;
1252 }
1253 
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 				     struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 	struct bpf_func_state *state = func(env, reg);
1258 	int spi, i, j;
1259 
1260 	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 	 * will do check_mem_access to check and update stack bounds later, so
1262 	 * return true for that case.
1263 	 */
1264 	spi = iter_get_spi(env, reg, nr_slots);
1265 	if (spi == -ERANGE)
1266 		return true;
1267 	if (spi < 0)
1268 		return false;
1269 
1270 	for (i = 0; i < nr_slots; i++) {
1271 		struct bpf_stack_state *slot = &state->stack[spi - i];
1272 
1273 		for (j = 0; j < BPF_REG_SIZE; j++)
1274 			if (slot->slot_type[j] == STACK_ITER)
1275 				return false;
1276 	}
1277 
1278 	return true;
1279 }
1280 
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 				   struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 	struct bpf_func_state *state = func(env, reg);
1285 	int spi, i, j;
1286 
1287 	spi = iter_get_spi(env, reg, nr_slots);
1288 	if (spi < 0)
1289 		return false;
1290 
1291 	for (i = 0; i < nr_slots; i++) {
1292 		struct bpf_stack_state *slot = &state->stack[spi - i];
1293 		struct bpf_reg_state *st = &slot->spilled_ptr;
1294 
1295 		/* only main (first) slot has ref_obj_id set */
1296 		if (i == 0 && !st->ref_obj_id)
1297 			return false;
1298 		if (i != 0 && st->ref_obj_id)
1299 			return false;
1300 		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 			return false;
1302 
1303 		for (j = 0; j < BPF_REG_SIZE; j++)
1304 			if (slot->slot_type[j] != STACK_ITER)
1305 				return false;
1306 	}
1307 
1308 	return true;
1309 }
1310 
1311 /* Check if given stack slot is "special":
1312  *   - spilled register state (STACK_SPILL);
1313  *   - dynptr state (STACK_DYNPTR);
1314  *   - iter state (STACK_ITER).
1315  */
is_stack_slot_special(const struct bpf_stack_state * stack)1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319 
1320 	switch (type) {
1321 	case STACK_SPILL:
1322 	case STACK_DYNPTR:
1323 	case STACK_ITER:
1324 		return true;
1325 	case STACK_INVALID:
1326 	case STACK_MISC:
1327 	case STACK_ZERO:
1328 		return false;
1329 	default:
1330 		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 		return true;
1332 	}
1333 }
1334 
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336  * it was spilled to the stack.
1337  */
is_spilled_reg(const struct bpf_stack_state * stack)1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342 
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 	       stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348 
scrub_spilled_slot(u8 * stype)1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 	if (*stype != STACK_INVALID)
1352 		*stype = STACK_MISC;
1353 }
1354 
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state,bool print_all)1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 				 const struct bpf_func_state *state,
1357 				 bool print_all)
1358 {
1359 	const struct bpf_reg_state *reg;
1360 	enum bpf_reg_type t;
1361 	int i;
1362 
1363 	if (state->frameno)
1364 		verbose(env, " frame%d:", state->frameno);
1365 	for (i = 0; i < MAX_BPF_REG; i++) {
1366 		reg = &state->regs[i];
1367 		t = reg->type;
1368 		if (t == NOT_INIT)
1369 			continue;
1370 		if (!print_all && !reg_scratched(env, i))
1371 			continue;
1372 		verbose(env, " R%d", i);
1373 		print_liveness(env, reg->live);
1374 		verbose(env, "=");
1375 		if (t == SCALAR_VALUE && reg->precise)
1376 			verbose(env, "P");
1377 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 		    tnum_is_const(reg->var_off)) {
1379 			/* reg->off should be 0 for SCALAR_VALUE */
1380 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 			verbose(env, "%lld", reg->var_off.value + reg->off);
1382 		} else {
1383 			const char *sep = "";
1384 
1385 			verbose(env, "%s", reg_type_str(env, t));
1386 			if (base_type(t) == PTR_TO_BTF_ID)
1387 				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 			verbose(env, "(");
1389 /*
1390  * _a stands for append, was shortened to avoid multiline statements below.
1391  * This macro is used to output a comma separated list of attributes.
1392  */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394 
1395 			if (reg->id)
1396 				verbose_a("id=%d", reg->id);
1397 			if (reg->ref_obj_id)
1398 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 			if (type_is_non_owning_ref(reg->type))
1400 				verbose_a("%s", "non_own_ref");
1401 			if (t != SCALAR_VALUE)
1402 				verbose_a("off=%d", reg->off);
1403 			if (type_is_pkt_pointer(t))
1404 				verbose_a("r=%d", reg->range);
1405 			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 				 base_type(t) == PTR_TO_MAP_KEY ||
1407 				 base_type(t) == PTR_TO_MAP_VALUE)
1408 				verbose_a("ks=%d,vs=%d",
1409 					  reg->map_ptr->key_size,
1410 					  reg->map_ptr->value_size);
1411 			if (tnum_is_const(reg->var_off)) {
1412 				/* Typically an immediate SCALAR_VALUE, but
1413 				 * could be a pointer whose offset is too big
1414 				 * for reg->off
1415 				 */
1416 				verbose_a("imm=%llx", reg->var_off.value);
1417 			} else {
1418 				if (reg->smin_value != reg->umin_value &&
1419 				    reg->smin_value != S64_MIN)
1420 					verbose_a("smin=%lld", (long long)reg->smin_value);
1421 				if (reg->smax_value != reg->umax_value &&
1422 				    reg->smax_value != S64_MAX)
1423 					verbose_a("smax=%lld", (long long)reg->smax_value);
1424 				if (reg->umin_value != 0)
1425 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 				if (reg->umax_value != U64_MAX)
1427 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 				if (!tnum_is_unknown(reg->var_off)) {
1429 					char tn_buf[48];
1430 
1431 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 					verbose_a("var_off=%s", tn_buf);
1433 				}
1434 				if (reg->s32_min_value != reg->smin_value &&
1435 				    reg->s32_min_value != S32_MIN)
1436 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 				if (reg->s32_max_value != reg->smax_value &&
1438 				    reg->s32_max_value != S32_MAX)
1439 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 				if (reg->u32_min_value != reg->umin_value &&
1441 				    reg->u32_min_value != U32_MIN)
1442 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 				if (reg->u32_max_value != reg->umax_value &&
1444 				    reg->u32_max_value != U32_MAX)
1445 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 			}
1447 #undef verbose_a
1448 
1449 			verbose(env, ")");
1450 		}
1451 	}
1452 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 		char types_buf[BPF_REG_SIZE + 1];
1454 		bool valid = false;
1455 		int j;
1456 
1457 		for (j = 0; j < BPF_REG_SIZE; j++) {
1458 			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 				valid = true;
1460 			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 		}
1462 		types_buf[BPF_REG_SIZE] = 0;
1463 		if (!valid)
1464 			continue;
1465 		if (!print_all && !stack_slot_scratched(env, i))
1466 			continue;
1467 		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 		case STACK_SPILL:
1469 			reg = &state->stack[i].spilled_ptr;
1470 			t = reg->type;
1471 
1472 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 			print_liveness(env, reg->live);
1474 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 			if (t == SCALAR_VALUE && reg->precise)
1476 				verbose(env, "P");
1477 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 				verbose(env, "%lld", reg->var_off.value + reg->off);
1479 			break;
1480 		case STACK_DYNPTR:
1481 			i += BPF_DYNPTR_NR_SLOTS - 1;
1482 			reg = &state->stack[i].spilled_ptr;
1483 
1484 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 			print_liveness(env, reg->live);
1486 			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 			if (reg->ref_obj_id)
1488 				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 			break;
1490 		case STACK_ITER:
1491 			/* only main slot has ref_obj_id set; skip others */
1492 			reg = &state->stack[i].spilled_ptr;
1493 			if (!reg->ref_obj_id)
1494 				continue;
1495 
1496 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 			print_liveness(env, reg->live);
1498 			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 				reg->iter.depth);
1502 			break;
1503 		case STACK_MISC:
1504 		case STACK_ZERO:
1505 		default:
1506 			reg = &state->stack[i].spilled_ptr;
1507 
1508 			for (j = 0; j < BPF_REG_SIZE; j++)
1509 				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 			types_buf[BPF_REG_SIZE] = 0;
1511 
1512 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 			print_liveness(env, reg->live);
1514 			verbose(env, "=%s", types_buf);
1515 			break;
1516 		}
1517 	}
1518 	if (state->acquired_refs && state->refs[0].id) {
1519 		verbose(env, " refs=%d", state->refs[0].id);
1520 		for (i = 1; i < state->acquired_refs; i++)
1521 			if (state->refs[i].id)
1522 				verbose(env, ",%d", state->refs[i].id);
1523 	}
1524 	if (state->in_callback_fn)
1525 		verbose(env, " cb");
1526 	if (state->in_async_callback_fn)
1527 		verbose(env, " async_cb");
1528 	verbose(env, "\n");
1529 	if (!print_all)
1530 		mark_verifier_state_clean(env);
1531 }
1532 
vlog_alignment(u32 pos)1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538 
print_insn_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 			     const struct bpf_func_state *state)
1541 {
1542 	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 		/* remove new line character */
1544 		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 	} else {
1547 		verbose(env, "%d:", env->insn_idx);
1548 	}
1549 	print_verifier_state(env, state, false);
1550 }
1551 
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553  * small to hold src. This is different from krealloc since we don't want to preserve
1554  * the contents of dst.
1555  *
1556  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557  * not be allocated.
1558  */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 	size_t alloc_bytes;
1562 	void *orig = dst;
1563 	size_t bytes;
1564 
1565 	if (ZERO_OR_NULL_PTR(src))
1566 		goto out;
1567 
1568 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 		return NULL;
1570 
1571 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 	dst = krealloc(orig, alloc_bytes, flags);
1573 	if (!dst) {
1574 		kfree(orig);
1575 		return NULL;
1576 	}
1577 
1578 	memcpy(dst, src, bytes);
1579 out:
1580 	return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582 
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584  * small to hold new_n items. new items are zeroed out if the array grows.
1585  *
1586  * Contrary to krealloc_array, does not free arr if new_n is zero.
1587  */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 	size_t alloc_size;
1591 	void *new_arr;
1592 
1593 	if (!new_n || old_n == new_n)
1594 		goto out;
1595 
1596 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 	if (!new_arr) {
1599 		kfree(arr);
1600 		return NULL;
1601 	}
1602 	arr = new_arr;
1603 
1604 	if (new_n > old_n)
1605 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606 
1607 out:
1608 	return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610 
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 	if (!dst->refs)
1616 		return -ENOMEM;
1617 
1618 	dst->acquired_refs = src->acquired_refs;
1619 	return 0;
1620 }
1621 
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625 
1626 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 				GFP_KERNEL);
1628 	if (!dst->stack)
1629 		return -ENOMEM;
1630 
1631 	dst->allocated_stack = src->allocated_stack;
1632 	return 0;
1633 }
1634 
resize_reference_state(struct bpf_func_state * state,size_t n)1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 				    sizeof(struct bpf_reference_state));
1639 	if (!state->refs)
1640 		return -ENOMEM;
1641 
1642 	state->acquired_refs = n;
1643 	return 0;
1644 }
1645 
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647  * possibly update the function's high-water mark in its bpf_subprog_info.
1648  */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652 
1653 	if (old_n >= n)
1654 		return 0;
1655 
1656 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 	if (!state->stack)
1658 		return -ENOMEM;
1659 
1660 	state->allocated_stack = size;
1661 
1662 	/* update known max for given subprogram */
1663 	if (env->subprog_info[state->subprogno].stack_depth < size)
1664 		env->subprog_info[state->subprogno].stack_depth = size;
1665 
1666 	return 0;
1667 }
1668 
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670  * this new pointer reference.
1671  * On success, returns a valid pointer id to associate with the register
1672  * On failure, returns a negative errno.
1673  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 	struct bpf_func_state *state = cur_func(env);
1677 	int new_ofs = state->acquired_refs;
1678 	int id, err;
1679 
1680 	err = resize_reference_state(state, state->acquired_refs + 1);
1681 	if (err)
1682 		return err;
1683 	id = ++env->id_gen;
1684 	state->refs[new_ofs].id = id;
1685 	state->refs[new_ofs].insn_idx = insn_idx;
1686 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687 
1688 	return id;
1689 }
1690 
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 	int i, last_idx;
1695 
1696 	last_idx = state->acquired_refs - 1;
1697 	for (i = 0; i < state->acquired_refs; i++) {
1698 		if (state->refs[i].id == ptr_id) {
1699 			/* Cannot release caller references in callbacks */
1700 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 				return -EINVAL;
1702 			if (last_idx && i != last_idx)
1703 				memcpy(&state->refs[i], &state->refs[last_idx],
1704 				       sizeof(*state->refs));
1705 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 			state->acquired_refs--;
1707 			return 0;
1708 		}
1709 	}
1710 	return -EINVAL;
1711 }
1712 
free_func_state(struct bpf_func_state * state)1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 	if (!state)
1716 		return;
1717 	kfree(state->refs);
1718 	kfree(state->stack);
1719 	kfree(state);
1720 }
1721 
clear_jmp_history(struct bpf_verifier_state * state)1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 	kfree(state->jmp_history);
1725 	state->jmp_history = NULL;
1726 	state->jmp_history_cnt = 0;
1727 }
1728 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 				bool free_self)
1731 {
1732 	int i;
1733 
1734 	for (i = 0; i <= state->curframe; i++) {
1735 		free_func_state(state->frame[i]);
1736 		state->frame[i] = NULL;
1737 	}
1738 	clear_jmp_history(state);
1739 	if (free_self)
1740 		kfree(state);
1741 }
1742 
1743 /* copy verifier state from src to dst growing dst stack space
1744  * when necessary to accommodate larger src stack
1745  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1746 static int copy_func_state(struct bpf_func_state *dst,
1747 			   const struct bpf_func_state *src)
1748 {
1749 	int err;
1750 
1751 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 	err = copy_reference_state(dst, src);
1753 	if (err)
1754 		return err;
1755 	return copy_stack_state(dst, src);
1756 }
1757 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 			       const struct bpf_verifier_state *src)
1760 {
1761 	struct bpf_func_state *dst;
1762 	int i, err;
1763 
1764 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 					    GFP_USER);
1767 	if (!dst_state->jmp_history)
1768 		return -ENOMEM;
1769 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770 
1771 	/* if dst has more stack frames then src frame, free them */
1772 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 		free_func_state(dst_state->frame[i]);
1774 		dst_state->frame[i] = NULL;
1775 	}
1776 	dst_state->speculative = src->speculative;
1777 	dst_state->active_rcu_lock = src->active_rcu_lock;
1778 	dst_state->curframe = src->curframe;
1779 	dst_state->active_lock.ptr = src->active_lock.ptr;
1780 	dst_state->active_lock.id = src->active_lock.id;
1781 	dst_state->branches = src->branches;
1782 	dst_state->parent = src->parent;
1783 	dst_state->first_insn_idx = src->first_insn_idx;
1784 	dst_state->last_insn_idx = src->last_insn_idx;
1785 	dst_state->dfs_depth = src->dfs_depth;
1786 	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 	for (i = 0; i <= src->curframe; i++) {
1789 		dst = dst_state->frame[i];
1790 		if (!dst) {
1791 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 			if (!dst)
1793 				return -ENOMEM;
1794 			dst_state->frame[i] = dst;
1795 		}
1796 		err = copy_func_state(dst, src->frame[i]);
1797 		if (err)
1798 			return err;
1799 	}
1800 	return 0;
1801 }
1802 
state_htab_size(struct bpf_verifier_env * env)1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 	return env->prog->len;
1806 }
1807 
explored_state(struct bpf_verifier_env * env,int idx)1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 	struct bpf_verifier_state *cur = env->cur_state;
1811 	struct bpf_func_state *state = cur->frame[cur->curframe];
1812 
1813 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815 
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 	int fr;
1819 
1820 	if (a->curframe != b->curframe)
1821 		return false;
1822 
1823 	for (fr = a->curframe; fr >= 0; fr--)
1824 		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 			return false;
1826 
1827 	return true;
1828 }
1829 
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831  * check unbounded loops that iterators.
1832  *
1833  * In is_state_visited() it is necessary to know if explored states are
1834  * part of some loops in order to decide whether non-exact states
1835  * comparison could be used:
1836  * - non-exact states comparison establishes sub-state relation and uses
1837  *   read and precision marks to do so, these marks are propagated from
1838  *   children states and thus are not guaranteed to be final in a loop;
1839  * - exact states comparison just checks if current and explored states
1840  *   are identical (and thus form a back-edge).
1841  *
1842  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844  * algorithm for loop structure detection and gives an overview of
1845  * relevant terminology. It also has helpful illustrations.
1846  *
1847  * [1] https://api.semanticscholar.org/CorpusID:15784067
1848  *
1849  * We use a similar algorithm but because loop nested structure is
1850  * irrelevant for verifier ours is significantly simpler and resembles
1851  * strongly connected components algorithm from Sedgewick's textbook.
1852  *
1853  * Define topmost loop entry as a first node of the loop traversed in a
1854  * depth first search starting from initial state. The goal of the loop
1855  * tracking algorithm is to associate topmost loop entries with states
1856  * derived from these entries.
1857  *
1858  * For each step in the DFS states traversal algorithm needs to identify
1859  * the following situations:
1860  *
1861  *          initial                     initial                   initial
1862  *            |                           |                         |
1863  *            V                           V                         V
1864  *           ...                         ...           .---------> hdr
1865  *            |                           |            |            |
1866  *            V                           V            |            V
1867  *           cur                     .-> succ          |    .------...
1868  *            |                      |    |            |    |       |
1869  *            V                      |    V            |    V       V
1870  *           succ                    '-- cur           |   ...     ...
1871  *                                                     |    |       |
1872  *                                                     |    V       V
1873  *                                                     |   succ <- cur
1874  *                                                     |    |
1875  *                                                     |    V
1876  *                                                     |   ...
1877  *                                                     |    |
1878  *                                                     '----'
1879  *
1880  *  (A) successor state of cur   (B) successor state of cur or it's entry
1881  *      not yet traversed            are in current DFS path, thus cur and succ
1882  *                                   are members of the same outermost loop
1883  *
1884  *                      initial                  initial
1885  *                        |                        |
1886  *                        V                        V
1887  *                       ...                      ...
1888  *                        |                        |
1889  *                        V                        V
1890  *                .------...               .------...
1891  *                |       |                |       |
1892  *                V       V                V       V
1893  *           .-> hdr     ...              ...     ...
1894  *           |    |       |                |       |
1895  *           |    V       V                V       V
1896  *           |   succ <- cur              succ <- cur
1897  *           |    |                        |
1898  *           |    V                        V
1899  *           |   ...                      ...
1900  *           |    |                        |
1901  *           '----'                       exit
1902  *
1903  * (C) successor state of cur is a part of some loop but this loop
1904  *     does not include cur or successor state is not in a loop at all.
1905  *
1906  * Algorithm could be described as the following python code:
1907  *
1908  *     traversed = set()   # Set of traversed nodes
1909  *     entries = {}        # Mapping from node to loop entry
1910  *     depths = {}         # Depth level assigned to graph node
1911  *     path = set()        # Current DFS path
1912  *
1913  *     # Find outermost loop entry known for n
1914  *     def get_loop_entry(n):
1915  *         h = entries.get(n, None)
1916  *         while h in entries and entries[h] != h:
1917  *             h = entries[h]
1918  *         return h
1919  *
1920  *     # Update n's loop entry if h's outermost entry comes
1921  *     # before n's outermost entry in current DFS path.
1922  *     def update_loop_entry(n, h):
1923  *         n1 = get_loop_entry(n) or n
1924  *         h1 = get_loop_entry(h) or h
1925  *         if h1 in path and depths[h1] <= depths[n1]:
1926  *             entries[n] = h1
1927  *
1928  *     def dfs(n, depth):
1929  *         traversed.add(n)
1930  *         path.add(n)
1931  *         depths[n] = depth
1932  *         for succ in G.successors(n):
1933  *             if succ not in traversed:
1934  *                 # Case A: explore succ and update cur's loop entry
1935  *                 #         only if succ's entry is in current DFS path.
1936  *                 dfs(succ, depth + 1)
1937  *                 h = get_loop_entry(succ)
1938  *                 update_loop_entry(n, h)
1939  *             else:
1940  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941  *                 update_loop_entry(n, succ)
1942  *         path.remove(n)
1943  *
1944  * To adapt this algorithm for use with verifier:
1945  * - use st->branch == 0 as a signal that DFS of succ had been finished
1946  *   and cur's loop entry has to be updated (case A), handle this in
1947  *   update_branch_counts();
1948  * - use st->branch > 0 as a signal that st is in the current DFS path;
1949  * - handle cases B and C in is_state_visited();
1950  * - update topmost loop entry for intermediate states in get_loop_entry().
1951  */
get_loop_entry(struct bpf_verifier_state * st)1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955 
1956 	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 		topmost = topmost->loop_entry;
1958 	/* Update loop entries for intermediate states to avoid this
1959 	 * traversal in future get_loop_entry() calls.
1960 	 */
1961 	while (st && st->loop_entry != topmost) {
1962 		old = st->loop_entry;
1963 		st->loop_entry = topmost;
1964 		st = old;
1965 	}
1966 	return topmost;
1967 }
1968 
update_loop_entry(struct bpf_verifier_state * cur,struct bpf_verifier_state * hdr)1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 	struct bpf_verifier_state *cur1, *hdr1;
1972 
1973 	cur1 = get_loop_entry(cur) ?: cur;
1974 	hdr1 = get_loop_entry(hdr) ?: hdr;
1975 	/* The head1->branches check decides between cases B and C in
1976 	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 	 * head's topmost loop entry is not in current DFS path,
1978 	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 	 * no need to update cur->loop_entry.
1980 	 */
1981 	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 		cur->loop_entry = hdr;
1983 		hdr->used_as_loop_entry = true;
1984 	}
1985 }
1986 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 	while (st) {
1990 		u32 br = --st->branches;
1991 
1992 		/* br == 0 signals that DFS exploration for 'st' is finished,
1993 		 * thus it is necessary to update parent's loop entry if it
1994 		 * turned out that st is a part of some loop.
1995 		 * This is a part of 'case A' in get_loop_entry() comment.
1996 		 */
1997 		if (br == 0 && st->parent && st->loop_entry)
1998 			update_loop_entry(st->parent, st->loop_entry);
1999 
2000 		/* WARN_ON(br > 1) technically makes sense here,
2001 		 * but see comment in push_stack(), hence:
2002 		 */
2003 		WARN_ONCE((int)br < 0,
2004 			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005 			  br);
2006 		if (br)
2007 			break;
2008 		st = st->parent;
2009 	}
2010 }
2011 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 		     int *insn_idx, bool pop_log)
2014 {
2015 	struct bpf_verifier_state *cur = env->cur_state;
2016 	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 	int err;
2018 
2019 	if (env->head == NULL)
2020 		return -ENOENT;
2021 
2022 	if (cur) {
2023 		err = copy_verifier_state(cur, &head->st);
2024 		if (err)
2025 			return err;
2026 	}
2027 	if (pop_log)
2028 		bpf_vlog_reset(&env->log, head->log_pos);
2029 	if (insn_idx)
2030 		*insn_idx = head->insn_idx;
2031 	if (prev_insn_idx)
2032 		*prev_insn_idx = head->prev_insn_idx;
2033 	elem = head->next;
2034 	free_verifier_state(&head->st, false);
2035 	kfree(head);
2036 	env->head = elem;
2037 	env->stack_size--;
2038 	return 0;
2039 }
2040 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 					     int insn_idx, int prev_insn_idx,
2043 					     bool speculative)
2044 {
2045 	struct bpf_verifier_state *cur = env->cur_state;
2046 	struct bpf_verifier_stack_elem *elem;
2047 	int err;
2048 
2049 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 	if (!elem)
2051 		goto err;
2052 
2053 	elem->insn_idx = insn_idx;
2054 	elem->prev_insn_idx = prev_insn_idx;
2055 	elem->next = env->head;
2056 	elem->log_pos = env->log.end_pos;
2057 	env->head = elem;
2058 	env->stack_size++;
2059 	err = copy_verifier_state(&elem->st, cur);
2060 	if (err)
2061 		goto err;
2062 	elem->st.speculative |= speculative;
2063 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 		verbose(env, "The sequence of %d jumps is too complex.\n",
2065 			env->stack_size);
2066 		goto err;
2067 	}
2068 	if (elem->st.parent) {
2069 		++elem->st.parent->branches;
2070 		/* WARN_ON(branches > 2) technically makes sense here,
2071 		 * but
2072 		 * 1. speculative states will bump 'branches' for non-branch
2073 		 * instructions
2074 		 * 2. is_state_visited() heuristics may decide not to create
2075 		 * a new state for a sequence of branches and all such current
2076 		 * and cloned states will be pointing to a single parent state
2077 		 * which might have large 'branches' count.
2078 		 */
2079 	}
2080 	return &elem->st;
2081 err:
2082 	free_verifier_state(env->cur_state, true);
2083 	env->cur_state = NULL;
2084 	/* pop all elements and return */
2085 	while (!pop_stack(env, NULL, NULL, false));
2086 	return NULL;
2087 }
2088 
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093 
2094 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 	reg->var_off = tnum_const(imm);
2098 	reg->smin_value = (s64)imm;
2099 	reg->smax_value = (s64)imm;
2100 	reg->umin_value = imm;
2101 	reg->umax_value = imm;
2102 
2103 	reg->s32_min_value = (s32)imm;
2104 	reg->s32_max_value = (s32)imm;
2105 	reg->u32_min_value = (u32)imm;
2106 	reg->u32_max_value = (u32)imm;
2107 }
2108 
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110  * known to have the value @imm.
2111  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 	/* Clear off and union(map_ptr, range) */
2115 	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 	reg->id = 0;
2118 	reg->ref_obj_id = 0;
2119 	___mark_reg_known(reg, imm);
2120 }
2121 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 	reg->s32_min_value = (s32)imm;
2126 	reg->s32_max_value = (s32)imm;
2127 	reg->u32_min_value = (u32)imm;
2128 	reg->u32_max_value = (u32)imm;
2129 }
2130 
2131 /* Mark the 'variable offset' part of a register as zero.  This should be
2132  * used only on registers holding a pointer type.
2133  */
__mark_reg_known_zero(struct bpf_reg_state * reg)2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 	__mark_reg_known(reg, 0);
2137 }
2138 
__mark_reg_const_zero(struct bpf_reg_state * reg)2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 	__mark_reg_known(reg, 0);
2142 	reg->type = SCALAR_VALUE;
2143 }
2144 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 				struct bpf_reg_state *regs, u32 regno)
2147 {
2148 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 		/* Something bad happened, let's kill all regs */
2151 		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 			__mark_reg_not_init(env, regs + regno);
2153 		return;
2154 	}
2155 	__mark_reg_known_zero(regs + regno);
2156 }
2157 
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 			      bool first_slot, int dynptr_id)
2160 {
2161 	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 	 */
2165 	__mark_reg_known_zero(reg);
2166 	reg->type = CONST_PTR_TO_DYNPTR;
2167 	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168 	reg->id = dynptr_id;
2169 	reg->dynptr.type = type;
2170 	reg->dynptr.first_slot = first_slot;
2171 }
2172 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 		const struct bpf_map *map = reg->map_ptr;
2177 
2178 		if (map->inner_map_meta) {
2179 			reg->type = CONST_PTR_TO_MAP;
2180 			reg->map_ptr = map->inner_map_meta;
2181 			/* transfer reg's id which is unique for every map_lookup_elem
2182 			 * as UID of the inner map.
2183 			 */
2184 			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 				reg->map_uid = reg->id;
2186 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 			reg->type = PTR_TO_XDP_SOCK;
2188 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 			reg->type = PTR_TO_SOCKET;
2191 		} else {
2192 			reg->type = PTR_TO_MAP_VALUE;
2193 		}
2194 		return;
2195 	}
2196 
2197 	reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199 
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 				struct btf_field_graph_root *ds_head)
2202 {
2203 	__mark_reg_known_zero(&regs[regno]);
2204 	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 	regs[regno].btf = ds_head->btf;
2206 	regs[regno].btf_id = ds_head->value_btf_id;
2207 	regs[regno].off = ds_head->node_offset;
2208 }
2209 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 	return type_is_pkt_pointer(reg->type);
2213 }
2214 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 	return reg_is_pkt_pointer(reg) ||
2218 	       reg->type == PTR_TO_PACKET_END;
2219 }
2220 
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 	return base_type(reg->type) == PTR_TO_MEM &&
2224 		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226 
2227 /* 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)2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 				    enum bpf_reg_type which)
2230 {
2231 	/* The register can already have a range from prior markings.
2232 	 * This is fine as long as it hasn't been advanced from its
2233 	 * origin.
2234 	 */
2235 	return reg->type == which &&
2236 	       reg->id == 0 &&
2237 	       reg->off == 0 &&
2238 	       tnum_equals_const(reg->var_off, 0);
2239 }
2240 
2241 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 	reg->smin_value = S64_MIN;
2245 	reg->smax_value = S64_MAX;
2246 	reg->umin_value = 0;
2247 	reg->umax_value = U64_MAX;
2248 
2249 	reg->s32_min_value = S32_MIN;
2250 	reg->s32_max_value = S32_MAX;
2251 	reg->u32_min_value = 0;
2252 	reg->u32_max_value = U32_MAX;
2253 }
2254 
__mark_reg64_unbounded(struct bpf_reg_state * reg)2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 	reg->smin_value = S64_MIN;
2258 	reg->smax_value = S64_MAX;
2259 	reg->umin_value = 0;
2260 	reg->umax_value = U64_MAX;
2261 }
2262 
__mark_reg32_unbounded(struct bpf_reg_state * reg)2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 	reg->s32_min_value = S32_MIN;
2266 	reg->s32_max_value = S32_MAX;
2267 	reg->u32_min_value = 0;
2268 	reg->u32_max_value = U32_MAX;
2269 }
2270 
__update_reg32_bounds(struct bpf_reg_state * reg)2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 	struct tnum var32_off = tnum_subreg(reg->var_off);
2274 
2275 	/* min signed is max(sign bit) | min(other bits) */
2276 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 			var32_off.value | (var32_off.mask & S32_MIN));
2278 	/* max signed is min(sign bit) | max(other bits) */
2279 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 			var32_off.value | (var32_off.mask & S32_MAX));
2281 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 	reg->u32_max_value = min(reg->u32_max_value,
2283 				 (u32)(var32_off.value | var32_off.mask));
2284 }
2285 
__update_reg64_bounds(struct bpf_reg_state * reg)2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 	/* min signed is max(sign bit) | min(other bits) */
2289 	reg->smin_value = max_t(s64, reg->smin_value,
2290 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 	/* max signed is min(sign bit) | max(other bits) */
2292 	reg->smax_value = min_t(s64, reg->smax_value,
2293 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 	reg->umax_value = min(reg->umax_value,
2296 			      reg->var_off.value | reg->var_off.mask);
2297 }
2298 
__update_reg_bounds(struct bpf_reg_state * reg)2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 	__update_reg32_bounds(reg);
2302 	__update_reg64_bounds(reg);
2303 }
2304 
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 	/* Learn sign from signed bounds.
2309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 	 * are the same, so combine.  This works even in the negative case, e.g.
2311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 	 */
2313 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 		reg->s32_min_value = reg->u32_min_value =
2315 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 		reg->s32_max_value = reg->u32_max_value =
2317 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 		return;
2319 	}
2320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321 	 * boundary, so we must be careful.
2322 	 */
2323 	if ((s32)reg->u32_max_value >= 0) {
2324 		/* Positive.  We can't learn anything from the smin, but smax
2325 		 * is positive, hence safe.
2326 		 */
2327 		reg->s32_min_value = reg->u32_min_value;
2328 		reg->s32_max_value = reg->u32_max_value =
2329 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 	} else if ((s32)reg->u32_min_value < 0) {
2331 		/* Negative.  We can't learn anything from the smax, but smin
2332 		 * is negative, hence safe.
2333 		 */
2334 		reg->s32_min_value = reg->u32_min_value =
2335 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 		reg->s32_max_value = reg->u32_max_value;
2337 	}
2338 }
2339 
__reg64_deduce_bounds(struct bpf_reg_state * reg)2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 	/* Learn sign from signed bounds.
2343 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 	 * are the same, so combine.  This works even in the negative case, e.g.
2345 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 	 */
2347 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 							  reg->umin_value);
2350 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 							  reg->umax_value);
2352 		return;
2353 	}
2354 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355 	 * boundary, so we must be careful.
2356 	 */
2357 	if ((s64)reg->umax_value >= 0) {
2358 		/* Positive.  We can't learn anything from the smin, but smax
2359 		 * is positive, hence safe.
2360 		 */
2361 		reg->smin_value = reg->umin_value;
2362 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 							  reg->umax_value);
2364 	} else if ((s64)reg->umin_value < 0) {
2365 		/* Negative.  We can't learn anything from the smax, but smin
2366 		 * is negative, hence safe.
2367 		 */
2368 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 							  reg->umin_value);
2370 		reg->smax_value = reg->umax_value;
2371 	}
2372 }
2373 
__reg_deduce_bounds(struct bpf_reg_state * reg)2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 	__reg32_deduce_bounds(reg);
2377 	__reg64_deduce_bounds(reg);
2378 }
2379 
2380 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 	struct tnum var64_off = tnum_intersect(reg->var_off,
2384 					       tnum_range(reg->umin_value,
2385 							  reg->umax_value));
2386 	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 					       tnum_range(reg->u32_min_value,
2388 							  reg->u32_max_value));
2389 
2390 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392 
reg_bounds_sync(struct bpf_reg_state * reg)2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 	/* We might have learned new bounds from the var_off. */
2396 	__update_reg_bounds(reg);
2397 	/* We might have learned something about the sign bit. */
2398 	__reg_deduce_bounds(reg);
2399 	/* We might have learned some bits from the bounds. */
2400 	__reg_bound_offset(reg);
2401 	/* Intersecting with the old var_off might have improved our bounds
2402 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 	 */
2405 	__update_reg_bounds(reg);
2406 }
2407 
__reg32_bound_s64(s32 a)2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 	return a >= 0 && a <= S32_MAX;
2411 }
2412 
__reg_assign_32_into_64(struct bpf_reg_state * reg)2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 	reg->umin_value = reg->u32_min_value;
2416 	reg->umax_value = reg->u32_max_value;
2417 
2418 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 	 * be positive otherwise set to worse case bounds and refine later
2420 	 * from tnum.
2421 	 */
2422 	if (__reg32_bound_s64(reg->s32_min_value) &&
2423 	    __reg32_bound_s64(reg->s32_max_value)) {
2424 		reg->smin_value = reg->s32_min_value;
2425 		reg->smax_value = reg->s32_max_value;
2426 	} else {
2427 		reg->smin_value = 0;
2428 		reg->smax_value = U32_MAX;
2429 	}
2430 }
2431 
__reg_combine_32_into_64(struct bpf_reg_state * reg)2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 	/* special case when 64-bit register has upper 32-bit register
2435 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 	 * allowing us to use 32-bit bounds directly,
2437 	 */
2438 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 		__reg_assign_32_into_64(reg);
2440 	} else {
2441 		/* Otherwise the best we can do is push lower 32bit known and
2442 		 * unknown bits into register (var_off set from jmp logic)
2443 		 * then learn as much as possible from the 64-bit tnum
2444 		 * known and unknown bits. The previous smin/smax bounds are
2445 		 * invalid here because of jmp32 compare so mark them unknown
2446 		 * so they do not impact tnum bounds calculation.
2447 		 */
2448 		__mark_reg64_unbounded(reg);
2449 	}
2450 	reg_bounds_sync(reg);
2451 }
2452 
__reg64_bound_s32(s64 a)2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 	return a >= S32_MIN && a <= S32_MAX;
2456 }
2457 
__reg64_bound_u32(u64 a)2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 	return a >= U32_MIN && a <= U32_MAX;
2461 }
2462 
__reg_combine_64_into_32(struct bpf_reg_state * reg)2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 	__mark_reg32_unbounded(reg);
2466 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 		reg->s32_min_value = (s32)reg->smin_value;
2468 		reg->s32_max_value = (s32)reg->smax_value;
2469 	}
2470 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 		reg->u32_min_value = (u32)reg->umin_value;
2472 		reg->u32_max_value = (u32)reg->umax_value;
2473 	}
2474 	reg_bounds_sync(reg);
2475 }
2476 
2477 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 			       struct bpf_reg_state *reg)
2480 {
2481 	/*
2482 	 * Clear type, off, and union(map_ptr, range) and
2483 	 * padding between 'type' and union
2484 	 */
2485 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 	reg->type = SCALAR_VALUE;
2487 	reg->id = 0;
2488 	reg->ref_obj_id = 0;
2489 	reg->var_off = tnum_unknown;
2490 	reg->frameno = 0;
2491 	reg->precise = !env->bpf_capable;
2492 	__mark_reg_unbounded(reg);
2493 }
2494 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 			     struct bpf_reg_state *regs, u32 regno)
2497 {
2498 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 		/* Something bad happened, let's kill all regs except FP */
2501 		for (regno = 0; regno < BPF_REG_FP; regno++)
2502 			__mark_reg_not_init(env, regs + regno);
2503 		return;
2504 	}
2505 	__mark_reg_unknown(env, regs + regno);
2506 }
2507 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 				struct bpf_reg_state *reg)
2510 {
2511 	__mark_reg_unknown(env, reg);
2512 	reg->type = NOT_INIT;
2513 }
2514 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 			      struct bpf_reg_state *regs, u32 regno)
2517 {
2518 	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 		/* Something bad happened, let's kill all regs except FP */
2521 		for (regno = 0; regno < BPF_REG_FP; regno++)
2522 			__mark_reg_not_init(env, regs + regno);
2523 		return;
2524 	}
2525 	__mark_reg_not_init(env, regs + regno);
2526 }
2527 
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)2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 			    struct bpf_reg_state *regs, u32 regno,
2530 			    enum bpf_reg_type reg_type,
2531 			    struct btf *btf, u32 btf_id,
2532 			    enum bpf_type_flag flag)
2533 {
2534 	if (reg_type == SCALAR_VALUE) {
2535 		mark_reg_unknown(env, regs, regno);
2536 		return;
2537 	}
2538 	mark_reg_known_zero(env, regs, regno);
2539 	regs[regno].type = PTR_TO_BTF_ID | flag;
2540 	regs[regno].btf = btf;
2541 	regs[regno].btf_id = btf_id;
2542 	if (type_may_be_null(flag))
2543 		regs[regno].id = ++env->id_gen;
2544 }
2545 
2546 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2547 static void init_reg_state(struct bpf_verifier_env *env,
2548 			   struct bpf_func_state *state)
2549 {
2550 	struct bpf_reg_state *regs = state->regs;
2551 	int i;
2552 
2553 	for (i = 0; i < MAX_BPF_REG; i++) {
2554 		mark_reg_not_init(env, regs, i);
2555 		regs[i].live = REG_LIVE_NONE;
2556 		regs[i].parent = NULL;
2557 		regs[i].subreg_def = DEF_NOT_SUBREG;
2558 	}
2559 
2560 	/* frame pointer */
2561 	regs[BPF_REG_FP].type = PTR_TO_STACK;
2562 	mark_reg_known_zero(env, regs, BPF_REG_FP);
2563 	regs[BPF_REG_FP].frameno = state->frameno;
2564 }
2565 
2566 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2567 static void init_func_state(struct bpf_verifier_env *env,
2568 			    struct bpf_func_state *state,
2569 			    int callsite, int frameno, int subprogno)
2570 {
2571 	state->callsite = callsite;
2572 	state->frameno = frameno;
2573 	state->subprogno = subprogno;
2574 	state->callback_ret_range = tnum_range(0, 0);
2575 	init_reg_state(env, state);
2576 	mark_verifier_state_scratched(env);
2577 }
2578 
2579 /* 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)2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2581 						int insn_idx, int prev_insn_idx,
2582 						int subprog)
2583 {
2584 	struct bpf_verifier_stack_elem *elem;
2585 	struct bpf_func_state *frame;
2586 
2587 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2588 	if (!elem)
2589 		goto err;
2590 
2591 	elem->insn_idx = insn_idx;
2592 	elem->prev_insn_idx = prev_insn_idx;
2593 	elem->next = env->head;
2594 	elem->log_pos = env->log.end_pos;
2595 	env->head = elem;
2596 	env->stack_size++;
2597 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2598 		verbose(env,
2599 			"The sequence of %d jumps is too complex for async cb.\n",
2600 			env->stack_size);
2601 		goto err;
2602 	}
2603 	/* Unlike push_stack() do not copy_verifier_state().
2604 	 * The caller state doesn't matter.
2605 	 * This is async callback. It starts in a fresh stack.
2606 	 * Initialize it similar to do_check_common().
2607 	 */
2608 	elem->st.branches = 1;
2609 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2610 	if (!frame)
2611 		goto err;
2612 	init_func_state(env, frame,
2613 			BPF_MAIN_FUNC /* callsite */,
2614 			0 /* frameno within this callchain */,
2615 			subprog /* subprog number within this prog */);
2616 	elem->st.frame[0] = frame;
2617 	return &elem->st;
2618 err:
2619 	free_verifier_state(env->cur_state, true);
2620 	env->cur_state = NULL;
2621 	/* pop all elements and return */
2622 	while (!pop_stack(env, NULL, NULL, false));
2623 	return NULL;
2624 }
2625 
2626 
2627 enum reg_arg_type {
2628 	SRC_OP,		/* register is used as source operand */
2629 	DST_OP,		/* register is used as destination operand */
2630 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2631 };
2632 
cmp_subprogs(const void * a,const void * b)2633 static int cmp_subprogs(const void *a, const void *b)
2634 {
2635 	return ((struct bpf_subprog_info *)a)->start -
2636 	       ((struct bpf_subprog_info *)b)->start;
2637 }
2638 
2639 /* Find subprogram that contains instruction at 'off' */
find_containing_subprog(struct bpf_verifier_env * env,int off)2640 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off)
2641 {
2642 	struct bpf_subprog_info *vals = env->subprog_info;
2643 	int l, r, m;
2644 
2645 	if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2646 		return NULL;
2647 
2648 	l = 0;
2649 	r = env->subprog_cnt - 1;
2650 	while (l < r) {
2651 		m = l + (r - l + 1) / 2;
2652 		if (vals[m].start <= off)
2653 			l = m;
2654 		else
2655 			r = m - 1;
2656 	}
2657 	return &vals[l];
2658 }
2659 
2660 /* Find subprogram that starts exactly at 'off' */
find_subprog(struct bpf_verifier_env * env,int off)2661 static int find_subprog(struct bpf_verifier_env *env, int off)
2662 {
2663 	struct bpf_subprog_info *p;
2664 
2665 	p = find_containing_subprog(env, off);
2666 	if (!p || p->start != off)
2667 		return -ENOENT;
2668 	return p - env->subprog_info;
2669 }
2670 
add_subprog(struct bpf_verifier_env * env,int off)2671 static int add_subprog(struct bpf_verifier_env *env, int off)
2672 {
2673 	int insn_cnt = env->prog->len;
2674 	int ret;
2675 
2676 	if (off >= insn_cnt || off < 0) {
2677 		verbose(env, "call to invalid destination\n");
2678 		return -EINVAL;
2679 	}
2680 	ret = find_subprog(env, off);
2681 	if (ret >= 0)
2682 		return ret;
2683 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2684 		verbose(env, "too many subprograms\n");
2685 		return -E2BIG;
2686 	}
2687 	/* determine subprog starts. The end is one before the next starts */
2688 	env->subprog_info[env->subprog_cnt++].start = off;
2689 	sort(env->subprog_info, env->subprog_cnt,
2690 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2691 	return env->subprog_cnt - 1;
2692 }
2693 
2694 #define MAX_KFUNC_DESCS 256
2695 #define MAX_KFUNC_BTFS	256
2696 
2697 struct bpf_kfunc_desc {
2698 	struct btf_func_model func_model;
2699 	u32 func_id;
2700 	s32 imm;
2701 	u16 offset;
2702 	unsigned long addr;
2703 };
2704 
2705 struct bpf_kfunc_btf {
2706 	struct btf *btf;
2707 	struct module *module;
2708 	u16 offset;
2709 };
2710 
2711 struct bpf_kfunc_desc_tab {
2712 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2713 	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2714 	 * available, therefore at the end of verification do_misc_fixups()
2715 	 * sorts this by imm and offset.
2716 	 */
2717 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2718 	u32 nr_descs;
2719 };
2720 
2721 struct bpf_kfunc_btf_tab {
2722 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2723 	u32 nr_descs;
2724 };
2725 
kfunc_desc_cmp_by_id_off(const void * a,const void * b)2726 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2727 {
2728 	const struct bpf_kfunc_desc *d0 = a;
2729 	const struct bpf_kfunc_desc *d1 = b;
2730 
2731 	/* func_id is not greater than BTF_MAX_TYPE */
2732 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2733 }
2734 
kfunc_btf_cmp_by_off(const void * a,const void * b)2735 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2736 {
2737 	const struct bpf_kfunc_btf *d0 = a;
2738 	const struct bpf_kfunc_btf *d1 = b;
2739 
2740 	return d0->offset - d1->offset;
2741 }
2742 
2743 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)2744 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2745 {
2746 	struct bpf_kfunc_desc desc = {
2747 		.func_id = func_id,
2748 		.offset = offset,
2749 	};
2750 	struct bpf_kfunc_desc_tab *tab;
2751 
2752 	tab = prog->aux->kfunc_tab;
2753 	return bsearch(&desc, tab->descs, tab->nr_descs,
2754 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2755 }
2756 
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)2757 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2758 		       u16 btf_fd_idx, u8 **func_addr)
2759 {
2760 	const struct bpf_kfunc_desc *desc;
2761 
2762 	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2763 	if (!desc)
2764 		return -EFAULT;
2765 
2766 	*func_addr = (u8 *)desc->addr;
2767 	return 0;
2768 }
2769 
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2770 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2771 					 s16 offset)
2772 {
2773 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2774 	struct bpf_kfunc_btf_tab *tab;
2775 	struct bpf_kfunc_btf *b;
2776 	struct module *mod;
2777 	struct btf *btf;
2778 	int btf_fd;
2779 
2780 	tab = env->prog->aux->kfunc_btf_tab;
2781 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2782 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2783 	if (!b) {
2784 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2785 			verbose(env, "too many different module BTFs\n");
2786 			return ERR_PTR(-E2BIG);
2787 		}
2788 
2789 		if (bpfptr_is_null(env->fd_array)) {
2790 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2791 			return ERR_PTR(-EPROTO);
2792 		}
2793 
2794 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2795 					    offset * sizeof(btf_fd),
2796 					    sizeof(btf_fd)))
2797 			return ERR_PTR(-EFAULT);
2798 
2799 		btf = btf_get_by_fd(btf_fd);
2800 		if (IS_ERR(btf)) {
2801 			verbose(env, "invalid module BTF fd specified\n");
2802 			return btf;
2803 		}
2804 
2805 		if (!btf_is_module(btf)) {
2806 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2807 			btf_put(btf);
2808 			return ERR_PTR(-EINVAL);
2809 		}
2810 
2811 		mod = btf_try_get_module(btf);
2812 		if (!mod) {
2813 			btf_put(btf);
2814 			return ERR_PTR(-ENXIO);
2815 		}
2816 
2817 		b = &tab->descs[tab->nr_descs++];
2818 		b->btf = btf;
2819 		b->module = mod;
2820 		b->offset = offset;
2821 
2822 		/* sort() reorders entries by value, so b may no longer point
2823 		 * to the right entry after this
2824 		 */
2825 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2826 		     kfunc_btf_cmp_by_off, NULL);
2827 	} else {
2828 		btf = b->btf;
2829 	}
2830 
2831 	return btf;
2832 }
2833 
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)2834 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2835 {
2836 	if (!tab)
2837 		return;
2838 
2839 	while (tab->nr_descs--) {
2840 		module_put(tab->descs[tab->nr_descs].module);
2841 		btf_put(tab->descs[tab->nr_descs].btf);
2842 	}
2843 	kfree(tab);
2844 }
2845 
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2846 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2847 {
2848 	if (offset) {
2849 		if (offset < 0) {
2850 			/* In the future, this can be allowed to increase limit
2851 			 * of fd index into fd_array, interpreted as u16.
2852 			 */
2853 			verbose(env, "negative offset disallowed for kernel module function call\n");
2854 			return ERR_PTR(-EINVAL);
2855 		}
2856 
2857 		return __find_kfunc_desc_btf(env, offset);
2858 	}
2859 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2860 }
2861 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)2862 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2863 {
2864 	const struct btf_type *func, *func_proto;
2865 	struct bpf_kfunc_btf_tab *btf_tab;
2866 	struct bpf_kfunc_desc_tab *tab;
2867 	struct bpf_prog_aux *prog_aux;
2868 	struct bpf_kfunc_desc *desc;
2869 	const char *func_name;
2870 	struct btf *desc_btf;
2871 	unsigned long call_imm;
2872 	unsigned long addr;
2873 	int err;
2874 
2875 	prog_aux = env->prog->aux;
2876 	tab = prog_aux->kfunc_tab;
2877 	btf_tab = prog_aux->kfunc_btf_tab;
2878 	if (!tab) {
2879 		if (!btf_vmlinux) {
2880 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2881 			return -ENOTSUPP;
2882 		}
2883 
2884 		if (!env->prog->jit_requested) {
2885 			verbose(env, "JIT is required for calling kernel function\n");
2886 			return -ENOTSUPP;
2887 		}
2888 
2889 		if (!bpf_jit_supports_kfunc_call()) {
2890 			verbose(env, "JIT does not support calling kernel function\n");
2891 			return -ENOTSUPP;
2892 		}
2893 
2894 		if (!env->prog->gpl_compatible) {
2895 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2896 			return -EINVAL;
2897 		}
2898 
2899 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2900 		if (!tab)
2901 			return -ENOMEM;
2902 		prog_aux->kfunc_tab = tab;
2903 	}
2904 
2905 	/* func_id == 0 is always invalid, but instead of returning an error, be
2906 	 * conservative and wait until the code elimination pass before returning
2907 	 * error, so that invalid calls that get pruned out can be in BPF programs
2908 	 * loaded from userspace.  It is also required that offset be untouched
2909 	 * for such calls.
2910 	 */
2911 	if (!func_id && !offset)
2912 		return 0;
2913 
2914 	if (!btf_tab && offset) {
2915 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2916 		if (!btf_tab)
2917 			return -ENOMEM;
2918 		prog_aux->kfunc_btf_tab = btf_tab;
2919 	}
2920 
2921 	desc_btf = find_kfunc_desc_btf(env, offset);
2922 	if (IS_ERR(desc_btf)) {
2923 		verbose(env, "failed to find BTF for kernel function\n");
2924 		return PTR_ERR(desc_btf);
2925 	}
2926 
2927 	if (find_kfunc_desc(env->prog, func_id, offset))
2928 		return 0;
2929 
2930 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2931 		verbose(env, "too many different kernel function calls\n");
2932 		return -E2BIG;
2933 	}
2934 
2935 	func = btf_type_by_id(desc_btf, func_id);
2936 	if (!func || !btf_type_is_func(func)) {
2937 		verbose(env, "kernel btf_id %u is not a function\n",
2938 			func_id);
2939 		return -EINVAL;
2940 	}
2941 	func_proto = btf_type_by_id(desc_btf, func->type);
2942 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2943 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2944 			func_id);
2945 		return -EINVAL;
2946 	}
2947 
2948 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2949 	addr = kallsyms_lookup_name(func_name);
2950 	if (!addr) {
2951 		verbose(env, "cannot find address for kernel function %s\n",
2952 			func_name);
2953 		return -EINVAL;
2954 	}
2955 	specialize_kfunc(env, func_id, offset, &addr);
2956 
2957 	if (bpf_jit_supports_far_kfunc_call()) {
2958 		call_imm = func_id;
2959 	} else {
2960 		call_imm = BPF_CALL_IMM(addr);
2961 		/* Check whether the relative offset overflows desc->imm */
2962 		if ((unsigned long)(s32)call_imm != call_imm) {
2963 			verbose(env, "address of kernel function %s is out of range\n",
2964 				func_name);
2965 			return -EINVAL;
2966 		}
2967 	}
2968 
2969 	if (bpf_dev_bound_kfunc_id(func_id)) {
2970 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2971 		if (err)
2972 			return err;
2973 	}
2974 
2975 	desc = &tab->descs[tab->nr_descs++];
2976 	desc->func_id = func_id;
2977 	desc->imm = call_imm;
2978 	desc->offset = offset;
2979 	desc->addr = addr;
2980 	err = btf_distill_func_proto(&env->log, desc_btf,
2981 				     func_proto, func_name,
2982 				     &desc->func_model);
2983 	if (!err)
2984 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2985 		     kfunc_desc_cmp_by_id_off, NULL);
2986 	return err;
2987 }
2988 
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)2989 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2990 {
2991 	const struct bpf_kfunc_desc *d0 = a;
2992 	const struct bpf_kfunc_desc *d1 = b;
2993 
2994 	if (d0->imm != d1->imm)
2995 		return d0->imm < d1->imm ? -1 : 1;
2996 	if (d0->offset != d1->offset)
2997 		return d0->offset < d1->offset ? -1 : 1;
2998 	return 0;
2999 }
3000 
sort_kfunc_descs_by_imm_off(struct bpf_prog * prog)3001 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3002 {
3003 	struct bpf_kfunc_desc_tab *tab;
3004 
3005 	tab = prog->aux->kfunc_tab;
3006 	if (!tab)
3007 		return;
3008 
3009 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3010 	     kfunc_desc_cmp_by_imm_off, NULL);
3011 }
3012 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)3013 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3014 {
3015 	return !!prog->aux->kfunc_tab;
3016 }
3017 
3018 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)3019 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3020 			 const struct bpf_insn *insn)
3021 {
3022 	const struct bpf_kfunc_desc desc = {
3023 		.imm = insn->imm,
3024 		.offset = insn->off,
3025 	};
3026 	const struct bpf_kfunc_desc *res;
3027 	struct bpf_kfunc_desc_tab *tab;
3028 
3029 	tab = prog->aux->kfunc_tab;
3030 	res = bsearch(&desc, tab->descs, tab->nr_descs,
3031 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3032 
3033 	return res ? &res->func_model : NULL;
3034 }
3035 
add_subprog_and_kfunc(struct bpf_verifier_env * env)3036 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3037 {
3038 	struct bpf_subprog_info *subprog = env->subprog_info;
3039 	struct bpf_insn *insn = env->prog->insnsi;
3040 	int i, ret, insn_cnt = env->prog->len;
3041 
3042 	/* Add entry function. */
3043 	ret = add_subprog(env, 0);
3044 	if (ret)
3045 		return ret;
3046 
3047 	for (i = 0; i < insn_cnt; i++, insn++) {
3048 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3049 		    !bpf_pseudo_kfunc_call(insn))
3050 			continue;
3051 
3052 		if (!env->bpf_capable) {
3053 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3054 			return -EPERM;
3055 		}
3056 
3057 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3058 			ret = add_subprog(env, i + insn->imm + 1);
3059 		else
3060 			ret = add_kfunc_call(env, insn->imm, insn->off);
3061 
3062 		if (ret < 0)
3063 			return ret;
3064 	}
3065 
3066 	/* Add a fake 'exit' subprog which could simplify subprog iteration
3067 	 * logic. 'subprog_cnt' should not be increased.
3068 	 */
3069 	subprog[env->subprog_cnt].start = insn_cnt;
3070 
3071 	if (env->log.level & BPF_LOG_LEVEL2)
3072 		for (i = 0; i < env->subprog_cnt; i++)
3073 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3074 
3075 	return 0;
3076 }
3077 
check_subprogs(struct bpf_verifier_env * env)3078 static int check_subprogs(struct bpf_verifier_env *env)
3079 {
3080 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3081 	struct bpf_subprog_info *subprog = env->subprog_info;
3082 	struct bpf_insn *insn = env->prog->insnsi;
3083 	int insn_cnt = env->prog->len;
3084 
3085 	/* now check that all jumps are within the same subprog */
3086 	subprog_start = subprog[cur_subprog].start;
3087 	subprog_end = subprog[cur_subprog + 1].start;
3088 	for (i = 0; i < insn_cnt; i++) {
3089 		u8 code = insn[i].code;
3090 
3091 		if (code == (BPF_JMP | BPF_CALL) &&
3092 		    insn[i].src_reg == 0 &&
3093 		    insn[i].imm == BPF_FUNC_tail_call) {
3094 			subprog[cur_subprog].has_tail_call = true;
3095 			subprog[cur_subprog].tail_call_reachable = true;
3096 		}
3097 		if (BPF_CLASS(code) == BPF_LD &&
3098 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3099 			subprog[cur_subprog].has_ld_abs = true;
3100 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3101 			goto next;
3102 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3103 			goto next;
3104 		if (code == (BPF_JMP32 | BPF_JA))
3105 			off = i + insn[i].imm + 1;
3106 		else
3107 			off = i + insn[i].off + 1;
3108 		if (off < subprog_start || off >= subprog_end) {
3109 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3110 			return -EINVAL;
3111 		}
3112 next:
3113 		if (i == subprog_end - 1) {
3114 			/* to avoid fall-through from one subprog into another
3115 			 * the last insn of the subprog should be either exit
3116 			 * or unconditional jump back
3117 			 */
3118 			if (code != (BPF_JMP | BPF_EXIT) &&
3119 			    code != (BPF_JMP32 | BPF_JA) &&
3120 			    code != (BPF_JMP | BPF_JA)) {
3121 				verbose(env, "last insn is not an exit or jmp\n");
3122 				return -EINVAL;
3123 			}
3124 			subprog_start = subprog_end;
3125 			cur_subprog++;
3126 			if (cur_subprog < env->subprog_cnt)
3127 				subprog_end = subprog[cur_subprog + 1].start;
3128 		}
3129 	}
3130 	return 0;
3131 }
3132 
3133 /* Parentage chain of this register (or stack slot) should take care of all
3134  * issues like callee-saved registers, stack slot allocation time, etc.
3135  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)3136 static int mark_reg_read(struct bpf_verifier_env *env,
3137 			 const struct bpf_reg_state *state,
3138 			 struct bpf_reg_state *parent, u8 flag)
3139 {
3140 	bool writes = parent == state->parent; /* Observe write marks */
3141 	int cnt = 0;
3142 
3143 	while (parent) {
3144 		/* if read wasn't screened by an earlier write ... */
3145 		if (writes && state->live & REG_LIVE_WRITTEN)
3146 			break;
3147 		if (parent->live & REG_LIVE_DONE) {
3148 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3149 				reg_type_str(env, parent->type),
3150 				parent->var_off.value, parent->off);
3151 			return -EFAULT;
3152 		}
3153 		/* The first condition is more likely to be true than the
3154 		 * second, checked it first.
3155 		 */
3156 		if ((parent->live & REG_LIVE_READ) == flag ||
3157 		    parent->live & REG_LIVE_READ64)
3158 			/* The parentage chain never changes and
3159 			 * this parent was already marked as LIVE_READ.
3160 			 * There is no need to keep walking the chain again and
3161 			 * keep re-marking all parents as LIVE_READ.
3162 			 * This case happens when the same register is read
3163 			 * multiple times without writes into it in-between.
3164 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3165 			 * then no need to set the weak REG_LIVE_READ32.
3166 			 */
3167 			break;
3168 		/* ... then we depend on parent's value */
3169 		parent->live |= flag;
3170 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3171 		if (flag == REG_LIVE_READ64)
3172 			parent->live &= ~REG_LIVE_READ32;
3173 		state = parent;
3174 		parent = state->parent;
3175 		writes = true;
3176 		cnt++;
3177 	}
3178 
3179 	if (env->longest_mark_read_walk < cnt)
3180 		env->longest_mark_read_walk = cnt;
3181 	return 0;
3182 }
3183 
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3184 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3185 {
3186 	struct bpf_func_state *state = func(env, reg);
3187 	int spi, ret;
3188 
3189 	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3190 	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3191 	 * check_kfunc_call.
3192 	 */
3193 	if (reg->type == CONST_PTR_TO_DYNPTR)
3194 		return 0;
3195 	spi = dynptr_get_spi(env, reg);
3196 	if (spi < 0)
3197 		return spi;
3198 	/* Caller ensures dynptr is valid and initialized, which means spi is in
3199 	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3200 	 * read.
3201 	 */
3202 	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3203 			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3204 	if (ret)
3205 		return ret;
3206 	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3207 			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3208 }
3209 
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3210 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3211 			  int spi, int nr_slots)
3212 {
3213 	struct bpf_func_state *state = func(env, reg);
3214 	int err, i;
3215 
3216 	for (i = 0; i < nr_slots; i++) {
3217 		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3218 
3219 		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3220 		if (err)
3221 			return err;
3222 
3223 		mark_stack_slot_scratched(env, spi - i);
3224 	}
3225 
3226 	return 0;
3227 }
3228 
3229 /* This function is supposed to be used by the following 32-bit optimization
3230  * code only. It returns TRUE if the source or destination register operates
3231  * on 64-bit, otherwise return FALSE.
3232  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3233 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3234 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3235 {
3236 	u8 code, class, op;
3237 
3238 	code = insn->code;
3239 	class = BPF_CLASS(code);
3240 	op = BPF_OP(code);
3241 	if (class == BPF_JMP) {
3242 		/* BPF_EXIT for "main" will reach here. Return TRUE
3243 		 * conservatively.
3244 		 */
3245 		if (op == BPF_EXIT)
3246 			return true;
3247 		if (op == BPF_CALL) {
3248 			/* BPF to BPF call will reach here because of marking
3249 			 * caller saved clobber with DST_OP_NO_MARK for which we
3250 			 * don't care the register def because they are anyway
3251 			 * marked as NOT_INIT already.
3252 			 */
3253 			if (insn->src_reg == BPF_PSEUDO_CALL)
3254 				return false;
3255 			/* Helper call will reach here because of arg type
3256 			 * check, conservatively return TRUE.
3257 			 */
3258 			if (t == SRC_OP)
3259 				return true;
3260 
3261 			return false;
3262 		}
3263 	}
3264 
3265 	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3266 		return false;
3267 
3268 	if (class == BPF_ALU64 || class == BPF_JMP ||
3269 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3270 		return true;
3271 
3272 	if (class == BPF_ALU || class == BPF_JMP32)
3273 		return false;
3274 
3275 	if (class == BPF_LDX) {
3276 		if (t != SRC_OP)
3277 			return BPF_SIZE(code) == BPF_DW;
3278 		/* LDX source must be ptr. */
3279 		return true;
3280 	}
3281 
3282 	if (class == BPF_STX) {
3283 		/* BPF_STX (including atomic variants) has multiple source
3284 		 * operands, one of which is a ptr. Check whether the caller is
3285 		 * asking about it.
3286 		 */
3287 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3288 			return true;
3289 		return BPF_SIZE(code) == BPF_DW;
3290 	}
3291 
3292 	if (class == BPF_LD) {
3293 		u8 mode = BPF_MODE(code);
3294 
3295 		/* LD_IMM64 */
3296 		if (mode == BPF_IMM)
3297 			return true;
3298 
3299 		/* Both LD_IND and LD_ABS return 32-bit data. */
3300 		if (t != SRC_OP)
3301 			return  false;
3302 
3303 		/* Implicit ctx ptr. */
3304 		if (regno == BPF_REG_6)
3305 			return true;
3306 
3307 		/* Explicit source could be any width. */
3308 		return true;
3309 	}
3310 
3311 	if (class == BPF_ST)
3312 		/* The only source register for BPF_ST is a ptr. */
3313 		return true;
3314 
3315 	/* Conservatively return true at default. */
3316 	return true;
3317 }
3318 
3319 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3320 static int insn_def_regno(const struct bpf_insn *insn)
3321 {
3322 	switch (BPF_CLASS(insn->code)) {
3323 	case BPF_JMP:
3324 	case BPF_JMP32:
3325 	case BPF_ST:
3326 		return -1;
3327 	case BPF_STX:
3328 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3329 		    (insn->imm & BPF_FETCH)) {
3330 			if (insn->imm == BPF_CMPXCHG)
3331 				return BPF_REG_0;
3332 			else
3333 				return insn->src_reg;
3334 		} else {
3335 			return -1;
3336 		}
3337 	default:
3338 		return insn->dst_reg;
3339 	}
3340 }
3341 
3342 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)3343 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3344 {
3345 	int dst_reg = insn_def_regno(insn);
3346 
3347 	if (dst_reg == -1)
3348 		return false;
3349 
3350 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3351 }
3352 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3353 static void mark_insn_zext(struct bpf_verifier_env *env,
3354 			   struct bpf_reg_state *reg)
3355 {
3356 	s32 def_idx = reg->subreg_def;
3357 
3358 	if (def_idx == DEF_NOT_SUBREG)
3359 		return;
3360 
3361 	env->insn_aux_data[def_idx - 1].zext_dst = true;
3362 	/* The dst will be zero extended, so won't be sub-register anymore. */
3363 	reg->subreg_def = DEF_NOT_SUBREG;
3364 }
3365 
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3366 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3367 			   enum reg_arg_type t)
3368 {
3369 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3370 	struct bpf_reg_state *reg;
3371 	bool rw64;
3372 
3373 	if (regno >= MAX_BPF_REG) {
3374 		verbose(env, "R%d is invalid\n", regno);
3375 		return -EINVAL;
3376 	}
3377 
3378 	mark_reg_scratched(env, regno);
3379 
3380 	reg = &regs[regno];
3381 	rw64 = is_reg64(env, insn, regno, reg, t);
3382 	if (t == SRC_OP) {
3383 		/* check whether register used as source operand can be read */
3384 		if (reg->type == NOT_INIT) {
3385 			verbose(env, "R%d !read_ok\n", regno);
3386 			return -EACCES;
3387 		}
3388 		/* We don't need to worry about FP liveness because it's read-only */
3389 		if (regno == BPF_REG_FP)
3390 			return 0;
3391 
3392 		if (rw64)
3393 			mark_insn_zext(env, reg);
3394 
3395 		return mark_reg_read(env, reg, reg->parent,
3396 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3397 	} else {
3398 		/* check whether register used as dest operand can be written to */
3399 		if (regno == BPF_REG_FP) {
3400 			verbose(env, "frame pointer is read only\n");
3401 			return -EACCES;
3402 		}
3403 		reg->live |= REG_LIVE_WRITTEN;
3404 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3405 		if (t == DST_OP)
3406 			mark_reg_unknown(env, regs, regno);
3407 	}
3408 	return 0;
3409 }
3410 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3411 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3412 			 enum reg_arg_type t)
3413 {
3414 	struct bpf_verifier_state *vstate = env->cur_state;
3415 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3416 
3417 	return __check_reg_arg(env, state->regs, regno, t);
3418 }
3419 
mark_jmp_point(struct bpf_verifier_env * env,int idx)3420 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3421 {
3422 	env->insn_aux_data[idx].jmp_point = true;
3423 }
3424 
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3425 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3426 {
3427 	return env->insn_aux_data[insn_idx].jmp_point;
3428 }
3429 
3430 /* 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)3431 static int push_jmp_history(struct bpf_verifier_env *env,
3432 			    struct bpf_verifier_state *cur)
3433 {
3434 	u32 cnt = cur->jmp_history_cnt;
3435 	struct bpf_idx_pair *p;
3436 	size_t alloc_size;
3437 
3438 	if (!is_jmp_point(env, env->insn_idx))
3439 		return 0;
3440 
3441 	cnt++;
3442 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3443 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3444 	if (!p)
3445 		return -ENOMEM;
3446 	p[cnt - 1].idx = env->insn_idx;
3447 	p[cnt - 1].prev_idx = env->prev_insn_idx;
3448 	cur->jmp_history = p;
3449 	cur->jmp_history_cnt = cnt;
3450 	return 0;
3451 }
3452 
3453 /* Backtrack one insn at a time. If idx is not at the top of recorded
3454  * history then previous instruction came from straight line execution.
3455  * Return -ENOENT if we exhausted all instructions within given state.
3456  *
3457  * It's legal to have a bit of a looping with the same starting and ending
3458  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3459  * instruction index is the same as state's first_idx doesn't mean we are
3460  * done. If there is still some jump history left, we should keep going. We
3461  * need to take into account that we might have a jump history between given
3462  * state's parent and itself, due to checkpointing. In this case, we'll have
3463  * history entry recording a jump from last instruction of parent state and
3464  * first instruction of given state.
3465  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)3466 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3467 			     u32 *history)
3468 {
3469 	u32 cnt = *history;
3470 
3471 	if (i == st->first_insn_idx) {
3472 		if (cnt == 0)
3473 			return -ENOENT;
3474 		if (cnt == 1 && st->jmp_history[0].idx == i)
3475 			return -ENOENT;
3476 	}
3477 
3478 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3479 		i = st->jmp_history[cnt - 1].prev_idx;
3480 		(*history)--;
3481 	} else {
3482 		i--;
3483 	}
3484 	return i;
3485 }
3486 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)3487 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3488 {
3489 	const struct btf_type *func;
3490 	struct btf *desc_btf;
3491 
3492 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3493 		return NULL;
3494 
3495 	desc_btf = find_kfunc_desc_btf(data, insn->off);
3496 	if (IS_ERR(desc_btf))
3497 		return "<error>";
3498 
3499 	func = btf_type_by_id(desc_btf, insn->imm);
3500 	return btf_name_by_offset(desc_btf, func->name_off);
3501 }
3502 
bt_init(struct backtrack_state * bt,u32 frame)3503 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3504 {
3505 	bt->frame = frame;
3506 }
3507 
bt_reset(struct backtrack_state * bt)3508 static inline void bt_reset(struct backtrack_state *bt)
3509 {
3510 	struct bpf_verifier_env *env = bt->env;
3511 
3512 	memset(bt, 0, sizeof(*bt));
3513 	bt->env = env;
3514 }
3515 
bt_empty(struct backtrack_state * bt)3516 static inline u32 bt_empty(struct backtrack_state *bt)
3517 {
3518 	u64 mask = 0;
3519 	int i;
3520 
3521 	for (i = 0; i <= bt->frame; i++)
3522 		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3523 
3524 	return mask == 0;
3525 }
3526 
bt_subprog_enter(struct backtrack_state * bt)3527 static inline int bt_subprog_enter(struct backtrack_state *bt)
3528 {
3529 	if (bt->frame == MAX_CALL_FRAMES - 1) {
3530 		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3531 		WARN_ONCE(1, "verifier backtracking bug");
3532 		return -EFAULT;
3533 	}
3534 	bt->frame++;
3535 	return 0;
3536 }
3537 
bt_subprog_exit(struct backtrack_state * bt)3538 static inline int bt_subprog_exit(struct backtrack_state *bt)
3539 {
3540 	if (bt->frame == 0) {
3541 		verbose(bt->env, "BUG subprog exit from frame 0\n");
3542 		WARN_ONCE(1, "verifier backtracking bug");
3543 		return -EFAULT;
3544 	}
3545 	bt->frame--;
3546 	return 0;
3547 }
3548 
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3549 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3550 {
3551 	bt->reg_masks[frame] |= 1 << reg;
3552 }
3553 
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3554 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3555 {
3556 	bt->reg_masks[frame] &= ~(1 << reg);
3557 }
3558 
bt_set_reg(struct backtrack_state * bt,u32 reg)3559 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3560 {
3561 	bt_set_frame_reg(bt, bt->frame, reg);
3562 }
3563 
bt_clear_reg(struct backtrack_state * bt,u32 reg)3564 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3565 {
3566 	bt_clear_frame_reg(bt, bt->frame, reg);
3567 }
3568 
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3569 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3570 {
3571 	bt->stack_masks[frame] |= 1ull << slot;
3572 }
3573 
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3574 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3575 {
3576 	bt->stack_masks[frame] &= ~(1ull << slot);
3577 }
3578 
bt_set_slot(struct backtrack_state * bt,u32 slot)3579 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3580 {
3581 	bt_set_frame_slot(bt, bt->frame, slot);
3582 }
3583 
bt_clear_slot(struct backtrack_state * bt,u32 slot)3584 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3585 {
3586 	bt_clear_frame_slot(bt, bt->frame, slot);
3587 }
3588 
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)3589 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3590 {
3591 	return bt->reg_masks[frame];
3592 }
3593 
bt_reg_mask(struct backtrack_state * bt)3594 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3595 {
3596 	return bt->reg_masks[bt->frame];
3597 }
3598 
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)3599 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3600 {
3601 	return bt->stack_masks[frame];
3602 }
3603 
bt_stack_mask(struct backtrack_state * bt)3604 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3605 {
3606 	return bt->stack_masks[bt->frame];
3607 }
3608 
bt_is_reg_set(struct backtrack_state * bt,u32 reg)3609 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3610 {
3611 	return bt->reg_masks[bt->frame] & (1 << reg);
3612 }
3613 
bt_is_slot_set(struct backtrack_state * bt,u32 slot)3614 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3615 {
3616 	return bt->stack_masks[bt->frame] & (1ull << slot);
3617 }
3618 
3619 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)3620 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3621 {
3622 	DECLARE_BITMAP(mask, 64);
3623 	bool first = true;
3624 	int i, n;
3625 
3626 	buf[0] = '\0';
3627 
3628 	bitmap_from_u64(mask, reg_mask);
3629 	for_each_set_bit(i, mask, 32) {
3630 		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3631 		first = false;
3632 		buf += n;
3633 		buf_sz -= n;
3634 		if (buf_sz < 0)
3635 			break;
3636 	}
3637 }
3638 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)3639 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3640 {
3641 	DECLARE_BITMAP(mask, 64);
3642 	bool first = true;
3643 	int i, n;
3644 
3645 	buf[0] = '\0';
3646 
3647 	bitmap_from_u64(mask, stack_mask);
3648 	for_each_set_bit(i, mask, 64) {
3649 		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3650 		first = false;
3651 		buf += n;
3652 		buf_sz -= n;
3653 		if (buf_sz < 0)
3654 			break;
3655 	}
3656 }
3657 
3658 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3659 
3660 /* For given verifier state backtrack_insn() is called from the last insn to
3661  * the first insn. Its purpose is to compute a bitmask of registers and
3662  * stack slots that needs precision in the parent verifier state.
3663  *
3664  * @idx is an index of the instruction we are currently processing;
3665  * @subseq_idx is an index of the subsequent instruction that:
3666  *   - *would be* executed next, if jump history is viewed in forward order;
3667  *   - *was* processed previously during backtracking.
3668  */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct backtrack_state * bt)3669 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3670 			  struct backtrack_state *bt)
3671 {
3672 	const struct bpf_insn_cbs cbs = {
3673 		.cb_call	= disasm_kfunc_name,
3674 		.cb_print	= verbose,
3675 		.private_data	= env,
3676 	};
3677 	struct bpf_insn *insn = env->prog->insnsi + idx;
3678 	u8 class = BPF_CLASS(insn->code);
3679 	u8 opcode = BPF_OP(insn->code);
3680 	u8 mode = BPF_MODE(insn->code);
3681 	u32 dreg = insn->dst_reg;
3682 	u32 sreg = insn->src_reg;
3683 	u32 spi, i;
3684 
3685 	if (insn->code == 0)
3686 		return 0;
3687 	if (env->log.level & BPF_LOG_LEVEL2) {
3688 		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3689 		verbose(env, "mark_precise: frame%d: regs=%s ",
3690 			bt->frame, env->tmp_str_buf);
3691 		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3692 		verbose(env, "stack=%s before ", env->tmp_str_buf);
3693 		verbose(env, "%d: ", idx);
3694 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3695 	}
3696 
3697 	if (class == BPF_ALU || class == BPF_ALU64) {
3698 		if (!bt_is_reg_set(bt, dreg))
3699 			return 0;
3700 		if (opcode == BPF_END || opcode == BPF_NEG) {
3701 			/* sreg is reserved and unused
3702 			 * dreg still need precision before this insn
3703 			 */
3704 			return 0;
3705 		} else if (opcode == BPF_MOV) {
3706 			if (BPF_SRC(insn->code) == BPF_X) {
3707 				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3708 				 * dreg needs precision after this insn
3709 				 * sreg needs precision before this insn
3710 				 */
3711 				bt_clear_reg(bt, dreg);
3712 				if (sreg != BPF_REG_FP)
3713 					bt_set_reg(bt, sreg);
3714 			} else {
3715 				/* dreg = K
3716 				 * dreg needs precision after this insn.
3717 				 * Corresponding register is already marked
3718 				 * as precise=true in this verifier state.
3719 				 * No further markings in parent are necessary
3720 				 */
3721 				bt_clear_reg(bt, dreg);
3722 			}
3723 		} else {
3724 			if (BPF_SRC(insn->code) == BPF_X) {
3725 				/* dreg += sreg
3726 				 * both dreg and sreg need precision
3727 				 * before this insn
3728 				 */
3729 				if (sreg != BPF_REG_FP)
3730 					bt_set_reg(bt, sreg);
3731 			} /* else dreg += K
3732 			   * dreg still needs precision before this insn
3733 			   */
3734 		}
3735 	} else if (class == BPF_LDX) {
3736 		if (!bt_is_reg_set(bt, dreg))
3737 			return 0;
3738 		bt_clear_reg(bt, dreg);
3739 
3740 		/* scalars can only be spilled into stack w/o losing precision.
3741 		 * Load from any other memory can be zero extended.
3742 		 * The desire to keep that precision is already indicated
3743 		 * by 'precise' mark in corresponding register of this state.
3744 		 * No further tracking necessary.
3745 		 */
3746 		if (insn->src_reg != BPF_REG_FP)
3747 			return 0;
3748 
3749 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3750 		 * that [fp - off] slot contains scalar that needs to be
3751 		 * tracked with precision
3752 		 */
3753 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3754 		if (spi >= 64) {
3755 			verbose(env, "BUG spi %d\n", spi);
3756 			WARN_ONCE(1, "verifier backtracking bug");
3757 			return -EFAULT;
3758 		}
3759 		bt_set_slot(bt, spi);
3760 	} else if (class == BPF_STX || class == BPF_ST) {
3761 		if (bt_is_reg_set(bt, dreg))
3762 			/* stx & st shouldn't be using _scalar_ dst_reg
3763 			 * to access memory. It means backtracking
3764 			 * encountered a case of pointer subtraction.
3765 			 */
3766 			return -ENOTSUPP;
3767 		/* scalars can only be spilled into stack */
3768 		if (insn->dst_reg != BPF_REG_FP)
3769 			return 0;
3770 		spi = (-insn->off - 1) / BPF_REG_SIZE;
3771 		if (spi >= 64) {
3772 			verbose(env, "BUG spi %d\n", spi);
3773 			WARN_ONCE(1, "verifier backtracking bug");
3774 			return -EFAULT;
3775 		}
3776 		if (!bt_is_slot_set(bt, spi))
3777 			return 0;
3778 		bt_clear_slot(bt, spi);
3779 		if (class == BPF_STX)
3780 			bt_set_reg(bt, sreg);
3781 	} else if (class == BPF_JMP || class == BPF_JMP32) {
3782 		if (bpf_pseudo_call(insn)) {
3783 			int subprog_insn_idx, subprog;
3784 
3785 			subprog_insn_idx = idx + insn->imm + 1;
3786 			subprog = find_subprog(env, subprog_insn_idx);
3787 			if (subprog < 0)
3788 				return -EFAULT;
3789 
3790 			if (subprog_is_global(env, subprog)) {
3791 				/* check that jump history doesn't have any
3792 				 * extra instructions from subprog; the next
3793 				 * instruction after call to global subprog
3794 				 * should be literally next instruction in
3795 				 * caller program
3796 				 */
3797 				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3798 				/* r1-r5 are invalidated after subprog call,
3799 				 * so for global func call it shouldn't be set
3800 				 * anymore
3801 				 */
3802 				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3803 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3804 					WARN_ONCE(1, "verifier backtracking bug");
3805 					return -EFAULT;
3806 				}
3807 				/* global subprog always sets R0 */
3808 				bt_clear_reg(bt, BPF_REG_0);
3809 				return 0;
3810 			} else {
3811 				/* static subprog call instruction, which
3812 				 * means that we are exiting current subprog,
3813 				 * so only r1-r5 could be still requested as
3814 				 * precise, r0 and r6-r10 or any stack slot in
3815 				 * the current frame should be zero by now
3816 				 */
3817 				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3818 					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3819 					WARN_ONCE(1, "verifier backtracking bug");
3820 					return -EFAULT;
3821 				}
3822 				/* we don't track register spills perfectly,
3823 				 * so fallback to force-precise instead of failing */
3824 				if (bt_stack_mask(bt) != 0)
3825 					return -ENOTSUPP;
3826 				/* propagate r1-r5 to the caller */
3827 				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3828 					if (bt_is_reg_set(bt, i)) {
3829 						bt_clear_reg(bt, i);
3830 						bt_set_frame_reg(bt, bt->frame - 1, i);
3831 					}
3832 				}
3833 				if (bt_subprog_exit(bt))
3834 					return -EFAULT;
3835 				return 0;
3836 			}
3837 		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3838 			/* exit from callback subprog to callback-calling helper or
3839 			 * kfunc call. Use idx/subseq_idx check to discern it from
3840 			 * straight line code backtracking.
3841 			 * Unlike the subprog call handling above, we shouldn't
3842 			 * propagate precision of r1-r5 (if any requested), as they are
3843 			 * not actually arguments passed directly to callback subprogs
3844 			 */
3845 			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3846 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3847 				WARN_ONCE(1, "verifier backtracking bug");
3848 				return -EFAULT;
3849 			}
3850 			if (bt_stack_mask(bt) != 0)
3851 				return -ENOTSUPP;
3852 			/* clear r1-r5 in callback subprog's mask */
3853 			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3854 				bt_clear_reg(bt, i);
3855 			if (bt_subprog_exit(bt))
3856 				return -EFAULT;
3857 			return 0;
3858 		} else if (opcode == BPF_CALL) {
3859 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3860 			 * catch this error later. Make backtracking conservative
3861 			 * with ENOTSUPP.
3862 			 */
3863 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3864 				return -ENOTSUPP;
3865 			/* regular helper call sets R0 */
3866 			bt_clear_reg(bt, BPF_REG_0);
3867 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3868 				/* if backtracing was looking for registers R1-R5
3869 				 * they should have been found already.
3870 				 */
3871 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3872 				WARN_ONCE(1, "verifier backtracking bug");
3873 				return -EFAULT;
3874 			}
3875 		} else if (opcode == BPF_EXIT) {
3876 			bool r0_precise;
3877 
3878 			/* Backtracking to a nested function call, 'idx' is a part of
3879 			 * the inner frame 'subseq_idx' is a part of the outer frame.
3880 			 * In case of a regular function call, instructions giving
3881 			 * precision to registers R1-R5 should have been found already.
3882 			 * In case of a callback, it is ok to have R1-R5 marked for
3883 			 * backtracking, as these registers are set by the function
3884 			 * invoking callback.
3885 			 */
3886 			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3887 				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3888 					bt_clear_reg(bt, i);
3889 			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3890 				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3891 				WARN_ONCE(1, "verifier backtracking bug");
3892 				return -EFAULT;
3893 			}
3894 
3895 			/* BPF_EXIT in subprog or callback always returns
3896 			 * right after the call instruction, so by checking
3897 			 * whether the instruction at subseq_idx-1 is subprog
3898 			 * call or not we can distinguish actual exit from
3899 			 * *subprog* from exit from *callback*. In the former
3900 			 * case, we need to propagate r0 precision, if
3901 			 * necessary. In the former we never do that.
3902 			 */
3903 			r0_precise = subseq_idx - 1 >= 0 &&
3904 				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3905 				     bt_is_reg_set(bt, BPF_REG_0);
3906 
3907 			bt_clear_reg(bt, BPF_REG_0);
3908 			if (bt_subprog_enter(bt))
3909 				return -EFAULT;
3910 
3911 			if (r0_precise)
3912 				bt_set_reg(bt, BPF_REG_0);
3913 			/* r6-r9 and stack slots will stay set in caller frame
3914 			 * bitmasks until we return back from callee(s)
3915 			 */
3916 			return 0;
3917 		} else if (BPF_SRC(insn->code) == BPF_X) {
3918 			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3919 				return 0;
3920 			/* dreg <cond> sreg
3921 			 * Both dreg and sreg need precision before
3922 			 * this insn. If only sreg was marked precise
3923 			 * before it would be equally necessary to
3924 			 * propagate it to dreg.
3925 			 */
3926 			bt_set_reg(bt, dreg);
3927 			bt_set_reg(bt, sreg);
3928 			 /* else dreg <cond> K
3929 			  * Only dreg still needs precision before
3930 			  * this insn, so for the K-based conditional
3931 			  * there is nothing new to be marked.
3932 			  */
3933 		}
3934 	} else if (class == BPF_LD) {
3935 		if (!bt_is_reg_set(bt, dreg))
3936 			return 0;
3937 		bt_clear_reg(bt, dreg);
3938 		/* It's ld_imm64 or ld_abs or ld_ind.
3939 		 * For ld_imm64 no further tracking of precision
3940 		 * into parent is necessary
3941 		 */
3942 		if (mode == BPF_IND || mode == BPF_ABS)
3943 			/* to be analyzed */
3944 			return -ENOTSUPP;
3945 	}
3946 	return 0;
3947 }
3948 
3949 /* the scalar precision tracking algorithm:
3950  * . at the start all registers have precise=false.
3951  * . scalar ranges are tracked as normal through alu and jmp insns.
3952  * . once precise value of the scalar register is used in:
3953  *   .  ptr + scalar alu
3954  *   . if (scalar cond K|scalar)
3955  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3956  *   backtrack through the verifier states and mark all registers and
3957  *   stack slots with spilled constants that these scalar regisers
3958  *   should be precise.
3959  * . during state pruning two registers (or spilled stack slots)
3960  *   are equivalent if both are not precise.
3961  *
3962  * Note the verifier cannot simply walk register parentage chain,
3963  * since many different registers and stack slots could have been
3964  * used to compute single precise scalar.
3965  *
3966  * The approach of starting with precise=true for all registers and then
3967  * backtrack to mark a register as not precise when the verifier detects
3968  * that program doesn't care about specific value (e.g., when helper
3969  * takes register as ARG_ANYTHING parameter) is not safe.
3970  *
3971  * It's ok to walk single parentage chain of the verifier states.
3972  * It's possible that this backtracking will go all the way till 1st insn.
3973  * All other branches will be explored for needing precision later.
3974  *
3975  * The backtracking needs to deal with cases like:
3976  *   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)
3977  * r9 -= r8
3978  * r5 = r9
3979  * if r5 > 0x79f goto pc+7
3980  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3981  * r5 += 1
3982  * ...
3983  * call bpf_perf_event_output#25
3984  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3985  *
3986  * and this case:
3987  * r6 = 1
3988  * call foo // uses callee's r6 inside to compute r0
3989  * r0 += r6
3990  * if r0 == 0 goto
3991  *
3992  * to track above reg_mask/stack_mask needs to be independent for each frame.
3993  *
3994  * Also if parent's curframe > frame where backtracking started,
3995  * the verifier need to mark registers in both frames, otherwise callees
3996  * may incorrectly prune callers. This is similar to
3997  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3998  *
3999  * For now backtracking falls back into conservative marking.
4000  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4001 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4002 				     struct bpf_verifier_state *st)
4003 {
4004 	struct bpf_func_state *func;
4005 	struct bpf_reg_state *reg;
4006 	int i, j;
4007 
4008 	if (env->log.level & BPF_LOG_LEVEL2) {
4009 		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4010 			st->curframe);
4011 	}
4012 
4013 	/* big hammer: mark all scalars precise in this path.
4014 	 * pop_stack may still get !precise scalars.
4015 	 * We also skip current state and go straight to first parent state,
4016 	 * because precision markings in current non-checkpointed state are
4017 	 * not needed. See why in the comment in __mark_chain_precision below.
4018 	 */
4019 	for (st = st->parent; st; st = st->parent) {
4020 		for (i = 0; i <= st->curframe; i++) {
4021 			func = st->frame[i];
4022 			for (j = 0; j < BPF_REG_FP; j++) {
4023 				reg = &func->regs[j];
4024 				if (reg->type != SCALAR_VALUE || reg->precise)
4025 					continue;
4026 				reg->precise = true;
4027 				if (env->log.level & BPF_LOG_LEVEL2) {
4028 					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4029 						i, j);
4030 				}
4031 			}
4032 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4033 				if (!is_spilled_reg(&func->stack[j]))
4034 					continue;
4035 				reg = &func->stack[j].spilled_ptr;
4036 				if (reg->type != SCALAR_VALUE || reg->precise)
4037 					continue;
4038 				reg->precise = true;
4039 				if (env->log.level & BPF_LOG_LEVEL2) {
4040 					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4041 						i, -(j + 1) * 8);
4042 				}
4043 			}
4044 		}
4045 	}
4046 }
4047 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4048 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4049 {
4050 	struct bpf_func_state *func;
4051 	struct bpf_reg_state *reg;
4052 	int i, j;
4053 
4054 	for (i = 0; i <= st->curframe; i++) {
4055 		func = st->frame[i];
4056 		for (j = 0; j < BPF_REG_FP; j++) {
4057 			reg = &func->regs[j];
4058 			if (reg->type != SCALAR_VALUE)
4059 				continue;
4060 			reg->precise = false;
4061 		}
4062 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4063 			if (!is_spilled_reg(&func->stack[j]))
4064 				continue;
4065 			reg = &func->stack[j].spilled_ptr;
4066 			if (reg->type != SCALAR_VALUE)
4067 				continue;
4068 			reg->precise = false;
4069 		}
4070 	}
4071 }
4072 
idset_contains(struct bpf_idset * s,u32 id)4073 static bool idset_contains(struct bpf_idset *s, u32 id)
4074 {
4075 	u32 i;
4076 
4077 	for (i = 0; i < s->count; ++i)
4078 		if (s->ids[i] == id)
4079 			return true;
4080 
4081 	return false;
4082 }
4083 
idset_push(struct bpf_idset * s,u32 id)4084 static int idset_push(struct bpf_idset *s, u32 id)
4085 {
4086 	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4087 		return -EFAULT;
4088 	s->ids[s->count++] = id;
4089 	return 0;
4090 }
4091 
idset_reset(struct bpf_idset * s)4092 static void idset_reset(struct bpf_idset *s)
4093 {
4094 	s->count = 0;
4095 }
4096 
4097 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4098  * Mark all registers with these IDs as precise.
4099  */
mark_precise_scalar_ids(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4100 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4101 {
4102 	struct bpf_idset *precise_ids = &env->idset_scratch;
4103 	struct backtrack_state *bt = &env->bt;
4104 	struct bpf_func_state *func;
4105 	struct bpf_reg_state *reg;
4106 	DECLARE_BITMAP(mask, 64);
4107 	int i, fr;
4108 
4109 	idset_reset(precise_ids);
4110 
4111 	for (fr = bt->frame; fr >= 0; fr--) {
4112 		func = st->frame[fr];
4113 
4114 		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4115 		for_each_set_bit(i, mask, 32) {
4116 			reg = &func->regs[i];
4117 			if (!reg->id || reg->type != SCALAR_VALUE)
4118 				continue;
4119 			if (idset_push(precise_ids, reg->id))
4120 				return -EFAULT;
4121 		}
4122 
4123 		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4124 		for_each_set_bit(i, mask, 64) {
4125 			if (i >= func->allocated_stack / BPF_REG_SIZE)
4126 				break;
4127 			if (!is_spilled_scalar_reg(&func->stack[i]))
4128 				continue;
4129 			reg = &func->stack[i].spilled_ptr;
4130 			if (!reg->id)
4131 				continue;
4132 			if (idset_push(precise_ids, reg->id))
4133 				return -EFAULT;
4134 		}
4135 	}
4136 
4137 	for (fr = 0; fr <= st->curframe; ++fr) {
4138 		func = st->frame[fr];
4139 
4140 		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4141 			reg = &func->regs[i];
4142 			if (!reg->id)
4143 				continue;
4144 			if (!idset_contains(precise_ids, reg->id))
4145 				continue;
4146 			bt_set_frame_reg(bt, fr, i);
4147 		}
4148 		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4149 			if (!is_spilled_scalar_reg(&func->stack[i]))
4150 				continue;
4151 			reg = &func->stack[i].spilled_ptr;
4152 			if (!reg->id)
4153 				continue;
4154 			if (!idset_contains(precise_ids, reg->id))
4155 				continue;
4156 			bt_set_frame_slot(bt, fr, i);
4157 		}
4158 	}
4159 
4160 	return 0;
4161 }
4162 
4163 /*
4164  * __mark_chain_precision() backtracks BPF program instruction sequence and
4165  * chain of verifier states making sure that register *regno* (if regno >= 0)
4166  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4167  * SCALARS, as well as any other registers and slots that contribute to
4168  * a tracked state of given registers/stack slots, depending on specific BPF
4169  * assembly instructions (see backtrack_insns() for exact instruction handling
4170  * logic). This backtracking relies on recorded jmp_history and is able to
4171  * traverse entire chain of parent states. This process ends only when all the
4172  * necessary registers/slots and their transitive dependencies are marked as
4173  * precise.
4174  *
4175  * One important and subtle aspect is that precise marks *do not matter* in
4176  * the currently verified state (current state). It is important to understand
4177  * why this is the case.
4178  *
4179  * First, note that current state is the state that is not yet "checkpointed",
4180  * i.e., it is not yet put into env->explored_states, and it has no children
4181  * states as well. It's ephemeral, and can end up either a) being discarded if
4182  * compatible explored state is found at some point or BPF_EXIT instruction is
4183  * reached or b) checkpointed and put into env->explored_states, branching out
4184  * into one or more children states.
4185  *
4186  * In the former case, precise markings in current state are completely
4187  * ignored by state comparison code (see regsafe() for details). Only
4188  * checkpointed ("old") state precise markings are important, and if old
4189  * state's register/slot is precise, regsafe() assumes current state's
4190  * register/slot as precise and checks value ranges exactly and precisely. If
4191  * states turn out to be compatible, current state's necessary precise
4192  * markings and any required parent states' precise markings are enforced
4193  * after the fact with propagate_precision() logic, after the fact. But it's
4194  * important to realize that in this case, even after marking current state
4195  * registers/slots as precise, we immediately discard current state. So what
4196  * actually matters is any of the precise markings propagated into current
4197  * state's parent states, which are always checkpointed (due to b) case above).
4198  * As such, for scenario a) it doesn't matter if current state has precise
4199  * markings set or not.
4200  *
4201  * Now, for the scenario b), checkpointing and forking into child(ren)
4202  * state(s). Note that before current state gets to checkpointing step, any
4203  * processed instruction always assumes precise SCALAR register/slot
4204  * knowledge: if precise value or range is useful to prune jump branch, BPF
4205  * verifier takes this opportunity enthusiastically. Similarly, when
4206  * register's value is used to calculate offset or memory address, exact
4207  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4208  * what we mentioned above about state comparison ignoring precise markings
4209  * during state comparison, BPF verifier ignores and also assumes precise
4210  * markings *at will* during instruction verification process. But as verifier
4211  * assumes precision, it also propagates any precision dependencies across
4212  * parent states, which are not yet finalized, so can be further restricted
4213  * based on new knowledge gained from restrictions enforced by their children
4214  * states. This is so that once those parent states are finalized, i.e., when
4215  * they have no more active children state, state comparison logic in
4216  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4217  * required for correctness.
4218  *
4219  * To build a bit more intuition, note also that once a state is checkpointed,
4220  * the path we took to get to that state is not important. This is crucial
4221  * property for state pruning. When state is checkpointed and finalized at
4222  * some instruction index, it can be correctly and safely used to "short
4223  * circuit" any *compatible* state that reaches exactly the same instruction
4224  * index. I.e., if we jumped to that instruction from a completely different
4225  * code path than original finalized state was derived from, it doesn't
4226  * matter, current state can be discarded because from that instruction
4227  * forward having a compatible state will ensure we will safely reach the
4228  * exit. States describe preconditions for further exploration, but completely
4229  * forget the history of how we got here.
4230  *
4231  * This also means that even if we needed precise SCALAR range to get to
4232  * finalized state, but from that point forward *that same* SCALAR register is
4233  * never used in a precise context (i.e., it's precise value is not needed for
4234  * correctness), it's correct and safe to mark such register as "imprecise"
4235  * (i.e., precise marking set to false). This is what we rely on when we do
4236  * not set precise marking in current state. If no child state requires
4237  * precision for any given SCALAR register, it's safe to dictate that it can
4238  * be imprecise. If any child state does require this register to be precise,
4239  * we'll mark it precise later retroactively during precise markings
4240  * propagation from child state to parent states.
4241  *
4242  * Skipping precise marking setting in current state is a mild version of
4243  * relying on the above observation. But we can utilize this property even
4244  * more aggressively by proactively forgetting any precise marking in the
4245  * current state (which we inherited from the parent state), right before we
4246  * checkpoint it and branch off into new child state. This is done by
4247  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4248  * finalized states which help in short circuiting more future states.
4249  */
__mark_chain_precision(struct bpf_verifier_env * env,int regno)4250 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4251 {
4252 	struct backtrack_state *bt = &env->bt;
4253 	struct bpf_verifier_state *st = env->cur_state;
4254 	int first_idx = st->first_insn_idx;
4255 	int last_idx = env->insn_idx;
4256 	int subseq_idx = -1;
4257 	struct bpf_func_state *func;
4258 	struct bpf_reg_state *reg;
4259 	bool skip_first = true;
4260 	int i, fr, err;
4261 
4262 	if (!env->bpf_capable)
4263 		return 0;
4264 
4265 	/* set frame number from which we are starting to backtrack */
4266 	bt_init(bt, env->cur_state->curframe);
4267 
4268 	/* Do sanity checks against current state of register and/or stack
4269 	 * slot, but don't set precise flag in current state, as precision
4270 	 * tracking in the current state is unnecessary.
4271 	 */
4272 	func = st->frame[bt->frame];
4273 	if (regno >= 0) {
4274 		reg = &func->regs[regno];
4275 		if (reg->type != SCALAR_VALUE) {
4276 			WARN_ONCE(1, "backtracing misuse");
4277 			return -EFAULT;
4278 		}
4279 		bt_set_reg(bt, regno);
4280 	}
4281 
4282 	if (bt_empty(bt))
4283 		return 0;
4284 
4285 	for (;;) {
4286 		DECLARE_BITMAP(mask, 64);
4287 		u32 history = st->jmp_history_cnt;
4288 
4289 		if (env->log.level & BPF_LOG_LEVEL2) {
4290 			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4291 				bt->frame, last_idx, first_idx, subseq_idx);
4292 		}
4293 
4294 		/* If some register with scalar ID is marked as precise,
4295 		 * make sure that all registers sharing this ID are also precise.
4296 		 * This is needed to estimate effect of find_equal_scalars().
4297 		 * Do this at the last instruction of each state,
4298 		 * bpf_reg_state::id fields are valid for these instructions.
4299 		 *
4300 		 * Allows to track precision in situation like below:
4301 		 *
4302 		 *     r2 = unknown value
4303 		 *     ...
4304 		 *   --- state #0 ---
4305 		 *     ...
4306 		 *     r1 = r2                 // r1 and r2 now share the same ID
4307 		 *     ...
4308 		 *   --- state #1 {r1.id = A, r2.id = A} ---
4309 		 *     ...
4310 		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4311 		 *     ...
4312 		 *   --- state #2 {r1.id = A, r2.id = A} ---
4313 		 *     r3 = r10
4314 		 *     r3 += r1                // need to mark both r1 and r2
4315 		 */
4316 		if (mark_precise_scalar_ids(env, st))
4317 			return -EFAULT;
4318 
4319 		if (last_idx < 0) {
4320 			/* we are at the entry into subprog, which
4321 			 * is expected for global funcs, but only if
4322 			 * requested precise registers are R1-R5
4323 			 * (which are global func's input arguments)
4324 			 */
4325 			if (st->curframe == 0 &&
4326 			    st->frame[0]->subprogno > 0 &&
4327 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4328 			    bt_stack_mask(bt) == 0 &&
4329 			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4330 				bitmap_from_u64(mask, bt_reg_mask(bt));
4331 				for_each_set_bit(i, mask, 32) {
4332 					reg = &st->frame[0]->regs[i];
4333 					bt_clear_reg(bt, i);
4334 					if (reg->type == SCALAR_VALUE)
4335 						reg->precise = true;
4336 				}
4337 				return 0;
4338 			}
4339 
4340 			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4341 				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4342 			WARN_ONCE(1, "verifier backtracking bug");
4343 			return -EFAULT;
4344 		}
4345 
4346 		for (i = last_idx;;) {
4347 			if (skip_first) {
4348 				err = 0;
4349 				skip_first = false;
4350 			} else {
4351 				err = backtrack_insn(env, i, subseq_idx, bt);
4352 			}
4353 			if (err == -ENOTSUPP) {
4354 				mark_all_scalars_precise(env, env->cur_state);
4355 				bt_reset(bt);
4356 				return 0;
4357 			} else if (err) {
4358 				return err;
4359 			}
4360 			if (bt_empty(bt))
4361 				/* Found assignment(s) into tracked register in this state.
4362 				 * Since this state is already marked, just return.
4363 				 * Nothing to be tracked further in the parent state.
4364 				 */
4365 				return 0;
4366 			subseq_idx = i;
4367 			i = get_prev_insn_idx(st, i, &history);
4368 			if (i == -ENOENT)
4369 				break;
4370 			if (i >= env->prog->len) {
4371 				/* This can happen if backtracking reached insn 0
4372 				 * and there are still reg_mask or stack_mask
4373 				 * to backtrack.
4374 				 * It means the backtracking missed the spot where
4375 				 * particular register was initialized with a constant.
4376 				 */
4377 				verbose(env, "BUG backtracking idx %d\n", i);
4378 				WARN_ONCE(1, "verifier backtracking bug");
4379 				return -EFAULT;
4380 			}
4381 		}
4382 		st = st->parent;
4383 		if (!st)
4384 			break;
4385 
4386 		for (fr = bt->frame; fr >= 0; fr--) {
4387 			func = st->frame[fr];
4388 			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4389 			for_each_set_bit(i, mask, 32) {
4390 				reg = &func->regs[i];
4391 				if (reg->type != SCALAR_VALUE) {
4392 					bt_clear_frame_reg(bt, fr, i);
4393 					continue;
4394 				}
4395 				if (reg->precise)
4396 					bt_clear_frame_reg(bt, fr, i);
4397 				else
4398 					reg->precise = true;
4399 			}
4400 
4401 			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4402 			for_each_set_bit(i, mask, 64) {
4403 				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4404 					/* the sequence of instructions:
4405 					 * 2: (bf) r3 = r10
4406 					 * 3: (7b) *(u64 *)(r3 -8) = r0
4407 					 * 4: (79) r4 = *(u64 *)(r10 -8)
4408 					 * doesn't contain jmps. It's backtracked
4409 					 * as a single block.
4410 					 * During backtracking insn 3 is not recognized as
4411 					 * stack access, so at the end of backtracking
4412 					 * stack slot fp-8 is still marked in stack_mask.
4413 					 * However the parent state may not have accessed
4414 					 * fp-8 and it's "unallocated" stack space.
4415 					 * In such case fallback to conservative.
4416 					 */
4417 					mark_all_scalars_precise(env, env->cur_state);
4418 					bt_reset(bt);
4419 					return 0;
4420 				}
4421 
4422 				if (!is_spilled_scalar_reg(&func->stack[i])) {
4423 					bt_clear_frame_slot(bt, fr, i);
4424 					continue;
4425 				}
4426 				reg = &func->stack[i].spilled_ptr;
4427 				if (reg->precise)
4428 					bt_clear_frame_slot(bt, fr, i);
4429 				else
4430 					reg->precise = true;
4431 			}
4432 			if (env->log.level & BPF_LOG_LEVEL2) {
4433 				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4434 					     bt_frame_reg_mask(bt, fr));
4435 				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4436 					fr, env->tmp_str_buf);
4437 				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4438 					       bt_frame_stack_mask(bt, fr));
4439 				verbose(env, "stack=%s: ", env->tmp_str_buf);
4440 				print_verifier_state(env, func, true);
4441 			}
4442 		}
4443 
4444 		if (bt_empty(bt))
4445 			return 0;
4446 
4447 		subseq_idx = first_idx;
4448 		last_idx = st->last_insn_idx;
4449 		first_idx = st->first_insn_idx;
4450 	}
4451 
4452 	/* if we still have requested precise regs or slots, we missed
4453 	 * something (e.g., stack access through non-r10 register), so
4454 	 * fallback to marking all precise
4455 	 */
4456 	if (!bt_empty(bt)) {
4457 		mark_all_scalars_precise(env, env->cur_state);
4458 		bt_reset(bt);
4459 	}
4460 
4461 	return 0;
4462 }
4463 
mark_chain_precision(struct bpf_verifier_env * env,int regno)4464 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4465 {
4466 	return __mark_chain_precision(env, regno);
4467 }
4468 
4469 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4470  * desired reg and stack masks across all relevant frames
4471  */
mark_chain_precision_batch(struct bpf_verifier_env * env)4472 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4473 {
4474 	return __mark_chain_precision(env, -1);
4475 }
4476 
is_spillable_regtype(enum bpf_reg_type type)4477 static bool is_spillable_regtype(enum bpf_reg_type type)
4478 {
4479 	switch (base_type(type)) {
4480 	case PTR_TO_MAP_VALUE:
4481 	case PTR_TO_STACK:
4482 	case PTR_TO_CTX:
4483 	case PTR_TO_PACKET:
4484 	case PTR_TO_PACKET_META:
4485 	case PTR_TO_PACKET_END:
4486 	case PTR_TO_FLOW_KEYS:
4487 	case CONST_PTR_TO_MAP:
4488 	case PTR_TO_SOCKET:
4489 	case PTR_TO_SOCK_COMMON:
4490 	case PTR_TO_TCP_SOCK:
4491 	case PTR_TO_XDP_SOCK:
4492 	case PTR_TO_BTF_ID:
4493 	case PTR_TO_BUF:
4494 	case PTR_TO_MEM:
4495 	case PTR_TO_FUNC:
4496 	case PTR_TO_MAP_KEY:
4497 		return true;
4498 	default:
4499 		return false;
4500 	}
4501 }
4502 
4503 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4504 static bool register_is_null(struct bpf_reg_state *reg)
4505 {
4506 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4507 }
4508 
register_is_const(struct bpf_reg_state * reg)4509 static bool register_is_const(struct bpf_reg_state *reg)
4510 {
4511 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4512 }
4513 
__is_scalar_unbounded(struct bpf_reg_state * reg)4514 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4515 {
4516 	return tnum_is_unknown(reg->var_off) &&
4517 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4518 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4519 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4520 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4521 }
4522 
register_is_bounded(struct bpf_reg_state * reg)4523 static bool register_is_bounded(struct bpf_reg_state *reg)
4524 {
4525 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4526 }
4527 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)4528 static bool __is_pointer_value(bool allow_ptr_leaks,
4529 			       const struct bpf_reg_state *reg)
4530 {
4531 	if (allow_ptr_leaks)
4532 		return false;
4533 
4534 	return reg->type != SCALAR_VALUE;
4535 }
4536 
4537 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)4538 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4539 {
4540 	struct bpf_reg_state *parent = dst->parent;
4541 	enum bpf_reg_liveness live = dst->live;
4542 
4543 	*dst = *src;
4544 	dst->parent = parent;
4545 	dst->live = live;
4546 }
4547 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)4548 static void save_register_state(struct bpf_func_state *state,
4549 				int spi, struct bpf_reg_state *reg,
4550 				int size)
4551 {
4552 	int i;
4553 
4554 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4555 	if (size == BPF_REG_SIZE)
4556 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4557 
4558 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4559 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4560 
4561 	/* size < 8 bytes spill */
4562 	for (; i; i--)
4563 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4564 }
4565 
is_bpf_st_mem(struct bpf_insn * insn)4566 static bool is_bpf_st_mem(struct bpf_insn *insn)
4567 {
4568 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4569 }
4570 
4571 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4572  * stack boundary and alignment are checked in check_mem_access()
4573  */
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)4574 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4575 				       /* stack frame we're writing to */
4576 				       struct bpf_func_state *state,
4577 				       int off, int size, int value_regno,
4578 				       int insn_idx)
4579 {
4580 	struct bpf_func_state *cur; /* state of the current function */
4581 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4582 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4583 	struct bpf_reg_state *reg = NULL;
4584 	u32 dst_reg = insn->dst_reg;
4585 
4586 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4587 	 * so it's aligned access and [off, off + size) are within stack limits
4588 	 */
4589 	if (!env->allow_ptr_leaks &&
4590 	    is_spilled_reg(&state->stack[spi]) &&
4591 	    !is_spilled_scalar_reg(&state->stack[spi]) &&
4592 	    size != BPF_REG_SIZE) {
4593 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4594 		return -EACCES;
4595 	}
4596 
4597 	cur = env->cur_state->frame[env->cur_state->curframe];
4598 	if (value_regno >= 0)
4599 		reg = &cur->regs[value_regno];
4600 	if (!env->bypass_spec_v4) {
4601 		bool sanitize = reg && is_spillable_regtype(reg->type);
4602 
4603 		for (i = 0; i < size; i++) {
4604 			u8 type = state->stack[spi].slot_type[i];
4605 
4606 			if (type != STACK_MISC && type != STACK_ZERO) {
4607 				sanitize = true;
4608 				break;
4609 			}
4610 		}
4611 
4612 		if (sanitize)
4613 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4614 	}
4615 
4616 	err = destroy_if_dynptr_stack_slot(env, state, spi);
4617 	if (err)
4618 		return err;
4619 
4620 	mark_stack_slot_scratched(env, spi);
4621 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4622 	    !register_is_null(reg) && env->bpf_capable) {
4623 		if (dst_reg != BPF_REG_FP) {
4624 			/* The backtracking logic can only recognize explicit
4625 			 * stack slot address like [fp - 8]. Other spill of
4626 			 * scalar via different register has to be conservative.
4627 			 * Backtrack from here and mark all registers as precise
4628 			 * that contributed into 'reg' being a constant.
4629 			 */
4630 			err = mark_chain_precision(env, value_regno);
4631 			if (err)
4632 				return err;
4633 		}
4634 		save_register_state(state, spi, reg, size);
4635 		/* Break the relation on a narrowing spill. */
4636 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4637 			state->stack[spi].spilled_ptr.id = 0;
4638 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4639 		   insn->imm != 0 && env->bpf_capable) {
4640 		struct bpf_reg_state fake_reg = {};
4641 
4642 		__mark_reg_known(&fake_reg, insn->imm);
4643 		fake_reg.type = SCALAR_VALUE;
4644 		save_register_state(state, spi, &fake_reg, size);
4645 	} else if (reg && is_spillable_regtype(reg->type)) {
4646 		/* register containing pointer is being spilled into stack */
4647 		if (size != BPF_REG_SIZE) {
4648 			verbose_linfo(env, insn_idx, "; ");
4649 			verbose(env, "invalid size of register spill\n");
4650 			return -EACCES;
4651 		}
4652 		if (state != cur && reg->type == PTR_TO_STACK) {
4653 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4654 			return -EINVAL;
4655 		}
4656 		save_register_state(state, spi, reg, size);
4657 	} else {
4658 		u8 type = STACK_MISC;
4659 
4660 		/* regular write of data into stack destroys any spilled ptr */
4661 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4662 		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4663 		if (is_stack_slot_special(&state->stack[spi]))
4664 			for (i = 0; i < BPF_REG_SIZE; i++)
4665 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4666 
4667 		/* only mark the slot as written if all 8 bytes were written
4668 		 * otherwise read propagation may incorrectly stop too soon
4669 		 * when stack slots are partially written.
4670 		 * This heuristic means that read propagation will be
4671 		 * conservative, since it will add reg_live_read marks
4672 		 * to stack slots all the way to first state when programs
4673 		 * writes+reads less than 8 bytes
4674 		 */
4675 		if (size == BPF_REG_SIZE)
4676 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4677 
4678 		/* when we zero initialize stack slots mark them as such */
4679 		if ((reg && register_is_null(reg)) ||
4680 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4681 			/* backtracking doesn't work for STACK_ZERO yet. */
4682 			err = mark_chain_precision(env, value_regno);
4683 			if (err)
4684 				return err;
4685 			type = STACK_ZERO;
4686 		}
4687 
4688 		/* Mark slots affected by this stack write. */
4689 		for (i = 0; i < size; i++)
4690 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4691 				type;
4692 	}
4693 	return 0;
4694 }
4695 
4696 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4697  * known to contain a variable offset.
4698  * This function checks whether the write is permitted and conservatively
4699  * tracks the effects of the write, considering that each stack slot in the
4700  * dynamic range is potentially written to.
4701  *
4702  * 'off' includes 'regno->off'.
4703  * 'value_regno' can be -1, meaning that an unknown value is being written to
4704  * the stack.
4705  *
4706  * Spilled pointers in range are not marked as written because we don't know
4707  * what's going to be actually written. This means that read propagation for
4708  * future reads cannot be terminated by this write.
4709  *
4710  * For privileged programs, uninitialized stack slots are considered
4711  * initialized by this write (even though we don't know exactly what offsets
4712  * are going to be written to). The idea is that we don't want the verifier to
4713  * reject future reads that access slots written to through variable offsets.
4714  */
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)4715 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4716 				     /* func where register points to */
4717 				     struct bpf_func_state *state,
4718 				     int ptr_regno, int off, int size,
4719 				     int value_regno, int insn_idx)
4720 {
4721 	struct bpf_func_state *cur; /* state of the current function */
4722 	int min_off, max_off;
4723 	int i, err;
4724 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4725 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4726 	bool writing_zero = false;
4727 	/* set if the fact that we're writing a zero is used to let any
4728 	 * stack slots remain STACK_ZERO
4729 	 */
4730 	bool zero_used = false;
4731 
4732 	cur = env->cur_state->frame[env->cur_state->curframe];
4733 	ptr_reg = &cur->regs[ptr_regno];
4734 	min_off = ptr_reg->smin_value + off;
4735 	max_off = ptr_reg->smax_value + off + size;
4736 	if (value_regno >= 0)
4737 		value_reg = &cur->regs[value_regno];
4738 	if ((value_reg && register_is_null(value_reg)) ||
4739 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4740 		writing_zero = true;
4741 
4742 	for (i = min_off; i < max_off; i++) {
4743 		int spi;
4744 
4745 		spi = __get_spi(i);
4746 		err = destroy_if_dynptr_stack_slot(env, state, spi);
4747 		if (err)
4748 			return err;
4749 	}
4750 
4751 	/* Variable offset writes destroy any spilled pointers in range. */
4752 	for (i = min_off; i < max_off; i++) {
4753 		u8 new_type, *stype;
4754 		int slot, spi;
4755 
4756 		slot = -i - 1;
4757 		spi = slot / BPF_REG_SIZE;
4758 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4759 		mark_stack_slot_scratched(env, spi);
4760 
4761 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4762 			/* Reject the write if range we may write to has not
4763 			 * been initialized beforehand. If we didn't reject
4764 			 * here, the ptr status would be erased below (even
4765 			 * though not all slots are actually overwritten),
4766 			 * possibly opening the door to leaks.
4767 			 *
4768 			 * We do however catch STACK_INVALID case below, and
4769 			 * only allow reading possibly uninitialized memory
4770 			 * later for CAP_PERFMON, as the write may not happen to
4771 			 * that slot.
4772 			 */
4773 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4774 				insn_idx, i);
4775 			return -EINVAL;
4776 		}
4777 
4778 		/* Erase all spilled pointers. */
4779 		state->stack[spi].spilled_ptr.type = NOT_INIT;
4780 
4781 		/* Update the slot type. */
4782 		new_type = STACK_MISC;
4783 		if (writing_zero && *stype == STACK_ZERO) {
4784 			new_type = STACK_ZERO;
4785 			zero_used = true;
4786 		}
4787 		/* If the slot is STACK_INVALID, we check whether it's OK to
4788 		 * pretend that it will be initialized by this write. The slot
4789 		 * might not actually be written to, and so if we mark it as
4790 		 * initialized future reads might leak uninitialized memory.
4791 		 * For privileged programs, we will accept such reads to slots
4792 		 * that may or may not be written because, if we're reject
4793 		 * them, the error would be too confusing.
4794 		 */
4795 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4796 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4797 					insn_idx, i);
4798 			return -EINVAL;
4799 		}
4800 		*stype = new_type;
4801 	}
4802 	if (zero_used) {
4803 		/* backtracking doesn't work for STACK_ZERO yet. */
4804 		err = mark_chain_precision(env, value_regno);
4805 		if (err)
4806 			return err;
4807 	}
4808 	return 0;
4809 }
4810 
4811 /* When register 'dst_regno' is assigned some values from stack[min_off,
4812  * max_off), we set the register's type according to the types of the
4813  * respective stack slots. If all the stack values are known to be zeros, then
4814  * so is the destination reg. Otherwise, the register is considered to be
4815  * SCALAR. This function does not deal with register filling; the caller must
4816  * ensure that all spilled registers in the stack range have been marked as
4817  * read.
4818  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)4819 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4820 				/* func where src register points to */
4821 				struct bpf_func_state *ptr_state,
4822 				int min_off, int max_off, int dst_regno)
4823 {
4824 	struct bpf_verifier_state *vstate = env->cur_state;
4825 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4826 	int i, slot, spi;
4827 	u8 *stype;
4828 	int zeros = 0;
4829 
4830 	for (i = min_off; i < max_off; i++) {
4831 		slot = -i - 1;
4832 		spi = slot / BPF_REG_SIZE;
4833 		mark_stack_slot_scratched(env, spi);
4834 		stype = ptr_state->stack[spi].slot_type;
4835 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4836 			break;
4837 		zeros++;
4838 	}
4839 	if (zeros == max_off - min_off) {
4840 		/* any access_size read into register is zero extended,
4841 		 * so the whole register == const_zero
4842 		 */
4843 		__mark_reg_const_zero(&state->regs[dst_regno]);
4844 		/* backtracking doesn't support STACK_ZERO yet,
4845 		 * so mark it precise here, so that later
4846 		 * backtracking can stop here.
4847 		 * Backtracking may not need this if this register
4848 		 * doesn't participate in pointer adjustment.
4849 		 * Forward propagation of precise flag is not
4850 		 * necessary either. This mark is only to stop
4851 		 * backtracking. Any register that contributed
4852 		 * to const 0 was marked precise before spill.
4853 		 */
4854 		state->regs[dst_regno].precise = true;
4855 	} else {
4856 		/* have read misc data from the stack */
4857 		mark_reg_unknown(env, state->regs, dst_regno);
4858 	}
4859 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4860 }
4861 
4862 /* Read the stack at 'off' and put the results into the register indicated by
4863  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4864  * spilled reg.
4865  *
4866  * 'dst_regno' can be -1, meaning that the read value is not going to a
4867  * register.
4868  *
4869  * The access is assumed to be within the current stack bounds.
4870  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)4871 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4872 				      /* func where src register points to */
4873 				      struct bpf_func_state *reg_state,
4874 				      int off, int size, int dst_regno)
4875 {
4876 	struct bpf_verifier_state *vstate = env->cur_state;
4877 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4878 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4879 	struct bpf_reg_state *reg;
4880 	u8 *stype, type;
4881 
4882 	stype = reg_state->stack[spi].slot_type;
4883 	reg = &reg_state->stack[spi].spilled_ptr;
4884 
4885 	mark_stack_slot_scratched(env, spi);
4886 
4887 	if (is_spilled_reg(&reg_state->stack[spi])) {
4888 		u8 spill_size = 1;
4889 
4890 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4891 			spill_size++;
4892 
4893 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4894 			if (reg->type != SCALAR_VALUE) {
4895 				verbose_linfo(env, env->insn_idx, "; ");
4896 				verbose(env, "invalid size of register fill\n");
4897 				return -EACCES;
4898 			}
4899 
4900 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4901 			if (dst_regno < 0)
4902 				return 0;
4903 
4904 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4905 				/* The earlier check_reg_arg() has decided the
4906 				 * subreg_def for this insn.  Save it first.
4907 				 */
4908 				s32 subreg_def = state->regs[dst_regno].subreg_def;
4909 
4910 				copy_register_state(&state->regs[dst_regno], reg);
4911 				state->regs[dst_regno].subreg_def = subreg_def;
4912 			} else {
4913 				for (i = 0; i < size; i++) {
4914 					type = stype[(slot - i) % BPF_REG_SIZE];
4915 					if (type == STACK_SPILL)
4916 						continue;
4917 					if (type == STACK_MISC)
4918 						continue;
4919 					if (type == STACK_INVALID && env->allow_uninit_stack)
4920 						continue;
4921 					verbose(env, "invalid read from stack off %d+%d size %d\n",
4922 						off, i, size);
4923 					return -EACCES;
4924 				}
4925 				mark_reg_unknown(env, state->regs, dst_regno);
4926 			}
4927 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4928 			return 0;
4929 		}
4930 
4931 		if (dst_regno >= 0) {
4932 			/* restore register state from stack */
4933 			copy_register_state(&state->regs[dst_regno], reg);
4934 			/* mark reg as written since spilled pointer state likely
4935 			 * has its liveness marks cleared by is_state_visited()
4936 			 * which resets stack/reg liveness for state transitions
4937 			 */
4938 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4939 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4940 			/* If dst_regno==-1, the caller is asking us whether
4941 			 * it is acceptable to use this value as a SCALAR_VALUE
4942 			 * (e.g. for XADD).
4943 			 * We must not allow unprivileged callers to do that
4944 			 * with spilled pointers.
4945 			 */
4946 			verbose(env, "leaking pointer from stack off %d\n",
4947 				off);
4948 			return -EACCES;
4949 		}
4950 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4951 	} else {
4952 		for (i = 0; i < size; i++) {
4953 			type = stype[(slot - i) % BPF_REG_SIZE];
4954 			if (type == STACK_MISC)
4955 				continue;
4956 			if (type == STACK_ZERO)
4957 				continue;
4958 			if (type == STACK_INVALID && env->allow_uninit_stack)
4959 				continue;
4960 			verbose(env, "invalid read from stack off %d+%d size %d\n",
4961 				off, i, size);
4962 			return -EACCES;
4963 		}
4964 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4965 		if (dst_regno >= 0)
4966 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4967 	}
4968 	return 0;
4969 }
4970 
4971 enum bpf_access_src {
4972 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4973 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4974 };
4975 
4976 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4977 					 int regno, int off, int access_size,
4978 					 bool zero_size_allowed,
4979 					 enum bpf_access_src type,
4980 					 struct bpf_call_arg_meta *meta);
4981 
reg_state(struct bpf_verifier_env * env,int regno)4982 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4983 {
4984 	return cur_regs(env) + regno;
4985 }
4986 
4987 /* Read the stack at 'ptr_regno + off' and put the result into the register
4988  * 'dst_regno'.
4989  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4990  * but not its variable offset.
4991  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4992  *
4993  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4994  * filling registers (i.e. reads of spilled register cannot be detected when
4995  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4996  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4997  * offset; for a fixed offset check_stack_read_fixed_off should be used
4998  * instead.
4999  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5000 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5001 				    int ptr_regno, int off, int size, int dst_regno)
5002 {
5003 	/* The state of the source register. */
5004 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5005 	struct bpf_func_state *ptr_state = func(env, reg);
5006 	int err;
5007 	int min_off, max_off;
5008 
5009 	/* Note that we pass a NULL meta, so raw access will not be permitted.
5010 	 */
5011 	err = check_stack_range_initialized(env, ptr_regno, off, size,
5012 					    false, ACCESS_DIRECT, NULL);
5013 	if (err)
5014 		return err;
5015 
5016 	min_off = reg->smin_value + off;
5017 	max_off = reg->smax_value + off;
5018 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5019 	return 0;
5020 }
5021 
5022 /* check_stack_read dispatches to check_stack_read_fixed_off or
5023  * check_stack_read_var_off.
5024  *
5025  * The caller must ensure that the offset falls within the allocated stack
5026  * bounds.
5027  *
5028  * 'dst_regno' is a register which will receive the value from the stack. It
5029  * can be -1, meaning that the read value is not going to a register.
5030  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5031 static int check_stack_read(struct bpf_verifier_env *env,
5032 			    int ptr_regno, int off, int size,
5033 			    int dst_regno)
5034 {
5035 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5036 	struct bpf_func_state *state = func(env, reg);
5037 	int err;
5038 	/* Some accesses are only permitted with a static offset. */
5039 	bool var_off = !tnum_is_const(reg->var_off);
5040 
5041 	/* The offset is required to be static when reads don't go to a
5042 	 * register, in order to not leak pointers (see
5043 	 * check_stack_read_fixed_off).
5044 	 */
5045 	if (dst_regno < 0 && var_off) {
5046 		char tn_buf[48];
5047 
5048 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5049 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5050 			tn_buf, off, size);
5051 		return -EACCES;
5052 	}
5053 	/* Variable offset is prohibited for unprivileged mode for simplicity
5054 	 * since it requires corresponding support in Spectre masking for stack
5055 	 * ALU. See also retrieve_ptr_limit(). The check in
5056 	 * check_stack_access_for_ptr_arithmetic() called by
5057 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5058 	 * with variable offsets, therefore no check is required here. Further,
5059 	 * just checking it here would be insufficient as speculative stack
5060 	 * writes could still lead to unsafe speculative behaviour.
5061 	 */
5062 	if (!var_off) {
5063 		off += reg->var_off.value;
5064 		err = check_stack_read_fixed_off(env, state, off, size,
5065 						 dst_regno);
5066 	} else {
5067 		/* Variable offset stack reads need more conservative handling
5068 		 * than fixed offset ones. Note that dst_regno >= 0 on this
5069 		 * branch.
5070 		 */
5071 		err = check_stack_read_var_off(env, ptr_regno, off, size,
5072 					       dst_regno);
5073 	}
5074 	return err;
5075 }
5076 
5077 
5078 /* check_stack_write dispatches to check_stack_write_fixed_off or
5079  * check_stack_write_var_off.
5080  *
5081  * 'ptr_regno' is the register used as a pointer into the stack.
5082  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5083  * 'value_regno' is the register whose value we're writing to the stack. It can
5084  * be -1, meaning that we're not writing from a register.
5085  *
5086  * The caller must ensure that the offset falls within the maximum stack size.
5087  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5088 static int check_stack_write(struct bpf_verifier_env *env,
5089 			     int ptr_regno, int off, int size,
5090 			     int value_regno, int insn_idx)
5091 {
5092 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5093 	struct bpf_func_state *state = func(env, reg);
5094 	int err;
5095 
5096 	if (tnum_is_const(reg->var_off)) {
5097 		off += reg->var_off.value;
5098 		err = check_stack_write_fixed_off(env, state, off, size,
5099 						  value_regno, insn_idx);
5100 	} else {
5101 		/* Variable offset stack reads need more conservative handling
5102 		 * than fixed offset ones.
5103 		 */
5104 		err = check_stack_write_var_off(env, state,
5105 						ptr_regno, off, size,
5106 						value_regno, insn_idx);
5107 	}
5108 	return err;
5109 }
5110 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5111 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5112 				 int off, int size, enum bpf_access_type type)
5113 {
5114 	struct bpf_reg_state *regs = cur_regs(env);
5115 	struct bpf_map *map = regs[regno].map_ptr;
5116 	u32 cap = bpf_map_flags_to_cap(map);
5117 
5118 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5119 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5120 			map->value_size, off, size);
5121 		return -EACCES;
5122 	}
5123 
5124 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5125 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5126 			map->value_size, off, size);
5127 		return -EACCES;
5128 	}
5129 
5130 	return 0;
5131 }
5132 
5133 /* 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)5134 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5135 			      int off, int size, u32 mem_size,
5136 			      bool zero_size_allowed)
5137 {
5138 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5139 	struct bpf_reg_state *reg;
5140 
5141 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5142 		return 0;
5143 
5144 	reg = &cur_regs(env)[regno];
5145 	switch (reg->type) {
5146 	case PTR_TO_MAP_KEY:
5147 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5148 			mem_size, off, size);
5149 		break;
5150 	case PTR_TO_MAP_VALUE:
5151 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5152 			mem_size, off, size);
5153 		break;
5154 	case PTR_TO_PACKET:
5155 	case PTR_TO_PACKET_META:
5156 	case PTR_TO_PACKET_END:
5157 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5158 			off, size, regno, reg->id, off, mem_size);
5159 		break;
5160 	case PTR_TO_MEM:
5161 	default:
5162 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5163 			mem_size, off, size);
5164 	}
5165 
5166 	return -EACCES;
5167 }
5168 
5169 /* 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)5170 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5171 				   int off, int size, u32 mem_size,
5172 				   bool zero_size_allowed)
5173 {
5174 	struct bpf_verifier_state *vstate = env->cur_state;
5175 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5176 	struct bpf_reg_state *reg = &state->regs[regno];
5177 	int err;
5178 
5179 	/* We may have adjusted the register pointing to memory region, so we
5180 	 * need to try adding each of min_value and max_value to off
5181 	 * to make sure our theoretical access will be safe.
5182 	 *
5183 	 * The minimum value is only important with signed
5184 	 * comparisons where we can't assume the floor of a
5185 	 * value is 0.  If we are using signed variables for our
5186 	 * index'es we need to make sure that whatever we use
5187 	 * will have a set floor within our range.
5188 	 */
5189 	if (reg->smin_value < 0 &&
5190 	    (reg->smin_value == S64_MIN ||
5191 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5192 	      reg->smin_value + off < 0)) {
5193 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5194 			regno);
5195 		return -EACCES;
5196 	}
5197 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5198 				 mem_size, zero_size_allowed);
5199 	if (err) {
5200 		verbose(env, "R%d min value is outside of the allowed memory range\n",
5201 			regno);
5202 		return err;
5203 	}
5204 
5205 	/* If we haven't set a max value then we need to bail since we can't be
5206 	 * sure we won't do bad things.
5207 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5208 	 */
5209 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5210 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5211 			regno);
5212 		return -EACCES;
5213 	}
5214 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5215 				 mem_size, zero_size_allowed);
5216 	if (err) {
5217 		verbose(env, "R%d max value is outside of the allowed memory range\n",
5218 			regno);
5219 		return err;
5220 	}
5221 
5222 	return 0;
5223 }
5224 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5225 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5226 			       const struct bpf_reg_state *reg, int regno,
5227 			       bool fixed_off_ok)
5228 {
5229 	/* Access to this pointer-typed register or passing it to a helper
5230 	 * is only allowed in its original, unmodified form.
5231 	 */
5232 
5233 	if (reg->off < 0) {
5234 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5235 			reg_type_str(env, reg->type), regno, reg->off);
5236 		return -EACCES;
5237 	}
5238 
5239 	if (!fixed_off_ok && reg->off) {
5240 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5241 			reg_type_str(env, reg->type), regno, reg->off);
5242 		return -EACCES;
5243 	}
5244 
5245 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5246 		char tn_buf[48];
5247 
5248 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5249 		verbose(env, "variable %s access var_off=%s disallowed\n",
5250 			reg_type_str(env, reg->type), tn_buf);
5251 		return -EACCES;
5252 	}
5253 
5254 	return 0;
5255 }
5256 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5257 int check_ptr_off_reg(struct bpf_verifier_env *env,
5258 		      const struct bpf_reg_state *reg, int regno)
5259 {
5260 	return __check_ptr_off_reg(env, reg, regno, false);
5261 }
5262 
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5263 static int map_kptr_match_type(struct bpf_verifier_env *env,
5264 			       struct btf_field *kptr_field,
5265 			       struct bpf_reg_state *reg, u32 regno)
5266 {
5267 	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5268 	int perm_flags;
5269 	const char *reg_name = "";
5270 
5271 	if (btf_is_kernel(reg->btf)) {
5272 		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5273 
5274 		/* Only unreferenced case accepts untrusted pointers */
5275 		if (kptr_field->type == BPF_KPTR_UNREF)
5276 			perm_flags |= PTR_UNTRUSTED;
5277 	} else {
5278 		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5279 	}
5280 
5281 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5282 		goto bad_type;
5283 
5284 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5285 	reg_name = btf_type_name(reg->btf, reg->btf_id);
5286 
5287 	/* For ref_ptr case, release function check should ensure we get one
5288 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5289 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5290 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5291 	 * reg->off and reg->ref_obj_id are not needed here.
5292 	 */
5293 	if (__check_ptr_off_reg(env, reg, regno, true))
5294 		return -EACCES;
5295 
5296 	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5297 	 * we also need to take into account the reg->off.
5298 	 *
5299 	 * We want to support cases like:
5300 	 *
5301 	 * struct foo {
5302 	 *         struct bar br;
5303 	 *         struct baz bz;
5304 	 * };
5305 	 *
5306 	 * struct foo *v;
5307 	 * v = func();	      // PTR_TO_BTF_ID
5308 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5309 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5310 	 *                    // first member type of struct after comparison fails
5311 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5312 	 *                    // to match type
5313 	 *
5314 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5315 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5316 	 * the struct to match type against first member of struct, i.e. reject
5317 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5318 	 * strict mode to true for type match.
5319 	 */
5320 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5321 				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5322 				  kptr_field->type == BPF_KPTR_REF))
5323 		goto bad_type;
5324 	return 0;
5325 bad_type:
5326 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5327 		reg_type_str(env, reg->type), reg_name);
5328 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5329 	if (kptr_field->type == BPF_KPTR_UNREF)
5330 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5331 			targ_name);
5332 	else
5333 		verbose(env, "\n");
5334 	return -EINVAL;
5335 }
5336 
5337 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5338  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5339  */
in_rcu_cs(struct bpf_verifier_env * env)5340 static bool in_rcu_cs(struct bpf_verifier_env *env)
5341 {
5342 	return env->cur_state->active_rcu_lock ||
5343 	       env->cur_state->active_lock.ptr ||
5344 	       !env->prog->aux->sleepable;
5345 }
5346 
5347 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5348 BTF_SET_START(rcu_protected_types)
BTF_ID(struct,prog_test_ref_kfunc)5349 BTF_ID(struct, prog_test_ref_kfunc)
5350 BTF_ID(struct, cgroup)
5351 BTF_ID(struct, bpf_cpumask)
5352 BTF_ID(struct, task_struct)
5353 BTF_SET_END(rcu_protected_types)
5354 
5355 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5356 {
5357 	if (!btf_is_kernel(btf))
5358 		return false;
5359 	return btf_id_set_contains(&rcu_protected_types, btf_id);
5360 }
5361 
rcu_safe_kptr(const struct btf_field * field)5362 static bool rcu_safe_kptr(const struct btf_field *field)
5363 {
5364 	const struct btf_field_kptr *kptr = &field->kptr;
5365 
5366 	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5367 }
5368 
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)5369 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5370 				 int value_regno, int insn_idx,
5371 				 struct btf_field *kptr_field)
5372 {
5373 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5374 	int class = BPF_CLASS(insn->code);
5375 	struct bpf_reg_state *val_reg;
5376 
5377 	/* Things we already checked for in check_map_access and caller:
5378 	 *  - Reject cases where variable offset may touch kptr
5379 	 *  - size of access (must be BPF_DW)
5380 	 *  - tnum_is_const(reg->var_off)
5381 	 *  - kptr_field->offset == off + reg->var_off.value
5382 	 */
5383 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5384 	if (BPF_MODE(insn->code) != BPF_MEM) {
5385 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5386 		return -EACCES;
5387 	}
5388 
5389 	/* We only allow loading referenced kptr, since it will be marked as
5390 	 * untrusted, similar to unreferenced kptr.
5391 	 */
5392 	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5393 		verbose(env, "store to referenced kptr disallowed\n");
5394 		return -EACCES;
5395 	}
5396 
5397 	if (class == BPF_LDX) {
5398 		val_reg = reg_state(env, value_regno);
5399 		/* We can simply mark the value_regno receiving the pointer
5400 		 * value from map as PTR_TO_BTF_ID, with the correct type.
5401 		 */
5402 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5403 				kptr_field->kptr.btf_id,
5404 				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5405 				PTR_MAYBE_NULL | MEM_RCU :
5406 				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5407 	} else if (class == BPF_STX) {
5408 		val_reg = reg_state(env, value_regno);
5409 		if (!register_is_null(val_reg) &&
5410 		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5411 			return -EACCES;
5412 	} else if (class == BPF_ST) {
5413 		if (insn->imm) {
5414 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5415 				kptr_field->offset);
5416 			return -EACCES;
5417 		}
5418 	} else {
5419 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5420 		return -EACCES;
5421 	}
5422 	return 0;
5423 }
5424 
5425 /* 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)5426 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5427 			    int off, int size, bool zero_size_allowed,
5428 			    enum bpf_access_src src)
5429 {
5430 	struct bpf_verifier_state *vstate = env->cur_state;
5431 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5432 	struct bpf_reg_state *reg = &state->regs[regno];
5433 	struct bpf_map *map = reg->map_ptr;
5434 	struct btf_record *rec;
5435 	int err, i;
5436 
5437 	err = check_mem_region_access(env, regno, off, size, map->value_size,
5438 				      zero_size_allowed);
5439 	if (err)
5440 		return err;
5441 
5442 	if (IS_ERR_OR_NULL(map->record))
5443 		return 0;
5444 	rec = map->record;
5445 	for (i = 0; i < rec->cnt; i++) {
5446 		struct btf_field *field = &rec->fields[i];
5447 		u32 p = field->offset;
5448 
5449 		/* If any part of a field  can be touched by load/store, reject
5450 		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5451 		 * it is sufficient to check x1 < y2 && y1 < x2.
5452 		 */
5453 		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5454 		    p < reg->umax_value + off + size) {
5455 			switch (field->type) {
5456 			case BPF_KPTR_UNREF:
5457 			case BPF_KPTR_REF:
5458 				if (src != ACCESS_DIRECT) {
5459 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5460 					return -EACCES;
5461 				}
5462 				if (!tnum_is_const(reg->var_off)) {
5463 					verbose(env, "kptr access cannot have variable offset\n");
5464 					return -EACCES;
5465 				}
5466 				if (p != off + reg->var_off.value) {
5467 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5468 						p, off + reg->var_off.value);
5469 					return -EACCES;
5470 				}
5471 				if (size != bpf_size_to_bytes(BPF_DW)) {
5472 					verbose(env, "kptr access size must be BPF_DW\n");
5473 					return -EACCES;
5474 				}
5475 				break;
5476 			default:
5477 				verbose(env, "%s cannot be accessed directly by load/store\n",
5478 					btf_field_type_name(field->type));
5479 				return -EACCES;
5480 			}
5481 		}
5482 	}
5483 	return 0;
5484 }
5485 
5486 #define MAX_PACKET_OFF 0xffff
5487 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)5488 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5489 				       const struct bpf_call_arg_meta *meta,
5490 				       enum bpf_access_type t)
5491 {
5492 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5493 
5494 	switch (prog_type) {
5495 	/* Program types only with direct read access go here! */
5496 	case BPF_PROG_TYPE_LWT_IN:
5497 	case BPF_PROG_TYPE_LWT_OUT:
5498 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5499 	case BPF_PROG_TYPE_SK_REUSEPORT:
5500 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5501 	case BPF_PROG_TYPE_CGROUP_SKB:
5502 		if (t == BPF_WRITE)
5503 			return false;
5504 		fallthrough;
5505 
5506 	/* Program types with direct read + write access go here! */
5507 	case BPF_PROG_TYPE_SCHED_CLS:
5508 	case BPF_PROG_TYPE_SCHED_ACT:
5509 	case BPF_PROG_TYPE_XDP:
5510 	case BPF_PROG_TYPE_LWT_XMIT:
5511 	case BPF_PROG_TYPE_SK_SKB:
5512 	case BPF_PROG_TYPE_SK_MSG:
5513 		if (meta)
5514 			return meta->pkt_access;
5515 
5516 		env->seen_direct_write = true;
5517 		return true;
5518 
5519 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5520 		if (t == BPF_WRITE)
5521 			env->seen_direct_write = true;
5522 
5523 		return true;
5524 
5525 	default:
5526 		return false;
5527 	}
5528 }
5529 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)5530 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5531 			       int size, bool zero_size_allowed)
5532 {
5533 	struct bpf_reg_state *regs = cur_regs(env);
5534 	struct bpf_reg_state *reg = &regs[regno];
5535 	int err;
5536 
5537 	/* We may have added a variable offset to the packet pointer; but any
5538 	 * reg->range we have comes after that.  We are only checking the fixed
5539 	 * offset.
5540 	 */
5541 
5542 	/* We don't allow negative numbers, because we aren't tracking enough
5543 	 * detail to prove they're safe.
5544 	 */
5545 	if (reg->smin_value < 0) {
5546 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5547 			regno);
5548 		return -EACCES;
5549 	}
5550 
5551 	err = reg->range < 0 ? -EINVAL :
5552 	      __check_mem_access(env, regno, off, size, reg->range,
5553 				 zero_size_allowed);
5554 	if (err) {
5555 		verbose(env, "R%d offset is outside of the packet\n", regno);
5556 		return err;
5557 	}
5558 
5559 	/* __check_mem_access has made sure "off + size - 1" is within u16.
5560 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5561 	 * otherwise find_good_pkt_pointers would have refused to set range info
5562 	 * that __check_mem_access would have rejected this pkt access.
5563 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5564 	 */
5565 	env->prog->aux->max_pkt_offset =
5566 		max_t(u32, env->prog->aux->max_pkt_offset,
5567 		      off + reg->umax_value + size - 1);
5568 
5569 	return err;
5570 }
5571 
5572 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,enum bpf_reg_type * reg_type,struct btf ** btf,u32 * btf_id)5573 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5574 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5575 			    struct btf **btf, u32 *btf_id)
5576 {
5577 	struct bpf_insn_access_aux info = {
5578 		.reg_type = *reg_type,
5579 		.log = &env->log,
5580 	};
5581 
5582 	if (env->ops->is_valid_access &&
5583 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5584 		/* A non zero info.ctx_field_size indicates that this field is a
5585 		 * candidate for later verifier transformation to load the whole
5586 		 * field and then apply a mask when accessed with a narrower
5587 		 * access than actual ctx access size. A zero info.ctx_field_size
5588 		 * will only allow for whole field access and rejects any other
5589 		 * type of narrower access.
5590 		 */
5591 		*reg_type = info.reg_type;
5592 
5593 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5594 			*btf = info.btf;
5595 			*btf_id = info.btf_id;
5596 		} else {
5597 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5598 		}
5599 		/* remember the offset of last byte accessed in ctx */
5600 		if (env->prog->aux->max_ctx_offset < off + size)
5601 			env->prog->aux->max_ctx_offset = off + size;
5602 		return 0;
5603 	}
5604 
5605 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5606 	return -EACCES;
5607 }
5608 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)5609 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5610 				  int size)
5611 {
5612 	if (size < 0 || off < 0 ||
5613 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5614 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5615 			off, size);
5616 		return -EACCES;
5617 	}
5618 	return 0;
5619 }
5620 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)5621 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5622 			     u32 regno, int off, int size,
5623 			     enum bpf_access_type t)
5624 {
5625 	struct bpf_reg_state *regs = cur_regs(env);
5626 	struct bpf_reg_state *reg = &regs[regno];
5627 	struct bpf_insn_access_aux info = {};
5628 	bool valid;
5629 
5630 	if (reg->smin_value < 0) {
5631 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5632 			regno);
5633 		return -EACCES;
5634 	}
5635 
5636 	switch (reg->type) {
5637 	case PTR_TO_SOCK_COMMON:
5638 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5639 		break;
5640 	case PTR_TO_SOCKET:
5641 		valid = bpf_sock_is_valid_access(off, size, t, &info);
5642 		break;
5643 	case PTR_TO_TCP_SOCK:
5644 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5645 		break;
5646 	case PTR_TO_XDP_SOCK:
5647 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5648 		break;
5649 	default:
5650 		valid = false;
5651 	}
5652 
5653 
5654 	if (valid) {
5655 		env->insn_aux_data[insn_idx].ctx_field_size =
5656 			info.ctx_field_size;
5657 		return 0;
5658 	}
5659 
5660 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5661 		regno, reg_type_str(env, reg->type), off, size);
5662 
5663 	return -EACCES;
5664 }
5665 
is_pointer_value(struct bpf_verifier_env * env,int regno)5666 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5667 {
5668 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5669 }
5670 
is_ctx_reg(struct bpf_verifier_env * env,int regno)5671 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5672 {
5673 	const struct bpf_reg_state *reg = reg_state(env, regno);
5674 
5675 	return reg->type == PTR_TO_CTX;
5676 }
5677 
is_sk_reg(struct bpf_verifier_env * env,int regno)5678 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5679 {
5680 	const struct bpf_reg_state *reg = reg_state(env, regno);
5681 
5682 	return type_is_sk_pointer(reg->type);
5683 }
5684 
is_pkt_reg(struct bpf_verifier_env * env,int regno)5685 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5686 {
5687 	const struct bpf_reg_state *reg = reg_state(env, regno);
5688 
5689 	return type_is_pkt_pointer(reg->type);
5690 }
5691 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)5692 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5693 {
5694 	const struct bpf_reg_state *reg = reg_state(env, regno);
5695 
5696 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5697 	return reg->type == PTR_TO_FLOW_KEYS;
5698 }
5699 
5700 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5701 #ifdef CONFIG_NET
5702 	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5703 	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5704 	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5705 #endif
5706 	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5707 };
5708 
is_trusted_reg(const struct bpf_reg_state * reg)5709 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5710 {
5711 	/* A referenced register is always trusted. */
5712 	if (reg->ref_obj_id)
5713 		return true;
5714 
5715 	/* Types listed in the reg2btf_ids are always trusted */
5716 	if (reg2btf_ids[base_type(reg->type)] &&
5717 	    !bpf_type_has_unsafe_modifiers(reg->type))
5718 		return true;
5719 
5720 	/* If a register is not referenced, it is trusted if it has the
5721 	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5722 	 * other type modifiers may be safe, but we elect to take an opt-in
5723 	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5724 	 * not.
5725 	 *
5726 	 * Eventually, we should make PTR_TRUSTED the single source of truth
5727 	 * for whether a register is trusted.
5728 	 */
5729 	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5730 	       !bpf_type_has_unsafe_modifiers(reg->type);
5731 }
5732 
is_rcu_reg(const struct bpf_reg_state * reg)5733 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5734 {
5735 	return reg->type & MEM_RCU;
5736 }
5737 
clear_trusted_flags(enum bpf_type_flag * flag)5738 static void clear_trusted_flags(enum bpf_type_flag *flag)
5739 {
5740 	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5741 }
5742 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)5743 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5744 				   const struct bpf_reg_state *reg,
5745 				   int off, int size, bool strict)
5746 {
5747 	struct tnum reg_off;
5748 	int ip_align;
5749 
5750 	/* Byte size accesses are always allowed. */
5751 	if (!strict || size == 1)
5752 		return 0;
5753 
5754 	/* For platforms that do not have a Kconfig enabling
5755 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5756 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5757 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5758 	 * to this code only in strict mode where we want to emulate
5759 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5760 	 * unconditional IP align value of '2'.
5761 	 */
5762 	ip_align = 2;
5763 
5764 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5765 	if (!tnum_is_aligned(reg_off, size)) {
5766 		char tn_buf[48];
5767 
5768 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5769 		verbose(env,
5770 			"misaligned packet access off %d+%s+%d+%d size %d\n",
5771 			ip_align, tn_buf, reg->off, off, size);
5772 		return -EACCES;
5773 	}
5774 
5775 	return 0;
5776 }
5777 
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)5778 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5779 				       const struct bpf_reg_state *reg,
5780 				       const char *pointer_desc,
5781 				       int off, int size, bool strict)
5782 {
5783 	struct tnum reg_off;
5784 
5785 	/* Byte size accesses are always allowed. */
5786 	if (!strict || size == 1)
5787 		return 0;
5788 
5789 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5790 	if (!tnum_is_aligned(reg_off, size)) {
5791 		char tn_buf[48];
5792 
5793 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5794 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5795 			pointer_desc, tn_buf, reg->off, off, size);
5796 		return -EACCES;
5797 	}
5798 
5799 	return 0;
5800 }
5801 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)5802 static int check_ptr_alignment(struct bpf_verifier_env *env,
5803 			       const struct bpf_reg_state *reg, int off,
5804 			       int size, bool strict_alignment_once)
5805 {
5806 	bool strict = env->strict_alignment || strict_alignment_once;
5807 	const char *pointer_desc = "";
5808 
5809 	switch (reg->type) {
5810 	case PTR_TO_PACKET:
5811 	case PTR_TO_PACKET_META:
5812 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5813 		 * right in front, treat it the very same way.
5814 		 */
5815 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5816 	case PTR_TO_FLOW_KEYS:
5817 		pointer_desc = "flow keys ";
5818 		break;
5819 	case PTR_TO_MAP_KEY:
5820 		pointer_desc = "key ";
5821 		break;
5822 	case PTR_TO_MAP_VALUE:
5823 		pointer_desc = "value ";
5824 		break;
5825 	case PTR_TO_CTX:
5826 		pointer_desc = "context ";
5827 		break;
5828 	case PTR_TO_STACK:
5829 		pointer_desc = "stack ";
5830 		/* The stack spill tracking logic in check_stack_write_fixed_off()
5831 		 * and check_stack_read_fixed_off() relies on stack accesses being
5832 		 * aligned.
5833 		 */
5834 		strict = true;
5835 		break;
5836 	case PTR_TO_SOCKET:
5837 		pointer_desc = "sock ";
5838 		break;
5839 	case PTR_TO_SOCK_COMMON:
5840 		pointer_desc = "sock_common ";
5841 		break;
5842 	case PTR_TO_TCP_SOCK:
5843 		pointer_desc = "tcp_sock ";
5844 		break;
5845 	case PTR_TO_XDP_SOCK:
5846 		pointer_desc = "xdp_sock ";
5847 		break;
5848 	default:
5849 		break;
5850 	}
5851 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5852 					   strict);
5853 }
5854 
5855 /* starting from main bpf function walk all instructions of the function
5856  * and recursively walk all callees that given function can call.
5857  * Ignore jump and exit insns.
5858  * Since recursion is prevented by check_cfg() this algorithm
5859  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5860  */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx)5861 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5862 {
5863 	struct bpf_subprog_info *subprog = env->subprog_info;
5864 	struct bpf_insn *insn = env->prog->insnsi;
5865 	int depth = 0, frame = 0, i, subprog_end;
5866 	bool tail_call_reachable = false;
5867 	int ret_insn[MAX_CALL_FRAMES];
5868 	int ret_prog[MAX_CALL_FRAMES];
5869 	int j;
5870 
5871 	i = subprog[idx].start;
5872 process_func:
5873 	/* protect against potential stack overflow that might happen when
5874 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5875 	 * depth for such case down to 256 so that the worst case scenario
5876 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5877 	 * 8k).
5878 	 *
5879 	 * To get the idea what might happen, see an example:
5880 	 * func1 -> sub rsp, 128
5881 	 *  subfunc1 -> sub rsp, 256
5882 	 *  tailcall1 -> add rsp, 256
5883 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5884 	 *   subfunc2 -> sub rsp, 64
5885 	 *   subfunc22 -> sub rsp, 128
5886 	 *   tailcall2 -> add rsp, 128
5887 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5888 	 *
5889 	 * tailcall will unwind the current stack frame but it will not get rid
5890 	 * of caller's stack as shown on the example above.
5891 	 */
5892 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5893 		verbose(env,
5894 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5895 			depth);
5896 		return -EACCES;
5897 	}
5898 	/* round up to 32-bytes, since this is granularity
5899 	 * of interpreter stack size
5900 	 */
5901 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5902 	if (depth > MAX_BPF_STACK) {
5903 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5904 			frame + 1, depth);
5905 		return -EACCES;
5906 	}
5907 continue_func:
5908 	subprog_end = subprog[idx + 1].start;
5909 	for (; i < subprog_end; i++) {
5910 		int next_insn, sidx;
5911 
5912 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5913 			continue;
5914 		/* remember insn and function to return to */
5915 		ret_insn[frame] = i + 1;
5916 		ret_prog[frame] = idx;
5917 
5918 		/* find the callee */
5919 		next_insn = i + insn[i].imm + 1;
5920 		sidx = find_subprog(env, next_insn);
5921 		if (sidx < 0) {
5922 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5923 				  next_insn);
5924 			return -EFAULT;
5925 		}
5926 		if (subprog[sidx].is_async_cb) {
5927 			if (subprog[sidx].has_tail_call) {
5928 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5929 				return -EFAULT;
5930 			}
5931 			/* async callbacks don't increase bpf prog stack size unless called directly */
5932 			if (!bpf_pseudo_call(insn + i))
5933 				continue;
5934 		}
5935 		i = next_insn;
5936 		idx = sidx;
5937 
5938 		if (subprog[idx].has_tail_call)
5939 			tail_call_reachable = true;
5940 
5941 		frame++;
5942 		if (frame >= MAX_CALL_FRAMES) {
5943 			verbose(env, "the call stack of %d frames is too deep !\n",
5944 				frame);
5945 			return -E2BIG;
5946 		}
5947 		goto process_func;
5948 	}
5949 	/* if tail call got detected across bpf2bpf calls then mark each of the
5950 	 * currently present subprog frames as tail call reachable subprogs;
5951 	 * this info will be utilized by JIT so that we will be preserving the
5952 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5953 	 */
5954 	if (tail_call_reachable)
5955 		for (j = 0; j < frame; j++)
5956 			subprog[ret_prog[j]].tail_call_reachable = true;
5957 	if (subprog[0].tail_call_reachable)
5958 		env->prog->aux->tail_call_reachable = true;
5959 
5960 	/* end of for() loop means the last insn of the 'subprog'
5961 	 * was reached. Doesn't matter whether it was JA or EXIT
5962 	 */
5963 	if (frame == 0)
5964 		return 0;
5965 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5966 	frame--;
5967 	i = ret_insn[frame];
5968 	idx = ret_prog[frame];
5969 	goto continue_func;
5970 }
5971 
check_max_stack_depth(struct bpf_verifier_env * env)5972 static int check_max_stack_depth(struct bpf_verifier_env *env)
5973 {
5974 	struct bpf_subprog_info *si = env->subprog_info;
5975 	int ret;
5976 
5977 	for (int i = 0; i < env->subprog_cnt; i++) {
5978 		if (!i || si[i].is_async_cb) {
5979 			ret = check_max_stack_depth_subprog(env, i);
5980 			if (ret < 0)
5981 				return ret;
5982 		}
5983 		continue;
5984 	}
5985 	return 0;
5986 }
5987 
5988 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)5989 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5990 				  const struct bpf_insn *insn, int idx)
5991 {
5992 	int start = idx + insn->imm + 1, subprog;
5993 
5994 	subprog = find_subprog(env, start);
5995 	if (subprog < 0) {
5996 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5997 			  start);
5998 		return -EFAULT;
5999 	}
6000 	return env->subprog_info[subprog].stack_depth;
6001 }
6002 #endif
6003 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)6004 static int __check_buffer_access(struct bpf_verifier_env *env,
6005 				 const char *buf_info,
6006 				 const struct bpf_reg_state *reg,
6007 				 int regno, int off, int size)
6008 {
6009 	if (off < 0) {
6010 		verbose(env,
6011 			"R%d invalid %s buffer access: off=%d, size=%d\n",
6012 			regno, buf_info, off, size);
6013 		return -EACCES;
6014 	}
6015 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6016 		char tn_buf[48];
6017 
6018 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6019 		verbose(env,
6020 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6021 			regno, off, tn_buf);
6022 		return -EACCES;
6023 	}
6024 
6025 	return 0;
6026 }
6027 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)6028 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6029 				  const struct bpf_reg_state *reg,
6030 				  int regno, int off, int size)
6031 {
6032 	int err;
6033 
6034 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6035 	if (err)
6036 		return err;
6037 
6038 	if (off + size > env->prog->aux->max_tp_access)
6039 		env->prog->aux->max_tp_access = off + size;
6040 
6041 	return 0;
6042 }
6043 
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)6044 static int check_buffer_access(struct bpf_verifier_env *env,
6045 			       const struct bpf_reg_state *reg,
6046 			       int regno, int off, int size,
6047 			       bool zero_size_allowed,
6048 			       u32 *max_access)
6049 {
6050 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6051 	int err;
6052 
6053 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6054 	if (err)
6055 		return err;
6056 
6057 	if (off + size > *max_access)
6058 		*max_access = off + size;
6059 
6060 	return 0;
6061 }
6062 
6063 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6064 static void zext_32_to_64(struct bpf_reg_state *reg)
6065 {
6066 	reg->var_off = tnum_subreg(reg->var_off);
6067 	__reg_assign_32_into_64(reg);
6068 }
6069 
6070 /* truncate register to smaller size (in bytes)
6071  * must be called with size < BPF_REG_SIZE
6072  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6073 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6074 {
6075 	u64 mask;
6076 
6077 	/* clear high bits in bit representation */
6078 	reg->var_off = tnum_cast(reg->var_off, size);
6079 
6080 	/* fix arithmetic bounds */
6081 	mask = ((u64)1 << (size * 8)) - 1;
6082 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6083 		reg->umin_value &= mask;
6084 		reg->umax_value &= mask;
6085 	} else {
6086 		reg->umin_value = 0;
6087 		reg->umax_value = mask;
6088 	}
6089 	reg->smin_value = reg->umin_value;
6090 	reg->smax_value = reg->umax_value;
6091 
6092 	/* If size is smaller than 32bit register the 32bit register
6093 	 * values are also truncated so we push 64-bit bounds into
6094 	 * 32-bit bounds. Above were truncated < 32-bits already.
6095 	 */
6096 	if (size >= 4)
6097 		return;
6098 	__reg_combine_64_into_32(reg);
6099 }
6100 
set_sext64_default_val(struct bpf_reg_state * reg,int size)6101 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6102 {
6103 	if (size == 1) {
6104 		reg->smin_value = reg->s32_min_value = S8_MIN;
6105 		reg->smax_value = reg->s32_max_value = S8_MAX;
6106 	} else if (size == 2) {
6107 		reg->smin_value = reg->s32_min_value = S16_MIN;
6108 		reg->smax_value = reg->s32_max_value = S16_MAX;
6109 	} else {
6110 		/* size == 4 */
6111 		reg->smin_value = reg->s32_min_value = S32_MIN;
6112 		reg->smax_value = reg->s32_max_value = S32_MAX;
6113 	}
6114 	reg->umin_value = reg->u32_min_value = 0;
6115 	reg->umax_value = U64_MAX;
6116 	reg->u32_max_value = U32_MAX;
6117 	reg->var_off = tnum_unknown;
6118 }
6119 
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6120 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6121 {
6122 	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6123 	u64 top_smax_value, top_smin_value;
6124 	u64 num_bits = size * 8;
6125 
6126 	if (tnum_is_const(reg->var_off)) {
6127 		u64_cval = reg->var_off.value;
6128 		if (size == 1)
6129 			reg->var_off = tnum_const((s8)u64_cval);
6130 		else if (size == 2)
6131 			reg->var_off = tnum_const((s16)u64_cval);
6132 		else
6133 			/* size == 4 */
6134 			reg->var_off = tnum_const((s32)u64_cval);
6135 
6136 		u64_cval = reg->var_off.value;
6137 		reg->smax_value = reg->smin_value = u64_cval;
6138 		reg->umax_value = reg->umin_value = u64_cval;
6139 		reg->s32_max_value = reg->s32_min_value = u64_cval;
6140 		reg->u32_max_value = reg->u32_min_value = u64_cval;
6141 		return;
6142 	}
6143 
6144 	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6145 	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6146 
6147 	if (top_smax_value != top_smin_value)
6148 		goto out;
6149 
6150 	/* find the s64_min and s64_min after sign extension */
6151 	if (size == 1) {
6152 		init_s64_max = (s8)reg->smax_value;
6153 		init_s64_min = (s8)reg->smin_value;
6154 	} else if (size == 2) {
6155 		init_s64_max = (s16)reg->smax_value;
6156 		init_s64_min = (s16)reg->smin_value;
6157 	} else {
6158 		init_s64_max = (s32)reg->smax_value;
6159 		init_s64_min = (s32)reg->smin_value;
6160 	}
6161 
6162 	s64_max = max(init_s64_max, init_s64_min);
6163 	s64_min = min(init_s64_max, init_s64_min);
6164 
6165 	/* both of s64_max/s64_min positive or negative */
6166 	if ((s64_max >= 0) == (s64_min >= 0)) {
6167 		reg->s32_min_value = reg->smin_value = s64_min;
6168 		reg->s32_max_value = reg->smax_value = s64_max;
6169 		reg->u32_min_value = reg->umin_value = s64_min;
6170 		reg->u32_max_value = reg->umax_value = s64_max;
6171 		reg->var_off = tnum_range(s64_min, s64_max);
6172 		return;
6173 	}
6174 
6175 out:
6176 	set_sext64_default_val(reg, size);
6177 }
6178 
set_sext32_default_val(struct bpf_reg_state * reg,int size)6179 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6180 {
6181 	if (size == 1) {
6182 		reg->s32_min_value = S8_MIN;
6183 		reg->s32_max_value = S8_MAX;
6184 	} else {
6185 		/* size == 2 */
6186 		reg->s32_min_value = S16_MIN;
6187 		reg->s32_max_value = S16_MAX;
6188 	}
6189 	reg->u32_min_value = 0;
6190 	reg->u32_max_value = U32_MAX;
6191 	reg->var_off = tnum_subreg(tnum_unknown);
6192 }
6193 
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6194 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6195 {
6196 	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6197 	u32 top_smax_value, top_smin_value;
6198 	u32 num_bits = size * 8;
6199 
6200 	if (tnum_is_const(reg->var_off)) {
6201 		u32_val = reg->var_off.value;
6202 		if (size == 1)
6203 			reg->var_off = tnum_const((s8)u32_val);
6204 		else
6205 			reg->var_off = tnum_const((s16)u32_val);
6206 
6207 		u32_val = reg->var_off.value;
6208 		reg->s32_min_value = reg->s32_max_value = u32_val;
6209 		reg->u32_min_value = reg->u32_max_value = u32_val;
6210 		return;
6211 	}
6212 
6213 	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6214 	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6215 
6216 	if (top_smax_value != top_smin_value)
6217 		goto out;
6218 
6219 	/* find the s32_min and s32_min after sign extension */
6220 	if (size == 1) {
6221 		init_s32_max = (s8)reg->s32_max_value;
6222 		init_s32_min = (s8)reg->s32_min_value;
6223 	} else {
6224 		/* size == 2 */
6225 		init_s32_max = (s16)reg->s32_max_value;
6226 		init_s32_min = (s16)reg->s32_min_value;
6227 	}
6228 	s32_max = max(init_s32_max, init_s32_min);
6229 	s32_min = min(init_s32_max, init_s32_min);
6230 
6231 	if ((s32_min >= 0) == (s32_max >= 0)) {
6232 		reg->s32_min_value = s32_min;
6233 		reg->s32_max_value = s32_max;
6234 		reg->u32_min_value = (u32)s32_min;
6235 		reg->u32_max_value = (u32)s32_max;
6236 		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6237 		return;
6238 	}
6239 
6240 out:
6241 	set_sext32_default_val(reg, size);
6242 }
6243 
bpf_map_is_rdonly(const struct bpf_map * map)6244 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6245 {
6246 	/* A map is considered read-only if the following condition are true:
6247 	 *
6248 	 * 1) BPF program side cannot change any of the map content. The
6249 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6250 	 *    and was set at map creation time.
6251 	 * 2) The map value(s) have been initialized from user space by a
6252 	 *    loader and then "frozen", such that no new map update/delete
6253 	 *    operations from syscall side are possible for the rest of
6254 	 *    the map's lifetime from that point onwards.
6255 	 * 3) Any parallel/pending map update/delete operations from syscall
6256 	 *    side have been completed. Only after that point, it's safe to
6257 	 *    assume that map value(s) are immutable.
6258 	 */
6259 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6260 	       READ_ONCE(map->frozen) &&
6261 	       !bpf_map_write_active(map);
6262 }
6263 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)6264 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6265 			       bool is_ldsx)
6266 {
6267 	void *ptr;
6268 	u64 addr;
6269 	int err;
6270 
6271 	err = map->ops->map_direct_value_addr(map, &addr, off);
6272 	if (err)
6273 		return err;
6274 	ptr = (void *)(long)addr + off;
6275 
6276 	switch (size) {
6277 	case sizeof(u8):
6278 		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6279 		break;
6280 	case sizeof(u16):
6281 		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6282 		break;
6283 	case sizeof(u32):
6284 		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6285 		break;
6286 	case sizeof(u64):
6287 		*val = *(u64 *)ptr;
6288 		break;
6289 	default:
6290 		return -EINVAL;
6291 	}
6292 	return 0;
6293 }
6294 
6295 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6296 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6297 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6298 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6299 
6300 /*
6301  * Allow list few fields as RCU trusted or full trusted.
6302  * This logic doesn't allow mix tagging and will be removed once GCC supports
6303  * btf_type_tag.
6304  */
6305 
6306 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)6307 BTF_TYPE_SAFE_RCU(struct task_struct) {
6308 	const cpumask_t *cpus_ptr;
6309 	struct css_set __rcu *cgroups;
6310 	struct task_struct __rcu *real_parent;
6311 	struct task_struct *group_leader;
6312 };
6313 
BTF_TYPE_SAFE_RCU(struct cgroup)6314 BTF_TYPE_SAFE_RCU(struct cgroup) {
6315 	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6316 	struct kernfs_node *kn;
6317 };
6318 
BTF_TYPE_SAFE_RCU(struct css_set)6319 BTF_TYPE_SAFE_RCU(struct css_set) {
6320 	struct cgroup *dfl_cgrp;
6321 };
6322 
6323 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)6324 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6325 	struct file __rcu *exe_file;
6326 };
6327 
6328 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6329  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6330  */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)6331 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6332 	struct sock *sk;
6333 };
6334 
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)6335 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6336 	struct sock *sk;
6337 };
6338 
6339 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)6340 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6341 	struct seq_file *seq;
6342 };
6343 
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)6344 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6345 	struct bpf_iter_meta *meta;
6346 	struct task_struct *task;
6347 };
6348 
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)6349 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6350 	struct file *file;
6351 };
6352 
BTF_TYPE_SAFE_TRUSTED(struct file)6353 BTF_TYPE_SAFE_TRUSTED(struct file) {
6354 	struct inode *f_inode;
6355 };
6356 
BTF_TYPE_SAFE_TRUSTED(struct dentry)6357 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6358 	/* no negative dentry-s in places where bpf can see it */
6359 	struct inode *d_inode;
6360 };
6361 
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)6362 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6363 	struct sock *sk;
6364 };
6365 
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6366 static bool type_is_rcu(struct bpf_verifier_env *env,
6367 			struct bpf_reg_state *reg,
6368 			const char *field_name, u32 btf_id)
6369 {
6370 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6371 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6372 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6373 
6374 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6375 }
6376 
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6377 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6378 				struct bpf_reg_state *reg,
6379 				const char *field_name, u32 btf_id)
6380 {
6381 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6382 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6383 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6384 
6385 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6386 }
6387 
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6388 static bool type_is_trusted(struct bpf_verifier_env *env,
6389 			    struct bpf_reg_state *reg,
6390 			    const char *field_name, u32 btf_id)
6391 {
6392 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6393 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6394 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6395 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6396 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6397 
6398 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6399 }
6400 
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6401 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6402 				    struct bpf_reg_state *reg,
6403 				    const char *field_name, u32 btf_id)
6404 {
6405 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6406 
6407 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6408 					  "__safe_trusted_or_null");
6409 }
6410 
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)6411 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6412 				   struct bpf_reg_state *regs,
6413 				   int regno, int off, int size,
6414 				   enum bpf_access_type atype,
6415 				   int value_regno)
6416 {
6417 	struct bpf_reg_state *reg = regs + regno;
6418 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6419 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6420 	const char *field_name = NULL;
6421 	enum bpf_type_flag flag = 0;
6422 	u32 btf_id = 0;
6423 	int ret;
6424 
6425 	if (!env->allow_ptr_leaks) {
6426 		verbose(env,
6427 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6428 			tname);
6429 		return -EPERM;
6430 	}
6431 	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6432 		verbose(env,
6433 			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6434 			tname);
6435 		return -EINVAL;
6436 	}
6437 	if (off < 0) {
6438 		verbose(env,
6439 			"R%d is ptr_%s invalid negative access: off=%d\n",
6440 			regno, tname, off);
6441 		return -EACCES;
6442 	}
6443 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6444 		char tn_buf[48];
6445 
6446 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6447 		verbose(env,
6448 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6449 			regno, tname, off, tn_buf);
6450 		return -EACCES;
6451 	}
6452 
6453 	if (reg->type & MEM_USER) {
6454 		verbose(env,
6455 			"R%d is ptr_%s access user memory: off=%d\n",
6456 			regno, tname, off);
6457 		return -EACCES;
6458 	}
6459 
6460 	if (reg->type & MEM_PERCPU) {
6461 		verbose(env,
6462 			"R%d is ptr_%s access percpu memory: off=%d\n",
6463 			regno, tname, off);
6464 		return -EACCES;
6465 	}
6466 
6467 	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6468 		if (!btf_is_kernel(reg->btf)) {
6469 			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6470 			return -EFAULT;
6471 		}
6472 		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6473 	} else {
6474 		/* Writes are permitted with default btf_struct_access for
6475 		 * program allocated objects (which always have ref_obj_id > 0),
6476 		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6477 		 */
6478 		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6479 			verbose(env, "only read is supported\n");
6480 			return -EACCES;
6481 		}
6482 
6483 		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6484 		    !reg->ref_obj_id) {
6485 			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6486 			return -EFAULT;
6487 		}
6488 
6489 		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6490 	}
6491 
6492 	if (ret < 0)
6493 		return ret;
6494 
6495 	if (ret != PTR_TO_BTF_ID) {
6496 		/* just mark; */
6497 
6498 	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6499 		/* If this is an untrusted pointer, all pointers formed by walking it
6500 		 * also inherit the untrusted flag.
6501 		 */
6502 		flag = PTR_UNTRUSTED;
6503 
6504 	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6505 		/* By default any pointer obtained from walking a trusted pointer is no
6506 		 * longer trusted, unless the field being accessed has explicitly been
6507 		 * marked as inheriting its parent's state of trust (either full or RCU).
6508 		 * For example:
6509 		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6510 		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6511 		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6512 		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6513 		 *
6514 		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6515 		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6516 		 */
6517 		if (type_is_trusted(env, reg, field_name, btf_id)) {
6518 			flag |= PTR_TRUSTED;
6519 		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6520 			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6521 		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6522 			if (type_is_rcu(env, reg, field_name, btf_id)) {
6523 				/* ignore __rcu tag and mark it MEM_RCU */
6524 				flag |= MEM_RCU;
6525 			} else if (flag & MEM_RCU ||
6526 				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6527 				/* __rcu tagged pointers can be NULL */
6528 				flag |= MEM_RCU | PTR_MAYBE_NULL;
6529 
6530 				/* We always trust them */
6531 				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6532 				    flag & PTR_UNTRUSTED)
6533 					flag &= ~PTR_UNTRUSTED;
6534 			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6535 				/* keep as-is */
6536 			} else {
6537 				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6538 				clear_trusted_flags(&flag);
6539 			}
6540 		} else {
6541 			/*
6542 			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6543 			 * aggressively mark as untrusted otherwise such
6544 			 * pointers will be plain PTR_TO_BTF_ID without flags
6545 			 * and will be allowed to be passed into helpers for
6546 			 * compat reasons.
6547 			 */
6548 			flag = PTR_UNTRUSTED;
6549 		}
6550 	} else {
6551 		/* Old compat. Deprecated */
6552 		clear_trusted_flags(&flag);
6553 	}
6554 
6555 	if (atype == BPF_READ && value_regno >= 0)
6556 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6557 
6558 	return 0;
6559 }
6560 
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)6561 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6562 				   struct bpf_reg_state *regs,
6563 				   int regno, int off, int size,
6564 				   enum bpf_access_type atype,
6565 				   int value_regno)
6566 {
6567 	struct bpf_reg_state *reg = regs + regno;
6568 	struct bpf_map *map = reg->map_ptr;
6569 	struct bpf_reg_state map_reg;
6570 	enum bpf_type_flag flag = 0;
6571 	const struct btf_type *t;
6572 	const char *tname;
6573 	u32 btf_id;
6574 	int ret;
6575 
6576 	if (!btf_vmlinux) {
6577 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6578 		return -ENOTSUPP;
6579 	}
6580 
6581 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6582 		verbose(env, "map_ptr access not supported for map type %d\n",
6583 			map->map_type);
6584 		return -ENOTSUPP;
6585 	}
6586 
6587 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6588 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6589 
6590 	if (!env->allow_ptr_leaks) {
6591 		verbose(env,
6592 			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6593 			tname);
6594 		return -EPERM;
6595 	}
6596 
6597 	if (off < 0) {
6598 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6599 			regno, tname, off);
6600 		return -EACCES;
6601 	}
6602 
6603 	if (atype != BPF_READ) {
6604 		verbose(env, "only read from %s is supported\n", tname);
6605 		return -EACCES;
6606 	}
6607 
6608 	/* Simulate access to a PTR_TO_BTF_ID */
6609 	memset(&map_reg, 0, sizeof(map_reg));
6610 	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6611 	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6612 	if (ret < 0)
6613 		return ret;
6614 
6615 	if (value_regno >= 0)
6616 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6617 
6618 	return 0;
6619 }
6620 
6621 /* Check that the stack access at the given offset is within bounds. The
6622  * maximum valid offset is -1.
6623  *
6624  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6625  * -state->allocated_stack for reads.
6626  */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)6627 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6628                                           s64 off,
6629                                           struct bpf_func_state *state,
6630                                           enum bpf_access_type t)
6631 {
6632 	int min_valid_off;
6633 
6634 	if (t == BPF_WRITE || env->allow_uninit_stack)
6635 		min_valid_off = -MAX_BPF_STACK;
6636 	else
6637 		min_valid_off = -state->allocated_stack;
6638 
6639 	if (off < min_valid_off || off > -1)
6640 		return -EACCES;
6641 	return 0;
6642 }
6643 
6644 /* Check that the stack access at 'regno + off' falls within the maximum stack
6645  * bounds.
6646  *
6647  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6648  */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_src src,enum bpf_access_type type)6649 static int check_stack_access_within_bounds(
6650 		struct bpf_verifier_env *env,
6651 		int regno, int off, int access_size,
6652 		enum bpf_access_src src, enum bpf_access_type type)
6653 {
6654 	struct bpf_reg_state *regs = cur_regs(env);
6655 	struct bpf_reg_state *reg = regs + regno;
6656 	struct bpf_func_state *state = func(env, reg);
6657 	s64 min_off, max_off;
6658 	int err;
6659 	char *err_extra;
6660 
6661 	if (src == ACCESS_HELPER)
6662 		/* We don't know if helpers are reading or writing (or both). */
6663 		err_extra = " indirect access to";
6664 	else if (type == BPF_READ)
6665 		err_extra = " read from";
6666 	else
6667 		err_extra = " write to";
6668 
6669 	if (tnum_is_const(reg->var_off)) {
6670 		min_off = (s64)reg->var_off.value + off;
6671 		max_off = min_off + access_size;
6672 	} else {
6673 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6674 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6675 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6676 				err_extra, regno);
6677 			return -EACCES;
6678 		}
6679 		min_off = reg->smin_value + off;
6680 		max_off = reg->smax_value + off + access_size;
6681 	}
6682 
6683 	err = check_stack_slot_within_bounds(env, min_off, state, type);
6684 	if (!err && max_off > 0)
6685 		err = -EINVAL; /* out of stack access into non-negative offsets */
6686 	if (!err && access_size < 0)
6687 		/* access_size should not be negative (or overflow an int); others checks
6688 		 * along the way should have prevented such an access.
6689 		 */
6690 		err = -EFAULT; /* invalid negative access size; integer overflow? */
6691 
6692 	if (err) {
6693 		if (tnum_is_const(reg->var_off)) {
6694 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6695 				err_extra, regno, off, access_size);
6696 		} else {
6697 			char tn_buf[48];
6698 
6699 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6700 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6701 				err_extra, regno, tn_buf, access_size);
6702 		}
6703 		return err;
6704 	}
6705 
6706 	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6707 }
6708 
6709 /* check whether memory at (regno + off) is accessible for t = (read | write)
6710  * if t==write, value_regno is a register which value is stored into memory
6711  * if t==read, value_regno is a register which will receive the value from memory
6712  * if t==write && value_regno==-1, some unknown value is stored into memory
6713  * if t==read && value_regno==-1, don't care what we read from memory
6714  */
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)6715 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6716 			    int off, int bpf_size, enum bpf_access_type t,
6717 			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6718 {
6719 	struct bpf_reg_state *regs = cur_regs(env);
6720 	struct bpf_reg_state *reg = regs + regno;
6721 	int size, err = 0;
6722 
6723 	size = bpf_size_to_bytes(bpf_size);
6724 	if (size < 0)
6725 		return size;
6726 
6727 	/* alignment checks will add in reg->off themselves */
6728 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6729 	if (err)
6730 		return err;
6731 
6732 	/* for access checks, reg->off is just part of off */
6733 	off += reg->off;
6734 
6735 	if (reg->type == PTR_TO_MAP_KEY) {
6736 		if (t == BPF_WRITE) {
6737 			verbose(env, "write to change key R%d not allowed\n", regno);
6738 			return -EACCES;
6739 		}
6740 
6741 		err = check_mem_region_access(env, regno, off, size,
6742 					      reg->map_ptr->key_size, false);
6743 		if (err)
6744 			return err;
6745 		if (value_regno >= 0)
6746 			mark_reg_unknown(env, regs, value_regno);
6747 	} else if (reg->type == PTR_TO_MAP_VALUE) {
6748 		struct btf_field *kptr_field = NULL;
6749 
6750 		if (t == BPF_WRITE && value_regno >= 0 &&
6751 		    is_pointer_value(env, value_regno)) {
6752 			verbose(env, "R%d leaks addr into map\n", value_regno);
6753 			return -EACCES;
6754 		}
6755 		err = check_map_access_type(env, regno, off, size, t);
6756 		if (err)
6757 			return err;
6758 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6759 		if (err)
6760 			return err;
6761 		if (tnum_is_const(reg->var_off))
6762 			kptr_field = btf_record_find(reg->map_ptr->record,
6763 						     off + reg->var_off.value, BPF_KPTR);
6764 		if (kptr_field) {
6765 			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6766 		} else if (t == BPF_READ && value_regno >= 0) {
6767 			struct bpf_map *map = reg->map_ptr;
6768 
6769 			/* if map is read-only, track its contents as scalars */
6770 			if (tnum_is_const(reg->var_off) &&
6771 			    bpf_map_is_rdonly(map) &&
6772 			    map->ops->map_direct_value_addr) {
6773 				int map_off = off + reg->var_off.value;
6774 				u64 val = 0;
6775 
6776 				err = bpf_map_direct_read(map, map_off, size,
6777 							  &val, is_ldsx);
6778 				if (err)
6779 					return err;
6780 
6781 				regs[value_regno].type = SCALAR_VALUE;
6782 				__mark_reg_known(&regs[value_regno], val);
6783 			} else {
6784 				mark_reg_unknown(env, regs, value_regno);
6785 			}
6786 		}
6787 	} else if (base_type(reg->type) == PTR_TO_MEM) {
6788 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6789 
6790 		if (type_may_be_null(reg->type)) {
6791 			verbose(env, "R%d invalid mem access '%s'\n", regno,
6792 				reg_type_str(env, reg->type));
6793 			return -EACCES;
6794 		}
6795 
6796 		if (t == BPF_WRITE && rdonly_mem) {
6797 			verbose(env, "R%d cannot write into %s\n",
6798 				regno, reg_type_str(env, reg->type));
6799 			return -EACCES;
6800 		}
6801 
6802 		if (t == BPF_WRITE && value_regno >= 0 &&
6803 		    is_pointer_value(env, value_regno)) {
6804 			verbose(env, "R%d leaks addr into mem\n", value_regno);
6805 			return -EACCES;
6806 		}
6807 
6808 		err = check_mem_region_access(env, regno, off, size,
6809 					      reg->mem_size, false);
6810 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6811 			mark_reg_unknown(env, regs, value_regno);
6812 	} else if (reg->type == PTR_TO_CTX) {
6813 		enum bpf_reg_type reg_type = SCALAR_VALUE;
6814 		struct btf *btf = NULL;
6815 		u32 btf_id = 0;
6816 
6817 		if (t == BPF_WRITE && value_regno >= 0 &&
6818 		    is_pointer_value(env, value_regno)) {
6819 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6820 			return -EACCES;
6821 		}
6822 
6823 		err = check_ptr_off_reg(env, reg, regno);
6824 		if (err < 0)
6825 			return err;
6826 
6827 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6828 				       &btf_id);
6829 		if (err)
6830 			verbose_linfo(env, insn_idx, "; ");
6831 		if (!err && t == BPF_READ && value_regno >= 0) {
6832 			/* ctx access returns either a scalar, or a
6833 			 * PTR_TO_PACKET[_META,_END]. In the latter
6834 			 * case, we know the offset is zero.
6835 			 */
6836 			if (reg_type == SCALAR_VALUE) {
6837 				mark_reg_unknown(env, regs, value_regno);
6838 			} else {
6839 				mark_reg_known_zero(env, regs,
6840 						    value_regno);
6841 				if (type_may_be_null(reg_type))
6842 					regs[value_regno].id = ++env->id_gen;
6843 				/* A load of ctx field could have different
6844 				 * actual load size with the one encoded in the
6845 				 * insn. When the dst is PTR, it is for sure not
6846 				 * a sub-register.
6847 				 */
6848 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6849 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6850 					regs[value_regno].btf = btf;
6851 					regs[value_regno].btf_id = btf_id;
6852 				}
6853 			}
6854 			regs[value_regno].type = reg_type;
6855 		}
6856 
6857 	} else if (reg->type == PTR_TO_STACK) {
6858 		/* Basic bounds checks. */
6859 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6860 		if (err)
6861 			return err;
6862 
6863 		if (t == BPF_READ)
6864 			err = check_stack_read(env, regno, off, size,
6865 					       value_regno);
6866 		else
6867 			err = check_stack_write(env, regno, off, size,
6868 						value_regno, insn_idx);
6869 	} else if (reg_is_pkt_pointer(reg)) {
6870 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6871 			verbose(env, "cannot write into packet\n");
6872 			return -EACCES;
6873 		}
6874 		if (t == BPF_WRITE && value_regno >= 0 &&
6875 		    is_pointer_value(env, value_regno)) {
6876 			verbose(env, "R%d leaks addr into packet\n",
6877 				value_regno);
6878 			return -EACCES;
6879 		}
6880 		err = check_packet_access(env, regno, off, size, false);
6881 		if (!err && t == BPF_READ && value_regno >= 0)
6882 			mark_reg_unknown(env, regs, value_regno);
6883 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6884 		if (t == BPF_WRITE && value_regno >= 0 &&
6885 		    is_pointer_value(env, value_regno)) {
6886 			verbose(env, "R%d leaks addr into flow keys\n",
6887 				value_regno);
6888 			return -EACCES;
6889 		}
6890 
6891 		err = check_flow_keys_access(env, off, size);
6892 		if (!err && t == BPF_READ && value_regno >= 0)
6893 			mark_reg_unknown(env, regs, value_regno);
6894 	} else if (type_is_sk_pointer(reg->type)) {
6895 		if (t == BPF_WRITE) {
6896 			verbose(env, "R%d cannot write into %s\n",
6897 				regno, reg_type_str(env, reg->type));
6898 			return -EACCES;
6899 		}
6900 		err = check_sock_access(env, insn_idx, regno, off, size, t);
6901 		if (!err && value_regno >= 0)
6902 			mark_reg_unknown(env, regs, value_regno);
6903 	} else if (reg->type == PTR_TO_TP_BUFFER) {
6904 		err = check_tp_buffer_access(env, reg, regno, off, size);
6905 		if (!err && t == BPF_READ && value_regno >= 0)
6906 			mark_reg_unknown(env, regs, value_regno);
6907 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6908 		   !type_may_be_null(reg->type)) {
6909 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6910 					      value_regno);
6911 	} else if (reg->type == CONST_PTR_TO_MAP) {
6912 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6913 					      value_regno);
6914 	} else if (base_type(reg->type) == PTR_TO_BUF) {
6915 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6916 		u32 *max_access;
6917 
6918 		if (rdonly_mem) {
6919 			if (t == BPF_WRITE) {
6920 				verbose(env, "R%d cannot write into %s\n",
6921 					regno, reg_type_str(env, reg->type));
6922 				return -EACCES;
6923 			}
6924 			max_access = &env->prog->aux->max_rdonly_access;
6925 		} else {
6926 			max_access = &env->prog->aux->max_rdwr_access;
6927 		}
6928 
6929 		err = check_buffer_access(env, reg, regno, off, size, false,
6930 					  max_access);
6931 
6932 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6933 			mark_reg_unknown(env, regs, value_regno);
6934 	} else {
6935 		verbose(env, "R%d invalid mem access '%s'\n", regno,
6936 			reg_type_str(env, reg->type));
6937 		return -EACCES;
6938 	}
6939 
6940 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6941 	    regs[value_regno].type == SCALAR_VALUE) {
6942 		if (!is_ldsx)
6943 			/* b/h/w load zero-extends, mark upper bits as known 0 */
6944 			coerce_reg_to_size(&regs[value_regno], size);
6945 		else
6946 			coerce_reg_to_size_sx(&regs[value_regno], size);
6947 	}
6948 	return err;
6949 }
6950 
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)6951 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6952 {
6953 	int load_reg;
6954 	int err;
6955 
6956 	switch (insn->imm) {
6957 	case BPF_ADD:
6958 	case BPF_ADD | BPF_FETCH:
6959 	case BPF_AND:
6960 	case BPF_AND | BPF_FETCH:
6961 	case BPF_OR:
6962 	case BPF_OR | BPF_FETCH:
6963 	case BPF_XOR:
6964 	case BPF_XOR | BPF_FETCH:
6965 	case BPF_XCHG:
6966 	case BPF_CMPXCHG:
6967 		break;
6968 	default:
6969 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6970 		return -EINVAL;
6971 	}
6972 
6973 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6974 		verbose(env, "invalid atomic operand size\n");
6975 		return -EINVAL;
6976 	}
6977 
6978 	/* check src1 operand */
6979 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6980 	if (err)
6981 		return err;
6982 
6983 	/* check src2 operand */
6984 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6985 	if (err)
6986 		return err;
6987 
6988 	if (insn->imm == BPF_CMPXCHG) {
6989 		/* Check comparison of R0 with memory location */
6990 		const u32 aux_reg = BPF_REG_0;
6991 
6992 		err = check_reg_arg(env, aux_reg, SRC_OP);
6993 		if (err)
6994 			return err;
6995 
6996 		if (is_pointer_value(env, aux_reg)) {
6997 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6998 			return -EACCES;
6999 		}
7000 	}
7001 
7002 	if (is_pointer_value(env, insn->src_reg)) {
7003 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7004 		return -EACCES;
7005 	}
7006 
7007 	if (is_ctx_reg(env, insn->dst_reg) ||
7008 	    is_pkt_reg(env, insn->dst_reg) ||
7009 	    is_flow_key_reg(env, insn->dst_reg) ||
7010 	    is_sk_reg(env, insn->dst_reg)) {
7011 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7012 			insn->dst_reg,
7013 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7014 		return -EACCES;
7015 	}
7016 
7017 	if (insn->imm & BPF_FETCH) {
7018 		if (insn->imm == BPF_CMPXCHG)
7019 			load_reg = BPF_REG_0;
7020 		else
7021 			load_reg = insn->src_reg;
7022 
7023 		/* check and record load of old value */
7024 		err = check_reg_arg(env, load_reg, DST_OP);
7025 		if (err)
7026 			return err;
7027 	} else {
7028 		/* This instruction accesses a memory location but doesn't
7029 		 * actually load it into a register.
7030 		 */
7031 		load_reg = -1;
7032 	}
7033 
7034 	/* Check whether we can read the memory, with second call for fetch
7035 	 * case to simulate the register fill.
7036 	 */
7037 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7038 			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7039 	if (!err && load_reg >= 0)
7040 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7041 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7042 				       true, false);
7043 	if (err)
7044 		return err;
7045 
7046 	/* Check whether we can write into the same memory. */
7047 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7048 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7049 	if (err)
7050 		return err;
7051 
7052 	return 0;
7053 }
7054 
7055 /* When register 'regno' is used to read the stack (either directly or through
7056  * a helper function) make sure that it's within stack boundary and, depending
7057  * on the access type and privileges, that all elements of the stack are
7058  * initialized.
7059  *
7060  * 'off' includes 'regno->off', but not its dynamic part (if any).
7061  *
7062  * All registers that have been spilled on the stack in the slots within the
7063  * read offsets are marked as read.
7064  */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum bpf_access_src type,struct bpf_call_arg_meta * meta)7065 static int check_stack_range_initialized(
7066 		struct bpf_verifier_env *env, int regno, int off,
7067 		int access_size, bool zero_size_allowed,
7068 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7069 {
7070 	struct bpf_reg_state *reg = reg_state(env, regno);
7071 	struct bpf_func_state *state = func(env, reg);
7072 	int err, min_off, max_off, i, j, slot, spi;
7073 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7074 	enum bpf_access_type bounds_check_type;
7075 	/* Some accesses can write anything into the stack, others are
7076 	 * read-only.
7077 	 */
7078 	bool clobber = false;
7079 
7080 	if (access_size == 0 && !zero_size_allowed) {
7081 		verbose(env, "invalid zero-sized read\n");
7082 		return -EACCES;
7083 	}
7084 
7085 	if (type == ACCESS_HELPER) {
7086 		/* The bounds checks for writes are more permissive than for
7087 		 * reads. However, if raw_mode is not set, we'll do extra
7088 		 * checks below.
7089 		 */
7090 		bounds_check_type = BPF_WRITE;
7091 		clobber = true;
7092 	} else {
7093 		bounds_check_type = BPF_READ;
7094 	}
7095 	err = check_stack_access_within_bounds(env, regno, off, access_size,
7096 					       type, bounds_check_type);
7097 	if (err)
7098 		return err;
7099 
7100 
7101 	if (tnum_is_const(reg->var_off)) {
7102 		min_off = max_off = reg->var_off.value + off;
7103 	} else {
7104 		/* Variable offset is prohibited for unprivileged mode for
7105 		 * simplicity since it requires corresponding support in
7106 		 * Spectre masking for stack ALU.
7107 		 * See also retrieve_ptr_limit().
7108 		 */
7109 		if (!env->bypass_spec_v1) {
7110 			char tn_buf[48];
7111 
7112 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7113 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7114 				regno, err_extra, tn_buf);
7115 			return -EACCES;
7116 		}
7117 		/* Only initialized buffer on stack is allowed to be accessed
7118 		 * with variable offset. With uninitialized buffer it's hard to
7119 		 * guarantee that whole memory is marked as initialized on
7120 		 * helper return since specific bounds are unknown what may
7121 		 * cause uninitialized stack leaking.
7122 		 */
7123 		if (meta && meta->raw_mode)
7124 			meta = NULL;
7125 
7126 		min_off = reg->smin_value + off;
7127 		max_off = reg->smax_value + off;
7128 	}
7129 
7130 	if (meta && meta->raw_mode) {
7131 		/* Ensure we won't be overwriting dynptrs when simulating byte
7132 		 * by byte access in check_helper_call using meta.access_size.
7133 		 * This would be a problem if we have a helper in the future
7134 		 * which takes:
7135 		 *
7136 		 *	helper(uninit_mem, len, dynptr)
7137 		 *
7138 		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7139 		 * may end up writing to dynptr itself when touching memory from
7140 		 * arg 1. This can be relaxed on a case by case basis for known
7141 		 * safe cases, but reject due to the possibilitiy of aliasing by
7142 		 * default.
7143 		 */
7144 		for (i = min_off; i < max_off + access_size; i++) {
7145 			int stack_off = -i - 1;
7146 
7147 			spi = __get_spi(i);
7148 			/* raw_mode may write past allocated_stack */
7149 			if (state->allocated_stack <= stack_off)
7150 				continue;
7151 			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7152 				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7153 				return -EACCES;
7154 			}
7155 		}
7156 		meta->access_size = access_size;
7157 		meta->regno = regno;
7158 		return 0;
7159 	}
7160 
7161 	for (i = min_off; i < max_off + access_size; i++) {
7162 		u8 *stype;
7163 
7164 		slot = -i - 1;
7165 		spi = slot / BPF_REG_SIZE;
7166 		if (state->allocated_stack <= slot) {
7167 			verbose(env, "verifier bug: allocated_stack too small");
7168 			return -EFAULT;
7169 		}
7170 
7171 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7172 		if (*stype == STACK_MISC)
7173 			goto mark;
7174 		if ((*stype == STACK_ZERO) ||
7175 		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7176 			if (clobber) {
7177 				/* helper can write anything into the stack */
7178 				*stype = STACK_MISC;
7179 			}
7180 			goto mark;
7181 		}
7182 
7183 		if (is_spilled_reg(&state->stack[spi]) &&
7184 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7185 		     env->allow_ptr_leaks)) {
7186 			if (clobber) {
7187 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7188 				for (j = 0; j < BPF_REG_SIZE; j++)
7189 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7190 			}
7191 			goto mark;
7192 		}
7193 
7194 		if (tnum_is_const(reg->var_off)) {
7195 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7196 				err_extra, regno, min_off, i - min_off, access_size);
7197 		} else {
7198 			char tn_buf[48];
7199 
7200 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7201 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7202 				err_extra, regno, tn_buf, i - min_off, access_size);
7203 		}
7204 		return -EACCES;
7205 mark:
7206 		/* reading any byte out of 8-byte 'spill_slot' will cause
7207 		 * the whole slot to be marked as 'read'
7208 		 */
7209 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7210 			      state->stack[spi].spilled_ptr.parent,
7211 			      REG_LIVE_READ64);
7212 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7213 		 * be sure that whether stack slot is written to or not. Hence,
7214 		 * we must still conservatively propagate reads upwards even if
7215 		 * helper may write to the entire memory range.
7216 		 */
7217 	}
7218 	return 0;
7219 }
7220 
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)7221 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7222 				   int access_size, enum bpf_access_type access_type,
7223 				   bool zero_size_allowed,
7224 				   struct bpf_call_arg_meta *meta)
7225 {
7226 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7227 	u32 *max_access;
7228 
7229 	switch (base_type(reg->type)) {
7230 	case PTR_TO_PACKET:
7231 	case PTR_TO_PACKET_META:
7232 		return check_packet_access(env, regno, reg->off, access_size,
7233 					   zero_size_allowed);
7234 	case PTR_TO_MAP_KEY:
7235 		if (access_type == BPF_WRITE) {
7236 			verbose(env, "R%d cannot write into %s\n", regno,
7237 				reg_type_str(env, reg->type));
7238 			return -EACCES;
7239 		}
7240 		return check_mem_region_access(env, regno, reg->off, access_size,
7241 					       reg->map_ptr->key_size, false);
7242 	case PTR_TO_MAP_VALUE:
7243 		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
7244 			return -EACCES;
7245 		return check_map_access(env, regno, reg->off, access_size,
7246 					zero_size_allowed, ACCESS_HELPER);
7247 	case PTR_TO_MEM:
7248 		if (type_is_rdonly_mem(reg->type)) {
7249 			if (access_type == BPF_WRITE) {
7250 				verbose(env, "R%d cannot write into %s\n", regno,
7251 					reg_type_str(env, reg->type));
7252 				return -EACCES;
7253 			}
7254 		}
7255 		return check_mem_region_access(env, regno, reg->off,
7256 					       access_size, reg->mem_size,
7257 					       zero_size_allowed);
7258 	case PTR_TO_BUF:
7259 		if (type_is_rdonly_mem(reg->type)) {
7260 			if (access_type == BPF_WRITE) {
7261 				verbose(env, "R%d cannot write into %s\n", regno,
7262 					reg_type_str(env, reg->type));
7263 				return -EACCES;
7264 			}
7265 
7266 			max_access = &env->prog->aux->max_rdonly_access;
7267 		} else {
7268 			max_access = &env->prog->aux->max_rdwr_access;
7269 		}
7270 		return check_buffer_access(env, reg, regno, reg->off,
7271 					   access_size, zero_size_allowed,
7272 					   max_access);
7273 	case PTR_TO_STACK:
7274 		return check_stack_range_initialized(
7275 				env,
7276 				regno, reg->off, access_size,
7277 				zero_size_allowed, ACCESS_HELPER, meta);
7278 	case PTR_TO_BTF_ID:
7279 		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7280 					       access_size, BPF_READ, -1);
7281 	case PTR_TO_CTX:
7282 		/* in case the function doesn't know how to access the context,
7283 		 * (because we are in a program of type SYSCALL for example), we
7284 		 * can not statically check its size.
7285 		 * Dynamically check it now.
7286 		 */
7287 		if (!env->ops->convert_ctx_access) {
7288 			int offset = access_size - 1;
7289 
7290 			/* Allow zero-byte read from PTR_TO_CTX */
7291 			if (access_size == 0)
7292 				return zero_size_allowed ? 0 : -EACCES;
7293 
7294 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7295 						access_type, -1, false, false);
7296 		}
7297 
7298 		fallthrough;
7299 	default: /* scalar_value or invalid ptr */
7300 		/* Allow zero-byte read from NULL, regardless of pointer type */
7301 		if (zero_size_allowed && access_size == 0 &&
7302 		    register_is_null(reg))
7303 			return 0;
7304 
7305 		verbose(env, "R%d type=%s ", regno,
7306 			reg_type_str(env, reg->type));
7307 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7308 		return -EACCES;
7309 	}
7310 }
7311 
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)7312 static int check_mem_size_reg(struct bpf_verifier_env *env,
7313 			      struct bpf_reg_state *reg, u32 regno,
7314 			      enum bpf_access_type access_type,
7315 			      bool zero_size_allowed,
7316 			      struct bpf_call_arg_meta *meta)
7317 {
7318 	int err;
7319 
7320 	/* This is used to refine r0 return value bounds for helpers
7321 	 * that enforce this value as an upper bound on return values.
7322 	 * See do_refine_retval_range() for helpers that can refine
7323 	 * the return value. C type of helper is u32 so we pull register
7324 	 * bound from umax_value however, if negative verifier errors
7325 	 * out. Only upper bounds can be learned because retval is an
7326 	 * int type and negative retvals are allowed.
7327 	 */
7328 	meta->msize_max_value = reg->umax_value;
7329 
7330 	/* The register is SCALAR_VALUE; the access check happens using
7331 	 * its boundaries. For unprivileged variable accesses, disable
7332 	 * raw mode so that the program is required to initialize all
7333 	 * the memory that the helper could just partially fill up.
7334 	 */
7335 	if (!tnum_is_const(reg->var_off))
7336 		meta = NULL;
7337 
7338 	if (reg->smin_value < 0) {
7339 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7340 			regno);
7341 		return -EACCES;
7342 	}
7343 
7344 	if (reg->umin_value == 0 && !zero_size_allowed) {
7345 		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7346 			regno, reg->umin_value, reg->umax_value);
7347 		return -EACCES;
7348 	}
7349 
7350 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7351 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7352 			regno);
7353 		return -EACCES;
7354 	}
7355 	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
7356 				      access_type, zero_size_allowed, meta);
7357 	if (!err)
7358 		err = mark_chain_precision(env, regno);
7359 	return err;
7360 }
7361 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)7362 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7363 		   u32 regno, u32 mem_size)
7364 {
7365 	bool may_be_null = type_may_be_null(reg->type);
7366 	struct bpf_reg_state saved_reg;
7367 	int err;
7368 
7369 	if (register_is_null(reg))
7370 		return 0;
7371 
7372 	/* Assuming that the register contains a value check if the memory
7373 	 * access is safe. Temporarily save and restore the register's state as
7374 	 * the conversion shouldn't be visible to a caller.
7375 	 */
7376 	if (may_be_null) {
7377 		saved_reg = *reg;
7378 		mark_ptr_not_null_reg(reg);
7379 	}
7380 
7381 	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
7382 	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
7383 
7384 	if (may_be_null)
7385 		*reg = saved_reg;
7386 
7387 	return err;
7388 }
7389 
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)7390 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7391 				    u32 regno)
7392 {
7393 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7394 	bool may_be_null = type_may_be_null(mem_reg->type);
7395 	struct bpf_reg_state saved_reg;
7396 	struct bpf_call_arg_meta meta;
7397 	int err;
7398 
7399 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7400 
7401 	memset(&meta, 0, sizeof(meta));
7402 
7403 	if (may_be_null) {
7404 		saved_reg = *mem_reg;
7405 		mark_ptr_not_null_reg(mem_reg);
7406 	}
7407 
7408 	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
7409 	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
7410 
7411 	if (may_be_null)
7412 		*mem_reg = saved_reg;
7413 
7414 	return err;
7415 }
7416 
7417 /* Implementation details:
7418  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7419  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7420  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7421  * Two separate bpf_obj_new will also have different reg->id.
7422  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7423  * clears reg->id after value_or_null->value transition, since the verifier only
7424  * cares about the range of access to valid map value pointer and doesn't care
7425  * about actual address of the map element.
7426  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7427  * reg->id > 0 after value_or_null->value transition. By doing so
7428  * two bpf_map_lookups will be considered two different pointers that
7429  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7430  * returned from bpf_obj_new.
7431  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7432  * dead-locks.
7433  * Since only one bpf_spin_lock is allowed the checks are simpler than
7434  * reg_is_refcounted() logic. The verifier needs to remember only
7435  * one spin_lock instead of array of acquired_refs.
7436  * cur_state->active_lock remembers which map value element or allocated
7437  * object got locked and clears it after bpf_spin_unlock.
7438  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)7439 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7440 			     bool is_lock)
7441 {
7442 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7443 	struct bpf_verifier_state *cur = env->cur_state;
7444 	bool is_const = tnum_is_const(reg->var_off);
7445 	u64 val = reg->var_off.value;
7446 	struct bpf_map *map = NULL;
7447 	struct btf *btf = NULL;
7448 	struct btf_record *rec;
7449 
7450 	if (!is_const) {
7451 		verbose(env,
7452 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7453 			regno);
7454 		return -EINVAL;
7455 	}
7456 	if (reg->type == PTR_TO_MAP_VALUE) {
7457 		map = reg->map_ptr;
7458 		if (!map->btf) {
7459 			verbose(env,
7460 				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7461 				map->name);
7462 			return -EINVAL;
7463 		}
7464 	} else {
7465 		btf = reg->btf;
7466 	}
7467 
7468 	rec = reg_btf_record(reg);
7469 	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7470 		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7471 			map ? map->name : "kptr");
7472 		return -EINVAL;
7473 	}
7474 	if (rec->spin_lock_off != val + reg->off) {
7475 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7476 			val + reg->off, rec->spin_lock_off);
7477 		return -EINVAL;
7478 	}
7479 	if (is_lock) {
7480 		if (cur->active_lock.ptr) {
7481 			verbose(env,
7482 				"Locking two bpf_spin_locks are not allowed\n");
7483 			return -EINVAL;
7484 		}
7485 		if (map)
7486 			cur->active_lock.ptr = map;
7487 		else
7488 			cur->active_lock.ptr = btf;
7489 		cur->active_lock.id = reg->id;
7490 	} else {
7491 		void *ptr;
7492 
7493 		if (map)
7494 			ptr = map;
7495 		else
7496 			ptr = btf;
7497 
7498 		if (!cur->active_lock.ptr) {
7499 			verbose(env, "bpf_spin_unlock without taking a lock\n");
7500 			return -EINVAL;
7501 		}
7502 		if (cur->active_lock.ptr != ptr ||
7503 		    cur->active_lock.id != reg->id) {
7504 			verbose(env, "bpf_spin_unlock of different lock\n");
7505 			return -EINVAL;
7506 		}
7507 
7508 		invalidate_non_owning_refs(env);
7509 
7510 		cur->active_lock.ptr = NULL;
7511 		cur->active_lock.id = 0;
7512 	}
7513 	return 0;
7514 }
7515 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7516 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7517 			      struct bpf_call_arg_meta *meta)
7518 {
7519 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7520 	bool is_const = tnum_is_const(reg->var_off);
7521 	struct bpf_map *map = reg->map_ptr;
7522 	u64 val = reg->var_off.value;
7523 
7524 	if (!is_const) {
7525 		verbose(env,
7526 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7527 			regno);
7528 		return -EINVAL;
7529 	}
7530 	if (!map->btf) {
7531 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7532 			map->name);
7533 		return -EINVAL;
7534 	}
7535 	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7536 		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7537 		return -EINVAL;
7538 	}
7539 	if (map->record->timer_off != val + reg->off) {
7540 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7541 			val + reg->off, map->record->timer_off);
7542 		return -EINVAL;
7543 	}
7544 	if (meta->map_ptr) {
7545 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7546 		return -EFAULT;
7547 	}
7548 	meta->map_uid = reg->map_uid;
7549 	meta->map_ptr = map;
7550 	return 0;
7551 }
7552 
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7553 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7554 			     struct bpf_call_arg_meta *meta)
7555 {
7556 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7557 	struct bpf_map *map_ptr = reg->map_ptr;
7558 	struct btf_field *kptr_field;
7559 	u32 kptr_off;
7560 
7561 	if (!tnum_is_const(reg->var_off)) {
7562 		verbose(env,
7563 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7564 			regno);
7565 		return -EINVAL;
7566 	}
7567 	if (!map_ptr->btf) {
7568 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7569 			map_ptr->name);
7570 		return -EINVAL;
7571 	}
7572 	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7573 		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7574 		return -EINVAL;
7575 	}
7576 
7577 	meta->map_ptr = map_ptr;
7578 	kptr_off = reg->off + reg->var_off.value;
7579 	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7580 	if (!kptr_field) {
7581 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7582 		return -EACCES;
7583 	}
7584 	if (kptr_field->type != BPF_KPTR_REF) {
7585 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7586 		return -EACCES;
7587 	}
7588 	meta->kptr_field = kptr_field;
7589 	return 0;
7590 }
7591 
7592 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7593  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7594  *
7595  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7596  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7597  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7598  *
7599  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7600  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7601  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7602  * mutate the view of the dynptr and also possibly destroy it. In the latter
7603  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7604  * memory that dynptr points to.
7605  *
7606  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7607  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7608  * readonly dynptr view yet, hence only the first case is tracked and checked.
7609  *
7610  * This is consistent with how C applies the const modifier to a struct object,
7611  * where the pointer itself inside bpf_dynptr becomes const but not what it
7612  * points to.
7613  *
7614  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7615  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7616  */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)7617 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7618 			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7619 {
7620 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7621 	int err;
7622 
7623 	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7624 	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7625 	 */
7626 	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7627 		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7628 		return -EFAULT;
7629 	}
7630 
7631 	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7632 	 *		 constructing a mutable bpf_dynptr object.
7633 	 *
7634 	 *		 Currently, this is only possible with PTR_TO_STACK
7635 	 *		 pointing to a region of at least 16 bytes which doesn't
7636 	 *		 contain an existing bpf_dynptr.
7637 	 *
7638 	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7639 	 *		 mutated or destroyed. However, the memory it points to
7640 	 *		 may be mutated.
7641 	 *
7642 	 *  None       - Points to a initialized dynptr that can be mutated and
7643 	 *		 destroyed, including mutation of the memory it points
7644 	 *		 to.
7645 	 */
7646 	if (arg_type & MEM_UNINIT) {
7647 		int i;
7648 
7649 		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7650 			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7651 			return -EINVAL;
7652 		}
7653 
7654 		/* we write BPF_DW bits (8 bytes) at a time */
7655 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7656 			err = check_mem_access(env, insn_idx, regno,
7657 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7658 			if (err)
7659 				return err;
7660 		}
7661 
7662 		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7663 	} else /* MEM_RDONLY and None case from above */ {
7664 		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7665 		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7666 			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7667 			return -EINVAL;
7668 		}
7669 
7670 		if (!is_dynptr_reg_valid_init(env, reg)) {
7671 			verbose(env,
7672 				"Expected an initialized dynptr as arg #%d\n",
7673 				regno);
7674 			return -EINVAL;
7675 		}
7676 
7677 		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7678 		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7679 			verbose(env,
7680 				"Expected a dynptr of type %s as arg #%d\n",
7681 				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7682 			return -EINVAL;
7683 		}
7684 
7685 		err = mark_dynptr_read(env, reg);
7686 	}
7687 	return err;
7688 }
7689 
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)7690 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7691 {
7692 	struct bpf_func_state *state = func(env, reg);
7693 
7694 	return state->stack[spi].spilled_ptr.ref_obj_id;
7695 }
7696 
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)7697 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7698 {
7699 	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7700 }
7701 
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)7702 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7703 {
7704 	return meta->kfunc_flags & KF_ITER_NEW;
7705 }
7706 
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)7707 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7708 {
7709 	return meta->kfunc_flags & KF_ITER_NEXT;
7710 }
7711 
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)7712 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7713 {
7714 	return meta->kfunc_flags & KF_ITER_DESTROY;
7715 }
7716 
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg)7717 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7718 {
7719 	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7720 	 * kfunc is iter state pointer
7721 	 */
7722 	return arg == 0 && is_iter_kfunc(meta);
7723 }
7724 
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7725 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7726 			    struct bpf_kfunc_call_arg_meta *meta)
7727 {
7728 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7729 	const struct btf_type *t;
7730 	const struct btf_param *arg;
7731 	int spi, err, i, nr_slots;
7732 	u32 btf_id;
7733 
7734 	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7735 	arg = &btf_params(meta->func_proto)[0];
7736 	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7737 	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7738 	nr_slots = t->size / BPF_REG_SIZE;
7739 
7740 	if (is_iter_new_kfunc(meta)) {
7741 		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7742 		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7743 			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7744 				iter_type_str(meta->btf, btf_id), regno);
7745 			return -EINVAL;
7746 		}
7747 
7748 		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7749 			err = check_mem_access(env, insn_idx, regno,
7750 					       i, BPF_DW, BPF_WRITE, -1, false, false);
7751 			if (err)
7752 				return err;
7753 		}
7754 
7755 		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7756 		if (err)
7757 			return err;
7758 	} else {
7759 		/* iter_next() or iter_destroy() expect initialized iter state*/
7760 		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7761 			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7762 				iter_type_str(meta->btf, btf_id), regno);
7763 			return -EINVAL;
7764 		}
7765 
7766 		spi = iter_get_spi(env, reg, nr_slots);
7767 		if (spi < 0)
7768 			return spi;
7769 
7770 		err = mark_iter_read(env, reg, spi, nr_slots);
7771 		if (err)
7772 			return err;
7773 
7774 		/* remember meta->iter info for process_iter_next_call() */
7775 		meta->iter.spi = spi;
7776 		meta->iter.frameno = reg->frameno;
7777 		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7778 
7779 		if (is_iter_destroy_kfunc(meta)) {
7780 			err = unmark_stack_slots_iter(env, reg, nr_slots);
7781 			if (err)
7782 				return err;
7783 		}
7784 	}
7785 
7786 	return 0;
7787 }
7788 
7789 /* Look for a previous loop entry at insn_idx: nearest parent state
7790  * stopped at insn_idx with callsites matching those in cur->frame.
7791  */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)7792 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7793 						  struct bpf_verifier_state *cur,
7794 						  int insn_idx)
7795 {
7796 	struct bpf_verifier_state_list *sl;
7797 	struct bpf_verifier_state *st;
7798 
7799 	/* Explored states are pushed in stack order, most recent states come first */
7800 	sl = *explored_state(env, insn_idx);
7801 	for (; sl; sl = sl->next) {
7802 		/* If st->branches != 0 state is a part of current DFS verification path,
7803 		 * hence cur & st for a loop.
7804 		 */
7805 		st = &sl->state;
7806 		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7807 		    st->dfs_depth < cur->dfs_depth)
7808 			return st;
7809 	}
7810 
7811 	return NULL;
7812 }
7813 
7814 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7815 static bool regs_exact(const struct bpf_reg_state *rold,
7816 		       const struct bpf_reg_state *rcur,
7817 		       struct bpf_idmap *idmap);
7818 
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)7819 static void maybe_widen_reg(struct bpf_verifier_env *env,
7820 			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7821 			    struct bpf_idmap *idmap)
7822 {
7823 	if (rold->type != SCALAR_VALUE)
7824 		return;
7825 	if (rold->type != rcur->type)
7826 		return;
7827 	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7828 		return;
7829 	__mark_reg_unknown(env, rcur);
7830 }
7831 
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)7832 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7833 				   struct bpf_verifier_state *old,
7834 				   struct bpf_verifier_state *cur)
7835 {
7836 	struct bpf_func_state *fold, *fcur;
7837 	int i, fr;
7838 
7839 	reset_idmap_scratch(env);
7840 	for (fr = old->curframe; fr >= 0; fr--) {
7841 		fold = old->frame[fr];
7842 		fcur = cur->frame[fr];
7843 
7844 		for (i = 0; i < MAX_BPF_REG; i++)
7845 			maybe_widen_reg(env,
7846 					&fold->regs[i],
7847 					&fcur->regs[i],
7848 					&env->idmap_scratch);
7849 
7850 		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7851 			if (!is_spilled_reg(&fold->stack[i]) ||
7852 			    !is_spilled_reg(&fcur->stack[i]))
7853 				continue;
7854 
7855 			maybe_widen_reg(env,
7856 					&fold->stack[i].spilled_ptr,
7857 					&fcur->stack[i].spilled_ptr,
7858 					&env->idmap_scratch);
7859 		}
7860 	}
7861 	return 0;
7862 }
7863 
get_iter_from_state(struct bpf_verifier_state * cur_st,struct bpf_kfunc_call_arg_meta * meta)7864 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7865 						 struct bpf_kfunc_call_arg_meta *meta)
7866 {
7867 	int iter_frameno = meta->iter.frameno;
7868 	int iter_spi = meta->iter.spi;
7869 
7870 	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7871 }
7872 
7873 /* process_iter_next_call() is called when verifier gets to iterator's next
7874  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7875  * to it as just "iter_next()" in comments below.
7876  *
7877  * BPF verifier relies on a crucial contract for any iter_next()
7878  * implementation: it should *eventually* return NULL, and once that happens
7879  * it should keep returning NULL. That is, once iterator exhausts elements to
7880  * iterate, it should never reset or spuriously return new elements.
7881  *
7882  * With the assumption of such contract, process_iter_next_call() simulates
7883  * a fork in the verifier state to validate loop logic correctness and safety
7884  * without having to simulate infinite amount of iterations.
7885  *
7886  * In current state, we first assume that iter_next() returned NULL and
7887  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7888  * conditions we should not form an infinite loop and should eventually reach
7889  * exit.
7890  *
7891  * Besides that, we also fork current state and enqueue it for later
7892  * verification. In a forked state we keep iterator state as ACTIVE
7893  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7894  * also bump iteration depth to prevent erroneous infinite loop detection
7895  * later on (see iter_active_depths_differ() comment for details). In this
7896  * state we assume that we'll eventually loop back to another iter_next()
7897  * calls (it could be in exactly same location or in some other instruction,
7898  * it doesn't matter, we don't make any unnecessary assumptions about this,
7899  * everything revolves around iterator state in a stack slot, not which
7900  * instruction is calling iter_next()). When that happens, we either will come
7901  * to iter_next() with equivalent state and can conclude that next iteration
7902  * will proceed in exactly the same way as we just verified, so it's safe to
7903  * assume that loop converges. If not, we'll go on another iteration
7904  * simulation with a different input state, until all possible starting states
7905  * are validated or we reach maximum number of instructions limit.
7906  *
7907  * This way, we will either exhaustively discover all possible input states
7908  * that iterator loop can start with and eventually will converge, or we'll
7909  * effectively regress into bounded loop simulation logic and either reach
7910  * maximum number of instructions if loop is not provably convergent, or there
7911  * is some statically known limit on number of iterations (e.g., if there is
7912  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7913  *
7914  * Iteration convergence logic in is_state_visited() relies on exact
7915  * states comparison, which ignores read and precision marks.
7916  * This is necessary because read and precision marks are not finalized
7917  * while in the loop. Exact comparison might preclude convergence for
7918  * simple programs like below:
7919  *
7920  *     i = 0;
7921  *     while(iter_next(&it))
7922  *       i++;
7923  *
7924  * At each iteration step i++ would produce a new distinct state and
7925  * eventually instruction processing limit would be reached.
7926  *
7927  * To avoid such behavior speculatively forget (widen) range for
7928  * imprecise scalar registers, if those registers were not precise at the
7929  * end of the previous iteration and do not match exactly.
7930  *
7931  * This is a conservative heuristic that allows to verify wide range of programs,
7932  * however it precludes verification of programs that conjure an
7933  * imprecise value on the first loop iteration and use it as precise on a second.
7934  * For example, the following safe program would fail to verify:
7935  *
7936  *     struct bpf_num_iter it;
7937  *     int arr[10];
7938  *     int i = 0, a = 0;
7939  *     bpf_iter_num_new(&it, 0, 10);
7940  *     while (bpf_iter_num_next(&it)) {
7941  *       if (a == 0) {
7942  *         a = 1;
7943  *         i = 7; // Because i changed verifier would forget
7944  *                // it's range on second loop entry.
7945  *       } else {
7946  *         arr[i] = 42; // This would fail to verify.
7947  *       }
7948  *     }
7949  *     bpf_iter_num_destroy(&it);
7950  */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7951 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7952 				  struct bpf_kfunc_call_arg_meta *meta)
7953 {
7954 	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7955 	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7956 	struct bpf_reg_state *cur_iter, *queued_iter;
7957 
7958 	BTF_TYPE_EMIT(struct bpf_iter);
7959 
7960 	cur_iter = get_iter_from_state(cur_st, meta);
7961 
7962 	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7963 	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7964 		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7965 			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7966 		return -EFAULT;
7967 	}
7968 
7969 	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7970 		/* Because iter_next() call is a checkpoint is_state_visitied()
7971 		 * should guarantee parent state with same call sites and insn_idx.
7972 		 */
7973 		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7974 		    !same_callsites(cur_st->parent, cur_st)) {
7975 			verbose(env, "bug: bad parent state for iter next call");
7976 			return -EFAULT;
7977 		}
7978 		/* Note cur_st->parent in the call below, it is necessary to skip
7979 		 * checkpoint created for cur_st by is_state_visited()
7980 		 * right at this instruction.
7981 		 */
7982 		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7983 		/* branch out active iter state */
7984 		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7985 		if (!queued_st)
7986 			return -ENOMEM;
7987 
7988 		queued_iter = get_iter_from_state(queued_st, meta);
7989 		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7990 		queued_iter->iter.depth++;
7991 		if (prev_st)
7992 			widen_imprecise_scalars(env, prev_st, queued_st);
7993 
7994 		queued_fr = queued_st->frame[queued_st->curframe];
7995 		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7996 	}
7997 
7998 	/* switch to DRAINED state, but keep the depth unchanged */
7999 	/* mark current iter state as drained and assume returned NULL */
8000 	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8001 	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
8002 
8003 	return 0;
8004 }
8005 
arg_type_is_mem_size(enum bpf_arg_type type)8006 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8007 {
8008 	return type == ARG_CONST_SIZE ||
8009 	       type == ARG_CONST_SIZE_OR_ZERO;
8010 }
8011 
arg_type_is_raw_mem(enum bpf_arg_type type)8012 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
8013 {
8014 	return base_type(type) == ARG_PTR_TO_MEM &&
8015 	       type & MEM_UNINIT;
8016 }
8017 
arg_type_is_release(enum bpf_arg_type type)8018 static bool arg_type_is_release(enum bpf_arg_type type)
8019 {
8020 	return type & OBJ_RELEASE;
8021 }
8022 
arg_type_is_dynptr(enum bpf_arg_type type)8023 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8024 {
8025 	return base_type(type) == ARG_PTR_TO_DYNPTR;
8026 }
8027 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)8028 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8029 				 const struct bpf_call_arg_meta *meta,
8030 				 enum bpf_arg_type *arg_type)
8031 {
8032 	if (!meta->map_ptr) {
8033 		/* kernel subsystem misconfigured verifier */
8034 		verbose(env, "invalid map_ptr to access map->type\n");
8035 		return -EACCES;
8036 	}
8037 
8038 	switch (meta->map_ptr->map_type) {
8039 	case BPF_MAP_TYPE_SOCKMAP:
8040 	case BPF_MAP_TYPE_SOCKHASH:
8041 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8042 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8043 		} else {
8044 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8045 			return -EINVAL;
8046 		}
8047 		break;
8048 	case BPF_MAP_TYPE_BLOOM_FILTER:
8049 		if (meta->func_id == BPF_FUNC_map_peek_elem)
8050 			*arg_type = ARG_PTR_TO_MAP_VALUE;
8051 		break;
8052 	default:
8053 		break;
8054 	}
8055 	return 0;
8056 }
8057 
8058 struct bpf_reg_types {
8059 	const enum bpf_reg_type types[10];
8060 	u32 *btf_id;
8061 };
8062 
8063 static const struct bpf_reg_types sock_types = {
8064 	.types = {
8065 		PTR_TO_SOCK_COMMON,
8066 		PTR_TO_SOCKET,
8067 		PTR_TO_TCP_SOCK,
8068 		PTR_TO_XDP_SOCK,
8069 	},
8070 };
8071 
8072 #ifdef CONFIG_NET
8073 static const struct bpf_reg_types btf_id_sock_common_types = {
8074 	.types = {
8075 		PTR_TO_SOCK_COMMON,
8076 		PTR_TO_SOCKET,
8077 		PTR_TO_TCP_SOCK,
8078 		PTR_TO_XDP_SOCK,
8079 		PTR_TO_BTF_ID,
8080 		PTR_TO_BTF_ID | PTR_TRUSTED,
8081 	},
8082 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8083 };
8084 #endif
8085 
8086 static const struct bpf_reg_types mem_types = {
8087 	.types = {
8088 		PTR_TO_STACK,
8089 		PTR_TO_PACKET,
8090 		PTR_TO_PACKET_META,
8091 		PTR_TO_MAP_KEY,
8092 		PTR_TO_MAP_VALUE,
8093 		PTR_TO_MEM,
8094 		PTR_TO_MEM | MEM_RINGBUF,
8095 		PTR_TO_BUF,
8096 		PTR_TO_BTF_ID | PTR_TRUSTED,
8097 	},
8098 };
8099 
8100 static const struct bpf_reg_types spin_lock_types = {
8101 	.types = {
8102 		PTR_TO_MAP_VALUE,
8103 		PTR_TO_BTF_ID | MEM_ALLOC,
8104 	}
8105 };
8106 
8107 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8108 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8109 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8110 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8111 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8112 static const struct bpf_reg_types btf_ptr_types = {
8113 	.types = {
8114 		PTR_TO_BTF_ID,
8115 		PTR_TO_BTF_ID | PTR_TRUSTED,
8116 		PTR_TO_BTF_ID | MEM_RCU,
8117 	},
8118 };
8119 static const struct bpf_reg_types percpu_btf_ptr_types = {
8120 	.types = {
8121 		PTR_TO_BTF_ID | MEM_PERCPU,
8122 		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8123 	}
8124 };
8125 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8126 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8127 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8128 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8129 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8130 static const struct bpf_reg_types dynptr_types = {
8131 	.types = {
8132 		PTR_TO_STACK,
8133 		CONST_PTR_TO_DYNPTR,
8134 	}
8135 };
8136 
8137 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8138 	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8139 	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8140 	[ARG_CONST_SIZE]		= &scalar_types,
8141 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8142 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8143 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8144 	[ARG_PTR_TO_CTX]		= &context_types,
8145 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8146 #ifdef CONFIG_NET
8147 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8148 #endif
8149 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8150 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8151 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8152 	[ARG_PTR_TO_MEM]		= &mem_types,
8153 	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8154 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8155 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8156 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8157 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8158 	[ARG_PTR_TO_TIMER]		= &timer_types,
8159 	[ARG_PTR_TO_KPTR]		= &kptr_types,
8160 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8161 };
8162 
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)8163 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8164 			  enum bpf_arg_type arg_type,
8165 			  const u32 *arg_btf_id,
8166 			  struct bpf_call_arg_meta *meta)
8167 {
8168 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8169 	enum bpf_reg_type expected, type = reg->type;
8170 	const struct bpf_reg_types *compatible;
8171 	int i, j;
8172 
8173 	compatible = compatible_reg_types[base_type(arg_type)];
8174 	if (!compatible) {
8175 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8176 		return -EFAULT;
8177 	}
8178 
8179 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8180 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8181 	 *
8182 	 * Same for MAYBE_NULL:
8183 	 *
8184 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8185 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8186 	 *
8187 	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8188 	 *
8189 	 * Therefore we fold these flags depending on the arg_type before comparison.
8190 	 */
8191 	if (arg_type & MEM_RDONLY)
8192 		type &= ~MEM_RDONLY;
8193 	if (arg_type & PTR_MAYBE_NULL)
8194 		type &= ~PTR_MAYBE_NULL;
8195 	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8196 		type &= ~DYNPTR_TYPE_FLAG_MASK;
8197 
8198 	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8199 		type &= ~MEM_ALLOC;
8200 
8201 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8202 		expected = compatible->types[i];
8203 		if (expected == NOT_INIT)
8204 			break;
8205 
8206 		if (type == expected)
8207 			goto found;
8208 	}
8209 
8210 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8211 	for (j = 0; j + 1 < i; j++)
8212 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8213 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8214 	return -EACCES;
8215 
8216 found:
8217 	if (base_type(reg->type) != PTR_TO_BTF_ID)
8218 		return 0;
8219 
8220 	if (compatible == &mem_types) {
8221 		if (!(arg_type & MEM_RDONLY)) {
8222 			verbose(env,
8223 				"%s() may write into memory pointed by R%d type=%s\n",
8224 				func_id_name(meta->func_id),
8225 				regno, reg_type_str(env, reg->type));
8226 			return -EACCES;
8227 		}
8228 		return 0;
8229 	}
8230 
8231 	switch ((int)reg->type) {
8232 	case PTR_TO_BTF_ID:
8233 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8234 	case PTR_TO_BTF_ID | MEM_RCU:
8235 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8236 	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8237 	{
8238 		/* For bpf_sk_release, it needs to match against first member
8239 		 * 'struct sock_common', hence make an exception for it. This
8240 		 * allows bpf_sk_release to work for multiple socket types.
8241 		 */
8242 		bool strict_type_match = arg_type_is_release(arg_type) &&
8243 					 meta->func_id != BPF_FUNC_sk_release;
8244 
8245 		if (type_may_be_null(reg->type) &&
8246 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8247 			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8248 			return -EACCES;
8249 		}
8250 
8251 		if (!arg_btf_id) {
8252 			if (!compatible->btf_id) {
8253 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8254 				return -EFAULT;
8255 			}
8256 			arg_btf_id = compatible->btf_id;
8257 		}
8258 
8259 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8260 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8261 				return -EACCES;
8262 		} else {
8263 			if (arg_btf_id == BPF_PTR_POISON) {
8264 				verbose(env, "verifier internal error:");
8265 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8266 					regno);
8267 				return -EACCES;
8268 			}
8269 
8270 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8271 						  btf_vmlinux, *arg_btf_id,
8272 						  strict_type_match)) {
8273 				verbose(env, "R%d is of type %s but %s is expected\n",
8274 					regno, btf_type_name(reg->btf, reg->btf_id),
8275 					btf_type_name(btf_vmlinux, *arg_btf_id));
8276 				return -EACCES;
8277 			}
8278 		}
8279 		break;
8280 	}
8281 	case PTR_TO_BTF_ID | MEM_ALLOC:
8282 		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8283 		    meta->func_id != BPF_FUNC_kptr_xchg) {
8284 			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8285 			return -EFAULT;
8286 		}
8287 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8288 			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8289 				return -EACCES;
8290 		}
8291 		break;
8292 	case PTR_TO_BTF_ID | MEM_PERCPU:
8293 	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8294 		/* Handled by helper specific checks */
8295 		break;
8296 	default:
8297 		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8298 		return -EFAULT;
8299 	}
8300 	return 0;
8301 }
8302 
8303 static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)8304 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8305 {
8306 	struct btf_field *field;
8307 	struct btf_record *rec;
8308 
8309 	rec = reg_btf_record(reg);
8310 	if (!rec)
8311 		return NULL;
8312 
8313 	field = btf_record_find(rec, off, fields);
8314 	if (!field)
8315 		return NULL;
8316 
8317 	return field;
8318 }
8319 
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)8320 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8321 			   const struct bpf_reg_state *reg, int regno,
8322 			   enum bpf_arg_type arg_type)
8323 {
8324 	u32 type = reg->type;
8325 
8326 	/* When referenced register is passed to release function, its fixed
8327 	 * offset must be 0.
8328 	 *
8329 	 * We will check arg_type_is_release reg has ref_obj_id when storing
8330 	 * meta->release_regno.
8331 	 */
8332 	if (arg_type_is_release(arg_type)) {
8333 		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8334 		 * may not directly point to the object being released, but to
8335 		 * dynptr pointing to such object, which might be at some offset
8336 		 * on the stack. In that case, we simply to fallback to the
8337 		 * default handling.
8338 		 */
8339 		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8340 			return 0;
8341 
8342 		/* Doing check_ptr_off_reg check for the offset will catch this
8343 		 * because fixed_off_ok is false, but checking here allows us
8344 		 * to give the user a better error message.
8345 		 */
8346 		if (reg->off) {
8347 			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8348 				regno);
8349 			return -EINVAL;
8350 		}
8351 		return __check_ptr_off_reg(env, reg, regno, false);
8352 	}
8353 
8354 	switch (type) {
8355 	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8356 	case PTR_TO_STACK:
8357 	case PTR_TO_PACKET:
8358 	case PTR_TO_PACKET_META:
8359 	case PTR_TO_MAP_KEY:
8360 	case PTR_TO_MAP_VALUE:
8361 	case PTR_TO_MEM:
8362 	case PTR_TO_MEM | MEM_RDONLY:
8363 	case PTR_TO_MEM | MEM_RINGBUF:
8364 	case PTR_TO_BUF:
8365 	case PTR_TO_BUF | MEM_RDONLY:
8366 	case SCALAR_VALUE:
8367 		return 0;
8368 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8369 	 * fixed offset.
8370 	 */
8371 	case PTR_TO_BTF_ID:
8372 	case PTR_TO_BTF_ID | MEM_ALLOC:
8373 	case PTR_TO_BTF_ID | PTR_TRUSTED:
8374 	case PTR_TO_BTF_ID | MEM_RCU:
8375 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8376 	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8377 		/* When referenced PTR_TO_BTF_ID is passed to release function,
8378 		 * its fixed offset must be 0. In the other cases, fixed offset
8379 		 * can be non-zero. This was already checked above. So pass
8380 		 * fixed_off_ok as true to allow fixed offset for all other
8381 		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8382 		 * still need to do checks instead of returning.
8383 		 */
8384 		return __check_ptr_off_reg(env, reg, regno, true);
8385 	default:
8386 		return __check_ptr_off_reg(env, reg, regno, false);
8387 	}
8388 }
8389 
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)8390 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8391 						const struct bpf_func_proto *fn,
8392 						struct bpf_reg_state *regs)
8393 {
8394 	struct bpf_reg_state *state = NULL;
8395 	int i;
8396 
8397 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8398 		if (arg_type_is_dynptr(fn->arg_type[i])) {
8399 			if (state) {
8400 				verbose(env, "verifier internal error: multiple dynptr args\n");
8401 				return NULL;
8402 			}
8403 			state = &regs[BPF_REG_1 + i];
8404 		}
8405 
8406 	if (!state)
8407 		verbose(env, "verifier internal error: no dynptr arg found\n");
8408 
8409 	return state;
8410 }
8411 
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8412 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8413 {
8414 	struct bpf_func_state *state = func(env, reg);
8415 	int spi;
8416 
8417 	if (reg->type == CONST_PTR_TO_DYNPTR)
8418 		return reg->id;
8419 	spi = dynptr_get_spi(env, reg);
8420 	if (spi < 0)
8421 		return spi;
8422 	return state->stack[spi].spilled_ptr.id;
8423 }
8424 
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8425 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8426 {
8427 	struct bpf_func_state *state = func(env, reg);
8428 	int spi;
8429 
8430 	if (reg->type == CONST_PTR_TO_DYNPTR)
8431 		return reg->ref_obj_id;
8432 	spi = dynptr_get_spi(env, reg);
8433 	if (spi < 0)
8434 		return spi;
8435 	return state->stack[spi].spilled_ptr.ref_obj_id;
8436 }
8437 
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8438 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8439 					    struct bpf_reg_state *reg)
8440 {
8441 	struct bpf_func_state *state = func(env, reg);
8442 	int spi;
8443 
8444 	if (reg->type == CONST_PTR_TO_DYNPTR)
8445 		return reg->dynptr.type;
8446 
8447 	spi = __get_spi(reg->off);
8448 	if (spi < 0) {
8449 		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8450 		return BPF_DYNPTR_TYPE_INVALID;
8451 	}
8452 
8453 	return state->stack[spi].spilled_ptr.dynptr.type;
8454 }
8455 
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)8456 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8457 			  struct bpf_call_arg_meta *meta,
8458 			  const struct bpf_func_proto *fn,
8459 			  int insn_idx)
8460 {
8461 	u32 regno = BPF_REG_1 + arg;
8462 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8463 	enum bpf_arg_type arg_type = fn->arg_type[arg];
8464 	enum bpf_reg_type type = reg->type;
8465 	u32 *arg_btf_id = NULL;
8466 	int err = 0;
8467 
8468 	if (arg_type == ARG_DONTCARE)
8469 		return 0;
8470 
8471 	err = check_reg_arg(env, regno, SRC_OP);
8472 	if (err)
8473 		return err;
8474 
8475 	if (arg_type == ARG_ANYTHING) {
8476 		if (is_pointer_value(env, regno)) {
8477 			verbose(env, "R%d leaks addr into helper function\n",
8478 				regno);
8479 			return -EACCES;
8480 		}
8481 		return 0;
8482 	}
8483 
8484 	if (type_is_pkt_pointer(type) &&
8485 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8486 		verbose(env, "helper access to the packet is not allowed\n");
8487 		return -EACCES;
8488 	}
8489 
8490 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8491 		err = resolve_map_arg_type(env, meta, &arg_type);
8492 		if (err)
8493 			return err;
8494 	}
8495 
8496 	if (register_is_null(reg) && type_may_be_null(arg_type))
8497 		/* A NULL register has a SCALAR_VALUE type, so skip
8498 		 * type checking.
8499 		 */
8500 		goto skip_type_check;
8501 
8502 	/* arg_btf_id and arg_size are in a union. */
8503 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8504 	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8505 		arg_btf_id = fn->arg_btf_id[arg];
8506 
8507 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8508 	if (err)
8509 		return err;
8510 
8511 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8512 	if (err)
8513 		return err;
8514 
8515 skip_type_check:
8516 	if (arg_type_is_release(arg_type)) {
8517 		if (arg_type_is_dynptr(arg_type)) {
8518 			struct bpf_func_state *state = func(env, reg);
8519 			int spi;
8520 
8521 			/* Only dynptr created on stack can be released, thus
8522 			 * the get_spi and stack state checks for spilled_ptr
8523 			 * should only be done before process_dynptr_func for
8524 			 * PTR_TO_STACK.
8525 			 */
8526 			if (reg->type == PTR_TO_STACK) {
8527 				spi = dynptr_get_spi(env, reg);
8528 				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8529 					verbose(env, "arg %d is an unacquired reference\n", regno);
8530 					return -EINVAL;
8531 				}
8532 			} else {
8533 				verbose(env, "cannot release unowned const bpf_dynptr\n");
8534 				return -EINVAL;
8535 			}
8536 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8537 			verbose(env, "R%d must be referenced when passed to release function\n",
8538 				regno);
8539 			return -EINVAL;
8540 		}
8541 		if (meta->release_regno) {
8542 			verbose(env, "verifier internal error: more than one release argument\n");
8543 			return -EFAULT;
8544 		}
8545 		meta->release_regno = regno;
8546 	}
8547 
8548 	if (reg->ref_obj_id) {
8549 		if (meta->ref_obj_id) {
8550 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8551 				regno, reg->ref_obj_id,
8552 				meta->ref_obj_id);
8553 			return -EFAULT;
8554 		}
8555 		meta->ref_obj_id = reg->ref_obj_id;
8556 	}
8557 
8558 	switch (base_type(arg_type)) {
8559 	case ARG_CONST_MAP_PTR:
8560 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8561 		if (meta->map_ptr) {
8562 			/* Use map_uid (which is unique id of inner map) to reject:
8563 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8564 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8565 			 * if (inner_map1 && inner_map2) {
8566 			 *     timer = bpf_map_lookup_elem(inner_map1);
8567 			 *     if (timer)
8568 			 *         // mismatch would have been allowed
8569 			 *         bpf_timer_init(timer, inner_map2);
8570 			 * }
8571 			 *
8572 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8573 			 */
8574 			if (meta->map_ptr != reg->map_ptr ||
8575 			    meta->map_uid != reg->map_uid) {
8576 				verbose(env,
8577 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8578 					meta->map_uid, reg->map_uid);
8579 				return -EINVAL;
8580 			}
8581 		}
8582 		meta->map_ptr = reg->map_ptr;
8583 		meta->map_uid = reg->map_uid;
8584 		break;
8585 	case ARG_PTR_TO_MAP_KEY:
8586 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8587 		 * check that [key, key + map->key_size) are within
8588 		 * stack limits and initialized
8589 		 */
8590 		if (!meta->map_ptr) {
8591 			/* in function declaration map_ptr must come before
8592 			 * map_key, so that it's verified and known before
8593 			 * we have to check map_key here. Otherwise it means
8594 			 * that kernel subsystem misconfigured verifier
8595 			 */
8596 			verbose(env, "invalid map_ptr to access map->key\n");
8597 			return -EACCES;
8598 		}
8599 		err = check_helper_mem_access(env, regno, meta->map_ptr->key_size,
8600 					      BPF_READ, false, NULL);
8601 		break;
8602 	case ARG_PTR_TO_MAP_VALUE:
8603 		if (type_may_be_null(arg_type) && register_is_null(reg))
8604 			return 0;
8605 
8606 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8607 		 * check [value, value + map->value_size) validity
8608 		 */
8609 		if (!meta->map_ptr) {
8610 			/* kernel subsystem misconfigured verifier */
8611 			verbose(env, "invalid map_ptr to access map->value\n");
8612 			return -EACCES;
8613 		}
8614 		meta->raw_mode = arg_type & MEM_UNINIT;
8615 		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
8616 					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8617 					      false, meta);
8618 		break;
8619 	case ARG_PTR_TO_PERCPU_BTF_ID:
8620 		if (!reg->btf_id) {
8621 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8622 			return -EACCES;
8623 		}
8624 		meta->ret_btf = reg->btf;
8625 		meta->ret_btf_id = reg->btf_id;
8626 		break;
8627 	case ARG_PTR_TO_SPIN_LOCK:
8628 		if (in_rbtree_lock_required_cb(env)) {
8629 			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8630 			return -EACCES;
8631 		}
8632 		if (meta->func_id == BPF_FUNC_spin_lock) {
8633 			err = process_spin_lock(env, regno, true);
8634 			if (err)
8635 				return err;
8636 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8637 			err = process_spin_lock(env, regno, false);
8638 			if (err)
8639 				return err;
8640 		} else {
8641 			verbose(env, "verifier internal error\n");
8642 			return -EFAULT;
8643 		}
8644 		break;
8645 	case ARG_PTR_TO_TIMER:
8646 		err = process_timer_func(env, regno, meta);
8647 		if (err)
8648 			return err;
8649 		break;
8650 	case ARG_PTR_TO_FUNC:
8651 		meta->subprogno = reg->subprogno;
8652 		break;
8653 	case ARG_PTR_TO_MEM:
8654 		/* The access to this pointer is only checked when we hit the
8655 		 * next is_mem_size argument below.
8656 		 */
8657 		meta->raw_mode = arg_type & MEM_UNINIT;
8658 		if (arg_type & MEM_FIXED_SIZE) {
8659 			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
8660 						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8661 						      false, meta);
8662 			if (err)
8663 				return err;
8664 			if (arg_type & MEM_ALIGNED)
8665 				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8666 		}
8667 		break;
8668 	case ARG_CONST_SIZE:
8669 		err = check_mem_size_reg(env, reg, regno,
8670 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8671 					 BPF_WRITE : BPF_READ,
8672 					 false, meta);
8673 		break;
8674 	case ARG_CONST_SIZE_OR_ZERO:
8675 		err = check_mem_size_reg(env, reg, regno,
8676 					 fn->arg_type[arg - 1] & MEM_WRITE ?
8677 					 BPF_WRITE : BPF_READ,
8678 					 true, meta);
8679 		break;
8680 	case ARG_PTR_TO_DYNPTR:
8681 		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8682 		if (err)
8683 			return err;
8684 		break;
8685 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8686 		if (!tnum_is_const(reg->var_off)) {
8687 			verbose(env, "R%d is not a known constant'\n",
8688 				regno);
8689 			return -EACCES;
8690 		}
8691 		meta->mem_size = reg->var_off.value;
8692 		err = mark_chain_precision(env, regno);
8693 		if (err)
8694 			return err;
8695 		break;
8696 	case ARG_PTR_TO_CONST_STR:
8697 	{
8698 		struct bpf_map *map = reg->map_ptr;
8699 		int map_off;
8700 		u64 map_addr;
8701 		char *str_ptr;
8702 
8703 		if (!bpf_map_is_rdonly(map)) {
8704 			verbose(env, "R%d does not point to a readonly map'\n", regno);
8705 			return -EACCES;
8706 		}
8707 
8708 		if (!tnum_is_const(reg->var_off)) {
8709 			verbose(env, "R%d is not a constant address'\n", regno);
8710 			return -EACCES;
8711 		}
8712 
8713 		if (!map->ops->map_direct_value_addr) {
8714 			verbose(env, "no direct value access support for this map type\n");
8715 			return -EACCES;
8716 		}
8717 
8718 		err = check_map_access(env, regno, reg->off,
8719 				       map->value_size - reg->off, false,
8720 				       ACCESS_HELPER);
8721 		if (err)
8722 			return err;
8723 
8724 		map_off = reg->off + reg->var_off.value;
8725 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8726 		if (err) {
8727 			verbose(env, "direct value access on string failed\n");
8728 			return err;
8729 		}
8730 
8731 		str_ptr = (char *)(long)(map_addr);
8732 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8733 			verbose(env, "string is not zero-terminated\n");
8734 			return -EINVAL;
8735 		}
8736 		break;
8737 	}
8738 	case ARG_PTR_TO_KPTR:
8739 		err = process_kptr_func(env, regno, meta);
8740 		if (err)
8741 			return err;
8742 		break;
8743 	}
8744 
8745 	return err;
8746 }
8747 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)8748 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8749 {
8750 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8751 	enum bpf_prog_type type = resolve_prog_type(env->prog);
8752 
8753 	if (func_id != BPF_FUNC_map_update_elem &&
8754 	    func_id != BPF_FUNC_map_delete_elem)
8755 		return false;
8756 
8757 	/* It's not possible to get access to a locked struct sock in these
8758 	 * contexts, so updating is safe.
8759 	 */
8760 	switch (type) {
8761 	case BPF_PROG_TYPE_TRACING:
8762 		if (eatype == BPF_TRACE_ITER)
8763 			return true;
8764 		break;
8765 	case BPF_PROG_TYPE_SOCK_OPS:
8766 		/* map_update allowed only via dedicated helpers with event type checks */
8767 		if (func_id == BPF_FUNC_map_delete_elem)
8768 			return true;
8769 		break;
8770 	case BPF_PROG_TYPE_SOCKET_FILTER:
8771 	case BPF_PROG_TYPE_SCHED_CLS:
8772 	case BPF_PROG_TYPE_SCHED_ACT:
8773 	case BPF_PROG_TYPE_XDP:
8774 	case BPF_PROG_TYPE_SK_REUSEPORT:
8775 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8776 	case BPF_PROG_TYPE_SK_LOOKUP:
8777 		return true;
8778 	default:
8779 		break;
8780 	}
8781 
8782 	verbose(env, "cannot update sockmap in this context\n");
8783 	return false;
8784 }
8785 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)8786 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8787 {
8788 	return env->prog->jit_requested &&
8789 	       bpf_jit_supports_subprog_tailcalls();
8790 }
8791 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)8792 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8793 					struct bpf_map *map, int func_id)
8794 {
8795 	if (!map)
8796 		return 0;
8797 
8798 	/* We need a two way check, first is from map perspective ... */
8799 	switch (map->map_type) {
8800 	case BPF_MAP_TYPE_PROG_ARRAY:
8801 		if (func_id != BPF_FUNC_tail_call)
8802 			goto error;
8803 		break;
8804 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8805 		if (func_id != BPF_FUNC_perf_event_read &&
8806 		    func_id != BPF_FUNC_perf_event_output &&
8807 		    func_id != BPF_FUNC_skb_output &&
8808 		    func_id != BPF_FUNC_perf_event_read_value &&
8809 		    func_id != BPF_FUNC_xdp_output)
8810 			goto error;
8811 		break;
8812 	case BPF_MAP_TYPE_RINGBUF:
8813 		if (func_id != BPF_FUNC_ringbuf_output &&
8814 		    func_id != BPF_FUNC_ringbuf_reserve &&
8815 		    func_id != BPF_FUNC_ringbuf_query &&
8816 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8817 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8818 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8819 			goto error;
8820 		break;
8821 	case BPF_MAP_TYPE_USER_RINGBUF:
8822 		if (func_id != BPF_FUNC_user_ringbuf_drain)
8823 			goto error;
8824 		break;
8825 	case BPF_MAP_TYPE_STACK_TRACE:
8826 		if (func_id != BPF_FUNC_get_stackid)
8827 			goto error;
8828 		break;
8829 	case BPF_MAP_TYPE_CGROUP_ARRAY:
8830 		if (func_id != BPF_FUNC_skb_under_cgroup &&
8831 		    func_id != BPF_FUNC_current_task_under_cgroup)
8832 			goto error;
8833 		break;
8834 	case BPF_MAP_TYPE_CGROUP_STORAGE:
8835 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8836 		if (func_id != BPF_FUNC_get_local_storage)
8837 			goto error;
8838 		break;
8839 	case BPF_MAP_TYPE_DEVMAP:
8840 	case BPF_MAP_TYPE_DEVMAP_HASH:
8841 		if (func_id != BPF_FUNC_redirect_map &&
8842 		    func_id != BPF_FUNC_map_lookup_elem)
8843 			goto error;
8844 		break;
8845 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8846 	 * appear.
8847 	 */
8848 	case BPF_MAP_TYPE_CPUMAP:
8849 		if (func_id != BPF_FUNC_redirect_map)
8850 			goto error;
8851 		break;
8852 	case BPF_MAP_TYPE_XSKMAP:
8853 		if (func_id != BPF_FUNC_redirect_map &&
8854 		    func_id != BPF_FUNC_map_lookup_elem)
8855 			goto error;
8856 		break;
8857 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8858 	case BPF_MAP_TYPE_HASH_OF_MAPS:
8859 		if (func_id != BPF_FUNC_map_lookup_elem)
8860 			goto error;
8861 		break;
8862 	case BPF_MAP_TYPE_SOCKMAP:
8863 		if (func_id != BPF_FUNC_sk_redirect_map &&
8864 		    func_id != BPF_FUNC_sock_map_update &&
8865 		    func_id != BPF_FUNC_msg_redirect_map &&
8866 		    func_id != BPF_FUNC_sk_select_reuseport &&
8867 		    func_id != BPF_FUNC_map_lookup_elem &&
8868 		    !may_update_sockmap(env, func_id))
8869 			goto error;
8870 		break;
8871 	case BPF_MAP_TYPE_SOCKHASH:
8872 		if (func_id != BPF_FUNC_sk_redirect_hash &&
8873 		    func_id != BPF_FUNC_sock_hash_update &&
8874 		    func_id != BPF_FUNC_msg_redirect_hash &&
8875 		    func_id != BPF_FUNC_sk_select_reuseport &&
8876 		    func_id != BPF_FUNC_map_lookup_elem &&
8877 		    !may_update_sockmap(env, func_id))
8878 			goto error;
8879 		break;
8880 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8881 		if (func_id != BPF_FUNC_sk_select_reuseport)
8882 			goto error;
8883 		break;
8884 	case BPF_MAP_TYPE_QUEUE:
8885 	case BPF_MAP_TYPE_STACK:
8886 		if (func_id != BPF_FUNC_map_peek_elem &&
8887 		    func_id != BPF_FUNC_map_pop_elem &&
8888 		    func_id != BPF_FUNC_map_push_elem)
8889 			goto error;
8890 		break;
8891 	case BPF_MAP_TYPE_SK_STORAGE:
8892 		if (func_id != BPF_FUNC_sk_storage_get &&
8893 		    func_id != BPF_FUNC_sk_storage_delete &&
8894 		    func_id != BPF_FUNC_kptr_xchg)
8895 			goto error;
8896 		break;
8897 	case BPF_MAP_TYPE_INODE_STORAGE:
8898 		if (func_id != BPF_FUNC_inode_storage_get &&
8899 		    func_id != BPF_FUNC_inode_storage_delete &&
8900 		    func_id != BPF_FUNC_kptr_xchg)
8901 			goto error;
8902 		break;
8903 	case BPF_MAP_TYPE_TASK_STORAGE:
8904 		if (func_id != BPF_FUNC_task_storage_get &&
8905 		    func_id != BPF_FUNC_task_storage_delete &&
8906 		    func_id != BPF_FUNC_kptr_xchg)
8907 			goto error;
8908 		break;
8909 	case BPF_MAP_TYPE_CGRP_STORAGE:
8910 		if (func_id != BPF_FUNC_cgrp_storage_get &&
8911 		    func_id != BPF_FUNC_cgrp_storage_delete &&
8912 		    func_id != BPF_FUNC_kptr_xchg)
8913 			goto error;
8914 		break;
8915 	case BPF_MAP_TYPE_BLOOM_FILTER:
8916 		if (func_id != BPF_FUNC_map_peek_elem &&
8917 		    func_id != BPF_FUNC_map_push_elem)
8918 			goto error;
8919 		break;
8920 	default:
8921 		break;
8922 	}
8923 
8924 	/* ... and second from the function itself. */
8925 	switch (func_id) {
8926 	case BPF_FUNC_tail_call:
8927 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8928 			goto error;
8929 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8930 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8931 			return -EINVAL;
8932 		}
8933 		break;
8934 	case BPF_FUNC_perf_event_read:
8935 	case BPF_FUNC_perf_event_output:
8936 	case BPF_FUNC_perf_event_read_value:
8937 	case BPF_FUNC_skb_output:
8938 	case BPF_FUNC_xdp_output:
8939 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8940 			goto error;
8941 		break;
8942 	case BPF_FUNC_ringbuf_output:
8943 	case BPF_FUNC_ringbuf_reserve:
8944 	case BPF_FUNC_ringbuf_query:
8945 	case BPF_FUNC_ringbuf_reserve_dynptr:
8946 	case BPF_FUNC_ringbuf_submit_dynptr:
8947 	case BPF_FUNC_ringbuf_discard_dynptr:
8948 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8949 			goto error;
8950 		break;
8951 	case BPF_FUNC_user_ringbuf_drain:
8952 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8953 			goto error;
8954 		break;
8955 	case BPF_FUNC_get_stackid:
8956 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8957 			goto error;
8958 		break;
8959 	case BPF_FUNC_current_task_under_cgroup:
8960 	case BPF_FUNC_skb_under_cgroup:
8961 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8962 			goto error;
8963 		break;
8964 	case BPF_FUNC_redirect_map:
8965 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8966 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8967 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8968 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8969 			goto error;
8970 		break;
8971 	case BPF_FUNC_sk_redirect_map:
8972 	case BPF_FUNC_msg_redirect_map:
8973 	case BPF_FUNC_sock_map_update:
8974 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8975 			goto error;
8976 		break;
8977 	case BPF_FUNC_sk_redirect_hash:
8978 	case BPF_FUNC_msg_redirect_hash:
8979 	case BPF_FUNC_sock_hash_update:
8980 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8981 			goto error;
8982 		break;
8983 	case BPF_FUNC_get_local_storage:
8984 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8985 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8986 			goto error;
8987 		break;
8988 	case BPF_FUNC_sk_select_reuseport:
8989 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8990 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8991 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8992 			goto error;
8993 		break;
8994 	case BPF_FUNC_map_pop_elem:
8995 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8996 		    map->map_type != BPF_MAP_TYPE_STACK)
8997 			goto error;
8998 		break;
8999 	case BPF_FUNC_map_peek_elem:
9000 	case BPF_FUNC_map_push_elem:
9001 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9002 		    map->map_type != BPF_MAP_TYPE_STACK &&
9003 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9004 			goto error;
9005 		break;
9006 	case BPF_FUNC_map_lookup_percpu_elem:
9007 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9008 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9009 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9010 			goto error;
9011 		break;
9012 	case BPF_FUNC_sk_storage_get:
9013 	case BPF_FUNC_sk_storage_delete:
9014 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9015 			goto error;
9016 		break;
9017 	case BPF_FUNC_inode_storage_get:
9018 	case BPF_FUNC_inode_storage_delete:
9019 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9020 			goto error;
9021 		break;
9022 	case BPF_FUNC_task_storage_get:
9023 	case BPF_FUNC_task_storage_delete:
9024 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9025 			goto error;
9026 		break;
9027 	case BPF_FUNC_cgrp_storage_get:
9028 	case BPF_FUNC_cgrp_storage_delete:
9029 		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9030 			goto error;
9031 		break;
9032 	default:
9033 		break;
9034 	}
9035 
9036 	return 0;
9037 error:
9038 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9039 		map->map_type, func_id_name(func_id), func_id);
9040 	return -EINVAL;
9041 }
9042 
check_raw_mode_ok(const struct bpf_func_proto * fn)9043 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9044 {
9045 	int count = 0;
9046 
9047 	if (arg_type_is_raw_mem(fn->arg1_type))
9048 		count++;
9049 	if (arg_type_is_raw_mem(fn->arg2_type))
9050 		count++;
9051 	if (arg_type_is_raw_mem(fn->arg3_type))
9052 		count++;
9053 	if (arg_type_is_raw_mem(fn->arg4_type))
9054 		count++;
9055 	if (arg_type_is_raw_mem(fn->arg5_type))
9056 		count++;
9057 
9058 	/* We only support one arg being in raw mode at the moment,
9059 	 * which is sufficient for the helper functions we have
9060 	 * right now.
9061 	 */
9062 	return count <= 1;
9063 }
9064 
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)9065 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9066 {
9067 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9068 	bool has_size = fn->arg_size[arg] != 0;
9069 	bool is_next_size = false;
9070 
9071 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9072 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9073 
9074 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9075 		return is_next_size;
9076 
9077 	return has_size == is_next_size || is_next_size == is_fixed;
9078 }
9079 
check_arg_pair_ok(const struct bpf_func_proto * fn)9080 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9081 {
9082 	/* bpf_xxx(..., buf, len) call will access 'len'
9083 	 * bytes from memory 'buf'. Both arg types need
9084 	 * to be paired, so make sure there's no buggy
9085 	 * helper function specification.
9086 	 */
9087 	if (arg_type_is_mem_size(fn->arg1_type) ||
9088 	    check_args_pair_invalid(fn, 0) ||
9089 	    check_args_pair_invalid(fn, 1) ||
9090 	    check_args_pair_invalid(fn, 2) ||
9091 	    check_args_pair_invalid(fn, 3) ||
9092 	    check_args_pair_invalid(fn, 4))
9093 		return false;
9094 
9095 	return true;
9096 }
9097 
check_btf_id_ok(const struct bpf_func_proto * fn)9098 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9099 {
9100 	int i;
9101 
9102 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9103 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9104 			return !!fn->arg_btf_id[i];
9105 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9106 			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9107 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9108 		    /* arg_btf_id and arg_size are in a union. */
9109 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9110 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9111 			return false;
9112 	}
9113 
9114 	return true;
9115 }
9116 
check_func_proto(const struct bpf_func_proto * fn,int func_id)9117 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9118 {
9119 	return check_raw_mode_ok(fn) &&
9120 	       check_arg_pair_ok(fn) &&
9121 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9122 }
9123 
9124 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9125  * are now invalid, so turn them into unknown SCALAR_VALUE.
9126  *
9127  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9128  * since these slices point to packet data.
9129  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)9130 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9131 {
9132 	struct bpf_func_state *state;
9133 	struct bpf_reg_state *reg;
9134 
9135 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9136 		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9137 			mark_reg_invalid(env, reg);
9138 	}));
9139 }
9140 
9141 enum {
9142 	AT_PKT_END = -1,
9143 	BEYOND_PKT_END = -2,
9144 };
9145 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)9146 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9147 {
9148 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9149 	struct bpf_reg_state *reg = &state->regs[regn];
9150 
9151 	if (reg->type != PTR_TO_PACKET)
9152 		/* PTR_TO_PACKET_META is not supported yet */
9153 		return;
9154 
9155 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9156 	 * How far beyond pkt_end it goes is unknown.
9157 	 * if (!range_open) it's the case of pkt >= pkt_end
9158 	 * if (range_open) it's the case of pkt > pkt_end
9159 	 * hence this pointer is at least 1 byte bigger than pkt_end
9160 	 */
9161 	if (range_open)
9162 		reg->range = BEYOND_PKT_END;
9163 	else
9164 		reg->range = AT_PKT_END;
9165 }
9166 
9167 /* The pointer with the specified id has released its reference to kernel
9168  * resources. Identify all copies of the same pointer and clear the reference.
9169  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)9170 static int release_reference(struct bpf_verifier_env *env,
9171 			     int ref_obj_id)
9172 {
9173 	struct bpf_func_state *state;
9174 	struct bpf_reg_state *reg;
9175 	int err;
9176 
9177 	err = release_reference_state(cur_func(env), ref_obj_id);
9178 	if (err)
9179 		return err;
9180 
9181 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9182 		if (reg->ref_obj_id == ref_obj_id)
9183 			mark_reg_invalid(env, reg);
9184 	}));
9185 
9186 	return 0;
9187 }
9188 
invalidate_non_owning_refs(struct bpf_verifier_env * env)9189 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9190 {
9191 	struct bpf_func_state *unused;
9192 	struct bpf_reg_state *reg;
9193 
9194 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9195 		if (type_is_non_owning_ref(reg->type))
9196 			mark_reg_invalid(env, reg);
9197 	}));
9198 }
9199 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9200 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9201 				    struct bpf_reg_state *regs)
9202 {
9203 	int i;
9204 
9205 	/* after the call registers r0 - r5 were scratched */
9206 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9207 		mark_reg_not_init(env, regs, caller_saved[i]);
9208 		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9209 	}
9210 }
9211 
9212 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9213 				   struct bpf_func_state *caller,
9214 				   struct bpf_func_state *callee,
9215 				   int insn_idx);
9216 
9217 static int set_callee_state(struct bpf_verifier_env *env,
9218 			    struct bpf_func_state *caller,
9219 			    struct bpf_func_state *callee, int insn_idx);
9220 
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)9221 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9222 			    set_callee_state_fn set_callee_state_cb,
9223 			    struct bpf_verifier_state *state)
9224 {
9225 	struct bpf_func_state *caller, *callee;
9226 	int err;
9227 
9228 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9229 		verbose(env, "the call stack of %d frames is too deep\n",
9230 			state->curframe + 2);
9231 		return -E2BIG;
9232 	}
9233 
9234 	if (state->frame[state->curframe + 1]) {
9235 		verbose(env, "verifier bug. Frame %d already allocated\n",
9236 			state->curframe + 1);
9237 		return -EFAULT;
9238 	}
9239 
9240 	caller = state->frame[state->curframe];
9241 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9242 	if (!callee)
9243 		return -ENOMEM;
9244 	state->frame[state->curframe + 1] = callee;
9245 
9246 	/* callee cannot access r0, r6 - r9 for reading and has to write
9247 	 * into its own stack before reading from it.
9248 	 * callee can read/write into caller's stack
9249 	 */
9250 	init_func_state(env, callee,
9251 			/* remember the callsite, it will be used by bpf_exit */
9252 			callsite,
9253 			state->curframe + 1 /* frameno within this callchain */,
9254 			subprog /* subprog number within this prog */);
9255 	/* Transfer references to the callee */
9256 	err = copy_reference_state(callee, caller);
9257 	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9258 	if (err)
9259 		goto err_out;
9260 
9261 	/* only increment it after check_reg_arg() finished */
9262 	state->curframe++;
9263 
9264 	return 0;
9265 
9266 err_out:
9267 	free_func_state(callee);
9268 	state->frame[state->curframe + 1] = NULL;
9269 	return err;
9270 }
9271 
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)9272 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9273 			      int insn_idx, int subprog,
9274 			      set_callee_state_fn set_callee_state_cb)
9275 {
9276 	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9277 	struct bpf_func_state *caller, *callee;
9278 	int err;
9279 
9280 	caller = state->frame[state->curframe];
9281 	err = btf_check_subprog_call(env, subprog, caller->regs);
9282 	if (err == -EFAULT)
9283 		return err;
9284 
9285 	/* set_callee_state is used for direct subprog calls, but we are
9286 	 * interested in validating only BPF helpers that can call subprogs as
9287 	 * callbacks
9288 	 */
9289 	if (bpf_pseudo_kfunc_call(insn) &&
9290 	    !is_sync_callback_calling_kfunc(insn->imm)) {
9291 		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9292 			func_id_name(insn->imm), insn->imm);
9293 		return -EFAULT;
9294 	} else if (!bpf_pseudo_kfunc_call(insn) &&
9295 		   !is_callback_calling_function(insn->imm)) { /* helper */
9296 		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9297 			func_id_name(insn->imm), insn->imm);
9298 		return -EFAULT;
9299 	}
9300 
9301 	if (insn->code == (BPF_JMP | BPF_CALL) &&
9302 	    insn->src_reg == 0 &&
9303 	    insn->imm == BPF_FUNC_timer_set_callback) {
9304 		struct bpf_verifier_state *async_cb;
9305 
9306 		/* there is no real recursion here. timer callbacks are async */
9307 		env->subprog_info[subprog].is_async_cb = true;
9308 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9309 					 insn_idx, subprog);
9310 		if (!async_cb)
9311 			return -EFAULT;
9312 		callee = async_cb->frame[0];
9313 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9314 
9315 		/* Convert bpf_timer_set_callback() args into timer callback args */
9316 		err = set_callee_state_cb(env, caller, callee, insn_idx);
9317 		if (err)
9318 			return err;
9319 
9320 		return 0;
9321 	}
9322 
9323 	/* for callback functions enqueue entry to callback and
9324 	 * proceed with next instruction within current frame.
9325 	 */
9326 	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9327 	if (!callback_state)
9328 		return -ENOMEM;
9329 
9330 	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9331 			       callback_state);
9332 	if (err)
9333 		return err;
9334 
9335 	callback_state->callback_unroll_depth++;
9336 	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9337 	caller->callback_depth = 0;
9338 	return 0;
9339 }
9340 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)9341 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9342 			   int *insn_idx)
9343 {
9344 	struct bpf_verifier_state *state = env->cur_state;
9345 	struct bpf_func_state *caller;
9346 	int err, subprog, target_insn;
9347 
9348 	target_insn = *insn_idx + insn->imm + 1;
9349 	subprog = find_subprog(env, target_insn);
9350 	if (subprog < 0) {
9351 		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9352 		return -EFAULT;
9353 	}
9354 
9355 	caller = state->frame[state->curframe];
9356 	err = btf_check_subprog_call(env, subprog, caller->regs);
9357 	if (err == -EFAULT)
9358 		return err;
9359 	if (subprog_is_global(env, subprog)) {
9360 		if (err) {
9361 			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9362 			return err;
9363 		}
9364 
9365 		if (env->log.level & BPF_LOG_LEVEL)
9366 			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9367 		if (env->subprog_info[subprog].changes_pkt_data)
9368 			clear_all_pkt_pointers(env);
9369 		clear_caller_saved_regs(env, caller->regs);
9370 
9371 		/* All global functions return a 64-bit SCALAR_VALUE */
9372 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9373 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9374 
9375 		/* continue with next insn after call */
9376 		return 0;
9377 	}
9378 
9379 	/* for regular function entry setup new frame and continue
9380 	 * from that frame.
9381 	 */
9382 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9383 	if (err)
9384 		return err;
9385 
9386 	clear_caller_saved_regs(env, caller->regs);
9387 
9388 	/* and go analyze first insn of the callee */
9389 	*insn_idx = env->subprog_info[subprog].start - 1;
9390 
9391 	if (env->log.level & BPF_LOG_LEVEL) {
9392 		verbose(env, "caller:\n");
9393 		print_verifier_state(env, caller, true);
9394 		verbose(env, "callee:\n");
9395 		print_verifier_state(env, state->frame[state->curframe], true);
9396 	}
9397 
9398 	return 0;
9399 }
9400 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)9401 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9402 				   struct bpf_func_state *caller,
9403 				   struct bpf_func_state *callee)
9404 {
9405 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9406 	 *      void *callback_ctx, u64 flags);
9407 	 * callback_fn(struct bpf_map *map, void *key, void *value,
9408 	 *      void *callback_ctx);
9409 	 */
9410 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9411 
9412 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9413 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9414 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9415 
9416 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9417 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9418 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9419 
9420 	/* pointer to stack or null */
9421 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9422 
9423 	/* unused */
9424 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9425 	return 0;
9426 }
9427 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9428 static int set_callee_state(struct bpf_verifier_env *env,
9429 			    struct bpf_func_state *caller,
9430 			    struct bpf_func_state *callee, int insn_idx)
9431 {
9432 	int i;
9433 
9434 	/* copy r1 - r5 args that callee can access.  The copy includes parent
9435 	 * pointers, which connects us up to the liveness chain
9436 	 */
9437 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9438 		callee->regs[i] = caller->regs[i];
9439 	return 0;
9440 }
9441 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9442 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9443 				       struct bpf_func_state *caller,
9444 				       struct bpf_func_state *callee,
9445 				       int insn_idx)
9446 {
9447 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9448 	struct bpf_map *map;
9449 	int err;
9450 
9451 	if (bpf_map_ptr_poisoned(insn_aux)) {
9452 		verbose(env, "tail_call abusing map_ptr\n");
9453 		return -EINVAL;
9454 	}
9455 
9456 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9457 	if (!map->ops->map_set_for_each_callback_args ||
9458 	    !map->ops->map_for_each_callback) {
9459 		verbose(env, "callback function not allowed for map\n");
9460 		return -ENOTSUPP;
9461 	}
9462 
9463 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9464 	if (err)
9465 		return err;
9466 
9467 	callee->in_callback_fn = true;
9468 	callee->callback_ret_range = tnum_range(0, 1);
9469 	return 0;
9470 }
9471 
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9472 static int set_loop_callback_state(struct bpf_verifier_env *env,
9473 				   struct bpf_func_state *caller,
9474 				   struct bpf_func_state *callee,
9475 				   int insn_idx)
9476 {
9477 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9478 	 *	    u64 flags);
9479 	 * callback_fn(u32 index, void *callback_ctx);
9480 	 */
9481 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9482 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9483 
9484 	/* unused */
9485 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9486 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9487 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9488 
9489 	callee->in_callback_fn = true;
9490 	callee->callback_ret_range = tnum_range(0, 1);
9491 	return 0;
9492 }
9493 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9494 static int set_timer_callback_state(struct bpf_verifier_env *env,
9495 				    struct bpf_func_state *caller,
9496 				    struct bpf_func_state *callee,
9497 				    int insn_idx)
9498 {
9499 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9500 
9501 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9502 	 * callback_fn(struct bpf_map *map, void *key, void *value);
9503 	 */
9504 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9505 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9506 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9507 
9508 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9509 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9510 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9511 
9512 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9513 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9514 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9515 
9516 	/* unused */
9517 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9518 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9519 	callee->in_async_callback_fn = true;
9520 	callee->callback_ret_range = tnum_range(0, 1);
9521 	return 0;
9522 }
9523 
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9524 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9525 				       struct bpf_func_state *caller,
9526 				       struct bpf_func_state *callee,
9527 				       int insn_idx)
9528 {
9529 	/* bpf_find_vma(struct task_struct *task, u64 addr,
9530 	 *               void *callback_fn, void *callback_ctx, u64 flags)
9531 	 * (callback_fn)(struct task_struct *task,
9532 	 *               struct vm_area_struct *vma, void *callback_ctx);
9533 	 */
9534 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9535 
9536 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9537 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9538 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9539 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9540 
9541 	/* pointer to stack or null */
9542 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9543 
9544 	/* unused */
9545 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9546 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9547 	callee->in_callback_fn = true;
9548 	callee->callback_ret_range = tnum_range(0, 1);
9549 	return 0;
9550 }
9551 
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9552 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9553 					   struct bpf_func_state *caller,
9554 					   struct bpf_func_state *callee,
9555 					   int insn_idx)
9556 {
9557 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9558 	 *			  callback_ctx, u64 flags);
9559 	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9560 	 */
9561 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9562 	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9563 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9564 
9565 	/* unused */
9566 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9567 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9568 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9569 
9570 	callee->in_callback_fn = true;
9571 	callee->callback_ret_range = tnum_range(0, 1);
9572 	return 0;
9573 }
9574 
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9575 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9576 					 struct bpf_func_state *caller,
9577 					 struct bpf_func_state *callee,
9578 					 int insn_idx)
9579 {
9580 	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9581 	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9582 	 *
9583 	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9584 	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9585 	 * by this point, so look at 'root'
9586 	 */
9587 	struct btf_field *field;
9588 
9589 	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9590 				      BPF_RB_ROOT);
9591 	if (!field || !field->graph_root.value_btf_id)
9592 		return -EFAULT;
9593 
9594 	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9595 	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9596 	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9597 	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9598 
9599 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9600 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9601 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9602 	callee->in_callback_fn = true;
9603 	callee->callback_ret_range = tnum_range(0, 1);
9604 	return 0;
9605 }
9606 
9607 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9608 
9609 /* Are we currently verifying the callback for a rbtree helper that must
9610  * be called with lock held? If so, no need to complain about unreleased
9611  * lock
9612  */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)9613 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9614 {
9615 	struct bpf_verifier_state *state = env->cur_state;
9616 	struct bpf_insn *insn = env->prog->insnsi;
9617 	struct bpf_func_state *callee;
9618 	int kfunc_btf_id;
9619 
9620 	if (!state->curframe)
9621 		return false;
9622 
9623 	callee = state->frame[state->curframe];
9624 
9625 	if (!callee->in_callback_fn)
9626 		return false;
9627 
9628 	kfunc_btf_id = insn[callee->callsite].imm;
9629 	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9630 }
9631 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)9632 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9633 {
9634 	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9635 	struct bpf_func_state *caller, *callee;
9636 	struct bpf_reg_state *r0;
9637 	bool in_callback_fn;
9638 	int err;
9639 
9640 	callee = state->frame[state->curframe];
9641 	r0 = &callee->regs[BPF_REG_0];
9642 	if (r0->type == PTR_TO_STACK) {
9643 		/* technically it's ok to return caller's stack pointer
9644 		 * (or caller's caller's pointer) back to the caller,
9645 		 * since these pointers are valid. Only current stack
9646 		 * pointer will be invalid as soon as function exits,
9647 		 * but let's be conservative
9648 		 */
9649 		verbose(env, "cannot return stack pointer to the caller\n");
9650 		return -EINVAL;
9651 	}
9652 
9653 	caller = state->frame[state->curframe - 1];
9654 	if (callee->in_callback_fn) {
9655 		/* enforce R0 return value range [0, 1]. */
9656 		struct tnum range = callee->callback_ret_range;
9657 
9658 		if (r0->type != SCALAR_VALUE) {
9659 			verbose(env, "R0 not a scalar value\n");
9660 			return -EACCES;
9661 		}
9662 
9663 		/* we are going to rely on register's precise value */
9664 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9665 		err = err ?: mark_chain_precision(env, BPF_REG_0);
9666 		if (err)
9667 			return err;
9668 
9669 		if (!tnum_in(range, r0->var_off)) {
9670 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9671 			return -EINVAL;
9672 		}
9673 		if (!calls_callback(env, callee->callsite)) {
9674 			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9675 				*insn_idx, callee->callsite);
9676 			return -EFAULT;
9677 		}
9678 	} else {
9679 		/* return to the caller whatever r0 had in the callee */
9680 		caller->regs[BPF_REG_0] = *r0;
9681 	}
9682 
9683 	/* callback_fn frame should have released its own additions to parent's
9684 	 * reference state at this point, or check_reference_leak would
9685 	 * complain, hence it must be the same as the caller. There is no need
9686 	 * to copy it back.
9687 	 */
9688 	if (!callee->in_callback_fn) {
9689 		/* Transfer references to the caller */
9690 		err = copy_reference_state(caller, callee);
9691 		if (err)
9692 			return err;
9693 	}
9694 
9695 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9696 	 * there function call logic would reschedule callback visit. If iteration
9697 	 * converges is_state_visited() would prune that visit eventually.
9698 	 */
9699 	in_callback_fn = callee->in_callback_fn;
9700 	if (in_callback_fn)
9701 		*insn_idx = callee->callsite;
9702 	else
9703 		*insn_idx = callee->callsite + 1;
9704 
9705 	if (env->log.level & BPF_LOG_LEVEL) {
9706 		verbose(env, "returning from callee:\n");
9707 		print_verifier_state(env, callee, true);
9708 		verbose(env, "to caller at %d:\n", *insn_idx);
9709 		print_verifier_state(env, caller, true);
9710 	}
9711 	/* clear everything in the callee */
9712 	free_func_state(callee);
9713 	state->frame[state->curframe--] = NULL;
9714 
9715 	/* for callbacks widen imprecise scalars to make programs like below verify:
9716 	 *
9717 	 *   struct ctx { int i; }
9718 	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9719 	 *   ...
9720 	 *   struct ctx = { .i = 0; }
9721 	 *   bpf_loop(100, cb, &ctx, 0);
9722 	 *
9723 	 * This is similar to what is done in process_iter_next_call() for open
9724 	 * coded iterators.
9725 	 */
9726 	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9727 	if (prev_st) {
9728 		err = widen_imprecise_scalars(env, prev_st, state);
9729 		if (err)
9730 			return err;
9731 	}
9732 	return 0;
9733 }
9734 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)9735 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9736 				   int func_id,
9737 				   struct bpf_call_arg_meta *meta)
9738 {
9739 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9740 
9741 	if (ret_type != RET_INTEGER)
9742 		return;
9743 
9744 	switch (func_id) {
9745 	case BPF_FUNC_get_stack:
9746 	case BPF_FUNC_get_task_stack:
9747 	case BPF_FUNC_probe_read_str:
9748 	case BPF_FUNC_probe_read_kernel_str:
9749 	case BPF_FUNC_probe_read_user_str:
9750 		ret_reg->smax_value = meta->msize_max_value;
9751 		ret_reg->s32_max_value = meta->msize_max_value;
9752 		ret_reg->smin_value = -MAX_ERRNO;
9753 		ret_reg->s32_min_value = -MAX_ERRNO;
9754 		reg_bounds_sync(ret_reg);
9755 		break;
9756 	case BPF_FUNC_get_smp_processor_id:
9757 		ret_reg->umax_value = nr_cpu_ids - 1;
9758 		ret_reg->u32_max_value = nr_cpu_ids - 1;
9759 		ret_reg->smax_value = nr_cpu_ids - 1;
9760 		ret_reg->s32_max_value = nr_cpu_ids - 1;
9761 		ret_reg->umin_value = 0;
9762 		ret_reg->u32_min_value = 0;
9763 		ret_reg->smin_value = 0;
9764 		ret_reg->s32_min_value = 0;
9765 		reg_bounds_sync(ret_reg);
9766 		break;
9767 	}
9768 }
9769 
9770 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)9771 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9772 		int func_id, int insn_idx)
9773 {
9774 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9775 	struct bpf_map *map = meta->map_ptr;
9776 
9777 	if (func_id != BPF_FUNC_tail_call &&
9778 	    func_id != BPF_FUNC_map_lookup_elem &&
9779 	    func_id != BPF_FUNC_map_update_elem &&
9780 	    func_id != BPF_FUNC_map_delete_elem &&
9781 	    func_id != BPF_FUNC_map_push_elem &&
9782 	    func_id != BPF_FUNC_map_pop_elem &&
9783 	    func_id != BPF_FUNC_map_peek_elem &&
9784 	    func_id != BPF_FUNC_for_each_map_elem &&
9785 	    func_id != BPF_FUNC_redirect_map &&
9786 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9787 		return 0;
9788 
9789 	if (map == NULL) {
9790 		verbose(env, "kernel subsystem misconfigured verifier\n");
9791 		return -EINVAL;
9792 	}
9793 
9794 	/* In case of read-only, some additional restrictions
9795 	 * need to be applied in order to prevent altering the
9796 	 * state of the map from program side.
9797 	 */
9798 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9799 	    (func_id == BPF_FUNC_map_delete_elem ||
9800 	     func_id == BPF_FUNC_map_update_elem ||
9801 	     func_id == BPF_FUNC_map_push_elem ||
9802 	     func_id == BPF_FUNC_map_pop_elem)) {
9803 		verbose(env, "write into map forbidden\n");
9804 		return -EACCES;
9805 	}
9806 
9807 	if (!BPF_MAP_PTR(aux->map_ptr_state))
9808 		bpf_map_ptr_store(aux, meta->map_ptr,
9809 				  !meta->map_ptr->bypass_spec_v1);
9810 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9811 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9812 				  !meta->map_ptr->bypass_spec_v1);
9813 	return 0;
9814 }
9815 
9816 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)9817 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9818 		int func_id, int insn_idx)
9819 {
9820 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9821 	struct bpf_reg_state *regs = cur_regs(env), *reg;
9822 	struct bpf_map *map = meta->map_ptr;
9823 	u64 val, max;
9824 	int err;
9825 
9826 	if (func_id != BPF_FUNC_tail_call)
9827 		return 0;
9828 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9829 		verbose(env, "kernel subsystem misconfigured verifier\n");
9830 		return -EINVAL;
9831 	}
9832 
9833 	reg = &regs[BPF_REG_3];
9834 	val = reg->var_off.value;
9835 	max = map->max_entries;
9836 
9837 	if (!(register_is_const(reg) && val < max)) {
9838 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9839 		return 0;
9840 	}
9841 
9842 	err = mark_chain_precision(env, BPF_REG_3);
9843 	if (err)
9844 		return err;
9845 	if (bpf_map_key_unseen(aux))
9846 		bpf_map_key_store(aux, val);
9847 	else if (!bpf_map_key_poisoned(aux) &&
9848 		  bpf_map_key_immediate(aux) != val)
9849 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9850 	return 0;
9851 }
9852 
check_reference_leak(struct bpf_verifier_env * env)9853 static int check_reference_leak(struct bpf_verifier_env *env)
9854 {
9855 	struct bpf_func_state *state = cur_func(env);
9856 	bool refs_lingering = false;
9857 	int i;
9858 
9859 	if (state->frameno && !state->in_callback_fn)
9860 		return 0;
9861 
9862 	for (i = 0; i < state->acquired_refs; i++) {
9863 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9864 			continue;
9865 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9866 			state->refs[i].id, state->refs[i].insn_idx);
9867 		refs_lingering = true;
9868 	}
9869 	return refs_lingering ? -EINVAL : 0;
9870 }
9871 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9872 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9873 				   struct bpf_reg_state *regs)
9874 {
9875 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9876 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9877 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9878 	struct bpf_bprintf_data data = {};
9879 	int err, fmt_map_off, num_args;
9880 	u64 fmt_addr;
9881 	char *fmt;
9882 
9883 	/* data must be an array of u64 */
9884 	if (data_len_reg->var_off.value % 8)
9885 		return -EINVAL;
9886 	num_args = data_len_reg->var_off.value / 8;
9887 
9888 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9889 	 * and map_direct_value_addr is set.
9890 	 */
9891 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9892 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9893 						  fmt_map_off);
9894 	if (err) {
9895 		verbose(env, "verifier bug\n");
9896 		return -EFAULT;
9897 	}
9898 	fmt = (char *)(long)fmt_addr + fmt_map_off;
9899 
9900 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9901 	 * can focus on validating the format specifiers.
9902 	 */
9903 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9904 	if (err < 0)
9905 		verbose(env, "Invalid format string\n");
9906 
9907 	return err;
9908 }
9909 
check_get_func_ip(struct bpf_verifier_env * env)9910 static int check_get_func_ip(struct bpf_verifier_env *env)
9911 {
9912 	enum bpf_prog_type type = resolve_prog_type(env->prog);
9913 	int func_id = BPF_FUNC_get_func_ip;
9914 
9915 	if (type == BPF_PROG_TYPE_TRACING) {
9916 		if (!bpf_prog_has_trampoline(env->prog)) {
9917 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9918 				func_id_name(func_id), func_id);
9919 			return -ENOTSUPP;
9920 		}
9921 		return 0;
9922 	} else if (type == BPF_PROG_TYPE_KPROBE) {
9923 		return 0;
9924 	}
9925 
9926 	verbose(env, "func %s#%d not supported for program type %d\n",
9927 		func_id_name(func_id), func_id, type);
9928 	return -ENOTSUPP;
9929 }
9930 
cur_aux(struct bpf_verifier_env * env)9931 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9932 {
9933 	return &env->insn_aux_data[env->insn_idx];
9934 }
9935 
loop_flag_is_zero(struct bpf_verifier_env * env)9936 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9937 {
9938 	struct bpf_reg_state *regs = cur_regs(env);
9939 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9940 	bool reg_is_null = register_is_null(reg);
9941 
9942 	if (reg_is_null)
9943 		mark_chain_precision(env, BPF_REG_4);
9944 
9945 	return reg_is_null;
9946 }
9947 
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)9948 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9949 {
9950 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9951 
9952 	if (!state->initialized) {
9953 		state->initialized = 1;
9954 		state->fit_for_inline = loop_flag_is_zero(env);
9955 		state->callback_subprogno = subprogno;
9956 		return;
9957 	}
9958 
9959 	if (!state->fit_for_inline)
9960 		return;
9961 
9962 	state->fit_for_inline = (loop_flag_is_zero(env) &&
9963 				 state->callback_subprogno == subprogno);
9964 }
9965 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)9966 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9967 			     int *insn_idx_p)
9968 {
9969 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9970 	const struct bpf_func_proto *fn = NULL;
9971 	enum bpf_return_type ret_type;
9972 	enum bpf_type_flag ret_flag;
9973 	struct bpf_reg_state *regs;
9974 	struct bpf_call_arg_meta meta;
9975 	int insn_idx = *insn_idx_p;
9976 	bool changes_data;
9977 	int i, err, func_id;
9978 
9979 	/* find function prototype */
9980 	func_id = insn->imm;
9981 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9982 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9983 			func_id);
9984 		return -EINVAL;
9985 	}
9986 
9987 	if (env->ops->get_func_proto)
9988 		fn = env->ops->get_func_proto(func_id, env->prog);
9989 	if (!fn) {
9990 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9991 			func_id);
9992 		return -EINVAL;
9993 	}
9994 
9995 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9996 	if (!env->prog->gpl_compatible && fn->gpl_only) {
9997 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9998 		return -EINVAL;
9999 	}
10000 
10001 	if (fn->allowed && !fn->allowed(env->prog)) {
10002 		verbose(env, "helper call is not allowed in probe\n");
10003 		return -EINVAL;
10004 	}
10005 
10006 	if (!env->prog->aux->sleepable && fn->might_sleep) {
10007 		verbose(env, "helper call might sleep in a non-sleepable prog\n");
10008 		return -EINVAL;
10009 	}
10010 
10011 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
10012 	changes_data = bpf_helper_changes_pkt_data(func_id);
10013 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10014 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10015 			func_id_name(func_id), func_id);
10016 		return -EINVAL;
10017 	}
10018 
10019 	memset(&meta, 0, sizeof(meta));
10020 	meta.pkt_access = fn->pkt_access;
10021 
10022 	err = check_func_proto(fn, func_id);
10023 	if (err) {
10024 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10025 			func_id_name(func_id), func_id);
10026 		return err;
10027 	}
10028 
10029 	if (env->cur_state->active_rcu_lock) {
10030 		if (fn->might_sleep) {
10031 			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10032 				func_id_name(func_id), func_id);
10033 			return -EINVAL;
10034 		}
10035 
10036 		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10037 			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10038 	}
10039 
10040 	meta.func_id = func_id;
10041 	/* check args */
10042 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10043 		err = check_func_arg(env, i, &meta, fn, insn_idx);
10044 		if (err)
10045 			return err;
10046 	}
10047 
10048 	err = record_func_map(env, &meta, func_id, insn_idx);
10049 	if (err)
10050 		return err;
10051 
10052 	err = record_func_key(env, &meta, func_id, insn_idx);
10053 	if (err)
10054 		return err;
10055 
10056 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10057 	 * is inferred from register state.
10058 	 */
10059 	for (i = 0; i < meta.access_size; i++) {
10060 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10061 				       BPF_WRITE, -1, false, false);
10062 		if (err)
10063 			return err;
10064 	}
10065 
10066 	regs = cur_regs(env);
10067 
10068 	if (meta.release_regno) {
10069 		err = -EINVAL;
10070 		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10071 		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10072 		 * is safe to do directly.
10073 		 */
10074 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10075 			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10076 				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10077 				return -EFAULT;
10078 			}
10079 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10080 		} else if (meta.ref_obj_id) {
10081 			err = release_reference(env, meta.ref_obj_id);
10082 		} else if (register_is_null(&regs[meta.release_regno])) {
10083 			/* meta.ref_obj_id can only be 0 if register that is meant to be
10084 			 * released is NULL, which must be > R0.
10085 			 */
10086 			err = 0;
10087 		}
10088 		if (err) {
10089 			verbose(env, "func %s#%d reference has not been acquired before\n",
10090 				func_id_name(func_id), func_id);
10091 			return err;
10092 		}
10093 	}
10094 
10095 	switch (func_id) {
10096 	case BPF_FUNC_tail_call:
10097 		err = check_reference_leak(env);
10098 		if (err) {
10099 			verbose(env, "tail_call would lead to reference leak\n");
10100 			return err;
10101 		}
10102 		break;
10103 	case BPF_FUNC_get_local_storage:
10104 		/* check that flags argument in get_local_storage(map, flags) is 0,
10105 		 * this is required because get_local_storage() can't return an error.
10106 		 */
10107 		if (!register_is_null(&regs[BPF_REG_2])) {
10108 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10109 			return -EINVAL;
10110 		}
10111 		break;
10112 	case BPF_FUNC_for_each_map_elem:
10113 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10114 					 set_map_elem_callback_state);
10115 		break;
10116 	case BPF_FUNC_timer_set_callback:
10117 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10118 					 set_timer_callback_state);
10119 		break;
10120 	case BPF_FUNC_find_vma:
10121 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10122 					 set_find_vma_callback_state);
10123 		break;
10124 	case BPF_FUNC_snprintf:
10125 		err = check_bpf_snprintf_call(env, regs);
10126 		break;
10127 	case BPF_FUNC_loop:
10128 		update_loop_inline_state(env, meta.subprogno);
10129 		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10130 		 * is finished, thus mark it precise.
10131 		 */
10132 		err = mark_chain_precision(env, BPF_REG_1);
10133 		if (err)
10134 			return err;
10135 		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10136 			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10137 						 set_loop_callback_state);
10138 		} else {
10139 			cur_func(env)->callback_depth = 0;
10140 			if (env->log.level & BPF_LOG_LEVEL2)
10141 				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10142 					env->cur_state->curframe);
10143 		}
10144 		break;
10145 	case BPF_FUNC_dynptr_from_mem:
10146 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10147 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10148 				reg_type_str(env, regs[BPF_REG_1].type));
10149 			return -EACCES;
10150 		}
10151 		break;
10152 	case BPF_FUNC_set_retval:
10153 		if (prog_type == BPF_PROG_TYPE_LSM &&
10154 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10155 			if (!env->prog->aux->attach_func_proto->type) {
10156 				/* Make sure programs that attach to void
10157 				 * hooks don't try to modify return value.
10158 				 */
10159 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10160 				return -EINVAL;
10161 			}
10162 		}
10163 		break;
10164 	case BPF_FUNC_dynptr_data:
10165 	{
10166 		struct bpf_reg_state *reg;
10167 		int id, ref_obj_id;
10168 
10169 		reg = get_dynptr_arg_reg(env, fn, regs);
10170 		if (!reg)
10171 			return -EFAULT;
10172 
10173 
10174 		if (meta.dynptr_id) {
10175 			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10176 			return -EFAULT;
10177 		}
10178 		if (meta.ref_obj_id) {
10179 			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10180 			return -EFAULT;
10181 		}
10182 
10183 		id = dynptr_id(env, reg);
10184 		if (id < 0) {
10185 			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10186 			return id;
10187 		}
10188 
10189 		ref_obj_id = dynptr_ref_obj_id(env, reg);
10190 		if (ref_obj_id < 0) {
10191 			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10192 			return ref_obj_id;
10193 		}
10194 
10195 		meta.dynptr_id = id;
10196 		meta.ref_obj_id = ref_obj_id;
10197 
10198 		break;
10199 	}
10200 	case BPF_FUNC_dynptr_write:
10201 	{
10202 		enum bpf_dynptr_type dynptr_type;
10203 		struct bpf_reg_state *reg;
10204 
10205 		reg = get_dynptr_arg_reg(env, fn, regs);
10206 		if (!reg)
10207 			return -EFAULT;
10208 
10209 		dynptr_type = dynptr_get_type(env, reg);
10210 		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10211 			return -EFAULT;
10212 
10213 		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10214 			/* this will trigger clear_all_pkt_pointers(), which will
10215 			 * invalidate all dynptr slices associated with the skb
10216 			 */
10217 			changes_data = true;
10218 
10219 		break;
10220 	}
10221 	case BPF_FUNC_user_ringbuf_drain:
10222 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10223 					 set_user_ringbuf_callback_state);
10224 		break;
10225 	}
10226 
10227 	if (err)
10228 		return err;
10229 
10230 	/* reset caller saved regs */
10231 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10232 		mark_reg_not_init(env, regs, caller_saved[i]);
10233 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10234 	}
10235 
10236 	/* helper call returns 64-bit value. */
10237 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10238 
10239 	/* update return register (already marked as written above) */
10240 	ret_type = fn->ret_type;
10241 	ret_flag = type_flag(ret_type);
10242 
10243 	switch (base_type(ret_type)) {
10244 	case RET_INTEGER:
10245 		/* sets type to SCALAR_VALUE */
10246 		mark_reg_unknown(env, regs, BPF_REG_0);
10247 		break;
10248 	case RET_VOID:
10249 		regs[BPF_REG_0].type = NOT_INIT;
10250 		break;
10251 	case RET_PTR_TO_MAP_VALUE:
10252 		/* There is no offset yet applied, variable or fixed */
10253 		mark_reg_known_zero(env, regs, BPF_REG_0);
10254 		/* remember map_ptr, so that check_map_access()
10255 		 * can check 'value_size' boundary of memory access
10256 		 * to map element returned from bpf_map_lookup_elem()
10257 		 */
10258 		if (meta.map_ptr == NULL) {
10259 			verbose(env,
10260 				"kernel subsystem misconfigured verifier\n");
10261 			return -EINVAL;
10262 		}
10263 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10264 		regs[BPF_REG_0].map_uid = meta.map_uid;
10265 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10266 		if (!type_may_be_null(ret_type) &&
10267 		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10268 			regs[BPF_REG_0].id = ++env->id_gen;
10269 		}
10270 		break;
10271 	case RET_PTR_TO_SOCKET:
10272 		mark_reg_known_zero(env, regs, BPF_REG_0);
10273 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10274 		break;
10275 	case RET_PTR_TO_SOCK_COMMON:
10276 		mark_reg_known_zero(env, regs, BPF_REG_0);
10277 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10278 		break;
10279 	case RET_PTR_TO_TCP_SOCK:
10280 		mark_reg_known_zero(env, regs, BPF_REG_0);
10281 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10282 		break;
10283 	case RET_PTR_TO_MEM:
10284 		mark_reg_known_zero(env, regs, BPF_REG_0);
10285 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10286 		regs[BPF_REG_0].mem_size = meta.mem_size;
10287 		break;
10288 	case RET_PTR_TO_MEM_OR_BTF_ID:
10289 	{
10290 		const struct btf_type *t;
10291 
10292 		mark_reg_known_zero(env, regs, BPF_REG_0);
10293 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10294 		if (!btf_type_is_struct(t)) {
10295 			u32 tsize;
10296 			const struct btf_type *ret;
10297 			const char *tname;
10298 
10299 			/* resolve the type size of ksym. */
10300 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10301 			if (IS_ERR(ret)) {
10302 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10303 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10304 					tname, PTR_ERR(ret));
10305 				return -EINVAL;
10306 			}
10307 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10308 			regs[BPF_REG_0].mem_size = tsize;
10309 		} else {
10310 			/* MEM_RDONLY may be carried from ret_flag, but it
10311 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10312 			 * it will confuse the check of PTR_TO_BTF_ID in
10313 			 * check_mem_access().
10314 			 */
10315 			ret_flag &= ~MEM_RDONLY;
10316 
10317 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10318 			regs[BPF_REG_0].btf = meta.ret_btf;
10319 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10320 		}
10321 		break;
10322 	}
10323 	case RET_PTR_TO_BTF_ID:
10324 	{
10325 		struct btf *ret_btf;
10326 		int ret_btf_id;
10327 
10328 		mark_reg_known_zero(env, regs, BPF_REG_0);
10329 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10330 		if (func_id == BPF_FUNC_kptr_xchg) {
10331 			ret_btf = meta.kptr_field->kptr.btf;
10332 			ret_btf_id = meta.kptr_field->kptr.btf_id;
10333 			if (!btf_is_kernel(ret_btf))
10334 				regs[BPF_REG_0].type |= MEM_ALLOC;
10335 		} else {
10336 			if (fn->ret_btf_id == BPF_PTR_POISON) {
10337 				verbose(env, "verifier internal error:");
10338 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10339 					func_id_name(func_id));
10340 				return -EINVAL;
10341 			}
10342 			ret_btf = btf_vmlinux;
10343 			ret_btf_id = *fn->ret_btf_id;
10344 		}
10345 		if (ret_btf_id == 0) {
10346 			verbose(env, "invalid return type %u of func %s#%d\n",
10347 				base_type(ret_type), func_id_name(func_id),
10348 				func_id);
10349 			return -EINVAL;
10350 		}
10351 		regs[BPF_REG_0].btf = ret_btf;
10352 		regs[BPF_REG_0].btf_id = ret_btf_id;
10353 		break;
10354 	}
10355 	default:
10356 		verbose(env, "unknown return type %u of func %s#%d\n",
10357 			base_type(ret_type), func_id_name(func_id), func_id);
10358 		return -EINVAL;
10359 	}
10360 
10361 	if (type_may_be_null(regs[BPF_REG_0].type))
10362 		regs[BPF_REG_0].id = ++env->id_gen;
10363 
10364 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10365 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10366 			func_id_name(func_id), func_id);
10367 		return -EFAULT;
10368 	}
10369 
10370 	if (is_dynptr_ref_function(func_id))
10371 		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10372 
10373 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10374 		/* For release_reference() */
10375 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10376 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10377 		int id = acquire_reference_state(env, insn_idx);
10378 
10379 		if (id < 0)
10380 			return id;
10381 		/* For mark_ptr_or_null_reg() */
10382 		regs[BPF_REG_0].id = id;
10383 		/* For release_reference() */
10384 		regs[BPF_REG_0].ref_obj_id = id;
10385 	}
10386 
10387 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10388 
10389 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10390 	if (err)
10391 		return err;
10392 
10393 	if ((func_id == BPF_FUNC_get_stack ||
10394 	     func_id == BPF_FUNC_get_task_stack) &&
10395 	    !env->prog->has_callchain_buf) {
10396 		const char *err_str;
10397 
10398 #ifdef CONFIG_PERF_EVENTS
10399 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10400 		err_str = "cannot get callchain buffer for func %s#%d\n";
10401 #else
10402 		err = -ENOTSUPP;
10403 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10404 #endif
10405 		if (err) {
10406 			verbose(env, err_str, func_id_name(func_id), func_id);
10407 			return err;
10408 		}
10409 
10410 		env->prog->has_callchain_buf = true;
10411 	}
10412 
10413 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10414 		env->prog->call_get_stack = true;
10415 
10416 	if (func_id == BPF_FUNC_get_func_ip) {
10417 		if (check_get_func_ip(env))
10418 			return -ENOTSUPP;
10419 		env->prog->call_get_func_ip = true;
10420 	}
10421 
10422 	if (changes_data)
10423 		clear_all_pkt_pointers(env);
10424 	return 0;
10425 }
10426 
10427 /* mark_btf_func_reg_size() is used when the reg size is determined by
10428  * the BTF func_proto's return value size and argument.
10429  */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)10430 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10431 				   size_t reg_size)
10432 {
10433 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10434 
10435 	if (regno == BPF_REG_0) {
10436 		/* Function return value */
10437 		reg->live |= REG_LIVE_WRITTEN;
10438 		reg->subreg_def = reg_size == sizeof(u64) ?
10439 			DEF_NOT_SUBREG : env->insn_idx + 1;
10440 	} else {
10441 		/* Function argument */
10442 		if (reg_size == sizeof(u64)) {
10443 			mark_insn_zext(env, reg);
10444 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10445 		} else {
10446 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10447 		}
10448 	}
10449 }
10450 
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)10451 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10452 {
10453 	return meta->kfunc_flags & KF_ACQUIRE;
10454 }
10455 
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)10456 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10457 {
10458 	return meta->kfunc_flags & KF_RELEASE;
10459 }
10460 
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)10461 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10462 {
10463 	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10464 }
10465 
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)10466 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10467 {
10468 	return meta->kfunc_flags & KF_SLEEPABLE;
10469 }
10470 
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)10471 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10472 {
10473 	return meta->kfunc_flags & KF_DESTRUCTIVE;
10474 }
10475 
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)10476 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10477 {
10478 	return meta->kfunc_flags & KF_RCU;
10479 }
10480 
__kfunc_param_match_suffix(const struct btf * btf,const struct btf_param * arg,const char * suffix)10481 static bool __kfunc_param_match_suffix(const struct btf *btf,
10482 				       const struct btf_param *arg,
10483 				       const char *suffix)
10484 {
10485 	int suffix_len = strlen(suffix), len;
10486 	const char *param_name;
10487 
10488 	/* In the future, this can be ported to use BTF tagging */
10489 	param_name = btf_name_by_offset(btf, arg->name_off);
10490 	if (str_is_empty(param_name))
10491 		return false;
10492 	len = strlen(param_name);
10493 	if (len < suffix_len)
10494 		return false;
10495 	param_name += len - suffix_len;
10496 	return !strncmp(param_name, suffix, suffix_len);
10497 }
10498 
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10499 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10500 				  const struct btf_param *arg,
10501 				  const struct bpf_reg_state *reg)
10502 {
10503 	const struct btf_type *t;
10504 
10505 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10506 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10507 		return false;
10508 
10509 	return __kfunc_param_match_suffix(btf, arg, "__sz");
10510 }
10511 
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10512 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10513 					const struct btf_param *arg,
10514 					const struct bpf_reg_state *reg)
10515 {
10516 	const struct btf_type *t;
10517 
10518 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10519 	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10520 		return false;
10521 
10522 	return __kfunc_param_match_suffix(btf, arg, "__szk");
10523 }
10524 
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)10525 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10526 {
10527 	return __kfunc_param_match_suffix(btf, arg, "__opt");
10528 }
10529 
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)10530 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10531 {
10532 	return __kfunc_param_match_suffix(btf, arg, "__k");
10533 }
10534 
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)10535 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10536 {
10537 	return __kfunc_param_match_suffix(btf, arg, "__ign");
10538 }
10539 
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)10540 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10541 {
10542 	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10543 }
10544 
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)10545 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10546 {
10547 	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10548 }
10549 
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)10550 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10551 {
10552 	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10553 }
10554 
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)10555 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10556 					  const struct btf_param *arg,
10557 					  const char *name)
10558 {
10559 	int len, target_len = strlen(name);
10560 	const char *param_name;
10561 
10562 	param_name = btf_name_by_offset(btf, arg->name_off);
10563 	if (str_is_empty(param_name))
10564 		return false;
10565 	len = strlen(param_name);
10566 	if (len != target_len)
10567 		return false;
10568 	if (strcmp(param_name, name))
10569 		return false;
10570 
10571 	return true;
10572 }
10573 
10574 enum {
10575 	KF_ARG_DYNPTR_ID,
10576 	KF_ARG_LIST_HEAD_ID,
10577 	KF_ARG_LIST_NODE_ID,
10578 	KF_ARG_RB_ROOT_ID,
10579 	KF_ARG_RB_NODE_ID,
10580 };
10581 
10582 BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr_kern)10583 BTF_ID(struct, bpf_dynptr_kern)
10584 BTF_ID(struct, bpf_list_head)
10585 BTF_ID(struct, bpf_list_node)
10586 BTF_ID(struct, bpf_rb_root)
10587 BTF_ID(struct, bpf_rb_node)
10588 
10589 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10590 				    const struct btf_param *arg, int type)
10591 {
10592 	const struct btf_type *t;
10593 	u32 res_id;
10594 
10595 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10596 	if (!t)
10597 		return false;
10598 	if (!btf_type_is_ptr(t))
10599 		return false;
10600 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10601 	if (!t)
10602 		return false;
10603 	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10604 }
10605 
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)10606 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10607 {
10608 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10609 }
10610 
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)10611 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10612 {
10613 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10614 }
10615 
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)10616 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10617 {
10618 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10619 }
10620 
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)10621 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10622 {
10623 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10624 }
10625 
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)10626 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10627 {
10628 	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10629 }
10630 
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)10631 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10632 				  const struct btf_param *arg)
10633 {
10634 	const struct btf_type *t;
10635 
10636 	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10637 	if (!t)
10638 		return false;
10639 
10640 	return true;
10641 }
10642 
10643 /* 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)10644 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10645 					const struct btf *btf,
10646 					const struct btf_type *t, int rec)
10647 {
10648 	const struct btf_type *member_type;
10649 	const struct btf_member *member;
10650 	u32 i;
10651 
10652 	if (!btf_type_is_struct(t))
10653 		return false;
10654 
10655 	for_each_member(i, t, member) {
10656 		const struct btf_array *array;
10657 
10658 		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10659 		if (btf_type_is_struct(member_type)) {
10660 			if (rec >= 3) {
10661 				verbose(env, "max struct nesting depth exceeded\n");
10662 				return false;
10663 			}
10664 			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10665 				return false;
10666 			continue;
10667 		}
10668 		if (btf_type_is_array(member_type)) {
10669 			array = btf_array(member_type);
10670 			if (!array->nelems)
10671 				return false;
10672 			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10673 			if (!btf_type_is_scalar(member_type))
10674 				return false;
10675 			continue;
10676 		}
10677 		if (!btf_type_is_scalar(member_type))
10678 			return false;
10679 	}
10680 	return true;
10681 }
10682 
10683 enum kfunc_ptr_arg_type {
10684 	KF_ARG_PTR_TO_CTX,
10685 	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10686 	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10687 	KF_ARG_PTR_TO_DYNPTR,
10688 	KF_ARG_PTR_TO_ITER,
10689 	KF_ARG_PTR_TO_LIST_HEAD,
10690 	KF_ARG_PTR_TO_LIST_NODE,
10691 	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10692 	KF_ARG_PTR_TO_MEM,
10693 	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10694 	KF_ARG_PTR_TO_CALLBACK,
10695 	KF_ARG_PTR_TO_RB_ROOT,
10696 	KF_ARG_PTR_TO_RB_NODE,
10697 };
10698 
10699 enum special_kfunc_type {
10700 	KF_bpf_obj_new_impl,
10701 	KF_bpf_obj_drop_impl,
10702 	KF_bpf_refcount_acquire_impl,
10703 	KF_bpf_list_push_front_impl,
10704 	KF_bpf_list_push_back_impl,
10705 	KF_bpf_list_pop_front,
10706 	KF_bpf_list_pop_back,
10707 	KF_bpf_cast_to_kern_ctx,
10708 	KF_bpf_rdonly_cast,
10709 	KF_bpf_rcu_read_lock,
10710 	KF_bpf_rcu_read_unlock,
10711 	KF_bpf_rbtree_remove,
10712 	KF_bpf_rbtree_add_impl,
10713 	KF_bpf_rbtree_first,
10714 	KF_bpf_dynptr_from_skb,
10715 	KF_bpf_dynptr_from_xdp,
10716 	KF_bpf_dynptr_slice,
10717 	KF_bpf_dynptr_slice_rdwr,
10718 	KF_bpf_dynptr_clone,
10719 };
10720 
10721 BTF_SET_START(special_kfunc_set)
BTF_ID(func,bpf_obj_new_impl)10722 BTF_ID(func, bpf_obj_new_impl)
10723 BTF_ID(func, bpf_obj_drop_impl)
10724 BTF_ID(func, bpf_refcount_acquire_impl)
10725 BTF_ID(func, bpf_list_push_front_impl)
10726 BTF_ID(func, bpf_list_push_back_impl)
10727 BTF_ID(func, bpf_list_pop_front)
10728 BTF_ID(func, bpf_list_pop_back)
10729 BTF_ID(func, bpf_cast_to_kern_ctx)
10730 BTF_ID(func, bpf_rdonly_cast)
10731 BTF_ID(func, bpf_rbtree_remove)
10732 BTF_ID(func, bpf_rbtree_add_impl)
10733 BTF_ID(func, bpf_rbtree_first)
10734 BTF_ID(func, bpf_dynptr_from_skb)
10735 BTF_ID(func, bpf_dynptr_from_xdp)
10736 BTF_ID(func, bpf_dynptr_slice)
10737 BTF_ID(func, bpf_dynptr_slice_rdwr)
10738 BTF_ID(func, bpf_dynptr_clone)
10739 BTF_SET_END(special_kfunc_set)
10740 
10741 BTF_ID_LIST(special_kfunc_list)
10742 BTF_ID(func, bpf_obj_new_impl)
10743 BTF_ID(func, bpf_obj_drop_impl)
10744 BTF_ID(func, bpf_refcount_acquire_impl)
10745 BTF_ID(func, bpf_list_push_front_impl)
10746 BTF_ID(func, bpf_list_push_back_impl)
10747 BTF_ID(func, bpf_list_pop_front)
10748 BTF_ID(func, bpf_list_pop_back)
10749 BTF_ID(func, bpf_cast_to_kern_ctx)
10750 BTF_ID(func, bpf_rdonly_cast)
10751 BTF_ID(func, bpf_rcu_read_lock)
10752 BTF_ID(func, bpf_rcu_read_unlock)
10753 BTF_ID(func, bpf_rbtree_remove)
10754 BTF_ID(func, bpf_rbtree_add_impl)
10755 BTF_ID(func, bpf_rbtree_first)
10756 BTF_ID(func, bpf_dynptr_from_skb)
10757 BTF_ID(func, bpf_dynptr_from_xdp)
10758 BTF_ID(func, bpf_dynptr_slice)
10759 BTF_ID(func, bpf_dynptr_slice_rdwr)
10760 BTF_ID(func, bpf_dynptr_clone)
10761 
10762 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10763 {
10764 	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10765 	    meta->arg_owning_ref) {
10766 		return false;
10767 	}
10768 
10769 	return meta->kfunc_flags & KF_RET_NULL;
10770 }
10771 
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)10772 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10773 {
10774 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10775 }
10776 
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)10777 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10778 {
10779 	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10780 }
10781 
10782 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)10783 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10784 		       struct bpf_kfunc_call_arg_meta *meta,
10785 		       const struct btf_type *t, const struct btf_type *ref_t,
10786 		       const char *ref_tname, const struct btf_param *args,
10787 		       int argno, int nargs)
10788 {
10789 	u32 regno = argno + 1;
10790 	struct bpf_reg_state *regs = cur_regs(env);
10791 	struct bpf_reg_state *reg = &regs[regno];
10792 	bool arg_mem_size = false;
10793 
10794 	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10795 		return KF_ARG_PTR_TO_CTX;
10796 
10797 	/* In this function, we verify the kfunc's BTF as per the argument type,
10798 	 * leaving the rest of the verification with respect to the register
10799 	 * type to our caller. When a set of conditions hold in the BTF type of
10800 	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10801 	 */
10802 	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10803 		return KF_ARG_PTR_TO_CTX;
10804 
10805 	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10806 		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10807 
10808 	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10809 		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10810 
10811 	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10812 		return KF_ARG_PTR_TO_DYNPTR;
10813 
10814 	if (is_kfunc_arg_iter(meta, argno))
10815 		return KF_ARG_PTR_TO_ITER;
10816 
10817 	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10818 		return KF_ARG_PTR_TO_LIST_HEAD;
10819 
10820 	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10821 		return KF_ARG_PTR_TO_LIST_NODE;
10822 
10823 	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10824 		return KF_ARG_PTR_TO_RB_ROOT;
10825 
10826 	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10827 		return KF_ARG_PTR_TO_RB_NODE;
10828 
10829 	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10830 		if (!btf_type_is_struct(ref_t)) {
10831 			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10832 				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10833 			return -EINVAL;
10834 		}
10835 		return KF_ARG_PTR_TO_BTF_ID;
10836 	}
10837 
10838 	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10839 		return KF_ARG_PTR_TO_CALLBACK;
10840 
10841 
10842 	if (argno + 1 < nargs &&
10843 	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10844 	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10845 		arg_mem_size = true;
10846 
10847 	/* This is the catch all argument type of register types supported by
10848 	 * check_helper_mem_access. However, we only allow when argument type is
10849 	 * pointer to scalar, or struct composed (recursively) of scalars. When
10850 	 * arg_mem_size is true, the pointer can be void *.
10851 	 */
10852 	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10853 	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10854 		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10855 			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10856 		return -EINVAL;
10857 	}
10858 	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10859 }
10860 
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)10861 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10862 					struct bpf_reg_state *reg,
10863 					const struct btf_type *ref_t,
10864 					const char *ref_tname, u32 ref_id,
10865 					struct bpf_kfunc_call_arg_meta *meta,
10866 					int argno)
10867 {
10868 	const struct btf_type *reg_ref_t;
10869 	bool strict_type_match = false;
10870 	const struct btf *reg_btf;
10871 	const char *reg_ref_tname;
10872 	u32 reg_ref_id;
10873 
10874 	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10875 		reg_btf = reg->btf;
10876 		reg_ref_id = reg->btf_id;
10877 	} else {
10878 		reg_btf = btf_vmlinux;
10879 		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10880 	}
10881 
10882 	/* Enforce strict type matching for calls to kfuncs that are acquiring
10883 	 * or releasing a reference, or are no-cast aliases. We do _not_
10884 	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10885 	 * as we want to enable BPF programs to pass types that are bitwise
10886 	 * equivalent without forcing them to explicitly cast with something
10887 	 * like bpf_cast_to_kern_ctx().
10888 	 *
10889 	 * For example, say we had a type like the following:
10890 	 *
10891 	 * struct bpf_cpumask {
10892 	 *	cpumask_t cpumask;
10893 	 *	refcount_t usage;
10894 	 * };
10895 	 *
10896 	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10897 	 * to a struct cpumask, so it would be safe to pass a struct
10898 	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10899 	 *
10900 	 * The philosophy here is similar to how we allow scalars of different
10901 	 * types to be passed to kfuncs as long as the size is the same. The
10902 	 * only difference here is that we're simply allowing
10903 	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10904 	 * resolve types.
10905 	 */
10906 	if (is_kfunc_acquire(meta) ||
10907 	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10908 	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10909 		strict_type_match = true;
10910 
10911 	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10912 
10913 	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10914 	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10915 	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10916 		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10917 			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10918 			btf_type_str(reg_ref_t), reg_ref_tname);
10919 		return -EINVAL;
10920 	}
10921 	return 0;
10922 }
10923 
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)10924 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10925 {
10926 	struct bpf_verifier_state *state = env->cur_state;
10927 	struct btf_record *rec = reg_btf_record(reg);
10928 
10929 	if (!state->active_lock.ptr) {
10930 		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10931 		return -EFAULT;
10932 	}
10933 
10934 	if (type_flag(reg->type) & NON_OWN_REF) {
10935 		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10936 		return -EFAULT;
10937 	}
10938 
10939 	reg->type |= NON_OWN_REF;
10940 	if (rec->refcount_off >= 0)
10941 		reg->type |= MEM_RCU;
10942 
10943 	return 0;
10944 }
10945 
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)10946 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10947 {
10948 	struct bpf_func_state *state, *unused;
10949 	struct bpf_reg_state *reg;
10950 	int i;
10951 
10952 	state = cur_func(env);
10953 
10954 	if (!ref_obj_id) {
10955 		verbose(env, "verifier internal error: ref_obj_id is zero for "
10956 			     "owning -> non-owning conversion\n");
10957 		return -EFAULT;
10958 	}
10959 
10960 	for (i = 0; i < state->acquired_refs; i++) {
10961 		if (state->refs[i].id != ref_obj_id)
10962 			continue;
10963 
10964 		/* Clear ref_obj_id here so release_reference doesn't clobber
10965 		 * the whole reg
10966 		 */
10967 		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10968 			if (reg->ref_obj_id == ref_obj_id) {
10969 				reg->ref_obj_id = 0;
10970 				ref_set_non_owning(env, reg);
10971 			}
10972 		}));
10973 		return 0;
10974 	}
10975 
10976 	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10977 	return -EFAULT;
10978 }
10979 
10980 /* Implementation details:
10981  *
10982  * Each register points to some region of memory, which we define as an
10983  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10984  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10985  * allocation. The lock and the data it protects are colocated in the same
10986  * memory region.
10987  *
10988  * Hence, everytime a register holds a pointer value pointing to such
10989  * allocation, the verifier preserves a unique reg->id for it.
10990  *
10991  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10992  * bpf_spin_lock is called.
10993  *
10994  * To enable this, lock state in the verifier captures two values:
10995  *	active_lock.ptr = Register's type specific pointer
10996  *	active_lock.id  = A unique ID for each register pointer value
10997  *
10998  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10999  * supported register types.
11000  *
11001  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11002  * allocated objects is the reg->btf pointer.
11003  *
11004  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11005  * can establish the provenance of the map value statically for each distinct
11006  * lookup into such maps. They always contain a single map value hence unique
11007  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11008  *
11009  * So, in case of global variables, they use array maps with max_entries = 1,
11010  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11011  * into the same map value as max_entries is 1, as described above).
11012  *
11013  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11014  * outer map pointer (in verifier context), but each lookup into an inner map
11015  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11016  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11017  * will get different reg->id assigned to each lookup, hence different
11018  * active_lock.id.
11019  *
11020  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11021  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11022  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11023  */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)11024 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11025 {
11026 	void *ptr;
11027 	u32 id;
11028 
11029 	switch ((int)reg->type) {
11030 	case PTR_TO_MAP_VALUE:
11031 		ptr = reg->map_ptr;
11032 		break;
11033 	case PTR_TO_BTF_ID | MEM_ALLOC:
11034 		ptr = reg->btf;
11035 		break;
11036 	default:
11037 		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11038 		return -EFAULT;
11039 	}
11040 	id = reg->id;
11041 
11042 	if (!env->cur_state->active_lock.ptr)
11043 		return -EINVAL;
11044 	if (env->cur_state->active_lock.ptr != ptr ||
11045 	    env->cur_state->active_lock.id != id) {
11046 		verbose(env, "held lock and object are not in the same allocation\n");
11047 		return -EINVAL;
11048 	}
11049 	return 0;
11050 }
11051 
is_bpf_list_api_kfunc(u32 btf_id)11052 static bool is_bpf_list_api_kfunc(u32 btf_id)
11053 {
11054 	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11055 	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11056 	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11057 	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11058 }
11059 
is_bpf_rbtree_api_kfunc(u32 btf_id)11060 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11061 {
11062 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11063 	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11064 	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11065 }
11066 
is_bpf_graph_api_kfunc(u32 btf_id)11067 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11068 {
11069 	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11070 	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11071 }
11072 
is_sync_callback_calling_kfunc(u32 btf_id)11073 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11074 {
11075 	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11076 }
11077 
is_rbtree_lock_required_kfunc(u32 btf_id)11078 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11079 {
11080 	return is_bpf_rbtree_api_kfunc(btf_id);
11081 }
11082 
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)11083 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11084 					  enum btf_field_type head_field_type,
11085 					  u32 kfunc_btf_id)
11086 {
11087 	bool ret;
11088 
11089 	switch (head_field_type) {
11090 	case BPF_LIST_HEAD:
11091 		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11092 		break;
11093 	case BPF_RB_ROOT:
11094 		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11095 		break;
11096 	default:
11097 		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11098 			btf_field_type_name(head_field_type));
11099 		return false;
11100 	}
11101 
11102 	if (!ret)
11103 		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11104 			btf_field_type_name(head_field_type));
11105 	return ret;
11106 }
11107 
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)11108 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11109 					  enum btf_field_type node_field_type,
11110 					  u32 kfunc_btf_id)
11111 {
11112 	bool ret;
11113 
11114 	switch (node_field_type) {
11115 	case BPF_LIST_NODE:
11116 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11117 		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11118 		break;
11119 	case BPF_RB_NODE:
11120 		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11121 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11122 		break;
11123 	default:
11124 		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11125 			btf_field_type_name(node_field_type));
11126 		return false;
11127 	}
11128 
11129 	if (!ret)
11130 		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11131 			btf_field_type_name(node_field_type));
11132 	return ret;
11133 }
11134 
11135 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)11136 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11137 				   struct bpf_reg_state *reg, u32 regno,
11138 				   struct bpf_kfunc_call_arg_meta *meta,
11139 				   enum btf_field_type head_field_type,
11140 				   struct btf_field **head_field)
11141 {
11142 	const char *head_type_name;
11143 	struct btf_field *field;
11144 	struct btf_record *rec;
11145 	u32 head_off;
11146 
11147 	if (meta->btf != btf_vmlinux) {
11148 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11149 		return -EFAULT;
11150 	}
11151 
11152 	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11153 		return -EFAULT;
11154 
11155 	head_type_name = btf_field_type_name(head_field_type);
11156 	if (!tnum_is_const(reg->var_off)) {
11157 		verbose(env,
11158 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11159 			regno, head_type_name);
11160 		return -EINVAL;
11161 	}
11162 
11163 	rec = reg_btf_record(reg);
11164 	head_off = reg->off + reg->var_off.value;
11165 	field = btf_record_find(rec, head_off, head_field_type);
11166 	if (!field) {
11167 		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11168 		return -EINVAL;
11169 	}
11170 
11171 	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11172 	if (check_reg_allocation_locked(env, reg)) {
11173 		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11174 			rec->spin_lock_off, head_type_name);
11175 		return -EINVAL;
11176 	}
11177 
11178 	if (*head_field) {
11179 		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11180 		return -EFAULT;
11181 	}
11182 	*head_field = field;
11183 	return 0;
11184 }
11185 
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)11186 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11187 					   struct bpf_reg_state *reg, u32 regno,
11188 					   struct bpf_kfunc_call_arg_meta *meta)
11189 {
11190 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11191 							  &meta->arg_list_head.field);
11192 }
11193 
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)11194 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11195 					     struct bpf_reg_state *reg, u32 regno,
11196 					     struct bpf_kfunc_call_arg_meta *meta)
11197 {
11198 	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11199 							  &meta->arg_rbtree_root.field);
11200 }
11201 
11202 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)11203 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11204 				   struct bpf_reg_state *reg, u32 regno,
11205 				   struct bpf_kfunc_call_arg_meta *meta,
11206 				   enum btf_field_type head_field_type,
11207 				   enum btf_field_type node_field_type,
11208 				   struct btf_field **node_field)
11209 {
11210 	const char *node_type_name;
11211 	const struct btf_type *et, *t;
11212 	struct btf_field *field;
11213 	u32 node_off;
11214 
11215 	if (meta->btf != btf_vmlinux) {
11216 		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11217 		return -EFAULT;
11218 	}
11219 
11220 	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11221 		return -EFAULT;
11222 
11223 	node_type_name = btf_field_type_name(node_field_type);
11224 	if (!tnum_is_const(reg->var_off)) {
11225 		verbose(env,
11226 			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11227 			regno, node_type_name);
11228 		return -EINVAL;
11229 	}
11230 
11231 	node_off = reg->off + reg->var_off.value;
11232 	field = reg_find_field_offset(reg, node_off, node_field_type);
11233 	if (!field || field->offset != node_off) {
11234 		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11235 		return -EINVAL;
11236 	}
11237 
11238 	field = *node_field;
11239 
11240 	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11241 	t = btf_type_by_id(reg->btf, reg->btf_id);
11242 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11243 				  field->graph_root.value_btf_id, true)) {
11244 		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11245 			"in struct %s, but arg is at offset=%d in struct %s\n",
11246 			btf_field_type_name(head_field_type),
11247 			btf_field_type_name(node_field_type),
11248 			field->graph_root.node_offset,
11249 			btf_name_by_offset(field->graph_root.btf, et->name_off),
11250 			node_off, btf_name_by_offset(reg->btf, t->name_off));
11251 		return -EINVAL;
11252 	}
11253 	meta->arg_btf = reg->btf;
11254 	meta->arg_btf_id = reg->btf_id;
11255 
11256 	if (node_off != field->graph_root.node_offset) {
11257 		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11258 			node_off, btf_field_type_name(node_field_type),
11259 			field->graph_root.node_offset,
11260 			btf_name_by_offset(field->graph_root.btf, et->name_off));
11261 		return -EINVAL;
11262 	}
11263 
11264 	return 0;
11265 }
11266 
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)11267 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11268 					   struct bpf_reg_state *reg, u32 regno,
11269 					   struct bpf_kfunc_call_arg_meta *meta)
11270 {
11271 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11272 						  BPF_LIST_HEAD, BPF_LIST_NODE,
11273 						  &meta->arg_list_head.field);
11274 }
11275 
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)11276 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11277 					     struct bpf_reg_state *reg, u32 regno,
11278 					     struct bpf_kfunc_call_arg_meta *meta)
11279 {
11280 	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11281 						  BPF_RB_ROOT, BPF_RB_NODE,
11282 						  &meta->arg_rbtree_root.field);
11283 }
11284 
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)11285 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11286 			    int insn_idx)
11287 {
11288 	const char *func_name = meta->func_name, *ref_tname;
11289 	const struct btf *btf = meta->btf;
11290 	const struct btf_param *args;
11291 	struct btf_record *rec;
11292 	u32 i, nargs;
11293 	int ret;
11294 
11295 	args = (const struct btf_param *)(meta->func_proto + 1);
11296 	nargs = btf_type_vlen(meta->func_proto);
11297 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11298 		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11299 			MAX_BPF_FUNC_REG_ARGS);
11300 		return -EINVAL;
11301 	}
11302 
11303 	/* Check that BTF function arguments match actual types that the
11304 	 * verifier sees.
11305 	 */
11306 	for (i = 0; i < nargs; i++) {
11307 		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11308 		const struct btf_type *t, *ref_t, *resolve_ret;
11309 		enum bpf_arg_type arg_type = ARG_DONTCARE;
11310 		u32 regno = i + 1, ref_id, type_size;
11311 		bool is_ret_buf_sz = false;
11312 		int kf_arg_type;
11313 
11314 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11315 
11316 		if (is_kfunc_arg_ignore(btf, &args[i]))
11317 			continue;
11318 
11319 		if (btf_type_is_scalar(t)) {
11320 			if (reg->type != SCALAR_VALUE) {
11321 				verbose(env, "R%d is not a scalar\n", regno);
11322 				return -EINVAL;
11323 			}
11324 
11325 			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11326 				if (meta->arg_constant.found) {
11327 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11328 					return -EFAULT;
11329 				}
11330 				if (!tnum_is_const(reg->var_off)) {
11331 					verbose(env, "R%d must be a known constant\n", regno);
11332 					return -EINVAL;
11333 				}
11334 				ret = mark_chain_precision(env, regno);
11335 				if (ret < 0)
11336 					return ret;
11337 				meta->arg_constant.found = true;
11338 				meta->arg_constant.value = reg->var_off.value;
11339 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11340 				meta->r0_rdonly = true;
11341 				is_ret_buf_sz = true;
11342 			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11343 				is_ret_buf_sz = true;
11344 			}
11345 
11346 			if (is_ret_buf_sz) {
11347 				if (meta->r0_size) {
11348 					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11349 					return -EINVAL;
11350 				}
11351 
11352 				if (!tnum_is_const(reg->var_off)) {
11353 					verbose(env, "R%d is not a const\n", regno);
11354 					return -EINVAL;
11355 				}
11356 
11357 				meta->r0_size = reg->var_off.value;
11358 				ret = mark_chain_precision(env, regno);
11359 				if (ret)
11360 					return ret;
11361 			}
11362 			continue;
11363 		}
11364 
11365 		if (!btf_type_is_ptr(t)) {
11366 			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11367 			return -EINVAL;
11368 		}
11369 
11370 		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11371 		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11372 			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11373 			return -EACCES;
11374 		}
11375 
11376 		if (reg->ref_obj_id) {
11377 			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11378 				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11379 					regno, reg->ref_obj_id,
11380 					meta->ref_obj_id);
11381 				return -EFAULT;
11382 			}
11383 			meta->ref_obj_id = reg->ref_obj_id;
11384 			if (is_kfunc_release(meta))
11385 				meta->release_regno = regno;
11386 		}
11387 
11388 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11389 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11390 
11391 		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11392 		if (kf_arg_type < 0)
11393 			return kf_arg_type;
11394 
11395 		switch (kf_arg_type) {
11396 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11397 		case KF_ARG_PTR_TO_BTF_ID:
11398 			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11399 				break;
11400 
11401 			if (!is_trusted_reg(reg)) {
11402 				if (!is_kfunc_rcu(meta)) {
11403 					verbose(env, "R%d must be referenced or trusted\n", regno);
11404 					return -EINVAL;
11405 				}
11406 				if (!is_rcu_reg(reg)) {
11407 					verbose(env, "R%d must be a rcu pointer\n", regno);
11408 					return -EINVAL;
11409 				}
11410 			}
11411 
11412 			fallthrough;
11413 		case KF_ARG_PTR_TO_CTX:
11414 			/* Trusted arguments have the same offset checks as release arguments */
11415 			arg_type |= OBJ_RELEASE;
11416 			break;
11417 		case KF_ARG_PTR_TO_DYNPTR:
11418 		case KF_ARG_PTR_TO_ITER:
11419 		case KF_ARG_PTR_TO_LIST_HEAD:
11420 		case KF_ARG_PTR_TO_LIST_NODE:
11421 		case KF_ARG_PTR_TO_RB_ROOT:
11422 		case KF_ARG_PTR_TO_RB_NODE:
11423 		case KF_ARG_PTR_TO_MEM:
11424 		case KF_ARG_PTR_TO_MEM_SIZE:
11425 		case KF_ARG_PTR_TO_CALLBACK:
11426 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11427 			/* Trusted by default */
11428 			break;
11429 		default:
11430 			WARN_ON_ONCE(1);
11431 			return -EFAULT;
11432 		}
11433 
11434 		if (is_kfunc_release(meta) && reg->ref_obj_id)
11435 			arg_type |= OBJ_RELEASE;
11436 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11437 		if (ret < 0)
11438 			return ret;
11439 
11440 		switch (kf_arg_type) {
11441 		case KF_ARG_PTR_TO_CTX:
11442 			if (reg->type != PTR_TO_CTX) {
11443 				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11444 				return -EINVAL;
11445 			}
11446 
11447 			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11448 				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11449 				if (ret < 0)
11450 					return -EINVAL;
11451 				meta->ret_btf_id  = ret;
11452 			}
11453 			break;
11454 		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11455 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11456 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11457 				return -EINVAL;
11458 			}
11459 			if (!reg->ref_obj_id) {
11460 				verbose(env, "allocated object must be referenced\n");
11461 				return -EINVAL;
11462 			}
11463 			if (meta->btf == btf_vmlinux &&
11464 			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11465 				meta->arg_btf = reg->btf;
11466 				meta->arg_btf_id = reg->btf_id;
11467 			}
11468 			break;
11469 		case KF_ARG_PTR_TO_DYNPTR:
11470 		{
11471 			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11472 			int clone_ref_obj_id = 0;
11473 
11474 			if (reg->type != PTR_TO_STACK &&
11475 			    reg->type != CONST_PTR_TO_DYNPTR) {
11476 				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11477 				return -EINVAL;
11478 			}
11479 
11480 			if (reg->type == CONST_PTR_TO_DYNPTR)
11481 				dynptr_arg_type |= MEM_RDONLY;
11482 
11483 			if (is_kfunc_arg_uninit(btf, &args[i]))
11484 				dynptr_arg_type |= MEM_UNINIT;
11485 
11486 			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11487 				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11488 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11489 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11490 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11491 				   (dynptr_arg_type & MEM_UNINIT)) {
11492 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11493 
11494 				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11495 					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11496 					return -EFAULT;
11497 				}
11498 
11499 				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11500 				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11501 				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11502 					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11503 					return -EFAULT;
11504 				}
11505 			}
11506 
11507 			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11508 			if (ret < 0)
11509 				return ret;
11510 
11511 			if (!(dynptr_arg_type & MEM_UNINIT)) {
11512 				int id = dynptr_id(env, reg);
11513 
11514 				if (id < 0) {
11515 					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11516 					return id;
11517 				}
11518 				meta->initialized_dynptr.id = id;
11519 				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11520 				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11521 			}
11522 
11523 			break;
11524 		}
11525 		case KF_ARG_PTR_TO_ITER:
11526 			ret = process_iter_arg(env, regno, insn_idx, meta);
11527 			if (ret < 0)
11528 				return ret;
11529 			break;
11530 		case KF_ARG_PTR_TO_LIST_HEAD:
11531 			if (reg->type != PTR_TO_MAP_VALUE &&
11532 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11533 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11534 				return -EINVAL;
11535 			}
11536 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11537 				verbose(env, "allocated object must be referenced\n");
11538 				return -EINVAL;
11539 			}
11540 			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11541 			if (ret < 0)
11542 				return ret;
11543 			break;
11544 		case KF_ARG_PTR_TO_RB_ROOT:
11545 			if (reg->type != PTR_TO_MAP_VALUE &&
11546 			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11547 				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11548 				return -EINVAL;
11549 			}
11550 			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11551 				verbose(env, "allocated object must be referenced\n");
11552 				return -EINVAL;
11553 			}
11554 			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11555 			if (ret < 0)
11556 				return ret;
11557 			break;
11558 		case KF_ARG_PTR_TO_LIST_NODE:
11559 			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11560 				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11561 				return -EINVAL;
11562 			}
11563 			if (!reg->ref_obj_id) {
11564 				verbose(env, "allocated object must be referenced\n");
11565 				return -EINVAL;
11566 			}
11567 			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11568 			if (ret < 0)
11569 				return ret;
11570 			break;
11571 		case KF_ARG_PTR_TO_RB_NODE:
11572 			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11573 				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11574 					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11575 					return -EINVAL;
11576 				}
11577 				if (in_rbtree_lock_required_cb(env)) {
11578 					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11579 					return -EINVAL;
11580 				}
11581 			} else {
11582 				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11583 					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11584 					return -EINVAL;
11585 				}
11586 				if (!reg->ref_obj_id) {
11587 					verbose(env, "allocated object must be referenced\n");
11588 					return -EINVAL;
11589 				}
11590 			}
11591 
11592 			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11593 			if (ret < 0)
11594 				return ret;
11595 			break;
11596 		case KF_ARG_PTR_TO_BTF_ID:
11597 			/* Only base_type is checked, further checks are done here */
11598 			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11599 			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11600 			    !reg2btf_ids[base_type(reg->type)]) {
11601 				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11602 				verbose(env, "expected %s or socket\n",
11603 					reg_type_str(env, base_type(reg->type) |
11604 							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11605 				return -EINVAL;
11606 			}
11607 			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11608 			if (ret < 0)
11609 				return ret;
11610 			break;
11611 		case KF_ARG_PTR_TO_MEM:
11612 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11613 			if (IS_ERR(resolve_ret)) {
11614 				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11615 					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11616 				return -EINVAL;
11617 			}
11618 			ret = check_mem_reg(env, reg, regno, type_size);
11619 			if (ret < 0)
11620 				return ret;
11621 			break;
11622 		case KF_ARG_PTR_TO_MEM_SIZE:
11623 		{
11624 			struct bpf_reg_state *buff_reg = &regs[regno];
11625 			const struct btf_param *buff_arg = &args[i];
11626 			struct bpf_reg_state *size_reg = &regs[regno + 1];
11627 			const struct btf_param *size_arg = &args[i + 1];
11628 
11629 			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11630 				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11631 				if (ret < 0) {
11632 					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11633 					return ret;
11634 				}
11635 			}
11636 
11637 			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11638 				if (meta->arg_constant.found) {
11639 					verbose(env, "verifier internal error: only one constant argument permitted\n");
11640 					return -EFAULT;
11641 				}
11642 				if (!tnum_is_const(size_reg->var_off)) {
11643 					verbose(env, "R%d must be a known constant\n", regno + 1);
11644 					return -EINVAL;
11645 				}
11646 				meta->arg_constant.found = true;
11647 				meta->arg_constant.value = size_reg->var_off.value;
11648 			}
11649 
11650 			/* Skip next '__sz' or '__szk' argument */
11651 			i++;
11652 			break;
11653 		}
11654 		case KF_ARG_PTR_TO_CALLBACK:
11655 			if (reg->type != PTR_TO_FUNC) {
11656 				verbose(env, "arg%d expected pointer to func\n", i);
11657 				return -EINVAL;
11658 			}
11659 			meta->subprogno = reg->subprogno;
11660 			break;
11661 		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11662 			if (!type_is_ptr_alloc_obj(reg->type)) {
11663 				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11664 				return -EINVAL;
11665 			}
11666 			if (!type_is_non_owning_ref(reg->type))
11667 				meta->arg_owning_ref = true;
11668 
11669 			rec = reg_btf_record(reg);
11670 			if (!rec) {
11671 				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11672 				return -EFAULT;
11673 			}
11674 
11675 			if (rec->refcount_off < 0) {
11676 				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11677 				return -EINVAL;
11678 			}
11679 
11680 			meta->arg_btf = reg->btf;
11681 			meta->arg_btf_id = reg->btf_id;
11682 			break;
11683 		}
11684 	}
11685 
11686 	if (is_kfunc_release(meta) && !meta->release_regno) {
11687 		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11688 			func_name);
11689 		return -EINVAL;
11690 	}
11691 
11692 	return 0;
11693 }
11694 
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)11695 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11696 			    struct bpf_insn *insn,
11697 			    struct bpf_kfunc_call_arg_meta *meta,
11698 			    const char **kfunc_name)
11699 {
11700 	const struct btf_type *func, *func_proto;
11701 	u32 func_id, *kfunc_flags;
11702 	const char *func_name;
11703 	struct btf *desc_btf;
11704 
11705 	if (kfunc_name)
11706 		*kfunc_name = NULL;
11707 
11708 	if (!insn->imm)
11709 		return -EINVAL;
11710 
11711 	desc_btf = find_kfunc_desc_btf(env, insn->off);
11712 	if (IS_ERR(desc_btf))
11713 		return PTR_ERR(desc_btf);
11714 
11715 	func_id = insn->imm;
11716 	func = btf_type_by_id(desc_btf, func_id);
11717 	func_name = btf_name_by_offset(desc_btf, func->name_off);
11718 	if (kfunc_name)
11719 		*kfunc_name = func_name;
11720 	func_proto = btf_type_by_id(desc_btf, func->type);
11721 
11722 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11723 	if (!kfunc_flags) {
11724 		return -EACCES;
11725 	}
11726 
11727 	memset(meta, 0, sizeof(*meta));
11728 	meta->btf = desc_btf;
11729 	meta->func_id = func_id;
11730 	meta->kfunc_flags = *kfunc_flags;
11731 	meta->func_proto = func_proto;
11732 	meta->func_name = func_name;
11733 
11734 	return 0;
11735 }
11736 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11737 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11738 			    int *insn_idx_p)
11739 {
11740 	const struct btf_type *t, *ptr_type;
11741 	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11742 	struct bpf_reg_state *regs = cur_regs(env);
11743 	const char *func_name, *ptr_type_name;
11744 	bool sleepable, rcu_lock, rcu_unlock;
11745 	struct bpf_kfunc_call_arg_meta meta;
11746 	struct bpf_insn_aux_data *insn_aux;
11747 	int err, insn_idx = *insn_idx_p;
11748 	const struct btf_param *args;
11749 	const struct btf_type *ret_t;
11750 	struct btf *desc_btf;
11751 
11752 	/* skip for now, but return error when we find this in fixup_kfunc_call */
11753 	if (!insn->imm)
11754 		return 0;
11755 
11756 	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11757 	if (err == -EACCES && func_name)
11758 		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11759 	if (err)
11760 		return err;
11761 	desc_btf = meta.btf;
11762 	insn_aux = &env->insn_aux_data[insn_idx];
11763 
11764 	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11765 
11766 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11767 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11768 		return -EACCES;
11769 	}
11770 
11771 	sleepable = is_kfunc_sleepable(&meta);
11772 	if (sleepable && !env->prog->aux->sleepable) {
11773 		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11774 		return -EACCES;
11775 	}
11776 
11777 	/* Check the arguments */
11778 	err = check_kfunc_args(env, &meta, insn_idx);
11779 	if (err < 0)
11780 		return err;
11781 
11782 	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11783 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11784 					 set_rbtree_add_callback_state);
11785 		if (err) {
11786 			verbose(env, "kfunc %s#%d failed callback verification\n",
11787 				func_name, meta.func_id);
11788 			return err;
11789 		}
11790 	}
11791 
11792 	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11793 	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11794 
11795 	if (env->cur_state->active_rcu_lock) {
11796 		struct bpf_func_state *state;
11797 		struct bpf_reg_state *reg;
11798 
11799 		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11800 			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11801 			return -EACCES;
11802 		}
11803 
11804 		if (rcu_lock) {
11805 			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11806 			return -EINVAL;
11807 		} else if (rcu_unlock) {
11808 			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11809 				if (reg->type & MEM_RCU) {
11810 					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11811 					reg->type |= PTR_UNTRUSTED;
11812 				}
11813 			}));
11814 			env->cur_state->active_rcu_lock = false;
11815 		} else if (sleepable) {
11816 			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11817 			return -EACCES;
11818 		}
11819 	} else if (rcu_lock) {
11820 		env->cur_state->active_rcu_lock = true;
11821 	} else if (rcu_unlock) {
11822 		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11823 		return -EINVAL;
11824 	}
11825 
11826 	/* In case of release function, we get register number of refcounted
11827 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11828 	 */
11829 	if (meta.release_regno) {
11830 		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11831 		if (err) {
11832 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11833 				func_name, meta.func_id);
11834 			return err;
11835 		}
11836 	}
11837 
11838 	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11839 	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11840 	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11841 		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11842 		insn_aux->insert_off = regs[BPF_REG_2].off;
11843 		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11844 		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11845 		if (err) {
11846 			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11847 				func_name, meta.func_id);
11848 			return err;
11849 		}
11850 
11851 		err = release_reference(env, release_ref_obj_id);
11852 		if (err) {
11853 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11854 				func_name, meta.func_id);
11855 			return err;
11856 		}
11857 	}
11858 
11859 	for (i = 0; i < CALLER_SAVED_REGS; i++)
11860 		mark_reg_not_init(env, regs, caller_saved[i]);
11861 
11862 	/* Check return type */
11863 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11864 
11865 	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11866 		/* Only exception is bpf_obj_new_impl */
11867 		if (meta.btf != btf_vmlinux ||
11868 		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11869 		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11870 			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11871 			return -EINVAL;
11872 		}
11873 	}
11874 
11875 	if (btf_type_is_scalar(t)) {
11876 		mark_reg_unknown(env, regs, BPF_REG_0);
11877 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11878 	} else if (btf_type_is_ptr(t)) {
11879 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11880 
11881 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11882 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11883 				struct btf *ret_btf;
11884 				u32 ret_btf_id;
11885 
11886 				if (unlikely(!bpf_global_ma_set))
11887 					return -ENOMEM;
11888 
11889 				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11890 					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11891 					return -EINVAL;
11892 				}
11893 
11894 				ret_btf = env->prog->aux->btf;
11895 				ret_btf_id = meta.arg_constant.value;
11896 
11897 				/* This may be NULL due to user not supplying a BTF */
11898 				if (!ret_btf) {
11899 					verbose(env, "bpf_obj_new requires prog BTF\n");
11900 					return -EINVAL;
11901 				}
11902 
11903 				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11904 				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11905 					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11906 					return -EINVAL;
11907 				}
11908 
11909 				mark_reg_known_zero(env, regs, BPF_REG_0);
11910 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11911 				regs[BPF_REG_0].btf = ret_btf;
11912 				regs[BPF_REG_0].btf_id = ret_btf_id;
11913 
11914 				insn_aux->obj_new_size = ret_t->size;
11915 				insn_aux->kptr_struct_meta =
11916 					btf_find_struct_meta(ret_btf, ret_btf_id);
11917 			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11918 				mark_reg_known_zero(env, regs, BPF_REG_0);
11919 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11920 				regs[BPF_REG_0].btf = meta.arg_btf;
11921 				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11922 
11923 				insn_aux->kptr_struct_meta =
11924 					btf_find_struct_meta(meta.arg_btf,
11925 							     meta.arg_btf_id);
11926 			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11927 				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11928 				struct btf_field *field = meta.arg_list_head.field;
11929 
11930 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11931 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11932 				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11933 				struct btf_field *field = meta.arg_rbtree_root.field;
11934 
11935 				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11936 			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11937 				mark_reg_known_zero(env, regs, BPF_REG_0);
11938 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11939 				regs[BPF_REG_0].btf = desc_btf;
11940 				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11941 			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11942 				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11943 				if (!ret_t || !btf_type_is_struct(ret_t)) {
11944 					verbose(env,
11945 						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11946 					return -EINVAL;
11947 				}
11948 
11949 				mark_reg_known_zero(env, regs, BPF_REG_0);
11950 				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11951 				regs[BPF_REG_0].btf = desc_btf;
11952 				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11953 			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11954 				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11955 				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11956 
11957 				mark_reg_known_zero(env, regs, BPF_REG_0);
11958 
11959 				if (!meta.arg_constant.found) {
11960 					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11961 					return -EFAULT;
11962 				}
11963 
11964 				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11965 
11966 				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11967 				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11968 
11969 				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11970 					regs[BPF_REG_0].type |= MEM_RDONLY;
11971 				} else {
11972 					/* this will set env->seen_direct_write to true */
11973 					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11974 						verbose(env, "the prog does not allow writes to packet data\n");
11975 						return -EINVAL;
11976 					}
11977 				}
11978 
11979 				if (!meta.initialized_dynptr.id) {
11980 					verbose(env, "verifier internal error: no dynptr id\n");
11981 					return -EFAULT;
11982 				}
11983 				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11984 
11985 				/* we don't need to set BPF_REG_0's ref obj id
11986 				 * because packet slices are not refcounted (see
11987 				 * dynptr_type_refcounted)
11988 				 */
11989 			} else {
11990 				verbose(env, "kernel function %s unhandled dynamic return type\n",
11991 					meta.func_name);
11992 				return -EFAULT;
11993 			}
11994 		} else if (!__btf_type_is_struct(ptr_type)) {
11995 			if (!meta.r0_size) {
11996 				__u32 sz;
11997 
11998 				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11999 					meta.r0_size = sz;
12000 					meta.r0_rdonly = true;
12001 				}
12002 			}
12003 			if (!meta.r0_size) {
12004 				ptr_type_name = btf_name_by_offset(desc_btf,
12005 								   ptr_type->name_off);
12006 				verbose(env,
12007 					"kernel function %s returns pointer type %s %s is not supported\n",
12008 					func_name,
12009 					btf_type_str(ptr_type),
12010 					ptr_type_name);
12011 				return -EINVAL;
12012 			}
12013 
12014 			mark_reg_known_zero(env, regs, BPF_REG_0);
12015 			regs[BPF_REG_0].type = PTR_TO_MEM;
12016 			regs[BPF_REG_0].mem_size = meta.r0_size;
12017 
12018 			if (meta.r0_rdonly)
12019 				regs[BPF_REG_0].type |= MEM_RDONLY;
12020 
12021 			/* Ensures we don't access the memory after a release_reference() */
12022 			if (meta.ref_obj_id)
12023 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12024 		} else {
12025 			mark_reg_known_zero(env, regs, BPF_REG_0);
12026 			regs[BPF_REG_0].btf = desc_btf;
12027 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12028 			regs[BPF_REG_0].btf_id = ptr_type_id;
12029 
12030 			if (is_iter_next_kfunc(&meta)) {
12031 				struct bpf_reg_state *cur_iter;
12032 
12033 				cur_iter = get_iter_from_state(env->cur_state, &meta);
12034 
12035 				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12036 					regs[BPF_REG_0].type |= MEM_RCU;
12037 				else
12038 					regs[BPF_REG_0].type |= PTR_TRUSTED;
12039 			}
12040 		}
12041 
12042 		if (is_kfunc_ret_null(&meta)) {
12043 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12044 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12045 			regs[BPF_REG_0].id = ++env->id_gen;
12046 		}
12047 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12048 		if (is_kfunc_acquire(&meta)) {
12049 			int id = acquire_reference_state(env, insn_idx);
12050 
12051 			if (id < 0)
12052 				return id;
12053 			if (is_kfunc_ret_null(&meta))
12054 				regs[BPF_REG_0].id = id;
12055 			regs[BPF_REG_0].ref_obj_id = id;
12056 		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12057 			ref_set_non_owning(env, &regs[BPF_REG_0]);
12058 		}
12059 
12060 		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12061 			regs[BPF_REG_0].id = ++env->id_gen;
12062 	} else if (btf_type_is_void(t)) {
12063 		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12064 			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12065 				insn_aux->kptr_struct_meta =
12066 					btf_find_struct_meta(meta.arg_btf,
12067 							     meta.arg_btf_id);
12068 			}
12069 		}
12070 	}
12071 
12072 	nargs = btf_type_vlen(meta.func_proto);
12073 	args = (const struct btf_param *)(meta.func_proto + 1);
12074 	for (i = 0; i < nargs; i++) {
12075 		u32 regno = i + 1;
12076 
12077 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12078 		if (btf_type_is_ptr(t))
12079 			mark_btf_func_reg_size(env, regno, sizeof(void *));
12080 		else
12081 			/* scalar. ensured by btf_check_kfunc_arg_match() */
12082 			mark_btf_func_reg_size(env, regno, t->size);
12083 	}
12084 
12085 	if (is_iter_next_kfunc(&meta)) {
12086 		err = process_iter_next_call(env, insn_idx, &meta);
12087 		if (err)
12088 			return err;
12089 	}
12090 
12091 	return 0;
12092 }
12093 
signed_add_overflows(s64 a,s64 b)12094 static bool signed_add_overflows(s64 a, s64 b)
12095 {
12096 	/* Do the add in u64, where overflow is well-defined */
12097 	s64 res = (s64)((u64)a + (u64)b);
12098 
12099 	if (b < 0)
12100 		return res > a;
12101 	return res < a;
12102 }
12103 
signed_add32_overflows(s32 a,s32 b)12104 static bool signed_add32_overflows(s32 a, s32 b)
12105 {
12106 	/* Do the add in u32, where overflow is well-defined */
12107 	s32 res = (s32)((u32)a + (u32)b);
12108 
12109 	if (b < 0)
12110 		return res > a;
12111 	return res < a;
12112 }
12113 
signed_sub_overflows(s64 a,s64 b)12114 static bool signed_sub_overflows(s64 a, s64 b)
12115 {
12116 	/* Do the sub in u64, where overflow is well-defined */
12117 	s64 res = (s64)((u64)a - (u64)b);
12118 
12119 	if (b < 0)
12120 		return res < a;
12121 	return res > a;
12122 }
12123 
signed_sub32_overflows(s32 a,s32 b)12124 static bool signed_sub32_overflows(s32 a, s32 b)
12125 {
12126 	/* Do the sub in u32, where overflow is well-defined */
12127 	s32 res = (s32)((u32)a - (u32)b);
12128 
12129 	if (b < 0)
12130 		return res < a;
12131 	return res > a;
12132 }
12133 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)12134 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12135 				  const struct bpf_reg_state *reg,
12136 				  enum bpf_reg_type type)
12137 {
12138 	bool known = tnum_is_const(reg->var_off);
12139 	s64 val = reg->var_off.value;
12140 	s64 smin = reg->smin_value;
12141 
12142 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12143 		verbose(env, "math between %s pointer and %lld is not allowed\n",
12144 			reg_type_str(env, type), val);
12145 		return false;
12146 	}
12147 
12148 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12149 		verbose(env, "%s pointer offset %d is not allowed\n",
12150 			reg_type_str(env, type), reg->off);
12151 		return false;
12152 	}
12153 
12154 	if (smin == S64_MIN) {
12155 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12156 			reg_type_str(env, type));
12157 		return false;
12158 	}
12159 
12160 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12161 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12162 			smin, reg_type_str(env, type));
12163 		return false;
12164 	}
12165 
12166 	return true;
12167 }
12168 
12169 enum {
12170 	REASON_BOUNDS	= -1,
12171 	REASON_TYPE	= -2,
12172 	REASON_PATHS	= -3,
12173 	REASON_LIMIT	= -4,
12174 	REASON_STACK	= -5,
12175 };
12176 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)12177 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12178 			      u32 *alu_limit, bool mask_to_left)
12179 {
12180 	u32 max = 0, ptr_limit = 0;
12181 
12182 	switch (ptr_reg->type) {
12183 	case PTR_TO_STACK:
12184 		/* Offset 0 is out-of-bounds, but acceptable start for the
12185 		 * left direction, see BPF_REG_FP. Also, unknown scalar
12186 		 * offset where we would need to deal with min/max bounds is
12187 		 * currently prohibited for unprivileged.
12188 		 */
12189 		max = MAX_BPF_STACK + mask_to_left;
12190 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12191 		break;
12192 	case PTR_TO_MAP_VALUE:
12193 		max = ptr_reg->map_ptr->value_size;
12194 		ptr_limit = (mask_to_left ?
12195 			     ptr_reg->smin_value :
12196 			     ptr_reg->umax_value) + ptr_reg->off;
12197 		break;
12198 	default:
12199 		return REASON_TYPE;
12200 	}
12201 
12202 	if (ptr_limit >= max)
12203 		return REASON_LIMIT;
12204 	*alu_limit = ptr_limit;
12205 	return 0;
12206 }
12207 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)12208 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12209 				    const struct bpf_insn *insn)
12210 {
12211 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12212 }
12213 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)12214 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12215 				       u32 alu_state, u32 alu_limit)
12216 {
12217 	/* If we arrived here from different branches with different
12218 	 * state or limits to sanitize, then this won't work.
12219 	 */
12220 	if (aux->alu_state &&
12221 	    (aux->alu_state != alu_state ||
12222 	     aux->alu_limit != alu_limit))
12223 		return REASON_PATHS;
12224 
12225 	/* Corresponding fixup done in do_misc_fixups(). */
12226 	aux->alu_state = alu_state;
12227 	aux->alu_limit = alu_limit;
12228 	return 0;
12229 }
12230 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)12231 static int sanitize_val_alu(struct bpf_verifier_env *env,
12232 			    struct bpf_insn *insn)
12233 {
12234 	struct bpf_insn_aux_data *aux = cur_aux(env);
12235 
12236 	if (can_skip_alu_sanitation(env, insn))
12237 		return 0;
12238 
12239 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12240 }
12241 
sanitize_needed(u8 opcode)12242 static bool sanitize_needed(u8 opcode)
12243 {
12244 	return opcode == BPF_ADD || opcode == BPF_SUB;
12245 }
12246 
12247 struct bpf_sanitize_info {
12248 	struct bpf_insn_aux_data aux;
12249 	bool mask_to_left;
12250 };
12251 
12252 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)12253 sanitize_speculative_path(struct bpf_verifier_env *env,
12254 			  const struct bpf_insn *insn,
12255 			  u32 next_idx, u32 curr_idx)
12256 {
12257 	struct bpf_verifier_state *branch;
12258 	struct bpf_reg_state *regs;
12259 
12260 	branch = push_stack(env, next_idx, curr_idx, true);
12261 	if (branch && insn) {
12262 		regs = branch->frame[branch->curframe]->regs;
12263 		if (BPF_SRC(insn->code) == BPF_K) {
12264 			mark_reg_unknown(env, regs, insn->dst_reg);
12265 		} else if (BPF_SRC(insn->code) == BPF_X) {
12266 			mark_reg_unknown(env, regs, insn->dst_reg);
12267 			mark_reg_unknown(env, regs, insn->src_reg);
12268 		}
12269 	}
12270 	return branch;
12271 }
12272 
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)12273 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12274 			    struct bpf_insn *insn,
12275 			    const struct bpf_reg_state *ptr_reg,
12276 			    const struct bpf_reg_state *off_reg,
12277 			    struct bpf_reg_state *dst_reg,
12278 			    struct bpf_sanitize_info *info,
12279 			    const bool commit_window)
12280 {
12281 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12282 	struct bpf_verifier_state *vstate = env->cur_state;
12283 	bool off_is_imm = tnum_is_const(off_reg->var_off);
12284 	bool off_is_neg = off_reg->smin_value < 0;
12285 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12286 	u8 opcode = BPF_OP(insn->code);
12287 	u32 alu_state, alu_limit;
12288 	struct bpf_reg_state tmp;
12289 	bool ret;
12290 	int err;
12291 
12292 	if (can_skip_alu_sanitation(env, insn))
12293 		return 0;
12294 
12295 	/* We already marked aux for masking from non-speculative
12296 	 * paths, thus we got here in the first place. We only care
12297 	 * to explore bad access from here.
12298 	 */
12299 	if (vstate->speculative)
12300 		goto do_sim;
12301 
12302 	if (!commit_window) {
12303 		if (!tnum_is_const(off_reg->var_off) &&
12304 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12305 			return REASON_BOUNDS;
12306 
12307 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12308 				     (opcode == BPF_SUB && !off_is_neg);
12309 	}
12310 
12311 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12312 	if (err < 0)
12313 		return err;
12314 
12315 	if (commit_window) {
12316 		/* In commit phase we narrow the masking window based on
12317 		 * the observed pointer move after the simulated operation.
12318 		 */
12319 		alu_state = info->aux.alu_state;
12320 		alu_limit = abs(info->aux.alu_limit - alu_limit);
12321 	} else {
12322 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12323 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12324 		alu_state |= ptr_is_dst_reg ?
12325 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12326 
12327 		/* Limit pruning on unknown scalars to enable deep search for
12328 		 * potential masking differences from other program paths.
12329 		 */
12330 		if (!off_is_imm)
12331 			env->explore_alu_limits = true;
12332 	}
12333 
12334 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12335 	if (err < 0)
12336 		return err;
12337 do_sim:
12338 	/* If we're in commit phase, we're done here given we already
12339 	 * pushed the truncated dst_reg into the speculative verification
12340 	 * stack.
12341 	 *
12342 	 * Also, when register is a known constant, we rewrite register-based
12343 	 * operation to immediate-based, and thus do not need masking (and as
12344 	 * a consequence, do not need to simulate the zero-truncation either).
12345 	 */
12346 	if (commit_window || off_is_imm)
12347 		return 0;
12348 
12349 	/* Simulate and find potential out-of-bounds access under
12350 	 * speculative execution from truncation as a result of
12351 	 * masking when off was not within expected range. If off
12352 	 * sits in dst, then we temporarily need to move ptr there
12353 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12354 	 * for cases where we use K-based arithmetic in one direction
12355 	 * and truncated reg-based in the other in order to explore
12356 	 * bad access.
12357 	 */
12358 	if (!ptr_is_dst_reg) {
12359 		tmp = *dst_reg;
12360 		copy_register_state(dst_reg, ptr_reg);
12361 	}
12362 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12363 					env->insn_idx);
12364 	if (!ptr_is_dst_reg && ret)
12365 		*dst_reg = tmp;
12366 	return !ret ? REASON_STACK : 0;
12367 }
12368 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)12369 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12370 {
12371 	struct bpf_verifier_state *vstate = env->cur_state;
12372 
12373 	/* If we simulate paths under speculation, we don't update the
12374 	 * insn as 'seen' such that when we verify unreachable paths in
12375 	 * the non-speculative domain, sanitize_dead_code() can still
12376 	 * rewrite/sanitize them.
12377 	 */
12378 	if (!vstate->speculative)
12379 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12380 }
12381 
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)12382 static int sanitize_err(struct bpf_verifier_env *env,
12383 			const struct bpf_insn *insn, int reason,
12384 			const struct bpf_reg_state *off_reg,
12385 			const struct bpf_reg_state *dst_reg)
12386 {
12387 	static const char *err = "pointer arithmetic with it prohibited for !root";
12388 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12389 	u32 dst = insn->dst_reg, src = insn->src_reg;
12390 
12391 	switch (reason) {
12392 	case REASON_BOUNDS:
12393 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12394 			off_reg == dst_reg ? dst : src, err);
12395 		break;
12396 	case REASON_TYPE:
12397 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12398 			off_reg == dst_reg ? src : dst, err);
12399 		break;
12400 	case REASON_PATHS:
12401 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12402 			dst, op, err);
12403 		break;
12404 	case REASON_LIMIT:
12405 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12406 			dst, op, err);
12407 		break;
12408 	case REASON_STACK:
12409 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12410 			dst, err);
12411 		break;
12412 	default:
12413 		verbose(env, "verifier internal error: unknown reason (%d)\n",
12414 			reason);
12415 		break;
12416 	}
12417 
12418 	return -EACCES;
12419 }
12420 
12421 /* check that stack access falls within stack limits and that 'reg' doesn't
12422  * have a variable offset.
12423  *
12424  * Variable offset is prohibited for unprivileged mode for simplicity since it
12425  * requires corresponding support in Spectre masking for stack ALU.  See also
12426  * retrieve_ptr_limit().
12427  *
12428  *
12429  * 'off' includes 'reg->off'.
12430  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)12431 static int check_stack_access_for_ptr_arithmetic(
12432 				struct bpf_verifier_env *env,
12433 				int regno,
12434 				const struct bpf_reg_state *reg,
12435 				int off)
12436 {
12437 	if (!tnum_is_const(reg->var_off)) {
12438 		char tn_buf[48];
12439 
12440 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12441 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12442 			regno, tn_buf, off);
12443 		return -EACCES;
12444 	}
12445 
12446 	if (off >= 0 || off < -MAX_BPF_STACK) {
12447 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12448 			"prohibited for !root; off=%d\n", regno, off);
12449 		return -EACCES;
12450 	}
12451 
12452 	return 0;
12453 }
12454 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)12455 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12456 				 const struct bpf_insn *insn,
12457 				 const struct bpf_reg_state *dst_reg)
12458 {
12459 	u32 dst = insn->dst_reg;
12460 
12461 	/* For unprivileged we require that resulting offset must be in bounds
12462 	 * in order to be able to sanitize access later on.
12463 	 */
12464 	if (env->bypass_spec_v1)
12465 		return 0;
12466 
12467 	switch (dst_reg->type) {
12468 	case PTR_TO_STACK:
12469 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12470 					dst_reg->off + dst_reg->var_off.value))
12471 			return -EACCES;
12472 		break;
12473 	case PTR_TO_MAP_VALUE:
12474 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12475 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12476 				"prohibited for !root\n", dst);
12477 			return -EACCES;
12478 		}
12479 		break;
12480 	default:
12481 		break;
12482 	}
12483 
12484 	return 0;
12485 }
12486 
12487 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12488  * Caller should also handle BPF_MOV case separately.
12489  * If we return -EACCES, caller may want to try again treating pointer as a
12490  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12491  */
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)12492 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12493 				   struct bpf_insn *insn,
12494 				   const struct bpf_reg_state *ptr_reg,
12495 				   const struct bpf_reg_state *off_reg)
12496 {
12497 	struct bpf_verifier_state *vstate = env->cur_state;
12498 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12499 	struct bpf_reg_state *regs = state->regs, *dst_reg;
12500 	bool known = tnum_is_const(off_reg->var_off);
12501 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12502 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12503 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12504 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12505 	struct bpf_sanitize_info info = {};
12506 	u8 opcode = BPF_OP(insn->code);
12507 	u32 dst = insn->dst_reg;
12508 	int ret;
12509 
12510 	dst_reg = &regs[dst];
12511 
12512 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12513 	    smin_val > smax_val || umin_val > umax_val) {
12514 		/* Taint dst register if offset had invalid bounds derived from
12515 		 * e.g. dead branches.
12516 		 */
12517 		__mark_reg_unknown(env, dst_reg);
12518 		return 0;
12519 	}
12520 
12521 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12522 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12523 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12524 			__mark_reg_unknown(env, dst_reg);
12525 			return 0;
12526 		}
12527 
12528 		verbose(env,
12529 			"R%d 32-bit pointer arithmetic prohibited\n",
12530 			dst);
12531 		return -EACCES;
12532 	}
12533 
12534 	if (ptr_reg->type & PTR_MAYBE_NULL) {
12535 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12536 			dst, reg_type_str(env, ptr_reg->type));
12537 		return -EACCES;
12538 	}
12539 
12540 	switch (base_type(ptr_reg->type)) {
12541 	case PTR_TO_FLOW_KEYS:
12542 		if (known)
12543 			break;
12544 		fallthrough;
12545 	case CONST_PTR_TO_MAP:
12546 		/* smin_val represents the known value */
12547 		if (known && smin_val == 0 && opcode == BPF_ADD)
12548 			break;
12549 		fallthrough;
12550 	case PTR_TO_PACKET_END:
12551 	case PTR_TO_SOCKET:
12552 	case PTR_TO_SOCK_COMMON:
12553 	case PTR_TO_TCP_SOCK:
12554 	case PTR_TO_XDP_SOCK:
12555 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12556 			dst, reg_type_str(env, ptr_reg->type));
12557 		return -EACCES;
12558 	default:
12559 		break;
12560 	}
12561 
12562 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12563 	 * The id may be overwritten later if we create a new variable offset.
12564 	 */
12565 	dst_reg->type = ptr_reg->type;
12566 	dst_reg->id = ptr_reg->id;
12567 
12568 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12569 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12570 		return -EINVAL;
12571 
12572 	/* pointer types do not carry 32-bit bounds at the moment. */
12573 	__mark_reg32_unbounded(dst_reg);
12574 
12575 	if (sanitize_needed(opcode)) {
12576 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12577 				       &info, false);
12578 		if (ret < 0)
12579 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12580 	}
12581 
12582 	switch (opcode) {
12583 	case BPF_ADD:
12584 		/* We can take a fixed offset as long as it doesn't overflow
12585 		 * the s32 'off' field
12586 		 */
12587 		if (known && (ptr_reg->off + smin_val ==
12588 			      (s64)(s32)(ptr_reg->off + smin_val))) {
12589 			/* pointer += K.  Accumulate it into fixed offset */
12590 			dst_reg->smin_value = smin_ptr;
12591 			dst_reg->smax_value = smax_ptr;
12592 			dst_reg->umin_value = umin_ptr;
12593 			dst_reg->umax_value = umax_ptr;
12594 			dst_reg->var_off = ptr_reg->var_off;
12595 			dst_reg->off = ptr_reg->off + smin_val;
12596 			dst_reg->raw = ptr_reg->raw;
12597 			break;
12598 		}
12599 		/* A new variable offset is created.  Note that off_reg->off
12600 		 * == 0, since it's a scalar.
12601 		 * dst_reg gets the pointer type and since some positive
12602 		 * integer value was added to the pointer, give it a new 'id'
12603 		 * if it's a PTR_TO_PACKET.
12604 		 * this creates a new 'base' pointer, off_reg (variable) gets
12605 		 * added into the variable offset, and we copy the fixed offset
12606 		 * from ptr_reg.
12607 		 */
12608 		if (signed_add_overflows(smin_ptr, smin_val) ||
12609 		    signed_add_overflows(smax_ptr, smax_val)) {
12610 			dst_reg->smin_value = S64_MIN;
12611 			dst_reg->smax_value = S64_MAX;
12612 		} else {
12613 			dst_reg->smin_value = smin_ptr + smin_val;
12614 			dst_reg->smax_value = smax_ptr + smax_val;
12615 		}
12616 		if (umin_ptr + umin_val < umin_ptr ||
12617 		    umax_ptr + umax_val < umax_ptr) {
12618 			dst_reg->umin_value = 0;
12619 			dst_reg->umax_value = U64_MAX;
12620 		} else {
12621 			dst_reg->umin_value = umin_ptr + umin_val;
12622 			dst_reg->umax_value = umax_ptr + umax_val;
12623 		}
12624 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12625 		dst_reg->off = ptr_reg->off;
12626 		dst_reg->raw = ptr_reg->raw;
12627 		if (reg_is_pkt_pointer(ptr_reg)) {
12628 			dst_reg->id = ++env->id_gen;
12629 			/* something was added to pkt_ptr, set range to zero */
12630 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12631 		}
12632 		break;
12633 	case BPF_SUB:
12634 		if (dst_reg == off_reg) {
12635 			/* scalar -= pointer.  Creates an unknown scalar */
12636 			verbose(env, "R%d tried to subtract pointer from scalar\n",
12637 				dst);
12638 			return -EACCES;
12639 		}
12640 		/* We don't allow subtraction from FP, because (according to
12641 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12642 		 * be able to deal with it.
12643 		 */
12644 		if (ptr_reg->type == PTR_TO_STACK) {
12645 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12646 				dst);
12647 			return -EACCES;
12648 		}
12649 		if (known && (ptr_reg->off - smin_val ==
12650 			      (s64)(s32)(ptr_reg->off - smin_val))) {
12651 			/* pointer -= K.  Subtract it from fixed offset */
12652 			dst_reg->smin_value = smin_ptr;
12653 			dst_reg->smax_value = smax_ptr;
12654 			dst_reg->umin_value = umin_ptr;
12655 			dst_reg->umax_value = umax_ptr;
12656 			dst_reg->var_off = ptr_reg->var_off;
12657 			dst_reg->id = ptr_reg->id;
12658 			dst_reg->off = ptr_reg->off - smin_val;
12659 			dst_reg->raw = ptr_reg->raw;
12660 			break;
12661 		}
12662 		/* A new variable offset is created.  If the subtrahend is known
12663 		 * nonnegative, then any reg->range we had before is still good.
12664 		 */
12665 		if (signed_sub_overflows(smin_ptr, smax_val) ||
12666 		    signed_sub_overflows(smax_ptr, smin_val)) {
12667 			/* Overflow possible, we know nothing */
12668 			dst_reg->smin_value = S64_MIN;
12669 			dst_reg->smax_value = S64_MAX;
12670 		} else {
12671 			dst_reg->smin_value = smin_ptr - smax_val;
12672 			dst_reg->smax_value = smax_ptr - smin_val;
12673 		}
12674 		if (umin_ptr < umax_val) {
12675 			/* Overflow possible, we know nothing */
12676 			dst_reg->umin_value = 0;
12677 			dst_reg->umax_value = U64_MAX;
12678 		} else {
12679 			/* Cannot overflow (as long as bounds are consistent) */
12680 			dst_reg->umin_value = umin_ptr - umax_val;
12681 			dst_reg->umax_value = umax_ptr - umin_val;
12682 		}
12683 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12684 		dst_reg->off = ptr_reg->off;
12685 		dst_reg->raw = ptr_reg->raw;
12686 		if (reg_is_pkt_pointer(ptr_reg)) {
12687 			dst_reg->id = ++env->id_gen;
12688 			/* something was added to pkt_ptr, set range to zero */
12689 			if (smin_val < 0)
12690 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12691 		}
12692 		break;
12693 	case BPF_AND:
12694 	case BPF_OR:
12695 	case BPF_XOR:
12696 		/* bitwise ops on pointers are troublesome, prohibit. */
12697 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12698 			dst, bpf_alu_string[opcode >> 4]);
12699 		return -EACCES;
12700 	default:
12701 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12702 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12703 			dst, bpf_alu_string[opcode >> 4]);
12704 		return -EACCES;
12705 	}
12706 
12707 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12708 		return -EINVAL;
12709 	reg_bounds_sync(dst_reg);
12710 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12711 		return -EACCES;
12712 	if (sanitize_needed(opcode)) {
12713 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12714 				       &info, true);
12715 		if (ret < 0)
12716 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12717 	}
12718 
12719 	return 0;
12720 }
12721 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12722 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12723 				 struct bpf_reg_state *src_reg)
12724 {
12725 	s32 smin_val = src_reg->s32_min_value;
12726 	s32 smax_val = src_reg->s32_max_value;
12727 	u32 umin_val = src_reg->u32_min_value;
12728 	u32 umax_val = src_reg->u32_max_value;
12729 
12730 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12731 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12732 		dst_reg->s32_min_value = S32_MIN;
12733 		dst_reg->s32_max_value = S32_MAX;
12734 	} else {
12735 		dst_reg->s32_min_value += smin_val;
12736 		dst_reg->s32_max_value += smax_val;
12737 	}
12738 	if (dst_reg->u32_min_value + umin_val < umin_val ||
12739 	    dst_reg->u32_max_value + umax_val < umax_val) {
12740 		dst_reg->u32_min_value = 0;
12741 		dst_reg->u32_max_value = U32_MAX;
12742 	} else {
12743 		dst_reg->u32_min_value += umin_val;
12744 		dst_reg->u32_max_value += umax_val;
12745 	}
12746 }
12747 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12748 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12749 			       struct bpf_reg_state *src_reg)
12750 {
12751 	s64 smin_val = src_reg->smin_value;
12752 	s64 smax_val = src_reg->smax_value;
12753 	u64 umin_val = src_reg->umin_value;
12754 	u64 umax_val = src_reg->umax_value;
12755 
12756 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12757 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12758 		dst_reg->smin_value = S64_MIN;
12759 		dst_reg->smax_value = S64_MAX;
12760 	} else {
12761 		dst_reg->smin_value += smin_val;
12762 		dst_reg->smax_value += smax_val;
12763 	}
12764 	if (dst_reg->umin_value + umin_val < umin_val ||
12765 	    dst_reg->umax_value + umax_val < umax_val) {
12766 		dst_reg->umin_value = 0;
12767 		dst_reg->umax_value = U64_MAX;
12768 	} else {
12769 		dst_reg->umin_value += umin_val;
12770 		dst_reg->umax_value += umax_val;
12771 	}
12772 }
12773 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12774 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12775 				 struct bpf_reg_state *src_reg)
12776 {
12777 	s32 smin_val = src_reg->s32_min_value;
12778 	s32 smax_val = src_reg->s32_max_value;
12779 	u32 umin_val = src_reg->u32_min_value;
12780 	u32 umax_val = src_reg->u32_max_value;
12781 
12782 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12783 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12784 		/* Overflow possible, we know nothing */
12785 		dst_reg->s32_min_value = S32_MIN;
12786 		dst_reg->s32_max_value = S32_MAX;
12787 	} else {
12788 		dst_reg->s32_min_value -= smax_val;
12789 		dst_reg->s32_max_value -= smin_val;
12790 	}
12791 	if (dst_reg->u32_min_value < umax_val) {
12792 		/* Overflow possible, we know nothing */
12793 		dst_reg->u32_min_value = 0;
12794 		dst_reg->u32_max_value = U32_MAX;
12795 	} else {
12796 		/* Cannot overflow (as long as bounds are consistent) */
12797 		dst_reg->u32_min_value -= umax_val;
12798 		dst_reg->u32_max_value -= umin_val;
12799 	}
12800 }
12801 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12802 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12803 			       struct bpf_reg_state *src_reg)
12804 {
12805 	s64 smin_val = src_reg->smin_value;
12806 	s64 smax_val = src_reg->smax_value;
12807 	u64 umin_val = src_reg->umin_value;
12808 	u64 umax_val = src_reg->umax_value;
12809 
12810 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12811 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12812 		/* Overflow possible, we know nothing */
12813 		dst_reg->smin_value = S64_MIN;
12814 		dst_reg->smax_value = S64_MAX;
12815 	} else {
12816 		dst_reg->smin_value -= smax_val;
12817 		dst_reg->smax_value -= smin_val;
12818 	}
12819 	if (dst_reg->umin_value < umax_val) {
12820 		/* Overflow possible, we know nothing */
12821 		dst_reg->umin_value = 0;
12822 		dst_reg->umax_value = U64_MAX;
12823 	} else {
12824 		/* Cannot overflow (as long as bounds are consistent) */
12825 		dst_reg->umin_value -= umax_val;
12826 		dst_reg->umax_value -= umin_val;
12827 	}
12828 }
12829 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12830 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12831 				 struct bpf_reg_state *src_reg)
12832 {
12833 	s32 smin_val = src_reg->s32_min_value;
12834 	u32 umin_val = src_reg->u32_min_value;
12835 	u32 umax_val = src_reg->u32_max_value;
12836 
12837 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12838 		/* Ain't nobody got time to multiply that sign */
12839 		__mark_reg32_unbounded(dst_reg);
12840 		return;
12841 	}
12842 	/* Both values are positive, so we can work with unsigned and
12843 	 * copy the result to signed (unless it exceeds S32_MAX).
12844 	 */
12845 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12846 		/* Potential overflow, we know nothing */
12847 		__mark_reg32_unbounded(dst_reg);
12848 		return;
12849 	}
12850 	dst_reg->u32_min_value *= umin_val;
12851 	dst_reg->u32_max_value *= umax_val;
12852 	if (dst_reg->u32_max_value > S32_MAX) {
12853 		/* Overflow possible, we know nothing */
12854 		dst_reg->s32_min_value = S32_MIN;
12855 		dst_reg->s32_max_value = S32_MAX;
12856 	} else {
12857 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12858 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12859 	}
12860 }
12861 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12862 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12863 			       struct bpf_reg_state *src_reg)
12864 {
12865 	s64 smin_val = src_reg->smin_value;
12866 	u64 umin_val = src_reg->umin_value;
12867 	u64 umax_val = src_reg->umax_value;
12868 
12869 	if (smin_val < 0 || dst_reg->smin_value < 0) {
12870 		/* Ain't nobody got time to multiply that sign */
12871 		__mark_reg64_unbounded(dst_reg);
12872 		return;
12873 	}
12874 	/* Both values are positive, so we can work with unsigned and
12875 	 * copy the result to signed (unless it exceeds S64_MAX).
12876 	 */
12877 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12878 		/* Potential overflow, we know nothing */
12879 		__mark_reg64_unbounded(dst_reg);
12880 		return;
12881 	}
12882 	dst_reg->umin_value *= umin_val;
12883 	dst_reg->umax_value *= umax_val;
12884 	if (dst_reg->umax_value > S64_MAX) {
12885 		/* Overflow possible, we know nothing */
12886 		dst_reg->smin_value = S64_MIN;
12887 		dst_reg->smax_value = S64_MAX;
12888 	} else {
12889 		dst_reg->smin_value = dst_reg->umin_value;
12890 		dst_reg->smax_value = dst_reg->umax_value;
12891 	}
12892 }
12893 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12894 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12895 				 struct bpf_reg_state *src_reg)
12896 {
12897 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12898 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12899 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12900 	s32 smin_val = src_reg->s32_min_value;
12901 	u32 umax_val = src_reg->u32_max_value;
12902 
12903 	if (src_known && dst_known) {
12904 		__mark_reg32_known(dst_reg, var32_off.value);
12905 		return;
12906 	}
12907 
12908 	/* We get our minimum from the var_off, since that's inherently
12909 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12910 	 */
12911 	dst_reg->u32_min_value = var32_off.value;
12912 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12913 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12914 		/* Lose signed bounds when ANDing negative numbers,
12915 		 * ain't nobody got time for that.
12916 		 */
12917 		dst_reg->s32_min_value = S32_MIN;
12918 		dst_reg->s32_max_value = S32_MAX;
12919 	} else {
12920 		/* ANDing two positives gives a positive, so safe to
12921 		 * cast result into s64.
12922 		 */
12923 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12924 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12925 	}
12926 }
12927 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12928 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12929 			       struct bpf_reg_state *src_reg)
12930 {
12931 	bool src_known = tnum_is_const(src_reg->var_off);
12932 	bool dst_known = tnum_is_const(dst_reg->var_off);
12933 	s64 smin_val = src_reg->smin_value;
12934 	u64 umax_val = src_reg->umax_value;
12935 
12936 	if (src_known && dst_known) {
12937 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12938 		return;
12939 	}
12940 
12941 	/* We get our minimum from the var_off, since that's inherently
12942 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12943 	 */
12944 	dst_reg->umin_value = dst_reg->var_off.value;
12945 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12946 	if (dst_reg->smin_value < 0 || smin_val < 0) {
12947 		/* Lose signed bounds when ANDing negative numbers,
12948 		 * ain't nobody got time for that.
12949 		 */
12950 		dst_reg->smin_value = S64_MIN;
12951 		dst_reg->smax_value = S64_MAX;
12952 	} else {
12953 		/* ANDing two positives gives a positive, so safe to
12954 		 * cast result into s64.
12955 		 */
12956 		dst_reg->smin_value = dst_reg->umin_value;
12957 		dst_reg->smax_value = dst_reg->umax_value;
12958 	}
12959 	/* We may learn something more from the var_off */
12960 	__update_reg_bounds(dst_reg);
12961 }
12962 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12963 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12964 				struct bpf_reg_state *src_reg)
12965 {
12966 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12967 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12968 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12969 	s32 smin_val = src_reg->s32_min_value;
12970 	u32 umin_val = src_reg->u32_min_value;
12971 
12972 	if (src_known && dst_known) {
12973 		__mark_reg32_known(dst_reg, var32_off.value);
12974 		return;
12975 	}
12976 
12977 	/* We get our maximum from the var_off, and our minimum is the
12978 	 * maximum of the operands' minima
12979 	 */
12980 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12981 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12982 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12983 		/* Lose signed bounds when ORing negative numbers,
12984 		 * ain't nobody got time for that.
12985 		 */
12986 		dst_reg->s32_min_value = S32_MIN;
12987 		dst_reg->s32_max_value = S32_MAX;
12988 	} else {
12989 		/* ORing two positives gives a positive, so safe to
12990 		 * cast result into s64.
12991 		 */
12992 		dst_reg->s32_min_value = dst_reg->u32_min_value;
12993 		dst_reg->s32_max_value = dst_reg->u32_max_value;
12994 	}
12995 }
12996 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12997 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12998 			      struct bpf_reg_state *src_reg)
12999 {
13000 	bool src_known = tnum_is_const(src_reg->var_off);
13001 	bool dst_known = tnum_is_const(dst_reg->var_off);
13002 	s64 smin_val = src_reg->smin_value;
13003 	u64 umin_val = src_reg->umin_value;
13004 
13005 	if (src_known && dst_known) {
13006 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13007 		return;
13008 	}
13009 
13010 	/* We get our maximum from the var_off, and our minimum is the
13011 	 * maximum of the operands' minima
13012 	 */
13013 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13014 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13015 	if (dst_reg->smin_value < 0 || smin_val < 0) {
13016 		/* Lose signed bounds when ORing negative numbers,
13017 		 * ain't nobody got time for that.
13018 		 */
13019 		dst_reg->smin_value = S64_MIN;
13020 		dst_reg->smax_value = S64_MAX;
13021 	} else {
13022 		/* ORing two positives gives a positive, so safe to
13023 		 * cast result into s64.
13024 		 */
13025 		dst_reg->smin_value = dst_reg->umin_value;
13026 		dst_reg->smax_value = dst_reg->umax_value;
13027 	}
13028 	/* We may learn something more from the var_off */
13029 	__update_reg_bounds(dst_reg);
13030 }
13031 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13032 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13033 				 struct bpf_reg_state *src_reg)
13034 {
13035 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13036 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13037 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13038 	s32 smin_val = src_reg->s32_min_value;
13039 
13040 	if (src_known && dst_known) {
13041 		__mark_reg32_known(dst_reg, var32_off.value);
13042 		return;
13043 	}
13044 
13045 	/* We get both minimum and maximum from the var32_off. */
13046 	dst_reg->u32_min_value = var32_off.value;
13047 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13048 
13049 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13050 		/* XORing two positive sign numbers gives a positive,
13051 		 * so safe to cast u32 result into s32.
13052 		 */
13053 		dst_reg->s32_min_value = dst_reg->u32_min_value;
13054 		dst_reg->s32_max_value = dst_reg->u32_max_value;
13055 	} else {
13056 		dst_reg->s32_min_value = S32_MIN;
13057 		dst_reg->s32_max_value = S32_MAX;
13058 	}
13059 }
13060 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13061 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13062 			       struct bpf_reg_state *src_reg)
13063 {
13064 	bool src_known = tnum_is_const(src_reg->var_off);
13065 	bool dst_known = tnum_is_const(dst_reg->var_off);
13066 	s64 smin_val = src_reg->smin_value;
13067 
13068 	if (src_known && dst_known) {
13069 		/* dst_reg->var_off.value has been updated earlier */
13070 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13071 		return;
13072 	}
13073 
13074 	/* We get both minimum and maximum from the var_off. */
13075 	dst_reg->umin_value = dst_reg->var_off.value;
13076 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13077 
13078 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13079 		/* XORing two positive sign numbers gives a positive,
13080 		 * so safe to cast u64 result into s64.
13081 		 */
13082 		dst_reg->smin_value = dst_reg->umin_value;
13083 		dst_reg->smax_value = dst_reg->umax_value;
13084 	} else {
13085 		dst_reg->smin_value = S64_MIN;
13086 		dst_reg->smax_value = S64_MAX;
13087 	}
13088 
13089 	__update_reg_bounds(dst_reg);
13090 }
13091 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13092 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13093 				   u64 umin_val, u64 umax_val)
13094 {
13095 	/* We lose all sign bit information (except what we can pick
13096 	 * up from var_off)
13097 	 */
13098 	dst_reg->s32_min_value = S32_MIN;
13099 	dst_reg->s32_max_value = S32_MAX;
13100 	/* If we might shift our top bit out, then we know nothing */
13101 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13102 		dst_reg->u32_min_value = 0;
13103 		dst_reg->u32_max_value = U32_MAX;
13104 	} else {
13105 		dst_reg->u32_min_value <<= umin_val;
13106 		dst_reg->u32_max_value <<= umax_val;
13107 	}
13108 }
13109 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13110 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13111 				 struct bpf_reg_state *src_reg)
13112 {
13113 	u32 umax_val = src_reg->u32_max_value;
13114 	u32 umin_val = src_reg->u32_min_value;
13115 	/* u32 alu operation will zext upper bits */
13116 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13117 
13118 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13119 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13120 	/* Not required but being careful mark reg64 bounds as unknown so
13121 	 * that we are forced to pick them up from tnum and zext later and
13122 	 * if some path skips this step we are still safe.
13123 	 */
13124 	__mark_reg64_unbounded(dst_reg);
13125 	__update_reg32_bounds(dst_reg);
13126 }
13127 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13128 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13129 				   u64 umin_val, u64 umax_val)
13130 {
13131 	/* Special case <<32 because it is a common compiler pattern to sign
13132 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13133 	 * positive we know this shift will also be positive so we can track
13134 	 * bounds correctly. Otherwise we lose all sign bit information except
13135 	 * what we can pick up from var_off. Perhaps we can generalize this
13136 	 * later to shifts of any length.
13137 	 */
13138 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13139 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13140 	else
13141 		dst_reg->smax_value = S64_MAX;
13142 
13143 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13144 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13145 	else
13146 		dst_reg->smin_value = S64_MIN;
13147 
13148 	/* If we might shift our top bit out, then we know nothing */
13149 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13150 		dst_reg->umin_value = 0;
13151 		dst_reg->umax_value = U64_MAX;
13152 	} else {
13153 		dst_reg->umin_value <<= umin_val;
13154 		dst_reg->umax_value <<= umax_val;
13155 	}
13156 }
13157 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13158 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13159 			       struct bpf_reg_state *src_reg)
13160 {
13161 	u64 umax_val = src_reg->umax_value;
13162 	u64 umin_val = src_reg->umin_value;
13163 
13164 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13165 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13166 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13167 
13168 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13169 	/* We may learn something more from the var_off */
13170 	__update_reg_bounds(dst_reg);
13171 }
13172 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13173 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13174 				 struct bpf_reg_state *src_reg)
13175 {
13176 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13177 	u32 umax_val = src_reg->u32_max_value;
13178 	u32 umin_val = src_reg->u32_min_value;
13179 
13180 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13181 	 * be negative, then either:
13182 	 * 1) src_reg might be zero, so the sign bit of the result is
13183 	 *    unknown, so we lose our signed bounds
13184 	 * 2) it's known negative, thus the unsigned bounds capture the
13185 	 *    signed bounds
13186 	 * 3) the signed bounds cross zero, so they tell us nothing
13187 	 *    about the result
13188 	 * If the value in dst_reg is known nonnegative, then again the
13189 	 * unsigned bounds capture the signed bounds.
13190 	 * Thus, in all cases it suffices to blow away our signed bounds
13191 	 * and rely on inferring new ones from the unsigned bounds and
13192 	 * var_off of the result.
13193 	 */
13194 	dst_reg->s32_min_value = S32_MIN;
13195 	dst_reg->s32_max_value = S32_MAX;
13196 
13197 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13198 	dst_reg->u32_min_value >>= umax_val;
13199 	dst_reg->u32_max_value >>= umin_val;
13200 
13201 	__mark_reg64_unbounded(dst_reg);
13202 	__update_reg32_bounds(dst_reg);
13203 }
13204 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13205 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13206 			       struct bpf_reg_state *src_reg)
13207 {
13208 	u64 umax_val = src_reg->umax_value;
13209 	u64 umin_val = src_reg->umin_value;
13210 
13211 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13212 	 * be negative, then either:
13213 	 * 1) src_reg might be zero, so the sign bit of the result is
13214 	 *    unknown, so we lose our signed bounds
13215 	 * 2) it's known negative, thus the unsigned bounds capture the
13216 	 *    signed bounds
13217 	 * 3) the signed bounds cross zero, so they tell us nothing
13218 	 *    about the result
13219 	 * If the value in dst_reg is known nonnegative, then again the
13220 	 * unsigned bounds capture the signed bounds.
13221 	 * Thus, in all cases it suffices to blow away our signed bounds
13222 	 * and rely on inferring new ones from the unsigned bounds and
13223 	 * var_off of the result.
13224 	 */
13225 	dst_reg->smin_value = S64_MIN;
13226 	dst_reg->smax_value = S64_MAX;
13227 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13228 	dst_reg->umin_value >>= umax_val;
13229 	dst_reg->umax_value >>= umin_val;
13230 
13231 	/* Its not easy to operate on alu32 bounds here because it depends
13232 	 * on bits being shifted in. Take easy way out and mark unbounded
13233 	 * so we can recalculate later from tnum.
13234 	 */
13235 	__mark_reg32_unbounded(dst_reg);
13236 	__update_reg_bounds(dst_reg);
13237 }
13238 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13239 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13240 				  struct bpf_reg_state *src_reg)
13241 {
13242 	u64 umin_val = src_reg->u32_min_value;
13243 
13244 	/* Upon reaching here, src_known is true and
13245 	 * umax_val is equal to umin_val.
13246 	 */
13247 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13248 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13249 
13250 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13251 
13252 	/* blow away the dst_reg umin_value/umax_value and rely on
13253 	 * dst_reg var_off to refine the result.
13254 	 */
13255 	dst_reg->u32_min_value = 0;
13256 	dst_reg->u32_max_value = U32_MAX;
13257 
13258 	__mark_reg64_unbounded(dst_reg);
13259 	__update_reg32_bounds(dst_reg);
13260 }
13261 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13262 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13263 				struct bpf_reg_state *src_reg)
13264 {
13265 	u64 umin_val = src_reg->umin_value;
13266 
13267 	/* Upon reaching here, src_known is true and umax_val is equal
13268 	 * to umin_val.
13269 	 */
13270 	dst_reg->smin_value >>= umin_val;
13271 	dst_reg->smax_value >>= umin_val;
13272 
13273 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13274 
13275 	/* blow away the dst_reg umin_value/umax_value and rely on
13276 	 * dst_reg var_off to refine the result.
13277 	 */
13278 	dst_reg->umin_value = 0;
13279 	dst_reg->umax_value = U64_MAX;
13280 
13281 	/* Its not easy to operate on alu32 bounds here because it depends
13282 	 * on bits being shifted in from upper 32-bits. Take easy way out
13283 	 * and mark unbounded so we can recalculate later from tnum.
13284 	 */
13285 	__mark_reg32_unbounded(dst_reg);
13286 	__update_reg_bounds(dst_reg);
13287 }
13288 
13289 /* WARNING: This function does calculations on 64-bit values, but the actual
13290  * execution may occur on 32-bit values. Therefore, things like bitshifts
13291  * need extra checks in the 32-bit case.
13292  */
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)13293 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13294 				      struct bpf_insn *insn,
13295 				      struct bpf_reg_state *dst_reg,
13296 				      struct bpf_reg_state src_reg)
13297 {
13298 	struct bpf_reg_state *regs = cur_regs(env);
13299 	u8 opcode = BPF_OP(insn->code);
13300 	bool src_known;
13301 	s64 smin_val, smax_val;
13302 	u64 umin_val, umax_val;
13303 	s32 s32_min_val, s32_max_val;
13304 	u32 u32_min_val, u32_max_val;
13305 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13306 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13307 	int ret;
13308 
13309 	smin_val = src_reg.smin_value;
13310 	smax_val = src_reg.smax_value;
13311 	umin_val = src_reg.umin_value;
13312 	umax_val = src_reg.umax_value;
13313 
13314 	s32_min_val = src_reg.s32_min_value;
13315 	s32_max_val = src_reg.s32_max_value;
13316 	u32_min_val = src_reg.u32_min_value;
13317 	u32_max_val = src_reg.u32_max_value;
13318 
13319 	if (alu32) {
13320 		src_known = tnum_subreg_is_const(src_reg.var_off);
13321 		if ((src_known &&
13322 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13323 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13324 			/* Taint dst register if offset had invalid bounds
13325 			 * derived from e.g. dead branches.
13326 			 */
13327 			__mark_reg_unknown(env, dst_reg);
13328 			return 0;
13329 		}
13330 	} else {
13331 		src_known = tnum_is_const(src_reg.var_off);
13332 		if ((src_known &&
13333 		     (smin_val != smax_val || umin_val != umax_val)) ||
13334 		    smin_val > smax_val || umin_val > umax_val) {
13335 			/* Taint dst register if offset had invalid bounds
13336 			 * derived from e.g. dead branches.
13337 			 */
13338 			__mark_reg_unknown(env, dst_reg);
13339 			return 0;
13340 		}
13341 	}
13342 
13343 	if (!src_known &&
13344 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13345 		__mark_reg_unknown(env, dst_reg);
13346 		return 0;
13347 	}
13348 
13349 	if (sanitize_needed(opcode)) {
13350 		ret = sanitize_val_alu(env, insn);
13351 		if (ret < 0)
13352 			return sanitize_err(env, insn, ret, NULL, NULL);
13353 	}
13354 
13355 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13356 	 * There are two classes of instructions: The first class we track both
13357 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13358 	 * greatest amount of precision when alu operations are mixed with jmp32
13359 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13360 	 * and BPF_OR. This is possible because these ops have fairly easy to
13361 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13362 	 * See alu32 verifier tests for examples. The second class of
13363 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13364 	 * with regards to tracking sign/unsigned bounds because the bits may
13365 	 * cross subreg boundaries in the alu64 case. When this happens we mark
13366 	 * the reg unbounded in the subreg bound space and use the resulting
13367 	 * tnum to calculate an approximation of the sign/unsigned bounds.
13368 	 */
13369 	switch (opcode) {
13370 	case BPF_ADD:
13371 		scalar32_min_max_add(dst_reg, &src_reg);
13372 		scalar_min_max_add(dst_reg, &src_reg);
13373 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13374 		break;
13375 	case BPF_SUB:
13376 		scalar32_min_max_sub(dst_reg, &src_reg);
13377 		scalar_min_max_sub(dst_reg, &src_reg);
13378 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13379 		break;
13380 	case BPF_MUL:
13381 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13382 		scalar32_min_max_mul(dst_reg, &src_reg);
13383 		scalar_min_max_mul(dst_reg, &src_reg);
13384 		break;
13385 	case BPF_AND:
13386 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13387 		scalar32_min_max_and(dst_reg, &src_reg);
13388 		scalar_min_max_and(dst_reg, &src_reg);
13389 		break;
13390 	case BPF_OR:
13391 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13392 		scalar32_min_max_or(dst_reg, &src_reg);
13393 		scalar_min_max_or(dst_reg, &src_reg);
13394 		break;
13395 	case BPF_XOR:
13396 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13397 		scalar32_min_max_xor(dst_reg, &src_reg);
13398 		scalar_min_max_xor(dst_reg, &src_reg);
13399 		break;
13400 	case BPF_LSH:
13401 		if (umax_val >= insn_bitness) {
13402 			/* Shifts greater than 31 or 63 are undefined.
13403 			 * This includes shifts by a negative number.
13404 			 */
13405 			mark_reg_unknown(env, regs, insn->dst_reg);
13406 			break;
13407 		}
13408 		if (alu32)
13409 			scalar32_min_max_lsh(dst_reg, &src_reg);
13410 		else
13411 			scalar_min_max_lsh(dst_reg, &src_reg);
13412 		break;
13413 	case BPF_RSH:
13414 		if (umax_val >= insn_bitness) {
13415 			/* Shifts greater than 31 or 63 are undefined.
13416 			 * This includes shifts by a negative number.
13417 			 */
13418 			mark_reg_unknown(env, regs, insn->dst_reg);
13419 			break;
13420 		}
13421 		if (alu32)
13422 			scalar32_min_max_rsh(dst_reg, &src_reg);
13423 		else
13424 			scalar_min_max_rsh(dst_reg, &src_reg);
13425 		break;
13426 	case BPF_ARSH:
13427 		if (umax_val >= insn_bitness) {
13428 			/* Shifts greater than 31 or 63 are undefined.
13429 			 * This includes shifts by a negative number.
13430 			 */
13431 			mark_reg_unknown(env, regs, insn->dst_reg);
13432 			break;
13433 		}
13434 		if (alu32)
13435 			scalar32_min_max_arsh(dst_reg, &src_reg);
13436 		else
13437 			scalar_min_max_arsh(dst_reg, &src_reg);
13438 		break;
13439 	default:
13440 		mark_reg_unknown(env, regs, insn->dst_reg);
13441 		break;
13442 	}
13443 
13444 	/* ALU32 ops are zero extended into 64bit register */
13445 	if (alu32)
13446 		zext_32_to_64(dst_reg);
13447 	reg_bounds_sync(dst_reg);
13448 	return 0;
13449 }
13450 
13451 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13452  * and var_off.
13453  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)13454 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13455 				   struct bpf_insn *insn)
13456 {
13457 	struct bpf_verifier_state *vstate = env->cur_state;
13458 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13459 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13460 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13461 	u8 opcode = BPF_OP(insn->code);
13462 	int err;
13463 
13464 	dst_reg = &regs[insn->dst_reg];
13465 	src_reg = NULL;
13466 	if (dst_reg->type != SCALAR_VALUE)
13467 		ptr_reg = dst_reg;
13468 	else
13469 		/* Make sure ID is cleared otherwise dst_reg min/max could be
13470 		 * incorrectly propagated into other registers by find_equal_scalars()
13471 		 */
13472 		dst_reg->id = 0;
13473 	if (BPF_SRC(insn->code) == BPF_X) {
13474 		src_reg = &regs[insn->src_reg];
13475 		if (src_reg->type != SCALAR_VALUE) {
13476 			if (dst_reg->type != SCALAR_VALUE) {
13477 				/* Combining two pointers by any ALU op yields
13478 				 * an arbitrary scalar. Disallow all math except
13479 				 * pointer subtraction
13480 				 */
13481 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13482 					mark_reg_unknown(env, regs, insn->dst_reg);
13483 					return 0;
13484 				}
13485 				verbose(env, "R%d pointer %s pointer prohibited\n",
13486 					insn->dst_reg,
13487 					bpf_alu_string[opcode >> 4]);
13488 				return -EACCES;
13489 			} else {
13490 				/* scalar += pointer
13491 				 * This is legal, but we have to reverse our
13492 				 * src/dest handling in computing the range
13493 				 */
13494 				err = mark_chain_precision(env, insn->dst_reg);
13495 				if (err)
13496 					return err;
13497 				return adjust_ptr_min_max_vals(env, insn,
13498 							       src_reg, dst_reg);
13499 			}
13500 		} else if (ptr_reg) {
13501 			/* pointer += scalar */
13502 			err = mark_chain_precision(env, insn->src_reg);
13503 			if (err)
13504 				return err;
13505 			return adjust_ptr_min_max_vals(env, insn,
13506 						       dst_reg, src_reg);
13507 		} else if (dst_reg->precise) {
13508 			/* if dst_reg is precise, src_reg should be precise as well */
13509 			err = mark_chain_precision(env, insn->src_reg);
13510 			if (err)
13511 				return err;
13512 		}
13513 	} else {
13514 		/* Pretend the src is a reg with a known value, since we only
13515 		 * need to be able to read from this state.
13516 		 */
13517 		off_reg.type = SCALAR_VALUE;
13518 		__mark_reg_known(&off_reg, insn->imm);
13519 		src_reg = &off_reg;
13520 		if (ptr_reg) /* pointer += K */
13521 			return adjust_ptr_min_max_vals(env, insn,
13522 						       ptr_reg, src_reg);
13523 	}
13524 
13525 	/* Got here implies adding two SCALAR_VALUEs */
13526 	if (WARN_ON_ONCE(ptr_reg)) {
13527 		print_verifier_state(env, state, true);
13528 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13529 		return -EINVAL;
13530 	}
13531 	if (WARN_ON(!src_reg)) {
13532 		print_verifier_state(env, state, true);
13533 		verbose(env, "verifier internal error: no src_reg\n");
13534 		return -EINVAL;
13535 	}
13536 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13537 }
13538 
13539 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)13540 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13541 {
13542 	struct bpf_reg_state *regs = cur_regs(env);
13543 	u8 opcode = BPF_OP(insn->code);
13544 	int err;
13545 
13546 	if (opcode == BPF_END || opcode == BPF_NEG) {
13547 		if (opcode == BPF_NEG) {
13548 			if (BPF_SRC(insn->code) != BPF_K ||
13549 			    insn->src_reg != BPF_REG_0 ||
13550 			    insn->off != 0 || insn->imm != 0) {
13551 				verbose(env, "BPF_NEG uses reserved fields\n");
13552 				return -EINVAL;
13553 			}
13554 		} else {
13555 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13556 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13557 			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13558 			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13559 				verbose(env, "BPF_END uses reserved fields\n");
13560 				return -EINVAL;
13561 			}
13562 		}
13563 
13564 		/* check src operand */
13565 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13566 		if (err)
13567 			return err;
13568 
13569 		if (is_pointer_value(env, insn->dst_reg)) {
13570 			verbose(env, "R%d pointer arithmetic prohibited\n",
13571 				insn->dst_reg);
13572 			return -EACCES;
13573 		}
13574 
13575 		/* check dest operand */
13576 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13577 		if (err)
13578 			return err;
13579 
13580 	} else if (opcode == BPF_MOV) {
13581 
13582 		if (BPF_SRC(insn->code) == BPF_X) {
13583 			if (insn->imm != 0) {
13584 				verbose(env, "BPF_MOV uses reserved fields\n");
13585 				return -EINVAL;
13586 			}
13587 
13588 			if (BPF_CLASS(insn->code) == BPF_ALU) {
13589 				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13590 					verbose(env, "BPF_MOV uses reserved fields\n");
13591 					return -EINVAL;
13592 				}
13593 			} else {
13594 				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13595 				    insn->off != 32) {
13596 					verbose(env, "BPF_MOV uses reserved fields\n");
13597 					return -EINVAL;
13598 				}
13599 			}
13600 
13601 			/* check src operand */
13602 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13603 			if (err)
13604 				return err;
13605 		} else {
13606 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13607 				verbose(env, "BPF_MOV uses reserved fields\n");
13608 				return -EINVAL;
13609 			}
13610 		}
13611 
13612 		/* check dest operand, mark as required later */
13613 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13614 		if (err)
13615 			return err;
13616 
13617 		if (BPF_SRC(insn->code) == BPF_X) {
13618 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13619 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13620 			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13621 				       !tnum_is_const(src_reg->var_off);
13622 
13623 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13624 				if (insn->off == 0) {
13625 					/* case: R1 = R2
13626 					 * copy register state to dest reg
13627 					 */
13628 					if (need_id)
13629 						/* Assign src and dst registers the same ID
13630 						 * that will be used by find_equal_scalars()
13631 						 * to propagate min/max range.
13632 						 */
13633 						src_reg->id = ++env->id_gen;
13634 					copy_register_state(dst_reg, src_reg);
13635 					dst_reg->live |= REG_LIVE_WRITTEN;
13636 					dst_reg->subreg_def = DEF_NOT_SUBREG;
13637 				} else {
13638 					/* case: R1 = (s8, s16 s32)R2 */
13639 					if (is_pointer_value(env, insn->src_reg)) {
13640 						verbose(env,
13641 							"R%d sign-extension part of pointer\n",
13642 							insn->src_reg);
13643 						return -EACCES;
13644 					} else if (src_reg->type == SCALAR_VALUE) {
13645 						bool no_sext;
13646 
13647 						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13648 						if (no_sext && need_id)
13649 							src_reg->id = ++env->id_gen;
13650 						copy_register_state(dst_reg, src_reg);
13651 						if (!no_sext)
13652 							dst_reg->id = 0;
13653 						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13654 						dst_reg->live |= REG_LIVE_WRITTEN;
13655 						dst_reg->subreg_def = DEF_NOT_SUBREG;
13656 					} else {
13657 						mark_reg_unknown(env, regs, insn->dst_reg);
13658 					}
13659 				}
13660 			} else {
13661 				/* R1 = (u32) R2 */
13662 				if (is_pointer_value(env, insn->src_reg)) {
13663 					verbose(env,
13664 						"R%d partial copy of pointer\n",
13665 						insn->src_reg);
13666 					return -EACCES;
13667 				} else if (src_reg->type == SCALAR_VALUE) {
13668 					if (insn->off == 0) {
13669 						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13670 
13671 						if (is_src_reg_u32 && need_id)
13672 							src_reg->id = ++env->id_gen;
13673 						copy_register_state(dst_reg, src_reg);
13674 						/* Make sure ID is cleared if src_reg is not in u32
13675 						 * range otherwise dst_reg min/max could be incorrectly
13676 						 * propagated into src_reg by find_equal_scalars()
13677 						 */
13678 						if (!is_src_reg_u32)
13679 							dst_reg->id = 0;
13680 						dst_reg->live |= REG_LIVE_WRITTEN;
13681 						dst_reg->subreg_def = env->insn_idx + 1;
13682 					} else {
13683 						/* case: W1 = (s8, s16)W2 */
13684 						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13685 
13686 						if (no_sext && need_id)
13687 							src_reg->id = ++env->id_gen;
13688 						copy_register_state(dst_reg, src_reg);
13689 						if (!no_sext)
13690 							dst_reg->id = 0;
13691 						dst_reg->live |= REG_LIVE_WRITTEN;
13692 						dst_reg->subreg_def = env->insn_idx + 1;
13693 						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13694 					}
13695 				} else {
13696 					mark_reg_unknown(env, regs,
13697 							 insn->dst_reg);
13698 				}
13699 				zext_32_to_64(dst_reg);
13700 				reg_bounds_sync(dst_reg);
13701 			}
13702 		} else {
13703 			/* case: R = imm
13704 			 * remember the value we stored into this reg
13705 			 */
13706 			/* clear any state __mark_reg_known doesn't set */
13707 			mark_reg_unknown(env, regs, insn->dst_reg);
13708 			regs[insn->dst_reg].type = SCALAR_VALUE;
13709 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13710 				__mark_reg_known(regs + insn->dst_reg,
13711 						 insn->imm);
13712 			} else {
13713 				__mark_reg_known(regs + insn->dst_reg,
13714 						 (u32)insn->imm);
13715 			}
13716 		}
13717 
13718 	} else if (opcode > BPF_END) {
13719 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13720 		return -EINVAL;
13721 
13722 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13723 
13724 		if (BPF_SRC(insn->code) == BPF_X) {
13725 			if (insn->imm != 0 || insn->off > 1 ||
13726 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13727 				verbose(env, "BPF_ALU uses reserved fields\n");
13728 				return -EINVAL;
13729 			}
13730 			/* check src1 operand */
13731 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13732 			if (err)
13733 				return err;
13734 		} else {
13735 			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13736 			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13737 				verbose(env, "BPF_ALU uses reserved fields\n");
13738 				return -EINVAL;
13739 			}
13740 		}
13741 
13742 		/* check src2 operand */
13743 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13744 		if (err)
13745 			return err;
13746 
13747 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13748 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13749 			verbose(env, "div by zero\n");
13750 			return -EINVAL;
13751 		}
13752 
13753 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13754 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13755 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13756 
13757 			if (insn->imm < 0 || insn->imm >= size) {
13758 				verbose(env, "invalid shift %d\n", insn->imm);
13759 				return -EINVAL;
13760 			}
13761 		}
13762 
13763 		/* check dest operand */
13764 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13765 		if (err)
13766 			return err;
13767 
13768 		return adjust_reg_min_max_vals(env, insn);
13769 	}
13770 
13771 	return 0;
13772 }
13773 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)13774 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13775 				   struct bpf_reg_state *dst_reg,
13776 				   enum bpf_reg_type type,
13777 				   bool range_right_open)
13778 {
13779 	struct bpf_func_state *state;
13780 	struct bpf_reg_state *reg;
13781 	int new_range;
13782 
13783 	if (dst_reg->off < 0 ||
13784 	    (dst_reg->off == 0 && range_right_open))
13785 		/* This doesn't give us any range */
13786 		return;
13787 
13788 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13789 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13790 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13791 		 * than pkt_end, but that's because it's also less than pkt.
13792 		 */
13793 		return;
13794 
13795 	new_range = dst_reg->off;
13796 	if (range_right_open)
13797 		new_range++;
13798 
13799 	/* Examples for register markings:
13800 	 *
13801 	 * pkt_data in dst register:
13802 	 *
13803 	 *   r2 = r3;
13804 	 *   r2 += 8;
13805 	 *   if (r2 > pkt_end) goto <handle exception>
13806 	 *   <access okay>
13807 	 *
13808 	 *   r2 = r3;
13809 	 *   r2 += 8;
13810 	 *   if (r2 < pkt_end) goto <access okay>
13811 	 *   <handle exception>
13812 	 *
13813 	 *   Where:
13814 	 *     r2 == dst_reg, pkt_end == src_reg
13815 	 *     r2=pkt(id=n,off=8,r=0)
13816 	 *     r3=pkt(id=n,off=0,r=0)
13817 	 *
13818 	 * pkt_data in src register:
13819 	 *
13820 	 *   r2 = r3;
13821 	 *   r2 += 8;
13822 	 *   if (pkt_end >= r2) goto <access okay>
13823 	 *   <handle exception>
13824 	 *
13825 	 *   r2 = r3;
13826 	 *   r2 += 8;
13827 	 *   if (pkt_end <= r2) goto <handle exception>
13828 	 *   <access okay>
13829 	 *
13830 	 *   Where:
13831 	 *     pkt_end == dst_reg, r2 == src_reg
13832 	 *     r2=pkt(id=n,off=8,r=0)
13833 	 *     r3=pkt(id=n,off=0,r=0)
13834 	 *
13835 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13836 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13837 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13838 	 * the check.
13839 	 */
13840 
13841 	/* If our ids match, then we must have the same max_value.  And we
13842 	 * don't care about the other reg's fixed offset, since if it's too big
13843 	 * the range won't allow anything.
13844 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13845 	 */
13846 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13847 		if (reg->type == type && reg->id == dst_reg->id)
13848 			/* keep the maximum range already checked */
13849 			reg->range = max(reg->range, new_range);
13850 	}));
13851 }
13852 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)13853 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13854 {
13855 	struct tnum subreg = tnum_subreg(reg->var_off);
13856 	s32 sval = (s32)val;
13857 
13858 	switch (opcode) {
13859 	case BPF_JEQ:
13860 		if (tnum_is_const(subreg))
13861 			return !!tnum_equals_const(subreg, val);
13862 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13863 			return 0;
13864 		break;
13865 	case BPF_JNE:
13866 		if (tnum_is_const(subreg))
13867 			return !tnum_equals_const(subreg, val);
13868 		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13869 			return 1;
13870 		break;
13871 	case BPF_JSET:
13872 		if ((~subreg.mask & subreg.value) & val)
13873 			return 1;
13874 		if (!((subreg.mask | subreg.value) & val))
13875 			return 0;
13876 		break;
13877 	case BPF_JGT:
13878 		if (reg->u32_min_value > val)
13879 			return 1;
13880 		else if (reg->u32_max_value <= val)
13881 			return 0;
13882 		break;
13883 	case BPF_JSGT:
13884 		if (reg->s32_min_value > sval)
13885 			return 1;
13886 		else if (reg->s32_max_value <= sval)
13887 			return 0;
13888 		break;
13889 	case BPF_JLT:
13890 		if (reg->u32_max_value < val)
13891 			return 1;
13892 		else if (reg->u32_min_value >= val)
13893 			return 0;
13894 		break;
13895 	case BPF_JSLT:
13896 		if (reg->s32_max_value < sval)
13897 			return 1;
13898 		else if (reg->s32_min_value >= sval)
13899 			return 0;
13900 		break;
13901 	case BPF_JGE:
13902 		if (reg->u32_min_value >= val)
13903 			return 1;
13904 		else if (reg->u32_max_value < val)
13905 			return 0;
13906 		break;
13907 	case BPF_JSGE:
13908 		if (reg->s32_min_value >= sval)
13909 			return 1;
13910 		else if (reg->s32_max_value < sval)
13911 			return 0;
13912 		break;
13913 	case BPF_JLE:
13914 		if (reg->u32_max_value <= val)
13915 			return 1;
13916 		else if (reg->u32_min_value > val)
13917 			return 0;
13918 		break;
13919 	case BPF_JSLE:
13920 		if (reg->s32_max_value <= sval)
13921 			return 1;
13922 		else if (reg->s32_min_value > sval)
13923 			return 0;
13924 		break;
13925 	}
13926 
13927 	return -1;
13928 }
13929 
13930 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)13931 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13932 {
13933 	s64 sval = (s64)val;
13934 
13935 	switch (opcode) {
13936 	case BPF_JEQ:
13937 		if (tnum_is_const(reg->var_off))
13938 			return !!tnum_equals_const(reg->var_off, val);
13939 		else if (val < reg->umin_value || val > reg->umax_value)
13940 			return 0;
13941 		break;
13942 	case BPF_JNE:
13943 		if (tnum_is_const(reg->var_off))
13944 			return !tnum_equals_const(reg->var_off, val);
13945 		else if (val < reg->umin_value || val > reg->umax_value)
13946 			return 1;
13947 		break;
13948 	case BPF_JSET:
13949 		if ((~reg->var_off.mask & reg->var_off.value) & val)
13950 			return 1;
13951 		if (!((reg->var_off.mask | reg->var_off.value) & val))
13952 			return 0;
13953 		break;
13954 	case BPF_JGT:
13955 		if (reg->umin_value > val)
13956 			return 1;
13957 		else if (reg->umax_value <= val)
13958 			return 0;
13959 		break;
13960 	case BPF_JSGT:
13961 		if (reg->smin_value > sval)
13962 			return 1;
13963 		else if (reg->smax_value <= sval)
13964 			return 0;
13965 		break;
13966 	case BPF_JLT:
13967 		if (reg->umax_value < val)
13968 			return 1;
13969 		else if (reg->umin_value >= val)
13970 			return 0;
13971 		break;
13972 	case BPF_JSLT:
13973 		if (reg->smax_value < sval)
13974 			return 1;
13975 		else if (reg->smin_value >= sval)
13976 			return 0;
13977 		break;
13978 	case BPF_JGE:
13979 		if (reg->umin_value >= val)
13980 			return 1;
13981 		else if (reg->umax_value < val)
13982 			return 0;
13983 		break;
13984 	case BPF_JSGE:
13985 		if (reg->smin_value >= sval)
13986 			return 1;
13987 		else if (reg->smax_value < sval)
13988 			return 0;
13989 		break;
13990 	case BPF_JLE:
13991 		if (reg->umax_value <= val)
13992 			return 1;
13993 		else if (reg->umin_value > val)
13994 			return 0;
13995 		break;
13996 	case BPF_JSLE:
13997 		if (reg->smax_value <= sval)
13998 			return 1;
13999 		else if (reg->smin_value > sval)
14000 			return 0;
14001 		break;
14002 	}
14003 
14004 	return -1;
14005 }
14006 
14007 /* compute branch direction of the expression "if (reg opcode val) goto target;"
14008  * and return:
14009  *  1 - branch will be taken and "goto target" will be executed
14010  *  0 - branch will not be taken and fall-through to next insn
14011  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
14012  *      range [0,10]
14013  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)14014 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
14015 			   bool is_jmp32)
14016 {
14017 	if (__is_pointer_value(false, reg)) {
14018 		if (!reg_not_null(reg))
14019 			return -1;
14020 
14021 		/* If pointer is valid tests against zero will fail so we can
14022 		 * use this to direct branch taken.
14023 		 */
14024 		if (val != 0)
14025 			return -1;
14026 
14027 		switch (opcode) {
14028 		case BPF_JEQ:
14029 			return 0;
14030 		case BPF_JNE:
14031 			return 1;
14032 		default:
14033 			return -1;
14034 		}
14035 	}
14036 
14037 	if (is_jmp32)
14038 		return is_branch32_taken(reg, val, opcode);
14039 	return is_branch64_taken(reg, val, opcode);
14040 }
14041 
flip_opcode(u32 opcode)14042 static int flip_opcode(u32 opcode)
14043 {
14044 	/* How can we transform "a <op> b" into "b <op> a"? */
14045 	static const u8 opcode_flip[16] = {
14046 		/* these stay the same */
14047 		[BPF_JEQ  >> 4] = BPF_JEQ,
14048 		[BPF_JNE  >> 4] = BPF_JNE,
14049 		[BPF_JSET >> 4] = BPF_JSET,
14050 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14051 		[BPF_JGE  >> 4] = BPF_JLE,
14052 		[BPF_JGT  >> 4] = BPF_JLT,
14053 		[BPF_JLE  >> 4] = BPF_JGE,
14054 		[BPF_JLT  >> 4] = BPF_JGT,
14055 		[BPF_JSGE >> 4] = BPF_JSLE,
14056 		[BPF_JSGT >> 4] = BPF_JSLT,
14057 		[BPF_JSLE >> 4] = BPF_JSGE,
14058 		[BPF_JSLT >> 4] = BPF_JSGT
14059 	};
14060 	return opcode_flip[opcode >> 4];
14061 }
14062 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)14063 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14064 				   struct bpf_reg_state *src_reg,
14065 				   u8 opcode)
14066 {
14067 	struct bpf_reg_state *pkt;
14068 
14069 	if (src_reg->type == PTR_TO_PACKET_END) {
14070 		pkt = dst_reg;
14071 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14072 		pkt = src_reg;
14073 		opcode = flip_opcode(opcode);
14074 	} else {
14075 		return -1;
14076 	}
14077 
14078 	if (pkt->range >= 0)
14079 		return -1;
14080 
14081 	switch (opcode) {
14082 	case BPF_JLE:
14083 		/* pkt <= pkt_end */
14084 		fallthrough;
14085 	case BPF_JGT:
14086 		/* pkt > pkt_end */
14087 		if (pkt->range == BEYOND_PKT_END)
14088 			/* pkt has at last one extra byte beyond pkt_end */
14089 			return opcode == BPF_JGT;
14090 		break;
14091 	case BPF_JLT:
14092 		/* pkt < pkt_end */
14093 		fallthrough;
14094 	case BPF_JGE:
14095 		/* pkt >= pkt_end */
14096 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14097 			return opcode == BPF_JGE;
14098 		break;
14099 	}
14100 	return -1;
14101 }
14102 
14103 /* Adjusts the register min/max values in the case that the dst_reg is the
14104  * variable register that we are working on, and src_reg is a constant or we're
14105  * simply doing a BPF_K check.
14106  * In JEQ/JNE cases we also adjust the var_off values.
14107  */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u32 val32,u8 opcode,bool is_jmp32)14108 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14109 			    struct bpf_reg_state *false_reg,
14110 			    u64 val, u32 val32,
14111 			    u8 opcode, bool is_jmp32)
14112 {
14113 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14114 	struct tnum false_64off = false_reg->var_off;
14115 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14116 	struct tnum true_64off = true_reg->var_off;
14117 	s64 sval = (s64)val;
14118 	s32 sval32 = (s32)val32;
14119 
14120 	/* If the dst_reg is a pointer, we can't learn anything about its
14121 	 * variable offset from the compare (unless src_reg were a pointer into
14122 	 * the same object, but we don't bother with that.
14123 	 * Since false_reg and true_reg have the same type by construction, we
14124 	 * only need to check one of them for pointerness.
14125 	 */
14126 	if (__is_pointer_value(false, false_reg))
14127 		return;
14128 
14129 	switch (opcode) {
14130 	/* JEQ/JNE comparison doesn't change the register equivalence.
14131 	 *
14132 	 * r1 = r2;
14133 	 * if (r1 == 42) goto label;
14134 	 * ...
14135 	 * label: // here both r1 and r2 are known to be 42.
14136 	 *
14137 	 * Hence when marking register as known preserve it's ID.
14138 	 */
14139 	case BPF_JEQ:
14140 		if (is_jmp32) {
14141 			__mark_reg32_known(true_reg, val32);
14142 			true_32off = tnum_subreg(true_reg->var_off);
14143 		} else {
14144 			___mark_reg_known(true_reg, val);
14145 			true_64off = true_reg->var_off;
14146 		}
14147 		break;
14148 	case BPF_JNE:
14149 		if (is_jmp32) {
14150 			__mark_reg32_known(false_reg, val32);
14151 			false_32off = tnum_subreg(false_reg->var_off);
14152 		} else {
14153 			___mark_reg_known(false_reg, val);
14154 			false_64off = false_reg->var_off;
14155 		}
14156 		break;
14157 	case BPF_JSET:
14158 		if (is_jmp32) {
14159 			false_32off = tnum_and(false_32off, tnum_const(~val32));
14160 			if (is_power_of_2(val32))
14161 				true_32off = tnum_or(true_32off,
14162 						     tnum_const(val32));
14163 		} else {
14164 			false_64off = tnum_and(false_64off, tnum_const(~val));
14165 			if (is_power_of_2(val))
14166 				true_64off = tnum_or(true_64off,
14167 						     tnum_const(val));
14168 		}
14169 		break;
14170 	case BPF_JGE:
14171 	case BPF_JGT:
14172 	{
14173 		if (is_jmp32) {
14174 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14175 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14176 
14177 			false_reg->u32_max_value = min(false_reg->u32_max_value,
14178 						       false_umax);
14179 			true_reg->u32_min_value = max(true_reg->u32_min_value,
14180 						      true_umin);
14181 		} else {
14182 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14183 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14184 
14185 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14186 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14187 		}
14188 		break;
14189 	}
14190 	case BPF_JSGE:
14191 	case BPF_JSGT:
14192 	{
14193 		if (is_jmp32) {
14194 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14195 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14196 
14197 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14198 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14199 		} else {
14200 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14201 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14202 
14203 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14204 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14205 		}
14206 		break;
14207 	}
14208 	case BPF_JLE:
14209 	case BPF_JLT:
14210 	{
14211 		if (is_jmp32) {
14212 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14213 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14214 
14215 			false_reg->u32_min_value = max(false_reg->u32_min_value,
14216 						       false_umin);
14217 			true_reg->u32_max_value = min(true_reg->u32_max_value,
14218 						      true_umax);
14219 		} else {
14220 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14221 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14222 
14223 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14224 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14225 		}
14226 		break;
14227 	}
14228 	case BPF_JSLE:
14229 	case BPF_JSLT:
14230 	{
14231 		if (is_jmp32) {
14232 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14233 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14234 
14235 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14236 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14237 		} else {
14238 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14239 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14240 
14241 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14242 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14243 		}
14244 		break;
14245 	}
14246 	default:
14247 		return;
14248 	}
14249 
14250 	if (is_jmp32) {
14251 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14252 					     tnum_subreg(false_32off));
14253 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14254 					    tnum_subreg(true_32off));
14255 		__reg_combine_32_into_64(false_reg);
14256 		__reg_combine_32_into_64(true_reg);
14257 	} else {
14258 		false_reg->var_off = false_64off;
14259 		true_reg->var_off = true_64off;
14260 		__reg_combine_64_into_32(false_reg);
14261 		__reg_combine_64_into_32(true_reg);
14262 	}
14263 }
14264 
14265 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14266  * the variable reg.
14267  */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u32 val32,u8 opcode,bool is_jmp32)14268 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14269 				struct bpf_reg_state *false_reg,
14270 				u64 val, u32 val32,
14271 				u8 opcode, bool is_jmp32)
14272 {
14273 	opcode = flip_opcode(opcode);
14274 	/* This uses zero as "not present in table"; luckily the zero opcode,
14275 	 * BPF_JA, can't get here.
14276 	 */
14277 	if (opcode)
14278 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14279 }
14280 
14281 /* Regs are known to be equal, so intersect their min/max/var_off */
__reg_combine_min_max(struct bpf_reg_state * src_reg,struct bpf_reg_state * dst_reg)14282 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14283 				  struct bpf_reg_state *dst_reg)
14284 {
14285 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14286 							dst_reg->umin_value);
14287 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14288 							dst_reg->umax_value);
14289 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14290 							dst_reg->smin_value);
14291 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14292 							dst_reg->smax_value);
14293 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14294 							     dst_reg->var_off);
14295 	reg_bounds_sync(src_reg);
14296 	reg_bounds_sync(dst_reg);
14297 }
14298 
reg_combine_min_max(struct bpf_reg_state * true_src,struct bpf_reg_state * true_dst,struct bpf_reg_state * false_src,struct bpf_reg_state * false_dst,u8 opcode)14299 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14300 				struct bpf_reg_state *true_dst,
14301 				struct bpf_reg_state *false_src,
14302 				struct bpf_reg_state *false_dst,
14303 				u8 opcode)
14304 {
14305 	switch (opcode) {
14306 	case BPF_JEQ:
14307 		__reg_combine_min_max(true_src, true_dst);
14308 		break;
14309 	case BPF_JNE:
14310 		__reg_combine_min_max(false_src, false_dst);
14311 		break;
14312 	}
14313 }
14314 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)14315 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14316 				 struct bpf_reg_state *reg, u32 id,
14317 				 bool is_null)
14318 {
14319 	if (type_may_be_null(reg->type) && reg->id == id &&
14320 	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14321 		/* Old offset (both fixed and variable parts) should have been
14322 		 * known-zero, because we don't allow pointer arithmetic on
14323 		 * pointers that might be NULL. If we see this happening, don't
14324 		 * convert the register.
14325 		 *
14326 		 * But in some cases, some helpers that return local kptrs
14327 		 * advance offset for the returned pointer. In those cases, it
14328 		 * is fine to expect to see reg->off.
14329 		 */
14330 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14331 			return;
14332 		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14333 		    WARN_ON_ONCE(reg->off))
14334 			return;
14335 
14336 		if (is_null) {
14337 			reg->type = SCALAR_VALUE;
14338 			/* We don't need id and ref_obj_id from this point
14339 			 * onwards anymore, thus we should better reset it,
14340 			 * so that state pruning has chances to take effect.
14341 			 */
14342 			reg->id = 0;
14343 			reg->ref_obj_id = 0;
14344 
14345 			return;
14346 		}
14347 
14348 		mark_ptr_not_null_reg(reg);
14349 
14350 		if (!reg_may_point_to_spin_lock(reg)) {
14351 			/* For not-NULL ptr, reg->ref_obj_id will be reset
14352 			 * in release_reference().
14353 			 *
14354 			 * reg->id is still used by spin_lock ptr. Other
14355 			 * than spin_lock ptr type, reg->id can be reset.
14356 			 */
14357 			reg->id = 0;
14358 		}
14359 	}
14360 }
14361 
14362 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14363  * be folded together at some point.
14364  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)14365 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14366 				  bool is_null)
14367 {
14368 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14369 	struct bpf_reg_state *regs = state->regs, *reg;
14370 	u32 ref_obj_id = regs[regno].ref_obj_id;
14371 	u32 id = regs[regno].id;
14372 
14373 	if (ref_obj_id && ref_obj_id == id && is_null)
14374 		/* regs[regno] is in the " == NULL" branch.
14375 		 * No one could have freed the reference state before
14376 		 * doing the NULL check.
14377 		 */
14378 		WARN_ON_ONCE(release_reference_state(state, id));
14379 
14380 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14381 		mark_ptr_or_null_reg(state, reg, id, is_null);
14382 	}));
14383 }
14384 
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)14385 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14386 				   struct bpf_reg_state *dst_reg,
14387 				   struct bpf_reg_state *src_reg,
14388 				   struct bpf_verifier_state *this_branch,
14389 				   struct bpf_verifier_state *other_branch)
14390 {
14391 	if (BPF_SRC(insn->code) != BPF_X)
14392 		return false;
14393 
14394 	/* Pointers are always 64-bit. */
14395 	if (BPF_CLASS(insn->code) == BPF_JMP32)
14396 		return false;
14397 
14398 	switch (BPF_OP(insn->code)) {
14399 	case BPF_JGT:
14400 		if ((dst_reg->type == PTR_TO_PACKET &&
14401 		     src_reg->type == PTR_TO_PACKET_END) ||
14402 		    (dst_reg->type == PTR_TO_PACKET_META &&
14403 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14404 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14405 			find_good_pkt_pointers(this_branch, dst_reg,
14406 					       dst_reg->type, false);
14407 			mark_pkt_end(other_branch, insn->dst_reg, true);
14408 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14409 			    src_reg->type == PTR_TO_PACKET) ||
14410 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14411 			    src_reg->type == PTR_TO_PACKET_META)) {
14412 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14413 			find_good_pkt_pointers(other_branch, src_reg,
14414 					       src_reg->type, true);
14415 			mark_pkt_end(this_branch, insn->src_reg, false);
14416 		} else {
14417 			return false;
14418 		}
14419 		break;
14420 	case BPF_JLT:
14421 		if ((dst_reg->type == PTR_TO_PACKET &&
14422 		     src_reg->type == PTR_TO_PACKET_END) ||
14423 		    (dst_reg->type == PTR_TO_PACKET_META &&
14424 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14425 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14426 			find_good_pkt_pointers(other_branch, dst_reg,
14427 					       dst_reg->type, true);
14428 			mark_pkt_end(this_branch, insn->dst_reg, false);
14429 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14430 			    src_reg->type == PTR_TO_PACKET) ||
14431 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14432 			    src_reg->type == PTR_TO_PACKET_META)) {
14433 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14434 			find_good_pkt_pointers(this_branch, src_reg,
14435 					       src_reg->type, false);
14436 			mark_pkt_end(other_branch, insn->src_reg, true);
14437 		} else {
14438 			return false;
14439 		}
14440 		break;
14441 	case BPF_JGE:
14442 		if ((dst_reg->type == PTR_TO_PACKET &&
14443 		     src_reg->type == PTR_TO_PACKET_END) ||
14444 		    (dst_reg->type == PTR_TO_PACKET_META &&
14445 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14446 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14447 			find_good_pkt_pointers(this_branch, dst_reg,
14448 					       dst_reg->type, true);
14449 			mark_pkt_end(other_branch, insn->dst_reg, false);
14450 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14451 			    src_reg->type == PTR_TO_PACKET) ||
14452 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14453 			    src_reg->type == PTR_TO_PACKET_META)) {
14454 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14455 			find_good_pkt_pointers(other_branch, src_reg,
14456 					       src_reg->type, false);
14457 			mark_pkt_end(this_branch, insn->src_reg, true);
14458 		} else {
14459 			return false;
14460 		}
14461 		break;
14462 	case BPF_JLE:
14463 		if ((dst_reg->type == PTR_TO_PACKET &&
14464 		     src_reg->type == PTR_TO_PACKET_END) ||
14465 		    (dst_reg->type == PTR_TO_PACKET_META &&
14466 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14467 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14468 			find_good_pkt_pointers(other_branch, dst_reg,
14469 					       dst_reg->type, false);
14470 			mark_pkt_end(this_branch, insn->dst_reg, true);
14471 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14472 			    src_reg->type == PTR_TO_PACKET) ||
14473 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14474 			    src_reg->type == PTR_TO_PACKET_META)) {
14475 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14476 			find_good_pkt_pointers(this_branch, src_reg,
14477 					       src_reg->type, true);
14478 			mark_pkt_end(other_branch, insn->src_reg, false);
14479 		} else {
14480 			return false;
14481 		}
14482 		break;
14483 	default:
14484 		return false;
14485 	}
14486 
14487 	return true;
14488 }
14489 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)14490 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14491 			       struct bpf_reg_state *known_reg)
14492 {
14493 	struct bpf_func_state *state;
14494 	struct bpf_reg_state *reg;
14495 
14496 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14497 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) {
14498 			s32 saved_subreg_def = reg->subreg_def;
14499 			copy_register_state(reg, known_reg);
14500 			reg->subreg_def = saved_subreg_def;
14501 		}
14502 	}));
14503 }
14504 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)14505 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14506 			     struct bpf_insn *insn, int *insn_idx)
14507 {
14508 	struct bpf_verifier_state *this_branch = env->cur_state;
14509 	struct bpf_verifier_state *other_branch;
14510 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14511 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14512 	struct bpf_reg_state *eq_branch_regs;
14513 	u8 opcode = BPF_OP(insn->code);
14514 	bool is_jmp32;
14515 	int pred = -1;
14516 	int err;
14517 
14518 	/* Only conditional jumps are expected to reach here. */
14519 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14520 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14521 		return -EINVAL;
14522 	}
14523 
14524 	/* check src2 operand */
14525 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14526 	if (err)
14527 		return err;
14528 
14529 	dst_reg = &regs[insn->dst_reg];
14530 	if (BPF_SRC(insn->code) == BPF_X) {
14531 		if (insn->imm != 0) {
14532 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14533 			return -EINVAL;
14534 		}
14535 
14536 		/* check src1 operand */
14537 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14538 		if (err)
14539 			return err;
14540 
14541 		src_reg = &regs[insn->src_reg];
14542 		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14543 		    is_pointer_value(env, insn->src_reg)) {
14544 			verbose(env, "R%d pointer comparison prohibited\n",
14545 				insn->src_reg);
14546 			return -EACCES;
14547 		}
14548 	} else {
14549 		if (insn->src_reg != BPF_REG_0) {
14550 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14551 			return -EINVAL;
14552 		}
14553 	}
14554 
14555 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14556 
14557 	if (BPF_SRC(insn->code) == BPF_K) {
14558 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14559 	} else if (src_reg->type == SCALAR_VALUE &&
14560 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14561 		pred = is_branch_taken(dst_reg,
14562 				       tnum_subreg(src_reg->var_off).value,
14563 				       opcode,
14564 				       is_jmp32);
14565 	} else if (src_reg->type == SCALAR_VALUE &&
14566 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14567 		pred = is_branch_taken(dst_reg,
14568 				       src_reg->var_off.value,
14569 				       opcode,
14570 				       is_jmp32);
14571 	} else if (dst_reg->type == SCALAR_VALUE &&
14572 		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14573 		pred = is_branch_taken(src_reg,
14574 				       tnum_subreg(dst_reg->var_off).value,
14575 				       flip_opcode(opcode),
14576 				       is_jmp32);
14577 	} else if (dst_reg->type == SCALAR_VALUE &&
14578 		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14579 		pred = is_branch_taken(src_reg,
14580 				       dst_reg->var_off.value,
14581 				       flip_opcode(opcode),
14582 				       is_jmp32);
14583 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14584 		   reg_is_pkt_pointer_any(src_reg) &&
14585 		   !is_jmp32) {
14586 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14587 	}
14588 
14589 	if (pred >= 0) {
14590 		/* If we get here with a dst_reg pointer type it is because
14591 		 * above is_branch_taken() special cased the 0 comparison.
14592 		 */
14593 		if (!__is_pointer_value(false, dst_reg))
14594 			err = mark_chain_precision(env, insn->dst_reg);
14595 		if (BPF_SRC(insn->code) == BPF_X && !err &&
14596 		    !__is_pointer_value(false, src_reg))
14597 			err = mark_chain_precision(env, insn->src_reg);
14598 		if (err)
14599 			return err;
14600 	}
14601 
14602 	if (pred == 1) {
14603 		/* Only follow the goto, ignore fall-through. If needed, push
14604 		 * the fall-through branch for simulation under speculative
14605 		 * execution.
14606 		 */
14607 		if (!env->bypass_spec_v1 &&
14608 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14609 					       *insn_idx))
14610 			return -EFAULT;
14611 		if (env->log.level & BPF_LOG_LEVEL)
14612 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14613 		*insn_idx += insn->off;
14614 		return 0;
14615 	} else if (pred == 0) {
14616 		/* Only follow the fall-through branch, since that's where the
14617 		 * program will go. If needed, push the goto branch for
14618 		 * simulation under speculative execution.
14619 		 */
14620 		if (!env->bypass_spec_v1 &&
14621 		    !sanitize_speculative_path(env, insn,
14622 					       *insn_idx + insn->off + 1,
14623 					       *insn_idx))
14624 			return -EFAULT;
14625 		if (env->log.level & BPF_LOG_LEVEL)
14626 			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14627 		return 0;
14628 	}
14629 
14630 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14631 				  false);
14632 	if (!other_branch)
14633 		return -EFAULT;
14634 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14635 
14636 	/* detect if we are comparing against a constant value so we can adjust
14637 	 * our min/max values for our dst register.
14638 	 * this is only legit if both are scalars (or pointers to the same
14639 	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14640 	 * because otherwise the different base pointers mean the offsets aren't
14641 	 * comparable.
14642 	 */
14643 	if (BPF_SRC(insn->code) == BPF_X) {
14644 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14645 
14646 		if (dst_reg->type == SCALAR_VALUE &&
14647 		    src_reg->type == SCALAR_VALUE) {
14648 			if (tnum_is_const(src_reg->var_off) ||
14649 			    (is_jmp32 &&
14650 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14651 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14652 						dst_reg,
14653 						src_reg->var_off.value,
14654 						tnum_subreg(src_reg->var_off).value,
14655 						opcode, is_jmp32);
14656 			else if (tnum_is_const(dst_reg->var_off) ||
14657 				 (is_jmp32 &&
14658 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14659 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14660 						    src_reg,
14661 						    dst_reg->var_off.value,
14662 						    tnum_subreg(dst_reg->var_off).value,
14663 						    opcode, is_jmp32);
14664 			else if (!is_jmp32 &&
14665 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14666 				/* Comparing for equality, we can combine knowledge */
14667 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14668 						    &other_branch_regs[insn->dst_reg],
14669 						    src_reg, dst_reg, opcode);
14670 			if (src_reg->id &&
14671 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14672 				find_equal_scalars(this_branch, src_reg);
14673 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14674 			}
14675 
14676 		}
14677 	} else if (dst_reg->type == SCALAR_VALUE) {
14678 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14679 					dst_reg, insn->imm, (u32)insn->imm,
14680 					opcode, is_jmp32);
14681 	}
14682 
14683 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14684 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14685 		find_equal_scalars(this_branch, dst_reg);
14686 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14687 	}
14688 
14689 	/* if one pointer register is compared to another pointer
14690 	 * register check if PTR_MAYBE_NULL could be lifted.
14691 	 * E.g. register A - maybe null
14692 	 *      register B - not null
14693 	 * for JNE A, B, ... - A is not null in the false branch;
14694 	 * for JEQ A, B, ... - A is not null in the true branch.
14695 	 *
14696 	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14697 	 * not need to be null checked by the BPF program, i.e.,
14698 	 * could be null even without PTR_MAYBE_NULL marking, so
14699 	 * only propagate nullness when neither reg is that type.
14700 	 */
14701 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14702 	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14703 	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14704 	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14705 	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14706 		eq_branch_regs = NULL;
14707 		switch (opcode) {
14708 		case BPF_JEQ:
14709 			eq_branch_regs = other_branch_regs;
14710 			break;
14711 		case BPF_JNE:
14712 			eq_branch_regs = regs;
14713 			break;
14714 		default:
14715 			/* do nothing */
14716 			break;
14717 		}
14718 		if (eq_branch_regs) {
14719 			if (type_may_be_null(src_reg->type))
14720 				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14721 			else
14722 				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14723 		}
14724 	}
14725 
14726 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14727 	 * NOTE: these optimizations below are related with pointer comparison
14728 	 *       which will never be JMP32.
14729 	 */
14730 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14731 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14732 	    type_may_be_null(dst_reg->type)) {
14733 		/* Mark all identical registers in each branch as either
14734 		 * safe or unknown depending R == 0 or R != 0 conditional.
14735 		 */
14736 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14737 				      opcode == BPF_JNE);
14738 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14739 				      opcode == BPF_JEQ);
14740 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14741 					   this_branch, other_branch) &&
14742 		   is_pointer_value(env, insn->dst_reg)) {
14743 		verbose(env, "R%d pointer comparison prohibited\n",
14744 			insn->dst_reg);
14745 		return -EACCES;
14746 	}
14747 	if (env->log.level & BPF_LOG_LEVEL)
14748 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14749 	return 0;
14750 }
14751 
14752 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)14753 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14754 {
14755 	struct bpf_insn_aux_data *aux = cur_aux(env);
14756 	struct bpf_reg_state *regs = cur_regs(env);
14757 	struct bpf_reg_state *dst_reg;
14758 	struct bpf_map *map;
14759 	int err;
14760 
14761 	if (BPF_SIZE(insn->code) != BPF_DW) {
14762 		verbose(env, "invalid BPF_LD_IMM insn\n");
14763 		return -EINVAL;
14764 	}
14765 	if (insn->off != 0) {
14766 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14767 		return -EINVAL;
14768 	}
14769 
14770 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14771 	if (err)
14772 		return err;
14773 
14774 	dst_reg = &regs[insn->dst_reg];
14775 	if (insn->src_reg == 0) {
14776 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14777 
14778 		dst_reg->type = SCALAR_VALUE;
14779 		__mark_reg_known(&regs[insn->dst_reg], imm);
14780 		return 0;
14781 	}
14782 
14783 	/* All special src_reg cases are listed below. From this point onwards
14784 	 * we either succeed and assign a corresponding dst_reg->type after
14785 	 * zeroing the offset, or fail and reject the program.
14786 	 */
14787 	mark_reg_known_zero(env, regs, insn->dst_reg);
14788 
14789 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14790 		dst_reg->type = aux->btf_var.reg_type;
14791 		switch (base_type(dst_reg->type)) {
14792 		case PTR_TO_MEM:
14793 			dst_reg->mem_size = aux->btf_var.mem_size;
14794 			break;
14795 		case PTR_TO_BTF_ID:
14796 			dst_reg->btf = aux->btf_var.btf;
14797 			dst_reg->btf_id = aux->btf_var.btf_id;
14798 			break;
14799 		default:
14800 			verbose(env, "bpf verifier is misconfigured\n");
14801 			return -EFAULT;
14802 		}
14803 		return 0;
14804 	}
14805 
14806 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14807 		struct bpf_prog_aux *aux = env->prog->aux;
14808 		u32 subprogno = find_subprog(env,
14809 					     env->insn_idx + insn->imm + 1);
14810 
14811 		if (!aux->func_info) {
14812 			verbose(env, "missing btf func_info\n");
14813 			return -EINVAL;
14814 		}
14815 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14816 			verbose(env, "callback function not static\n");
14817 			return -EINVAL;
14818 		}
14819 
14820 		dst_reg->type = PTR_TO_FUNC;
14821 		dst_reg->subprogno = subprogno;
14822 		return 0;
14823 	}
14824 
14825 	map = env->used_maps[aux->map_index];
14826 	dst_reg->map_ptr = map;
14827 
14828 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14829 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14830 		dst_reg->type = PTR_TO_MAP_VALUE;
14831 		dst_reg->off = aux->map_off;
14832 		WARN_ON_ONCE(map->max_entries != 1);
14833 		/* We want reg->id to be same (0) as map_value is not distinct */
14834 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14835 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14836 		dst_reg->type = CONST_PTR_TO_MAP;
14837 	} else {
14838 		verbose(env, "bpf verifier is misconfigured\n");
14839 		return -EINVAL;
14840 	}
14841 
14842 	return 0;
14843 }
14844 
may_access_skb(enum bpf_prog_type type)14845 static bool may_access_skb(enum bpf_prog_type type)
14846 {
14847 	switch (type) {
14848 	case BPF_PROG_TYPE_SOCKET_FILTER:
14849 	case BPF_PROG_TYPE_SCHED_CLS:
14850 	case BPF_PROG_TYPE_SCHED_ACT:
14851 		return true;
14852 	default:
14853 		return false;
14854 	}
14855 }
14856 
14857 /* verify safety of LD_ABS|LD_IND instructions:
14858  * - they can only appear in the programs where ctx == skb
14859  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14860  *   preserve R6-R9, and store return value into R0
14861  *
14862  * Implicit input:
14863  *   ctx == skb == R6 == CTX
14864  *
14865  * Explicit input:
14866  *   SRC == any register
14867  *   IMM == 32-bit immediate
14868  *
14869  * Output:
14870  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14871  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)14872 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14873 {
14874 	struct bpf_reg_state *regs = cur_regs(env);
14875 	static const int ctx_reg = BPF_REG_6;
14876 	u8 mode = BPF_MODE(insn->code);
14877 	int i, err;
14878 
14879 	if (!may_access_skb(resolve_prog_type(env->prog))) {
14880 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14881 		return -EINVAL;
14882 	}
14883 
14884 	if (!env->ops->gen_ld_abs) {
14885 		verbose(env, "bpf verifier is misconfigured\n");
14886 		return -EINVAL;
14887 	}
14888 
14889 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14890 	    BPF_SIZE(insn->code) == BPF_DW ||
14891 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14892 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14893 		return -EINVAL;
14894 	}
14895 
14896 	/* check whether implicit source operand (register R6) is readable */
14897 	err = check_reg_arg(env, ctx_reg, SRC_OP);
14898 	if (err)
14899 		return err;
14900 
14901 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14902 	 * gen_ld_abs() may terminate the program at runtime, leading to
14903 	 * reference leak.
14904 	 */
14905 	err = check_reference_leak(env);
14906 	if (err) {
14907 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14908 		return err;
14909 	}
14910 
14911 	if (env->cur_state->active_lock.ptr) {
14912 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14913 		return -EINVAL;
14914 	}
14915 
14916 	if (env->cur_state->active_rcu_lock) {
14917 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14918 		return -EINVAL;
14919 	}
14920 
14921 	if (regs[ctx_reg].type != PTR_TO_CTX) {
14922 		verbose(env,
14923 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14924 		return -EINVAL;
14925 	}
14926 
14927 	if (mode == BPF_IND) {
14928 		/* check explicit source operand */
14929 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14930 		if (err)
14931 			return err;
14932 	}
14933 
14934 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14935 	if (err < 0)
14936 		return err;
14937 
14938 	/* reset caller saved regs to unreadable */
14939 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14940 		mark_reg_not_init(env, regs, caller_saved[i]);
14941 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14942 	}
14943 
14944 	/* mark destination R0 register as readable, since it contains
14945 	 * the value fetched from the packet.
14946 	 * Already marked as written above.
14947 	 */
14948 	mark_reg_unknown(env, regs, BPF_REG_0);
14949 	/* ld_abs load up to 32-bit skb data. */
14950 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14951 	return 0;
14952 }
14953 
check_return_code(struct bpf_verifier_env * env)14954 static int check_return_code(struct bpf_verifier_env *env)
14955 {
14956 	struct tnum enforce_attach_type_range = tnum_unknown;
14957 	const struct bpf_prog *prog = env->prog;
14958 	struct bpf_reg_state *reg;
14959 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14960 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14961 	int err;
14962 	struct bpf_func_state *frame = env->cur_state->frame[0];
14963 	const bool is_subprog = frame->subprogno;
14964 
14965 	/* LSM and struct_ops func-ptr's return type could be "void" */
14966 	if (!is_subprog) {
14967 		switch (prog_type) {
14968 		case BPF_PROG_TYPE_LSM:
14969 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14970 				/* See below, can be 0 or 0-1 depending on hook. */
14971 				break;
14972 			fallthrough;
14973 		case BPF_PROG_TYPE_STRUCT_OPS:
14974 			if (!prog->aux->attach_func_proto->type)
14975 				return 0;
14976 			break;
14977 		default:
14978 			break;
14979 		}
14980 	}
14981 
14982 	/* eBPF calling convention is such that R0 is used
14983 	 * to return the value from eBPF program.
14984 	 * Make sure that it's readable at this time
14985 	 * of bpf_exit, which means that program wrote
14986 	 * something into it earlier
14987 	 */
14988 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14989 	if (err)
14990 		return err;
14991 
14992 	if (is_pointer_value(env, BPF_REG_0)) {
14993 		verbose(env, "R0 leaks addr as return value\n");
14994 		return -EACCES;
14995 	}
14996 
14997 	reg = cur_regs(env) + BPF_REG_0;
14998 
14999 	if (frame->in_async_callback_fn) {
15000 		/* enforce return zero from async callbacks like timer */
15001 		if (reg->type != SCALAR_VALUE) {
15002 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
15003 				reg_type_str(env, reg->type));
15004 			return -EINVAL;
15005 		}
15006 
15007 		if (!tnum_in(const_0, reg->var_off)) {
15008 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
15009 			return -EINVAL;
15010 		}
15011 		return 0;
15012 	}
15013 
15014 	if (is_subprog) {
15015 		if (reg->type != SCALAR_VALUE) {
15016 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
15017 				reg_type_str(env, reg->type));
15018 			return -EINVAL;
15019 		}
15020 		return 0;
15021 	}
15022 
15023 	switch (prog_type) {
15024 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15025 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15026 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15027 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15028 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15029 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15030 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15031 			range = tnum_range(1, 1);
15032 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15033 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15034 			range = tnum_range(0, 3);
15035 		break;
15036 	case BPF_PROG_TYPE_CGROUP_SKB:
15037 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15038 			range = tnum_range(0, 3);
15039 			enforce_attach_type_range = tnum_range(2, 3);
15040 		}
15041 		break;
15042 	case BPF_PROG_TYPE_CGROUP_SOCK:
15043 	case BPF_PROG_TYPE_SOCK_OPS:
15044 	case BPF_PROG_TYPE_CGROUP_DEVICE:
15045 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15046 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15047 		break;
15048 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15049 		if (!env->prog->aux->attach_btf_id)
15050 			return 0;
15051 		range = tnum_const(0);
15052 		break;
15053 	case BPF_PROG_TYPE_TRACING:
15054 		switch (env->prog->expected_attach_type) {
15055 		case BPF_TRACE_FENTRY:
15056 		case BPF_TRACE_FEXIT:
15057 			range = tnum_const(0);
15058 			break;
15059 		case BPF_TRACE_RAW_TP:
15060 		case BPF_MODIFY_RETURN:
15061 			return 0;
15062 		case BPF_TRACE_ITER:
15063 			break;
15064 		default:
15065 			return -ENOTSUPP;
15066 		}
15067 		break;
15068 	case BPF_PROG_TYPE_SK_LOOKUP:
15069 		range = tnum_range(SK_DROP, SK_PASS);
15070 		break;
15071 
15072 	case BPF_PROG_TYPE_LSM:
15073 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15074 			/* Regular BPF_PROG_TYPE_LSM programs can return
15075 			 * any value.
15076 			 */
15077 			return 0;
15078 		}
15079 		if (!env->prog->aux->attach_func_proto->type) {
15080 			/* Make sure programs that attach to void
15081 			 * hooks don't try to modify return value.
15082 			 */
15083 			range = tnum_range(1, 1);
15084 		}
15085 		break;
15086 
15087 	case BPF_PROG_TYPE_NETFILTER:
15088 		range = tnum_range(NF_DROP, NF_ACCEPT);
15089 		break;
15090 	case BPF_PROG_TYPE_EXT:
15091 		/* freplace program can return anything as its return value
15092 		 * depends on the to-be-replaced kernel func or bpf program.
15093 		 */
15094 	default:
15095 		return 0;
15096 	}
15097 
15098 	if (reg->type != SCALAR_VALUE) {
15099 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15100 			reg_type_str(env, reg->type));
15101 		return -EINVAL;
15102 	}
15103 
15104 	if (!tnum_in(range, reg->var_off)) {
15105 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15106 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15107 		    prog_type == BPF_PROG_TYPE_LSM &&
15108 		    !prog->aux->attach_func_proto->type)
15109 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15110 		return -EINVAL;
15111 	}
15112 
15113 	if (!tnum_is_unknown(enforce_attach_type_range) &&
15114 	    tnum_in(enforce_attach_type_range, reg->var_off))
15115 		env->prog->enforce_expected_attach_type = 1;
15116 	return 0;
15117 }
15118 
mark_subprog_changes_pkt_data(struct bpf_verifier_env * env,int off)15119 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
15120 {
15121 	struct bpf_subprog_info *subprog;
15122 
15123 	subprog = find_containing_subprog(env, off);
15124 	subprog->changes_pkt_data = true;
15125 }
15126 
15127 /* 't' is an index of a call-site.
15128  * 'w' is a callee entry point.
15129  * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
15130  * Rely on DFS traversal order and absence of recursive calls to guarantee that
15131  * callee's change_pkt_data marks would be correct at that moment.
15132  */
merge_callee_effects(struct bpf_verifier_env * env,int t,int w)15133 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
15134 {
15135 	struct bpf_subprog_info *caller, *callee;
15136 
15137 	caller = find_containing_subprog(env, t);
15138 	callee = find_containing_subprog(env, w);
15139 	caller->changes_pkt_data |= callee->changes_pkt_data;
15140 }
15141 
15142 /* non-recursive DFS pseudo code
15143  * 1  procedure DFS-iterative(G,v):
15144  * 2      label v as discovered
15145  * 3      let S be a stack
15146  * 4      S.push(v)
15147  * 5      while S is not empty
15148  * 6            t <- S.peek()
15149  * 7            if t is what we're looking for:
15150  * 8                return t
15151  * 9            for all edges e in G.adjacentEdges(t) do
15152  * 10               if edge e is already labelled
15153  * 11                   continue with the next edge
15154  * 12               w <- G.adjacentVertex(t,e)
15155  * 13               if vertex w is not discovered and not explored
15156  * 14                   label e as tree-edge
15157  * 15                   label w as discovered
15158  * 16                   S.push(w)
15159  * 17                   continue at 5
15160  * 18               else if vertex w is discovered
15161  * 19                   label e as back-edge
15162  * 20               else
15163  * 21                   // vertex w is explored
15164  * 22                   label e as forward- or cross-edge
15165  * 23           label t as explored
15166  * 24           S.pop()
15167  *
15168  * convention:
15169  * 0x10 - discovered
15170  * 0x11 - discovered and fall-through edge labelled
15171  * 0x12 - discovered and fall-through and branch edges labelled
15172  * 0x20 - explored
15173  */
15174 
15175 enum {
15176 	DISCOVERED = 0x10,
15177 	EXPLORED = 0x20,
15178 	FALLTHROUGH = 1,
15179 	BRANCH = 2,
15180 };
15181 
mark_prune_point(struct bpf_verifier_env * env,int idx)15182 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15183 {
15184 	env->insn_aux_data[idx].prune_point = true;
15185 }
15186 
is_prune_point(struct bpf_verifier_env * env,int insn_idx)15187 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15188 {
15189 	return env->insn_aux_data[insn_idx].prune_point;
15190 }
15191 
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)15192 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15193 {
15194 	env->insn_aux_data[idx].force_checkpoint = true;
15195 }
15196 
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)15197 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15198 {
15199 	return env->insn_aux_data[insn_idx].force_checkpoint;
15200 }
15201 
mark_calls_callback(struct bpf_verifier_env * env,int idx)15202 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15203 {
15204 	env->insn_aux_data[idx].calls_callback = true;
15205 }
15206 
calls_callback(struct bpf_verifier_env * env,int insn_idx)15207 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15208 {
15209 	return env->insn_aux_data[insn_idx].calls_callback;
15210 }
15211 
15212 enum {
15213 	DONE_EXPLORING = 0,
15214 	KEEP_EXPLORING = 1,
15215 };
15216 
15217 /* t, w, e - match pseudo-code above:
15218  * t - index of current instruction
15219  * w - next instruction
15220  * e - edge
15221  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)15222 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15223 {
15224 	int *insn_stack = env->cfg.insn_stack;
15225 	int *insn_state = env->cfg.insn_state;
15226 
15227 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15228 		return DONE_EXPLORING;
15229 
15230 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15231 		return DONE_EXPLORING;
15232 
15233 	if (w < 0 || w >= env->prog->len) {
15234 		verbose_linfo(env, t, "%d: ", t);
15235 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15236 		return -EINVAL;
15237 	}
15238 
15239 	if (e == BRANCH) {
15240 		/* mark branch target for state pruning */
15241 		mark_prune_point(env, w);
15242 		mark_jmp_point(env, w);
15243 	}
15244 
15245 	if (insn_state[w] == 0) {
15246 		/* tree-edge */
15247 		insn_state[t] = DISCOVERED | e;
15248 		insn_state[w] = DISCOVERED;
15249 		if (env->cfg.cur_stack >= env->prog->len)
15250 			return -E2BIG;
15251 		insn_stack[env->cfg.cur_stack++] = w;
15252 		return KEEP_EXPLORING;
15253 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15254 		if (env->bpf_capable)
15255 			return DONE_EXPLORING;
15256 		verbose_linfo(env, t, "%d: ", t);
15257 		verbose_linfo(env, w, "%d: ", w);
15258 		verbose(env, "back-edge from insn %d to %d\n", t, w);
15259 		return -EINVAL;
15260 	} else if (insn_state[w] == EXPLORED) {
15261 		/* forward- or cross-edge */
15262 		insn_state[t] = DISCOVERED | e;
15263 	} else {
15264 		verbose(env, "insn state internal bug\n");
15265 		return -EFAULT;
15266 	}
15267 	return DONE_EXPLORING;
15268 }
15269 
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)15270 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15271 				struct bpf_verifier_env *env,
15272 				bool visit_callee)
15273 {
15274 	int ret, insn_sz;
15275 	int w;
15276 
15277 	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15278 	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15279 	if (ret)
15280 		return ret;
15281 
15282 	mark_prune_point(env, t + insn_sz);
15283 	/* when we exit from subprog, we need to record non-linear history */
15284 	mark_jmp_point(env, t + insn_sz);
15285 
15286 	if (visit_callee) {
15287 		w = t + insns[t].imm + 1;
15288 		mark_prune_point(env, t);
15289 		merge_callee_effects(env, t, w);
15290 		ret = push_insn(t, w, BRANCH, env);
15291 	}
15292 	return ret;
15293 }
15294 
15295 /* Visits the instruction at index t and returns one of the following:
15296  *  < 0 - an error occurred
15297  *  DONE_EXPLORING - the instruction was fully explored
15298  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15299  */
visit_insn(int t,struct bpf_verifier_env * env)15300 static int visit_insn(int t, struct bpf_verifier_env *env)
15301 {
15302 	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15303 	int ret, off, insn_sz;
15304 
15305 	if (bpf_pseudo_func(insn))
15306 		return visit_func_call_insn(t, insns, env, true);
15307 
15308 	/* All non-branch instructions have a single fall-through edge. */
15309 	if (BPF_CLASS(insn->code) != BPF_JMP &&
15310 	    BPF_CLASS(insn->code) != BPF_JMP32) {
15311 		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15312 		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15313 	}
15314 
15315 	switch (BPF_OP(insn->code)) {
15316 	case BPF_EXIT:
15317 		return DONE_EXPLORING;
15318 
15319 	case BPF_CALL:
15320 		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15321 			/* Mark this call insn as a prune point to trigger
15322 			 * is_state_visited() check before call itself is
15323 			 * processed by __check_func_call(). Otherwise new
15324 			 * async state will be pushed for further exploration.
15325 			 */
15326 			mark_prune_point(env, t);
15327 		/* For functions that invoke callbacks it is not known how many times
15328 		 * callback would be called. Verifier models callback calling functions
15329 		 * by repeatedly visiting callback bodies and returning to origin call
15330 		 * instruction.
15331 		 * In order to stop such iteration verifier needs to identify when a
15332 		 * state identical some state from a previous iteration is reached.
15333 		 * Check below forces creation of checkpoint before callback calling
15334 		 * instruction to allow search for such identical states.
15335 		 */
15336 		if (is_sync_callback_calling_insn(insn)) {
15337 			mark_calls_callback(env, t);
15338 			mark_force_checkpoint(env, t);
15339 			mark_prune_point(env, t);
15340 			mark_jmp_point(env, t);
15341 		}
15342 		if (bpf_helper_call(insn) && bpf_helper_changes_pkt_data(insn->imm))
15343 			mark_subprog_changes_pkt_data(env, t);
15344 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15345 			struct bpf_kfunc_call_arg_meta meta;
15346 
15347 			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15348 			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15349 				mark_prune_point(env, t);
15350 				/* Checking and saving state checkpoints at iter_next() call
15351 				 * is crucial for fast convergence of open-coded iterator loop
15352 				 * logic, so we need to force it. If we don't do that,
15353 				 * is_state_visited() might skip saving a checkpoint, causing
15354 				 * unnecessarily long sequence of not checkpointed
15355 				 * instructions and jumps, leading to exhaustion of jump
15356 				 * history buffer, and potentially other undesired outcomes.
15357 				 * It is expected that with correct open-coded iterators
15358 				 * convergence will happen quickly, so we don't run a risk of
15359 				 * exhausting memory.
15360 				 */
15361 				mark_force_checkpoint(env, t);
15362 			}
15363 		}
15364 		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15365 
15366 	case BPF_JA:
15367 		if (BPF_SRC(insn->code) != BPF_K)
15368 			return -EINVAL;
15369 
15370 		if (BPF_CLASS(insn->code) == BPF_JMP)
15371 			off = insn->off;
15372 		else
15373 			off = insn->imm;
15374 
15375 		/* unconditional jump with single edge */
15376 		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15377 		if (ret)
15378 			return ret;
15379 
15380 		mark_prune_point(env, t + off + 1);
15381 		mark_jmp_point(env, t + off + 1);
15382 
15383 		return ret;
15384 
15385 	default:
15386 		/* conditional jump with two edges */
15387 		mark_prune_point(env, t);
15388 
15389 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15390 		if (ret)
15391 			return ret;
15392 
15393 		return push_insn(t, t + insn->off + 1, BRANCH, env);
15394 	}
15395 }
15396 
15397 /* non-recursive depth-first-search to detect loops in BPF program
15398  * loop == back-edge in directed graph
15399  */
check_cfg(struct bpf_verifier_env * env)15400 static int check_cfg(struct bpf_verifier_env *env)
15401 {
15402 	int insn_cnt = env->prog->len;
15403 	int *insn_stack, *insn_state;
15404 	int ret = 0;
15405 	int i;
15406 
15407 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15408 	if (!insn_state)
15409 		return -ENOMEM;
15410 
15411 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15412 	if (!insn_stack) {
15413 		kvfree(insn_state);
15414 		return -ENOMEM;
15415 	}
15416 
15417 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15418 	insn_stack[0] = 0; /* 0 is the first instruction */
15419 	env->cfg.cur_stack = 1;
15420 
15421 	while (env->cfg.cur_stack > 0) {
15422 		int t = insn_stack[env->cfg.cur_stack - 1];
15423 
15424 		ret = visit_insn(t, env);
15425 		switch (ret) {
15426 		case DONE_EXPLORING:
15427 			insn_state[t] = EXPLORED;
15428 			env->cfg.cur_stack--;
15429 			break;
15430 		case KEEP_EXPLORING:
15431 			break;
15432 		default:
15433 			if (ret > 0) {
15434 				verbose(env, "visit_insn internal bug\n");
15435 				ret = -EFAULT;
15436 			}
15437 			goto err_free;
15438 		}
15439 	}
15440 
15441 	if (env->cfg.cur_stack < 0) {
15442 		verbose(env, "pop stack internal bug\n");
15443 		ret = -EFAULT;
15444 		goto err_free;
15445 	}
15446 
15447 	for (i = 0; i < insn_cnt; i++) {
15448 		struct bpf_insn *insn = &env->prog->insnsi[i];
15449 
15450 		if (insn_state[i] != EXPLORED) {
15451 			verbose(env, "unreachable insn %d\n", i);
15452 			ret = -EINVAL;
15453 			goto err_free;
15454 		}
15455 		if (bpf_is_ldimm64(insn)) {
15456 			if (insn_state[i + 1] != 0) {
15457 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15458 				ret = -EINVAL;
15459 				goto err_free;
15460 			}
15461 			i++; /* skip second half of ldimm64 */
15462 		}
15463 	}
15464 	ret = 0; /* cfg looks good */
15465 	env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
15466 
15467 err_free:
15468 	kvfree(insn_state);
15469 	kvfree(insn_stack);
15470 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15471 	return ret;
15472 }
15473 
check_abnormal_return(struct bpf_verifier_env * env)15474 static int check_abnormal_return(struct bpf_verifier_env *env)
15475 {
15476 	int i;
15477 
15478 	for (i = 1; i < env->subprog_cnt; i++) {
15479 		if (env->subprog_info[i].has_ld_abs) {
15480 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15481 			return -EINVAL;
15482 		}
15483 		if (env->subprog_info[i].has_tail_call) {
15484 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15485 			return -EINVAL;
15486 		}
15487 	}
15488 	return 0;
15489 }
15490 
15491 /* The minimum supported BTF func info size */
15492 #define MIN_BPF_FUNCINFO_SIZE	8
15493 #define MAX_FUNCINFO_REC_SIZE	252
15494 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15495 static int check_btf_func(struct bpf_verifier_env *env,
15496 			  const union bpf_attr *attr,
15497 			  bpfptr_t uattr)
15498 {
15499 	const struct btf_type *type, *func_proto, *ret_type;
15500 	u32 i, nfuncs, urec_size, min_size;
15501 	u32 krec_size = sizeof(struct bpf_func_info);
15502 	struct bpf_func_info *krecord;
15503 	struct bpf_func_info_aux *info_aux = NULL;
15504 	struct bpf_prog *prog;
15505 	const struct btf *btf;
15506 	bpfptr_t urecord;
15507 	u32 prev_offset = 0;
15508 	bool scalar_return;
15509 	int ret = -ENOMEM;
15510 
15511 	nfuncs = attr->func_info_cnt;
15512 	if (!nfuncs) {
15513 		if (check_abnormal_return(env))
15514 			return -EINVAL;
15515 		return 0;
15516 	}
15517 
15518 	if (nfuncs != env->subprog_cnt) {
15519 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15520 		return -EINVAL;
15521 	}
15522 
15523 	urec_size = attr->func_info_rec_size;
15524 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15525 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15526 	    urec_size % sizeof(u32)) {
15527 		verbose(env, "invalid func info rec size %u\n", urec_size);
15528 		return -EINVAL;
15529 	}
15530 
15531 	prog = env->prog;
15532 	btf = prog->aux->btf;
15533 
15534 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15535 	min_size = min_t(u32, krec_size, urec_size);
15536 
15537 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15538 	if (!krecord)
15539 		return -ENOMEM;
15540 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15541 	if (!info_aux)
15542 		goto err_free;
15543 
15544 	for (i = 0; i < nfuncs; i++) {
15545 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15546 		if (ret) {
15547 			if (ret == -E2BIG) {
15548 				verbose(env, "nonzero tailing record in func info");
15549 				/* set the size kernel expects so loader can zero
15550 				 * out the rest of the record.
15551 				 */
15552 				if (copy_to_bpfptr_offset(uattr,
15553 							  offsetof(union bpf_attr, func_info_rec_size),
15554 							  &min_size, sizeof(min_size)))
15555 					ret = -EFAULT;
15556 			}
15557 			goto err_free;
15558 		}
15559 
15560 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15561 			ret = -EFAULT;
15562 			goto err_free;
15563 		}
15564 
15565 		/* check insn_off */
15566 		ret = -EINVAL;
15567 		if (i == 0) {
15568 			if (krecord[i].insn_off) {
15569 				verbose(env,
15570 					"nonzero insn_off %u for the first func info record",
15571 					krecord[i].insn_off);
15572 				goto err_free;
15573 			}
15574 		} else if (krecord[i].insn_off <= prev_offset) {
15575 			verbose(env,
15576 				"same or smaller insn offset (%u) than previous func info record (%u)",
15577 				krecord[i].insn_off, prev_offset);
15578 			goto err_free;
15579 		}
15580 
15581 		if (env->subprog_info[i].start != krecord[i].insn_off) {
15582 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15583 			goto err_free;
15584 		}
15585 
15586 		/* check type_id */
15587 		type = btf_type_by_id(btf, krecord[i].type_id);
15588 		if (!type || !btf_type_is_func(type)) {
15589 			verbose(env, "invalid type id %d in func info",
15590 				krecord[i].type_id);
15591 			goto err_free;
15592 		}
15593 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15594 
15595 		func_proto = btf_type_by_id(btf, type->type);
15596 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15597 			/* btf_func_check() already verified it during BTF load */
15598 			goto err_free;
15599 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15600 		scalar_return =
15601 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15602 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15603 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15604 			goto err_free;
15605 		}
15606 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15607 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15608 			goto err_free;
15609 		}
15610 
15611 		prev_offset = krecord[i].insn_off;
15612 		bpfptr_add(&urecord, urec_size);
15613 	}
15614 
15615 	prog->aux->func_info = krecord;
15616 	prog->aux->func_info_cnt = nfuncs;
15617 	prog->aux->func_info_aux = info_aux;
15618 	return 0;
15619 
15620 err_free:
15621 	kvfree(krecord);
15622 	kfree(info_aux);
15623 	return ret;
15624 }
15625 
adjust_btf_func(struct bpf_verifier_env * env)15626 static void adjust_btf_func(struct bpf_verifier_env *env)
15627 {
15628 	struct bpf_prog_aux *aux = env->prog->aux;
15629 	int i;
15630 
15631 	if (!aux->func_info)
15632 		return;
15633 
15634 	for (i = 0; i < env->subprog_cnt; i++)
15635 		aux->func_info[i].insn_off = env->subprog_info[i].start;
15636 }
15637 
15638 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15639 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15640 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15641 static int check_btf_line(struct bpf_verifier_env *env,
15642 			  const union bpf_attr *attr,
15643 			  bpfptr_t uattr)
15644 {
15645 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15646 	struct bpf_subprog_info *sub;
15647 	struct bpf_line_info *linfo;
15648 	struct bpf_prog *prog;
15649 	const struct btf *btf;
15650 	bpfptr_t ulinfo;
15651 	int err;
15652 
15653 	nr_linfo = attr->line_info_cnt;
15654 	if (!nr_linfo)
15655 		return 0;
15656 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15657 		return -EINVAL;
15658 
15659 	rec_size = attr->line_info_rec_size;
15660 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15661 	    rec_size > MAX_LINEINFO_REC_SIZE ||
15662 	    rec_size & (sizeof(u32) - 1))
15663 		return -EINVAL;
15664 
15665 	/* Need to zero it in case the userspace may
15666 	 * pass in a smaller bpf_line_info object.
15667 	 */
15668 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15669 			 GFP_KERNEL | __GFP_NOWARN);
15670 	if (!linfo)
15671 		return -ENOMEM;
15672 
15673 	prog = env->prog;
15674 	btf = prog->aux->btf;
15675 
15676 	s = 0;
15677 	sub = env->subprog_info;
15678 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15679 	expected_size = sizeof(struct bpf_line_info);
15680 	ncopy = min_t(u32, expected_size, rec_size);
15681 	for (i = 0; i < nr_linfo; i++) {
15682 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15683 		if (err) {
15684 			if (err == -E2BIG) {
15685 				verbose(env, "nonzero tailing record in line_info");
15686 				if (copy_to_bpfptr_offset(uattr,
15687 							  offsetof(union bpf_attr, line_info_rec_size),
15688 							  &expected_size, sizeof(expected_size)))
15689 					err = -EFAULT;
15690 			}
15691 			goto err_free;
15692 		}
15693 
15694 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15695 			err = -EFAULT;
15696 			goto err_free;
15697 		}
15698 
15699 		/*
15700 		 * Check insn_off to ensure
15701 		 * 1) strictly increasing AND
15702 		 * 2) bounded by prog->len
15703 		 *
15704 		 * The linfo[0].insn_off == 0 check logically falls into
15705 		 * the later "missing bpf_line_info for func..." case
15706 		 * because the first linfo[0].insn_off must be the
15707 		 * first sub also and the first sub must have
15708 		 * subprog_info[0].start == 0.
15709 		 */
15710 		if ((i && linfo[i].insn_off <= prev_offset) ||
15711 		    linfo[i].insn_off >= prog->len) {
15712 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15713 				i, linfo[i].insn_off, prev_offset,
15714 				prog->len);
15715 			err = -EINVAL;
15716 			goto err_free;
15717 		}
15718 
15719 		if (!prog->insnsi[linfo[i].insn_off].code) {
15720 			verbose(env,
15721 				"Invalid insn code at line_info[%u].insn_off\n",
15722 				i);
15723 			err = -EINVAL;
15724 			goto err_free;
15725 		}
15726 
15727 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15728 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15729 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15730 			err = -EINVAL;
15731 			goto err_free;
15732 		}
15733 
15734 		if (s != env->subprog_cnt) {
15735 			if (linfo[i].insn_off == sub[s].start) {
15736 				sub[s].linfo_idx = i;
15737 				s++;
15738 			} else if (sub[s].start < linfo[i].insn_off) {
15739 				verbose(env, "missing bpf_line_info for func#%u\n", s);
15740 				err = -EINVAL;
15741 				goto err_free;
15742 			}
15743 		}
15744 
15745 		prev_offset = linfo[i].insn_off;
15746 		bpfptr_add(&ulinfo, rec_size);
15747 	}
15748 
15749 	if (s != env->subprog_cnt) {
15750 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15751 			env->subprog_cnt - s, s);
15752 		err = -EINVAL;
15753 		goto err_free;
15754 	}
15755 
15756 	prog->aux->linfo = linfo;
15757 	prog->aux->nr_linfo = nr_linfo;
15758 
15759 	return 0;
15760 
15761 err_free:
15762 	kvfree(linfo);
15763 	return err;
15764 }
15765 
15766 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15767 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15768 
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15769 static int check_core_relo(struct bpf_verifier_env *env,
15770 			   const union bpf_attr *attr,
15771 			   bpfptr_t uattr)
15772 {
15773 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15774 	struct bpf_core_relo core_relo = {};
15775 	struct bpf_prog *prog = env->prog;
15776 	const struct btf *btf = prog->aux->btf;
15777 	struct bpf_core_ctx ctx = {
15778 		.log = &env->log,
15779 		.btf = btf,
15780 	};
15781 	bpfptr_t u_core_relo;
15782 	int err;
15783 
15784 	nr_core_relo = attr->core_relo_cnt;
15785 	if (!nr_core_relo)
15786 		return 0;
15787 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15788 		return -EINVAL;
15789 
15790 	rec_size = attr->core_relo_rec_size;
15791 	if (rec_size < MIN_CORE_RELO_SIZE ||
15792 	    rec_size > MAX_CORE_RELO_SIZE ||
15793 	    rec_size % sizeof(u32))
15794 		return -EINVAL;
15795 
15796 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15797 	expected_size = sizeof(struct bpf_core_relo);
15798 	ncopy = min_t(u32, expected_size, rec_size);
15799 
15800 	/* Unlike func_info and line_info, copy and apply each CO-RE
15801 	 * relocation record one at a time.
15802 	 */
15803 	for (i = 0; i < nr_core_relo; i++) {
15804 		/* future proofing when sizeof(bpf_core_relo) changes */
15805 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15806 		if (err) {
15807 			if (err == -E2BIG) {
15808 				verbose(env, "nonzero tailing record in core_relo");
15809 				if (copy_to_bpfptr_offset(uattr,
15810 							  offsetof(union bpf_attr, core_relo_rec_size),
15811 							  &expected_size, sizeof(expected_size)))
15812 					err = -EFAULT;
15813 			}
15814 			break;
15815 		}
15816 
15817 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15818 			err = -EFAULT;
15819 			break;
15820 		}
15821 
15822 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15823 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15824 				i, core_relo.insn_off, prog->len);
15825 			err = -EINVAL;
15826 			break;
15827 		}
15828 
15829 		err = bpf_core_apply(&ctx, &core_relo, i,
15830 				     &prog->insnsi[core_relo.insn_off / 8]);
15831 		if (err)
15832 			break;
15833 		bpfptr_add(&u_core_relo, rec_size);
15834 	}
15835 	return err;
15836 }
15837 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15838 static int check_btf_info(struct bpf_verifier_env *env,
15839 			  const union bpf_attr *attr,
15840 			  bpfptr_t uattr)
15841 {
15842 	struct btf *btf;
15843 	int err;
15844 
15845 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15846 		if (check_abnormal_return(env))
15847 			return -EINVAL;
15848 		return 0;
15849 	}
15850 
15851 	btf = btf_get_by_fd(attr->prog_btf_fd);
15852 	if (IS_ERR(btf))
15853 		return PTR_ERR(btf);
15854 	if (btf_is_kernel(btf)) {
15855 		btf_put(btf);
15856 		return -EACCES;
15857 	}
15858 	env->prog->aux->btf = btf;
15859 
15860 	err = check_btf_func(env, attr, uattr);
15861 	if (err)
15862 		return err;
15863 
15864 	err = check_btf_line(env, attr, uattr);
15865 	if (err)
15866 		return err;
15867 
15868 	err = check_core_relo(env, attr, uattr);
15869 	if (err)
15870 		return err;
15871 
15872 	return 0;
15873 }
15874 
15875 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)15876 static bool range_within(struct bpf_reg_state *old,
15877 			 struct bpf_reg_state *cur)
15878 {
15879 	return old->umin_value <= cur->umin_value &&
15880 	       old->umax_value >= cur->umax_value &&
15881 	       old->smin_value <= cur->smin_value &&
15882 	       old->smax_value >= cur->smax_value &&
15883 	       old->u32_min_value <= cur->u32_min_value &&
15884 	       old->u32_max_value >= cur->u32_max_value &&
15885 	       old->s32_min_value <= cur->s32_min_value &&
15886 	       old->s32_max_value >= cur->s32_max_value;
15887 }
15888 
15889 /* If in the old state two registers had the same id, then they need to have
15890  * the same id in the new state as well.  But that id could be different from
15891  * the old state, so we need to track the mapping from old to new ids.
15892  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15893  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15894  * regs with a different old id could still have new id 9, we don't care about
15895  * that.
15896  * So we look through our idmap to see if this old id has been seen before.  If
15897  * so, we require the new id to match; otherwise, we add the id pair to the map.
15898  */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)15899 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15900 {
15901 	struct bpf_id_pair *map = idmap->map;
15902 	unsigned int i;
15903 
15904 	/* either both IDs should be set or both should be zero */
15905 	if (!!old_id != !!cur_id)
15906 		return false;
15907 
15908 	if (old_id == 0) /* cur_id == 0 as well */
15909 		return true;
15910 
15911 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15912 		if (!map[i].old) {
15913 			/* Reached an empty slot; haven't seen this id before */
15914 			map[i].old = old_id;
15915 			map[i].cur = cur_id;
15916 			return true;
15917 		}
15918 		if (map[i].old == old_id)
15919 			return map[i].cur == cur_id;
15920 		if (map[i].cur == cur_id)
15921 			return false;
15922 	}
15923 	/* We ran out of idmap slots, which should be impossible */
15924 	WARN_ON_ONCE(1);
15925 	return false;
15926 }
15927 
15928 /* Similar to check_ids(), but allocate a unique temporary ID
15929  * for 'old_id' or 'cur_id' of zero.
15930  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15931  */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)15932 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15933 {
15934 	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15935 	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15936 
15937 	return check_ids(old_id, cur_id, idmap);
15938 }
15939 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)15940 static void clean_func_state(struct bpf_verifier_env *env,
15941 			     struct bpf_func_state *st)
15942 {
15943 	enum bpf_reg_liveness live;
15944 	int i, j;
15945 
15946 	for (i = 0; i < BPF_REG_FP; i++) {
15947 		live = st->regs[i].live;
15948 		/* liveness must not touch this register anymore */
15949 		st->regs[i].live |= REG_LIVE_DONE;
15950 		if (!(live & REG_LIVE_READ))
15951 			/* since the register is unused, clear its state
15952 			 * to make further comparison simpler
15953 			 */
15954 			__mark_reg_not_init(env, &st->regs[i]);
15955 	}
15956 
15957 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15958 		live = st->stack[i].spilled_ptr.live;
15959 		/* liveness must not touch this stack slot anymore */
15960 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15961 		if (!(live & REG_LIVE_READ)) {
15962 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15963 			for (j = 0; j < BPF_REG_SIZE; j++)
15964 				st->stack[i].slot_type[j] = STACK_INVALID;
15965 		}
15966 	}
15967 }
15968 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)15969 static void clean_verifier_state(struct bpf_verifier_env *env,
15970 				 struct bpf_verifier_state *st)
15971 {
15972 	int i;
15973 
15974 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15975 		/* all regs in this state in all frames were already marked */
15976 		return;
15977 
15978 	for (i = 0; i <= st->curframe; i++)
15979 		clean_func_state(env, st->frame[i]);
15980 }
15981 
15982 /* the parentage chains form a tree.
15983  * the verifier states are added to state lists at given insn and
15984  * pushed into state stack for future exploration.
15985  * when the verifier reaches bpf_exit insn some of the verifer states
15986  * stored in the state lists have their final liveness state already,
15987  * but a lot of states will get revised from liveness point of view when
15988  * the verifier explores other branches.
15989  * Example:
15990  * 1: r0 = 1
15991  * 2: if r1 == 100 goto pc+1
15992  * 3: r0 = 2
15993  * 4: exit
15994  * when the verifier reaches exit insn the register r0 in the state list of
15995  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15996  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15997  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15998  *
15999  * Since the verifier pushes the branch states as it sees them while exploring
16000  * the program the condition of walking the branch instruction for the second
16001  * time means that all states below this branch were already explored and
16002  * their final liveness marks are already propagated.
16003  * Hence when the verifier completes the search of state list in is_state_visited()
16004  * we can call this clean_live_states() function to mark all liveness states
16005  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16006  * will not be used.
16007  * This function also clears the registers and stack for states that !READ
16008  * to simplify state merging.
16009  *
16010  * Important note here that walking the same branch instruction in the callee
16011  * doesn't meant that the states are DONE. The verifier has to compare
16012  * the callsites
16013  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)16014 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16015 			      struct bpf_verifier_state *cur)
16016 {
16017 	struct bpf_verifier_state *loop_entry;
16018 	struct bpf_verifier_state_list *sl;
16019 
16020 	sl = *explored_state(env, insn);
16021 	while (sl) {
16022 		if (sl->state.branches)
16023 			goto next;
16024 		loop_entry = get_loop_entry(&sl->state);
16025 		if (loop_entry && loop_entry->branches)
16026 			goto next;
16027 		if (sl->state.insn_idx != insn ||
16028 		    !same_callsites(&sl->state, cur))
16029 			goto next;
16030 		clean_verifier_state(env, &sl->state);
16031 next:
16032 		sl = sl->next;
16033 	}
16034 }
16035 
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)16036 static bool regs_exact(const struct bpf_reg_state *rold,
16037 		       const struct bpf_reg_state *rcur,
16038 		       struct bpf_idmap *idmap)
16039 {
16040 	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16041 	       check_ids(rold->id, rcur->id, idmap) &&
16042 	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16043 }
16044 
16045 /* 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,bool exact)16046 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16047 		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16048 {
16049 	if (exact)
16050 		return regs_exact(rold, rcur, idmap);
16051 
16052 	if (!(rold->live & REG_LIVE_READ))
16053 		/* explored state didn't use this */
16054 		return true;
16055 	if (rold->type == NOT_INIT)
16056 		/* explored state can't have used this */
16057 		return true;
16058 	if (rcur->type == NOT_INIT)
16059 		return false;
16060 
16061 	/* Enforce that register types have to match exactly, including their
16062 	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16063 	 * rule.
16064 	 *
16065 	 * One can make a point that using a pointer register as unbounded
16066 	 * SCALAR would be technically acceptable, but this could lead to
16067 	 * pointer leaks because scalars are allowed to leak while pointers
16068 	 * are not. We could make this safe in special cases if root is
16069 	 * calling us, but it's probably not worth the hassle.
16070 	 *
16071 	 * Also, register types that are *not* MAYBE_NULL could technically be
16072 	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16073 	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16074 	 * to the same map).
16075 	 * However, if the old MAYBE_NULL register then got NULL checked,
16076 	 * doing so could have affected others with the same id, and we can't
16077 	 * check for that because we lost the id when we converted to
16078 	 * a non-MAYBE_NULL variant.
16079 	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16080 	 * non-MAYBE_NULL registers as well.
16081 	 */
16082 	if (rold->type != rcur->type)
16083 		return false;
16084 
16085 	switch (base_type(rold->type)) {
16086 	case SCALAR_VALUE:
16087 		if (env->explore_alu_limits) {
16088 			/* explore_alu_limits disables tnum_in() and range_within()
16089 			 * logic and requires everything to be strict
16090 			 */
16091 			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16092 			       check_scalar_ids(rold->id, rcur->id, idmap);
16093 		}
16094 		if (!rold->precise)
16095 			return true;
16096 		/* Why check_ids() for scalar registers?
16097 		 *
16098 		 * Consider the following BPF code:
16099 		 *   1: r6 = ... unbound scalar, ID=a ...
16100 		 *   2: r7 = ... unbound scalar, ID=b ...
16101 		 *   3: if (r6 > r7) goto +1
16102 		 *   4: r6 = r7
16103 		 *   5: if (r6 > X) goto ...
16104 		 *   6: ... memory operation using r7 ...
16105 		 *
16106 		 * First verification path is [1-6]:
16107 		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16108 		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16109 		 *   r7 <= X, because r6 and r7 share same id.
16110 		 * Next verification path is [1-4, 6].
16111 		 *
16112 		 * Instruction (6) would be reached in two states:
16113 		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16114 		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16115 		 *
16116 		 * Use check_ids() to distinguish these states.
16117 		 * ---
16118 		 * Also verify that new value satisfies old value range knowledge.
16119 		 */
16120 		return range_within(rold, rcur) &&
16121 		       tnum_in(rold->var_off, rcur->var_off) &&
16122 		       check_scalar_ids(rold->id, rcur->id, idmap);
16123 	case PTR_TO_MAP_KEY:
16124 	case PTR_TO_MAP_VALUE:
16125 	case PTR_TO_MEM:
16126 	case PTR_TO_BUF:
16127 	case PTR_TO_TP_BUFFER:
16128 		/* If the new min/max/var_off satisfy the old ones and
16129 		 * everything else matches, we are OK.
16130 		 */
16131 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16132 		       range_within(rold, rcur) &&
16133 		       tnum_in(rold->var_off, rcur->var_off) &&
16134 		       check_ids(rold->id, rcur->id, idmap) &&
16135 		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16136 	case PTR_TO_PACKET_META:
16137 	case PTR_TO_PACKET:
16138 		/* We must have at least as much range as the old ptr
16139 		 * did, so that any accesses which were safe before are
16140 		 * still safe.  This is true even if old range < old off,
16141 		 * since someone could have accessed through (ptr - k), or
16142 		 * even done ptr -= k in a register, to get a safe access.
16143 		 */
16144 		if (rold->range > rcur->range)
16145 			return false;
16146 		/* If the offsets don't match, we can't trust our alignment;
16147 		 * nor can we be sure that we won't fall out of range.
16148 		 */
16149 		if (rold->off != rcur->off)
16150 			return false;
16151 		/* id relations must be preserved */
16152 		if (!check_ids(rold->id, rcur->id, idmap))
16153 			return false;
16154 		/* new val must satisfy old val knowledge */
16155 		return range_within(rold, rcur) &&
16156 		       tnum_in(rold->var_off, rcur->var_off);
16157 	case PTR_TO_STACK:
16158 		/* two stack pointers are equal only if they're pointing to
16159 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16160 		 */
16161 		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16162 	default:
16163 		return regs_exact(rold, rcur, idmap);
16164 	}
16165 }
16166 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,bool exact)16167 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16168 		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16169 {
16170 	int i, spi;
16171 
16172 	/* walk slots of the explored stack and ignore any additional
16173 	 * slots in the current stack, since explored(safe) state
16174 	 * didn't use them
16175 	 */
16176 	for (i = 0; i < old->allocated_stack; i++) {
16177 		struct bpf_reg_state *old_reg, *cur_reg;
16178 
16179 		spi = i / BPF_REG_SIZE;
16180 
16181 		if (exact &&
16182 		    (i >= cur->allocated_stack ||
16183 		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16184 		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16185 			return false;
16186 
16187 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16188 			i += BPF_REG_SIZE - 1;
16189 			/* explored state didn't use this */
16190 			continue;
16191 		}
16192 
16193 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16194 			continue;
16195 
16196 		if (env->allow_uninit_stack &&
16197 		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16198 			continue;
16199 
16200 		/* explored stack has more populated slots than current stack
16201 		 * and these slots were used
16202 		 */
16203 		if (i >= cur->allocated_stack)
16204 			return false;
16205 
16206 		/* if old state was safe with misc data in the stack
16207 		 * it will be safe with zero-initialized stack.
16208 		 * The opposite is not true
16209 		 */
16210 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16211 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16212 			continue;
16213 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16214 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16215 			/* Ex: old explored (safe) state has STACK_SPILL in
16216 			 * this stack slot, but current has STACK_MISC ->
16217 			 * this verifier states are not equivalent,
16218 			 * return false to continue verification of this path
16219 			 */
16220 			return false;
16221 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16222 			continue;
16223 		/* Both old and cur are having same slot_type */
16224 		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16225 		case STACK_SPILL:
16226 			/* when explored and current stack slot are both storing
16227 			 * spilled registers, check that stored pointers types
16228 			 * are the same as well.
16229 			 * Ex: explored safe path could have stored
16230 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16231 			 * but current path has stored:
16232 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16233 			 * such verifier states are not equivalent.
16234 			 * return false to continue verification of this path
16235 			 */
16236 			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16237 				     &cur->stack[spi].spilled_ptr, idmap, exact))
16238 				return false;
16239 			break;
16240 		case STACK_DYNPTR:
16241 			old_reg = &old->stack[spi].spilled_ptr;
16242 			cur_reg = &cur->stack[spi].spilled_ptr;
16243 			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16244 			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16245 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16246 				return false;
16247 			break;
16248 		case STACK_ITER:
16249 			old_reg = &old->stack[spi].spilled_ptr;
16250 			cur_reg = &cur->stack[spi].spilled_ptr;
16251 			/* iter.depth is not compared between states as it
16252 			 * doesn't matter for correctness and would otherwise
16253 			 * prevent convergence; we maintain it only to prevent
16254 			 * infinite loop check triggering, see
16255 			 * iter_active_depths_differ()
16256 			 */
16257 			if (old_reg->iter.btf != cur_reg->iter.btf ||
16258 			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16259 			    old_reg->iter.state != cur_reg->iter.state ||
16260 			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16261 			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16262 				return false;
16263 			break;
16264 		case STACK_MISC:
16265 		case STACK_ZERO:
16266 		case STACK_INVALID:
16267 			continue;
16268 		/* Ensure that new unhandled slot types return false by default */
16269 		default:
16270 			return false;
16271 		}
16272 	}
16273 	return true;
16274 }
16275 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap)16276 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16277 		    struct bpf_idmap *idmap)
16278 {
16279 	int i;
16280 
16281 	if (old->acquired_refs != cur->acquired_refs)
16282 		return false;
16283 
16284 	for (i = 0; i < old->acquired_refs; i++) {
16285 		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16286 			return false;
16287 	}
16288 
16289 	return true;
16290 }
16291 
16292 /* compare two verifier states
16293  *
16294  * all states stored in state_list are known to be valid, since
16295  * verifier reached 'bpf_exit' instruction through them
16296  *
16297  * this function is called when verifier exploring different branches of
16298  * execution popped from the state stack. If it sees an old state that has
16299  * more strict register state and more strict stack state then this execution
16300  * branch doesn't need to be explored further, since verifier already
16301  * concluded that more strict state leads to valid finish.
16302  *
16303  * Therefore two states are equivalent if register state is more conservative
16304  * and explored stack state is more conservative than the current one.
16305  * Example:
16306  *       explored                   current
16307  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16308  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16309  *
16310  * In other words if current stack state (one being explored) has more
16311  * valid slots than old one that already passed validation, it means
16312  * the verifier can stop exploring and conclude that current state is valid too
16313  *
16314  * Similarly with registers. If explored state has register type as invalid
16315  * whereas register type in current state is meaningful, it means that
16316  * the current state will reach 'bpf_exit' instruction safely
16317  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,bool exact)16318 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16319 			      struct bpf_func_state *cur, bool exact)
16320 {
16321 	int i;
16322 
16323 	if (old->callback_depth > cur->callback_depth)
16324 		return false;
16325 
16326 	for (i = 0; i < MAX_BPF_REG; i++)
16327 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16328 			     &env->idmap_scratch, exact))
16329 			return false;
16330 
16331 	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16332 		return false;
16333 
16334 	if (!refsafe(old, cur, &env->idmap_scratch))
16335 		return false;
16336 
16337 	return true;
16338 }
16339 
reset_idmap_scratch(struct bpf_verifier_env * env)16340 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16341 {
16342 	env->idmap_scratch.tmp_id_gen = env->id_gen;
16343 	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16344 }
16345 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool exact)16346 static bool states_equal(struct bpf_verifier_env *env,
16347 			 struct bpf_verifier_state *old,
16348 			 struct bpf_verifier_state *cur,
16349 			 bool exact)
16350 {
16351 	int i;
16352 
16353 	if (old->curframe != cur->curframe)
16354 		return false;
16355 
16356 	reset_idmap_scratch(env);
16357 
16358 	/* Verification state from speculative execution simulation
16359 	 * must never prune a non-speculative execution one.
16360 	 */
16361 	if (old->speculative && !cur->speculative)
16362 		return false;
16363 
16364 	if (old->active_lock.ptr != cur->active_lock.ptr)
16365 		return false;
16366 
16367 	/* Old and cur active_lock's have to be either both present
16368 	 * or both absent.
16369 	 */
16370 	if (!!old->active_lock.id != !!cur->active_lock.id)
16371 		return false;
16372 
16373 	if (old->active_lock.id &&
16374 	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16375 		return false;
16376 
16377 	if (old->active_rcu_lock != cur->active_rcu_lock)
16378 		return false;
16379 
16380 	/* for states to be equal callsites have to be the same
16381 	 * and all frame states need to be equivalent
16382 	 */
16383 	for (i = 0; i <= old->curframe; i++) {
16384 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16385 			return false;
16386 		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16387 			return false;
16388 	}
16389 	return true;
16390 }
16391 
16392 /* Return 0 if no propagation happened. Return negative error code if error
16393  * happened. Otherwise, return the propagated bit.
16394  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)16395 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16396 				  struct bpf_reg_state *reg,
16397 				  struct bpf_reg_state *parent_reg)
16398 {
16399 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16400 	u8 flag = reg->live & REG_LIVE_READ;
16401 	int err;
16402 
16403 	/* When comes here, read flags of PARENT_REG or REG could be any of
16404 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16405 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16406 	 */
16407 	if (parent_flag == REG_LIVE_READ64 ||
16408 	    /* Or if there is no read flag from REG. */
16409 	    !flag ||
16410 	    /* Or if the read flag from REG is the same as PARENT_REG. */
16411 	    parent_flag == flag)
16412 		return 0;
16413 
16414 	err = mark_reg_read(env, reg, parent_reg, flag);
16415 	if (err)
16416 		return err;
16417 
16418 	return flag;
16419 }
16420 
16421 /* A write screens off any subsequent reads; but write marks come from the
16422  * straight-line code between a state and its parent.  When we arrive at an
16423  * equivalent state (jump target or such) we didn't arrive by the straight-line
16424  * code, so read marks in the state must propagate to the parent regardless
16425  * of the state's write marks. That's what 'parent == state->parent' comparison
16426  * in mark_reg_read() is for.
16427  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)16428 static int propagate_liveness(struct bpf_verifier_env *env,
16429 			      const struct bpf_verifier_state *vstate,
16430 			      struct bpf_verifier_state *vparent)
16431 {
16432 	struct bpf_reg_state *state_reg, *parent_reg;
16433 	struct bpf_func_state *state, *parent;
16434 	int i, frame, err = 0;
16435 
16436 	if (vparent->curframe != vstate->curframe) {
16437 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16438 		     vparent->curframe, vstate->curframe);
16439 		return -EFAULT;
16440 	}
16441 	/* Propagate read liveness of registers... */
16442 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16443 	for (frame = 0; frame <= vstate->curframe; frame++) {
16444 		parent = vparent->frame[frame];
16445 		state = vstate->frame[frame];
16446 		parent_reg = parent->regs;
16447 		state_reg = state->regs;
16448 		/* We don't need to worry about FP liveness, it's read-only */
16449 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16450 			err = propagate_liveness_reg(env, &state_reg[i],
16451 						     &parent_reg[i]);
16452 			if (err < 0)
16453 				return err;
16454 			if (err == REG_LIVE_READ64)
16455 				mark_insn_zext(env, &parent_reg[i]);
16456 		}
16457 
16458 		/* Propagate stack slots. */
16459 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16460 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16461 			parent_reg = &parent->stack[i].spilled_ptr;
16462 			state_reg = &state->stack[i].spilled_ptr;
16463 			err = propagate_liveness_reg(env, state_reg,
16464 						     parent_reg);
16465 			if (err < 0)
16466 				return err;
16467 		}
16468 	}
16469 	return 0;
16470 }
16471 
16472 /* find precise scalars in the previous equivalent state and
16473  * propagate them into the current state
16474  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)16475 static int propagate_precision(struct bpf_verifier_env *env,
16476 			       const struct bpf_verifier_state *old)
16477 {
16478 	struct bpf_reg_state *state_reg;
16479 	struct bpf_func_state *state;
16480 	int i, err = 0, fr;
16481 	bool first;
16482 
16483 	for (fr = old->curframe; fr >= 0; fr--) {
16484 		state = old->frame[fr];
16485 		state_reg = state->regs;
16486 		first = true;
16487 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16488 			if (state_reg->type != SCALAR_VALUE ||
16489 			    !state_reg->precise ||
16490 			    !(state_reg->live & REG_LIVE_READ))
16491 				continue;
16492 			if (env->log.level & BPF_LOG_LEVEL2) {
16493 				if (first)
16494 					verbose(env, "frame %d: propagating r%d", fr, i);
16495 				else
16496 					verbose(env, ",r%d", i);
16497 			}
16498 			bt_set_frame_reg(&env->bt, fr, i);
16499 			first = false;
16500 		}
16501 
16502 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16503 			if (!is_spilled_reg(&state->stack[i]))
16504 				continue;
16505 			state_reg = &state->stack[i].spilled_ptr;
16506 			if (state_reg->type != SCALAR_VALUE ||
16507 			    !state_reg->precise ||
16508 			    !(state_reg->live & REG_LIVE_READ))
16509 				continue;
16510 			if (env->log.level & BPF_LOG_LEVEL2) {
16511 				if (first)
16512 					verbose(env, "frame %d: propagating fp%d",
16513 						fr, (-i - 1) * BPF_REG_SIZE);
16514 				else
16515 					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16516 			}
16517 			bt_set_frame_slot(&env->bt, fr, i);
16518 			first = false;
16519 		}
16520 		if (!first)
16521 			verbose(env, "\n");
16522 	}
16523 
16524 	err = mark_chain_precision_batch(env);
16525 	if (err < 0)
16526 		return err;
16527 
16528 	return 0;
16529 }
16530 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)16531 static bool states_maybe_looping(struct bpf_verifier_state *old,
16532 				 struct bpf_verifier_state *cur)
16533 {
16534 	struct bpf_func_state *fold, *fcur;
16535 	int i, fr = cur->curframe;
16536 
16537 	if (old->curframe != fr)
16538 		return false;
16539 
16540 	fold = old->frame[fr];
16541 	fcur = cur->frame[fr];
16542 	for (i = 0; i < MAX_BPF_REG; i++)
16543 		if (memcmp(&fold->regs[i], &fcur->regs[i],
16544 			   offsetof(struct bpf_reg_state, parent)))
16545 			return false;
16546 	return true;
16547 }
16548 
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)16549 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16550 {
16551 	return env->insn_aux_data[insn_idx].is_iter_next;
16552 }
16553 
16554 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16555  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16556  * states to match, which otherwise would look like an infinite loop. So while
16557  * iter_next() calls are taken care of, we still need to be careful and
16558  * prevent erroneous and too eager declaration of "ininite loop", when
16559  * iterators are involved.
16560  *
16561  * Here's a situation in pseudo-BPF assembly form:
16562  *
16563  *   0: again:                          ; set up iter_next() call args
16564  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16565  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16566  *   3:   if r0 == 0 goto done
16567  *   4:   ... something useful here ...
16568  *   5:   goto again                    ; another iteration
16569  *   6: done:
16570  *   7:   r1 = &it
16571  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16572  *   9:   exit
16573  *
16574  * This is a typical loop. Let's assume that we have a prune point at 1:,
16575  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16576  * again`, assuming other heuristics don't get in a way).
16577  *
16578  * When we first time come to 1:, let's say we have some state X. We proceed
16579  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16580  * Now we come back to validate that forked ACTIVE state. We proceed through
16581  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16582  * are converging. But the problem is that we don't know that yet, as this
16583  * convergence has to happen at iter_next() call site only. So if nothing is
16584  * done, at 1: verifier will use bounded loop logic and declare infinite
16585  * looping (and would be *technically* correct, if not for iterator's
16586  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16587  * don't want that. So what we do in process_iter_next_call() when we go on
16588  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16589  * a different iteration. So when we suspect an infinite loop, we additionally
16590  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16591  * pretend we are not looping and wait for next iter_next() call.
16592  *
16593  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16594  * loop, because that would actually mean infinite loop, as DRAINED state is
16595  * "sticky", and so we'll keep returning into the same instruction with the
16596  * same state (at least in one of possible code paths).
16597  *
16598  * This approach allows to keep infinite loop heuristic even in the face of
16599  * active iterator. E.g., C snippet below is and will be detected as
16600  * inifintely looping:
16601  *
16602  *   struct bpf_iter_num it;
16603  *   int *p, x;
16604  *
16605  *   bpf_iter_num_new(&it, 0, 10);
16606  *   while ((p = bpf_iter_num_next(&t))) {
16607  *       x = p;
16608  *       while (x--) {} // <<-- infinite loop here
16609  *   }
16610  *
16611  */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)16612 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16613 {
16614 	struct bpf_reg_state *slot, *cur_slot;
16615 	struct bpf_func_state *state;
16616 	int i, fr;
16617 
16618 	for (fr = old->curframe; fr >= 0; fr--) {
16619 		state = old->frame[fr];
16620 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16621 			if (state->stack[i].slot_type[0] != STACK_ITER)
16622 				continue;
16623 
16624 			slot = &state->stack[i].spilled_ptr;
16625 			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16626 				continue;
16627 
16628 			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16629 			if (cur_slot->iter.depth != slot->iter.depth)
16630 				return true;
16631 		}
16632 	}
16633 	return false;
16634 }
16635 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)16636 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16637 {
16638 	struct bpf_verifier_state_list *new_sl;
16639 	struct bpf_verifier_state_list *sl, **pprev;
16640 	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16641 	int i, j, n, err, states_cnt = 0;
16642 	bool force_new_state, add_new_state, force_exact;
16643 
16644 	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
16645 			  /* Avoid accumulating infinitely long jmp history */
16646 			  cur->jmp_history_cnt > 40;
16647 
16648 	/* bpf progs typically have pruning point every 4 instructions
16649 	 * http://vger.kernel.org/bpfconf2019.html#session-1
16650 	 * Do not add new state for future pruning if the verifier hasn't seen
16651 	 * at least 2 jumps and at least 8 instructions.
16652 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16653 	 * In tests that amounts to up to 50% reduction into total verifier
16654 	 * memory consumption and 20% verifier time speedup.
16655 	 */
16656 	add_new_state = force_new_state;
16657 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16658 	    env->insn_processed - env->prev_insn_processed >= 8)
16659 		add_new_state = true;
16660 
16661 	pprev = explored_state(env, insn_idx);
16662 	sl = *pprev;
16663 
16664 	clean_live_states(env, insn_idx, cur);
16665 
16666 	while (sl) {
16667 		states_cnt++;
16668 		if (sl->state.insn_idx != insn_idx)
16669 			goto next;
16670 
16671 		if (sl->state.branches) {
16672 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16673 
16674 			if (frame->in_async_callback_fn &&
16675 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16676 				/* Different async_entry_cnt means that the verifier is
16677 				 * processing another entry into async callback.
16678 				 * Seeing the same state is not an indication of infinite
16679 				 * loop or infinite recursion.
16680 				 * But finding the same state doesn't mean that it's safe
16681 				 * to stop processing the current state. The previous state
16682 				 * hasn't yet reached bpf_exit, since state.branches > 0.
16683 				 * Checking in_async_callback_fn alone is not enough either.
16684 				 * Since the verifier still needs to catch infinite loops
16685 				 * inside async callbacks.
16686 				 */
16687 				goto skip_inf_loop_check;
16688 			}
16689 			/* BPF open-coded iterators loop detection is special.
16690 			 * states_maybe_looping() logic is too simplistic in detecting
16691 			 * states that *might* be equivalent, because it doesn't know
16692 			 * about ID remapping, so don't even perform it.
16693 			 * See process_iter_next_call() and iter_active_depths_differ()
16694 			 * for overview of the logic. When current and one of parent
16695 			 * states are detected as equivalent, it's a good thing: we prove
16696 			 * convergence and can stop simulating further iterations.
16697 			 * It's safe to assume that iterator loop will finish, taking into
16698 			 * account iter_next() contract of eventually returning
16699 			 * sticky NULL result.
16700 			 *
16701 			 * Note, that states have to be compared exactly in this case because
16702 			 * read and precision marks might not be finalized inside the loop.
16703 			 * E.g. as in the program below:
16704 			 *
16705 			 *     1. r7 = -16
16706 			 *     2. r6 = bpf_get_prandom_u32()
16707 			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16708 			 *     4.   if (r6 != 42) {
16709 			 *     5.     r7 = -32
16710 			 *     6.     r6 = bpf_get_prandom_u32()
16711 			 *     7.     continue
16712 			 *     8.   }
16713 			 *     9.   r0 = r10
16714 			 *    10.   r0 += r7
16715 			 *    11.   r8 = *(u64 *)(r0 + 0)
16716 			 *    12.   r6 = bpf_get_prandom_u32()
16717 			 *    13. }
16718 			 *
16719 			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16720 			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16721 			 * not have read or precision mark for r7 yet, thus inexact states
16722 			 * comparison would discard current state with r7=-32
16723 			 * => unsafe memory access at 11 would not be caught.
16724 			 */
16725 			if (is_iter_next_insn(env, insn_idx)) {
16726 				if (states_equal(env, &sl->state, cur, true)) {
16727 					struct bpf_func_state *cur_frame;
16728 					struct bpf_reg_state *iter_state, *iter_reg;
16729 					int spi;
16730 
16731 					cur_frame = cur->frame[cur->curframe];
16732 					/* btf_check_iter_kfuncs() enforces that
16733 					 * iter state pointer is always the first arg
16734 					 */
16735 					iter_reg = &cur_frame->regs[BPF_REG_1];
16736 					/* current state is valid due to states_equal(),
16737 					 * so we can assume valid iter and reg state,
16738 					 * no need for extra (re-)validations
16739 					 */
16740 					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16741 					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16742 					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16743 						update_loop_entry(cur, &sl->state);
16744 						goto hit;
16745 					}
16746 				}
16747 				goto skip_inf_loop_check;
16748 			}
16749 			if (calls_callback(env, insn_idx)) {
16750 				if (states_equal(env, &sl->state, cur, true))
16751 					goto hit;
16752 				goto skip_inf_loop_check;
16753 			}
16754 			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16755 			if (states_maybe_looping(&sl->state, cur) &&
16756 			    states_equal(env, &sl->state, cur, false) &&
16757 			    !iter_active_depths_differ(&sl->state, cur) &&
16758 			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16759 				verbose_linfo(env, insn_idx, "; ");
16760 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16761 				verbose(env, "cur state:");
16762 				print_verifier_state(env, cur->frame[cur->curframe], true);
16763 				verbose(env, "old state:");
16764 				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16765 				return -EINVAL;
16766 			}
16767 			/* if the verifier is processing a loop, avoid adding new state
16768 			 * too often, since different loop iterations have distinct
16769 			 * states and may not help future pruning.
16770 			 * This threshold shouldn't be too low to make sure that
16771 			 * a loop with large bound will be rejected quickly.
16772 			 * The most abusive loop will be:
16773 			 * r1 += 1
16774 			 * if r1 < 1000000 goto pc-2
16775 			 * 1M insn_procssed limit / 100 == 10k peak states.
16776 			 * This threshold shouldn't be too high either, since states
16777 			 * at the end of the loop are likely to be useful in pruning.
16778 			 */
16779 skip_inf_loop_check:
16780 			if (!force_new_state &&
16781 			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16782 			    env->insn_processed - env->prev_insn_processed < 100)
16783 				add_new_state = false;
16784 			goto miss;
16785 		}
16786 		/* If sl->state is a part of a loop and this loop's entry is a part of
16787 		 * current verification path then states have to be compared exactly.
16788 		 * 'force_exact' is needed to catch the following case:
16789 		 *
16790 		 *                initial     Here state 'succ' was processed first,
16791 		 *                  |         it was eventually tracked to produce a
16792 		 *                  V         state identical to 'hdr'.
16793 		 *     .---------> hdr        All branches from 'succ' had been explored
16794 		 *     |            |         and thus 'succ' has its .branches == 0.
16795 		 *     |            V
16796 		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16797 		 *     |    |       |         to the same instruction + callsites.
16798 		 *     |    V       V         In such case it is necessary to check
16799 		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16800 		 *     |    |       |         If 'succ' and 'cur' are a part of the
16801 		 *     |    V       V         same loop exact flag has to be set.
16802 		 *     |   succ <- cur        To check if that is the case, verify
16803 		 *     |    |                 if loop entry of 'succ' is in current
16804 		 *     |    V                 DFS path.
16805 		 *     |   ...
16806 		 *     |    |
16807 		 *     '----'
16808 		 *
16809 		 * Additional details are in the comment before get_loop_entry().
16810 		 */
16811 		loop_entry = get_loop_entry(&sl->state);
16812 		force_exact = loop_entry && loop_entry->branches > 0;
16813 		if (states_equal(env, &sl->state, cur, force_exact)) {
16814 			if (force_exact)
16815 				update_loop_entry(cur, loop_entry);
16816 hit:
16817 			sl->hit_cnt++;
16818 			/* reached equivalent register/stack state,
16819 			 * prune the search.
16820 			 * Registers read by the continuation are read by us.
16821 			 * If we have any write marks in env->cur_state, they
16822 			 * will prevent corresponding reads in the continuation
16823 			 * from reaching our parent (an explored_state).  Our
16824 			 * own state will get the read marks recorded, but
16825 			 * they'll be immediately forgotten as we're pruning
16826 			 * this state and will pop a new one.
16827 			 */
16828 			err = propagate_liveness(env, &sl->state, cur);
16829 
16830 			/* if previous state reached the exit with precision and
16831 			 * current state is equivalent to it (except precsion marks)
16832 			 * the precision needs to be propagated back in
16833 			 * the current state.
16834 			 */
16835 			err = err ? : push_jmp_history(env, cur);
16836 			err = err ? : propagate_precision(env, &sl->state);
16837 			if (err)
16838 				return err;
16839 			return 1;
16840 		}
16841 miss:
16842 		/* when new state is not going to be added do not increase miss count.
16843 		 * Otherwise several loop iterations will remove the state
16844 		 * recorded earlier. The goal of these heuristics is to have
16845 		 * states from some iterations of the loop (some in the beginning
16846 		 * and some at the end) to help pruning.
16847 		 */
16848 		if (add_new_state)
16849 			sl->miss_cnt++;
16850 		/* heuristic to determine whether this state is beneficial
16851 		 * to keep checking from state equivalence point of view.
16852 		 * Higher numbers increase max_states_per_insn and verification time,
16853 		 * but do not meaningfully decrease insn_processed.
16854 		 * 'n' controls how many times state could miss before eviction.
16855 		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16856 		 * too early would hinder iterator convergence.
16857 		 */
16858 		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16859 		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16860 			/* the state is unlikely to be useful. Remove it to
16861 			 * speed up verification
16862 			 */
16863 			*pprev = sl->next;
16864 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16865 			    !sl->state.used_as_loop_entry) {
16866 				u32 br = sl->state.branches;
16867 
16868 				WARN_ONCE(br,
16869 					  "BUG live_done but branches_to_explore %d\n",
16870 					  br);
16871 				free_verifier_state(&sl->state, false);
16872 				kfree(sl);
16873 				env->peak_states--;
16874 			} else {
16875 				/* cannot free this state, since parentage chain may
16876 				 * walk it later. Add it for free_list instead to
16877 				 * be freed at the end of verification
16878 				 */
16879 				sl->next = env->free_list;
16880 				env->free_list = sl;
16881 			}
16882 			sl = *pprev;
16883 			continue;
16884 		}
16885 next:
16886 		pprev = &sl->next;
16887 		sl = *pprev;
16888 	}
16889 
16890 	if (env->max_states_per_insn < states_cnt)
16891 		env->max_states_per_insn = states_cnt;
16892 
16893 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16894 		return 0;
16895 
16896 	if (!add_new_state)
16897 		return 0;
16898 
16899 	/* There were no equivalent states, remember the current one.
16900 	 * Technically the current state is not proven to be safe yet,
16901 	 * but it will either reach outer most bpf_exit (which means it's safe)
16902 	 * or it will be rejected. When there are no loops the verifier won't be
16903 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16904 	 * again on the way to bpf_exit.
16905 	 * When looping the sl->state.branches will be > 0 and this state
16906 	 * will not be considered for equivalence until branches == 0.
16907 	 */
16908 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16909 	if (!new_sl)
16910 		return -ENOMEM;
16911 	env->total_states++;
16912 	env->peak_states++;
16913 	env->prev_jmps_processed = env->jmps_processed;
16914 	env->prev_insn_processed = env->insn_processed;
16915 
16916 	/* forget precise markings we inherited, see __mark_chain_precision */
16917 	if (env->bpf_capable)
16918 		mark_all_scalars_imprecise(env, cur);
16919 
16920 	/* add new state to the head of linked list */
16921 	new = &new_sl->state;
16922 	err = copy_verifier_state(new, cur);
16923 	if (err) {
16924 		free_verifier_state(new, false);
16925 		kfree(new_sl);
16926 		return err;
16927 	}
16928 	new->insn_idx = insn_idx;
16929 	WARN_ONCE(new->branches != 1,
16930 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16931 
16932 	cur->parent = new;
16933 	cur->first_insn_idx = insn_idx;
16934 	cur->dfs_depth = new->dfs_depth + 1;
16935 	clear_jmp_history(cur);
16936 	new_sl->next = *explored_state(env, insn_idx);
16937 	*explored_state(env, insn_idx) = new_sl;
16938 	/* connect new state to parentage chain. Current frame needs all
16939 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16940 	 * to the stack implicitly by JITs) so in callers' frames connect just
16941 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16942 	 * the state of the call instruction (with WRITTEN set), and r0 comes
16943 	 * from callee with its full parentage chain, anyway.
16944 	 */
16945 	/* clear write marks in current state: the writes we did are not writes
16946 	 * our child did, so they don't screen off its reads from us.
16947 	 * (There are no read marks in current state, because reads always mark
16948 	 * their parent and current state never has children yet.  Only
16949 	 * explored_states can get read marks.)
16950 	 */
16951 	for (j = 0; j <= cur->curframe; j++) {
16952 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16953 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16954 		for (i = 0; i < BPF_REG_FP; i++)
16955 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16956 	}
16957 
16958 	/* all stack frames are accessible from callee, clear them all */
16959 	for (j = 0; j <= cur->curframe; j++) {
16960 		struct bpf_func_state *frame = cur->frame[j];
16961 		struct bpf_func_state *newframe = new->frame[j];
16962 
16963 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16964 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16965 			frame->stack[i].spilled_ptr.parent =
16966 						&newframe->stack[i].spilled_ptr;
16967 		}
16968 	}
16969 	return 0;
16970 }
16971 
16972 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)16973 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16974 {
16975 	switch (base_type(type)) {
16976 	case PTR_TO_CTX:
16977 	case PTR_TO_SOCKET:
16978 	case PTR_TO_SOCK_COMMON:
16979 	case PTR_TO_TCP_SOCK:
16980 	case PTR_TO_XDP_SOCK:
16981 	case PTR_TO_BTF_ID:
16982 		return false;
16983 	default:
16984 		return true;
16985 	}
16986 }
16987 
16988 /* If an instruction was previously used with particular pointer types, then we
16989  * need to be careful to avoid cases such as the below, where it may be ok
16990  * for one branch accessing the pointer, but not ok for the other branch:
16991  *
16992  * R1 = sock_ptr
16993  * goto X;
16994  * ...
16995  * R1 = some_other_valid_ptr;
16996  * goto X;
16997  * ...
16998  * R2 = *(u32 *)(R1 + 0);
16999  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)17000 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17001 {
17002 	return src != prev && (!reg_type_mismatch_ok(src) ||
17003 			       !reg_type_mismatch_ok(prev));
17004 }
17005 
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_missmatch)17006 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17007 			     bool allow_trust_missmatch)
17008 {
17009 	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17010 
17011 	if (*prev_type == NOT_INIT) {
17012 		/* Saw a valid insn
17013 		 * dst_reg = *(u32 *)(src_reg + off)
17014 		 * save type to validate intersecting paths
17015 		 */
17016 		*prev_type = type;
17017 	} else if (reg_type_mismatch(type, *prev_type)) {
17018 		/* Abuser program is trying to use the same insn
17019 		 * dst_reg = *(u32*) (src_reg + off)
17020 		 * with different pointer types:
17021 		 * src_reg == ctx in one branch and
17022 		 * src_reg == stack|map in some other branch.
17023 		 * Reject it.
17024 		 */
17025 		if (allow_trust_missmatch &&
17026 		    base_type(type) == PTR_TO_BTF_ID &&
17027 		    base_type(*prev_type) == PTR_TO_BTF_ID) {
17028 			/*
17029 			 * Have to support a use case when one path through
17030 			 * the program yields TRUSTED pointer while another
17031 			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
17032 			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17033 			 */
17034 			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17035 		} else {
17036 			verbose(env, "same insn cannot be used with different pointers\n");
17037 			return -EINVAL;
17038 		}
17039 	}
17040 
17041 	return 0;
17042 }
17043 
do_check(struct bpf_verifier_env * env)17044 static int do_check(struct bpf_verifier_env *env)
17045 {
17046 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17047 	struct bpf_verifier_state *state = env->cur_state;
17048 	struct bpf_insn *insns = env->prog->insnsi;
17049 	struct bpf_reg_state *regs;
17050 	int insn_cnt = env->prog->len;
17051 	bool do_print_state = false;
17052 	int prev_insn_idx = -1;
17053 
17054 	for (;;) {
17055 		struct bpf_insn *insn;
17056 		u8 class;
17057 		int err;
17058 
17059 		env->prev_insn_idx = prev_insn_idx;
17060 		if (env->insn_idx >= insn_cnt) {
17061 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17062 				env->insn_idx, insn_cnt);
17063 			return -EFAULT;
17064 		}
17065 
17066 		insn = &insns[env->insn_idx];
17067 		class = BPF_CLASS(insn->code);
17068 
17069 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17070 			verbose(env,
17071 				"BPF program is too large. Processed %d insn\n",
17072 				env->insn_processed);
17073 			return -E2BIG;
17074 		}
17075 
17076 		state->last_insn_idx = env->prev_insn_idx;
17077 
17078 		if (is_prune_point(env, env->insn_idx)) {
17079 			err = is_state_visited(env, env->insn_idx);
17080 			if (err < 0)
17081 				return err;
17082 			if (err == 1) {
17083 				/* found equivalent state, can prune the search */
17084 				if (env->log.level & BPF_LOG_LEVEL) {
17085 					if (do_print_state)
17086 						verbose(env, "\nfrom %d to %d%s: safe\n",
17087 							env->prev_insn_idx, env->insn_idx,
17088 							env->cur_state->speculative ?
17089 							" (speculative execution)" : "");
17090 					else
17091 						verbose(env, "%d: safe\n", env->insn_idx);
17092 				}
17093 				goto process_bpf_exit;
17094 			}
17095 		}
17096 
17097 		if (is_jmp_point(env, env->insn_idx)) {
17098 			err = push_jmp_history(env, state);
17099 			if (err)
17100 				return err;
17101 		}
17102 
17103 		if (signal_pending(current))
17104 			return -EAGAIN;
17105 
17106 		if (need_resched())
17107 			cond_resched();
17108 
17109 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17110 			verbose(env, "\nfrom %d to %d%s:",
17111 				env->prev_insn_idx, env->insn_idx,
17112 				env->cur_state->speculative ?
17113 				" (speculative execution)" : "");
17114 			print_verifier_state(env, state->frame[state->curframe], true);
17115 			do_print_state = false;
17116 		}
17117 
17118 		if (env->log.level & BPF_LOG_LEVEL) {
17119 			const struct bpf_insn_cbs cbs = {
17120 				.cb_call	= disasm_kfunc_name,
17121 				.cb_print	= verbose,
17122 				.private_data	= env,
17123 			};
17124 
17125 			if (verifier_state_scratched(env))
17126 				print_insn_state(env, state->frame[state->curframe]);
17127 
17128 			verbose_linfo(env, env->insn_idx, "; ");
17129 			env->prev_log_pos = env->log.end_pos;
17130 			verbose(env, "%d: ", env->insn_idx);
17131 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17132 			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17133 			env->prev_log_pos = env->log.end_pos;
17134 		}
17135 
17136 		if (bpf_prog_is_offloaded(env->prog->aux)) {
17137 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17138 							   env->prev_insn_idx);
17139 			if (err)
17140 				return err;
17141 		}
17142 
17143 		regs = cur_regs(env);
17144 		sanitize_mark_insn_seen(env);
17145 		prev_insn_idx = env->insn_idx;
17146 
17147 		if (class == BPF_ALU || class == BPF_ALU64) {
17148 			err = check_alu_op(env, insn);
17149 			if (err)
17150 				return err;
17151 
17152 		} else if (class == BPF_LDX) {
17153 			enum bpf_reg_type src_reg_type;
17154 
17155 			/* check for reserved fields is already done */
17156 
17157 			/* check src operand */
17158 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17159 			if (err)
17160 				return err;
17161 
17162 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17163 			if (err)
17164 				return err;
17165 
17166 			src_reg_type = regs[insn->src_reg].type;
17167 
17168 			/* check that memory (src_reg + off) is readable,
17169 			 * the state of dst_reg will be updated by this func
17170 			 */
17171 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17172 					       insn->off, BPF_SIZE(insn->code),
17173 					       BPF_READ, insn->dst_reg, false,
17174 					       BPF_MODE(insn->code) == BPF_MEMSX);
17175 			if (err)
17176 				return err;
17177 
17178 			err = save_aux_ptr_type(env, src_reg_type, true);
17179 			if (err)
17180 				return err;
17181 		} else if (class == BPF_STX) {
17182 			enum bpf_reg_type dst_reg_type;
17183 
17184 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17185 				err = check_atomic(env, env->insn_idx, insn);
17186 				if (err)
17187 					return err;
17188 				env->insn_idx++;
17189 				continue;
17190 			}
17191 
17192 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17193 				verbose(env, "BPF_STX uses reserved fields\n");
17194 				return -EINVAL;
17195 			}
17196 
17197 			/* check src1 operand */
17198 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17199 			if (err)
17200 				return err;
17201 			/* check src2 operand */
17202 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17203 			if (err)
17204 				return err;
17205 
17206 			dst_reg_type = regs[insn->dst_reg].type;
17207 
17208 			/* check that memory (dst_reg + off) is writeable */
17209 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17210 					       insn->off, BPF_SIZE(insn->code),
17211 					       BPF_WRITE, insn->src_reg, false, false);
17212 			if (err)
17213 				return err;
17214 
17215 			err = save_aux_ptr_type(env, dst_reg_type, false);
17216 			if (err)
17217 				return err;
17218 		} else if (class == BPF_ST) {
17219 			enum bpf_reg_type dst_reg_type;
17220 
17221 			if (BPF_MODE(insn->code) != BPF_MEM ||
17222 			    insn->src_reg != BPF_REG_0) {
17223 				verbose(env, "BPF_ST uses reserved fields\n");
17224 				return -EINVAL;
17225 			}
17226 			/* check src operand */
17227 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17228 			if (err)
17229 				return err;
17230 
17231 			dst_reg_type = regs[insn->dst_reg].type;
17232 
17233 			/* check that memory (dst_reg + off) is writeable */
17234 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17235 					       insn->off, BPF_SIZE(insn->code),
17236 					       BPF_WRITE, -1, false, false);
17237 			if (err)
17238 				return err;
17239 
17240 			err = save_aux_ptr_type(env, dst_reg_type, false);
17241 			if (err)
17242 				return err;
17243 		} else if (class == BPF_JMP || class == BPF_JMP32) {
17244 			u8 opcode = BPF_OP(insn->code);
17245 
17246 			env->jmps_processed++;
17247 			if (opcode == BPF_CALL) {
17248 				if (BPF_SRC(insn->code) != BPF_K ||
17249 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17250 				     && insn->off != 0) ||
17251 				    (insn->src_reg != BPF_REG_0 &&
17252 				     insn->src_reg != BPF_PSEUDO_CALL &&
17253 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17254 				    insn->dst_reg != BPF_REG_0 ||
17255 				    class == BPF_JMP32) {
17256 					verbose(env, "BPF_CALL uses reserved fields\n");
17257 					return -EINVAL;
17258 				}
17259 
17260 				if (env->cur_state->active_lock.ptr) {
17261 					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17262 					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17263 					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17264 					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17265 						verbose(env, "function calls are not allowed while holding a lock\n");
17266 						return -EINVAL;
17267 					}
17268 				}
17269 				if (insn->src_reg == BPF_PSEUDO_CALL)
17270 					err = check_func_call(env, insn, &env->insn_idx);
17271 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17272 					err = check_kfunc_call(env, insn, &env->insn_idx);
17273 				else
17274 					err = check_helper_call(env, insn, &env->insn_idx);
17275 				if (err)
17276 					return err;
17277 
17278 				mark_reg_scratched(env, BPF_REG_0);
17279 			} else if (opcode == BPF_JA) {
17280 				if (BPF_SRC(insn->code) != BPF_K ||
17281 				    insn->src_reg != BPF_REG_0 ||
17282 				    insn->dst_reg != BPF_REG_0 ||
17283 				    (class == BPF_JMP && insn->imm != 0) ||
17284 				    (class == BPF_JMP32 && insn->off != 0)) {
17285 					verbose(env, "BPF_JA uses reserved fields\n");
17286 					return -EINVAL;
17287 				}
17288 
17289 				if (class == BPF_JMP)
17290 					env->insn_idx += insn->off + 1;
17291 				else
17292 					env->insn_idx += insn->imm + 1;
17293 				continue;
17294 
17295 			} else if (opcode == BPF_EXIT) {
17296 				if (BPF_SRC(insn->code) != BPF_K ||
17297 				    insn->imm != 0 ||
17298 				    insn->src_reg != BPF_REG_0 ||
17299 				    insn->dst_reg != BPF_REG_0 ||
17300 				    class == BPF_JMP32) {
17301 					verbose(env, "BPF_EXIT uses reserved fields\n");
17302 					return -EINVAL;
17303 				}
17304 
17305 				if (env->cur_state->active_lock.ptr &&
17306 				    !in_rbtree_lock_required_cb(env)) {
17307 					verbose(env, "bpf_spin_unlock is missing\n");
17308 					return -EINVAL;
17309 				}
17310 
17311 				if (env->cur_state->active_rcu_lock &&
17312 				    !in_rbtree_lock_required_cb(env)) {
17313 					verbose(env, "bpf_rcu_read_unlock is missing\n");
17314 					return -EINVAL;
17315 				}
17316 
17317 				/* We must do check_reference_leak here before
17318 				 * prepare_func_exit to handle the case when
17319 				 * state->curframe > 0, it may be a callback
17320 				 * function, for which reference_state must
17321 				 * match caller reference state when it exits.
17322 				 */
17323 				err = check_reference_leak(env);
17324 				if (err)
17325 					return err;
17326 
17327 				if (state->curframe) {
17328 					/* exit from nested function */
17329 					err = prepare_func_exit(env, &env->insn_idx);
17330 					if (err)
17331 						return err;
17332 					do_print_state = true;
17333 					continue;
17334 				}
17335 
17336 				err = check_return_code(env);
17337 				if (err)
17338 					return err;
17339 process_bpf_exit:
17340 				mark_verifier_state_scratched(env);
17341 				update_branch_counts(env, env->cur_state);
17342 				err = pop_stack(env, &prev_insn_idx,
17343 						&env->insn_idx, pop_log);
17344 				if (err < 0) {
17345 					if (err != -ENOENT)
17346 						return err;
17347 					break;
17348 				} else {
17349 					do_print_state = true;
17350 					continue;
17351 				}
17352 			} else {
17353 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17354 				if (err)
17355 					return err;
17356 			}
17357 		} else if (class == BPF_LD) {
17358 			u8 mode = BPF_MODE(insn->code);
17359 
17360 			if (mode == BPF_ABS || mode == BPF_IND) {
17361 				err = check_ld_abs(env, insn);
17362 				if (err)
17363 					return err;
17364 
17365 			} else if (mode == BPF_IMM) {
17366 				err = check_ld_imm(env, insn);
17367 				if (err)
17368 					return err;
17369 
17370 				env->insn_idx++;
17371 				sanitize_mark_insn_seen(env);
17372 			} else {
17373 				verbose(env, "invalid BPF_LD mode\n");
17374 				return -EINVAL;
17375 			}
17376 		} else {
17377 			verbose(env, "unknown insn class %d\n", class);
17378 			return -EINVAL;
17379 		}
17380 
17381 		env->insn_idx++;
17382 	}
17383 
17384 	return 0;
17385 }
17386 
find_btf_percpu_datasec(struct btf * btf)17387 static int find_btf_percpu_datasec(struct btf *btf)
17388 {
17389 	const struct btf_type *t;
17390 	const char *tname;
17391 	int i, n;
17392 
17393 	/*
17394 	 * Both vmlinux and module each have their own ".data..percpu"
17395 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17396 	 * types to look at only module's own BTF types.
17397 	 */
17398 	n = btf_nr_types(btf);
17399 	if (btf_is_module(btf))
17400 		i = btf_nr_types(btf_vmlinux);
17401 	else
17402 		i = 1;
17403 
17404 	for(; i < n; i++) {
17405 		t = btf_type_by_id(btf, i);
17406 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17407 			continue;
17408 
17409 		tname = btf_name_by_offset(btf, t->name_off);
17410 		if (!strcmp(tname, ".data..percpu"))
17411 			return i;
17412 	}
17413 
17414 	return -ENOENT;
17415 }
17416 
17417 /* 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)17418 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17419 			       struct bpf_insn *insn,
17420 			       struct bpf_insn_aux_data *aux)
17421 {
17422 	const struct btf_var_secinfo *vsi;
17423 	const struct btf_type *datasec;
17424 	struct btf_mod_pair *btf_mod;
17425 	const struct btf_type *t;
17426 	const char *sym_name;
17427 	bool percpu = false;
17428 	u32 type, id = insn->imm;
17429 	struct btf *btf;
17430 	s32 datasec_id;
17431 	u64 addr;
17432 	int i, btf_fd, err;
17433 
17434 	btf_fd = insn[1].imm;
17435 	if (btf_fd) {
17436 		btf = btf_get_by_fd(btf_fd);
17437 		if (IS_ERR(btf)) {
17438 			verbose(env, "invalid module BTF object FD specified.\n");
17439 			return -EINVAL;
17440 		}
17441 	} else {
17442 		if (!btf_vmlinux) {
17443 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17444 			return -EINVAL;
17445 		}
17446 		btf = btf_vmlinux;
17447 		btf_get(btf);
17448 	}
17449 
17450 	t = btf_type_by_id(btf, id);
17451 	if (!t) {
17452 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17453 		err = -ENOENT;
17454 		goto err_put;
17455 	}
17456 
17457 	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17458 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17459 		err = -EINVAL;
17460 		goto err_put;
17461 	}
17462 
17463 	sym_name = btf_name_by_offset(btf, t->name_off);
17464 	addr = kallsyms_lookup_name(sym_name);
17465 	if (!addr) {
17466 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17467 			sym_name);
17468 		err = -ENOENT;
17469 		goto err_put;
17470 	}
17471 	insn[0].imm = (u32)addr;
17472 	insn[1].imm = addr >> 32;
17473 
17474 	if (btf_type_is_func(t)) {
17475 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17476 		aux->btf_var.mem_size = 0;
17477 		goto check_btf;
17478 	}
17479 
17480 	datasec_id = find_btf_percpu_datasec(btf);
17481 	if (datasec_id > 0) {
17482 		datasec = btf_type_by_id(btf, datasec_id);
17483 		for_each_vsi(i, datasec, vsi) {
17484 			if (vsi->type == id) {
17485 				percpu = true;
17486 				break;
17487 			}
17488 		}
17489 	}
17490 
17491 	type = t->type;
17492 	t = btf_type_skip_modifiers(btf, type, NULL);
17493 	if (percpu) {
17494 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17495 		aux->btf_var.btf = btf;
17496 		aux->btf_var.btf_id = type;
17497 	} else if (!btf_type_is_struct(t)) {
17498 		const struct btf_type *ret;
17499 		const char *tname;
17500 		u32 tsize;
17501 
17502 		/* resolve the type size of ksym. */
17503 		ret = btf_resolve_size(btf, t, &tsize);
17504 		if (IS_ERR(ret)) {
17505 			tname = btf_name_by_offset(btf, t->name_off);
17506 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17507 				tname, PTR_ERR(ret));
17508 			err = -EINVAL;
17509 			goto err_put;
17510 		}
17511 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17512 		aux->btf_var.mem_size = tsize;
17513 	} else {
17514 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17515 		aux->btf_var.btf = btf;
17516 		aux->btf_var.btf_id = type;
17517 	}
17518 check_btf:
17519 	/* check whether we recorded this BTF (and maybe module) already */
17520 	for (i = 0; i < env->used_btf_cnt; i++) {
17521 		if (env->used_btfs[i].btf == btf) {
17522 			btf_put(btf);
17523 			return 0;
17524 		}
17525 	}
17526 
17527 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17528 		err = -E2BIG;
17529 		goto err_put;
17530 	}
17531 
17532 	btf_mod = &env->used_btfs[env->used_btf_cnt];
17533 	btf_mod->btf = btf;
17534 	btf_mod->module = NULL;
17535 
17536 	/* if we reference variables from kernel module, bump its refcount */
17537 	if (btf_is_module(btf)) {
17538 		btf_mod->module = btf_try_get_module(btf);
17539 		if (!btf_mod->module) {
17540 			err = -ENXIO;
17541 			goto err_put;
17542 		}
17543 	}
17544 
17545 	env->used_btf_cnt++;
17546 
17547 	return 0;
17548 err_put:
17549 	btf_put(btf);
17550 	return err;
17551 }
17552 
is_tracing_prog_type(enum bpf_prog_type type)17553 static bool is_tracing_prog_type(enum bpf_prog_type type)
17554 {
17555 	switch (type) {
17556 	case BPF_PROG_TYPE_KPROBE:
17557 	case BPF_PROG_TYPE_TRACEPOINT:
17558 	case BPF_PROG_TYPE_PERF_EVENT:
17559 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17560 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17561 		return true;
17562 	default:
17563 		return false;
17564 	}
17565 }
17566 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)17567 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17568 					struct bpf_map *map,
17569 					struct bpf_prog *prog)
17570 
17571 {
17572 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17573 
17574 	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17575 	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17576 		if (is_tracing_prog_type(prog_type)) {
17577 			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17578 			return -EINVAL;
17579 		}
17580 	}
17581 
17582 	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17583 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17584 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17585 			return -EINVAL;
17586 		}
17587 
17588 		if (is_tracing_prog_type(prog_type)) {
17589 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17590 			return -EINVAL;
17591 		}
17592 	}
17593 
17594 	if (btf_record_has_field(map->record, BPF_TIMER)) {
17595 		if (is_tracing_prog_type(prog_type)) {
17596 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17597 			return -EINVAL;
17598 		}
17599 	}
17600 
17601 	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17602 	    !bpf_offload_prog_map_match(prog, map)) {
17603 		verbose(env, "offload device mismatch between prog and map\n");
17604 		return -EINVAL;
17605 	}
17606 
17607 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17608 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17609 		return -EINVAL;
17610 	}
17611 
17612 	if (prog->aux->sleepable)
17613 		switch (map->map_type) {
17614 		case BPF_MAP_TYPE_HASH:
17615 		case BPF_MAP_TYPE_LRU_HASH:
17616 		case BPF_MAP_TYPE_ARRAY:
17617 		case BPF_MAP_TYPE_PERCPU_HASH:
17618 		case BPF_MAP_TYPE_PERCPU_ARRAY:
17619 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17620 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17621 		case BPF_MAP_TYPE_HASH_OF_MAPS:
17622 		case BPF_MAP_TYPE_RINGBUF:
17623 		case BPF_MAP_TYPE_USER_RINGBUF:
17624 		case BPF_MAP_TYPE_INODE_STORAGE:
17625 		case BPF_MAP_TYPE_SK_STORAGE:
17626 		case BPF_MAP_TYPE_TASK_STORAGE:
17627 		case BPF_MAP_TYPE_CGRP_STORAGE:
17628 			break;
17629 		default:
17630 			verbose(env,
17631 				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17632 			return -EINVAL;
17633 		}
17634 
17635 	return 0;
17636 }
17637 
bpf_map_is_cgroup_storage(struct bpf_map * map)17638 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17639 {
17640 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17641 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17642 }
17643 
17644 /* find and rewrite pseudo imm in ld_imm64 instructions:
17645  *
17646  * 1. if it accesses map FD, replace it with actual map pointer.
17647  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17648  *
17649  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17650  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)17651 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17652 {
17653 	struct bpf_insn *insn = env->prog->insnsi;
17654 	int insn_cnt = env->prog->len;
17655 	int i, j, err;
17656 
17657 	err = bpf_prog_calc_tag(env->prog);
17658 	if (err)
17659 		return err;
17660 
17661 	for (i = 0; i < insn_cnt; i++, insn++) {
17662 		if (BPF_CLASS(insn->code) == BPF_LDX &&
17663 		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17664 		    insn->imm != 0)) {
17665 			verbose(env, "BPF_LDX uses reserved fields\n");
17666 			return -EINVAL;
17667 		}
17668 
17669 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17670 			struct bpf_insn_aux_data *aux;
17671 			struct bpf_map *map;
17672 			struct fd f;
17673 			u64 addr;
17674 			u32 fd;
17675 
17676 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17677 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17678 			    insn[1].off != 0) {
17679 				verbose(env, "invalid bpf_ld_imm64 insn\n");
17680 				return -EINVAL;
17681 			}
17682 
17683 			if (insn[0].src_reg == 0)
17684 				/* valid generic load 64-bit imm */
17685 				goto next_insn;
17686 
17687 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17688 				aux = &env->insn_aux_data[i];
17689 				err = check_pseudo_btf_id(env, insn, aux);
17690 				if (err)
17691 					return err;
17692 				goto next_insn;
17693 			}
17694 
17695 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17696 				aux = &env->insn_aux_data[i];
17697 				aux->ptr_type = PTR_TO_FUNC;
17698 				goto next_insn;
17699 			}
17700 
17701 			/* In final convert_pseudo_ld_imm64() step, this is
17702 			 * converted into regular 64-bit imm load insn.
17703 			 */
17704 			switch (insn[0].src_reg) {
17705 			case BPF_PSEUDO_MAP_VALUE:
17706 			case BPF_PSEUDO_MAP_IDX_VALUE:
17707 				break;
17708 			case BPF_PSEUDO_MAP_FD:
17709 			case BPF_PSEUDO_MAP_IDX:
17710 				if (insn[1].imm == 0)
17711 					break;
17712 				fallthrough;
17713 			default:
17714 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17715 				return -EINVAL;
17716 			}
17717 
17718 			switch (insn[0].src_reg) {
17719 			case BPF_PSEUDO_MAP_IDX_VALUE:
17720 			case BPF_PSEUDO_MAP_IDX:
17721 				if (bpfptr_is_null(env->fd_array)) {
17722 					verbose(env, "fd_idx without fd_array is invalid\n");
17723 					return -EPROTO;
17724 				}
17725 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17726 							    insn[0].imm * sizeof(fd),
17727 							    sizeof(fd)))
17728 					return -EFAULT;
17729 				break;
17730 			default:
17731 				fd = insn[0].imm;
17732 				break;
17733 			}
17734 
17735 			f = fdget(fd);
17736 			map = __bpf_map_get(f);
17737 			if (IS_ERR(map)) {
17738 				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17739 				return PTR_ERR(map);
17740 			}
17741 
17742 			err = check_map_prog_compatibility(env, map, env->prog);
17743 			if (err) {
17744 				fdput(f);
17745 				return err;
17746 			}
17747 
17748 			aux = &env->insn_aux_data[i];
17749 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17750 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17751 				addr = (unsigned long)map;
17752 			} else {
17753 				u32 off = insn[1].imm;
17754 
17755 				if (off >= BPF_MAX_VAR_OFF) {
17756 					verbose(env, "direct value offset of %u is not allowed\n", off);
17757 					fdput(f);
17758 					return -EINVAL;
17759 				}
17760 
17761 				if (!map->ops->map_direct_value_addr) {
17762 					verbose(env, "no direct value access support for this map type\n");
17763 					fdput(f);
17764 					return -EINVAL;
17765 				}
17766 
17767 				err = map->ops->map_direct_value_addr(map, &addr, off);
17768 				if (err) {
17769 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17770 						map->value_size, off);
17771 					fdput(f);
17772 					return err;
17773 				}
17774 
17775 				aux->map_off = off;
17776 				addr += off;
17777 			}
17778 
17779 			insn[0].imm = (u32)addr;
17780 			insn[1].imm = addr >> 32;
17781 
17782 			/* check whether we recorded this map already */
17783 			for (j = 0; j < env->used_map_cnt; j++) {
17784 				if (env->used_maps[j] == map) {
17785 					aux->map_index = j;
17786 					fdput(f);
17787 					goto next_insn;
17788 				}
17789 			}
17790 
17791 			if (env->used_map_cnt >= MAX_USED_MAPS) {
17792 				fdput(f);
17793 				return -E2BIG;
17794 			}
17795 
17796 			if (env->prog->aux->sleepable)
17797 				atomic64_inc(&map->sleepable_refcnt);
17798 			/* hold the map. If the program is rejected by verifier,
17799 			 * the map will be released by release_maps() or it
17800 			 * will be used by the valid program until it's unloaded
17801 			 * and all maps are released in bpf_free_used_maps()
17802 			 */
17803 			bpf_map_inc(map);
17804 
17805 			aux->map_index = env->used_map_cnt;
17806 			env->used_maps[env->used_map_cnt++] = map;
17807 
17808 			if (bpf_map_is_cgroup_storage(map) &&
17809 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17810 				verbose(env, "only one cgroup storage of each type is allowed\n");
17811 				fdput(f);
17812 				return -EBUSY;
17813 			}
17814 
17815 			fdput(f);
17816 next_insn:
17817 			insn++;
17818 			i++;
17819 			continue;
17820 		}
17821 
17822 		/* Basic sanity check before we invest more work here. */
17823 		if (!bpf_opcode_in_insntable(insn->code)) {
17824 			verbose(env, "unknown opcode %02x\n", insn->code);
17825 			return -EINVAL;
17826 		}
17827 	}
17828 
17829 	/* now all pseudo BPF_LD_IMM64 instructions load valid
17830 	 * 'struct bpf_map *' into a register instead of user map_fd.
17831 	 * These pointers will be used later by verifier to validate map access.
17832 	 */
17833 	return 0;
17834 }
17835 
17836 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)17837 static void release_maps(struct bpf_verifier_env *env)
17838 {
17839 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17840 			     env->used_map_cnt);
17841 }
17842 
17843 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)17844 static void release_btfs(struct bpf_verifier_env *env)
17845 {
17846 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17847 			     env->used_btf_cnt);
17848 }
17849 
17850 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)17851 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17852 {
17853 	struct bpf_insn *insn = env->prog->insnsi;
17854 	int insn_cnt = env->prog->len;
17855 	int i;
17856 
17857 	for (i = 0; i < insn_cnt; i++, insn++) {
17858 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17859 			continue;
17860 		if (insn->src_reg == BPF_PSEUDO_FUNC)
17861 			continue;
17862 		insn->src_reg = 0;
17863 	}
17864 }
17865 
17866 /* single env->prog->insni[off] instruction was replaced with the range
17867  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17868  * [0, off) and [off, end) to new locations, so the patched range stays zero
17869  */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_insn_aux_data * new_data,struct bpf_prog * new_prog,u32 off,u32 cnt)17870 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17871 				 struct bpf_insn_aux_data *new_data,
17872 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17873 {
17874 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17875 	struct bpf_insn *insn = new_prog->insnsi;
17876 	u32 old_seen = old_data[off].seen;
17877 	u32 prog_len;
17878 	int i;
17879 
17880 	/* aux info at OFF always needs adjustment, no matter fast path
17881 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17882 	 * original insn at old prog.
17883 	 */
17884 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17885 
17886 	if (cnt == 1)
17887 		return;
17888 	prog_len = new_prog->len;
17889 
17890 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17891 	memcpy(new_data + off + cnt - 1, old_data + off,
17892 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17893 	for (i = off; i < off + cnt - 1; i++) {
17894 		/* Expand insni[off]'s seen count to the patched range. */
17895 		new_data[i].seen = old_seen;
17896 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17897 	}
17898 	env->insn_aux_data = new_data;
17899 	vfree(old_data);
17900 }
17901 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)17902 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17903 {
17904 	int i;
17905 
17906 	if (len == 1)
17907 		return;
17908 	/* NOTE: fake 'exit' subprog should be updated as well. */
17909 	for (i = 0; i <= env->subprog_cnt; i++) {
17910 		if (env->subprog_info[i].start <= off)
17911 			continue;
17912 		env->subprog_info[i].start += len - 1;
17913 	}
17914 }
17915 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)17916 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17917 {
17918 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17919 	int i, sz = prog->aux->size_poke_tab;
17920 	struct bpf_jit_poke_descriptor *desc;
17921 
17922 	for (i = 0; i < sz; i++) {
17923 		desc = &tab[i];
17924 		if (desc->insn_idx <= off)
17925 			continue;
17926 		desc->insn_idx += len - 1;
17927 	}
17928 }
17929 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)17930 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17931 					    const struct bpf_insn *patch, u32 len)
17932 {
17933 	struct bpf_prog *new_prog;
17934 	struct bpf_insn_aux_data *new_data = NULL;
17935 
17936 	if (len > 1) {
17937 		new_data = vzalloc(array_size(env->prog->len + len - 1,
17938 					      sizeof(struct bpf_insn_aux_data)));
17939 		if (!new_data)
17940 			return NULL;
17941 	}
17942 
17943 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17944 	if (IS_ERR(new_prog)) {
17945 		if (PTR_ERR(new_prog) == -ERANGE)
17946 			verbose(env,
17947 				"insn %d cannot be patched due to 16-bit range\n",
17948 				env->insn_aux_data[off].orig_idx);
17949 		vfree(new_data);
17950 		return NULL;
17951 	}
17952 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17953 	adjust_subprog_starts(env, off, len);
17954 	adjust_poke_descs(new_prog, off, len);
17955 	return new_prog;
17956 }
17957 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)17958 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17959 					      u32 off, u32 cnt)
17960 {
17961 	int i, j;
17962 
17963 	/* find first prog starting at or after off (first to remove) */
17964 	for (i = 0; i < env->subprog_cnt; i++)
17965 		if (env->subprog_info[i].start >= off)
17966 			break;
17967 	/* find first prog starting at or after off + cnt (first to stay) */
17968 	for (j = i; j < env->subprog_cnt; j++)
17969 		if (env->subprog_info[j].start >= off + cnt)
17970 			break;
17971 	/* if j doesn't start exactly at off + cnt, we are just removing
17972 	 * the front of previous prog
17973 	 */
17974 	if (env->subprog_info[j].start != off + cnt)
17975 		j--;
17976 
17977 	if (j > i) {
17978 		struct bpf_prog_aux *aux = env->prog->aux;
17979 		int move;
17980 
17981 		/* move fake 'exit' subprog as well */
17982 		move = env->subprog_cnt + 1 - j;
17983 
17984 		memmove(env->subprog_info + i,
17985 			env->subprog_info + j,
17986 			sizeof(*env->subprog_info) * move);
17987 		env->subprog_cnt -= j - i;
17988 
17989 		/* remove func_info */
17990 		if (aux->func_info) {
17991 			move = aux->func_info_cnt - j;
17992 
17993 			memmove(aux->func_info + i,
17994 				aux->func_info + j,
17995 				sizeof(*aux->func_info) * move);
17996 			aux->func_info_cnt -= j - i;
17997 			/* func_info->insn_off is set after all code rewrites,
17998 			 * in adjust_btf_func() - no need to adjust
17999 			 */
18000 		}
18001 	} else {
18002 		/* convert i from "first prog to remove" to "first to adjust" */
18003 		if (env->subprog_info[i].start == off)
18004 			i++;
18005 	}
18006 
18007 	/* update fake 'exit' subprog as well */
18008 	for (; i <= env->subprog_cnt; i++)
18009 		env->subprog_info[i].start -= cnt;
18010 
18011 	return 0;
18012 }
18013 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)18014 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18015 				      u32 cnt)
18016 {
18017 	struct bpf_prog *prog = env->prog;
18018 	u32 i, l_off, l_cnt, nr_linfo;
18019 	struct bpf_line_info *linfo;
18020 
18021 	nr_linfo = prog->aux->nr_linfo;
18022 	if (!nr_linfo)
18023 		return 0;
18024 
18025 	linfo = prog->aux->linfo;
18026 
18027 	/* find first line info to remove, count lines to be removed */
18028 	for (i = 0; i < nr_linfo; i++)
18029 		if (linfo[i].insn_off >= off)
18030 			break;
18031 
18032 	l_off = i;
18033 	l_cnt = 0;
18034 	for (; i < nr_linfo; i++)
18035 		if (linfo[i].insn_off < off + cnt)
18036 			l_cnt++;
18037 		else
18038 			break;
18039 
18040 	/* First live insn doesn't match first live linfo, it needs to "inherit"
18041 	 * last removed linfo.  prog is already modified, so prog->len == off
18042 	 * means no live instructions after (tail of the program was removed).
18043 	 */
18044 	if (prog->len != off && l_cnt &&
18045 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18046 		l_cnt--;
18047 		linfo[--i].insn_off = off + cnt;
18048 	}
18049 
18050 	/* remove the line info which refer to the removed instructions */
18051 	if (l_cnt) {
18052 		memmove(linfo + l_off, linfo + i,
18053 			sizeof(*linfo) * (nr_linfo - i));
18054 
18055 		prog->aux->nr_linfo -= l_cnt;
18056 		nr_linfo = prog->aux->nr_linfo;
18057 	}
18058 
18059 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18060 	for (i = l_off; i < nr_linfo; i++)
18061 		linfo[i].insn_off -= cnt;
18062 
18063 	/* fix up all subprogs (incl. 'exit') which start >= off */
18064 	for (i = 0; i <= env->subprog_cnt; i++)
18065 		if (env->subprog_info[i].linfo_idx > l_off) {
18066 			/* program may have started in the removed region but
18067 			 * may not be fully removed
18068 			 */
18069 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18070 				env->subprog_info[i].linfo_idx -= l_cnt;
18071 			else
18072 				env->subprog_info[i].linfo_idx = l_off;
18073 		}
18074 
18075 	return 0;
18076 }
18077 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)18078 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18079 {
18080 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18081 	unsigned int orig_prog_len = env->prog->len;
18082 	int err;
18083 
18084 	if (bpf_prog_is_offloaded(env->prog->aux))
18085 		bpf_prog_offload_remove_insns(env, off, cnt);
18086 
18087 	err = bpf_remove_insns(env->prog, off, cnt);
18088 	if (err)
18089 		return err;
18090 
18091 	err = adjust_subprog_starts_after_remove(env, off, cnt);
18092 	if (err)
18093 		return err;
18094 
18095 	err = bpf_adj_linfo_after_remove(env, off, cnt);
18096 	if (err)
18097 		return err;
18098 
18099 	memmove(aux_data + off,	aux_data + off + cnt,
18100 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18101 
18102 	return 0;
18103 }
18104 
18105 /* The verifier does more data flow analysis than llvm and will not
18106  * explore branches that are dead at run time. Malicious programs can
18107  * have dead code too. Therefore replace all dead at-run-time code
18108  * with 'ja -1'.
18109  *
18110  * Just nops are not optimal, e.g. if they would sit at the end of the
18111  * program and through another bug we would manage to jump there, then
18112  * we'd execute beyond program memory otherwise. Returning exception
18113  * code also wouldn't work since we can have subprogs where the dead
18114  * code could be located.
18115  */
sanitize_dead_code(struct bpf_verifier_env * env)18116 static void sanitize_dead_code(struct bpf_verifier_env *env)
18117 {
18118 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18119 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18120 	struct bpf_insn *insn = env->prog->insnsi;
18121 	const int insn_cnt = env->prog->len;
18122 	int i;
18123 
18124 	for (i = 0; i < insn_cnt; i++) {
18125 		if (aux_data[i].seen)
18126 			continue;
18127 		memcpy(insn + i, &trap, sizeof(trap));
18128 		aux_data[i].zext_dst = false;
18129 	}
18130 }
18131 
insn_is_cond_jump(u8 code)18132 static bool insn_is_cond_jump(u8 code)
18133 {
18134 	u8 op;
18135 
18136 	op = BPF_OP(code);
18137 	if (BPF_CLASS(code) == BPF_JMP32)
18138 		return op != BPF_JA;
18139 
18140 	if (BPF_CLASS(code) != BPF_JMP)
18141 		return false;
18142 
18143 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18144 }
18145 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)18146 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18147 {
18148 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18149 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18150 	struct bpf_insn *insn = env->prog->insnsi;
18151 	const int insn_cnt = env->prog->len;
18152 	int i;
18153 
18154 	for (i = 0; i < insn_cnt; i++, insn++) {
18155 		if (!insn_is_cond_jump(insn->code))
18156 			continue;
18157 
18158 		if (!aux_data[i + 1].seen)
18159 			ja.off = insn->off;
18160 		else if (!aux_data[i + 1 + insn->off].seen)
18161 			ja.off = 0;
18162 		else
18163 			continue;
18164 
18165 		if (bpf_prog_is_offloaded(env->prog->aux))
18166 			bpf_prog_offload_replace_insn(env, i, &ja);
18167 
18168 		memcpy(insn, &ja, sizeof(ja));
18169 	}
18170 }
18171 
opt_remove_dead_code(struct bpf_verifier_env * env)18172 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18173 {
18174 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18175 	int insn_cnt = env->prog->len;
18176 	int i, err;
18177 
18178 	for (i = 0; i < insn_cnt; i++) {
18179 		int j;
18180 
18181 		j = 0;
18182 		while (i + j < insn_cnt && !aux_data[i + j].seen)
18183 			j++;
18184 		if (!j)
18185 			continue;
18186 
18187 		err = verifier_remove_insns(env, i, j);
18188 		if (err)
18189 			return err;
18190 		insn_cnt = env->prog->len;
18191 	}
18192 
18193 	return 0;
18194 }
18195 
opt_remove_nops(struct bpf_verifier_env * env)18196 static int opt_remove_nops(struct bpf_verifier_env *env)
18197 {
18198 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18199 	struct bpf_insn *insn = env->prog->insnsi;
18200 	int insn_cnt = env->prog->len;
18201 	int i, err;
18202 
18203 	for (i = 0; i < insn_cnt; i++) {
18204 		if (memcmp(&insn[i], &ja, sizeof(ja)))
18205 			continue;
18206 
18207 		err = verifier_remove_insns(env, i, 1);
18208 		if (err)
18209 			return err;
18210 		insn_cnt--;
18211 		i--;
18212 	}
18213 
18214 	return 0;
18215 }
18216 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)18217 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18218 					 const union bpf_attr *attr)
18219 {
18220 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18221 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18222 	int i, patch_len, delta = 0, len = env->prog->len;
18223 	struct bpf_insn *insns = env->prog->insnsi;
18224 	struct bpf_prog *new_prog;
18225 	bool rnd_hi32;
18226 
18227 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18228 	zext_patch[1] = BPF_ZEXT_REG(0);
18229 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18230 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18231 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18232 	for (i = 0; i < len; i++) {
18233 		int adj_idx = i + delta;
18234 		struct bpf_insn insn;
18235 		int load_reg;
18236 
18237 		insn = insns[adj_idx];
18238 		load_reg = insn_def_regno(&insn);
18239 		if (!aux[adj_idx].zext_dst) {
18240 			u8 code, class;
18241 			u32 imm_rnd;
18242 
18243 			if (!rnd_hi32)
18244 				continue;
18245 
18246 			code = insn.code;
18247 			class = BPF_CLASS(code);
18248 			if (load_reg == -1)
18249 				continue;
18250 
18251 			/* NOTE: arg "reg" (the fourth one) is only used for
18252 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18253 			 *       here.
18254 			 */
18255 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18256 				if (class == BPF_LD &&
18257 				    BPF_MODE(code) == BPF_IMM)
18258 					i++;
18259 				continue;
18260 			}
18261 
18262 			/* ctx load could be transformed into wider load. */
18263 			if (class == BPF_LDX &&
18264 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18265 				continue;
18266 
18267 			imm_rnd = get_random_u32();
18268 			rnd_hi32_patch[0] = insn;
18269 			rnd_hi32_patch[1].imm = imm_rnd;
18270 			rnd_hi32_patch[3].dst_reg = load_reg;
18271 			patch = rnd_hi32_patch;
18272 			patch_len = 4;
18273 			goto apply_patch_buffer;
18274 		}
18275 
18276 		/* Add in an zero-extend instruction if a) the JIT has requested
18277 		 * it or b) it's a CMPXCHG.
18278 		 *
18279 		 * The latter is because: BPF_CMPXCHG always loads a value into
18280 		 * R0, therefore always zero-extends. However some archs'
18281 		 * equivalent instruction only does this load when the
18282 		 * comparison is successful. This detail of CMPXCHG is
18283 		 * orthogonal to the general zero-extension behaviour of the
18284 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18285 		 */
18286 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18287 			continue;
18288 
18289 		/* Zero-extension is done by the caller. */
18290 		if (bpf_pseudo_kfunc_call(&insn))
18291 			continue;
18292 
18293 		if (WARN_ON(load_reg == -1)) {
18294 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18295 			return -EFAULT;
18296 		}
18297 
18298 		zext_patch[0] = insn;
18299 		zext_patch[1].dst_reg = load_reg;
18300 		zext_patch[1].src_reg = load_reg;
18301 		patch = zext_patch;
18302 		patch_len = 2;
18303 apply_patch_buffer:
18304 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18305 		if (!new_prog)
18306 			return -ENOMEM;
18307 		env->prog = new_prog;
18308 		insns = new_prog->insnsi;
18309 		aux = env->insn_aux_data;
18310 		delta += patch_len - 1;
18311 	}
18312 
18313 	return 0;
18314 }
18315 
18316 /* convert load instructions that access fields of a context type into a
18317  * sequence of instructions that access fields of the underlying structure:
18318  *     struct __sk_buff    -> struct sk_buff
18319  *     struct bpf_sock_ops -> struct sock
18320  */
convert_ctx_accesses(struct bpf_verifier_env * env)18321 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18322 {
18323 	const struct bpf_verifier_ops *ops = env->ops;
18324 	int i, cnt, size, ctx_field_size, delta = 0;
18325 	const int insn_cnt = env->prog->len;
18326 	struct bpf_insn insn_buf[16], *insn;
18327 	u32 target_size, size_default, off;
18328 	struct bpf_prog *new_prog;
18329 	enum bpf_access_type type;
18330 	bool is_narrower_load;
18331 
18332 	if (ops->gen_prologue || env->seen_direct_write) {
18333 		if (!ops->gen_prologue) {
18334 			verbose(env, "bpf verifier is misconfigured\n");
18335 			return -EINVAL;
18336 		}
18337 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18338 					env->prog);
18339 		if (cnt >= ARRAY_SIZE(insn_buf)) {
18340 			verbose(env, "bpf verifier is misconfigured\n");
18341 			return -EINVAL;
18342 		} else if (cnt) {
18343 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18344 			if (!new_prog)
18345 				return -ENOMEM;
18346 
18347 			env->prog = new_prog;
18348 			delta += cnt - 1;
18349 		}
18350 	}
18351 
18352 	if (bpf_prog_is_offloaded(env->prog->aux))
18353 		return 0;
18354 
18355 	insn = env->prog->insnsi + delta;
18356 
18357 	for (i = 0; i < insn_cnt; i++, insn++) {
18358 		bpf_convert_ctx_access_t convert_ctx_access;
18359 		u8 mode;
18360 
18361 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18362 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18363 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18364 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18365 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18366 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18367 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18368 			type = BPF_READ;
18369 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18370 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18371 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18372 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18373 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18374 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18375 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18376 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18377 			type = BPF_WRITE;
18378 		} else {
18379 			continue;
18380 		}
18381 
18382 		if (type == BPF_WRITE &&
18383 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18384 			struct bpf_insn patch[] = {
18385 				*insn,
18386 				BPF_ST_NOSPEC(),
18387 			};
18388 
18389 			cnt = ARRAY_SIZE(patch);
18390 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18391 			if (!new_prog)
18392 				return -ENOMEM;
18393 
18394 			delta    += cnt - 1;
18395 			env->prog = new_prog;
18396 			insn      = new_prog->insnsi + i + delta;
18397 			continue;
18398 		}
18399 
18400 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18401 		case PTR_TO_CTX:
18402 			if (!ops->convert_ctx_access)
18403 				continue;
18404 			convert_ctx_access = ops->convert_ctx_access;
18405 			break;
18406 		case PTR_TO_SOCKET:
18407 		case PTR_TO_SOCK_COMMON:
18408 			convert_ctx_access = bpf_sock_convert_ctx_access;
18409 			break;
18410 		case PTR_TO_TCP_SOCK:
18411 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18412 			break;
18413 		case PTR_TO_XDP_SOCK:
18414 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18415 			break;
18416 		case PTR_TO_BTF_ID:
18417 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18418 		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18419 		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18420 		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18421 		 * any faults for loads into such types. BPF_WRITE is disallowed
18422 		 * for this case.
18423 		 */
18424 		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18425 			if (type == BPF_READ) {
18426 				if (BPF_MODE(insn->code) == BPF_MEM)
18427 					insn->code = BPF_LDX | BPF_PROBE_MEM |
18428 						     BPF_SIZE((insn)->code);
18429 				else
18430 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18431 						     BPF_SIZE((insn)->code);
18432 				env->prog->aux->num_exentries++;
18433 			}
18434 			continue;
18435 		default:
18436 			continue;
18437 		}
18438 
18439 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18440 		size = BPF_LDST_BYTES(insn);
18441 		mode = BPF_MODE(insn->code);
18442 
18443 		/* If the read access is a narrower load of the field,
18444 		 * convert to a 4/8-byte load, to minimum program type specific
18445 		 * convert_ctx_access changes. If conversion is successful,
18446 		 * we will apply proper mask to the result.
18447 		 */
18448 		is_narrower_load = size < ctx_field_size;
18449 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18450 		off = insn->off;
18451 		if (is_narrower_load) {
18452 			u8 size_code;
18453 
18454 			if (type == BPF_WRITE) {
18455 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18456 				return -EINVAL;
18457 			}
18458 
18459 			size_code = BPF_H;
18460 			if (ctx_field_size == 4)
18461 				size_code = BPF_W;
18462 			else if (ctx_field_size == 8)
18463 				size_code = BPF_DW;
18464 
18465 			insn->off = off & ~(size_default - 1);
18466 			insn->code = BPF_LDX | BPF_MEM | size_code;
18467 		}
18468 
18469 		target_size = 0;
18470 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18471 					 &target_size);
18472 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18473 		    (ctx_field_size && !target_size)) {
18474 			verbose(env, "bpf verifier is misconfigured\n");
18475 			return -EINVAL;
18476 		}
18477 
18478 		if (is_narrower_load && size < target_size) {
18479 			u8 shift = bpf_ctx_narrow_access_offset(
18480 				off, size, size_default) * 8;
18481 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18482 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18483 				return -EINVAL;
18484 			}
18485 			if (ctx_field_size <= 4) {
18486 				if (shift)
18487 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18488 									insn->dst_reg,
18489 									shift);
18490 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18491 								(1 << size * 8) - 1);
18492 			} else {
18493 				if (shift)
18494 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18495 									insn->dst_reg,
18496 									shift);
18497 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18498 								(1ULL << size * 8) - 1);
18499 			}
18500 		}
18501 		if (mode == BPF_MEMSX)
18502 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18503 						       insn->dst_reg, insn->dst_reg,
18504 						       size * 8, 0);
18505 
18506 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18507 		if (!new_prog)
18508 			return -ENOMEM;
18509 
18510 		delta += cnt - 1;
18511 
18512 		/* keep walking new program and skip insns we just inserted */
18513 		env->prog = new_prog;
18514 		insn      = new_prog->insnsi + i + delta;
18515 	}
18516 
18517 	return 0;
18518 }
18519 
jit_subprogs(struct bpf_verifier_env * env)18520 static int jit_subprogs(struct bpf_verifier_env *env)
18521 {
18522 	struct bpf_prog *prog = env->prog, **func, *tmp;
18523 	int i, j, subprog_start, subprog_end = 0, len, subprog;
18524 	struct bpf_map *map_ptr;
18525 	struct bpf_insn *insn;
18526 	void *old_bpf_func;
18527 	int err, num_exentries;
18528 
18529 	if (env->subprog_cnt <= 1)
18530 		return 0;
18531 
18532 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18533 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18534 			continue;
18535 
18536 		/* Upon error here we cannot fall back to interpreter but
18537 		 * need a hard reject of the program. Thus -EFAULT is
18538 		 * propagated in any case.
18539 		 */
18540 		subprog = find_subprog(env, i + insn->imm + 1);
18541 		if (subprog < 0) {
18542 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18543 				  i + insn->imm + 1);
18544 			return -EFAULT;
18545 		}
18546 		/* temporarily remember subprog id inside insn instead of
18547 		 * aux_data, since next loop will split up all insns into funcs
18548 		 */
18549 		insn->off = subprog;
18550 		/* remember original imm in case JIT fails and fallback
18551 		 * to interpreter will be needed
18552 		 */
18553 		env->insn_aux_data[i].call_imm = insn->imm;
18554 		/* point imm to __bpf_call_base+1 from JITs point of view */
18555 		insn->imm = 1;
18556 		if (bpf_pseudo_func(insn))
18557 			/* jit (e.g. x86_64) may emit fewer instructions
18558 			 * if it learns a u32 imm is the same as a u64 imm.
18559 			 * Force a non zero here.
18560 			 */
18561 			insn[1].imm = 1;
18562 	}
18563 
18564 	err = bpf_prog_alloc_jited_linfo(prog);
18565 	if (err)
18566 		goto out_undo_insn;
18567 
18568 	err = -ENOMEM;
18569 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18570 	if (!func)
18571 		goto out_undo_insn;
18572 
18573 	for (i = 0; i < env->subprog_cnt; i++) {
18574 		subprog_start = subprog_end;
18575 		subprog_end = env->subprog_info[i + 1].start;
18576 
18577 		len = subprog_end - subprog_start;
18578 		/* bpf_prog_run() doesn't call subprogs directly,
18579 		 * hence main prog stats include the runtime of subprogs.
18580 		 * subprogs don't have IDs and not reachable via prog_get_next_id
18581 		 * func[i]->stats will never be accessed and stays NULL
18582 		 */
18583 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18584 		if (!func[i])
18585 			goto out_free;
18586 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18587 		       len * sizeof(struct bpf_insn));
18588 		func[i]->type = prog->type;
18589 		func[i]->len = len;
18590 		if (bpf_prog_calc_tag(func[i]))
18591 			goto out_free;
18592 		func[i]->is_func = 1;
18593 		func[i]->aux->func_idx = i;
18594 		/* Below members will be freed only at prog->aux */
18595 		func[i]->aux->btf = prog->aux->btf;
18596 		func[i]->aux->func_info = prog->aux->func_info;
18597 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18598 		func[i]->aux->poke_tab = prog->aux->poke_tab;
18599 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18600 
18601 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18602 			struct bpf_jit_poke_descriptor *poke;
18603 
18604 			poke = &prog->aux->poke_tab[j];
18605 			if (poke->insn_idx < subprog_end &&
18606 			    poke->insn_idx >= subprog_start)
18607 				poke->aux = func[i]->aux;
18608 		}
18609 
18610 		func[i]->aux->name[0] = 'F';
18611 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18612 		func[i]->jit_requested = 1;
18613 		func[i]->blinding_requested = prog->blinding_requested;
18614 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18615 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18616 		func[i]->aux->linfo = prog->aux->linfo;
18617 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18618 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18619 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18620 		num_exentries = 0;
18621 		insn = func[i]->insnsi;
18622 		for (j = 0; j < func[i]->len; j++, insn++) {
18623 			if (BPF_CLASS(insn->code) == BPF_LDX &&
18624 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18625 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18626 				num_exentries++;
18627 		}
18628 		func[i]->aux->num_exentries = num_exentries;
18629 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18630 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
18631 		func[i] = bpf_int_jit_compile(func[i]);
18632 		if (!func[i]->jited) {
18633 			err = -ENOTSUPP;
18634 			goto out_free;
18635 		}
18636 		cond_resched();
18637 	}
18638 
18639 	/* at this point all bpf functions were successfully JITed
18640 	 * now populate all bpf_calls with correct addresses and
18641 	 * run last pass of JIT
18642 	 */
18643 	for (i = 0; i < env->subprog_cnt; i++) {
18644 		insn = func[i]->insnsi;
18645 		for (j = 0; j < func[i]->len; j++, insn++) {
18646 			if (bpf_pseudo_func(insn)) {
18647 				subprog = insn->off;
18648 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18649 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18650 				continue;
18651 			}
18652 			if (!bpf_pseudo_call(insn))
18653 				continue;
18654 			subprog = insn->off;
18655 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18656 		}
18657 
18658 		/* we use the aux data to keep a list of the start addresses
18659 		 * of the JITed images for each function in the program
18660 		 *
18661 		 * for some architectures, such as powerpc64, the imm field
18662 		 * might not be large enough to hold the offset of the start
18663 		 * address of the callee's JITed image from __bpf_call_base
18664 		 *
18665 		 * in such cases, we can lookup the start address of a callee
18666 		 * by using its subprog id, available from the off field of
18667 		 * the call instruction, as an index for this list
18668 		 */
18669 		func[i]->aux->func = func;
18670 		func[i]->aux->func_cnt = env->subprog_cnt;
18671 	}
18672 	for (i = 0; i < env->subprog_cnt; i++) {
18673 		old_bpf_func = func[i]->bpf_func;
18674 		tmp = bpf_int_jit_compile(func[i]);
18675 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18676 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18677 			err = -ENOTSUPP;
18678 			goto out_free;
18679 		}
18680 		cond_resched();
18681 	}
18682 
18683 	/* finally lock prog and jit images for all functions and
18684 	 * populate kallsysm. Begin at the first subprogram, since
18685 	 * bpf_prog_load will add the kallsyms for the main program.
18686 	 */
18687 	for (i = 1; i < env->subprog_cnt; i++) {
18688 		bpf_prog_lock_ro(func[i]);
18689 		bpf_prog_kallsyms_add(func[i]);
18690 	}
18691 
18692 	/* Last step: make now unused interpreter insns from main
18693 	 * prog consistent for later dump requests, so they can
18694 	 * later look the same as if they were interpreted only.
18695 	 */
18696 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18697 		if (bpf_pseudo_func(insn)) {
18698 			insn[0].imm = env->insn_aux_data[i].call_imm;
18699 			insn[1].imm = insn->off;
18700 			insn->off = 0;
18701 			continue;
18702 		}
18703 		if (!bpf_pseudo_call(insn))
18704 			continue;
18705 		insn->off = env->insn_aux_data[i].call_imm;
18706 		subprog = find_subprog(env, i + insn->off + 1);
18707 		insn->imm = subprog;
18708 	}
18709 
18710 	prog->jited = 1;
18711 	prog->bpf_func = func[0]->bpf_func;
18712 	prog->jited_len = func[0]->jited_len;
18713 	prog->aux->extable = func[0]->aux->extable;
18714 	prog->aux->num_exentries = func[0]->aux->num_exentries;
18715 	prog->aux->func = func;
18716 	prog->aux->func_cnt = env->subprog_cnt;
18717 	bpf_prog_jit_attempt_done(prog);
18718 	return 0;
18719 out_free:
18720 	/* We failed JIT'ing, so at this point we need to unregister poke
18721 	 * descriptors from subprogs, so that kernel is not attempting to
18722 	 * patch it anymore as we're freeing the subprog JIT memory.
18723 	 */
18724 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18725 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18726 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18727 	}
18728 	/* At this point we're guaranteed that poke descriptors are not
18729 	 * live anymore. We can just unlink its descriptor table as it's
18730 	 * released with the main prog.
18731 	 */
18732 	for (i = 0; i < env->subprog_cnt; i++) {
18733 		if (!func[i])
18734 			continue;
18735 		func[i]->aux->poke_tab = NULL;
18736 		bpf_jit_free(func[i]);
18737 	}
18738 	kfree(func);
18739 out_undo_insn:
18740 	/* cleanup main prog to be interpreted */
18741 	prog->jit_requested = 0;
18742 	prog->blinding_requested = 0;
18743 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18744 		if (!bpf_pseudo_call(insn))
18745 			continue;
18746 		insn->off = 0;
18747 		insn->imm = env->insn_aux_data[i].call_imm;
18748 	}
18749 	bpf_prog_jit_attempt_done(prog);
18750 	return err;
18751 }
18752 
fixup_call_args(struct bpf_verifier_env * env)18753 static int fixup_call_args(struct bpf_verifier_env *env)
18754 {
18755 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18756 	struct bpf_prog *prog = env->prog;
18757 	struct bpf_insn *insn = prog->insnsi;
18758 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18759 	int i, depth;
18760 #endif
18761 	int err = 0;
18762 
18763 	if (env->prog->jit_requested &&
18764 	    !bpf_prog_is_offloaded(env->prog->aux)) {
18765 		err = jit_subprogs(env);
18766 		if (err == 0)
18767 			return 0;
18768 		if (err == -EFAULT)
18769 			return err;
18770 	}
18771 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18772 	if (has_kfunc_call) {
18773 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18774 		return -EINVAL;
18775 	}
18776 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18777 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18778 		 * have to be rejected, since interpreter doesn't support them yet.
18779 		 */
18780 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18781 		return -EINVAL;
18782 	}
18783 	for (i = 0; i < prog->len; i++, insn++) {
18784 		if (bpf_pseudo_func(insn)) {
18785 			/* When JIT fails the progs with callback calls
18786 			 * have to be rejected, since interpreter doesn't support them yet.
18787 			 */
18788 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18789 			return -EINVAL;
18790 		}
18791 
18792 		if (!bpf_pseudo_call(insn))
18793 			continue;
18794 		depth = get_callee_stack_depth(env, insn, i);
18795 		if (depth < 0)
18796 			return depth;
18797 		bpf_patch_call_args(insn, depth);
18798 	}
18799 	err = 0;
18800 #endif
18801 	return err;
18802 }
18803 
18804 /* 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)18805 static void specialize_kfunc(struct bpf_verifier_env *env,
18806 			     u32 func_id, u16 offset, unsigned long *addr)
18807 {
18808 	struct bpf_prog *prog = env->prog;
18809 	bool seen_direct_write;
18810 	void *xdp_kfunc;
18811 	bool is_rdonly;
18812 
18813 	if (bpf_dev_bound_kfunc_id(func_id)) {
18814 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18815 		if (xdp_kfunc) {
18816 			*addr = (unsigned long)xdp_kfunc;
18817 			return;
18818 		}
18819 		/* fallback to default kfunc when not supported by netdev */
18820 	}
18821 
18822 	if (offset)
18823 		return;
18824 
18825 	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18826 		seen_direct_write = env->seen_direct_write;
18827 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18828 
18829 		if (is_rdonly)
18830 			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18831 
18832 		/* restore env->seen_direct_write to its original value, since
18833 		 * may_access_direct_pkt_data mutates it
18834 		 */
18835 		env->seen_direct_write = seen_direct_write;
18836 	}
18837 }
18838 
__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)18839 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18840 					    u16 struct_meta_reg,
18841 					    u16 node_offset_reg,
18842 					    struct bpf_insn *insn,
18843 					    struct bpf_insn *insn_buf,
18844 					    int *cnt)
18845 {
18846 	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18847 	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18848 
18849 	insn_buf[0] = addr[0];
18850 	insn_buf[1] = addr[1];
18851 	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18852 	insn_buf[3] = *insn;
18853 	*cnt = 4;
18854 }
18855 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)18856 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18857 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18858 {
18859 	const struct bpf_kfunc_desc *desc;
18860 
18861 	if (!insn->imm) {
18862 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18863 		return -EINVAL;
18864 	}
18865 
18866 	*cnt = 0;
18867 
18868 	/* insn->imm has the btf func_id. Replace it with an offset relative to
18869 	 * __bpf_call_base, unless the JIT needs to call functions that are
18870 	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18871 	 */
18872 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18873 	if (!desc) {
18874 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18875 			insn->imm);
18876 		return -EFAULT;
18877 	}
18878 
18879 	if (!bpf_jit_supports_far_kfunc_call())
18880 		insn->imm = BPF_CALL_IMM(desc->addr);
18881 	if (insn->off)
18882 		return 0;
18883 	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18884 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18885 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18886 		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18887 
18888 		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18889 		insn_buf[1] = addr[0];
18890 		insn_buf[2] = addr[1];
18891 		insn_buf[3] = *insn;
18892 		*cnt = 4;
18893 	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18894 		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18895 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18896 		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18897 
18898 		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18899 		    !kptr_struct_meta) {
18900 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18901 				insn_idx);
18902 			return -EFAULT;
18903 		}
18904 
18905 		insn_buf[0] = addr[0];
18906 		insn_buf[1] = addr[1];
18907 		insn_buf[2] = *insn;
18908 		*cnt = 3;
18909 	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18910 		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18911 		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18912 		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18913 		int struct_meta_reg = BPF_REG_3;
18914 		int node_offset_reg = BPF_REG_4;
18915 
18916 		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18917 		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18918 			struct_meta_reg = BPF_REG_4;
18919 			node_offset_reg = BPF_REG_5;
18920 		}
18921 
18922 		if (!kptr_struct_meta) {
18923 			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18924 				insn_idx);
18925 			return -EFAULT;
18926 		}
18927 
18928 		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18929 						node_offset_reg, insn, insn_buf, cnt);
18930 	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18931 		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18932 		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18933 		*cnt = 1;
18934 	}
18935 	return 0;
18936 }
18937 
18938 /* Do various post-verification rewrites in a single program pass.
18939  * These rewrites simplify JIT and interpreter implementations.
18940  */
do_misc_fixups(struct bpf_verifier_env * env)18941 static int do_misc_fixups(struct bpf_verifier_env *env)
18942 {
18943 	struct bpf_prog *prog = env->prog;
18944 	enum bpf_attach_type eatype = prog->expected_attach_type;
18945 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18946 	struct bpf_insn *insn = prog->insnsi;
18947 	const struct bpf_func_proto *fn;
18948 	const int insn_cnt = prog->len;
18949 	const struct bpf_map_ops *ops;
18950 	struct bpf_insn_aux_data *aux;
18951 	struct bpf_insn insn_buf[16];
18952 	struct bpf_prog *new_prog;
18953 	struct bpf_map *map_ptr;
18954 	int i, ret, cnt, delta = 0;
18955 
18956 	for (i = 0; i < insn_cnt; i++, insn++) {
18957 		/* Make divide-by-zero exceptions impossible. */
18958 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18959 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18960 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18961 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18962 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18963 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18964 			struct bpf_insn *patchlet;
18965 			struct bpf_insn chk_and_div[] = {
18966 				/* [R,W]x div 0 -> 0 */
18967 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18968 					     BPF_JNE | BPF_K, insn->src_reg,
18969 					     0, 2, 0),
18970 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18971 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18972 				*insn,
18973 			};
18974 			struct bpf_insn chk_and_mod[] = {
18975 				/* [R,W]x mod 0 -> [R,W]x */
18976 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18977 					     BPF_JEQ | BPF_K, insn->src_reg,
18978 					     0, 1 + (is64 ? 0 : 1), 0),
18979 				*insn,
18980 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18981 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18982 			};
18983 
18984 			patchlet = isdiv ? chk_and_div : chk_and_mod;
18985 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18986 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18987 
18988 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18989 			if (!new_prog)
18990 				return -ENOMEM;
18991 
18992 			delta    += cnt - 1;
18993 			env->prog = prog = new_prog;
18994 			insn      = new_prog->insnsi + i + delta;
18995 			continue;
18996 		}
18997 
18998 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18999 		if (BPF_CLASS(insn->code) == BPF_LD &&
19000 		    (BPF_MODE(insn->code) == BPF_ABS ||
19001 		     BPF_MODE(insn->code) == BPF_IND)) {
19002 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
19003 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19004 				verbose(env, "bpf verifier is misconfigured\n");
19005 				return -EINVAL;
19006 			}
19007 
19008 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19009 			if (!new_prog)
19010 				return -ENOMEM;
19011 
19012 			delta    += cnt - 1;
19013 			env->prog = prog = new_prog;
19014 			insn      = new_prog->insnsi + i + delta;
19015 			continue;
19016 		}
19017 
19018 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
19019 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19020 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19021 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19022 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19023 			struct bpf_insn *patch = &insn_buf[0];
19024 			bool issrc, isneg, isimm;
19025 			u32 off_reg;
19026 
19027 			aux = &env->insn_aux_data[i + delta];
19028 			if (!aux->alu_state ||
19029 			    aux->alu_state == BPF_ALU_NON_POINTER)
19030 				continue;
19031 
19032 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19033 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19034 				BPF_ALU_SANITIZE_SRC;
19035 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19036 
19037 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
19038 			if (isimm) {
19039 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19040 			} else {
19041 				if (isneg)
19042 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19043 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19044 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19045 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19046 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19047 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19048 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19049 			}
19050 			if (!issrc)
19051 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19052 			insn->src_reg = BPF_REG_AX;
19053 			if (isneg)
19054 				insn->code = insn->code == code_add ?
19055 					     code_sub : code_add;
19056 			*patch++ = *insn;
19057 			if (issrc && isneg && !isimm)
19058 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19059 			cnt = patch - insn_buf;
19060 
19061 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19062 			if (!new_prog)
19063 				return -ENOMEM;
19064 
19065 			delta    += cnt - 1;
19066 			env->prog = prog = new_prog;
19067 			insn      = new_prog->insnsi + i + delta;
19068 			continue;
19069 		}
19070 
19071 		if (insn->code != (BPF_JMP | BPF_CALL))
19072 			continue;
19073 		if (insn->src_reg == BPF_PSEUDO_CALL)
19074 			continue;
19075 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19076 			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19077 			if (ret)
19078 				return ret;
19079 			if (cnt == 0)
19080 				continue;
19081 
19082 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19083 			if (!new_prog)
19084 				return -ENOMEM;
19085 
19086 			delta	 += cnt - 1;
19087 			env->prog = prog = new_prog;
19088 			insn	  = new_prog->insnsi + i + delta;
19089 			continue;
19090 		}
19091 
19092 		if (insn->imm == BPF_FUNC_get_route_realm)
19093 			prog->dst_needed = 1;
19094 		if (insn->imm == BPF_FUNC_get_prandom_u32)
19095 			bpf_user_rnd_init_once();
19096 		if (insn->imm == BPF_FUNC_override_return)
19097 			prog->kprobe_override = 1;
19098 		if (insn->imm == BPF_FUNC_tail_call) {
19099 			/* If we tail call into other programs, we
19100 			 * cannot make any assumptions since they can
19101 			 * be replaced dynamically during runtime in
19102 			 * the program array.
19103 			 */
19104 			prog->cb_access = 1;
19105 			if (!allow_tail_call_in_subprogs(env))
19106 				prog->aux->stack_depth = MAX_BPF_STACK;
19107 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19108 
19109 			/* mark bpf_tail_call as different opcode to avoid
19110 			 * conditional branch in the interpreter for every normal
19111 			 * call and to prevent accidental JITing by JIT compiler
19112 			 * that doesn't support bpf_tail_call yet
19113 			 */
19114 			insn->imm = 0;
19115 			insn->code = BPF_JMP | BPF_TAIL_CALL;
19116 
19117 			aux = &env->insn_aux_data[i + delta];
19118 			if (env->bpf_capable && !prog->blinding_requested &&
19119 			    prog->jit_requested &&
19120 			    !bpf_map_key_poisoned(aux) &&
19121 			    !bpf_map_ptr_poisoned(aux) &&
19122 			    !bpf_map_ptr_unpriv(aux)) {
19123 				struct bpf_jit_poke_descriptor desc = {
19124 					.reason = BPF_POKE_REASON_TAIL_CALL,
19125 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19126 					.tail_call.key = bpf_map_key_immediate(aux),
19127 					.insn_idx = i + delta,
19128 				};
19129 
19130 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19131 				if (ret < 0) {
19132 					verbose(env, "adding tail call poke descriptor failed\n");
19133 					return ret;
19134 				}
19135 
19136 				insn->imm = ret + 1;
19137 				continue;
19138 			}
19139 
19140 			if (!bpf_map_ptr_unpriv(aux))
19141 				continue;
19142 
19143 			/* instead of changing every JIT dealing with tail_call
19144 			 * emit two extra insns:
19145 			 * if (index >= max_entries) goto out;
19146 			 * index &= array->index_mask;
19147 			 * to avoid out-of-bounds cpu speculation
19148 			 */
19149 			if (bpf_map_ptr_poisoned(aux)) {
19150 				verbose(env, "tail_call abusing map_ptr\n");
19151 				return -EINVAL;
19152 			}
19153 
19154 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19155 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19156 						  map_ptr->max_entries, 2);
19157 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19158 						    container_of(map_ptr,
19159 								 struct bpf_array,
19160 								 map)->index_mask);
19161 			insn_buf[2] = *insn;
19162 			cnt = 3;
19163 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19164 			if (!new_prog)
19165 				return -ENOMEM;
19166 
19167 			delta    += cnt - 1;
19168 			env->prog = prog = new_prog;
19169 			insn      = new_prog->insnsi + i + delta;
19170 			continue;
19171 		}
19172 
19173 		if (insn->imm == BPF_FUNC_timer_set_callback) {
19174 			/* The verifier will process callback_fn as many times as necessary
19175 			 * with different maps and the register states prepared by
19176 			 * set_timer_callback_state will be accurate.
19177 			 *
19178 			 * The following use case is valid:
19179 			 *   map1 is shared by prog1, prog2, prog3.
19180 			 *   prog1 calls bpf_timer_init for some map1 elements
19181 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19182 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19183 			 *   prog3 calls bpf_timer_start for some map1 elements.
19184 			 *     Those that were not both bpf_timer_init-ed and
19185 			 *     bpf_timer_set_callback-ed will return -EINVAL.
19186 			 */
19187 			struct bpf_insn ld_addrs[2] = {
19188 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19189 			};
19190 
19191 			insn_buf[0] = ld_addrs[0];
19192 			insn_buf[1] = ld_addrs[1];
19193 			insn_buf[2] = *insn;
19194 			cnt = 3;
19195 
19196 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19197 			if (!new_prog)
19198 				return -ENOMEM;
19199 
19200 			delta    += cnt - 1;
19201 			env->prog = prog = new_prog;
19202 			insn      = new_prog->insnsi + i + delta;
19203 			goto patch_call_imm;
19204 		}
19205 
19206 		if (is_storage_get_function(insn->imm)) {
19207 			if (!env->prog->aux->sleepable ||
19208 			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19209 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19210 			else
19211 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19212 			insn_buf[1] = *insn;
19213 			cnt = 2;
19214 
19215 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19216 			if (!new_prog)
19217 				return -ENOMEM;
19218 
19219 			delta += cnt - 1;
19220 			env->prog = prog = new_prog;
19221 			insn = new_prog->insnsi + i + delta;
19222 			goto patch_call_imm;
19223 		}
19224 
19225 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19226 		 * and other inlining handlers are currently limited to 64 bit
19227 		 * only.
19228 		 */
19229 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19230 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19231 		     insn->imm == BPF_FUNC_map_update_elem ||
19232 		     insn->imm == BPF_FUNC_map_delete_elem ||
19233 		     insn->imm == BPF_FUNC_map_push_elem   ||
19234 		     insn->imm == BPF_FUNC_map_pop_elem    ||
19235 		     insn->imm == BPF_FUNC_map_peek_elem   ||
19236 		     insn->imm == BPF_FUNC_redirect_map    ||
19237 		     insn->imm == BPF_FUNC_for_each_map_elem ||
19238 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19239 			aux = &env->insn_aux_data[i + delta];
19240 			if (bpf_map_ptr_poisoned(aux))
19241 				goto patch_call_imm;
19242 
19243 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19244 			ops = map_ptr->ops;
19245 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19246 			    ops->map_gen_lookup) {
19247 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19248 				if (cnt == -EOPNOTSUPP)
19249 					goto patch_map_ops_generic;
19250 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19251 					verbose(env, "bpf verifier is misconfigured\n");
19252 					return -EINVAL;
19253 				}
19254 
19255 				new_prog = bpf_patch_insn_data(env, i + delta,
19256 							       insn_buf, cnt);
19257 				if (!new_prog)
19258 					return -ENOMEM;
19259 
19260 				delta    += cnt - 1;
19261 				env->prog = prog = new_prog;
19262 				insn      = new_prog->insnsi + i + delta;
19263 				continue;
19264 			}
19265 
19266 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19267 				     (void *(*)(struct bpf_map *map, void *key))NULL));
19268 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19269 				     (long (*)(struct bpf_map *map, void *key))NULL));
19270 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19271 				     (long (*)(struct bpf_map *map, void *key, void *value,
19272 					      u64 flags))NULL));
19273 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19274 				     (long (*)(struct bpf_map *map, void *value,
19275 					      u64 flags))NULL));
19276 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19277 				     (long (*)(struct bpf_map *map, void *value))NULL));
19278 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19279 				     (long (*)(struct bpf_map *map, void *value))NULL));
19280 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19281 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19282 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19283 				     (long (*)(struct bpf_map *map,
19284 					      bpf_callback_t callback_fn,
19285 					      void *callback_ctx,
19286 					      u64 flags))NULL));
19287 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19288 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19289 
19290 patch_map_ops_generic:
19291 			switch (insn->imm) {
19292 			case BPF_FUNC_map_lookup_elem:
19293 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19294 				continue;
19295 			case BPF_FUNC_map_update_elem:
19296 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19297 				continue;
19298 			case BPF_FUNC_map_delete_elem:
19299 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19300 				continue;
19301 			case BPF_FUNC_map_push_elem:
19302 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19303 				continue;
19304 			case BPF_FUNC_map_pop_elem:
19305 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19306 				continue;
19307 			case BPF_FUNC_map_peek_elem:
19308 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19309 				continue;
19310 			case BPF_FUNC_redirect_map:
19311 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19312 				continue;
19313 			case BPF_FUNC_for_each_map_elem:
19314 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19315 				continue;
19316 			case BPF_FUNC_map_lookup_percpu_elem:
19317 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19318 				continue;
19319 			}
19320 
19321 			goto patch_call_imm;
19322 		}
19323 
19324 		/* Implement bpf_jiffies64 inline. */
19325 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19326 		    insn->imm == BPF_FUNC_jiffies64) {
19327 			struct bpf_insn ld_jiffies_addr[2] = {
19328 				BPF_LD_IMM64(BPF_REG_0,
19329 					     (unsigned long)&jiffies),
19330 			};
19331 
19332 			insn_buf[0] = ld_jiffies_addr[0];
19333 			insn_buf[1] = ld_jiffies_addr[1];
19334 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19335 						  BPF_REG_0, 0);
19336 			cnt = 3;
19337 
19338 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19339 						       cnt);
19340 			if (!new_prog)
19341 				return -ENOMEM;
19342 
19343 			delta    += cnt - 1;
19344 			env->prog = prog = new_prog;
19345 			insn      = new_prog->insnsi + i + delta;
19346 			continue;
19347 		}
19348 
19349 		/* Implement bpf_get_func_arg inline. */
19350 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19351 		    insn->imm == BPF_FUNC_get_func_arg) {
19352 			/* Load nr_args from ctx - 8 */
19353 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19354 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19355 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19356 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19357 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19358 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19359 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19360 			insn_buf[7] = BPF_JMP_A(1);
19361 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19362 			cnt = 9;
19363 
19364 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19365 			if (!new_prog)
19366 				return -ENOMEM;
19367 
19368 			delta    += cnt - 1;
19369 			env->prog = prog = new_prog;
19370 			insn      = new_prog->insnsi + i + delta;
19371 			continue;
19372 		}
19373 
19374 		/* Implement bpf_get_func_ret inline. */
19375 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19376 		    insn->imm == BPF_FUNC_get_func_ret) {
19377 			if (eatype == BPF_TRACE_FEXIT ||
19378 			    eatype == BPF_MODIFY_RETURN) {
19379 				/* Load nr_args from ctx - 8 */
19380 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19381 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19382 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19383 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19384 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19385 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19386 				cnt = 6;
19387 			} else {
19388 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19389 				cnt = 1;
19390 			}
19391 
19392 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19393 			if (!new_prog)
19394 				return -ENOMEM;
19395 
19396 			delta    += cnt - 1;
19397 			env->prog = prog = new_prog;
19398 			insn      = new_prog->insnsi + i + delta;
19399 			continue;
19400 		}
19401 
19402 		/* Implement get_func_arg_cnt inline. */
19403 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19404 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19405 			/* Load nr_args from ctx - 8 */
19406 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19407 
19408 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19409 			if (!new_prog)
19410 				return -ENOMEM;
19411 
19412 			env->prog = prog = new_prog;
19413 			insn      = new_prog->insnsi + i + delta;
19414 			continue;
19415 		}
19416 
19417 		/* Implement bpf_get_func_ip inline. */
19418 		if (prog_type == BPF_PROG_TYPE_TRACING &&
19419 		    insn->imm == BPF_FUNC_get_func_ip) {
19420 			/* Load IP address from ctx - 16 */
19421 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19422 
19423 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19424 			if (!new_prog)
19425 				return -ENOMEM;
19426 
19427 			env->prog = prog = new_prog;
19428 			insn      = new_prog->insnsi + i + delta;
19429 			continue;
19430 		}
19431 
19432 patch_call_imm:
19433 		fn = env->ops->get_func_proto(insn->imm, env->prog);
19434 		/* all functions that have prototype and verifier allowed
19435 		 * programs to call them, must be real in-kernel functions
19436 		 */
19437 		if (!fn->func) {
19438 			verbose(env,
19439 				"kernel subsystem misconfigured func %s#%d\n",
19440 				func_id_name(insn->imm), insn->imm);
19441 			return -EFAULT;
19442 		}
19443 		insn->imm = fn->func - __bpf_call_base;
19444 	}
19445 
19446 	/* Since poke tab is now finalized, publish aux to tracker. */
19447 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19448 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19449 		if (!map_ptr->ops->map_poke_track ||
19450 		    !map_ptr->ops->map_poke_untrack ||
19451 		    !map_ptr->ops->map_poke_run) {
19452 			verbose(env, "bpf verifier is misconfigured\n");
19453 			return -EINVAL;
19454 		}
19455 
19456 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19457 		if (ret < 0) {
19458 			verbose(env, "tracking tail call prog failed\n");
19459 			return ret;
19460 		}
19461 	}
19462 
19463 	sort_kfunc_descs_by_imm_off(env->prog);
19464 
19465 	return 0;
19466 }
19467 
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * cnt)19468 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19469 					int position,
19470 					s32 stack_base,
19471 					u32 callback_subprogno,
19472 					u32 *cnt)
19473 {
19474 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19475 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19476 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19477 	int reg_loop_max = BPF_REG_6;
19478 	int reg_loop_cnt = BPF_REG_7;
19479 	int reg_loop_ctx = BPF_REG_8;
19480 
19481 	struct bpf_prog *new_prog;
19482 	u32 callback_start;
19483 	u32 call_insn_offset;
19484 	s32 callback_offset;
19485 
19486 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19487 	 * be careful to modify this code in sync.
19488 	 */
19489 	struct bpf_insn insn_buf[] = {
19490 		/* Return error and jump to the end of the patch if
19491 		 * expected number of iterations is too big.
19492 		 */
19493 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19494 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19495 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19496 		/* spill R6, R7, R8 to use these as loop vars */
19497 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19498 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19499 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19500 		/* initialize loop vars */
19501 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19502 		BPF_MOV32_IMM(reg_loop_cnt, 0),
19503 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19504 		/* loop header,
19505 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19506 		 */
19507 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19508 		/* callback call,
19509 		 * correct callback offset would be set after patching
19510 		 */
19511 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19512 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19513 		BPF_CALL_REL(0),
19514 		/* increment loop counter */
19515 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19516 		/* jump to loop header if callback returned 0 */
19517 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19518 		/* return value of bpf_loop,
19519 		 * set R0 to the number of iterations
19520 		 */
19521 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19522 		/* restore original values of R6, R7, R8 */
19523 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19524 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19525 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19526 	};
19527 
19528 	*cnt = ARRAY_SIZE(insn_buf);
19529 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19530 	if (!new_prog)
19531 		return new_prog;
19532 
19533 	/* callback start is known only after patching */
19534 	callback_start = env->subprog_info[callback_subprogno].start;
19535 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19536 	call_insn_offset = position + 12;
19537 	callback_offset = callback_start - call_insn_offset - 1;
19538 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19539 
19540 	return new_prog;
19541 }
19542 
is_bpf_loop_call(struct bpf_insn * insn)19543 static bool is_bpf_loop_call(struct bpf_insn *insn)
19544 {
19545 	return insn->code == (BPF_JMP | BPF_CALL) &&
19546 		insn->src_reg == 0 &&
19547 		insn->imm == BPF_FUNC_loop;
19548 }
19549 
19550 /* For all sub-programs in the program (including main) check
19551  * insn_aux_data to see if there are bpf_loop calls that require
19552  * inlining. If such calls are found the calls are replaced with a
19553  * sequence of instructions produced by `inline_bpf_loop` function and
19554  * subprog stack_depth is increased by the size of 3 registers.
19555  * This stack space is used to spill values of the R6, R7, R8.  These
19556  * registers are used to store the loop bound, counter and context
19557  * variables.
19558  */
optimize_bpf_loop(struct bpf_verifier_env * env)19559 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19560 {
19561 	struct bpf_subprog_info *subprogs = env->subprog_info;
19562 	int i, cur_subprog = 0, cnt, delta = 0;
19563 	struct bpf_insn *insn = env->prog->insnsi;
19564 	int insn_cnt = env->prog->len;
19565 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19566 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19567 	u16 stack_depth_extra = 0;
19568 
19569 	for (i = 0; i < insn_cnt; i++, insn++) {
19570 		struct bpf_loop_inline_state *inline_state =
19571 			&env->insn_aux_data[i + delta].loop_inline_state;
19572 
19573 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19574 			struct bpf_prog *new_prog;
19575 
19576 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19577 			new_prog = inline_bpf_loop(env,
19578 						   i + delta,
19579 						   -(stack_depth + stack_depth_extra),
19580 						   inline_state->callback_subprogno,
19581 						   &cnt);
19582 			if (!new_prog)
19583 				return -ENOMEM;
19584 
19585 			delta     += cnt - 1;
19586 			env->prog  = new_prog;
19587 			insn       = new_prog->insnsi + i + delta;
19588 		}
19589 
19590 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19591 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19592 			cur_subprog++;
19593 			stack_depth = subprogs[cur_subprog].stack_depth;
19594 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19595 			stack_depth_extra = 0;
19596 		}
19597 	}
19598 
19599 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19600 
19601 	return 0;
19602 }
19603 
free_states(struct bpf_verifier_env * env)19604 static void free_states(struct bpf_verifier_env *env)
19605 {
19606 	struct bpf_verifier_state_list *sl, *sln;
19607 	int i;
19608 
19609 	sl = env->free_list;
19610 	while (sl) {
19611 		sln = sl->next;
19612 		free_verifier_state(&sl->state, false);
19613 		kfree(sl);
19614 		sl = sln;
19615 	}
19616 	env->free_list = NULL;
19617 
19618 	if (!env->explored_states)
19619 		return;
19620 
19621 	for (i = 0; i < state_htab_size(env); i++) {
19622 		sl = env->explored_states[i];
19623 
19624 		while (sl) {
19625 			sln = sl->next;
19626 			free_verifier_state(&sl->state, false);
19627 			kfree(sl);
19628 			sl = sln;
19629 		}
19630 		env->explored_states[i] = NULL;
19631 	}
19632 }
19633 
do_check_common(struct bpf_verifier_env * env,int subprog)19634 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19635 {
19636 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19637 	struct bpf_verifier_state *state;
19638 	struct bpf_reg_state *regs;
19639 	int ret, i;
19640 
19641 	env->prev_linfo = NULL;
19642 	env->pass_cnt++;
19643 
19644 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19645 	if (!state)
19646 		return -ENOMEM;
19647 	state->curframe = 0;
19648 	state->speculative = false;
19649 	state->branches = 1;
19650 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19651 	if (!state->frame[0]) {
19652 		kfree(state);
19653 		return -ENOMEM;
19654 	}
19655 	env->cur_state = state;
19656 	init_func_state(env, state->frame[0],
19657 			BPF_MAIN_FUNC /* callsite */,
19658 			0 /* frameno */,
19659 			subprog);
19660 	state->first_insn_idx = env->subprog_info[subprog].start;
19661 	state->last_insn_idx = -1;
19662 
19663 	regs = state->frame[state->curframe]->regs;
19664 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19665 		ret = btf_prepare_func_args(env, subprog, regs);
19666 		if (ret)
19667 			goto out;
19668 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19669 			if (regs[i].type == PTR_TO_CTX)
19670 				mark_reg_known_zero(env, regs, i);
19671 			else if (regs[i].type == SCALAR_VALUE)
19672 				mark_reg_unknown(env, regs, i);
19673 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19674 				const u32 mem_size = regs[i].mem_size;
19675 
19676 				mark_reg_known_zero(env, regs, i);
19677 				regs[i].mem_size = mem_size;
19678 				regs[i].id = ++env->id_gen;
19679 			}
19680 		}
19681 	} else {
19682 		/* 1st arg to a function */
19683 		regs[BPF_REG_1].type = PTR_TO_CTX;
19684 		mark_reg_known_zero(env, regs, BPF_REG_1);
19685 		ret = btf_check_subprog_arg_match(env, subprog, regs);
19686 		if (ret == -EFAULT)
19687 			/* unlikely verifier bug. abort.
19688 			 * ret == 0 and ret < 0 are sadly acceptable for
19689 			 * main() function due to backward compatibility.
19690 			 * Like socket filter program may be written as:
19691 			 * int bpf_prog(struct pt_regs *ctx)
19692 			 * and never dereference that ctx in the program.
19693 			 * 'struct pt_regs' is a type mismatch for socket
19694 			 * filter that should be using 'struct __sk_buff'.
19695 			 */
19696 			goto out;
19697 	}
19698 
19699 	ret = do_check(env);
19700 out:
19701 	/* check for NULL is necessary, since cur_state can be freed inside
19702 	 * do_check() under memory pressure.
19703 	 */
19704 	if (env->cur_state) {
19705 		free_verifier_state(env->cur_state, true);
19706 		env->cur_state = NULL;
19707 	}
19708 	while (!pop_stack(env, NULL, NULL, false));
19709 	if (!ret && pop_log)
19710 		bpf_vlog_reset(&env->log, 0);
19711 	free_states(env);
19712 	return ret;
19713 }
19714 
19715 /* Verify all global functions in a BPF program one by one based on their BTF.
19716  * All global functions must pass verification. Otherwise the whole program is rejected.
19717  * Consider:
19718  * int bar(int);
19719  * int foo(int f)
19720  * {
19721  *    return bar(f);
19722  * }
19723  * int bar(int b)
19724  * {
19725  *    ...
19726  * }
19727  * foo() will be verified first for R1=any_scalar_value. During verification it
19728  * will be assumed that bar() already verified successfully and call to bar()
19729  * from foo() will be checked for type match only. Later bar() will be verified
19730  * independently to check that it's safe for R1=any_scalar_value.
19731  */
do_check_subprogs(struct bpf_verifier_env * env)19732 static int do_check_subprogs(struct bpf_verifier_env *env)
19733 {
19734 	struct bpf_prog_aux *aux = env->prog->aux;
19735 	int i, ret;
19736 
19737 	if (!aux->func_info)
19738 		return 0;
19739 
19740 	for (i = 1; i < env->subprog_cnt; i++) {
19741 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19742 			continue;
19743 		env->insn_idx = env->subprog_info[i].start;
19744 		WARN_ON_ONCE(env->insn_idx == 0);
19745 		ret = do_check_common(env, i);
19746 		if (ret) {
19747 			return ret;
19748 		} else if (env->log.level & BPF_LOG_LEVEL) {
19749 			verbose(env,
19750 				"Func#%d is safe for any args that match its prototype\n",
19751 				i);
19752 		}
19753 	}
19754 	return 0;
19755 }
19756 
do_check_main(struct bpf_verifier_env * env)19757 static int do_check_main(struct bpf_verifier_env *env)
19758 {
19759 	int ret;
19760 
19761 	env->insn_idx = 0;
19762 	ret = do_check_common(env, 0);
19763 	if (!ret)
19764 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19765 	return ret;
19766 }
19767 
19768 
print_verification_stats(struct bpf_verifier_env * env)19769 static void print_verification_stats(struct bpf_verifier_env *env)
19770 {
19771 	int i;
19772 
19773 	if (env->log.level & BPF_LOG_STATS) {
19774 		verbose(env, "verification time %lld usec\n",
19775 			div_u64(env->verification_time, 1000));
19776 		verbose(env, "stack depth ");
19777 		for (i = 0; i < env->subprog_cnt; i++) {
19778 			u32 depth = env->subprog_info[i].stack_depth;
19779 
19780 			verbose(env, "%d", depth);
19781 			if (i + 1 < env->subprog_cnt)
19782 				verbose(env, "+");
19783 		}
19784 		verbose(env, "\n");
19785 	}
19786 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19787 		"total_states %d peak_states %d mark_read %d\n",
19788 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19789 		env->max_states_per_insn, env->total_states,
19790 		env->peak_states, env->longest_mark_read_walk);
19791 }
19792 
check_struct_ops_btf_id(struct bpf_verifier_env * env)19793 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19794 {
19795 	const struct btf_type *t, *func_proto;
19796 	const struct bpf_struct_ops *st_ops;
19797 	const struct btf_member *member;
19798 	struct bpf_prog *prog = env->prog;
19799 	u32 btf_id, member_idx;
19800 	const char *mname;
19801 
19802 	if (!prog->gpl_compatible) {
19803 		verbose(env, "struct ops programs must have a GPL compatible license\n");
19804 		return -EINVAL;
19805 	}
19806 
19807 	btf_id = prog->aux->attach_btf_id;
19808 	st_ops = bpf_struct_ops_find(btf_id);
19809 	if (!st_ops) {
19810 		verbose(env, "attach_btf_id %u is not a supported struct\n",
19811 			btf_id);
19812 		return -ENOTSUPP;
19813 	}
19814 
19815 	t = st_ops->type;
19816 	member_idx = prog->expected_attach_type;
19817 	if (member_idx >= btf_type_vlen(t)) {
19818 		verbose(env, "attach to invalid member idx %u of struct %s\n",
19819 			member_idx, st_ops->name);
19820 		return -EINVAL;
19821 	}
19822 
19823 	member = &btf_type_member(t)[member_idx];
19824 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19825 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19826 					       NULL);
19827 	if (!func_proto) {
19828 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19829 			mname, member_idx, st_ops->name);
19830 		return -EINVAL;
19831 	}
19832 
19833 	if (st_ops->check_member) {
19834 		int err = st_ops->check_member(t, member, prog);
19835 
19836 		if (err) {
19837 			verbose(env, "attach to unsupported member %s of struct %s\n",
19838 				mname, st_ops->name);
19839 			return err;
19840 		}
19841 	}
19842 
19843 	prog->aux->attach_func_proto = func_proto;
19844 	prog->aux->attach_func_name = mname;
19845 	env->ops = st_ops->verifier_ops;
19846 
19847 	return 0;
19848 }
19849 #define SECURITY_PREFIX "security_"
19850 
check_attach_modify_return(unsigned long addr,const char * func_name)19851 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19852 {
19853 	if (within_error_injection_list(addr) ||
19854 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19855 		return 0;
19856 
19857 	return -EINVAL;
19858 }
19859 
19860 /* list of non-sleepable functions that are otherwise on
19861  * ALLOW_ERROR_INJECTION list
19862  */
19863 BTF_SET_START(btf_non_sleepable_error_inject)
19864 /* Three functions below can be called from sleepable and non-sleepable context.
19865  * Assume non-sleepable from bpf safety point of view.
19866  */
BTF_ID(func,__filemap_add_folio)19867 BTF_ID(func, __filemap_add_folio)
19868 BTF_ID(func, should_fail_alloc_page)
19869 BTF_ID(func, should_failslab)
19870 BTF_SET_END(btf_non_sleepable_error_inject)
19871 
19872 static int check_non_sleepable_error_inject(u32 btf_id)
19873 {
19874 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19875 }
19876 
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)19877 int bpf_check_attach_target(struct bpf_verifier_log *log,
19878 			    const struct bpf_prog *prog,
19879 			    const struct bpf_prog *tgt_prog,
19880 			    u32 btf_id,
19881 			    struct bpf_attach_target_info *tgt_info)
19882 {
19883 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19884 	const char prefix[] = "btf_trace_";
19885 	int ret = 0, subprog = -1, i;
19886 	const struct btf_type *t;
19887 	bool conservative = true;
19888 	const char *tname;
19889 	struct btf *btf;
19890 	long addr = 0;
19891 	struct module *mod = NULL;
19892 
19893 	if (!btf_id) {
19894 		bpf_log(log, "Tracing programs must provide btf_id\n");
19895 		return -EINVAL;
19896 	}
19897 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19898 	if (!btf) {
19899 		bpf_log(log,
19900 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19901 		return -EINVAL;
19902 	}
19903 	t = btf_type_by_id(btf, btf_id);
19904 	if (!t) {
19905 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19906 		return -EINVAL;
19907 	}
19908 	tname = btf_name_by_offset(btf, t->name_off);
19909 	if (!tname) {
19910 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19911 		return -EINVAL;
19912 	}
19913 	if (tgt_prog) {
19914 		struct bpf_prog_aux *aux = tgt_prog->aux;
19915 		bool tgt_changes_pkt_data;
19916 
19917 		if (bpf_prog_is_dev_bound(prog->aux) &&
19918 		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19919 			bpf_log(log, "Target program bound device mismatch");
19920 			return -EINVAL;
19921 		}
19922 
19923 		for (i = 0; i < aux->func_info_cnt; i++)
19924 			if (aux->func_info[i].type_id == btf_id) {
19925 				subprog = i;
19926 				break;
19927 			}
19928 		if (subprog == -1) {
19929 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19930 			return -EINVAL;
19931 		}
19932 		conservative = aux->func_info_aux[subprog].unreliable;
19933 		if (prog_extension) {
19934 			if (conservative) {
19935 				bpf_log(log,
19936 					"Cannot replace static functions\n");
19937 				return -EINVAL;
19938 			}
19939 			if (!prog->jit_requested) {
19940 				bpf_log(log,
19941 					"Extension programs should be JITed\n");
19942 				return -EINVAL;
19943 			}
19944 			tgt_changes_pkt_data = aux->func
19945 					       ? aux->func[subprog]->aux->changes_pkt_data
19946 					       : aux->changes_pkt_data;
19947 			if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
19948 				bpf_log(log,
19949 					"Extension program changes packet data, while original does not\n");
19950 				return -EINVAL;
19951 			}
19952 		}
19953 		if (!tgt_prog->jited) {
19954 			bpf_log(log, "Can attach to only JITed progs\n");
19955 			return -EINVAL;
19956 		}
19957 		if (tgt_prog->type == prog->type) {
19958 			/* Cannot fentry/fexit another fentry/fexit program.
19959 			 * Cannot attach program extension to another extension.
19960 			 * It's ok to attach fentry/fexit to extension program.
19961 			 */
19962 			bpf_log(log, "Cannot recursively attach\n");
19963 			return -EINVAL;
19964 		}
19965 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19966 		    prog_extension &&
19967 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19968 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19969 			/* Program extensions can extend all program types
19970 			 * except fentry/fexit. The reason is the following.
19971 			 * The fentry/fexit programs are used for performance
19972 			 * analysis, stats and can be attached to any program
19973 			 * type except themselves. When extension program is
19974 			 * replacing XDP function it is necessary to allow
19975 			 * performance analysis of all functions. Both original
19976 			 * XDP program and its program extension. Hence
19977 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19978 			 * allowed. If extending of fentry/fexit was allowed it
19979 			 * would be possible to create long call chain
19980 			 * fentry->extension->fentry->extension beyond
19981 			 * reasonable stack size. Hence extending fentry is not
19982 			 * allowed.
19983 			 */
19984 			bpf_log(log, "Cannot extend fentry/fexit\n");
19985 			return -EINVAL;
19986 		}
19987 	} else {
19988 		if (prog_extension) {
19989 			bpf_log(log, "Cannot replace kernel functions\n");
19990 			return -EINVAL;
19991 		}
19992 	}
19993 
19994 	switch (prog->expected_attach_type) {
19995 	case BPF_TRACE_RAW_TP:
19996 		if (tgt_prog) {
19997 			bpf_log(log,
19998 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19999 			return -EINVAL;
20000 		}
20001 		if (!btf_type_is_typedef(t)) {
20002 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
20003 				btf_id);
20004 			return -EINVAL;
20005 		}
20006 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20007 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20008 				btf_id, tname);
20009 			return -EINVAL;
20010 		}
20011 		tname += sizeof(prefix) - 1;
20012 		t = btf_type_by_id(btf, t->type);
20013 		if (!btf_type_is_ptr(t))
20014 			/* should never happen in valid vmlinux build */
20015 			return -EINVAL;
20016 		t = btf_type_by_id(btf, t->type);
20017 		if (!btf_type_is_func_proto(t))
20018 			/* should never happen in valid vmlinux build */
20019 			return -EINVAL;
20020 
20021 		break;
20022 	case BPF_TRACE_ITER:
20023 		if (!btf_type_is_func(t)) {
20024 			bpf_log(log, "attach_btf_id %u is not a function\n",
20025 				btf_id);
20026 			return -EINVAL;
20027 		}
20028 		t = btf_type_by_id(btf, t->type);
20029 		if (!btf_type_is_func_proto(t))
20030 			return -EINVAL;
20031 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20032 		if (ret)
20033 			return ret;
20034 		break;
20035 	default:
20036 		if (!prog_extension)
20037 			return -EINVAL;
20038 		fallthrough;
20039 	case BPF_MODIFY_RETURN:
20040 	case BPF_LSM_MAC:
20041 	case BPF_LSM_CGROUP:
20042 	case BPF_TRACE_FENTRY:
20043 	case BPF_TRACE_FEXIT:
20044 		if (!btf_type_is_func(t)) {
20045 			bpf_log(log, "attach_btf_id %u is not a function\n",
20046 				btf_id);
20047 			return -EINVAL;
20048 		}
20049 		if (prog_extension &&
20050 		    btf_check_type_match(log, prog, btf, t))
20051 			return -EINVAL;
20052 		t = btf_type_by_id(btf, t->type);
20053 		if (!btf_type_is_func_proto(t))
20054 			return -EINVAL;
20055 
20056 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20057 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20058 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20059 			return -EINVAL;
20060 
20061 		if (tgt_prog && conservative)
20062 			t = NULL;
20063 
20064 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20065 		if (ret < 0)
20066 			return ret;
20067 
20068 		if (tgt_prog) {
20069 			if (subprog == 0)
20070 				addr = (long) tgt_prog->bpf_func;
20071 			else
20072 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20073 		} else {
20074 			if (btf_is_module(btf)) {
20075 				mod = btf_try_get_module(btf);
20076 				if (mod)
20077 					addr = find_kallsyms_symbol_value(mod, tname);
20078 				else
20079 					addr = 0;
20080 			} else {
20081 				addr = kallsyms_lookup_name(tname);
20082 			}
20083 			if (!addr) {
20084 				module_put(mod);
20085 				bpf_log(log,
20086 					"The address of function %s cannot be found\n",
20087 					tname);
20088 				return -ENOENT;
20089 			}
20090 		}
20091 
20092 		if (prog->aux->sleepable) {
20093 			ret = -EINVAL;
20094 			switch (prog->type) {
20095 			case BPF_PROG_TYPE_TRACING:
20096 
20097 				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20098 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20099 				 */
20100 				if (!check_non_sleepable_error_inject(btf_id) &&
20101 				    within_error_injection_list(addr))
20102 					ret = 0;
20103 				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20104 				 * in the fmodret id set with the KF_SLEEPABLE flag.
20105 				 */
20106 				else {
20107 					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20108 										prog);
20109 
20110 					if (flags && (*flags & KF_SLEEPABLE))
20111 						ret = 0;
20112 				}
20113 				break;
20114 			case BPF_PROG_TYPE_LSM:
20115 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20116 				 * Only some of them are sleepable.
20117 				 */
20118 				if (bpf_lsm_is_sleepable_hook(btf_id))
20119 					ret = 0;
20120 				break;
20121 			default:
20122 				break;
20123 			}
20124 			if (ret) {
20125 				module_put(mod);
20126 				bpf_log(log, "%s is not sleepable\n", tname);
20127 				return ret;
20128 			}
20129 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20130 			if (tgt_prog) {
20131 				module_put(mod);
20132 				bpf_log(log, "can't modify return codes of BPF programs\n");
20133 				return -EINVAL;
20134 			}
20135 			ret = -EINVAL;
20136 			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20137 			    !check_attach_modify_return(addr, tname))
20138 				ret = 0;
20139 			if (ret) {
20140 				module_put(mod);
20141 				bpf_log(log, "%s() is not modifiable\n", tname);
20142 				return ret;
20143 			}
20144 		}
20145 
20146 		break;
20147 	}
20148 	tgt_info->tgt_addr = addr;
20149 	tgt_info->tgt_name = tname;
20150 	tgt_info->tgt_type = t;
20151 	tgt_info->tgt_mod = mod;
20152 	return 0;
20153 }
20154 
BTF_SET_START(btf_id_deny)20155 BTF_SET_START(btf_id_deny)
20156 BTF_ID_UNUSED
20157 #ifdef CONFIG_SMP
20158 BTF_ID(func, migrate_disable)
20159 BTF_ID(func, migrate_enable)
20160 #endif
20161 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20162 BTF_ID(func, rcu_read_unlock_strict)
20163 #endif
20164 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20165 BTF_ID(func, preempt_count_add)
20166 BTF_ID(func, preempt_count_sub)
20167 #endif
20168 #ifdef CONFIG_PREEMPT_RCU
20169 BTF_ID(func, __rcu_read_lock)
20170 BTF_ID(func, __rcu_read_unlock)
20171 #endif
20172 BTF_SET_END(btf_id_deny)
20173 
20174 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
20175  * Currently, we must manually list all __noreturn functions here. Once a more
20176  * robust solution is implemented, this workaround can be removed.
20177  */
20178 BTF_SET_START(noreturn_deny)
20179 #ifdef CONFIG_IA32_EMULATION
20180 BTF_ID(func, __ia32_sys_exit)
20181 BTF_ID(func, __ia32_sys_exit_group)
20182 #endif
20183 #ifdef CONFIG_KUNIT
20184 BTF_ID(func, __kunit_abort)
20185 BTF_ID(func, kunit_try_catch_throw)
20186 #endif
20187 #ifdef CONFIG_MODULES
20188 BTF_ID(func, __module_put_and_kthread_exit)
20189 #endif
20190 #ifdef CONFIG_X86_64
20191 BTF_ID(func, __x64_sys_exit)
20192 BTF_ID(func, __x64_sys_exit_group)
20193 #endif
20194 BTF_ID(func, do_exit)
20195 BTF_ID(func, do_group_exit)
20196 BTF_ID(func, kthread_complete_and_exit)
20197 BTF_ID(func, kthread_exit)
20198 BTF_ID(func, make_task_dead)
20199 BTF_SET_END(noreturn_deny)
20200 
20201 static bool can_be_sleepable(struct bpf_prog *prog)
20202 {
20203 	if (prog->type == BPF_PROG_TYPE_TRACING) {
20204 		switch (prog->expected_attach_type) {
20205 		case BPF_TRACE_FENTRY:
20206 		case BPF_TRACE_FEXIT:
20207 		case BPF_MODIFY_RETURN:
20208 		case BPF_TRACE_ITER:
20209 			return true;
20210 		default:
20211 			return false;
20212 		}
20213 	}
20214 	return prog->type == BPF_PROG_TYPE_LSM ||
20215 	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20216 	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20217 }
20218 
check_attach_btf_id(struct bpf_verifier_env * env)20219 static int check_attach_btf_id(struct bpf_verifier_env *env)
20220 {
20221 	struct bpf_prog *prog = env->prog;
20222 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20223 	struct bpf_attach_target_info tgt_info = {};
20224 	u32 btf_id = prog->aux->attach_btf_id;
20225 	struct bpf_trampoline *tr;
20226 	int ret;
20227 	u64 key;
20228 
20229 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20230 		if (prog->aux->sleepable)
20231 			/* attach_btf_id checked to be zero already */
20232 			return 0;
20233 		verbose(env, "Syscall programs can only be sleepable\n");
20234 		return -EINVAL;
20235 	}
20236 
20237 	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20238 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20239 		return -EINVAL;
20240 	}
20241 
20242 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20243 		return check_struct_ops_btf_id(env);
20244 
20245 	if (prog->type != BPF_PROG_TYPE_TRACING &&
20246 	    prog->type != BPF_PROG_TYPE_LSM &&
20247 	    prog->type != BPF_PROG_TYPE_EXT)
20248 		return 0;
20249 
20250 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20251 	if (ret)
20252 		return ret;
20253 
20254 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20255 		/* to make freplace equivalent to their targets, they need to
20256 		 * inherit env->ops and expected_attach_type for the rest of the
20257 		 * verification
20258 		 */
20259 		env->ops = bpf_verifier_ops[tgt_prog->type];
20260 		prog->expected_attach_type = tgt_prog->expected_attach_type;
20261 	}
20262 
20263 	/* store info about the attachment target that will be used later */
20264 	prog->aux->attach_func_proto = tgt_info.tgt_type;
20265 	prog->aux->attach_func_name = tgt_info.tgt_name;
20266 	prog->aux->mod = tgt_info.tgt_mod;
20267 
20268 	if (tgt_prog) {
20269 		prog->aux->saved_dst_prog_type = tgt_prog->type;
20270 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20271 	}
20272 
20273 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20274 		prog->aux->attach_btf_trace = true;
20275 		return 0;
20276 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20277 		if (!bpf_iter_prog_supported(prog))
20278 			return -EINVAL;
20279 		return 0;
20280 	}
20281 
20282 	if (prog->type == BPF_PROG_TYPE_LSM) {
20283 		ret = bpf_lsm_verify_prog(&env->log, prog);
20284 		if (ret < 0)
20285 			return ret;
20286 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20287 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20288 		return -EINVAL;
20289 	} else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
20290 		   prog->expected_attach_type == BPF_MODIFY_RETURN) &&
20291 		   btf_id_set_contains(&noreturn_deny, btf_id)) {
20292 		verbose(env, "Attaching fexit/fmod_ret to __noreturn functions is rejected.\n");
20293 		return -EINVAL;
20294 	}
20295 
20296 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20297 	tr = bpf_trampoline_get(key, &tgt_info);
20298 	if (!tr)
20299 		return -ENOMEM;
20300 
20301 	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20302 		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20303 
20304 	prog->aux->dst_trampoline = tr;
20305 	return 0;
20306 }
20307 
bpf_get_btf_vmlinux(void)20308 struct btf *bpf_get_btf_vmlinux(void)
20309 {
20310 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20311 		mutex_lock(&bpf_verifier_lock);
20312 		if (!btf_vmlinux)
20313 			btf_vmlinux = btf_parse_vmlinux();
20314 		mutex_unlock(&bpf_verifier_lock);
20315 	}
20316 	return btf_vmlinux;
20317 }
20318 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)20319 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20320 {
20321 	u64 start_time = ktime_get_ns();
20322 	struct bpf_verifier_env *env;
20323 	int i, len, ret = -EINVAL, err;
20324 	u32 log_true_size;
20325 	bool is_priv;
20326 
20327 	/* no program is valid */
20328 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20329 		return -EINVAL;
20330 
20331 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20332 	 * allocate/free it every time bpf_check() is called
20333 	 */
20334 	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20335 	if (!env)
20336 		return -ENOMEM;
20337 
20338 	env->bt.env = env;
20339 
20340 	len = (*prog)->len;
20341 	env->insn_aux_data =
20342 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20343 	ret = -ENOMEM;
20344 	if (!env->insn_aux_data)
20345 		goto err_free_env;
20346 	for (i = 0; i < len; i++)
20347 		env->insn_aux_data[i].orig_idx = i;
20348 	env->prog = *prog;
20349 	env->ops = bpf_verifier_ops[env->prog->type];
20350 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20351 	is_priv = bpf_capable();
20352 
20353 	bpf_get_btf_vmlinux();
20354 
20355 	/* grab the mutex to protect few globals used by verifier */
20356 	if (!is_priv)
20357 		mutex_lock(&bpf_verifier_lock);
20358 
20359 	/* user could have requested verbose verifier output
20360 	 * and supplied buffer to store the verification trace
20361 	 */
20362 	ret = bpf_vlog_init(&env->log, attr->log_level,
20363 			    (char __user *) (unsigned long) attr->log_buf,
20364 			    attr->log_size);
20365 	if (ret)
20366 		goto err_unlock;
20367 
20368 	mark_verifier_state_clean(env);
20369 
20370 	if (IS_ERR(btf_vmlinux)) {
20371 		/* Either gcc or pahole or kernel are broken. */
20372 		verbose(env, "in-kernel BTF is malformed\n");
20373 		ret = PTR_ERR(btf_vmlinux);
20374 		goto skip_full_check;
20375 	}
20376 
20377 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20378 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20379 		env->strict_alignment = true;
20380 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20381 		env->strict_alignment = false;
20382 
20383 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20384 	env->allow_uninit_stack = bpf_allow_uninit_stack();
20385 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20386 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20387 	env->bpf_capable = bpf_capable();
20388 
20389 	if (is_priv)
20390 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20391 
20392 	env->explored_states = kvcalloc(state_htab_size(env),
20393 				       sizeof(struct bpf_verifier_state_list *),
20394 				       GFP_USER);
20395 	ret = -ENOMEM;
20396 	if (!env->explored_states)
20397 		goto skip_full_check;
20398 
20399 	ret = add_subprog_and_kfunc(env);
20400 	if (ret < 0)
20401 		goto skip_full_check;
20402 
20403 	ret = check_subprogs(env);
20404 	if (ret < 0)
20405 		goto skip_full_check;
20406 
20407 	ret = check_btf_info(env, attr, uattr);
20408 	if (ret < 0)
20409 		goto skip_full_check;
20410 
20411 	ret = resolve_pseudo_ldimm64(env);
20412 	if (ret < 0)
20413 		goto skip_full_check;
20414 
20415 	if (bpf_prog_is_offloaded(env->prog->aux)) {
20416 		ret = bpf_prog_offload_verifier_prep(env->prog);
20417 		if (ret)
20418 			goto skip_full_check;
20419 	}
20420 
20421 	ret = check_cfg(env);
20422 	if (ret < 0)
20423 		goto skip_full_check;
20424 
20425 	ret = check_attach_btf_id(env);
20426 	if (ret)
20427 		goto skip_full_check;
20428 
20429 	ret = do_check_subprogs(env);
20430 	ret = ret ?: do_check_main(env);
20431 
20432 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20433 		ret = bpf_prog_offload_finalize(env);
20434 
20435 skip_full_check:
20436 	kvfree(env->explored_states);
20437 
20438 	if (ret == 0)
20439 		ret = check_max_stack_depth(env);
20440 
20441 	/* instruction rewrites happen after this point */
20442 	if (ret == 0)
20443 		ret = optimize_bpf_loop(env);
20444 
20445 	if (is_priv) {
20446 		if (ret == 0)
20447 			opt_hard_wire_dead_code_branches(env);
20448 		if (ret == 0)
20449 			ret = opt_remove_dead_code(env);
20450 		if (ret == 0)
20451 			ret = opt_remove_nops(env);
20452 	} else {
20453 		if (ret == 0)
20454 			sanitize_dead_code(env);
20455 	}
20456 
20457 	if (ret == 0)
20458 		/* program is valid, convert *(u32*)(ctx + off) accesses */
20459 		ret = convert_ctx_accesses(env);
20460 
20461 	if (ret == 0)
20462 		ret = do_misc_fixups(env);
20463 
20464 	/* do 32-bit optimization after insn patching has done so those patched
20465 	 * insns could be handled correctly.
20466 	 */
20467 	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20468 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20469 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20470 								     : false;
20471 	}
20472 
20473 	if (ret == 0)
20474 		ret = fixup_call_args(env);
20475 
20476 	env->verification_time = ktime_get_ns() - start_time;
20477 	print_verification_stats(env);
20478 	env->prog->aux->verified_insns = env->insn_processed;
20479 
20480 	/* preserve original error even if log finalization is successful */
20481 	err = bpf_vlog_finalize(&env->log, &log_true_size);
20482 	if (err)
20483 		ret = err;
20484 
20485 	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20486 	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20487 				  &log_true_size, sizeof(log_true_size))) {
20488 		ret = -EFAULT;
20489 		goto err_release_maps;
20490 	}
20491 
20492 	if (ret)
20493 		goto err_release_maps;
20494 
20495 	if (env->used_map_cnt) {
20496 		/* if program passed verifier, update used_maps in bpf_prog_info */
20497 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20498 							  sizeof(env->used_maps[0]),
20499 							  GFP_KERNEL);
20500 
20501 		if (!env->prog->aux->used_maps) {
20502 			ret = -ENOMEM;
20503 			goto err_release_maps;
20504 		}
20505 
20506 		memcpy(env->prog->aux->used_maps, env->used_maps,
20507 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20508 		env->prog->aux->used_map_cnt = env->used_map_cnt;
20509 	}
20510 	if (env->used_btf_cnt) {
20511 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20512 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20513 							  sizeof(env->used_btfs[0]),
20514 							  GFP_KERNEL);
20515 		if (!env->prog->aux->used_btfs) {
20516 			ret = -ENOMEM;
20517 			goto err_release_maps;
20518 		}
20519 
20520 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20521 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20522 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20523 	}
20524 	if (env->used_map_cnt || env->used_btf_cnt) {
20525 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20526 		 * bpf_ld_imm64 instructions
20527 		 */
20528 		convert_pseudo_ld_imm64(env);
20529 	}
20530 
20531 	adjust_btf_func(env);
20532 
20533 err_release_maps:
20534 	if (!env->prog->aux->used_maps)
20535 		/* if we didn't copy map pointers into bpf_prog_info, release
20536 		 * them now. Otherwise free_used_maps() will release them.
20537 		 */
20538 		release_maps(env);
20539 	if (!env->prog->aux->used_btfs)
20540 		release_btfs(env);
20541 
20542 	/* extension progs temporarily inherit the attach_type of their targets
20543 	   for verification purposes, so set it back to zero before returning
20544 	 */
20545 	if (env->prog->type == BPF_PROG_TYPE_EXT)
20546 		env->prog->expected_attach_type = 0;
20547 
20548 	*prog = env->prog;
20549 err_unlock:
20550 	if (!is_priv)
20551 		mutex_unlock(&bpf_verifier_lock);
20552 	vfree(env->insn_aux_data);
20553 err_free_env:
20554 	kvfree(env);
20555 	return ret;
20556 }
20557