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 
28 #include "disasm.h"
29 
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 	[_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40 
41 /* bpf_check() is a static code analyzer that walks eBPF program
42  * instruction by instruction and updates register/stack state.
43  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44  *
45  * The first pass is depth-first-search to check that the program is a DAG.
46  * It rejects the following programs:
47  * - larger than BPF_MAXINSNS insns
48  * - if loop is present (detected via back-edge)
49  * - unreachable insns exist (shouldn't be a forest. program = one function)
50  * - out of bounds or malformed jumps
51  * The second pass is all possible path descent from the 1st insn.
52  * Since it's analyzing all paths through the program, the length of the
53  * analysis is limited to 64k insn, which may be hit even if total number of
54  * insn is less then 4K, but there are too many branches that change stack/regs.
55  * Number of 'branches to be analyzed' is limited to 1k
56  *
57  * On entry to each instruction, each register has a type, and the instruction
58  * changes the types of the registers depending on instruction semantics.
59  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60  * copied to R1.
61  *
62  * All registers are 64-bit.
63  * R0 - return register
64  * R1-R5 argument passing registers
65  * R6-R9 callee saved registers
66  * R10 - frame pointer read-only
67  *
68  * At the start of BPF program the register R1 contains a pointer to bpf_context
69  * and has type PTR_TO_CTX.
70  *
71  * Verifier tracks arithmetic operations on pointers in case:
72  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74  * 1st insn copies R10 (which has FRAME_PTR) type into R1
75  * and 2nd arithmetic instruction is pattern matched to recognize
76  * that it wants to construct a pointer to some element within stack.
77  * So after 2nd insn, the register R1 has type PTR_TO_STACK
78  * (and -20 constant is saved for further stack bounds checking).
79  * Meaning that this reg is a pointer to stack plus known immediate constant.
80  *
81  * Most of the time the registers have SCALAR_VALUE type, which
82  * means the register has some value, but it's not a valid pointer.
83  * (like pointer plus pointer becomes SCALAR_VALUE type)
84  *
85  * When verifier sees load or store instructions the type of base register
86  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87  * four pointer types recognized by check_mem_access() function.
88  *
89  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90  * and the range of [ptr, ptr + map's value_size) is accessible.
91  *
92  * registers used to pass values to function calls are checked against
93  * function argument constraints.
94  *
95  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96  * It means that the register type passed to this function must be
97  * PTR_TO_STACK and it will be used inside the function as
98  * 'pointer to map element key'
99  *
100  * For example the argument constraints for bpf_map_lookup_elem():
101  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102  *   .arg1_type = ARG_CONST_MAP_PTR,
103  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
104  *
105  * ret_type says that this function returns 'pointer to map elem value or null'
106  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107  * 2nd argument should be a pointer to stack, which will be used inside
108  * the helper function as a pointer to map element key.
109  *
110  * On the kernel side the helper function looks like:
111  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112  * {
113  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114  *    void *key = (void *) (unsigned long) r2;
115  *    void *value;
116  *
117  *    here kernel can access 'key' and 'map' pointers safely, knowing that
118  *    [key, key + map->key_size) bytes are valid and were initialized on
119  *    the stack of eBPF program.
120  * }
121  *
122  * Corresponding eBPF program may look like:
123  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
124  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
126  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127  * here verifier looks at prototype of map_lookup_elem() and sees:
128  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130  *
131  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133  * and were initialized prior to this call.
134  * If it's ok, then verifier allows this BPF_CALL insn and looks at
135  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137  * returns either pointer to map value or NULL.
138  *
139  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140  * insn, the register holding that pointer in the true branch changes state to
141  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142  * branch. See check_cond_jmp_op().
143  *
144  * After the call R0 is set to return type of the function and registers R1-R5
145  * are set to NOT_INIT to indicate that they are no longer readable.
146  *
147  * The following reference types represent a potential reference to a kernel
148  * resource which, after first being allocated, must be checked and freed by
149  * the BPF program:
150  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151  *
152  * When the verifier sees a helper call return a reference type, it allocates a
153  * pointer id for the reference and stores it in the current function state.
154  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156  * passes through a NULL-check conditional. For the branch wherein the state is
157  * changed to CONST_IMM, the verifier releases the reference.
158  *
159  * For each helper function that allocates a reference, such as
160  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161  * bpf_sk_release(). When a reference type passes into the release function,
162  * the verifier also releases the reference. If any unchecked or unreleased
163  * reference remains at the end of the program, the verifier rejects it.
164  */
165 
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 	/* verifer state is 'st'
169 	 * before processing instruction 'insn_idx'
170 	 * and after processing instruction 'prev_insn_idx'
171 	 */
172 	struct bpf_verifier_state st;
173 	int insn_idx;
174 	int prev_insn_idx;
175 	struct bpf_verifier_stack_elem *next;
176 	/* length of verifier log at the time this state was pushed on stack */
177 	u32 log_pos;
178 };
179 
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
181 #define BPF_COMPLEXITY_LIMIT_STATES	64
182 
183 #define BPF_MAP_KEY_POISON	(1ULL << 63)
184 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
185 
186 #define BPF_MAP_PTR_UNPRIV	1UL
187 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
188 					  POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190 
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203 
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 			      const struct bpf_map *map, bool unpriv)
206 {
207 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 	unpriv |= bpf_map_ptr_unpriv(aux);
209 	aux->map_ptr_state = (unsigned long)map |
210 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215 	return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227 
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230 	bool poisoned = bpf_map_key_poisoned(aux);
231 
232 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235 
bpf_pseudo_call(const struct bpf_insn * insn)236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238 	return insn->code == (BPF_JMP | BPF_CALL) &&
239 	       insn->src_reg == BPF_PSEUDO_CALL;
240 }
241 
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244 	return insn->code == (BPF_JMP | BPF_CALL) &&
245 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247 
248 struct bpf_call_arg_meta {
249 	struct bpf_map *map_ptr;
250 	bool raw_mode;
251 	bool pkt_access;
252 	u8 release_regno;
253 	int regno;
254 	int access_size;
255 	int mem_size;
256 	u64 msize_max_value;
257 	int ref_obj_id;
258 	int map_uid;
259 	int func_id;
260 	struct btf *btf;
261 	u32 btf_id;
262 	struct btf *ret_btf;
263 	u32 ret_btf_id;
264 	u32 subprogno;
265 	struct bpf_map_value_off_desc *kptr_off_desc;
266 	u8 uninit_dynptr_regno;
267 };
268 
269 struct btf *btf_vmlinux;
270 
271 static DEFINE_MUTEX(bpf_verifier_lock);
272 
273 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276 	const struct bpf_line_info *linfo;
277 	const struct bpf_prog *prog;
278 	u32 i, nr_linfo;
279 
280 	prog = env->prog;
281 	nr_linfo = prog->aux->nr_linfo;
282 
283 	if (!nr_linfo || insn_off >= prog->len)
284 		return NULL;
285 
286 	linfo = prog->aux->linfo;
287 	for (i = 1; i < nr_linfo; i++)
288 		if (insn_off < linfo[i].insn_off)
289 			break;
290 
291 	return &linfo[i - 1];
292 }
293 
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 		       va_list args)
296 {
297 	unsigned int n;
298 
299 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300 
301 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 		  "verifier log line truncated - local buffer too short\n");
303 
304 	if (log->level == BPF_LOG_KERNEL) {
305 		bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306 
307 		pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308 		return;
309 	}
310 
311 	n = min(log->len_total - log->len_used - 1, n);
312 	log->kbuf[n] = '\0';
313 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 		log->len_used += n;
315 	else
316 		log->ubuf = NULL;
317 }
318 
bpf_vlog_reset(struct bpf_verifier_log * log,u32 new_pos)319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321 	char zero = 0;
322 
323 	if (!bpf_verifier_log_needed(log))
324 		return;
325 
326 	log->len_used = new_pos;
327 	if (put_user(zero, log->ubuf + new_pos))
328 		log->ubuf = NULL;
329 }
330 
331 /* log_level controls verbosity level of eBPF verifier.
332  * bpf_verifier_log_write() is used to dump the verification trace to the log,
333  * so the user can figure out what's wrong with the program
334  */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 					   const char *fmt, ...)
337 {
338 	va_list args;
339 
340 	if (!bpf_verifier_log_needed(&env->log))
341 		return;
342 
343 	va_start(args, fmt);
344 	bpf_verifier_vlog(&env->log, fmt, args);
345 	va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348 
verbose(void * private_data,const char * fmt,...)349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351 	struct bpf_verifier_env *env = private_data;
352 	va_list args;
353 
354 	if (!bpf_verifier_log_needed(&env->log))
355 		return;
356 
357 	va_start(args, fmt);
358 	bpf_verifier_vlog(&env->log, fmt, args);
359 	va_end(args);
360 }
361 
bpf_log(struct bpf_verifier_log * log,const char * fmt,...)362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 			    const char *fmt, ...)
364 {
365 	va_list args;
366 
367 	if (!bpf_verifier_log_needed(log))
368 		return;
369 
370 	va_start(args, fmt);
371 	bpf_verifier_vlog(log, fmt, args);
372 	va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375 
ltrim(const char * s)376 static const char *ltrim(const char *s)
377 {
378 	while (isspace(*s))
379 		s++;
380 
381 	return s;
382 }
383 
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 					 u32 insn_off,
386 					 const char *prefix_fmt, ...)
387 {
388 	const struct bpf_line_info *linfo;
389 
390 	if (!bpf_verifier_log_needed(&env->log))
391 		return;
392 
393 	linfo = find_linfo(env, insn_off);
394 	if (!linfo || linfo == env->prev_linfo)
395 		return;
396 
397 	if (prefix_fmt) {
398 		va_list args;
399 
400 		va_start(args, prefix_fmt);
401 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 		va_end(args);
403 	}
404 
405 	verbose(env, "%s\n",
406 		ltrim(btf_name_by_offset(env->prog->aux->btf,
407 					 linfo->line_off)));
408 
409 	env->prev_linfo = linfo;
410 }
411 
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct tnum * range,const char * ctx,const char * reg_name)412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 				   struct bpf_reg_state *reg,
414 				   struct tnum *range, const char *ctx,
415 				   const char *reg_name)
416 {
417 	char tn_buf[48];
418 
419 	verbose(env, "At %s the register %s ", ctx, reg_name);
420 	if (!tnum_is_unknown(reg->var_off)) {
421 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 		verbose(env, "has value %s", tn_buf);
423 	} else {
424 		verbose(env, "has unknown scalar value");
425 	}
426 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 	verbose(env, " should have been in %s\n", tn_buf);
428 }
429 
type_is_pkt_pointer(enum bpf_reg_type type)430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432 	type = base_type(type);
433 	return type == PTR_TO_PACKET ||
434 	       type == PTR_TO_PACKET_META;
435 }
436 
type_is_sk_pointer(enum bpf_reg_type type)437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439 	return type == PTR_TO_SOCKET ||
440 		type == PTR_TO_SOCK_COMMON ||
441 		type == PTR_TO_TCP_SOCK ||
442 		type == PTR_TO_XDP_SOCK;
443 }
444 
reg_type_not_null(enum bpf_reg_type type)445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447 	return type == PTR_TO_SOCKET ||
448 		type == PTR_TO_TCP_SOCK ||
449 		type == PTR_TO_MAP_VALUE ||
450 		type == PTR_TO_MAP_KEY ||
451 		type == PTR_TO_SOCK_COMMON;
452 }
453 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456 	return reg->type == PTR_TO_MAP_VALUE &&
457 		map_value_has_spin_lock(reg->map_ptr);
458 }
459 
reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
461 {
462 	type = base_type(type);
463 	return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464 		type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
465 }
466 
type_is_rdonly_mem(u32 type)467 static bool type_is_rdonly_mem(u32 type)
468 {
469 	return type & MEM_RDONLY;
470 }
471 
type_may_be_null(u32 type)472 static bool type_may_be_null(u32 type)
473 {
474 	return type & PTR_MAYBE_NULL;
475 }
476 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)477 static bool is_acquire_function(enum bpf_func_id func_id,
478 				const struct bpf_map *map)
479 {
480 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481 
482 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
483 	    func_id == BPF_FUNC_sk_lookup_udp ||
484 	    func_id == BPF_FUNC_skc_lookup_tcp ||
485 	    func_id == BPF_FUNC_ringbuf_reserve ||
486 	    func_id == BPF_FUNC_kptr_xchg)
487 		return true;
488 
489 	if (func_id == BPF_FUNC_map_lookup_elem &&
490 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
491 	     map_type == BPF_MAP_TYPE_SOCKHASH))
492 		return true;
493 
494 	return false;
495 }
496 
is_ptr_cast_function(enum bpf_func_id func_id)497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
498 {
499 	return func_id == BPF_FUNC_tcp_sock ||
500 		func_id == BPF_FUNC_sk_fullsock ||
501 		func_id == BPF_FUNC_skc_to_tcp_sock ||
502 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
503 		func_id == BPF_FUNC_skc_to_udp6_sock ||
504 		func_id == BPF_FUNC_skc_to_mptcp_sock ||
505 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
507 }
508 
is_dynptr_ref_function(enum bpf_func_id func_id)509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
510 {
511 	return func_id == BPF_FUNC_dynptr_data;
512 }
513 
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)514 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
515 					const struct bpf_map *map)
516 {
517 	int ref_obj_uses = 0;
518 
519 	if (is_ptr_cast_function(func_id))
520 		ref_obj_uses++;
521 	if (is_acquire_function(func_id, map))
522 		ref_obj_uses++;
523 	if (is_dynptr_ref_function(func_id))
524 		ref_obj_uses++;
525 
526 	return ref_obj_uses > 1;
527 }
528 
is_cmpxchg_insn(const struct bpf_insn * insn)529 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
530 {
531 	return BPF_CLASS(insn->code) == BPF_STX &&
532 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
533 	       insn->imm == BPF_CMPXCHG;
534 }
535 
536 /* string representation of 'enum bpf_reg_type'
537  *
538  * Note that reg_type_str() can not appear more than once in a single verbose()
539  * statement.
540  */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)541 static const char *reg_type_str(struct bpf_verifier_env *env,
542 				enum bpf_reg_type type)
543 {
544 	char postfix[16] = {0}, prefix[32] = {0};
545 	static const char * const str[] = {
546 		[NOT_INIT]		= "?",
547 		[SCALAR_VALUE]		= "scalar",
548 		[PTR_TO_CTX]		= "ctx",
549 		[CONST_PTR_TO_MAP]	= "map_ptr",
550 		[PTR_TO_MAP_VALUE]	= "map_value",
551 		[PTR_TO_STACK]		= "fp",
552 		[PTR_TO_PACKET]		= "pkt",
553 		[PTR_TO_PACKET_META]	= "pkt_meta",
554 		[PTR_TO_PACKET_END]	= "pkt_end",
555 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
556 		[PTR_TO_SOCKET]		= "sock",
557 		[PTR_TO_SOCK_COMMON]	= "sock_common",
558 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
559 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
560 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
561 		[PTR_TO_BTF_ID]		= "ptr_",
562 		[PTR_TO_MEM]		= "mem",
563 		[PTR_TO_BUF]		= "buf",
564 		[PTR_TO_FUNC]		= "func",
565 		[PTR_TO_MAP_KEY]	= "map_key",
566 		[PTR_TO_DYNPTR]		= "dynptr_ptr",
567 	};
568 
569 	if (type & PTR_MAYBE_NULL) {
570 		if (base_type(type) == PTR_TO_BTF_ID)
571 			strncpy(postfix, "or_null_", 16);
572 		else
573 			strncpy(postfix, "_or_null", 16);
574 	}
575 
576 	if (type & MEM_RDONLY)
577 		strncpy(prefix, "rdonly_", 32);
578 	if (type & MEM_ALLOC)
579 		strncpy(prefix, "alloc_", 32);
580 	if (type & MEM_USER)
581 		strncpy(prefix, "user_", 32);
582 	if (type & MEM_PERCPU)
583 		strncpy(prefix, "percpu_", 32);
584 	if (type & PTR_UNTRUSTED)
585 		strncpy(prefix, "untrusted_", 32);
586 
587 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
588 		 prefix, str[base_type(type)], postfix);
589 	return env->type_str_buf;
590 }
591 
592 static char slot_type_char[] = {
593 	[STACK_INVALID]	= '?',
594 	[STACK_SPILL]	= 'r',
595 	[STACK_MISC]	= 'm',
596 	[STACK_ZERO]	= '0',
597 	[STACK_DYNPTR]	= 'd',
598 };
599 
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)600 static void print_liveness(struct bpf_verifier_env *env,
601 			   enum bpf_reg_liveness live)
602 {
603 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
604 	    verbose(env, "_");
605 	if (live & REG_LIVE_READ)
606 		verbose(env, "r");
607 	if (live & REG_LIVE_WRITTEN)
608 		verbose(env, "w");
609 	if (live & REG_LIVE_DONE)
610 		verbose(env, "D");
611 }
612 
get_spi(s32 off)613 static int get_spi(s32 off)
614 {
615 	return (-off - 1) / BPF_REG_SIZE;
616 }
617 
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
619 {
620 	int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
621 
622 	/* We need to check that slots between [spi - nr_slots + 1, spi] are
623 	 * within [0, allocated_stack).
624 	 *
625 	 * Please note that the spi grows downwards. For example, a dynptr
626 	 * takes the size of two stack slots; the first slot will be at
627 	 * spi and the second slot will be at spi - 1.
628 	 */
629 	return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
630 }
631 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633 				   const struct bpf_reg_state *reg)
634 {
635 	struct bpf_verifier_state *cur = env->cur_state;
636 
637 	return cur->frame[reg->frameno];
638 }
639 
kernel_type_name(const struct btf * btf,u32 id)640 static const char *kernel_type_name(const struct btf* btf, u32 id)
641 {
642 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
643 }
644 
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)645 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
646 {
647 	env->scratched_regs |= 1U << regno;
648 }
649 
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)650 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
651 {
652 	env->scratched_stack_slots |= 1ULL << spi;
653 }
654 
reg_scratched(const struct bpf_verifier_env * env,u32 regno)655 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
656 {
657 	return (env->scratched_regs >> regno) & 1;
658 }
659 
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)660 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
661 {
662 	return (env->scratched_stack_slots >> regno) & 1;
663 }
664 
verifier_state_scratched(const struct bpf_verifier_env * env)665 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
666 {
667 	return env->scratched_regs || env->scratched_stack_slots;
668 }
669 
mark_verifier_state_clean(struct bpf_verifier_env * env)670 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
671 {
672 	env->scratched_regs = 0U;
673 	env->scratched_stack_slots = 0ULL;
674 }
675 
676 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)677 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
678 {
679 	env->scratched_regs = ~0U;
680 	env->scratched_stack_slots = ~0ULL;
681 }
682 
arg_to_dynptr_type(enum bpf_arg_type arg_type)683 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
684 {
685 	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
686 	case DYNPTR_TYPE_LOCAL:
687 		return BPF_DYNPTR_TYPE_LOCAL;
688 	case DYNPTR_TYPE_RINGBUF:
689 		return BPF_DYNPTR_TYPE_RINGBUF;
690 	default:
691 		return BPF_DYNPTR_TYPE_INVALID;
692 	}
693 }
694 
dynptr_type_refcounted(enum bpf_dynptr_type type)695 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
696 {
697 	return type == BPF_DYNPTR_TYPE_RINGBUF;
698 }
699 
mark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type,int insn_idx)700 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
701 				   enum bpf_arg_type arg_type, int insn_idx)
702 {
703 	struct bpf_func_state *state = func(env, reg);
704 	enum bpf_dynptr_type type;
705 	int spi, i, id;
706 
707 	spi = get_spi(reg->off);
708 
709 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
710 		return -EINVAL;
711 
712 	for (i = 0; i < BPF_REG_SIZE; i++) {
713 		state->stack[spi].slot_type[i] = STACK_DYNPTR;
714 		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
715 	}
716 
717 	type = arg_to_dynptr_type(arg_type);
718 	if (type == BPF_DYNPTR_TYPE_INVALID)
719 		return -EINVAL;
720 
721 	state->stack[spi].spilled_ptr.dynptr.first_slot = true;
722 	state->stack[spi].spilled_ptr.dynptr.type = type;
723 	state->stack[spi - 1].spilled_ptr.dynptr.type = type;
724 
725 	if (dynptr_type_refcounted(type)) {
726 		/* The id is used to track proper releasing */
727 		id = acquire_reference_state(env, insn_idx);
728 		if (id < 0)
729 			return id;
730 
731 		state->stack[spi].spilled_ptr.id = id;
732 		state->stack[spi - 1].spilled_ptr.id = id;
733 	}
734 
735 	return 0;
736 }
737 
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)738 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
739 {
740 	struct bpf_func_state *state = func(env, reg);
741 	int spi, i;
742 
743 	spi = get_spi(reg->off);
744 
745 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
746 		return -EINVAL;
747 
748 	for (i = 0; i < BPF_REG_SIZE; i++) {
749 		state->stack[spi].slot_type[i] = STACK_INVALID;
750 		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
751 	}
752 
753 	/* Invalidate any slices associated with this dynptr */
754 	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
755 		release_reference(env, state->stack[spi].spilled_ptr.id);
756 		state->stack[spi].spilled_ptr.id = 0;
757 		state->stack[spi - 1].spilled_ptr.id = 0;
758 	}
759 
760 	state->stack[spi].spilled_ptr.dynptr.first_slot = false;
761 	state->stack[spi].spilled_ptr.dynptr.type = 0;
762 	state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
763 
764 	return 0;
765 }
766 
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)767 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
768 {
769 	struct bpf_func_state *state = func(env, reg);
770 	int spi = get_spi(reg->off);
771 	int i;
772 
773 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
774 		return true;
775 
776 	for (i = 0; i < BPF_REG_SIZE; i++) {
777 		if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
778 		    state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
779 			return false;
780 	}
781 
782 	return true;
783 }
784 
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)785 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
786 			      struct bpf_reg_state *reg)
787 {
788 	struct bpf_func_state *state = func(env, reg);
789 	int spi = get_spi(reg->off);
790 	int i;
791 
792 	if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
793 	    !state->stack[spi].spilled_ptr.dynptr.first_slot)
794 		return false;
795 
796 	for (i = 0; i < BPF_REG_SIZE; i++) {
797 		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
798 		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
799 			return false;
800 	}
801 
802 	return true;
803 }
804 
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)805 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
806 			     struct bpf_reg_state *reg,
807 			     enum bpf_arg_type arg_type)
808 {
809 	struct bpf_func_state *state = func(env, reg);
810 	enum bpf_dynptr_type dynptr_type;
811 	int spi = get_spi(reg->off);
812 
813 	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
814 	if (arg_type == ARG_PTR_TO_DYNPTR)
815 		return true;
816 
817 	dynptr_type = arg_to_dynptr_type(arg_type);
818 
819 	return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
820 }
821 
822 /* The reg state of a pointer or a bounded scalar was saved when
823  * it was spilled to the stack.
824  */
is_spilled_reg(const struct bpf_stack_state * stack)825 static bool is_spilled_reg(const struct bpf_stack_state *stack)
826 {
827 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
828 }
829 
scrub_spilled_slot(u8 * stype)830 static void scrub_spilled_slot(u8 *stype)
831 {
832 	if (*stype != STACK_INVALID)
833 		*stype = STACK_MISC;
834 }
835 
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state,bool print_all)836 static void print_verifier_state(struct bpf_verifier_env *env,
837 				 const struct bpf_func_state *state,
838 				 bool print_all)
839 {
840 	const struct bpf_reg_state *reg;
841 	enum bpf_reg_type t;
842 	int i;
843 
844 	if (state->frameno)
845 		verbose(env, " frame%d:", state->frameno);
846 	for (i = 0; i < MAX_BPF_REG; i++) {
847 		reg = &state->regs[i];
848 		t = reg->type;
849 		if (t == NOT_INIT)
850 			continue;
851 		if (!print_all && !reg_scratched(env, i))
852 			continue;
853 		verbose(env, " R%d", i);
854 		print_liveness(env, reg->live);
855 		verbose(env, "=");
856 		if (t == SCALAR_VALUE && reg->precise)
857 			verbose(env, "P");
858 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
859 		    tnum_is_const(reg->var_off)) {
860 			/* reg->off should be 0 for SCALAR_VALUE */
861 			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
862 			verbose(env, "%lld", reg->var_off.value + reg->off);
863 		} else {
864 			const char *sep = "";
865 
866 			verbose(env, "%s", reg_type_str(env, t));
867 			if (base_type(t) == PTR_TO_BTF_ID)
868 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
869 			verbose(env, "(");
870 /*
871  * _a stands for append, was shortened to avoid multiline statements below.
872  * This macro is used to output a comma separated list of attributes.
873  */
874 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
875 
876 			if (reg->id)
877 				verbose_a("id=%d", reg->id);
878 			if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
879 				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
880 			if (t != SCALAR_VALUE)
881 				verbose_a("off=%d", reg->off);
882 			if (type_is_pkt_pointer(t))
883 				verbose_a("r=%d", reg->range);
884 			else if (base_type(t) == CONST_PTR_TO_MAP ||
885 				 base_type(t) == PTR_TO_MAP_KEY ||
886 				 base_type(t) == PTR_TO_MAP_VALUE)
887 				verbose_a("ks=%d,vs=%d",
888 					  reg->map_ptr->key_size,
889 					  reg->map_ptr->value_size);
890 			if (tnum_is_const(reg->var_off)) {
891 				/* Typically an immediate SCALAR_VALUE, but
892 				 * could be a pointer whose offset is too big
893 				 * for reg->off
894 				 */
895 				verbose_a("imm=%llx", reg->var_off.value);
896 			} else {
897 				if (reg->smin_value != reg->umin_value &&
898 				    reg->smin_value != S64_MIN)
899 					verbose_a("smin=%lld", (long long)reg->smin_value);
900 				if (reg->smax_value != reg->umax_value &&
901 				    reg->smax_value != S64_MAX)
902 					verbose_a("smax=%lld", (long long)reg->smax_value);
903 				if (reg->umin_value != 0)
904 					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
905 				if (reg->umax_value != U64_MAX)
906 					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
907 				if (!tnum_is_unknown(reg->var_off)) {
908 					char tn_buf[48];
909 
910 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
911 					verbose_a("var_off=%s", tn_buf);
912 				}
913 				if (reg->s32_min_value != reg->smin_value &&
914 				    reg->s32_min_value != S32_MIN)
915 					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
916 				if (reg->s32_max_value != reg->smax_value &&
917 				    reg->s32_max_value != S32_MAX)
918 					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
919 				if (reg->u32_min_value != reg->umin_value &&
920 				    reg->u32_min_value != U32_MIN)
921 					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
922 				if (reg->u32_max_value != reg->umax_value &&
923 				    reg->u32_max_value != U32_MAX)
924 					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
925 			}
926 #undef verbose_a
927 
928 			verbose(env, ")");
929 		}
930 	}
931 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
932 		char types_buf[BPF_REG_SIZE + 1];
933 		bool valid = false;
934 		int j;
935 
936 		for (j = 0; j < BPF_REG_SIZE; j++) {
937 			if (state->stack[i].slot_type[j] != STACK_INVALID)
938 				valid = true;
939 			types_buf[j] = slot_type_char[
940 					state->stack[i].slot_type[j]];
941 		}
942 		types_buf[BPF_REG_SIZE] = 0;
943 		if (!valid)
944 			continue;
945 		if (!print_all && !stack_slot_scratched(env, i))
946 			continue;
947 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
948 		print_liveness(env, state->stack[i].spilled_ptr.live);
949 		if (is_spilled_reg(&state->stack[i])) {
950 			reg = &state->stack[i].spilled_ptr;
951 			t = reg->type;
952 			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
953 			if (t == SCALAR_VALUE && reg->precise)
954 				verbose(env, "P");
955 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
956 				verbose(env, "%lld", reg->var_off.value + reg->off);
957 		} else {
958 			verbose(env, "=%s", types_buf);
959 		}
960 	}
961 	if (state->acquired_refs && state->refs[0].id) {
962 		verbose(env, " refs=%d", state->refs[0].id);
963 		for (i = 1; i < state->acquired_refs; i++)
964 			if (state->refs[i].id)
965 				verbose(env, ",%d", state->refs[i].id);
966 	}
967 	if (state->in_callback_fn)
968 		verbose(env, " cb");
969 	if (state->in_async_callback_fn)
970 		verbose(env, " async_cb");
971 	verbose(env, "\n");
972 	mark_verifier_state_clean(env);
973 }
974 
vlog_alignment(u32 pos)975 static inline u32 vlog_alignment(u32 pos)
976 {
977 	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
978 			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
979 }
980 
print_insn_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)981 static void print_insn_state(struct bpf_verifier_env *env,
982 			     const struct bpf_func_state *state)
983 {
984 	if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
985 		/* remove new line character */
986 		bpf_vlog_reset(&env->log, env->prev_log_len - 1);
987 		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
988 	} else {
989 		verbose(env, "%d:", env->insn_idx);
990 	}
991 	print_verifier_state(env, state, false);
992 }
993 
994 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
995  * small to hold src. This is different from krealloc since we don't want to preserve
996  * the contents of dst.
997  *
998  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
999  * not be allocated.
1000  */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1001 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1002 {
1003 	size_t alloc_bytes;
1004 	void *orig = dst;
1005 	size_t bytes;
1006 
1007 	if (ZERO_OR_NULL_PTR(src))
1008 		goto out;
1009 
1010 	if (unlikely(check_mul_overflow(n, size, &bytes)))
1011 		return NULL;
1012 
1013 	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1014 	dst = krealloc(orig, alloc_bytes, flags);
1015 	if (!dst) {
1016 		kfree(orig);
1017 		return NULL;
1018 	}
1019 
1020 	memcpy(dst, src, bytes);
1021 out:
1022 	return dst ? dst : ZERO_SIZE_PTR;
1023 }
1024 
1025 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1026  * small to hold new_n items. new items are zeroed out if the array grows.
1027  *
1028  * Contrary to krealloc_array, does not free arr if new_n is zero.
1029  */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1030 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1031 {
1032 	size_t alloc_size;
1033 	void *new_arr;
1034 
1035 	if (!new_n || old_n == new_n)
1036 		goto out;
1037 
1038 	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1039 	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1040 	if (!new_arr) {
1041 		kfree(arr);
1042 		return NULL;
1043 	}
1044 	arr = new_arr;
1045 
1046 	if (new_n > old_n)
1047 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1048 
1049 out:
1050 	return arr ? arr : ZERO_SIZE_PTR;
1051 }
1052 
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1053 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1054 {
1055 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1056 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1057 	if (!dst->refs)
1058 		return -ENOMEM;
1059 
1060 	dst->acquired_refs = src->acquired_refs;
1061 	return 0;
1062 }
1063 
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1064 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1065 {
1066 	size_t n = src->allocated_stack / BPF_REG_SIZE;
1067 
1068 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1069 				GFP_KERNEL);
1070 	if (!dst->stack)
1071 		return -ENOMEM;
1072 
1073 	dst->allocated_stack = src->allocated_stack;
1074 	return 0;
1075 }
1076 
resize_reference_state(struct bpf_func_state * state,size_t n)1077 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1078 {
1079 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1080 				    sizeof(struct bpf_reference_state));
1081 	if (!state->refs)
1082 		return -ENOMEM;
1083 
1084 	state->acquired_refs = n;
1085 	return 0;
1086 }
1087 
grow_stack_state(struct bpf_func_state * state,int size)1088 static int grow_stack_state(struct bpf_func_state *state, int size)
1089 {
1090 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1091 
1092 	if (old_n >= n)
1093 		return 0;
1094 
1095 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1096 	if (!state->stack)
1097 		return -ENOMEM;
1098 
1099 	state->allocated_stack = size;
1100 	return 0;
1101 }
1102 
1103 /* Acquire a pointer id from the env and update the state->refs to include
1104  * this new pointer reference.
1105  * On success, returns a valid pointer id to associate with the register
1106  * On failure, returns a negative errno.
1107  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1108 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1109 {
1110 	struct bpf_func_state *state = cur_func(env);
1111 	int new_ofs = state->acquired_refs;
1112 	int id, err;
1113 
1114 	err = resize_reference_state(state, state->acquired_refs + 1);
1115 	if (err)
1116 		return err;
1117 	id = ++env->id_gen;
1118 	state->refs[new_ofs].id = id;
1119 	state->refs[new_ofs].insn_idx = insn_idx;
1120 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1121 
1122 	return id;
1123 }
1124 
1125 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)1126 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1127 {
1128 	int i, last_idx;
1129 
1130 	last_idx = state->acquired_refs - 1;
1131 	for (i = 0; i < state->acquired_refs; i++) {
1132 		if (state->refs[i].id == ptr_id) {
1133 			/* Cannot release caller references in callbacks */
1134 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1135 				return -EINVAL;
1136 			if (last_idx && i != last_idx)
1137 				memcpy(&state->refs[i], &state->refs[last_idx],
1138 				       sizeof(*state->refs));
1139 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1140 			state->acquired_refs--;
1141 			return 0;
1142 		}
1143 	}
1144 	return -EINVAL;
1145 }
1146 
free_func_state(struct bpf_func_state * state)1147 static void free_func_state(struct bpf_func_state *state)
1148 {
1149 	if (!state)
1150 		return;
1151 	kfree(state->refs);
1152 	kfree(state->stack);
1153 	kfree(state);
1154 }
1155 
clear_jmp_history(struct bpf_verifier_state * state)1156 static void clear_jmp_history(struct bpf_verifier_state *state)
1157 {
1158 	kfree(state->jmp_history);
1159 	state->jmp_history = NULL;
1160 	state->jmp_history_cnt = 0;
1161 }
1162 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1163 static void free_verifier_state(struct bpf_verifier_state *state,
1164 				bool free_self)
1165 {
1166 	int i;
1167 
1168 	for (i = 0; i <= state->curframe; i++) {
1169 		free_func_state(state->frame[i]);
1170 		state->frame[i] = NULL;
1171 	}
1172 	clear_jmp_history(state);
1173 	if (free_self)
1174 		kfree(state);
1175 }
1176 
1177 /* copy verifier state from src to dst growing dst stack space
1178  * when necessary to accommodate larger src stack
1179  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1180 static int copy_func_state(struct bpf_func_state *dst,
1181 			   const struct bpf_func_state *src)
1182 {
1183 	int err;
1184 
1185 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1186 	err = copy_reference_state(dst, src);
1187 	if (err)
1188 		return err;
1189 	return copy_stack_state(dst, src);
1190 }
1191 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1192 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1193 			       const struct bpf_verifier_state *src)
1194 {
1195 	struct bpf_func_state *dst;
1196 	int i, err;
1197 
1198 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1199 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1200 					    GFP_USER);
1201 	if (!dst_state->jmp_history)
1202 		return -ENOMEM;
1203 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1204 
1205 	/* if dst has more stack frames then src frame, free them */
1206 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1207 		free_func_state(dst_state->frame[i]);
1208 		dst_state->frame[i] = NULL;
1209 	}
1210 	dst_state->speculative = src->speculative;
1211 	dst_state->curframe = src->curframe;
1212 	dst_state->active_spin_lock = src->active_spin_lock;
1213 	dst_state->branches = src->branches;
1214 	dst_state->parent = src->parent;
1215 	dst_state->first_insn_idx = src->first_insn_idx;
1216 	dst_state->last_insn_idx = src->last_insn_idx;
1217 	for (i = 0; i <= src->curframe; i++) {
1218 		dst = dst_state->frame[i];
1219 		if (!dst) {
1220 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1221 			if (!dst)
1222 				return -ENOMEM;
1223 			dst_state->frame[i] = dst;
1224 		}
1225 		err = copy_func_state(dst, src->frame[i]);
1226 		if (err)
1227 			return err;
1228 	}
1229 	return 0;
1230 }
1231 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1232 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1233 {
1234 	while (st) {
1235 		u32 br = --st->branches;
1236 
1237 		/* WARN_ON(br > 1) technically makes sense here,
1238 		 * but see comment in push_stack(), hence:
1239 		 */
1240 		WARN_ONCE((int)br < 0,
1241 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1242 			  br);
1243 		if (br)
1244 			break;
1245 		st = st->parent;
1246 	}
1247 }
1248 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)1249 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1250 		     int *insn_idx, bool pop_log)
1251 {
1252 	struct bpf_verifier_state *cur = env->cur_state;
1253 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1254 	int err;
1255 
1256 	if (env->head == NULL)
1257 		return -ENOENT;
1258 
1259 	if (cur) {
1260 		err = copy_verifier_state(cur, &head->st);
1261 		if (err)
1262 			return err;
1263 	}
1264 	if (pop_log)
1265 		bpf_vlog_reset(&env->log, head->log_pos);
1266 	if (insn_idx)
1267 		*insn_idx = head->insn_idx;
1268 	if (prev_insn_idx)
1269 		*prev_insn_idx = head->prev_insn_idx;
1270 	elem = head->next;
1271 	free_verifier_state(&head->st, false);
1272 	kfree(head);
1273 	env->head = elem;
1274 	env->stack_size--;
1275 	return 0;
1276 }
1277 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)1278 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1279 					     int insn_idx, int prev_insn_idx,
1280 					     bool speculative)
1281 {
1282 	struct bpf_verifier_state *cur = env->cur_state;
1283 	struct bpf_verifier_stack_elem *elem;
1284 	int err;
1285 
1286 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1287 	if (!elem)
1288 		goto err;
1289 
1290 	elem->insn_idx = insn_idx;
1291 	elem->prev_insn_idx = prev_insn_idx;
1292 	elem->next = env->head;
1293 	elem->log_pos = env->log.len_used;
1294 	env->head = elem;
1295 	env->stack_size++;
1296 	err = copy_verifier_state(&elem->st, cur);
1297 	if (err)
1298 		goto err;
1299 	elem->st.speculative |= speculative;
1300 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1301 		verbose(env, "The sequence of %d jumps is too complex.\n",
1302 			env->stack_size);
1303 		goto err;
1304 	}
1305 	if (elem->st.parent) {
1306 		++elem->st.parent->branches;
1307 		/* WARN_ON(branches > 2) technically makes sense here,
1308 		 * but
1309 		 * 1. speculative states will bump 'branches' for non-branch
1310 		 * instructions
1311 		 * 2. is_state_visited() heuristics may decide not to create
1312 		 * a new state for a sequence of branches and all such current
1313 		 * and cloned states will be pointing to a single parent state
1314 		 * which might have large 'branches' count.
1315 		 */
1316 	}
1317 	return &elem->st;
1318 err:
1319 	free_verifier_state(env->cur_state, true);
1320 	env->cur_state = NULL;
1321 	/* pop all elements and return */
1322 	while (!pop_stack(env, NULL, NULL, false));
1323 	return NULL;
1324 }
1325 
1326 #define CALLER_SAVED_REGS 6
1327 static const int caller_saved[CALLER_SAVED_REGS] = {
1328 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1329 };
1330 
1331 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1332 				struct bpf_reg_state *reg);
1333 
1334 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1335 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1336 {
1337 	reg->var_off = tnum_const(imm);
1338 	reg->smin_value = (s64)imm;
1339 	reg->smax_value = (s64)imm;
1340 	reg->umin_value = imm;
1341 	reg->umax_value = imm;
1342 
1343 	reg->s32_min_value = (s32)imm;
1344 	reg->s32_max_value = (s32)imm;
1345 	reg->u32_min_value = (u32)imm;
1346 	reg->u32_max_value = (u32)imm;
1347 }
1348 
1349 /* Mark the unknown part of a register (variable offset or scalar value) as
1350  * known to have the value @imm.
1351  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1352 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1353 {
1354 	/* Clear id, off, and union(map_ptr, range) */
1355 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1356 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1357 	___mark_reg_known(reg, imm);
1358 }
1359 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1360 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1361 {
1362 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1363 	reg->s32_min_value = (s32)imm;
1364 	reg->s32_max_value = (s32)imm;
1365 	reg->u32_min_value = (u32)imm;
1366 	reg->u32_max_value = (u32)imm;
1367 }
1368 
1369 /* Mark the 'variable offset' part of a register as zero.  This should be
1370  * used only on registers holding a pointer type.
1371  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1372 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1373 {
1374 	__mark_reg_known(reg, 0);
1375 }
1376 
__mark_reg_const_zero(struct bpf_reg_state * reg)1377 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1378 {
1379 	__mark_reg_known(reg, 0);
1380 	reg->type = SCALAR_VALUE;
1381 }
1382 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1383 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1384 				struct bpf_reg_state *regs, u32 regno)
1385 {
1386 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1387 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1388 		/* Something bad happened, let's kill all regs */
1389 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1390 			__mark_reg_not_init(env, regs + regno);
1391 		return;
1392 	}
1393 	__mark_reg_known_zero(regs + regno);
1394 }
1395 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)1396 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1397 {
1398 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1399 		const struct bpf_map *map = reg->map_ptr;
1400 
1401 		if (map->inner_map_meta) {
1402 			reg->type = CONST_PTR_TO_MAP;
1403 			reg->map_ptr = map->inner_map_meta;
1404 			/* transfer reg's id which is unique for every map_lookup_elem
1405 			 * as UID of the inner map.
1406 			 */
1407 			if (map_value_has_timer(map->inner_map_meta))
1408 				reg->map_uid = reg->id;
1409 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1410 			reg->type = PTR_TO_XDP_SOCK;
1411 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1412 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1413 			reg->type = PTR_TO_SOCKET;
1414 		} else {
1415 			reg->type = PTR_TO_MAP_VALUE;
1416 		}
1417 		return;
1418 	}
1419 
1420 	reg->type &= ~PTR_MAYBE_NULL;
1421 }
1422 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1423 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1424 {
1425 	return type_is_pkt_pointer(reg->type);
1426 }
1427 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1428 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1429 {
1430 	return reg_is_pkt_pointer(reg) ||
1431 	       reg->type == PTR_TO_PACKET_END;
1432 }
1433 
1434 /* 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)1435 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1436 				    enum bpf_reg_type which)
1437 {
1438 	/* The register can already have a range from prior markings.
1439 	 * This is fine as long as it hasn't been advanced from its
1440 	 * origin.
1441 	 */
1442 	return reg->type == which &&
1443 	       reg->id == 0 &&
1444 	       reg->off == 0 &&
1445 	       tnum_equals_const(reg->var_off, 0);
1446 }
1447 
1448 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1449 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1450 {
1451 	reg->smin_value = S64_MIN;
1452 	reg->smax_value = S64_MAX;
1453 	reg->umin_value = 0;
1454 	reg->umax_value = U64_MAX;
1455 
1456 	reg->s32_min_value = S32_MIN;
1457 	reg->s32_max_value = S32_MAX;
1458 	reg->u32_min_value = 0;
1459 	reg->u32_max_value = U32_MAX;
1460 }
1461 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1462 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1463 {
1464 	reg->smin_value = S64_MIN;
1465 	reg->smax_value = S64_MAX;
1466 	reg->umin_value = 0;
1467 	reg->umax_value = U64_MAX;
1468 }
1469 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1470 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1471 {
1472 	reg->s32_min_value = S32_MIN;
1473 	reg->s32_max_value = S32_MAX;
1474 	reg->u32_min_value = 0;
1475 	reg->u32_max_value = U32_MAX;
1476 }
1477 
__update_reg32_bounds(struct bpf_reg_state * reg)1478 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1479 {
1480 	struct tnum var32_off = tnum_subreg(reg->var_off);
1481 
1482 	/* min signed is max(sign bit) | min(other bits) */
1483 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1484 			var32_off.value | (var32_off.mask & S32_MIN));
1485 	/* max signed is min(sign bit) | max(other bits) */
1486 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1487 			var32_off.value | (var32_off.mask & S32_MAX));
1488 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1489 	reg->u32_max_value = min(reg->u32_max_value,
1490 				 (u32)(var32_off.value | var32_off.mask));
1491 }
1492 
__update_reg64_bounds(struct bpf_reg_state * reg)1493 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1494 {
1495 	/* min signed is max(sign bit) | min(other bits) */
1496 	reg->smin_value = max_t(s64, reg->smin_value,
1497 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1498 	/* max signed is min(sign bit) | max(other bits) */
1499 	reg->smax_value = min_t(s64, reg->smax_value,
1500 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1501 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1502 	reg->umax_value = min(reg->umax_value,
1503 			      reg->var_off.value | reg->var_off.mask);
1504 }
1505 
__update_reg_bounds(struct bpf_reg_state * reg)1506 static void __update_reg_bounds(struct bpf_reg_state *reg)
1507 {
1508 	__update_reg32_bounds(reg);
1509 	__update_reg64_bounds(reg);
1510 }
1511 
1512 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1513 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1514 {
1515 	/* Learn sign from signed bounds.
1516 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1517 	 * are the same, so combine.  This works even in the negative case, e.g.
1518 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1519 	 */
1520 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1521 		reg->s32_min_value = reg->u32_min_value =
1522 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1523 		reg->s32_max_value = reg->u32_max_value =
1524 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1525 		return;
1526 	}
1527 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1528 	 * boundary, so we must be careful.
1529 	 */
1530 	if ((s32)reg->u32_max_value >= 0) {
1531 		/* Positive.  We can't learn anything from the smin, but smax
1532 		 * is positive, hence safe.
1533 		 */
1534 		reg->s32_min_value = reg->u32_min_value;
1535 		reg->s32_max_value = reg->u32_max_value =
1536 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1537 	} else if ((s32)reg->u32_min_value < 0) {
1538 		/* Negative.  We can't learn anything from the smax, but smin
1539 		 * is negative, hence safe.
1540 		 */
1541 		reg->s32_min_value = reg->u32_min_value =
1542 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1543 		reg->s32_max_value = reg->u32_max_value;
1544 	}
1545 }
1546 
__reg64_deduce_bounds(struct bpf_reg_state * reg)1547 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1548 {
1549 	/* Learn sign from signed bounds.
1550 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1551 	 * are the same, so combine.  This works even in the negative case, e.g.
1552 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1553 	 */
1554 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1555 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1556 							  reg->umin_value);
1557 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1558 							  reg->umax_value);
1559 		return;
1560 	}
1561 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1562 	 * boundary, so we must be careful.
1563 	 */
1564 	if ((s64)reg->umax_value >= 0) {
1565 		/* Positive.  We can't learn anything from the smin, but smax
1566 		 * is positive, hence safe.
1567 		 */
1568 		reg->smin_value = reg->umin_value;
1569 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1570 							  reg->umax_value);
1571 	} else if ((s64)reg->umin_value < 0) {
1572 		/* Negative.  We can't learn anything from the smax, but smin
1573 		 * is negative, hence safe.
1574 		 */
1575 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1576 							  reg->umin_value);
1577 		reg->smax_value = reg->umax_value;
1578 	}
1579 }
1580 
__reg_deduce_bounds(struct bpf_reg_state * reg)1581 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1582 {
1583 	__reg32_deduce_bounds(reg);
1584 	__reg64_deduce_bounds(reg);
1585 }
1586 
1587 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1588 static void __reg_bound_offset(struct bpf_reg_state *reg)
1589 {
1590 	struct tnum var64_off = tnum_intersect(reg->var_off,
1591 					       tnum_range(reg->umin_value,
1592 							  reg->umax_value));
1593 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1594 						tnum_range(reg->u32_min_value,
1595 							   reg->u32_max_value));
1596 
1597 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1598 }
1599 
reg_bounds_sync(struct bpf_reg_state * reg)1600 static void reg_bounds_sync(struct bpf_reg_state *reg)
1601 {
1602 	/* We might have learned new bounds from the var_off. */
1603 	__update_reg_bounds(reg);
1604 	/* We might have learned something about the sign bit. */
1605 	__reg_deduce_bounds(reg);
1606 	/* We might have learned some bits from the bounds. */
1607 	__reg_bound_offset(reg);
1608 	/* Intersecting with the old var_off might have improved our bounds
1609 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1610 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1611 	 */
1612 	__update_reg_bounds(reg);
1613 }
1614 
__reg32_bound_s64(s32 a)1615 static bool __reg32_bound_s64(s32 a)
1616 {
1617 	return a >= 0 && a <= S32_MAX;
1618 }
1619 
__reg_assign_32_into_64(struct bpf_reg_state * reg)1620 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1621 {
1622 	reg->umin_value = reg->u32_min_value;
1623 	reg->umax_value = reg->u32_max_value;
1624 
1625 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1626 	 * be positive otherwise set to worse case bounds and refine later
1627 	 * from tnum.
1628 	 */
1629 	if (__reg32_bound_s64(reg->s32_min_value) &&
1630 	    __reg32_bound_s64(reg->s32_max_value)) {
1631 		reg->smin_value = reg->s32_min_value;
1632 		reg->smax_value = reg->s32_max_value;
1633 	} else {
1634 		reg->smin_value = 0;
1635 		reg->smax_value = U32_MAX;
1636 	}
1637 }
1638 
__reg_combine_32_into_64(struct bpf_reg_state * reg)1639 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1640 {
1641 	/* special case when 64-bit register has upper 32-bit register
1642 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1643 	 * allowing us to use 32-bit bounds directly,
1644 	 */
1645 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1646 		__reg_assign_32_into_64(reg);
1647 	} else {
1648 		/* Otherwise the best we can do is push lower 32bit known and
1649 		 * unknown bits into register (var_off set from jmp logic)
1650 		 * then learn as much as possible from the 64-bit tnum
1651 		 * known and unknown bits. The previous smin/smax bounds are
1652 		 * invalid here because of jmp32 compare so mark them unknown
1653 		 * so they do not impact tnum bounds calculation.
1654 		 */
1655 		__mark_reg64_unbounded(reg);
1656 	}
1657 	reg_bounds_sync(reg);
1658 }
1659 
__reg64_bound_s32(s64 a)1660 static bool __reg64_bound_s32(s64 a)
1661 {
1662 	return a >= S32_MIN && a <= S32_MAX;
1663 }
1664 
__reg64_bound_u32(u64 a)1665 static bool __reg64_bound_u32(u64 a)
1666 {
1667 	return a >= U32_MIN && a <= U32_MAX;
1668 }
1669 
__reg_combine_64_into_32(struct bpf_reg_state * reg)1670 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1671 {
1672 	__mark_reg32_unbounded(reg);
1673 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1674 		reg->s32_min_value = (s32)reg->smin_value;
1675 		reg->s32_max_value = (s32)reg->smax_value;
1676 	}
1677 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1678 		reg->u32_min_value = (u32)reg->umin_value;
1679 		reg->u32_max_value = (u32)reg->umax_value;
1680 	}
1681 	reg_bounds_sync(reg);
1682 }
1683 
1684 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1685 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1686 			       struct bpf_reg_state *reg)
1687 {
1688 	/*
1689 	 * Clear type, id, off, and union(map_ptr, range) and
1690 	 * padding between 'type' and union
1691 	 */
1692 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1693 	reg->type = SCALAR_VALUE;
1694 	reg->var_off = tnum_unknown;
1695 	reg->frameno = 0;
1696 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1697 	__mark_reg_unbounded(reg);
1698 }
1699 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1700 static void mark_reg_unknown(struct bpf_verifier_env *env,
1701 			     struct bpf_reg_state *regs, u32 regno)
1702 {
1703 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1704 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1705 		/* Something bad happened, let's kill all regs except FP */
1706 		for (regno = 0; regno < BPF_REG_FP; regno++)
1707 			__mark_reg_not_init(env, regs + regno);
1708 		return;
1709 	}
1710 	__mark_reg_unknown(env, regs + regno);
1711 }
1712 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1713 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1714 				struct bpf_reg_state *reg)
1715 {
1716 	__mark_reg_unknown(env, reg);
1717 	reg->type = NOT_INIT;
1718 }
1719 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1720 static void mark_reg_not_init(struct bpf_verifier_env *env,
1721 			      struct bpf_reg_state *regs, u32 regno)
1722 {
1723 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1724 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1725 		/* Something bad happened, let's kill all regs except FP */
1726 		for (regno = 0; regno < BPF_REG_FP; regno++)
1727 			__mark_reg_not_init(env, regs + regno);
1728 		return;
1729 	}
1730 	__mark_reg_not_init(env, regs + regno);
1731 }
1732 
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)1733 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1734 			    struct bpf_reg_state *regs, u32 regno,
1735 			    enum bpf_reg_type reg_type,
1736 			    struct btf *btf, u32 btf_id,
1737 			    enum bpf_type_flag flag)
1738 {
1739 	if (reg_type == SCALAR_VALUE) {
1740 		mark_reg_unknown(env, regs, regno);
1741 		return;
1742 	}
1743 	mark_reg_known_zero(env, regs, regno);
1744 	regs[regno].type = PTR_TO_BTF_ID | flag;
1745 	regs[regno].btf = btf;
1746 	regs[regno].btf_id = btf_id;
1747 }
1748 
1749 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1750 static void init_reg_state(struct bpf_verifier_env *env,
1751 			   struct bpf_func_state *state)
1752 {
1753 	struct bpf_reg_state *regs = state->regs;
1754 	int i;
1755 
1756 	for (i = 0; i < MAX_BPF_REG; i++) {
1757 		mark_reg_not_init(env, regs, i);
1758 		regs[i].live = REG_LIVE_NONE;
1759 		regs[i].parent = NULL;
1760 		regs[i].subreg_def = DEF_NOT_SUBREG;
1761 	}
1762 
1763 	/* frame pointer */
1764 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1765 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1766 	regs[BPF_REG_FP].frameno = state->frameno;
1767 }
1768 
1769 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1770 static void init_func_state(struct bpf_verifier_env *env,
1771 			    struct bpf_func_state *state,
1772 			    int callsite, int frameno, int subprogno)
1773 {
1774 	state->callsite = callsite;
1775 	state->frameno = frameno;
1776 	state->subprogno = subprogno;
1777 	state->callback_ret_range = tnum_range(0, 0);
1778 	init_reg_state(env, state);
1779 	mark_verifier_state_scratched(env);
1780 }
1781 
1782 /* 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)1783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1784 						int insn_idx, int prev_insn_idx,
1785 						int subprog)
1786 {
1787 	struct bpf_verifier_stack_elem *elem;
1788 	struct bpf_func_state *frame;
1789 
1790 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1791 	if (!elem)
1792 		goto err;
1793 
1794 	elem->insn_idx = insn_idx;
1795 	elem->prev_insn_idx = prev_insn_idx;
1796 	elem->next = env->head;
1797 	elem->log_pos = env->log.len_used;
1798 	env->head = elem;
1799 	env->stack_size++;
1800 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1801 		verbose(env,
1802 			"The sequence of %d jumps is too complex for async cb.\n",
1803 			env->stack_size);
1804 		goto err;
1805 	}
1806 	/* Unlike push_stack() do not copy_verifier_state().
1807 	 * The caller state doesn't matter.
1808 	 * This is async callback. It starts in a fresh stack.
1809 	 * Initialize it similar to do_check_common().
1810 	 */
1811 	elem->st.branches = 1;
1812 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1813 	if (!frame)
1814 		goto err;
1815 	init_func_state(env, frame,
1816 			BPF_MAIN_FUNC /* callsite */,
1817 			0 /* frameno within this callchain */,
1818 			subprog /* subprog number within this prog */);
1819 	elem->st.frame[0] = frame;
1820 	return &elem->st;
1821 err:
1822 	free_verifier_state(env->cur_state, true);
1823 	env->cur_state = NULL;
1824 	/* pop all elements and return */
1825 	while (!pop_stack(env, NULL, NULL, false));
1826 	return NULL;
1827 }
1828 
1829 
1830 enum reg_arg_type {
1831 	SRC_OP,		/* register is used as source operand */
1832 	DST_OP,		/* register is used as destination operand */
1833 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1834 };
1835 
cmp_subprogs(const void * a,const void * b)1836 static int cmp_subprogs(const void *a, const void *b)
1837 {
1838 	return ((struct bpf_subprog_info *)a)->start -
1839 	       ((struct bpf_subprog_info *)b)->start;
1840 }
1841 
find_subprog(struct bpf_verifier_env * env,int off)1842 static int find_subprog(struct bpf_verifier_env *env, int off)
1843 {
1844 	struct bpf_subprog_info *p;
1845 
1846 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1847 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1848 	if (!p)
1849 		return -ENOENT;
1850 	return p - env->subprog_info;
1851 
1852 }
1853 
add_subprog(struct bpf_verifier_env * env,int off)1854 static int add_subprog(struct bpf_verifier_env *env, int off)
1855 {
1856 	int insn_cnt = env->prog->len;
1857 	int ret;
1858 
1859 	if (off >= insn_cnt || off < 0) {
1860 		verbose(env, "call to invalid destination\n");
1861 		return -EINVAL;
1862 	}
1863 	ret = find_subprog(env, off);
1864 	if (ret >= 0)
1865 		return ret;
1866 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1867 		verbose(env, "too many subprograms\n");
1868 		return -E2BIG;
1869 	}
1870 	/* determine subprog starts. The end is one before the next starts */
1871 	env->subprog_info[env->subprog_cnt++].start = off;
1872 	sort(env->subprog_info, env->subprog_cnt,
1873 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1874 	return env->subprog_cnt - 1;
1875 }
1876 
1877 #define MAX_KFUNC_DESCS 256
1878 #define MAX_KFUNC_BTFS	256
1879 
1880 struct bpf_kfunc_desc {
1881 	struct btf_func_model func_model;
1882 	u32 func_id;
1883 	s32 imm;
1884 	u16 offset;
1885 };
1886 
1887 struct bpf_kfunc_btf {
1888 	struct btf *btf;
1889 	struct module *module;
1890 	u16 offset;
1891 };
1892 
1893 struct bpf_kfunc_desc_tab {
1894 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1895 	u32 nr_descs;
1896 };
1897 
1898 struct bpf_kfunc_btf_tab {
1899 	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1900 	u32 nr_descs;
1901 };
1902 
kfunc_desc_cmp_by_id_off(const void * a,const void * b)1903 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1904 {
1905 	const struct bpf_kfunc_desc *d0 = a;
1906 	const struct bpf_kfunc_desc *d1 = b;
1907 
1908 	/* func_id is not greater than BTF_MAX_TYPE */
1909 	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1910 }
1911 
kfunc_btf_cmp_by_off(const void * a,const void * b)1912 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1913 {
1914 	const struct bpf_kfunc_btf *d0 = a;
1915 	const struct bpf_kfunc_btf *d1 = b;
1916 
1917 	return d0->offset - d1->offset;
1918 }
1919 
1920 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)1921 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1922 {
1923 	struct bpf_kfunc_desc desc = {
1924 		.func_id = func_id,
1925 		.offset = offset,
1926 	};
1927 	struct bpf_kfunc_desc_tab *tab;
1928 
1929 	tab = prog->aux->kfunc_tab;
1930 	return bsearch(&desc, tab->descs, tab->nr_descs,
1931 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1932 }
1933 
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)1934 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1935 					 s16 offset)
1936 {
1937 	struct bpf_kfunc_btf kf_btf = { .offset = offset };
1938 	struct bpf_kfunc_btf_tab *tab;
1939 	struct bpf_kfunc_btf *b;
1940 	struct module *mod;
1941 	struct btf *btf;
1942 	int btf_fd;
1943 
1944 	tab = env->prog->aux->kfunc_btf_tab;
1945 	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1946 		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1947 	if (!b) {
1948 		if (tab->nr_descs == MAX_KFUNC_BTFS) {
1949 			verbose(env, "too many different module BTFs\n");
1950 			return ERR_PTR(-E2BIG);
1951 		}
1952 
1953 		if (bpfptr_is_null(env->fd_array)) {
1954 			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1955 			return ERR_PTR(-EPROTO);
1956 		}
1957 
1958 		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1959 					    offset * sizeof(btf_fd),
1960 					    sizeof(btf_fd)))
1961 			return ERR_PTR(-EFAULT);
1962 
1963 		btf = btf_get_by_fd(btf_fd);
1964 		if (IS_ERR(btf)) {
1965 			verbose(env, "invalid module BTF fd specified\n");
1966 			return btf;
1967 		}
1968 
1969 		if (!btf_is_module(btf)) {
1970 			verbose(env, "BTF fd for kfunc is not a module BTF\n");
1971 			btf_put(btf);
1972 			return ERR_PTR(-EINVAL);
1973 		}
1974 
1975 		mod = btf_try_get_module(btf);
1976 		if (!mod) {
1977 			btf_put(btf);
1978 			return ERR_PTR(-ENXIO);
1979 		}
1980 
1981 		b = &tab->descs[tab->nr_descs++];
1982 		b->btf = btf;
1983 		b->module = mod;
1984 		b->offset = offset;
1985 
1986 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1987 		     kfunc_btf_cmp_by_off, NULL);
1988 	}
1989 	return b->btf;
1990 }
1991 
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)1992 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1993 {
1994 	if (!tab)
1995 		return;
1996 
1997 	while (tab->nr_descs--) {
1998 		module_put(tab->descs[tab->nr_descs].module);
1999 		btf_put(tab->descs[tab->nr_descs].btf);
2000 	}
2001 	kfree(tab);
2002 }
2003 
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2004 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2005 {
2006 	if (offset) {
2007 		if (offset < 0) {
2008 			/* In the future, this can be allowed to increase limit
2009 			 * of fd index into fd_array, interpreted as u16.
2010 			 */
2011 			verbose(env, "negative offset disallowed for kernel module function call\n");
2012 			return ERR_PTR(-EINVAL);
2013 		}
2014 
2015 		return __find_kfunc_desc_btf(env, offset);
2016 	}
2017 	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2018 }
2019 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)2020 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2021 {
2022 	const struct btf_type *func, *func_proto;
2023 	struct bpf_kfunc_btf_tab *btf_tab;
2024 	struct bpf_kfunc_desc_tab *tab;
2025 	struct bpf_prog_aux *prog_aux;
2026 	struct bpf_kfunc_desc *desc;
2027 	const char *func_name;
2028 	struct btf *desc_btf;
2029 	unsigned long call_imm;
2030 	unsigned long addr;
2031 	int err;
2032 
2033 	prog_aux = env->prog->aux;
2034 	tab = prog_aux->kfunc_tab;
2035 	btf_tab = prog_aux->kfunc_btf_tab;
2036 	if (!tab) {
2037 		if (!btf_vmlinux) {
2038 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2039 			return -ENOTSUPP;
2040 		}
2041 
2042 		if (!env->prog->jit_requested) {
2043 			verbose(env, "JIT is required for calling kernel function\n");
2044 			return -ENOTSUPP;
2045 		}
2046 
2047 		if (!bpf_jit_supports_kfunc_call()) {
2048 			verbose(env, "JIT does not support calling kernel function\n");
2049 			return -ENOTSUPP;
2050 		}
2051 
2052 		if (!env->prog->gpl_compatible) {
2053 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2054 			return -EINVAL;
2055 		}
2056 
2057 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2058 		if (!tab)
2059 			return -ENOMEM;
2060 		prog_aux->kfunc_tab = tab;
2061 	}
2062 
2063 	/* func_id == 0 is always invalid, but instead of returning an error, be
2064 	 * conservative and wait until the code elimination pass before returning
2065 	 * error, so that invalid calls that get pruned out can be in BPF programs
2066 	 * loaded from userspace.  It is also required that offset be untouched
2067 	 * for such calls.
2068 	 */
2069 	if (!func_id && !offset)
2070 		return 0;
2071 
2072 	if (!btf_tab && offset) {
2073 		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2074 		if (!btf_tab)
2075 			return -ENOMEM;
2076 		prog_aux->kfunc_btf_tab = btf_tab;
2077 	}
2078 
2079 	desc_btf = find_kfunc_desc_btf(env, offset);
2080 	if (IS_ERR(desc_btf)) {
2081 		verbose(env, "failed to find BTF for kernel function\n");
2082 		return PTR_ERR(desc_btf);
2083 	}
2084 
2085 	if (find_kfunc_desc(env->prog, func_id, offset))
2086 		return 0;
2087 
2088 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2089 		verbose(env, "too many different kernel function calls\n");
2090 		return -E2BIG;
2091 	}
2092 
2093 	func = btf_type_by_id(desc_btf, func_id);
2094 	if (!func || !btf_type_is_func(func)) {
2095 		verbose(env, "kernel btf_id %u is not a function\n",
2096 			func_id);
2097 		return -EINVAL;
2098 	}
2099 	func_proto = btf_type_by_id(desc_btf, func->type);
2100 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2101 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2102 			func_id);
2103 		return -EINVAL;
2104 	}
2105 
2106 	func_name = btf_name_by_offset(desc_btf, func->name_off);
2107 	addr = kallsyms_lookup_name(func_name);
2108 	if (!addr) {
2109 		verbose(env, "cannot find address for kernel function %s\n",
2110 			func_name);
2111 		return -EINVAL;
2112 	}
2113 
2114 	call_imm = BPF_CALL_IMM(addr);
2115 	/* Check whether or not the relative offset overflows desc->imm */
2116 	if ((unsigned long)(s32)call_imm != call_imm) {
2117 		verbose(env, "address of kernel function %s is out of range\n",
2118 			func_name);
2119 		return -EINVAL;
2120 	}
2121 
2122 	desc = &tab->descs[tab->nr_descs++];
2123 	desc->func_id = func_id;
2124 	desc->imm = call_imm;
2125 	desc->offset = offset;
2126 	err = btf_distill_func_proto(&env->log, desc_btf,
2127 				     func_proto, func_name,
2128 				     &desc->func_model);
2129 	if (!err)
2130 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2131 		     kfunc_desc_cmp_by_id_off, NULL);
2132 	return err;
2133 }
2134 
kfunc_desc_cmp_by_imm(const void * a,const void * b)2135 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2136 {
2137 	const struct bpf_kfunc_desc *d0 = a;
2138 	const struct bpf_kfunc_desc *d1 = b;
2139 
2140 	if (d0->imm > d1->imm)
2141 		return 1;
2142 	else if (d0->imm < d1->imm)
2143 		return -1;
2144 	return 0;
2145 }
2146 
sort_kfunc_descs_by_imm(struct bpf_prog * prog)2147 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2148 {
2149 	struct bpf_kfunc_desc_tab *tab;
2150 
2151 	tab = prog->aux->kfunc_tab;
2152 	if (!tab)
2153 		return;
2154 
2155 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2156 	     kfunc_desc_cmp_by_imm, NULL);
2157 }
2158 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)2159 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2160 {
2161 	return !!prog->aux->kfunc_tab;
2162 }
2163 
2164 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)2165 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2166 			 const struct bpf_insn *insn)
2167 {
2168 	const struct bpf_kfunc_desc desc = {
2169 		.imm = insn->imm,
2170 	};
2171 	const struct bpf_kfunc_desc *res;
2172 	struct bpf_kfunc_desc_tab *tab;
2173 
2174 	tab = prog->aux->kfunc_tab;
2175 	res = bsearch(&desc, tab->descs, tab->nr_descs,
2176 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2177 
2178 	return res ? &res->func_model : NULL;
2179 }
2180 
add_subprog_and_kfunc(struct bpf_verifier_env * env)2181 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2182 {
2183 	struct bpf_subprog_info *subprog = env->subprog_info;
2184 	struct bpf_insn *insn = env->prog->insnsi;
2185 	int i, ret, insn_cnt = env->prog->len;
2186 
2187 	/* Add entry function. */
2188 	ret = add_subprog(env, 0);
2189 	if (ret)
2190 		return ret;
2191 
2192 	for (i = 0; i < insn_cnt; i++, insn++) {
2193 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2194 		    !bpf_pseudo_kfunc_call(insn))
2195 			continue;
2196 
2197 		if (!env->bpf_capable) {
2198 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2199 			return -EPERM;
2200 		}
2201 
2202 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2203 			ret = add_subprog(env, i + insn->imm + 1);
2204 		else
2205 			ret = add_kfunc_call(env, insn->imm, insn->off);
2206 
2207 		if (ret < 0)
2208 			return ret;
2209 	}
2210 
2211 	/* Add a fake 'exit' subprog which could simplify subprog iteration
2212 	 * logic. 'subprog_cnt' should not be increased.
2213 	 */
2214 	subprog[env->subprog_cnt].start = insn_cnt;
2215 
2216 	if (env->log.level & BPF_LOG_LEVEL2)
2217 		for (i = 0; i < env->subprog_cnt; i++)
2218 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
2219 
2220 	return 0;
2221 }
2222 
check_subprogs(struct bpf_verifier_env * env)2223 static int check_subprogs(struct bpf_verifier_env *env)
2224 {
2225 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
2226 	struct bpf_subprog_info *subprog = env->subprog_info;
2227 	struct bpf_insn *insn = env->prog->insnsi;
2228 	int insn_cnt = env->prog->len;
2229 
2230 	/* now check that all jumps are within the same subprog */
2231 	subprog_start = subprog[cur_subprog].start;
2232 	subprog_end = subprog[cur_subprog + 1].start;
2233 	for (i = 0; i < insn_cnt; i++) {
2234 		u8 code = insn[i].code;
2235 
2236 		if (code == (BPF_JMP | BPF_CALL) &&
2237 		    insn[i].imm == BPF_FUNC_tail_call &&
2238 		    insn[i].src_reg != BPF_PSEUDO_CALL)
2239 			subprog[cur_subprog].has_tail_call = true;
2240 		if (BPF_CLASS(code) == BPF_LD &&
2241 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2242 			subprog[cur_subprog].has_ld_abs = true;
2243 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2244 			goto next;
2245 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2246 			goto next;
2247 		off = i + insn[i].off + 1;
2248 		if (off < subprog_start || off >= subprog_end) {
2249 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
2250 			return -EINVAL;
2251 		}
2252 next:
2253 		if (i == subprog_end - 1) {
2254 			/* to avoid fall-through from one subprog into another
2255 			 * the last insn of the subprog should be either exit
2256 			 * or unconditional jump back
2257 			 */
2258 			if (code != (BPF_JMP | BPF_EXIT) &&
2259 			    code != (BPF_JMP | BPF_JA)) {
2260 				verbose(env, "last insn is not an exit or jmp\n");
2261 				return -EINVAL;
2262 			}
2263 			subprog_start = subprog_end;
2264 			cur_subprog++;
2265 			if (cur_subprog < env->subprog_cnt)
2266 				subprog_end = subprog[cur_subprog + 1].start;
2267 		}
2268 	}
2269 	return 0;
2270 }
2271 
2272 /* Parentage chain of this register (or stack slot) should take care of all
2273  * issues like callee-saved registers, stack slot allocation time, etc.
2274  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)2275 static int mark_reg_read(struct bpf_verifier_env *env,
2276 			 const struct bpf_reg_state *state,
2277 			 struct bpf_reg_state *parent, u8 flag)
2278 {
2279 	bool writes = parent == state->parent; /* Observe write marks */
2280 	int cnt = 0;
2281 
2282 	while (parent) {
2283 		/* if read wasn't screened by an earlier write ... */
2284 		if (writes && state->live & REG_LIVE_WRITTEN)
2285 			break;
2286 		if (parent->live & REG_LIVE_DONE) {
2287 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2288 				reg_type_str(env, parent->type),
2289 				parent->var_off.value, parent->off);
2290 			return -EFAULT;
2291 		}
2292 		/* The first condition is more likely to be true than the
2293 		 * second, checked it first.
2294 		 */
2295 		if ((parent->live & REG_LIVE_READ) == flag ||
2296 		    parent->live & REG_LIVE_READ64)
2297 			/* The parentage chain never changes and
2298 			 * this parent was already marked as LIVE_READ.
2299 			 * There is no need to keep walking the chain again and
2300 			 * keep re-marking all parents as LIVE_READ.
2301 			 * This case happens when the same register is read
2302 			 * multiple times without writes into it in-between.
2303 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
2304 			 * then no need to set the weak REG_LIVE_READ32.
2305 			 */
2306 			break;
2307 		/* ... then we depend on parent's value */
2308 		parent->live |= flag;
2309 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2310 		if (flag == REG_LIVE_READ64)
2311 			parent->live &= ~REG_LIVE_READ32;
2312 		state = parent;
2313 		parent = state->parent;
2314 		writes = true;
2315 		cnt++;
2316 	}
2317 
2318 	if (env->longest_mark_read_walk < cnt)
2319 		env->longest_mark_read_walk = cnt;
2320 	return 0;
2321 }
2322 
2323 /* This function is supposed to be used by the following 32-bit optimization
2324  * code only. It returns TRUE if the source or destination register operates
2325  * on 64-bit, otherwise return FALSE.
2326  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)2327 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2328 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2329 {
2330 	u8 code, class, op;
2331 
2332 	code = insn->code;
2333 	class = BPF_CLASS(code);
2334 	op = BPF_OP(code);
2335 	if (class == BPF_JMP) {
2336 		/* BPF_EXIT for "main" will reach here. Return TRUE
2337 		 * conservatively.
2338 		 */
2339 		if (op == BPF_EXIT)
2340 			return true;
2341 		if (op == BPF_CALL) {
2342 			/* BPF to BPF call will reach here because of marking
2343 			 * caller saved clobber with DST_OP_NO_MARK for which we
2344 			 * don't care the register def because they are anyway
2345 			 * marked as NOT_INIT already.
2346 			 */
2347 			if (insn->src_reg == BPF_PSEUDO_CALL)
2348 				return false;
2349 			/* Helper call will reach here because of arg type
2350 			 * check, conservatively return TRUE.
2351 			 */
2352 			if (t == SRC_OP)
2353 				return true;
2354 
2355 			return false;
2356 		}
2357 	}
2358 
2359 	if (class == BPF_ALU64 || class == BPF_JMP ||
2360 	    /* BPF_END always use BPF_ALU class. */
2361 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2362 		return true;
2363 
2364 	if (class == BPF_ALU || class == BPF_JMP32)
2365 		return false;
2366 
2367 	if (class == BPF_LDX) {
2368 		if (t != SRC_OP)
2369 			return BPF_SIZE(code) == BPF_DW;
2370 		/* LDX source must be ptr. */
2371 		return true;
2372 	}
2373 
2374 	if (class == BPF_STX) {
2375 		/* BPF_STX (including atomic variants) has multiple source
2376 		 * operands, one of which is a ptr. Check whether the caller is
2377 		 * asking about it.
2378 		 */
2379 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
2380 			return true;
2381 		return BPF_SIZE(code) == BPF_DW;
2382 	}
2383 
2384 	if (class == BPF_LD) {
2385 		u8 mode = BPF_MODE(code);
2386 
2387 		/* LD_IMM64 */
2388 		if (mode == BPF_IMM)
2389 			return true;
2390 
2391 		/* Both LD_IND and LD_ABS return 32-bit data. */
2392 		if (t != SRC_OP)
2393 			return  false;
2394 
2395 		/* Implicit ctx ptr. */
2396 		if (regno == BPF_REG_6)
2397 			return true;
2398 
2399 		/* Explicit source could be any width. */
2400 		return true;
2401 	}
2402 
2403 	if (class == BPF_ST)
2404 		/* The only source register for BPF_ST is a ptr. */
2405 		return true;
2406 
2407 	/* Conservatively return true at default. */
2408 	return true;
2409 }
2410 
2411 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)2412 static int insn_def_regno(const struct bpf_insn *insn)
2413 {
2414 	switch (BPF_CLASS(insn->code)) {
2415 	case BPF_JMP:
2416 	case BPF_JMP32:
2417 	case BPF_ST:
2418 		return -1;
2419 	case BPF_STX:
2420 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2421 		    (insn->imm & BPF_FETCH)) {
2422 			if (insn->imm == BPF_CMPXCHG)
2423 				return BPF_REG_0;
2424 			else
2425 				return insn->src_reg;
2426 		} else {
2427 			return -1;
2428 		}
2429 	default:
2430 		return insn->dst_reg;
2431 	}
2432 }
2433 
2434 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)2435 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2436 {
2437 	int dst_reg = insn_def_regno(insn);
2438 
2439 	if (dst_reg == -1)
2440 		return false;
2441 
2442 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2443 }
2444 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)2445 static void mark_insn_zext(struct bpf_verifier_env *env,
2446 			   struct bpf_reg_state *reg)
2447 {
2448 	s32 def_idx = reg->subreg_def;
2449 
2450 	if (def_idx == DEF_NOT_SUBREG)
2451 		return;
2452 
2453 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2454 	/* The dst will be zero extended, so won't be sub-register anymore. */
2455 	reg->subreg_def = DEF_NOT_SUBREG;
2456 }
2457 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)2458 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2459 			 enum reg_arg_type t)
2460 {
2461 	struct bpf_verifier_state *vstate = env->cur_state;
2462 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2463 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2464 	struct bpf_reg_state *reg, *regs = state->regs;
2465 	bool rw64;
2466 
2467 	if (regno >= MAX_BPF_REG) {
2468 		verbose(env, "R%d is invalid\n", regno);
2469 		return -EINVAL;
2470 	}
2471 
2472 	mark_reg_scratched(env, regno);
2473 
2474 	reg = &regs[regno];
2475 	rw64 = is_reg64(env, insn, regno, reg, t);
2476 	if (t == SRC_OP) {
2477 		/* check whether register used as source operand can be read */
2478 		if (reg->type == NOT_INIT) {
2479 			verbose(env, "R%d !read_ok\n", regno);
2480 			return -EACCES;
2481 		}
2482 		/* We don't need to worry about FP liveness because it's read-only */
2483 		if (regno == BPF_REG_FP)
2484 			return 0;
2485 
2486 		if (rw64)
2487 			mark_insn_zext(env, reg);
2488 
2489 		return mark_reg_read(env, reg, reg->parent,
2490 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2491 	} else {
2492 		/* check whether register used as dest operand can be written to */
2493 		if (regno == BPF_REG_FP) {
2494 			verbose(env, "frame pointer is read only\n");
2495 			return -EACCES;
2496 		}
2497 		reg->live |= REG_LIVE_WRITTEN;
2498 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2499 		if (t == DST_OP)
2500 			mark_reg_unknown(env, regs, regno);
2501 	}
2502 	return 0;
2503 }
2504 
2505 /* 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)2506 static int push_jmp_history(struct bpf_verifier_env *env,
2507 			    struct bpf_verifier_state *cur)
2508 {
2509 	u32 cnt = cur->jmp_history_cnt;
2510 	struct bpf_idx_pair *p;
2511 	size_t alloc_size;
2512 
2513 	cnt++;
2514 	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2515 	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2516 	if (!p)
2517 		return -ENOMEM;
2518 	p[cnt - 1].idx = env->insn_idx;
2519 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2520 	cur->jmp_history = p;
2521 	cur->jmp_history_cnt = cnt;
2522 	return 0;
2523 }
2524 
2525 /* Backtrack one insn at a time. If idx is not at the top of recorded
2526  * history then previous instruction came from straight line execution.
2527  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)2528 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2529 			     u32 *history)
2530 {
2531 	u32 cnt = *history;
2532 
2533 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2534 		i = st->jmp_history[cnt - 1].prev_idx;
2535 		(*history)--;
2536 	} else {
2537 		i--;
2538 	}
2539 	return i;
2540 }
2541 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)2542 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2543 {
2544 	const struct btf_type *func;
2545 	struct btf *desc_btf;
2546 
2547 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2548 		return NULL;
2549 
2550 	desc_btf = find_kfunc_desc_btf(data, insn->off);
2551 	if (IS_ERR(desc_btf))
2552 		return "<error>";
2553 
2554 	func = btf_type_by_id(desc_btf, insn->imm);
2555 	return btf_name_by_offset(desc_btf, func->name_off);
2556 }
2557 
2558 /* For given verifier state backtrack_insn() is called from the last insn to
2559  * the first insn. Its purpose is to compute a bitmask of registers and
2560  * stack slots that needs precision in the parent verifier state.
2561  */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)2562 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2563 			  u32 *reg_mask, u64 *stack_mask)
2564 {
2565 	const struct bpf_insn_cbs cbs = {
2566 		.cb_call	= disasm_kfunc_name,
2567 		.cb_print	= verbose,
2568 		.private_data	= env,
2569 	};
2570 	struct bpf_insn *insn = env->prog->insnsi + idx;
2571 	u8 class = BPF_CLASS(insn->code);
2572 	u8 opcode = BPF_OP(insn->code);
2573 	u8 mode = BPF_MODE(insn->code);
2574 	u32 dreg = 1u << insn->dst_reg;
2575 	u32 sreg = 1u << insn->src_reg;
2576 	u32 spi;
2577 
2578 	if (insn->code == 0)
2579 		return 0;
2580 	if (env->log.level & BPF_LOG_LEVEL2) {
2581 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2582 		verbose(env, "%d: ", idx);
2583 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2584 	}
2585 
2586 	if (class == BPF_ALU || class == BPF_ALU64) {
2587 		if (!(*reg_mask & dreg))
2588 			return 0;
2589 		if (opcode == BPF_MOV) {
2590 			if (BPF_SRC(insn->code) == BPF_X) {
2591 				/* dreg = sreg
2592 				 * dreg needs precision after this insn
2593 				 * sreg needs precision before this insn
2594 				 */
2595 				*reg_mask &= ~dreg;
2596 				*reg_mask |= sreg;
2597 			} else {
2598 				/* dreg = K
2599 				 * dreg needs precision after this insn.
2600 				 * Corresponding register is already marked
2601 				 * as precise=true in this verifier state.
2602 				 * No further markings in parent are necessary
2603 				 */
2604 				*reg_mask &= ~dreg;
2605 			}
2606 		} else {
2607 			if (BPF_SRC(insn->code) == BPF_X) {
2608 				/* dreg += sreg
2609 				 * both dreg and sreg need precision
2610 				 * before this insn
2611 				 */
2612 				*reg_mask |= sreg;
2613 			} /* else dreg += K
2614 			   * dreg still needs precision before this insn
2615 			   */
2616 		}
2617 	} else if (class == BPF_LDX) {
2618 		if (!(*reg_mask & dreg))
2619 			return 0;
2620 		*reg_mask &= ~dreg;
2621 
2622 		/* scalars can only be spilled into stack w/o losing precision.
2623 		 * Load from any other memory can be zero extended.
2624 		 * The desire to keep that precision is already indicated
2625 		 * by 'precise' mark in corresponding register of this state.
2626 		 * No further tracking necessary.
2627 		 */
2628 		if (insn->src_reg != BPF_REG_FP)
2629 			return 0;
2630 
2631 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2632 		 * that [fp - off] slot contains scalar that needs to be
2633 		 * tracked with precision
2634 		 */
2635 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2636 		if (spi >= 64) {
2637 			verbose(env, "BUG spi %d\n", spi);
2638 			WARN_ONCE(1, "verifier backtracking bug");
2639 			return -EFAULT;
2640 		}
2641 		*stack_mask |= 1ull << spi;
2642 	} else if (class == BPF_STX || class == BPF_ST) {
2643 		if (*reg_mask & dreg)
2644 			/* stx & st shouldn't be using _scalar_ dst_reg
2645 			 * to access memory. It means backtracking
2646 			 * encountered a case of pointer subtraction.
2647 			 */
2648 			return -ENOTSUPP;
2649 		/* scalars can only be spilled into stack */
2650 		if (insn->dst_reg != BPF_REG_FP)
2651 			return 0;
2652 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2653 		if (spi >= 64) {
2654 			verbose(env, "BUG spi %d\n", spi);
2655 			WARN_ONCE(1, "verifier backtracking bug");
2656 			return -EFAULT;
2657 		}
2658 		if (!(*stack_mask & (1ull << spi)))
2659 			return 0;
2660 		*stack_mask &= ~(1ull << spi);
2661 		if (class == BPF_STX)
2662 			*reg_mask |= sreg;
2663 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2664 		if (opcode == BPF_CALL) {
2665 			if (insn->src_reg == BPF_PSEUDO_CALL)
2666 				return -ENOTSUPP;
2667 			/* regular helper call sets R0 */
2668 			*reg_mask &= ~1;
2669 			if (*reg_mask & 0x3f) {
2670 				/* if backtracing was looking for registers R1-R5
2671 				 * they should have been found already.
2672 				 */
2673 				verbose(env, "BUG regs %x\n", *reg_mask);
2674 				WARN_ONCE(1, "verifier backtracking bug");
2675 				return -EFAULT;
2676 			}
2677 		} else if (opcode == BPF_EXIT) {
2678 			return -ENOTSUPP;
2679 		}
2680 	} else if (class == BPF_LD) {
2681 		if (!(*reg_mask & dreg))
2682 			return 0;
2683 		*reg_mask &= ~dreg;
2684 		/* It's ld_imm64 or ld_abs or ld_ind.
2685 		 * For ld_imm64 no further tracking of precision
2686 		 * into parent is necessary
2687 		 */
2688 		if (mode == BPF_IND || mode == BPF_ABS)
2689 			/* to be analyzed */
2690 			return -ENOTSUPP;
2691 	}
2692 	return 0;
2693 }
2694 
2695 /* the scalar precision tracking algorithm:
2696  * . at the start all registers have precise=false.
2697  * . scalar ranges are tracked as normal through alu and jmp insns.
2698  * . once precise value of the scalar register is used in:
2699  *   .  ptr + scalar alu
2700  *   . if (scalar cond K|scalar)
2701  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2702  *   backtrack through the verifier states and mark all registers and
2703  *   stack slots with spilled constants that these scalar regisers
2704  *   should be precise.
2705  * . during state pruning two registers (or spilled stack slots)
2706  *   are equivalent if both are not precise.
2707  *
2708  * Note the verifier cannot simply walk register parentage chain,
2709  * since many different registers and stack slots could have been
2710  * used to compute single precise scalar.
2711  *
2712  * The approach of starting with precise=true for all registers and then
2713  * backtrack to mark a register as not precise when the verifier detects
2714  * that program doesn't care about specific value (e.g., when helper
2715  * takes register as ARG_ANYTHING parameter) is not safe.
2716  *
2717  * It's ok to walk single parentage chain of the verifier states.
2718  * It's possible that this backtracking will go all the way till 1st insn.
2719  * All other branches will be explored for needing precision later.
2720  *
2721  * The backtracking needs to deal with cases like:
2722  *   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)
2723  * r9 -= r8
2724  * r5 = r9
2725  * if r5 > 0x79f goto pc+7
2726  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2727  * r5 += 1
2728  * ...
2729  * call bpf_perf_event_output#25
2730  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2731  *
2732  * and this case:
2733  * r6 = 1
2734  * call foo // uses callee's r6 inside to compute r0
2735  * r0 += r6
2736  * if r0 == 0 goto
2737  *
2738  * to track above reg_mask/stack_mask needs to be independent for each frame.
2739  *
2740  * Also if parent's curframe > frame where backtracking started,
2741  * the verifier need to mark registers in both frames, otherwise callees
2742  * may incorrectly prune callers. This is similar to
2743  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2744  *
2745  * For now backtracking falls back into conservative marking.
2746  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2747 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2748 				     struct bpf_verifier_state *st)
2749 {
2750 	struct bpf_func_state *func;
2751 	struct bpf_reg_state *reg;
2752 	int i, j;
2753 
2754 	/* big hammer: mark all scalars precise in this path.
2755 	 * pop_stack may still get !precise scalars.
2756 	 */
2757 	for (; st; st = st->parent)
2758 		for (i = 0; i <= st->curframe; i++) {
2759 			func = st->frame[i];
2760 			for (j = 0; j < BPF_REG_FP; j++) {
2761 				reg = &func->regs[j];
2762 				if (reg->type != SCALAR_VALUE)
2763 					continue;
2764 				reg->precise = true;
2765 			}
2766 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2767 				if (!is_spilled_reg(&func->stack[j]))
2768 					continue;
2769 				reg = &func->stack[j].spilled_ptr;
2770 				if (reg->type != SCALAR_VALUE)
2771 					continue;
2772 				reg->precise = true;
2773 			}
2774 		}
2775 }
2776 
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2777 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2778 				  int spi)
2779 {
2780 	struct bpf_verifier_state *st = env->cur_state;
2781 	int first_idx = st->first_insn_idx;
2782 	int last_idx = env->insn_idx;
2783 	struct bpf_func_state *func;
2784 	struct bpf_reg_state *reg;
2785 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2786 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2787 	bool skip_first = true;
2788 	bool new_marks = false;
2789 	int i, err;
2790 
2791 	if (!env->bpf_capable)
2792 		return 0;
2793 
2794 	func = st->frame[frame];
2795 	if (regno >= 0) {
2796 		reg = &func->regs[regno];
2797 		if (reg->type != SCALAR_VALUE) {
2798 			WARN_ONCE(1, "backtracing misuse");
2799 			return -EFAULT;
2800 		}
2801 		if (!reg->precise)
2802 			new_marks = true;
2803 		else
2804 			reg_mask = 0;
2805 		reg->precise = true;
2806 	}
2807 
2808 	while (spi >= 0) {
2809 		if (!is_spilled_reg(&func->stack[spi])) {
2810 			stack_mask = 0;
2811 			break;
2812 		}
2813 		reg = &func->stack[spi].spilled_ptr;
2814 		if (reg->type != SCALAR_VALUE) {
2815 			stack_mask = 0;
2816 			break;
2817 		}
2818 		if (!reg->precise)
2819 			new_marks = true;
2820 		else
2821 			stack_mask = 0;
2822 		reg->precise = true;
2823 		break;
2824 	}
2825 
2826 	if (!new_marks)
2827 		return 0;
2828 	if (!reg_mask && !stack_mask)
2829 		return 0;
2830 	for (;;) {
2831 		DECLARE_BITMAP(mask, 64);
2832 		u32 history = st->jmp_history_cnt;
2833 
2834 		if (env->log.level & BPF_LOG_LEVEL2)
2835 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2836 		for (i = last_idx;;) {
2837 			if (skip_first) {
2838 				err = 0;
2839 				skip_first = false;
2840 			} else {
2841 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2842 			}
2843 			if (err == -ENOTSUPP) {
2844 				mark_all_scalars_precise(env, st);
2845 				return 0;
2846 			} else if (err) {
2847 				return err;
2848 			}
2849 			if (!reg_mask && !stack_mask)
2850 				/* Found assignment(s) into tracked register in this state.
2851 				 * Since this state is already marked, just return.
2852 				 * Nothing to be tracked further in the parent state.
2853 				 */
2854 				return 0;
2855 			if (i == first_idx)
2856 				break;
2857 			i = get_prev_insn_idx(st, i, &history);
2858 			if (i >= env->prog->len) {
2859 				/* This can happen if backtracking reached insn 0
2860 				 * and there are still reg_mask or stack_mask
2861 				 * to backtrack.
2862 				 * It means the backtracking missed the spot where
2863 				 * particular register was initialized with a constant.
2864 				 */
2865 				verbose(env, "BUG backtracking idx %d\n", i);
2866 				WARN_ONCE(1, "verifier backtracking bug");
2867 				return -EFAULT;
2868 			}
2869 		}
2870 		st = st->parent;
2871 		if (!st)
2872 			break;
2873 
2874 		new_marks = false;
2875 		func = st->frame[frame];
2876 		bitmap_from_u64(mask, reg_mask);
2877 		for_each_set_bit(i, mask, 32) {
2878 			reg = &func->regs[i];
2879 			if (reg->type != SCALAR_VALUE) {
2880 				reg_mask &= ~(1u << i);
2881 				continue;
2882 			}
2883 			if (!reg->precise)
2884 				new_marks = true;
2885 			reg->precise = true;
2886 		}
2887 
2888 		bitmap_from_u64(mask, stack_mask);
2889 		for_each_set_bit(i, mask, 64) {
2890 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2891 				/* the sequence of instructions:
2892 				 * 2: (bf) r3 = r10
2893 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2894 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2895 				 * doesn't contain jmps. It's backtracked
2896 				 * as a single block.
2897 				 * During backtracking insn 3 is not recognized as
2898 				 * stack access, so at the end of backtracking
2899 				 * stack slot fp-8 is still marked in stack_mask.
2900 				 * However the parent state may not have accessed
2901 				 * fp-8 and it's "unallocated" stack space.
2902 				 * In such case fallback to conservative.
2903 				 */
2904 				mark_all_scalars_precise(env, st);
2905 				return 0;
2906 			}
2907 
2908 			if (!is_spilled_reg(&func->stack[i])) {
2909 				stack_mask &= ~(1ull << i);
2910 				continue;
2911 			}
2912 			reg = &func->stack[i].spilled_ptr;
2913 			if (reg->type != SCALAR_VALUE) {
2914 				stack_mask &= ~(1ull << i);
2915 				continue;
2916 			}
2917 			if (!reg->precise)
2918 				new_marks = true;
2919 			reg->precise = true;
2920 		}
2921 		if (env->log.level & BPF_LOG_LEVEL2) {
2922 			verbose(env, "parent %s regs=%x stack=%llx marks:",
2923 				new_marks ? "didn't have" : "already had",
2924 				reg_mask, stack_mask);
2925 			print_verifier_state(env, func, true);
2926 		}
2927 
2928 		if (!reg_mask && !stack_mask)
2929 			break;
2930 		if (!new_marks)
2931 			break;
2932 
2933 		last_idx = st->last_insn_idx;
2934 		first_idx = st->first_insn_idx;
2935 	}
2936 	return 0;
2937 }
2938 
mark_chain_precision(struct bpf_verifier_env * env,int regno)2939 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2940 {
2941 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2942 }
2943 
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2944 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2945 {
2946 	return __mark_chain_precision(env, frame, regno, -1);
2947 }
2948 
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2949 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2950 {
2951 	return __mark_chain_precision(env, frame, -1, spi);
2952 }
2953 
is_spillable_regtype(enum bpf_reg_type type)2954 static bool is_spillable_regtype(enum bpf_reg_type type)
2955 {
2956 	switch (base_type(type)) {
2957 	case PTR_TO_MAP_VALUE:
2958 	case PTR_TO_STACK:
2959 	case PTR_TO_CTX:
2960 	case PTR_TO_PACKET:
2961 	case PTR_TO_PACKET_META:
2962 	case PTR_TO_PACKET_END:
2963 	case PTR_TO_FLOW_KEYS:
2964 	case CONST_PTR_TO_MAP:
2965 	case PTR_TO_SOCKET:
2966 	case PTR_TO_SOCK_COMMON:
2967 	case PTR_TO_TCP_SOCK:
2968 	case PTR_TO_XDP_SOCK:
2969 	case PTR_TO_BTF_ID:
2970 	case PTR_TO_BUF:
2971 	case PTR_TO_MEM:
2972 	case PTR_TO_FUNC:
2973 	case PTR_TO_MAP_KEY:
2974 		return true;
2975 	default:
2976 		return false;
2977 	}
2978 }
2979 
2980 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2981 static bool register_is_null(struct bpf_reg_state *reg)
2982 {
2983 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2984 }
2985 
register_is_const(struct bpf_reg_state * reg)2986 static bool register_is_const(struct bpf_reg_state *reg)
2987 {
2988 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2989 }
2990 
__is_scalar_unbounded(struct bpf_reg_state * reg)2991 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2992 {
2993 	return tnum_is_unknown(reg->var_off) &&
2994 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2995 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2996 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2997 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2998 }
2999 
register_is_bounded(struct bpf_reg_state * reg)3000 static bool register_is_bounded(struct bpf_reg_state *reg)
3001 {
3002 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3003 }
3004 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)3005 static bool __is_pointer_value(bool allow_ptr_leaks,
3006 			       const struct bpf_reg_state *reg)
3007 {
3008 	if (allow_ptr_leaks)
3009 		return false;
3010 
3011 	return reg->type != SCALAR_VALUE;
3012 }
3013 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)3014 static void save_register_state(struct bpf_func_state *state,
3015 				int spi, struct bpf_reg_state *reg,
3016 				int size)
3017 {
3018 	int i;
3019 
3020 	state->stack[spi].spilled_ptr = *reg;
3021 	if (size == BPF_REG_SIZE)
3022 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3023 
3024 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3025 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3026 
3027 	/* size < 8 bytes spill */
3028 	for (; i; i--)
3029 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3030 }
3031 
3032 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3033  * stack boundary and alignment are checked in check_mem_access()
3034  */
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)3035 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3036 				       /* stack frame we're writing to */
3037 				       struct bpf_func_state *state,
3038 				       int off, int size, int value_regno,
3039 				       int insn_idx)
3040 {
3041 	struct bpf_func_state *cur; /* state of the current function */
3042 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3043 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3044 	struct bpf_reg_state *reg = NULL;
3045 
3046 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3047 	if (err)
3048 		return err;
3049 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3050 	 * so it's aligned access and [off, off + size) are within stack limits
3051 	 */
3052 	if (!env->allow_ptr_leaks &&
3053 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
3054 	    size != BPF_REG_SIZE) {
3055 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
3056 		return -EACCES;
3057 	}
3058 
3059 	cur = env->cur_state->frame[env->cur_state->curframe];
3060 	if (value_regno >= 0)
3061 		reg = &cur->regs[value_regno];
3062 	if (!env->bypass_spec_v4) {
3063 		bool sanitize = reg && is_spillable_regtype(reg->type);
3064 
3065 		for (i = 0; i < size; i++) {
3066 			u8 type = state->stack[spi].slot_type[i];
3067 
3068 			if (type != STACK_MISC && type != STACK_ZERO) {
3069 				sanitize = true;
3070 				break;
3071 			}
3072 		}
3073 
3074 		if (sanitize)
3075 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3076 	}
3077 
3078 	mark_stack_slot_scratched(env, spi);
3079 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3080 	    !register_is_null(reg) && env->bpf_capable) {
3081 		if (dst_reg != BPF_REG_FP) {
3082 			/* The backtracking logic can only recognize explicit
3083 			 * stack slot address like [fp - 8]. Other spill of
3084 			 * scalar via different register has to be conservative.
3085 			 * Backtrack from here and mark all registers as precise
3086 			 * that contributed into 'reg' being a constant.
3087 			 */
3088 			err = mark_chain_precision(env, value_regno);
3089 			if (err)
3090 				return err;
3091 		}
3092 		save_register_state(state, spi, reg, size);
3093 	} else if (reg && is_spillable_regtype(reg->type)) {
3094 		/* register containing pointer is being spilled into stack */
3095 		if (size != BPF_REG_SIZE) {
3096 			verbose_linfo(env, insn_idx, "; ");
3097 			verbose(env, "invalid size of register spill\n");
3098 			return -EACCES;
3099 		}
3100 		if (state != cur && reg->type == PTR_TO_STACK) {
3101 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3102 			return -EINVAL;
3103 		}
3104 		save_register_state(state, spi, reg, size);
3105 	} else {
3106 		u8 type = STACK_MISC;
3107 
3108 		/* regular write of data into stack destroys any spilled ptr */
3109 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3110 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3111 		if (is_spilled_reg(&state->stack[spi]))
3112 			for (i = 0; i < BPF_REG_SIZE; i++)
3113 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3114 
3115 		/* only mark the slot as written if all 8 bytes were written
3116 		 * otherwise read propagation may incorrectly stop too soon
3117 		 * when stack slots are partially written.
3118 		 * This heuristic means that read propagation will be
3119 		 * conservative, since it will add reg_live_read marks
3120 		 * to stack slots all the way to first state when programs
3121 		 * writes+reads less than 8 bytes
3122 		 */
3123 		if (size == BPF_REG_SIZE)
3124 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3125 
3126 		/* when we zero initialize stack slots mark them as such */
3127 		if (reg && register_is_null(reg)) {
3128 			/* backtracking doesn't work for STACK_ZERO yet. */
3129 			err = mark_chain_precision(env, value_regno);
3130 			if (err)
3131 				return err;
3132 			type = STACK_ZERO;
3133 		}
3134 
3135 		/* Mark slots affected by this stack write. */
3136 		for (i = 0; i < size; i++)
3137 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3138 				type;
3139 	}
3140 	return 0;
3141 }
3142 
3143 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3144  * known to contain a variable offset.
3145  * This function checks whether the write is permitted and conservatively
3146  * tracks the effects of the write, considering that each stack slot in the
3147  * dynamic range is potentially written to.
3148  *
3149  * 'off' includes 'regno->off'.
3150  * 'value_regno' can be -1, meaning that an unknown value is being written to
3151  * the stack.
3152  *
3153  * Spilled pointers in range are not marked as written because we don't know
3154  * what's going to be actually written. This means that read propagation for
3155  * future reads cannot be terminated by this write.
3156  *
3157  * For privileged programs, uninitialized stack slots are considered
3158  * initialized by this write (even though we don't know exactly what offsets
3159  * are going to be written to). The idea is that we don't want the verifier to
3160  * reject future reads that access slots written to through variable offsets.
3161  */
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)3162 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3163 				     /* func where register points to */
3164 				     struct bpf_func_state *state,
3165 				     int ptr_regno, int off, int size,
3166 				     int value_regno, int insn_idx)
3167 {
3168 	struct bpf_func_state *cur; /* state of the current function */
3169 	int min_off, max_off;
3170 	int i, err;
3171 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3172 	bool writing_zero = false;
3173 	/* set if the fact that we're writing a zero is used to let any
3174 	 * stack slots remain STACK_ZERO
3175 	 */
3176 	bool zero_used = false;
3177 
3178 	cur = env->cur_state->frame[env->cur_state->curframe];
3179 	ptr_reg = &cur->regs[ptr_regno];
3180 	min_off = ptr_reg->smin_value + off;
3181 	max_off = ptr_reg->smax_value + off + size;
3182 	if (value_regno >= 0)
3183 		value_reg = &cur->regs[value_regno];
3184 	if (value_reg && register_is_null(value_reg))
3185 		writing_zero = true;
3186 
3187 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3188 	if (err)
3189 		return err;
3190 
3191 
3192 	/* Variable offset writes destroy any spilled pointers in range. */
3193 	for (i = min_off; i < max_off; i++) {
3194 		u8 new_type, *stype;
3195 		int slot, spi;
3196 
3197 		slot = -i - 1;
3198 		spi = slot / BPF_REG_SIZE;
3199 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3200 		mark_stack_slot_scratched(env, spi);
3201 
3202 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3203 			/* Reject the write if range we may write to has not
3204 			 * been initialized beforehand. If we didn't reject
3205 			 * here, the ptr status would be erased below (even
3206 			 * though not all slots are actually overwritten),
3207 			 * possibly opening the door to leaks.
3208 			 *
3209 			 * We do however catch STACK_INVALID case below, and
3210 			 * only allow reading possibly uninitialized memory
3211 			 * later for CAP_PERFMON, as the write may not happen to
3212 			 * that slot.
3213 			 */
3214 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3215 				insn_idx, i);
3216 			return -EINVAL;
3217 		}
3218 
3219 		/* Erase all spilled pointers. */
3220 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3221 
3222 		/* Update the slot type. */
3223 		new_type = STACK_MISC;
3224 		if (writing_zero && *stype == STACK_ZERO) {
3225 			new_type = STACK_ZERO;
3226 			zero_used = true;
3227 		}
3228 		/* If the slot is STACK_INVALID, we check whether it's OK to
3229 		 * pretend that it will be initialized by this write. The slot
3230 		 * might not actually be written to, and so if we mark it as
3231 		 * initialized future reads might leak uninitialized memory.
3232 		 * For privileged programs, we will accept such reads to slots
3233 		 * that may or may not be written because, if we're reject
3234 		 * them, the error would be too confusing.
3235 		 */
3236 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3237 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3238 					insn_idx, i);
3239 			return -EINVAL;
3240 		}
3241 		*stype = new_type;
3242 	}
3243 	if (zero_used) {
3244 		/* backtracking doesn't work for STACK_ZERO yet. */
3245 		err = mark_chain_precision(env, value_regno);
3246 		if (err)
3247 			return err;
3248 	}
3249 	return 0;
3250 }
3251 
3252 /* When register 'dst_regno' is assigned some values from stack[min_off,
3253  * max_off), we set the register's type according to the types of the
3254  * respective stack slots. If all the stack values are known to be zeros, then
3255  * so is the destination reg. Otherwise, the register is considered to be
3256  * SCALAR. This function does not deal with register filling; the caller must
3257  * ensure that all spilled registers in the stack range have been marked as
3258  * read.
3259  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)3260 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3261 				/* func where src register points to */
3262 				struct bpf_func_state *ptr_state,
3263 				int min_off, int max_off, int dst_regno)
3264 {
3265 	struct bpf_verifier_state *vstate = env->cur_state;
3266 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3267 	int i, slot, spi;
3268 	u8 *stype;
3269 	int zeros = 0;
3270 
3271 	for (i = min_off; i < max_off; i++) {
3272 		slot = -i - 1;
3273 		spi = slot / BPF_REG_SIZE;
3274 		stype = ptr_state->stack[spi].slot_type;
3275 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3276 			break;
3277 		zeros++;
3278 	}
3279 	if (zeros == max_off - min_off) {
3280 		/* any access_size read into register is zero extended,
3281 		 * so the whole register == const_zero
3282 		 */
3283 		__mark_reg_const_zero(&state->regs[dst_regno]);
3284 		/* backtracking doesn't support STACK_ZERO yet,
3285 		 * so mark it precise here, so that later
3286 		 * backtracking can stop here.
3287 		 * Backtracking may not need this if this register
3288 		 * doesn't participate in pointer adjustment.
3289 		 * Forward propagation of precise flag is not
3290 		 * necessary either. This mark is only to stop
3291 		 * backtracking. Any register that contributed
3292 		 * to const 0 was marked precise before spill.
3293 		 */
3294 		state->regs[dst_regno].precise = true;
3295 	} else {
3296 		/* have read misc data from the stack */
3297 		mark_reg_unknown(env, state->regs, dst_regno);
3298 	}
3299 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3300 }
3301 
3302 /* Read the stack at 'off' and put the results into the register indicated by
3303  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3304  * spilled reg.
3305  *
3306  * 'dst_regno' can be -1, meaning that the read value is not going to a
3307  * register.
3308  *
3309  * The access is assumed to be within the current stack bounds.
3310  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)3311 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3312 				      /* func where src register points to */
3313 				      struct bpf_func_state *reg_state,
3314 				      int off, int size, int dst_regno)
3315 {
3316 	struct bpf_verifier_state *vstate = env->cur_state;
3317 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3318 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3319 	struct bpf_reg_state *reg;
3320 	u8 *stype, type;
3321 
3322 	stype = reg_state->stack[spi].slot_type;
3323 	reg = &reg_state->stack[spi].spilled_ptr;
3324 
3325 	if (is_spilled_reg(&reg_state->stack[spi])) {
3326 		u8 spill_size = 1;
3327 
3328 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3329 			spill_size++;
3330 
3331 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3332 			if (reg->type != SCALAR_VALUE) {
3333 				verbose_linfo(env, env->insn_idx, "; ");
3334 				verbose(env, "invalid size of register fill\n");
3335 				return -EACCES;
3336 			}
3337 
3338 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3339 			if (dst_regno < 0)
3340 				return 0;
3341 
3342 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3343 				/* The earlier check_reg_arg() has decided the
3344 				 * subreg_def for this insn.  Save it first.
3345 				 */
3346 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3347 
3348 				state->regs[dst_regno] = *reg;
3349 				state->regs[dst_regno].subreg_def = subreg_def;
3350 			} else {
3351 				for (i = 0; i < size; i++) {
3352 					type = stype[(slot - i) % BPF_REG_SIZE];
3353 					if (type == STACK_SPILL)
3354 						continue;
3355 					if (type == STACK_MISC)
3356 						continue;
3357 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3358 						off, i, size);
3359 					return -EACCES;
3360 				}
3361 				mark_reg_unknown(env, state->regs, dst_regno);
3362 			}
3363 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3364 			return 0;
3365 		}
3366 
3367 		if (dst_regno >= 0) {
3368 			/* restore register state from stack */
3369 			state->regs[dst_regno] = *reg;
3370 			/* mark reg as written since spilled pointer state likely
3371 			 * has its liveness marks cleared by is_state_visited()
3372 			 * which resets stack/reg liveness for state transitions
3373 			 */
3374 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3375 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3376 			/* If dst_regno==-1, the caller is asking us whether
3377 			 * it is acceptable to use this value as a SCALAR_VALUE
3378 			 * (e.g. for XADD).
3379 			 * We must not allow unprivileged callers to do that
3380 			 * with spilled pointers.
3381 			 */
3382 			verbose(env, "leaking pointer from stack off %d\n",
3383 				off);
3384 			return -EACCES;
3385 		}
3386 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3387 	} else {
3388 		for (i = 0; i < size; i++) {
3389 			type = stype[(slot - i) % BPF_REG_SIZE];
3390 			if (type == STACK_MISC)
3391 				continue;
3392 			if (type == STACK_ZERO)
3393 				continue;
3394 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3395 				off, i, size);
3396 			return -EACCES;
3397 		}
3398 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3399 		if (dst_regno >= 0)
3400 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3401 	}
3402 	return 0;
3403 }
3404 
3405 enum bpf_access_src {
3406 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3407 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3408 };
3409 
3410 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3411 					 int regno, int off, int access_size,
3412 					 bool zero_size_allowed,
3413 					 enum bpf_access_src type,
3414 					 struct bpf_call_arg_meta *meta);
3415 
reg_state(struct bpf_verifier_env * env,int regno)3416 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3417 {
3418 	return cur_regs(env) + regno;
3419 }
3420 
3421 /* Read the stack at 'ptr_regno + off' and put the result into the register
3422  * 'dst_regno'.
3423  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3424  * but not its variable offset.
3425  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3426  *
3427  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3428  * filling registers (i.e. reads of spilled register cannot be detected when
3429  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3430  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3431  * offset; for a fixed offset check_stack_read_fixed_off should be used
3432  * instead.
3433  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3434 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3435 				    int ptr_regno, int off, int size, int dst_regno)
3436 {
3437 	/* The state of the source register. */
3438 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3439 	struct bpf_func_state *ptr_state = func(env, reg);
3440 	int err;
3441 	int min_off, max_off;
3442 
3443 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3444 	 */
3445 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3446 					    false, ACCESS_DIRECT, NULL);
3447 	if (err)
3448 		return err;
3449 
3450 	min_off = reg->smin_value + off;
3451 	max_off = reg->smax_value + off;
3452 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3453 	return 0;
3454 }
3455 
3456 /* check_stack_read dispatches to check_stack_read_fixed_off or
3457  * check_stack_read_var_off.
3458  *
3459  * The caller must ensure that the offset falls within the allocated stack
3460  * bounds.
3461  *
3462  * 'dst_regno' is a register which will receive the value from the stack. It
3463  * can be -1, meaning that the read value is not going to a register.
3464  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3465 static int check_stack_read(struct bpf_verifier_env *env,
3466 			    int ptr_regno, int off, int size,
3467 			    int dst_regno)
3468 {
3469 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3470 	struct bpf_func_state *state = func(env, reg);
3471 	int err;
3472 	/* Some accesses are only permitted with a static offset. */
3473 	bool var_off = !tnum_is_const(reg->var_off);
3474 
3475 	/* The offset is required to be static when reads don't go to a
3476 	 * register, in order to not leak pointers (see
3477 	 * check_stack_read_fixed_off).
3478 	 */
3479 	if (dst_regno < 0 && var_off) {
3480 		char tn_buf[48];
3481 
3482 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3483 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3484 			tn_buf, off, size);
3485 		return -EACCES;
3486 	}
3487 	/* Variable offset is prohibited for unprivileged mode for simplicity
3488 	 * since it requires corresponding support in Spectre masking for stack
3489 	 * ALU. See also retrieve_ptr_limit().
3490 	 */
3491 	if (!env->bypass_spec_v1 && var_off) {
3492 		char tn_buf[48];
3493 
3494 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3495 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3496 				ptr_regno, tn_buf);
3497 		return -EACCES;
3498 	}
3499 
3500 	if (!var_off) {
3501 		off += reg->var_off.value;
3502 		err = check_stack_read_fixed_off(env, state, off, size,
3503 						 dst_regno);
3504 	} else {
3505 		/* Variable offset stack reads need more conservative handling
3506 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3507 		 * branch.
3508 		 */
3509 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3510 					       dst_regno);
3511 	}
3512 	return err;
3513 }
3514 
3515 
3516 /* check_stack_write dispatches to check_stack_write_fixed_off or
3517  * check_stack_write_var_off.
3518  *
3519  * 'ptr_regno' is the register used as a pointer into the stack.
3520  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3521  * 'value_regno' is the register whose value we're writing to the stack. It can
3522  * be -1, meaning that we're not writing from a register.
3523  *
3524  * The caller must ensure that the offset falls within the maximum stack size.
3525  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)3526 static int check_stack_write(struct bpf_verifier_env *env,
3527 			     int ptr_regno, int off, int size,
3528 			     int value_regno, int insn_idx)
3529 {
3530 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3531 	struct bpf_func_state *state = func(env, reg);
3532 	int err;
3533 
3534 	if (tnum_is_const(reg->var_off)) {
3535 		off += reg->var_off.value;
3536 		err = check_stack_write_fixed_off(env, state, off, size,
3537 						  value_regno, insn_idx);
3538 	} else {
3539 		/* Variable offset stack reads need more conservative handling
3540 		 * than fixed offset ones.
3541 		 */
3542 		err = check_stack_write_var_off(env, state,
3543 						ptr_regno, off, size,
3544 						value_regno, insn_idx);
3545 	}
3546 	return err;
3547 }
3548 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)3549 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3550 				 int off, int size, enum bpf_access_type type)
3551 {
3552 	struct bpf_reg_state *regs = cur_regs(env);
3553 	struct bpf_map *map = regs[regno].map_ptr;
3554 	u32 cap = bpf_map_flags_to_cap(map);
3555 
3556 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3557 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3558 			map->value_size, off, size);
3559 		return -EACCES;
3560 	}
3561 
3562 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3563 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3564 			map->value_size, off, size);
3565 		return -EACCES;
3566 	}
3567 
3568 	return 0;
3569 }
3570 
3571 /* 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)3572 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3573 			      int off, int size, u32 mem_size,
3574 			      bool zero_size_allowed)
3575 {
3576 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3577 	struct bpf_reg_state *reg;
3578 
3579 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3580 		return 0;
3581 
3582 	reg = &cur_regs(env)[regno];
3583 	switch (reg->type) {
3584 	case PTR_TO_MAP_KEY:
3585 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3586 			mem_size, off, size);
3587 		break;
3588 	case PTR_TO_MAP_VALUE:
3589 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3590 			mem_size, off, size);
3591 		break;
3592 	case PTR_TO_PACKET:
3593 	case PTR_TO_PACKET_META:
3594 	case PTR_TO_PACKET_END:
3595 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3596 			off, size, regno, reg->id, off, mem_size);
3597 		break;
3598 	case PTR_TO_MEM:
3599 	default:
3600 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3601 			mem_size, off, size);
3602 	}
3603 
3604 	return -EACCES;
3605 }
3606 
3607 /* 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)3608 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3609 				   int off, int size, u32 mem_size,
3610 				   bool zero_size_allowed)
3611 {
3612 	struct bpf_verifier_state *vstate = env->cur_state;
3613 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3614 	struct bpf_reg_state *reg = &state->regs[regno];
3615 	int err;
3616 
3617 	/* We may have adjusted the register pointing to memory region, so we
3618 	 * need to try adding each of min_value and max_value to off
3619 	 * to make sure our theoretical access will be safe.
3620 	 *
3621 	 * The minimum value is only important with signed
3622 	 * comparisons where we can't assume the floor of a
3623 	 * value is 0.  If we are using signed variables for our
3624 	 * index'es we need to make sure that whatever we use
3625 	 * will have a set floor within our range.
3626 	 */
3627 	if (reg->smin_value < 0 &&
3628 	    (reg->smin_value == S64_MIN ||
3629 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3630 	      reg->smin_value + off < 0)) {
3631 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3632 			regno);
3633 		return -EACCES;
3634 	}
3635 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3636 				 mem_size, zero_size_allowed);
3637 	if (err) {
3638 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3639 			regno);
3640 		return err;
3641 	}
3642 
3643 	/* If we haven't set a max value then we need to bail since we can't be
3644 	 * sure we won't do bad things.
3645 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3646 	 */
3647 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3648 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3649 			regno);
3650 		return -EACCES;
3651 	}
3652 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3653 				 mem_size, zero_size_allowed);
3654 	if (err) {
3655 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3656 			regno);
3657 		return err;
3658 	}
3659 
3660 	return 0;
3661 }
3662 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)3663 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3664 			       const struct bpf_reg_state *reg, int regno,
3665 			       bool fixed_off_ok)
3666 {
3667 	/* Access to this pointer-typed register or passing it to a helper
3668 	 * is only allowed in its original, unmodified form.
3669 	 */
3670 
3671 	if (reg->off < 0) {
3672 		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3673 			reg_type_str(env, reg->type), regno, reg->off);
3674 		return -EACCES;
3675 	}
3676 
3677 	if (!fixed_off_ok && reg->off) {
3678 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3679 			reg_type_str(env, reg->type), regno, reg->off);
3680 		return -EACCES;
3681 	}
3682 
3683 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3684 		char tn_buf[48];
3685 
3686 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3687 		verbose(env, "variable %s access var_off=%s disallowed\n",
3688 			reg_type_str(env, reg->type), tn_buf);
3689 		return -EACCES;
3690 	}
3691 
3692 	return 0;
3693 }
3694 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3695 int check_ptr_off_reg(struct bpf_verifier_env *env,
3696 		      const struct bpf_reg_state *reg, int regno)
3697 {
3698 	return __check_ptr_off_reg(env, reg, regno, false);
3699 }
3700 
map_kptr_match_type(struct bpf_verifier_env * env,struct bpf_map_value_off_desc * off_desc,struct bpf_reg_state * reg,u32 regno)3701 static int map_kptr_match_type(struct bpf_verifier_env *env,
3702 			       struct bpf_map_value_off_desc *off_desc,
3703 			       struct bpf_reg_state *reg, u32 regno)
3704 {
3705 	const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3706 	int perm_flags = PTR_MAYBE_NULL;
3707 	const char *reg_name = "";
3708 
3709 	/* Only unreferenced case accepts untrusted pointers */
3710 	if (off_desc->type == BPF_KPTR_UNREF)
3711 		perm_flags |= PTR_UNTRUSTED;
3712 
3713 	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3714 		goto bad_type;
3715 
3716 	if (!btf_is_kernel(reg->btf)) {
3717 		verbose(env, "R%d must point to kernel BTF\n", regno);
3718 		return -EINVAL;
3719 	}
3720 	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
3721 	reg_name = kernel_type_name(reg->btf, reg->btf_id);
3722 
3723 	/* For ref_ptr case, release function check should ensure we get one
3724 	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3725 	 * normal store of unreferenced kptr, we must ensure var_off is zero.
3726 	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3727 	 * reg->off and reg->ref_obj_id are not needed here.
3728 	 */
3729 	if (__check_ptr_off_reg(env, reg, regno, true))
3730 		return -EACCES;
3731 
3732 	/* A full type match is needed, as BTF can be vmlinux or module BTF, and
3733 	 * we also need to take into account the reg->off.
3734 	 *
3735 	 * We want to support cases like:
3736 	 *
3737 	 * struct foo {
3738 	 *         struct bar br;
3739 	 *         struct baz bz;
3740 	 * };
3741 	 *
3742 	 * struct foo *v;
3743 	 * v = func();	      // PTR_TO_BTF_ID
3744 	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
3745 	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3746 	 *                    // first member type of struct after comparison fails
3747 	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3748 	 *                    // to match type
3749 	 *
3750 	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3751 	 * is zero. We must also ensure that btf_struct_ids_match does not walk
3752 	 * the struct to match type against first member of struct, i.e. reject
3753 	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3754 	 * strict mode to true for type match.
3755 	 */
3756 	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3757 				  off_desc->kptr.btf, off_desc->kptr.btf_id,
3758 				  off_desc->type == BPF_KPTR_REF))
3759 		goto bad_type;
3760 	return 0;
3761 bad_type:
3762 	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3763 		reg_type_str(env, reg->type), reg_name);
3764 	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3765 	if (off_desc->type == BPF_KPTR_UNREF)
3766 		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3767 			targ_name);
3768 	else
3769 		verbose(env, "\n");
3770 	return -EINVAL;
3771 }
3772 
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct bpf_map_value_off_desc * off_desc)3773 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3774 				 int value_regno, int insn_idx,
3775 				 struct bpf_map_value_off_desc *off_desc)
3776 {
3777 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3778 	int class = BPF_CLASS(insn->code);
3779 	struct bpf_reg_state *val_reg;
3780 
3781 	/* Things we already checked for in check_map_access and caller:
3782 	 *  - Reject cases where variable offset may touch kptr
3783 	 *  - size of access (must be BPF_DW)
3784 	 *  - tnum_is_const(reg->var_off)
3785 	 *  - off_desc->offset == off + reg->var_off.value
3786 	 */
3787 	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3788 	if (BPF_MODE(insn->code) != BPF_MEM) {
3789 		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3790 		return -EACCES;
3791 	}
3792 
3793 	/* We only allow loading referenced kptr, since it will be marked as
3794 	 * untrusted, similar to unreferenced kptr.
3795 	 */
3796 	if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3797 		verbose(env, "store to referenced kptr disallowed\n");
3798 		return -EACCES;
3799 	}
3800 
3801 	if (class == BPF_LDX) {
3802 		val_reg = reg_state(env, value_regno);
3803 		/* We can simply mark the value_regno receiving the pointer
3804 		 * value from map as PTR_TO_BTF_ID, with the correct type.
3805 		 */
3806 		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3807 				off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3808 		/* For mark_ptr_or_null_reg */
3809 		val_reg->id = ++env->id_gen;
3810 	} else if (class == BPF_STX) {
3811 		val_reg = reg_state(env, value_regno);
3812 		if (!register_is_null(val_reg) &&
3813 		    map_kptr_match_type(env, off_desc, val_reg, value_regno))
3814 			return -EACCES;
3815 	} else if (class == BPF_ST) {
3816 		if (insn->imm) {
3817 			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3818 				off_desc->offset);
3819 			return -EACCES;
3820 		}
3821 	} else {
3822 		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3823 		return -EACCES;
3824 	}
3825 	return 0;
3826 }
3827 
3828 /* 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)3829 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3830 			    int off, int size, bool zero_size_allowed,
3831 			    enum bpf_access_src src)
3832 {
3833 	struct bpf_verifier_state *vstate = env->cur_state;
3834 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3835 	struct bpf_reg_state *reg = &state->regs[regno];
3836 	struct bpf_map *map = reg->map_ptr;
3837 	int err;
3838 
3839 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3840 				      zero_size_allowed);
3841 	if (err)
3842 		return err;
3843 
3844 	if (map_value_has_spin_lock(map)) {
3845 		u32 lock = map->spin_lock_off;
3846 
3847 		/* if any part of struct bpf_spin_lock can be touched by
3848 		 * load/store reject this program.
3849 		 * To check that [x1, x2) overlaps with [y1, y2)
3850 		 * it is sufficient to check x1 < y2 && y1 < x2.
3851 		 */
3852 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3853 		     lock < reg->umax_value + off + size) {
3854 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3855 			return -EACCES;
3856 		}
3857 	}
3858 	if (map_value_has_timer(map)) {
3859 		u32 t = map->timer_off;
3860 
3861 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3862 		     t < reg->umax_value + off + size) {
3863 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3864 			return -EACCES;
3865 		}
3866 	}
3867 	if (map_value_has_kptrs(map)) {
3868 		struct bpf_map_value_off *tab = map->kptr_off_tab;
3869 		int i;
3870 
3871 		for (i = 0; i < tab->nr_off; i++) {
3872 			u32 p = tab->off[i].offset;
3873 
3874 			if (reg->smin_value + off < p + sizeof(u64) &&
3875 			    p < reg->umax_value + off + size) {
3876 				if (src != ACCESS_DIRECT) {
3877 					verbose(env, "kptr cannot be accessed indirectly by helper\n");
3878 					return -EACCES;
3879 				}
3880 				if (!tnum_is_const(reg->var_off)) {
3881 					verbose(env, "kptr access cannot have variable offset\n");
3882 					return -EACCES;
3883 				}
3884 				if (p != off + reg->var_off.value) {
3885 					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3886 						p, off + reg->var_off.value);
3887 					return -EACCES;
3888 				}
3889 				if (size != bpf_size_to_bytes(BPF_DW)) {
3890 					verbose(env, "kptr access size must be BPF_DW\n");
3891 					return -EACCES;
3892 				}
3893 				break;
3894 			}
3895 		}
3896 	}
3897 	return err;
3898 }
3899 
3900 #define MAX_PACKET_OFF 0xffff
3901 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)3902 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3903 				       const struct bpf_call_arg_meta *meta,
3904 				       enum bpf_access_type t)
3905 {
3906 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3907 
3908 	switch (prog_type) {
3909 	/* Program types only with direct read access go here! */
3910 	case BPF_PROG_TYPE_LWT_IN:
3911 	case BPF_PROG_TYPE_LWT_OUT:
3912 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3913 	case BPF_PROG_TYPE_SK_REUSEPORT:
3914 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3915 	case BPF_PROG_TYPE_CGROUP_SKB:
3916 		if (t == BPF_WRITE)
3917 			return false;
3918 		fallthrough;
3919 
3920 	/* Program types with direct read + write access go here! */
3921 	case BPF_PROG_TYPE_SCHED_CLS:
3922 	case BPF_PROG_TYPE_SCHED_ACT:
3923 	case BPF_PROG_TYPE_XDP:
3924 	case BPF_PROG_TYPE_LWT_XMIT:
3925 	case BPF_PROG_TYPE_SK_SKB:
3926 	case BPF_PROG_TYPE_SK_MSG:
3927 		if (meta)
3928 			return meta->pkt_access;
3929 
3930 		env->seen_direct_write = true;
3931 		return true;
3932 
3933 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3934 		if (t == BPF_WRITE)
3935 			env->seen_direct_write = true;
3936 
3937 		return true;
3938 
3939 	default:
3940 		return false;
3941 	}
3942 }
3943 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)3944 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3945 			       int size, bool zero_size_allowed)
3946 {
3947 	struct bpf_reg_state *regs = cur_regs(env);
3948 	struct bpf_reg_state *reg = &regs[regno];
3949 	int err;
3950 
3951 	/* We may have added a variable offset to the packet pointer; but any
3952 	 * reg->range we have comes after that.  We are only checking the fixed
3953 	 * offset.
3954 	 */
3955 
3956 	/* We don't allow negative numbers, because we aren't tracking enough
3957 	 * detail to prove they're safe.
3958 	 */
3959 	if (reg->smin_value < 0) {
3960 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3961 			regno);
3962 		return -EACCES;
3963 	}
3964 
3965 	err = reg->range < 0 ? -EINVAL :
3966 	      __check_mem_access(env, regno, off, size, reg->range,
3967 				 zero_size_allowed);
3968 	if (err) {
3969 		verbose(env, "R%d offset is outside of the packet\n", regno);
3970 		return err;
3971 	}
3972 
3973 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3974 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3975 	 * otherwise find_good_pkt_pointers would have refused to set range info
3976 	 * that __check_mem_access would have rejected this pkt access.
3977 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3978 	 */
3979 	env->prog->aux->max_pkt_offset =
3980 		max_t(u32, env->prog->aux->max_pkt_offset,
3981 		      off + reg->umax_value + size - 1);
3982 
3983 	return err;
3984 }
3985 
3986 /* 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)3987 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3988 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3989 			    struct btf **btf, u32 *btf_id)
3990 {
3991 	struct bpf_insn_access_aux info = {
3992 		.reg_type = *reg_type,
3993 		.log = &env->log,
3994 	};
3995 
3996 	if (env->ops->is_valid_access &&
3997 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3998 		/* A non zero info.ctx_field_size indicates that this field is a
3999 		 * candidate for later verifier transformation to load the whole
4000 		 * field and then apply a mask when accessed with a narrower
4001 		 * access than actual ctx access size. A zero info.ctx_field_size
4002 		 * will only allow for whole field access and rejects any other
4003 		 * type of narrower access.
4004 		 */
4005 		*reg_type = info.reg_type;
4006 
4007 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4008 			*btf = info.btf;
4009 			*btf_id = info.btf_id;
4010 		} else {
4011 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4012 		}
4013 		/* remember the offset of last byte accessed in ctx */
4014 		if (env->prog->aux->max_ctx_offset < off + size)
4015 			env->prog->aux->max_ctx_offset = off + size;
4016 		return 0;
4017 	}
4018 
4019 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4020 	return -EACCES;
4021 }
4022 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)4023 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4024 				  int size)
4025 {
4026 	if (size < 0 || off < 0 ||
4027 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
4028 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
4029 			off, size);
4030 		return -EACCES;
4031 	}
4032 	return 0;
4033 }
4034 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)4035 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4036 			     u32 regno, int off, int size,
4037 			     enum bpf_access_type t)
4038 {
4039 	struct bpf_reg_state *regs = cur_regs(env);
4040 	struct bpf_reg_state *reg = &regs[regno];
4041 	struct bpf_insn_access_aux info = {};
4042 	bool valid;
4043 
4044 	if (reg->smin_value < 0) {
4045 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4046 			regno);
4047 		return -EACCES;
4048 	}
4049 
4050 	switch (reg->type) {
4051 	case PTR_TO_SOCK_COMMON:
4052 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4053 		break;
4054 	case PTR_TO_SOCKET:
4055 		valid = bpf_sock_is_valid_access(off, size, t, &info);
4056 		break;
4057 	case PTR_TO_TCP_SOCK:
4058 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4059 		break;
4060 	case PTR_TO_XDP_SOCK:
4061 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4062 		break;
4063 	default:
4064 		valid = false;
4065 	}
4066 
4067 
4068 	if (valid) {
4069 		env->insn_aux_data[insn_idx].ctx_field_size =
4070 			info.ctx_field_size;
4071 		return 0;
4072 	}
4073 
4074 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
4075 		regno, reg_type_str(env, reg->type), off, size);
4076 
4077 	return -EACCES;
4078 }
4079 
is_pointer_value(struct bpf_verifier_env * env,int regno)4080 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4081 {
4082 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4083 }
4084 
is_ctx_reg(struct bpf_verifier_env * env,int regno)4085 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4086 {
4087 	const struct bpf_reg_state *reg = reg_state(env, regno);
4088 
4089 	return reg->type == PTR_TO_CTX;
4090 }
4091 
is_sk_reg(struct bpf_verifier_env * env,int regno)4092 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4093 {
4094 	const struct bpf_reg_state *reg = reg_state(env, regno);
4095 
4096 	return type_is_sk_pointer(reg->type);
4097 }
4098 
is_pkt_reg(struct bpf_verifier_env * env,int regno)4099 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4100 {
4101 	const struct bpf_reg_state *reg = reg_state(env, regno);
4102 
4103 	return type_is_pkt_pointer(reg->type);
4104 }
4105 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)4106 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4107 {
4108 	const struct bpf_reg_state *reg = reg_state(env, regno);
4109 
4110 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4111 	return reg->type == PTR_TO_FLOW_KEYS;
4112 }
4113 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)4114 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4115 				   const struct bpf_reg_state *reg,
4116 				   int off, int size, bool strict)
4117 {
4118 	struct tnum reg_off;
4119 	int ip_align;
4120 
4121 	/* Byte size accesses are always allowed. */
4122 	if (!strict || size == 1)
4123 		return 0;
4124 
4125 	/* For platforms that do not have a Kconfig enabling
4126 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4127 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
4128 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4129 	 * to this code only in strict mode where we want to emulate
4130 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
4131 	 * unconditional IP align value of '2'.
4132 	 */
4133 	ip_align = 2;
4134 
4135 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4136 	if (!tnum_is_aligned(reg_off, size)) {
4137 		char tn_buf[48];
4138 
4139 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4140 		verbose(env,
4141 			"misaligned packet access off %d+%s+%d+%d size %d\n",
4142 			ip_align, tn_buf, reg->off, off, size);
4143 		return -EACCES;
4144 	}
4145 
4146 	return 0;
4147 }
4148 
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)4149 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4150 				       const struct bpf_reg_state *reg,
4151 				       const char *pointer_desc,
4152 				       int off, int size, bool strict)
4153 {
4154 	struct tnum reg_off;
4155 
4156 	/* Byte size accesses are always allowed. */
4157 	if (!strict || size == 1)
4158 		return 0;
4159 
4160 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4161 	if (!tnum_is_aligned(reg_off, size)) {
4162 		char tn_buf[48];
4163 
4164 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4165 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4166 			pointer_desc, tn_buf, reg->off, off, size);
4167 		return -EACCES;
4168 	}
4169 
4170 	return 0;
4171 }
4172 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)4173 static int check_ptr_alignment(struct bpf_verifier_env *env,
4174 			       const struct bpf_reg_state *reg, int off,
4175 			       int size, bool strict_alignment_once)
4176 {
4177 	bool strict = env->strict_alignment || strict_alignment_once;
4178 	const char *pointer_desc = "";
4179 
4180 	switch (reg->type) {
4181 	case PTR_TO_PACKET:
4182 	case PTR_TO_PACKET_META:
4183 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
4184 		 * right in front, treat it the very same way.
4185 		 */
4186 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
4187 	case PTR_TO_FLOW_KEYS:
4188 		pointer_desc = "flow keys ";
4189 		break;
4190 	case PTR_TO_MAP_KEY:
4191 		pointer_desc = "key ";
4192 		break;
4193 	case PTR_TO_MAP_VALUE:
4194 		pointer_desc = "value ";
4195 		break;
4196 	case PTR_TO_CTX:
4197 		pointer_desc = "context ";
4198 		break;
4199 	case PTR_TO_STACK:
4200 		pointer_desc = "stack ";
4201 		/* The stack spill tracking logic in check_stack_write_fixed_off()
4202 		 * and check_stack_read_fixed_off() relies on stack accesses being
4203 		 * aligned.
4204 		 */
4205 		strict = true;
4206 		break;
4207 	case PTR_TO_SOCKET:
4208 		pointer_desc = "sock ";
4209 		break;
4210 	case PTR_TO_SOCK_COMMON:
4211 		pointer_desc = "sock_common ";
4212 		break;
4213 	case PTR_TO_TCP_SOCK:
4214 		pointer_desc = "tcp_sock ";
4215 		break;
4216 	case PTR_TO_XDP_SOCK:
4217 		pointer_desc = "xdp_sock ";
4218 		break;
4219 	default:
4220 		break;
4221 	}
4222 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4223 					   strict);
4224 }
4225 
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)4226 static int update_stack_depth(struct bpf_verifier_env *env,
4227 			      const struct bpf_func_state *func,
4228 			      int off)
4229 {
4230 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
4231 
4232 	if (stack >= -off)
4233 		return 0;
4234 
4235 	/* update known max for given subprogram */
4236 	env->subprog_info[func->subprogno].stack_depth = -off;
4237 	return 0;
4238 }
4239 
4240 /* starting from main bpf function walk all instructions of the function
4241  * and recursively walk all callees that given function can call.
4242  * Ignore jump and exit insns.
4243  * Since recursion is prevented by check_cfg() this algorithm
4244  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4245  */
check_max_stack_depth(struct bpf_verifier_env * env)4246 static int check_max_stack_depth(struct bpf_verifier_env *env)
4247 {
4248 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4249 	struct bpf_subprog_info *subprog = env->subprog_info;
4250 	struct bpf_insn *insn = env->prog->insnsi;
4251 	bool tail_call_reachable = false;
4252 	int ret_insn[MAX_CALL_FRAMES];
4253 	int ret_prog[MAX_CALL_FRAMES];
4254 	int j;
4255 
4256 process_func:
4257 	/* protect against potential stack overflow that might happen when
4258 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4259 	 * depth for such case down to 256 so that the worst case scenario
4260 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
4261 	 * 8k).
4262 	 *
4263 	 * To get the idea what might happen, see an example:
4264 	 * func1 -> sub rsp, 128
4265 	 *  subfunc1 -> sub rsp, 256
4266 	 *  tailcall1 -> add rsp, 256
4267 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4268 	 *   subfunc2 -> sub rsp, 64
4269 	 *   subfunc22 -> sub rsp, 128
4270 	 *   tailcall2 -> add rsp, 128
4271 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4272 	 *
4273 	 * tailcall will unwind the current stack frame but it will not get rid
4274 	 * of caller's stack as shown on the example above.
4275 	 */
4276 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
4277 		verbose(env,
4278 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4279 			depth);
4280 		return -EACCES;
4281 	}
4282 	/* round up to 32-bytes, since this is granularity
4283 	 * of interpreter stack size
4284 	 */
4285 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4286 	if (depth > MAX_BPF_STACK) {
4287 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
4288 			frame + 1, depth);
4289 		return -EACCES;
4290 	}
4291 continue_func:
4292 	subprog_end = subprog[idx + 1].start;
4293 	for (; i < subprog_end; i++) {
4294 		int next_insn;
4295 
4296 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4297 			continue;
4298 		/* remember insn and function to return to */
4299 		ret_insn[frame] = i + 1;
4300 		ret_prog[frame] = idx;
4301 
4302 		/* find the callee */
4303 		next_insn = i + insn[i].imm + 1;
4304 		idx = find_subprog(env, next_insn);
4305 		if (idx < 0) {
4306 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4307 				  next_insn);
4308 			return -EFAULT;
4309 		}
4310 		if (subprog[idx].is_async_cb) {
4311 			if (subprog[idx].has_tail_call) {
4312 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4313 				return -EFAULT;
4314 			}
4315 			 /* async callbacks don't increase bpf prog stack size */
4316 			continue;
4317 		}
4318 		i = next_insn;
4319 
4320 		if (subprog[idx].has_tail_call)
4321 			tail_call_reachable = true;
4322 
4323 		frame++;
4324 		if (frame >= MAX_CALL_FRAMES) {
4325 			verbose(env, "the call stack of %d frames is too deep !\n",
4326 				frame);
4327 			return -E2BIG;
4328 		}
4329 		goto process_func;
4330 	}
4331 	/* if tail call got detected across bpf2bpf calls then mark each of the
4332 	 * currently present subprog frames as tail call reachable subprogs;
4333 	 * this info will be utilized by JIT so that we will be preserving the
4334 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
4335 	 */
4336 	if (tail_call_reachable)
4337 		for (j = 0; j < frame; j++)
4338 			subprog[ret_prog[j]].tail_call_reachable = true;
4339 	if (subprog[0].tail_call_reachable)
4340 		env->prog->aux->tail_call_reachable = true;
4341 
4342 	/* end of for() loop means the last insn of the 'subprog'
4343 	 * was reached. Doesn't matter whether it was JA or EXIT
4344 	 */
4345 	if (frame == 0)
4346 		return 0;
4347 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4348 	frame--;
4349 	i = ret_insn[frame];
4350 	idx = ret_prog[frame];
4351 	goto continue_func;
4352 }
4353 
4354 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)4355 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4356 				  const struct bpf_insn *insn, int idx)
4357 {
4358 	int start = idx + insn->imm + 1, subprog;
4359 
4360 	subprog = find_subprog(env, start);
4361 	if (subprog < 0) {
4362 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4363 			  start);
4364 		return -EFAULT;
4365 	}
4366 	return env->subprog_info[subprog].stack_depth;
4367 }
4368 #endif
4369 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)4370 static int __check_buffer_access(struct bpf_verifier_env *env,
4371 				 const char *buf_info,
4372 				 const struct bpf_reg_state *reg,
4373 				 int regno, int off, int size)
4374 {
4375 	if (off < 0) {
4376 		verbose(env,
4377 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4378 			regno, buf_info, off, size);
4379 		return -EACCES;
4380 	}
4381 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4382 		char tn_buf[48];
4383 
4384 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4385 		verbose(env,
4386 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4387 			regno, off, tn_buf);
4388 		return -EACCES;
4389 	}
4390 
4391 	return 0;
4392 }
4393 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)4394 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4395 				  const struct bpf_reg_state *reg,
4396 				  int regno, int off, int size)
4397 {
4398 	int err;
4399 
4400 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4401 	if (err)
4402 		return err;
4403 
4404 	if (off + size > env->prog->aux->max_tp_access)
4405 		env->prog->aux->max_tp_access = off + size;
4406 
4407 	return 0;
4408 }
4409 
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)4410 static int check_buffer_access(struct bpf_verifier_env *env,
4411 			       const struct bpf_reg_state *reg,
4412 			       int regno, int off, int size,
4413 			       bool zero_size_allowed,
4414 			       u32 *max_access)
4415 {
4416 	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4417 	int err;
4418 
4419 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4420 	if (err)
4421 		return err;
4422 
4423 	if (off + size > *max_access)
4424 		*max_access = off + size;
4425 
4426 	return 0;
4427 }
4428 
4429 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)4430 static void zext_32_to_64(struct bpf_reg_state *reg)
4431 {
4432 	reg->var_off = tnum_subreg(reg->var_off);
4433 	__reg_assign_32_into_64(reg);
4434 }
4435 
4436 /* truncate register to smaller size (in bytes)
4437  * must be called with size < BPF_REG_SIZE
4438  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)4439 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4440 {
4441 	u64 mask;
4442 
4443 	/* clear high bits in bit representation */
4444 	reg->var_off = tnum_cast(reg->var_off, size);
4445 
4446 	/* fix arithmetic bounds */
4447 	mask = ((u64)1 << (size * 8)) - 1;
4448 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4449 		reg->umin_value &= mask;
4450 		reg->umax_value &= mask;
4451 	} else {
4452 		reg->umin_value = 0;
4453 		reg->umax_value = mask;
4454 	}
4455 	reg->smin_value = reg->umin_value;
4456 	reg->smax_value = reg->umax_value;
4457 
4458 	/* If size is smaller than 32bit register the 32bit register
4459 	 * values are also truncated so we push 64-bit bounds into
4460 	 * 32-bit bounds. Above were truncated < 32-bits already.
4461 	 */
4462 	if (size >= 4)
4463 		return;
4464 	__reg_combine_64_into_32(reg);
4465 }
4466 
bpf_map_is_rdonly(const struct bpf_map * map)4467 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4468 {
4469 	/* A map is considered read-only if the following condition are true:
4470 	 *
4471 	 * 1) BPF program side cannot change any of the map content. The
4472 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4473 	 *    and was set at map creation time.
4474 	 * 2) The map value(s) have been initialized from user space by a
4475 	 *    loader and then "frozen", such that no new map update/delete
4476 	 *    operations from syscall side are possible for the rest of
4477 	 *    the map's lifetime from that point onwards.
4478 	 * 3) Any parallel/pending map update/delete operations from syscall
4479 	 *    side have been completed. Only after that point, it's safe to
4480 	 *    assume that map value(s) are immutable.
4481 	 */
4482 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4483 	       READ_ONCE(map->frozen) &&
4484 	       !bpf_map_write_active(map);
4485 }
4486 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)4487 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4488 {
4489 	void *ptr;
4490 	u64 addr;
4491 	int err;
4492 
4493 	err = map->ops->map_direct_value_addr(map, &addr, off);
4494 	if (err)
4495 		return err;
4496 	ptr = (void *)(long)addr + off;
4497 
4498 	switch (size) {
4499 	case sizeof(u8):
4500 		*val = (u64)*(u8 *)ptr;
4501 		break;
4502 	case sizeof(u16):
4503 		*val = (u64)*(u16 *)ptr;
4504 		break;
4505 	case sizeof(u32):
4506 		*val = (u64)*(u32 *)ptr;
4507 		break;
4508 	case sizeof(u64):
4509 		*val = *(u64 *)ptr;
4510 		break;
4511 	default:
4512 		return -EINVAL;
4513 	}
4514 	return 0;
4515 }
4516 
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)4517 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4518 				   struct bpf_reg_state *regs,
4519 				   int regno, int off, int size,
4520 				   enum bpf_access_type atype,
4521 				   int value_regno)
4522 {
4523 	struct bpf_reg_state *reg = regs + regno;
4524 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4525 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4526 	enum bpf_type_flag flag = 0;
4527 	u32 btf_id;
4528 	int ret;
4529 
4530 	if (off < 0) {
4531 		verbose(env,
4532 			"R%d is ptr_%s invalid negative access: off=%d\n",
4533 			regno, tname, off);
4534 		return -EACCES;
4535 	}
4536 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4537 		char tn_buf[48];
4538 
4539 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4540 		verbose(env,
4541 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4542 			regno, tname, off, tn_buf);
4543 		return -EACCES;
4544 	}
4545 
4546 	if (reg->type & MEM_USER) {
4547 		verbose(env,
4548 			"R%d is ptr_%s access user memory: off=%d\n",
4549 			regno, tname, off);
4550 		return -EACCES;
4551 	}
4552 
4553 	if (reg->type & MEM_PERCPU) {
4554 		verbose(env,
4555 			"R%d is ptr_%s access percpu memory: off=%d\n",
4556 			regno, tname, off);
4557 		return -EACCES;
4558 	}
4559 
4560 	if (env->ops->btf_struct_access) {
4561 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4562 						  off, size, atype, &btf_id, &flag);
4563 	} else {
4564 		if (atype != BPF_READ) {
4565 			verbose(env, "only read is supported\n");
4566 			return -EACCES;
4567 		}
4568 
4569 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4570 					atype, &btf_id, &flag);
4571 	}
4572 
4573 	if (ret < 0)
4574 		return ret;
4575 
4576 	/* If this is an untrusted pointer, all pointers formed by walking it
4577 	 * also inherit the untrusted flag.
4578 	 */
4579 	if (type_flag(reg->type) & PTR_UNTRUSTED)
4580 		flag |= PTR_UNTRUSTED;
4581 
4582 	if (atype == BPF_READ && value_regno >= 0)
4583 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4584 
4585 	return 0;
4586 }
4587 
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)4588 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4589 				   struct bpf_reg_state *regs,
4590 				   int regno, int off, int size,
4591 				   enum bpf_access_type atype,
4592 				   int value_regno)
4593 {
4594 	struct bpf_reg_state *reg = regs + regno;
4595 	struct bpf_map *map = reg->map_ptr;
4596 	enum bpf_type_flag flag = 0;
4597 	const struct btf_type *t;
4598 	const char *tname;
4599 	u32 btf_id;
4600 	int ret;
4601 
4602 	if (!btf_vmlinux) {
4603 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4604 		return -ENOTSUPP;
4605 	}
4606 
4607 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4608 		verbose(env, "map_ptr access not supported for map type %d\n",
4609 			map->map_type);
4610 		return -ENOTSUPP;
4611 	}
4612 
4613 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4614 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4615 
4616 	if (!env->allow_ptr_to_map_access) {
4617 		verbose(env,
4618 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4619 			tname);
4620 		return -EPERM;
4621 	}
4622 
4623 	if (off < 0) {
4624 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4625 			regno, tname, off);
4626 		return -EACCES;
4627 	}
4628 
4629 	if (atype != BPF_READ) {
4630 		verbose(env, "only read from %s is supported\n", tname);
4631 		return -EACCES;
4632 	}
4633 
4634 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4635 	if (ret < 0)
4636 		return ret;
4637 
4638 	if (value_regno >= 0)
4639 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4640 
4641 	return 0;
4642 }
4643 
4644 /* Check that the stack access at the given offset is within bounds. The
4645  * maximum valid offset is -1.
4646  *
4647  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4648  * -state->allocated_stack for reads.
4649  */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)4650 static int check_stack_slot_within_bounds(int off,
4651 					  struct bpf_func_state *state,
4652 					  enum bpf_access_type t)
4653 {
4654 	int min_valid_off;
4655 
4656 	if (t == BPF_WRITE)
4657 		min_valid_off = -MAX_BPF_STACK;
4658 	else
4659 		min_valid_off = -state->allocated_stack;
4660 
4661 	if (off < min_valid_off || off > -1)
4662 		return -EACCES;
4663 	return 0;
4664 }
4665 
4666 /* Check that the stack access at 'regno + off' falls within the maximum stack
4667  * bounds.
4668  *
4669  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4670  */
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)4671 static int check_stack_access_within_bounds(
4672 		struct bpf_verifier_env *env,
4673 		int regno, int off, int access_size,
4674 		enum bpf_access_src src, enum bpf_access_type type)
4675 {
4676 	struct bpf_reg_state *regs = cur_regs(env);
4677 	struct bpf_reg_state *reg = regs + regno;
4678 	struct bpf_func_state *state = func(env, reg);
4679 	int min_off, max_off;
4680 	int err;
4681 	char *err_extra;
4682 
4683 	if (src == ACCESS_HELPER)
4684 		/* We don't know if helpers are reading or writing (or both). */
4685 		err_extra = " indirect access to";
4686 	else if (type == BPF_READ)
4687 		err_extra = " read from";
4688 	else
4689 		err_extra = " write to";
4690 
4691 	if (tnum_is_const(reg->var_off)) {
4692 		min_off = reg->var_off.value + off;
4693 		if (access_size > 0)
4694 			max_off = min_off + access_size - 1;
4695 		else
4696 			max_off = min_off;
4697 	} else {
4698 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4699 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4700 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4701 				err_extra, regno);
4702 			return -EACCES;
4703 		}
4704 		min_off = reg->smin_value + off;
4705 		if (access_size > 0)
4706 			max_off = reg->smax_value + off + access_size - 1;
4707 		else
4708 			max_off = min_off;
4709 	}
4710 
4711 	err = check_stack_slot_within_bounds(min_off, state, type);
4712 	if (!err)
4713 		err = check_stack_slot_within_bounds(max_off, state, type);
4714 
4715 	if (err) {
4716 		if (tnum_is_const(reg->var_off)) {
4717 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4718 				err_extra, regno, off, access_size);
4719 		} else {
4720 			char tn_buf[48];
4721 
4722 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4723 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4724 				err_extra, regno, tn_buf, access_size);
4725 		}
4726 	}
4727 	return err;
4728 }
4729 
4730 /* check whether memory at (regno + off) is accessible for t = (read | write)
4731  * if t==write, value_regno is a register which value is stored into memory
4732  * if t==read, value_regno is a register which will receive the value from memory
4733  * if t==write && value_regno==-1, some unknown value is stored into memory
4734  * if t==read && value_regno==-1, don't care what we read from memory
4735  */
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)4736 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4737 			    int off, int bpf_size, enum bpf_access_type t,
4738 			    int value_regno, bool strict_alignment_once)
4739 {
4740 	struct bpf_reg_state *regs = cur_regs(env);
4741 	struct bpf_reg_state *reg = regs + regno;
4742 	struct bpf_func_state *state;
4743 	int size, err = 0;
4744 
4745 	size = bpf_size_to_bytes(bpf_size);
4746 	if (size < 0)
4747 		return size;
4748 
4749 	/* alignment checks will add in reg->off themselves */
4750 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4751 	if (err)
4752 		return err;
4753 
4754 	/* for access checks, reg->off is just part of off */
4755 	off += reg->off;
4756 
4757 	if (reg->type == PTR_TO_MAP_KEY) {
4758 		if (t == BPF_WRITE) {
4759 			verbose(env, "write to change key R%d not allowed\n", regno);
4760 			return -EACCES;
4761 		}
4762 
4763 		err = check_mem_region_access(env, regno, off, size,
4764 					      reg->map_ptr->key_size, false);
4765 		if (err)
4766 			return err;
4767 		if (value_regno >= 0)
4768 			mark_reg_unknown(env, regs, value_regno);
4769 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4770 		struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4771 
4772 		if (t == BPF_WRITE && value_regno >= 0 &&
4773 		    is_pointer_value(env, value_regno)) {
4774 			verbose(env, "R%d leaks addr into map\n", value_regno);
4775 			return -EACCES;
4776 		}
4777 		err = check_map_access_type(env, regno, off, size, t);
4778 		if (err)
4779 			return err;
4780 		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4781 		if (err)
4782 			return err;
4783 		if (tnum_is_const(reg->var_off))
4784 			kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4785 								  off + reg->var_off.value);
4786 		if (kptr_off_desc) {
4787 			err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4788 						    kptr_off_desc);
4789 		} else if (t == BPF_READ && value_regno >= 0) {
4790 			struct bpf_map *map = reg->map_ptr;
4791 
4792 			/* if map is read-only, track its contents as scalars */
4793 			if (tnum_is_const(reg->var_off) &&
4794 			    bpf_map_is_rdonly(map) &&
4795 			    map->ops->map_direct_value_addr) {
4796 				int map_off = off + reg->var_off.value;
4797 				u64 val = 0;
4798 
4799 				err = bpf_map_direct_read(map, map_off, size,
4800 							  &val);
4801 				if (err)
4802 					return err;
4803 
4804 				regs[value_regno].type = SCALAR_VALUE;
4805 				__mark_reg_known(&regs[value_regno], val);
4806 			} else {
4807 				mark_reg_unknown(env, regs, value_regno);
4808 			}
4809 		}
4810 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4811 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4812 
4813 		if (type_may_be_null(reg->type)) {
4814 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4815 				reg_type_str(env, reg->type));
4816 			return -EACCES;
4817 		}
4818 
4819 		if (t == BPF_WRITE && rdonly_mem) {
4820 			verbose(env, "R%d cannot write into %s\n",
4821 				regno, reg_type_str(env, reg->type));
4822 			return -EACCES;
4823 		}
4824 
4825 		if (t == BPF_WRITE && value_regno >= 0 &&
4826 		    is_pointer_value(env, value_regno)) {
4827 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4828 			return -EACCES;
4829 		}
4830 
4831 		err = check_mem_region_access(env, regno, off, size,
4832 					      reg->mem_size, false);
4833 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4834 			mark_reg_unknown(env, regs, value_regno);
4835 	} else if (reg->type == PTR_TO_CTX) {
4836 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4837 		struct btf *btf = NULL;
4838 		u32 btf_id = 0;
4839 
4840 		if (t == BPF_WRITE && value_regno >= 0 &&
4841 		    is_pointer_value(env, value_regno)) {
4842 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4843 			return -EACCES;
4844 		}
4845 
4846 		err = check_ptr_off_reg(env, reg, regno);
4847 		if (err < 0)
4848 			return err;
4849 
4850 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4851 				       &btf_id);
4852 		if (err)
4853 			verbose_linfo(env, insn_idx, "; ");
4854 		if (!err && t == BPF_READ && value_regno >= 0) {
4855 			/* ctx access returns either a scalar, or a
4856 			 * PTR_TO_PACKET[_META,_END]. In the latter
4857 			 * case, we know the offset is zero.
4858 			 */
4859 			if (reg_type == SCALAR_VALUE) {
4860 				mark_reg_unknown(env, regs, value_regno);
4861 			} else {
4862 				mark_reg_known_zero(env, regs,
4863 						    value_regno);
4864 				if (type_may_be_null(reg_type))
4865 					regs[value_regno].id = ++env->id_gen;
4866 				/* A load of ctx field could have different
4867 				 * actual load size with the one encoded in the
4868 				 * insn. When the dst is PTR, it is for sure not
4869 				 * a sub-register.
4870 				 */
4871 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4872 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4873 					regs[value_regno].btf = btf;
4874 					regs[value_regno].btf_id = btf_id;
4875 				}
4876 			}
4877 			regs[value_regno].type = reg_type;
4878 		}
4879 
4880 	} else if (reg->type == PTR_TO_STACK) {
4881 		/* Basic bounds checks. */
4882 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4883 		if (err)
4884 			return err;
4885 
4886 		state = func(env, reg);
4887 		err = update_stack_depth(env, state, off);
4888 		if (err)
4889 			return err;
4890 
4891 		if (t == BPF_READ)
4892 			err = check_stack_read(env, regno, off, size,
4893 					       value_regno);
4894 		else
4895 			err = check_stack_write(env, regno, off, size,
4896 						value_regno, insn_idx);
4897 	} else if (reg_is_pkt_pointer(reg)) {
4898 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4899 			verbose(env, "cannot write into packet\n");
4900 			return -EACCES;
4901 		}
4902 		if (t == BPF_WRITE && value_regno >= 0 &&
4903 		    is_pointer_value(env, value_regno)) {
4904 			verbose(env, "R%d leaks addr into packet\n",
4905 				value_regno);
4906 			return -EACCES;
4907 		}
4908 		err = check_packet_access(env, regno, off, size, false);
4909 		if (!err && t == BPF_READ && value_regno >= 0)
4910 			mark_reg_unknown(env, regs, value_regno);
4911 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4912 		if (t == BPF_WRITE && value_regno >= 0 &&
4913 		    is_pointer_value(env, value_regno)) {
4914 			verbose(env, "R%d leaks addr into flow keys\n",
4915 				value_regno);
4916 			return -EACCES;
4917 		}
4918 
4919 		err = check_flow_keys_access(env, off, size);
4920 		if (!err && t == BPF_READ && value_regno >= 0)
4921 			mark_reg_unknown(env, regs, value_regno);
4922 	} else if (type_is_sk_pointer(reg->type)) {
4923 		if (t == BPF_WRITE) {
4924 			verbose(env, "R%d cannot write into %s\n",
4925 				regno, reg_type_str(env, reg->type));
4926 			return -EACCES;
4927 		}
4928 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4929 		if (!err && value_regno >= 0)
4930 			mark_reg_unknown(env, regs, value_regno);
4931 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4932 		err = check_tp_buffer_access(env, reg, regno, off, size);
4933 		if (!err && t == BPF_READ && value_regno >= 0)
4934 			mark_reg_unknown(env, regs, value_regno);
4935 	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4936 		   !type_may_be_null(reg->type)) {
4937 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4938 					      value_regno);
4939 	} else if (reg->type == CONST_PTR_TO_MAP) {
4940 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4941 					      value_regno);
4942 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4943 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4944 		u32 *max_access;
4945 
4946 		if (rdonly_mem) {
4947 			if (t == BPF_WRITE) {
4948 				verbose(env, "R%d cannot write into %s\n",
4949 					regno, reg_type_str(env, reg->type));
4950 				return -EACCES;
4951 			}
4952 			max_access = &env->prog->aux->max_rdonly_access;
4953 		} else {
4954 			max_access = &env->prog->aux->max_rdwr_access;
4955 		}
4956 
4957 		err = check_buffer_access(env, reg, regno, off, size, false,
4958 					  max_access);
4959 
4960 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4961 			mark_reg_unknown(env, regs, value_regno);
4962 	} else {
4963 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4964 			reg_type_str(env, reg->type));
4965 		return -EACCES;
4966 	}
4967 
4968 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4969 	    regs[value_regno].type == SCALAR_VALUE) {
4970 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4971 		coerce_reg_to_size(&regs[value_regno], size);
4972 	}
4973 	return err;
4974 }
4975 
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)4976 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4977 {
4978 	int load_reg;
4979 	int err;
4980 
4981 	switch (insn->imm) {
4982 	case BPF_ADD:
4983 	case BPF_ADD | BPF_FETCH:
4984 	case BPF_AND:
4985 	case BPF_AND | BPF_FETCH:
4986 	case BPF_OR:
4987 	case BPF_OR | BPF_FETCH:
4988 	case BPF_XOR:
4989 	case BPF_XOR | BPF_FETCH:
4990 	case BPF_XCHG:
4991 	case BPF_CMPXCHG:
4992 		break;
4993 	default:
4994 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4995 		return -EINVAL;
4996 	}
4997 
4998 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4999 		verbose(env, "invalid atomic operand size\n");
5000 		return -EINVAL;
5001 	}
5002 
5003 	/* check src1 operand */
5004 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
5005 	if (err)
5006 		return err;
5007 
5008 	/* check src2 operand */
5009 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5010 	if (err)
5011 		return err;
5012 
5013 	if (insn->imm == BPF_CMPXCHG) {
5014 		/* Check comparison of R0 with memory location */
5015 		const u32 aux_reg = BPF_REG_0;
5016 
5017 		err = check_reg_arg(env, aux_reg, SRC_OP);
5018 		if (err)
5019 			return err;
5020 
5021 		if (is_pointer_value(env, aux_reg)) {
5022 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
5023 			return -EACCES;
5024 		}
5025 	}
5026 
5027 	if (is_pointer_value(env, insn->src_reg)) {
5028 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5029 		return -EACCES;
5030 	}
5031 
5032 	if (is_ctx_reg(env, insn->dst_reg) ||
5033 	    is_pkt_reg(env, insn->dst_reg) ||
5034 	    is_flow_key_reg(env, insn->dst_reg) ||
5035 	    is_sk_reg(env, insn->dst_reg)) {
5036 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5037 			insn->dst_reg,
5038 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5039 		return -EACCES;
5040 	}
5041 
5042 	if (insn->imm & BPF_FETCH) {
5043 		if (insn->imm == BPF_CMPXCHG)
5044 			load_reg = BPF_REG_0;
5045 		else
5046 			load_reg = insn->src_reg;
5047 
5048 		/* check and record load of old value */
5049 		err = check_reg_arg(env, load_reg, DST_OP);
5050 		if (err)
5051 			return err;
5052 	} else {
5053 		/* This instruction accesses a memory location but doesn't
5054 		 * actually load it into a register.
5055 		 */
5056 		load_reg = -1;
5057 	}
5058 
5059 	/* Check whether we can read the memory, with second call for fetch
5060 	 * case to simulate the register fill.
5061 	 */
5062 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5063 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
5064 	if (!err && load_reg >= 0)
5065 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5066 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
5067 				       true);
5068 	if (err)
5069 		return err;
5070 
5071 	/* Check whether we can write into the same memory. */
5072 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5073 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5074 	if (err)
5075 		return err;
5076 
5077 	return 0;
5078 }
5079 
5080 /* When register 'regno' is used to read the stack (either directly or through
5081  * a helper function) make sure that it's within stack boundary and, depending
5082  * on the access type, that all elements of the stack are initialized.
5083  *
5084  * 'off' includes 'regno->off', but not its dynamic part (if any).
5085  *
5086  * All registers that have been spilled on the stack in the slots within the
5087  * read offsets are marked as read.
5088  */
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)5089 static int check_stack_range_initialized(
5090 		struct bpf_verifier_env *env, int regno, int off,
5091 		int access_size, bool zero_size_allowed,
5092 		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5093 {
5094 	struct bpf_reg_state *reg = reg_state(env, regno);
5095 	struct bpf_func_state *state = func(env, reg);
5096 	int err, min_off, max_off, i, j, slot, spi;
5097 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5098 	enum bpf_access_type bounds_check_type;
5099 	/* Some accesses can write anything into the stack, others are
5100 	 * read-only.
5101 	 */
5102 	bool clobber = false;
5103 
5104 	if (access_size == 0 && !zero_size_allowed) {
5105 		verbose(env, "invalid zero-sized read\n");
5106 		return -EACCES;
5107 	}
5108 
5109 	if (type == ACCESS_HELPER) {
5110 		/* The bounds checks for writes are more permissive than for
5111 		 * reads. However, if raw_mode is not set, we'll do extra
5112 		 * checks below.
5113 		 */
5114 		bounds_check_type = BPF_WRITE;
5115 		clobber = true;
5116 	} else {
5117 		bounds_check_type = BPF_READ;
5118 	}
5119 	err = check_stack_access_within_bounds(env, regno, off, access_size,
5120 					       type, bounds_check_type);
5121 	if (err)
5122 		return err;
5123 
5124 
5125 	if (tnum_is_const(reg->var_off)) {
5126 		min_off = max_off = reg->var_off.value + off;
5127 	} else {
5128 		/* Variable offset is prohibited for unprivileged mode for
5129 		 * simplicity since it requires corresponding support in
5130 		 * Spectre masking for stack ALU.
5131 		 * See also retrieve_ptr_limit().
5132 		 */
5133 		if (!env->bypass_spec_v1) {
5134 			char tn_buf[48];
5135 
5136 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5137 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5138 				regno, err_extra, tn_buf);
5139 			return -EACCES;
5140 		}
5141 		/* Only initialized buffer on stack is allowed to be accessed
5142 		 * with variable offset. With uninitialized buffer it's hard to
5143 		 * guarantee that whole memory is marked as initialized on
5144 		 * helper return since specific bounds are unknown what may
5145 		 * cause uninitialized stack leaking.
5146 		 */
5147 		if (meta && meta->raw_mode)
5148 			meta = NULL;
5149 
5150 		min_off = reg->smin_value + off;
5151 		max_off = reg->smax_value + off;
5152 	}
5153 
5154 	if (meta && meta->raw_mode) {
5155 		meta->access_size = access_size;
5156 		meta->regno = regno;
5157 		return 0;
5158 	}
5159 
5160 	for (i = min_off; i < max_off + access_size; i++) {
5161 		u8 *stype;
5162 
5163 		slot = -i - 1;
5164 		spi = slot / BPF_REG_SIZE;
5165 		if (state->allocated_stack <= slot)
5166 			goto err;
5167 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5168 		if (*stype == STACK_MISC)
5169 			goto mark;
5170 		if (*stype == STACK_ZERO) {
5171 			if (clobber) {
5172 				/* helper can write anything into the stack */
5173 				*stype = STACK_MISC;
5174 			}
5175 			goto mark;
5176 		}
5177 
5178 		if (is_spilled_reg(&state->stack[spi]) &&
5179 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5180 		     env->allow_ptr_leaks)) {
5181 			if (clobber) {
5182 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5183 				for (j = 0; j < BPF_REG_SIZE; j++)
5184 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5185 			}
5186 			goto mark;
5187 		}
5188 
5189 err:
5190 		if (tnum_is_const(reg->var_off)) {
5191 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5192 				err_extra, regno, min_off, i - min_off, access_size);
5193 		} else {
5194 			char tn_buf[48];
5195 
5196 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5197 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5198 				err_extra, regno, tn_buf, i - min_off, access_size);
5199 		}
5200 		return -EACCES;
5201 mark:
5202 		/* reading any byte out of 8-byte 'spill_slot' will cause
5203 		 * the whole slot to be marked as 'read'
5204 		 */
5205 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
5206 			      state->stack[spi].spilled_ptr.parent,
5207 			      REG_LIVE_READ64);
5208 		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5209 		 * be sure that whether stack slot is written to or not. Hence,
5210 		 * we must still conservatively propagate reads upwards even if
5211 		 * helper may write to the entire memory range.
5212 		 */
5213 	}
5214 	return update_stack_depth(env, state, min_off);
5215 }
5216 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)5217 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5218 				   int access_size, bool zero_size_allowed,
5219 				   struct bpf_call_arg_meta *meta)
5220 {
5221 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5222 	u32 *max_access;
5223 
5224 	switch (base_type(reg->type)) {
5225 	case PTR_TO_PACKET:
5226 	case PTR_TO_PACKET_META:
5227 		return check_packet_access(env, regno, reg->off, access_size,
5228 					   zero_size_allowed);
5229 	case PTR_TO_MAP_KEY:
5230 		if (meta && meta->raw_mode) {
5231 			verbose(env, "R%d cannot write into %s\n", regno,
5232 				reg_type_str(env, reg->type));
5233 			return -EACCES;
5234 		}
5235 		return check_mem_region_access(env, regno, reg->off, access_size,
5236 					       reg->map_ptr->key_size, false);
5237 	case PTR_TO_MAP_VALUE:
5238 		if (check_map_access_type(env, regno, reg->off, access_size,
5239 					  meta && meta->raw_mode ? BPF_WRITE :
5240 					  BPF_READ))
5241 			return -EACCES;
5242 		return check_map_access(env, regno, reg->off, access_size,
5243 					zero_size_allowed, ACCESS_HELPER);
5244 	case PTR_TO_MEM:
5245 		if (type_is_rdonly_mem(reg->type)) {
5246 			if (meta && meta->raw_mode) {
5247 				verbose(env, "R%d cannot write into %s\n", regno,
5248 					reg_type_str(env, reg->type));
5249 				return -EACCES;
5250 			}
5251 		}
5252 		return check_mem_region_access(env, regno, reg->off,
5253 					       access_size, reg->mem_size,
5254 					       zero_size_allowed);
5255 	case PTR_TO_BUF:
5256 		if (type_is_rdonly_mem(reg->type)) {
5257 			if (meta && meta->raw_mode) {
5258 				verbose(env, "R%d cannot write into %s\n", regno,
5259 					reg_type_str(env, reg->type));
5260 				return -EACCES;
5261 			}
5262 
5263 			max_access = &env->prog->aux->max_rdonly_access;
5264 		} else {
5265 			max_access = &env->prog->aux->max_rdwr_access;
5266 		}
5267 		return check_buffer_access(env, reg, regno, reg->off,
5268 					   access_size, zero_size_allowed,
5269 					   max_access);
5270 	case PTR_TO_STACK:
5271 		return check_stack_range_initialized(
5272 				env,
5273 				regno, reg->off, access_size,
5274 				zero_size_allowed, ACCESS_HELPER, meta);
5275 	case PTR_TO_CTX:
5276 		/* in case the function doesn't know how to access the context,
5277 		 * (because we are in a program of type SYSCALL for example), we
5278 		 * can not statically check its size.
5279 		 * Dynamically check it now.
5280 		 */
5281 		if (!env->ops->convert_ctx_access) {
5282 			enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5283 			int offset = access_size - 1;
5284 
5285 			/* Allow zero-byte read from PTR_TO_CTX */
5286 			if (access_size == 0)
5287 				return zero_size_allowed ? 0 : -EACCES;
5288 
5289 			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5290 						atype, -1, false);
5291 		}
5292 
5293 		fallthrough;
5294 	default: /* scalar_value or invalid ptr */
5295 		/* Allow zero-byte read from NULL, regardless of pointer type */
5296 		if (zero_size_allowed && access_size == 0 &&
5297 		    register_is_null(reg))
5298 			return 0;
5299 
5300 		verbose(env, "R%d type=%s ", regno,
5301 			reg_type_str(env, reg->type));
5302 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5303 		return -EACCES;
5304 	}
5305 }
5306 
check_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,bool zero_size_allowed,struct bpf_call_arg_meta * meta)5307 static int check_mem_size_reg(struct bpf_verifier_env *env,
5308 			      struct bpf_reg_state *reg, u32 regno,
5309 			      bool zero_size_allowed,
5310 			      struct bpf_call_arg_meta *meta)
5311 {
5312 	int err;
5313 
5314 	/* This is used to refine r0 return value bounds for helpers
5315 	 * that enforce this value as an upper bound on return values.
5316 	 * See do_refine_retval_range() for helpers that can refine
5317 	 * the return value. C type of helper is u32 so we pull register
5318 	 * bound from umax_value however, if negative verifier errors
5319 	 * out. Only upper bounds can be learned because retval is an
5320 	 * int type and negative retvals are allowed.
5321 	 */
5322 	meta->msize_max_value = reg->umax_value;
5323 
5324 	/* The register is SCALAR_VALUE; the access check
5325 	 * happens using its boundaries.
5326 	 */
5327 	if (!tnum_is_const(reg->var_off))
5328 		/* For unprivileged variable accesses, disable raw
5329 		 * mode so that the program is required to
5330 		 * initialize all the memory that the helper could
5331 		 * just partially fill up.
5332 		 */
5333 		meta = NULL;
5334 
5335 	if (reg->smin_value < 0) {
5336 		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5337 			regno);
5338 		return -EACCES;
5339 	}
5340 
5341 	if (reg->umin_value == 0) {
5342 		err = check_helper_mem_access(env, regno - 1, 0,
5343 					      zero_size_allowed,
5344 					      meta);
5345 		if (err)
5346 			return err;
5347 	}
5348 
5349 	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5350 		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5351 			regno);
5352 		return -EACCES;
5353 	}
5354 	err = check_helper_mem_access(env, regno - 1,
5355 				      reg->umax_value,
5356 				      zero_size_allowed, meta);
5357 	if (!err)
5358 		err = mark_chain_precision(env, regno);
5359 	return err;
5360 }
5361 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)5362 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5363 		   u32 regno, u32 mem_size)
5364 {
5365 	bool may_be_null = type_may_be_null(reg->type);
5366 	struct bpf_reg_state saved_reg;
5367 	struct bpf_call_arg_meta meta;
5368 	int err;
5369 
5370 	if (register_is_null(reg))
5371 		return 0;
5372 
5373 	memset(&meta, 0, sizeof(meta));
5374 	/* Assuming that the register contains a value check if the memory
5375 	 * access is safe. Temporarily save and restore the register's state as
5376 	 * the conversion shouldn't be visible to a caller.
5377 	 */
5378 	if (may_be_null) {
5379 		saved_reg = *reg;
5380 		mark_ptr_not_null_reg(reg);
5381 	}
5382 
5383 	err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5384 	/* Check access for BPF_WRITE */
5385 	meta.raw_mode = true;
5386 	err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5387 
5388 	if (may_be_null)
5389 		*reg = saved_reg;
5390 
5391 	return err;
5392 }
5393 
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)5394 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5395 			     u32 regno)
5396 {
5397 	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5398 	bool may_be_null = type_may_be_null(mem_reg->type);
5399 	struct bpf_reg_state saved_reg;
5400 	struct bpf_call_arg_meta meta;
5401 	int err;
5402 
5403 	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5404 
5405 	memset(&meta, 0, sizeof(meta));
5406 
5407 	if (may_be_null) {
5408 		saved_reg = *mem_reg;
5409 		mark_ptr_not_null_reg(mem_reg);
5410 	}
5411 
5412 	err = check_mem_size_reg(env, reg, regno, true, &meta);
5413 	/* Check access for BPF_WRITE */
5414 	meta.raw_mode = true;
5415 	err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5416 
5417 	if (may_be_null)
5418 		*mem_reg = saved_reg;
5419 	return err;
5420 }
5421 
5422 /* Implementation details:
5423  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5424  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5425  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5426  * value_or_null->value transition, since the verifier only cares about
5427  * the range of access to valid map value pointer and doesn't care about actual
5428  * address of the map element.
5429  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5430  * reg->id > 0 after value_or_null->value transition. By doing so
5431  * two bpf_map_lookups will be considered two different pointers that
5432  * point to different bpf_spin_locks.
5433  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5434  * dead-locks.
5435  * Since only one bpf_spin_lock is allowed the checks are simpler than
5436  * reg_is_refcounted() logic. The verifier needs to remember only
5437  * one spin_lock instead of array of acquired_refs.
5438  * cur_state->active_spin_lock remembers which map value element got locked
5439  * and clears it after bpf_spin_unlock.
5440  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)5441 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5442 			     bool is_lock)
5443 {
5444 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5445 	struct bpf_verifier_state *cur = env->cur_state;
5446 	bool is_const = tnum_is_const(reg->var_off);
5447 	struct bpf_map *map = reg->map_ptr;
5448 	u64 val = reg->var_off.value;
5449 
5450 	if (!is_const) {
5451 		verbose(env,
5452 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5453 			regno);
5454 		return -EINVAL;
5455 	}
5456 	if (!map->btf) {
5457 		verbose(env,
5458 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
5459 			map->name);
5460 		return -EINVAL;
5461 	}
5462 	if (!map_value_has_spin_lock(map)) {
5463 		if (map->spin_lock_off == -E2BIG)
5464 			verbose(env,
5465 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
5466 				map->name);
5467 		else if (map->spin_lock_off == -ENOENT)
5468 			verbose(env,
5469 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
5470 				map->name);
5471 		else
5472 			verbose(env,
5473 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5474 				map->name);
5475 		return -EINVAL;
5476 	}
5477 	if (map->spin_lock_off != val + reg->off) {
5478 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5479 			val + reg->off);
5480 		return -EINVAL;
5481 	}
5482 	if (is_lock) {
5483 		if (cur->active_spin_lock) {
5484 			verbose(env,
5485 				"Locking two bpf_spin_locks are not allowed\n");
5486 			return -EINVAL;
5487 		}
5488 		cur->active_spin_lock = reg->id;
5489 	} else {
5490 		if (!cur->active_spin_lock) {
5491 			verbose(env, "bpf_spin_unlock without taking a lock\n");
5492 			return -EINVAL;
5493 		}
5494 		if (cur->active_spin_lock != reg->id) {
5495 			verbose(env, "bpf_spin_unlock of different lock\n");
5496 			return -EINVAL;
5497 		}
5498 		cur->active_spin_lock = 0;
5499 	}
5500 	return 0;
5501 }
5502 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)5503 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5504 			      struct bpf_call_arg_meta *meta)
5505 {
5506 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5507 	bool is_const = tnum_is_const(reg->var_off);
5508 	struct bpf_map *map = reg->map_ptr;
5509 	u64 val = reg->var_off.value;
5510 
5511 	if (!is_const) {
5512 		verbose(env,
5513 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5514 			regno);
5515 		return -EINVAL;
5516 	}
5517 	if (!map->btf) {
5518 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5519 			map->name);
5520 		return -EINVAL;
5521 	}
5522 	if (!map_value_has_timer(map)) {
5523 		if (map->timer_off == -E2BIG)
5524 			verbose(env,
5525 				"map '%s' has more than one 'struct bpf_timer'\n",
5526 				map->name);
5527 		else if (map->timer_off == -ENOENT)
5528 			verbose(env,
5529 				"map '%s' doesn't have 'struct bpf_timer'\n",
5530 				map->name);
5531 		else
5532 			verbose(env,
5533 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5534 				map->name);
5535 		return -EINVAL;
5536 	}
5537 	if (map->timer_off != val + reg->off) {
5538 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5539 			val + reg->off, map->timer_off);
5540 		return -EINVAL;
5541 	}
5542 	if (meta->map_ptr) {
5543 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5544 		return -EFAULT;
5545 	}
5546 	meta->map_uid = reg->map_uid;
5547 	meta->map_ptr = map;
5548 	return 0;
5549 }
5550 
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)5551 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5552 			     struct bpf_call_arg_meta *meta)
5553 {
5554 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5555 	struct bpf_map_value_off_desc *off_desc;
5556 	struct bpf_map *map_ptr = reg->map_ptr;
5557 	u32 kptr_off;
5558 	int ret;
5559 
5560 	if (!tnum_is_const(reg->var_off)) {
5561 		verbose(env,
5562 			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5563 			regno);
5564 		return -EINVAL;
5565 	}
5566 	if (!map_ptr->btf) {
5567 		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5568 			map_ptr->name);
5569 		return -EINVAL;
5570 	}
5571 	if (!map_value_has_kptrs(map_ptr)) {
5572 		ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5573 		if (ret == -E2BIG)
5574 			verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5575 				BPF_MAP_VALUE_OFF_MAX);
5576 		else if (ret == -EEXIST)
5577 			verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5578 		else
5579 			verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5580 		return -EINVAL;
5581 	}
5582 
5583 	meta->map_ptr = map_ptr;
5584 	kptr_off = reg->off + reg->var_off.value;
5585 	off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5586 	if (!off_desc) {
5587 		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5588 		return -EACCES;
5589 	}
5590 	if (off_desc->type != BPF_KPTR_REF) {
5591 		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5592 		return -EACCES;
5593 	}
5594 	meta->kptr_off_desc = off_desc;
5595 	return 0;
5596 }
5597 
arg_type_is_mem_size(enum bpf_arg_type type)5598 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5599 {
5600 	return type == ARG_CONST_SIZE ||
5601 	       type == ARG_CONST_SIZE_OR_ZERO;
5602 }
5603 
arg_type_is_release(enum bpf_arg_type type)5604 static bool arg_type_is_release(enum bpf_arg_type type)
5605 {
5606 	return type & OBJ_RELEASE;
5607 }
5608 
arg_type_is_dynptr(enum bpf_arg_type type)5609 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5610 {
5611 	return base_type(type) == ARG_PTR_TO_DYNPTR;
5612 }
5613 
int_ptr_type_to_size(enum bpf_arg_type type)5614 static int int_ptr_type_to_size(enum bpf_arg_type type)
5615 {
5616 	if (type == ARG_PTR_TO_INT)
5617 		return sizeof(u32);
5618 	else if (type == ARG_PTR_TO_LONG)
5619 		return sizeof(u64);
5620 
5621 	return -EINVAL;
5622 }
5623 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)5624 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5625 				 const struct bpf_call_arg_meta *meta,
5626 				 enum bpf_arg_type *arg_type)
5627 {
5628 	if (!meta->map_ptr) {
5629 		/* kernel subsystem misconfigured verifier */
5630 		verbose(env, "invalid map_ptr to access map->type\n");
5631 		return -EACCES;
5632 	}
5633 
5634 	switch (meta->map_ptr->map_type) {
5635 	case BPF_MAP_TYPE_SOCKMAP:
5636 	case BPF_MAP_TYPE_SOCKHASH:
5637 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5638 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5639 		} else {
5640 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5641 			return -EINVAL;
5642 		}
5643 		break;
5644 	case BPF_MAP_TYPE_BLOOM_FILTER:
5645 		if (meta->func_id == BPF_FUNC_map_peek_elem)
5646 			*arg_type = ARG_PTR_TO_MAP_VALUE;
5647 		break;
5648 	default:
5649 		break;
5650 	}
5651 	return 0;
5652 }
5653 
5654 struct bpf_reg_types {
5655 	const enum bpf_reg_type types[10];
5656 	u32 *btf_id;
5657 };
5658 
5659 static const struct bpf_reg_types map_key_value_types = {
5660 	.types = {
5661 		PTR_TO_STACK,
5662 		PTR_TO_PACKET,
5663 		PTR_TO_PACKET_META,
5664 		PTR_TO_MAP_KEY,
5665 		PTR_TO_MAP_VALUE,
5666 	},
5667 };
5668 
5669 static const struct bpf_reg_types sock_types = {
5670 	.types = {
5671 		PTR_TO_SOCK_COMMON,
5672 		PTR_TO_SOCKET,
5673 		PTR_TO_TCP_SOCK,
5674 		PTR_TO_XDP_SOCK,
5675 	},
5676 };
5677 
5678 #ifdef CONFIG_NET
5679 static const struct bpf_reg_types btf_id_sock_common_types = {
5680 	.types = {
5681 		PTR_TO_SOCK_COMMON,
5682 		PTR_TO_SOCKET,
5683 		PTR_TO_TCP_SOCK,
5684 		PTR_TO_XDP_SOCK,
5685 		PTR_TO_BTF_ID,
5686 	},
5687 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5688 };
5689 #endif
5690 
5691 static const struct bpf_reg_types mem_types = {
5692 	.types = {
5693 		PTR_TO_STACK,
5694 		PTR_TO_PACKET,
5695 		PTR_TO_PACKET_META,
5696 		PTR_TO_MAP_KEY,
5697 		PTR_TO_MAP_VALUE,
5698 		PTR_TO_MEM,
5699 		PTR_TO_MEM | MEM_ALLOC,
5700 		PTR_TO_BUF,
5701 	},
5702 };
5703 
5704 static const struct bpf_reg_types int_ptr_types = {
5705 	.types = {
5706 		PTR_TO_STACK,
5707 		PTR_TO_PACKET,
5708 		PTR_TO_PACKET_META,
5709 		PTR_TO_MAP_KEY,
5710 		PTR_TO_MAP_VALUE,
5711 	},
5712 };
5713 
5714 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5715 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5716 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5717 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5718 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5719 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5720 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5721 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5722 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5723 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5724 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5725 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5726 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5727 static const struct bpf_reg_types dynptr_types = {
5728 	.types = {
5729 		PTR_TO_STACK,
5730 		PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5731 	}
5732 };
5733 
5734 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5735 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5736 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5737 	[ARG_CONST_SIZE]		= &scalar_types,
5738 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5739 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5740 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5741 	[ARG_PTR_TO_CTX]		= &context_types,
5742 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5743 #ifdef CONFIG_NET
5744 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5745 #endif
5746 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5747 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5748 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5749 	[ARG_PTR_TO_MEM]		= &mem_types,
5750 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5751 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5752 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5753 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5754 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5755 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5756 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5757 	[ARG_PTR_TO_TIMER]		= &timer_types,
5758 	[ARG_PTR_TO_KPTR]		= &kptr_types,
5759 	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
5760 };
5761 
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)5762 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5763 			  enum bpf_arg_type arg_type,
5764 			  const u32 *arg_btf_id,
5765 			  struct bpf_call_arg_meta *meta)
5766 {
5767 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5768 	enum bpf_reg_type expected, type = reg->type;
5769 	const struct bpf_reg_types *compatible;
5770 	int i, j;
5771 
5772 	compatible = compatible_reg_types[base_type(arg_type)];
5773 	if (!compatible) {
5774 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5775 		return -EFAULT;
5776 	}
5777 
5778 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5779 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5780 	 *
5781 	 * Same for MAYBE_NULL:
5782 	 *
5783 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5784 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5785 	 *
5786 	 * Therefore we fold these flags depending on the arg_type before comparison.
5787 	 */
5788 	if (arg_type & MEM_RDONLY)
5789 		type &= ~MEM_RDONLY;
5790 	if (arg_type & PTR_MAYBE_NULL)
5791 		type &= ~PTR_MAYBE_NULL;
5792 
5793 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5794 		expected = compatible->types[i];
5795 		if (expected == NOT_INIT)
5796 			break;
5797 
5798 		if (type == expected)
5799 			goto found;
5800 	}
5801 
5802 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5803 	for (j = 0; j + 1 < i; j++)
5804 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5805 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5806 	return -EACCES;
5807 
5808 found:
5809 	if (reg->type == PTR_TO_BTF_ID) {
5810 		/* For bpf_sk_release, it needs to match against first member
5811 		 * 'struct sock_common', hence make an exception for it. This
5812 		 * allows bpf_sk_release to work for multiple socket types.
5813 		 */
5814 		bool strict_type_match = arg_type_is_release(arg_type) &&
5815 					 meta->func_id != BPF_FUNC_sk_release;
5816 
5817 		if (!arg_btf_id) {
5818 			if (!compatible->btf_id) {
5819 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5820 				return -EFAULT;
5821 			}
5822 			arg_btf_id = compatible->btf_id;
5823 		}
5824 
5825 		if (meta->func_id == BPF_FUNC_kptr_xchg) {
5826 			if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5827 				return -EACCES;
5828 		} else {
5829 			if (arg_btf_id == BPF_PTR_POISON) {
5830 				verbose(env, "verifier internal error:");
5831 				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5832 					regno);
5833 				return -EACCES;
5834 			}
5835 
5836 			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5837 						  btf_vmlinux, *arg_btf_id,
5838 						  strict_type_match)) {
5839 				verbose(env, "R%d is of type %s but %s is expected\n",
5840 					regno, kernel_type_name(reg->btf, reg->btf_id),
5841 					kernel_type_name(btf_vmlinux, *arg_btf_id));
5842 				return -EACCES;
5843 			}
5844 		}
5845 	}
5846 
5847 	return 0;
5848 }
5849 
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)5850 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5851 			   const struct bpf_reg_state *reg, int regno,
5852 			   enum bpf_arg_type arg_type)
5853 {
5854 	enum bpf_reg_type type = reg->type;
5855 	bool fixed_off_ok = false;
5856 
5857 	switch ((u32)type) {
5858 	/* Pointer types where reg offset is explicitly allowed: */
5859 	case PTR_TO_STACK:
5860 		if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5861 			verbose(env, "cannot pass in dynptr at an offset\n");
5862 			return -EINVAL;
5863 		}
5864 		fallthrough;
5865 	case PTR_TO_PACKET:
5866 	case PTR_TO_PACKET_META:
5867 	case PTR_TO_MAP_KEY:
5868 	case PTR_TO_MAP_VALUE:
5869 	case PTR_TO_MEM:
5870 	case PTR_TO_MEM | MEM_RDONLY:
5871 	case PTR_TO_MEM | MEM_ALLOC:
5872 	case PTR_TO_BUF:
5873 	case PTR_TO_BUF | MEM_RDONLY:
5874 	case SCALAR_VALUE:
5875 		/* Some of the argument types nevertheless require a
5876 		 * zero register offset.
5877 		 */
5878 		if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5879 			return 0;
5880 		break;
5881 	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5882 	 * fixed offset.
5883 	 */
5884 	case PTR_TO_BTF_ID:
5885 		/* When referenced PTR_TO_BTF_ID is passed to release function,
5886 		 * it's fixed offset must be 0.	In the other cases, fixed offset
5887 		 * can be non-zero.
5888 		 */
5889 		if (arg_type_is_release(arg_type) && reg->off) {
5890 			verbose(env, "R%d must have zero offset when passed to release func\n",
5891 				regno);
5892 			return -EINVAL;
5893 		}
5894 		/* For arg is release pointer, fixed_off_ok must be false, but
5895 		 * we already checked and rejected reg->off != 0 above, so set
5896 		 * to true to allow fixed offset for all other cases.
5897 		 */
5898 		fixed_off_ok = true;
5899 		break;
5900 	default:
5901 		break;
5902 	}
5903 	return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5904 }
5905 
stack_slot_get_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)5906 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5907 {
5908 	struct bpf_func_state *state = func(env, reg);
5909 	int spi = get_spi(reg->off);
5910 
5911 	return state->stack[spi].spilled_ptr.id;
5912 }
5913 
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)5914 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5915 			  struct bpf_call_arg_meta *meta,
5916 			  const struct bpf_func_proto *fn)
5917 {
5918 	u32 regno = BPF_REG_1 + arg;
5919 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5920 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5921 	enum bpf_reg_type type = reg->type;
5922 	u32 *arg_btf_id = NULL;
5923 	int err = 0;
5924 
5925 	if (arg_type == ARG_DONTCARE)
5926 		return 0;
5927 
5928 	err = check_reg_arg(env, regno, SRC_OP);
5929 	if (err)
5930 		return err;
5931 
5932 	if (arg_type == ARG_ANYTHING) {
5933 		if (is_pointer_value(env, regno)) {
5934 			verbose(env, "R%d leaks addr into helper function\n",
5935 				regno);
5936 			return -EACCES;
5937 		}
5938 		return 0;
5939 	}
5940 
5941 	if (type_is_pkt_pointer(type) &&
5942 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5943 		verbose(env, "helper access to the packet is not allowed\n");
5944 		return -EACCES;
5945 	}
5946 
5947 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5948 		err = resolve_map_arg_type(env, meta, &arg_type);
5949 		if (err)
5950 			return err;
5951 	}
5952 
5953 	if (register_is_null(reg) && type_may_be_null(arg_type))
5954 		/* A NULL register has a SCALAR_VALUE type, so skip
5955 		 * type checking.
5956 		 */
5957 		goto skip_type_check;
5958 
5959 	/* arg_btf_id and arg_size are in a union. */
5960 	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5961 		arg_btf_id = fn->arg_btf_id[arg];
5962 
5963 	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5964 	if (err)
5965 		return err;
5966 
5967 	err = check_func_arg_reg_off(env, reg, regno, arg_type);
5968 	if (err)
5969 		return err;
5970 
5971 skip_type_check:
5972 	if (arg_type_is_release(arg_type)) {
5973 		if (arg_type_is_dynptr(arg_type)) {
5974 			struct bpf_func_state *state = func(env, reg);
5975 			int spi = get_spi(reg->off);
5976 
5977 			if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5978 			    !state->stack[spi].spilled_ptr.id) {
5979 				verbose(env, "arg %d is an unacquired reference\n", regno);
5980 				return -EINVAL;
5981 			}
5982 		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
5983 			verbose(env, "R%d must be referenced when passed to release function\n",
5984 				regno);
5985 			return -EINVAL;
5986 		}
5987 		if (meta->release_regno) {
5988 			verbose(env, "verifier internal error: more than one release argument\n");
5989 			return -EFAULT;
5990 		}
5991 		meta->release_regno = regno;
5992 	}
5993 
5994 	if (reg->ref_obj_id) {
5995 		if (meta->ref_obj_id) {
5996 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5997 				regno, reg->ref_obj_id,
5998 				meta->ref_obj_id);
5999 			return -EFAULT;
6000 		}
6001 		meta->ref_obj_id = reg->ref_obj_id;
6002 	}
6003 
6004 	switch (base_type(arg_type)) {
6005 	case ARG_CONST_MAP_PTR:
6006 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6007 		if (meta->map_ptr) {
6008 			/* Use map_uid (which is unique id of inner map) to reject:
6009 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6010 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6011 			 * if (inner_map1 && inner_map2) {
6012 			 *     timer = bpf_map_lookup_elem(inner_map1);
6013 			 *     if (timer)
6014 			 *         // mismatch would have been allowed
6015 			 *         bpf_timer_init(timer, inner_map2);
6016 			 * }
6017 			 *
6018 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
6019 			 */
6020 			if (meta->map_ptr != reg->map_ptr ||
6021 			    meta->map_uid != reg->map_uid) {
6022 				verbose(env,
6023 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6024 					meta->map_uid, reg->map_uid);
6025 				return -EINVAL;
6026 			}
6027 		}
6028 		meta->map_ptr = reg->map_ptr;
6029 		meta->map_uid = reg->map_uid;
6030 		break;
6031 	case ARG_PTR_TO_MAP_KEY:
6032 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
6033 		 * check that [key, key + map->key_size) are within
6034 		 * stack limits and initialized
6035 		 */
6036 		if (!meta->map_ptr) {
6037 			/* in function declaration map_ptr must come before
6038 			 * map_key, so that it's verified and known before
6039 			 * we have to check map_key here. Otherwise it means
6040 			 * that kernel subsystem misconfigured verifier
6041 			 */
6042 			verbose(env, "invalid map_ptr to access map->key\n");
6043 			return -EACCES;
6044 		}
6045 		err = check_helper_mem_access(env, regno,
6046 					      meta->map_ptr->key_size, false,
6047 					      NULL);
6048 		break;
6049 	case ARG_PTR_TO_MAP_VALUE:
6050 		if (type_may_be_null(arg_type) && register_is_null(reg))
6051 			return 0;
6052 
6053 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
6054 		 * check [value, value + map->value_size) validity
6055 		 */
6056 		if (!meta->map_ptr) {
6057 			/* kernel subsystem misconfigured verifier */
6058 			verbose(env, "invalid map_ptr to access map->value\n");
6059 			return -EACCES;
6060 		}
6061 		meta->raw_mode = arg_type & MEM_UNINIT;
6062 		err = check_helper_mem_access(env, regno,
6063 					      meta->map_ptr->value_size, false,
6064 					      meta);
6065 		break;
6066 	case ARG_PTR_TO_PERCPU_BTF_ID:
6067 		if (!reg->btf_id) {
6068 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6069 			return -EACCES;
6070 		}
6071 		meta->ret_btf = reg->btf;
6072 		meta->ret_btf_id = reg->btf_id;
6073 		break;
6074 	case ARG_PTR_TO_SPIN_LOCK:
6075 		if (meta->func_id == BPF_FUNC_spin_lock) {
6076 			if (process_spin_lock(env, regno, true))
6077 				return -EACCES;
6078 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
6079 			if (process_spin_lock(env, regno, false))
6080 				return -EACCES;
6081 		} else {
6082 			verbose(env, "verifier internal error\n");
6083 			return -EFAULT;
6084 		}
6085 		break;
6086 	case ARG_PTR_TO_TIMER:
6087 		if (process_timer_func(env, regno, meta))
6088 			return -EACCES;
6089 		break;
6090 	case ARG_PTR_TO_FUNC:
6091 		meta->subprogno = reg->subprogno;
6092 		break;
6093 	case ARG_PTR_TO_MEM:
6094 		/* The access to this pointer is only checked when we hit the
6095 		 * next is_mem_size argument below.
6096 		 */
6097 		meta->raw_mode = arg_type & MEM_UNINIT;
6098 		if (arg_type & MEM_FIXED_SIZE) {
6099 			err = check_helper_mem_access(env, regno,
6100 						      fn->arg_size[arg], false,
6101 						      meta);
6102 		}
6103 		break;
6104 	case ARG_CONST_SIZE:
6105 		err = check_mem_size_reg(env, reg, regno, false, meta);
6106 		break;
6107 	case ARG_CONST_SIZE_OR_ZERO:
6108 		err = check_mem_size_reg(env, reg, regno, true, meta);
6109 		break;
6110 	case ARG_PTR_TO_DYNPTR:
6111 		/* We only need to check for initialized / uninitialized helper
6112 		 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6113 		 * assumption is that if it is, that a helper function
6114 		 * initialized the dynptr on behalf of the BPF program.
6115 		 */
6116 		if (base_type(reg->type) == PTR_TO_DYNPTR)
6117 			break;
6118 		if (arg_type & MEM_UNINIT) {
6119 			if (!is_dynptr_reg_valid_uninit(env, reg)) {
6120 				verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6121 				return -EINVAL;
6122 			}
6123 
6124 			/* We only support one dynptr being uninitialized at the moment,
6125 			 * which is sufficient for the helper functions we have right now.
6126 			 */
6127 			if (meta->uninit_dynptr_regno) {
6128 				verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6129 				return -EFAULT;
6130 			}
6131 
6132 			meta->uninit_dynptr_regno = regno;
6133 		} else if (!is_dynptr_reg_valid_init(env, reg)) {
6134 			verbose(env,
6135 				"Expected an initialized dynptr as arg #%d\n",
6136 				arg + 1);
6137 			return -EINVAL;
6138 		} else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6139 			const char *err_extra = "";
6140 
6141 			switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6142 			case DYNPTR_TYPE_LOCAL:
6143 				err_extra = "local";
6144 				break;
6145 			case DYNPTR_TYPE_RINGBUF:
6146 				err_extra = "ringbuf";
6147 				break;
6148 			default:
6149 				err_extra = "<unknown>";
6150 				break;
6151 			}
6152 			verbose(env,
6153 				"Expected a dynptr of type %s as arg #%d\n",
6154 				err_extra, arg + 1);
6155 			return -EINVAL;
6156 		}
6157 		break;
6158 	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6159 		if (!tnum_is_const(reg->var_off)) {
6160 			verbose(env, "R%d is not a known constant'\n",
6161 				regno);
6162 			return -EACCES;
6163 		}
6164 		meta->mem_size = reg->var_off.value;
6165 		err = mark_chain_precision(env, regno);
6166 		if (err)
6167 			return err;
6168 		break;
6169 	case ARG_PTR_TO_INT:
6170 	case ARG_PTR_TO_LONG:
6171 	{
6172 		int size = int_ptr_type_to_size(arg_type);
6173 
6174 		err = check_helper_mem_access(env, regno, size, false, meta);
6175 		if (err)
6176 			return err;
6177 		err = check_ptr_alignment(env, reg, 0, size, true);
6178 		break;
6179 	}
6180 	case ARG_PTR_TO_CONST_STR:
6181 	{
6182 		struct bpf_map *map = reg->map_ptr;
6183 		int map_off;
6184 		u64 map_addr;
6185 		char *str_ptr;
6186 
6187 		if (!bpf_map_is_rdonly(map)) {
6188 			verbose(env, "R%d does not point to a readonly map'\n", regno);
6189 			return -EACCES;
6190 		}
6191 
6192 		if (!tnum_is_const(reg->var_off)) {
6193 			verbose(env, "R%d is not a constant address'\n", regno);
6194 			return -EACCES;
6195 		}
6196 
6197 		if (!map->ops->map_direct_value_addr) {
6198 			verbose(env, "no direct value access support for this map type\n");
6199 			return -EACCES;
6200 		}
6201 
6202 		err = check_map_access(env, regno, reg->off,
6203 				       map->value_size - reg->off, false,
6204 				       ACCESS_HELPER);
6205 		if (err)
6206 			return err;
6207 
6208 		map_off = reg->off + reg->var_off.value;
6209 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6210 		if (err) {
6211 			verbose(env, "direct value access on string failed\n");
6212 			return err;
6213 		}
6214 
6215 		str_ptr = (char *)(long)(map_addr);
6216 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6217 			verbose(env, "string is not zero-terminated\n");
6218 			return -EINVAL;
6219 		}
6220 		break;
6221 	}
6222 	case ARG_PTR_TO_KPTR:
6223 		if (process_kptr_func(env, regno, meta))
6224 			return -EACCES;
6225 		break;
6226 	}
6227 
6228 	return err;
6229 }
6230 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)6231 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6232 {
6233 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6234 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6235 
6236 	if (func_id != BPF_FUNC_map_update_elem)
6237 		return false;
6238 
6239 	/* It's not possible to get access to a locked struct sock in these
6240 	 * contexts, so updating is safe.
6241 	 */
6242 	switch (type) {
6243 	case BPF_PROG_TYPE_TRACING:
6244 		if (eatype == BPF_TRACE_ITER)
6245 			return true;
6246 		break;
6247 	case BPF_PROG_TYPE_SOCKET_FILTER:
6248 	case BPF_PROG_TYPE_SCHED_CLS:
6249 	case BPF_PROG_TYPE_SCHED_ACT:
6250 	case BPF_PROG_TYPE_XDP:
6251 	case BPF_PROG_TYPE_SK_REUSEPORT:
6252 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
6253 	case BPF_PROG_TYPE_SK_LOOKUP:
6254 		return true;
6255 	default:
6256 		break;
6257 	}
6258 
6259 	verbose(env, "cannot update sockmap in this context\n");
6260 	return false;
6261 }
6262 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)6263 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6264 {
6265 	return env->prog->jit_requested &&
6266 	       bpf_jit_supports_subprog_tailcalls();
6267 }
6268 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)6269 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6270 					struct bpf_map *map, int func_id)
6271 {
6272 	if (!map)
6273 		return 0;
6274 
6275 	/* We need a two way check, first is from map perspective ... */
6276 	switch (map->map_type) {
6277 	case BPF_MAP_TYPE_PROG_ARRAY:
6278 		if (func_id != BPF_FUNC_tail_call)
6279 			goto error;
6280 		break;
6281 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6282 		if (func_id != BPF_FUNC_perf_event_read &&
6283 		    func_id != BPF_FUNC_perf_event_output &&
6284 		    func_id != BPF_FUNC_skb_output &&
6285 		    func_id != BPF_FUNC_perf_event_read_value &&
6286 		    func_id != BPF_FUNC_xdp_output)
6287 			goto error;
6288 		break;
6289 	case BPF_MAP_TYPE_RINGBUF:
6290 		if (func_id != BPF_FUNC_ringbuf_output &&
6291 		    func_id != BPF_FUNC_ringbuf_reserve &&
6292 		    func_id != BPF_FUNC_ringbuf_query &&
6293 		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6294 		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6295 		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
6296 			goto error;
6297 		break;
6298 	case BPF_MAP_TYPE_USER_RINGBUF:
6299 		if (func_id != BPF_FUNC_user_ringbuf_drain)
6300 			goto error;
6301 		break;
6302 	case BPF_MAP_TYPE_STACK_TRACE:
6303 		if (func_id != BPF_FUNC_get_stackid)
6304 			goto error;
6305 		break;
6306 	case BPF_MAP_TYPE_CGROUP_ARRAY:
6307 		if (func_id != BPF_FUNC_skb_under_cgroup &&
6308 		    func_id != BPF_FUNC_current_task_under_cgroup)
6309 			goto error;
6310 		break;
6311 	case BPF_MAP_TYPE_CGROUP_STORAGE:
6312 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6313 		if (func_id != BPF_FUNC_get_local_storage)
6314 			goto error;
6315 		break;
6316 	case BPF_MAP_TYPE_DEVMAP:
6317 	case BPF_MAP_TYPE_DEVMAP_HASH:
6318 		if (func_id != BPF_FUNC_redirect_map &&
6319 		    func_id != BPF_FUNC_map_lookup_elem)
6320 			goto error;
6321 		break;
6322 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
6323 	 * appear.
6324 	 */
6325 	case BPF_MAP_TYPE_CPUMAP:
6326 		if (func_id != BPF_FUNC_redirect_map)
6327 			goto error;
6328 		break;
6329 	case BPF_MAP_TYPE_XSKMAP:
6330 		if (func_id != BPF_FUNC_redirect_map &&
6331 		    func_id != BPF_FUNC_map_lookup_elem)
6332 			goto error;
6333 		break;
6334 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6335 	case BPF_MAP_TYPE_HASH_OF_MAPS:
6336 		if (func_id != BPF_FUNC_map_lookup_elem)
6337 			goto error;
6338 		break;
6339 	case BPF_MAP_TYPE_SOCKMAP:
6340 		if (func_id != BPF_FUNC_sk_redirect_map &&
6341 		    func_id != BPF_FUNC_sock_map_update &&
6342 		    func_id != BPF_FUNC_map_delete_elem &&
6343 		    func_id != BPF_FUNC_msg_redirect_map &&
6344 		    func_id != BPF_FUNC_sk_select_reuseport &&
6345 		    func_id != BPF_FUNC_map_lookup_elem &&
6346 		    !may_update_sockmap(env, func_id))
6347 			goto error;
6348 		break;
6349 	case BPF_MAP_TYPE_SOCKHASH:
6350 		if (func_id != BPF_FUNC_sk_redirect_hash &&
6351 		    func_id != BPF_FUNC_sock_hash_update &&
6352 		    func_id != BPF_FUNC_map_delete_elem &&
6353 		    func_id != BPF_FUNC_msg_redirect_hash &&
6354 		    func_id != BPF_FUNC_sk_select_reuseport &&
6355 		    func_id != BPF_FUNC_map_lookup_elem &&
6356 		    !may_update_sockmap(env, func_id))
6357 			goto error;
6358 		break;
6359 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6360 		if (func_id != BPF_FUNC_sk_select_reuseport)
6361 			goto error;
6362 		break;
6363 	case BPF_MAP_TYPE_QUEUE:
6364 	case BPF_MAP_TYPE_STACK:
6365 		if (func_id != BPF_FUNC_map_peek_elem &&
6366 		    func_id != BPF_FUNC_map_pop_elem &&
6367 		    func_id != BPF_FUNC_map_push_elem)
6368 			goto error;
6369 		break;
6370 	case BPF_MAP_TYPE_SK_STORAGE:
6371 		if (func_id != BPF_FUNC_sk_storage_get &&
6372 		    func_id != BPF_FUNC_sk_storage_delete)
6373 			goto error;
6374 		break;
6375 	case BPF_MAP_TYPE_INODE_STORAGE:
6376 		if (func_id != BPF_FUNC_inode_storage_get &&
6377 		    func_id != BPF_FUNC_inode_storage_delete)
6378 			goto error;
6379 		break;
6380 	case BPF_MAP_TYPE_TASK_STORAGE:
6381 		if (func_id != BPF_FUNC_task_storage_get &&
6382 		    func_id != BPF_FUNC_task_storage_delete)
6383 			goto error;
6384 		break;
6385 	case BPF_MAP_TYPE_BLOOM_FILTER:
6386 		if (func_id != BPF_FUNC_map_peek_elem &&
6387 		    func_id != BPF_FUNC_map_push_elem)
6388 			goto error;
6389 		break;
6390 	default:
6391 		break;
6392 	}
6393 
6394 	/* ... and second from the function itself. */
6395 	switch (func_id) {
6396 	case BPF_FUNC_tail_call:
6397 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6398 			goto error;
6399 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6400 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6401 			return -EINVAL;
6402 		}
6403 		break;
6404 	case BPF_FUNC_perf_event_read:
6405 	case BPF_FUNC_perf_event_output:
6406 	case BPF_FUNC_perf_event_read_value:
6407 	case BPF_FUNC_skb_output:
6408 	case BPF_FUNC_xdp_output:
6409 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6410 			goto error;
6411 		break;
6412 	case BPF_FUNC_ringbuf_output:
6413 	case BPF_FUNC_ringbuf_reserve:
6414 	case BPF_FUNC_ringbuf_query:
6415 	case BPF_FUNC_ringbuf_reserve_dynptr:
6416 	case BPF_FUNC_ringbuf_submit_dynptr:
6417 	case BPF_FUNC_ringbuf_discard_dynptr:
6418 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6419 			goto error;
6420 		break;
6421 	case BPF_FUNC_user_ringbuf_drain:
6422 		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6423 			goto error;
6424 		break;
6425 	case BPF_FUNC_get_stackid:
6426 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6427 			goto error;
6428 		break;
6429 	case BPF_FUNC_current_task_under_cgroup:
6430 	case BPF_FUNC_skb_under_cgroup:
6431 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6432 			goto error;
6433 		break;
6434 	case BPF_FUNC_redirect_map:
6435 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6436 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6437 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
6438 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
6439 			goto error;
6440 		break;
6441 	case BPF_FUNC_sk_redirect_map:
6442 	case BPF_FUNC_msg_redirect_map:
6443 	case BPF_FUNC_sock_map_update:
6444 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6445 			goto error;
6446 		break;
6447 	case BPF_FUNC_sk_redirect_hash:
6448 	case BPF_FUNC_msg_redirect_hash:
6449 	case BPF_FUNC_sock_hash_update:
6450 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6451 			goto error;
6452 		break;
6453 	case BPF_FUNC_get_local_storage:
6454 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6455 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6456 			goto error;
6457 		break;
6458 	case BPF_FUNC_sk_select_reuseport:
6459 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6460 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6461 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
6462 			goto error;
6463 		break;
6464 	case BPF_FUNC_map_pop_elem:
6465 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6466 		    map->map_type != BPF_MAP_TYPE_STACK)
6467 			goto error;
6468 		break;
6469 	case BPF_FUNC_map_peek_elem:
6470 	case BPF_FUNC_map_push_elem:
6471 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6472 		    map->map_type != BPF_MAP_TYPE_STACK &&
6473 		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6474 			goto error;
6475 		break;
6476 	case BPF_FUNC_map_lookup_percpu_elem:
6477 		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6478 		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6479 		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6480 			goto error;
6481 		break;
6482 	case BPF_FUNC_sk_storage_get:
6483 	case BPF_FUNC_sk_storage_delete:
6484 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6485 			goto error;
6486 		break;
6487 	case BPF_FUNC_inode_storage_get:
6488 	case BPF_FUNC_inode_storage_delete:
6489 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6490 			goto error;
6491 		break;
6492 	case BPF_FUNC_task_storage_get:
6493 	case BPF_FUNC_task_storage_delete:
6494 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6495 			goto error;
6496 		break;
6497 	default:
6498 		break;
6499 	}
6500 
6501 	return 0;
6502 error:
6503 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
6504 		map->map_type, func_id_name(func_id), func_id);
6505 	return -EINVAL;
6506 }
6507 
check_raw_mode_ok(const struct bpf_func_proto * fn)6508 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6509 {
6510 	int count = 0;
6511 
6512 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6513 		count++;
6514 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6515 		count++;
6516 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6517 		count++;
6518 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6519 		count++;
6520 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6521 		count++;
6522 
6523 	/* We only support one arg being in raw mode at the moment,
6524 	 * which is sufficient for the helper functions we have
6525 	 * right now.
6526 	 */
6527 	return count <= 1;
6528 }
6529 
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)6530 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6531 {
6532 	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6533 	bool has_size = fn->arg_size[arg] != 0;
6534 	bool is_next_size = false;
6535 
6536 	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6537 		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6538 
6539 	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6540 		return is_next_size;
6541 
6542 	return has_size == is_next_size || is_next_size == is_fixed;
6543 }
6544 
check_arg_pair_ok(const struct bpf_func_proto * fn)6545 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6546 {
6547 	/* bpf_xxx(..., buf, len) call will access 'len'
6548 	 * bytes from memory 'buf'. Both arg types need
6549 	 * to be paired, so make sure there's no buggy
6550 	 * helper function specification.
6551 	 */
6552 	if (arg_type_is_mem_size(fn->arg1_type) ||
6553 	    check_args_pair_invalid(fn, 0) ||
6554 	    check_args_pair_invalid(fn, 1) ||
6555 	    check_args_pair_invalid(fn, 2) ||
6556 	    check_args_pair_invalid(fn, 3) ||
6557 	    check_args_pair_invalid(fn, 4))
6558 		return false;
6559 
6560 	return true;
6561 }
6562 
check_btf_id_ok(const struct bpf_func_proto * fn)6563 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6564 {
6565 	int i;
6566 
6567 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6568 		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6569 			return false;
6570 
6571 		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6572 		    /* arg_btf_id and arg_size are in a union. */
6573 		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6574 		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6575 			return false;
6576 	}
6577 
6578 	return true;
6579 }
6580 
check_func_proto(const struct bpf_func_proto * fn,int func_id)6581 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6582 {
6583 	return check_raw_mode_ok(fn) &&
6584 	       check_arg_pair_ok(fn) &&
6585 	       check_btf_id_ok(fn) ? 0 : -EINVAL;
6586 }
6587 
6588 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6589  * are now invalid, so turn them into unknown SCALAR_VALUE.
6590  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)6591 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6592 {
6593 	struct bpf_func_state *state;
6594 	struct bpf_reg_state *reg;
6595 
6596 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6597 		if (reg_is_pkt_pointer_any(reg))
6598 			__mark_reg_unknown(env, reg);
6599 	}));
6600 }
6601 
6602 enum {
6603 	AT_PKT_END = -1,
6604 	BEYOND_PKT_END = -2,
6605 };
6606 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)6607 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6608 {
6609 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6610 	struct bpf_reg_state *reg = &state->regs[regn];
6611 
6612 	if (reg->type != PTR_TO_PACKET)
6613 		/* PTR_TO_PACKET_META is not supported yet */
6614 		return;
6615 
6616 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6617 	 * How far beyond pkt_end it goes is unknown.
6618 	 * if (!range_open) it's the case of pkt >= pkt_end
6619 	 * if (range_open) it's the case of pkt > pkt_end
6620 	 * hence this pointer is at least 1 byte bigger than pkt_end
6621 	 */
6622 	if (range_open)
6623 		reg->range = BEYOND_PKT_END;
6624 	else
6625 		reg->range = AT_PKT_END;
6626 }
6627 
6628 /* The pointer with the specified id has released its reference to kernel
6629  * resources. Identify all copies of the same pointer and clear the reference.
6630  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)6631 static int release_reference(struct bpf_verifier_env *env,
6632 			     int ref_obj_id)
6633 {
6634 	struct bpf_func_state *state;
6635 	struct bpf_reg_state *reg;
6636 	int err;
6637 
6638 	err = release_reference_state(cur_func(env), ref_obj_id);
6639 	if (err)
6640 		return err;
6641 
6642 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6643 		if (reg->ref_obj_id == ref_obj_id) {
6644 			if (!env->allow_ptr_leaks)
6645 				__mark_reg_not_init(env, reg);
6646 			else
6647 				__mark_reg_unknown(env, reg);
6648 		}
6649 	}));
6650 
6651 	return 0;
6652 }
6653 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)6654 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6655 				    struct bpf_reg_state *regs)
6656 {
6657 	int i;
6658 
6659 	/* after the call registers r0 - r5 were scratched */
6660 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6661 		mark_reg_not_init(env, regs, caller_saved[i]);
6662 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6663 	}
6664 }
6665 
6666 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6667 				   struct bpf_func_state *caller,
6668 				   struct bpf_func_state *callee,
6669 				   int insn_idx);
6670 
__check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx,int subprog,set_callee_state_fn set_callee_state_cb)6671 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6672 			     int *insn_idx, int subprog,
6673 			     set_callee_state_fn set_callee_state_cb)
6674 {
6675 	struct bpf_verifier_state *state = env->cur_state;
6676 	struct bpf_func_info_aux *func_info_aux;
6677 	struct bpf_func_state *caller, *callee;
6678 	int err;
6679 	bool is_global = false;
6680 
6681 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6682 		verbose(env, "the call stack of %d frames is too deep\n",
6683 			state->curframe + 2);
6684 		return -E2BIG;
6685 	}
6686 
6687 	caller = state->frame[state->curframe];
6688 	if (state->frame[state->curframe + 1]) {
6689 		verbose(env, "verifier bug. Frame %d already allocated\n",
6690 			state->curframe + 1);
6691 		return -EFAULT;
6692 	}
6693 
6694 	func_info_aux = env->prog->aux->func_info_aux;
6695 	if (func_info_aux)
6696 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6697 	err = btf_check_subprog_call(env, subprog, caller->regs);
6698 	if (err == -EFAULT)
6699 		return err;
6700 	if (is_global) {
6701 		if (err) {
6702 			verbose(env, "Caller passes invalid args into func#%d\n",
6703 				subprog);
6704 			return err;
6705 		} else {
6706 			if (env->log.level & BPF_LOG_LEVEL)
6707 				verbose(env,
6708 					"Func#%d is global and valid. Skipping.\n",
6709 					subprog);
6710 			clear_caller_saved_regs(env, caller->regs);
6711 
6712 			/* All global functions return a 64-bit SCALAR_VALUE */
6713 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6714 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6715 
6716 			/* continue with next insn after call */
6717 			return 0;
6718 		}
6719 	}
6720 
6721 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6722 	    insn->src_reg == 0 &&
6723 	    insn->imm == BPF_FUNC_timer_set_callback) {
6724 		struct bpf_verifier_state *async_cb;
6725 
6726 		/* there is no real recursion here. timer callbacks are async */
6727 		env->subprog_info[subprog].is_async_cb = true;
6728 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6729 					 *insn_idx, subprog);
6730 		if (!async_cb)
6731 			return -EFAULT;
6732 		callee = async_cb->frame[0];
6733 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6734 
6735 		/* Convert bpf_timer_set_callback() args into timer callback args */
6736 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6737 		if (err)
6738 			return err;
6739 
6740 		clear_caller_saved_regs(env, caller->regs);
6741 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6742 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6743 		/* continue with next insn after call */
6744 		return 0;
6745 	}
6746 
6747 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6748 	if (!callee)
6749 		return -ENOMEM;
6750 	state->frame[state->curframe + 1] = callee;
6751 
6752 	/* callee cannot access r0, r6 - r9 for reading and has to write
6753 	 * into its own stack before reading from it.
6754 	 * callee can read/write into caller's stack
6755 	 */
6756 	init_func_state(env, callee,
6757 			/* remember the callsite, it will be used by bpf_exit */
6758 			*insn_idx /* callsite */,
6759 			state->curframe + 1 /* frameno within this callchain */,
6760 			subprog /* subprog number within this prog */);
6761 
6762 	/* Transfer references to the callee */
6763 	err = copy_reference_state(callee, caller);
6764 	if (err)
6765 		goto err_out;
6766 
6767 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6768 	if (err)
6769 		goto err_out;
6770 
6771 	clear_caller_saved_regs(env, caller->regs);
6772 
6773 	/* only increment it after check_reg_arg() finished */
6774 	state->curframe++;
6775 
6776 	/* and go analyze first insn of the callee */
6777 	*insn_idx = env->subprog_info[subprog].start - 1;
6778 
6779 	if (env->log.level & BPF_LOG_LEVEL) {
6780 		verbose(env, "caller:\n");
6781 		print_verifier_state(env, caller, true);
6782 		verbose(env, "callee:\n");
6783 		print_verifier_state(env, callee, true);
6784 	}
6785 	return 0;
6786 
6787 err_out:
6788 	free_func_state(callee);
6789 	state->frame[state->curframe + 1] = NULL;
6790 	return err;
6791 }
6792 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)6793 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6794 				   struct bpf_func_state *caller,
6795 				   struct bpf_func_state *callee)
6796 {
6797 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6798 	 *      void *callback_ctx, u64 flags);
6799 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6800 	 *      void *callback_ctx);
6801 	 */
6802 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6803 
6804 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6805 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6806 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6807 
6808 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6809 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6810 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6811 
6812 	/* pointer to stack or null */
6813 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6814 
6815 	/* unused */
6816 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6817 	return 0;
6818 }
6819 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6820 static int set_callee_state(struct bpf_verifier_env *env,
6821 			    struct bpf_func_state *caller,
6822 			    struct bpf_func_state *callee, int insn_idx)
6823 {
6824 	int i;
6825 
6826 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6827 	 * pointers, which connects us up to the liveness chain
6828 	 */
6829 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6830 		callee->regs[i] = caller->regs[i];
6831 	return 0;
6832 }
6833 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)6834 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6835 			   int *insn_idx)
6836 {
6837 	int subprog, target_insn;
6838 
6839 	target_insn = *insn_idx + insn->imm + 1;
6840 	subprog = find_subprog(env, target_insn);
6841 	if (subprog < 0) {
6842 		verbose(env, "verifier bug. No program starts at insn %d\n",
6843 			target_insn);
6844 		return -EFAULT;
6845 	}
6846 
6847 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6848 }
6849 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6850 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6851 				       struct bpf_func_state *caller,
6852 				       struct bpf_func_state *callee,
6853 				       int insn_idx)
6854 {
6855 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6856 	struct bpf_map *map;
6857 	int err;
6858 
6859 	if (bpf_map_ptr_poisoned(insn_aux)) {
6860 		verbose(env, "tail_call abusing map_ptr\n");
6861 		return -EINVAL;
6862 	}
6863 
6864 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6865 	if (!map->ops->map_set_for_each_callback_args ||
6866 	    !map->ops->map_for_each_callback) {
6867 		verbose(env, "callback function not allowed for map\n");
6868 		return -ENOTSUPP;
6869 	}
6870 
6871 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6872 	if (err)
6873 		return err;
6874 
6875 	callee->in_callback_fn = true;
6876 	callee->callback_ret_range = tnum_range(0, 1);
6877 	return 0;
6878 }
6879 
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6880 static int set_loop_callback_state(struct bpf_verifier_env *env,
6881 				   struct bpf_func_state *caller,
6882 				   struct bpf_func_state *callee,
6883 				   int insn_idx)
6884 {
6885 	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6886 	 *	    u64 flags);
6887 	 * callback_fn(u32 index, void *callback_ctx);
6888 	 */
6889 	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6890 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6891 
6892 	/* unused */
6893 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6894 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6895 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6896 
6897 	callee->in_callback_fn = true;
6898 	callee->callback_ret_range = tnum_range(0, 1);
6899 	return 0;
6900 }
6901 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6902 static int set_timer_callback_state(struct bpf_verifier_env *env,
6903 				    struct bpf_func_state *caller,
6904 				    struct bpf_func_state *callee,
6905 				    int insn_idx)
6906 {
6907 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6908 
6909 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6910 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6911 	 */
6912 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6913 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6914 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6915 
6916 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6917 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6918 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6919 
6920 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6921 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6922 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6923 
6924 	/* unused */
6925 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6926 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6927 	callee->in_async_callback_fn = true;
6928 	callee->callback_ret_range = tnum_range(0, 1);
6929 	return 0;
6930 }
6931 
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6932 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6933 				       struct bpf_func_state *caller,
6934 				       struct bpf_func_state *callee,
6935 				       int insn_idx)
6936 {
6937 	/* bpf_find_vma(struct task_struct *task, u64 addr,
6938 	 *               void *callback_fn, void *callback_ctx, u64 flags)
6939 	 * (callback_fn)(struct task_struct *task,
6940 	 *               struct vm_area_struct *vma, void *callback_ctx);
6941 	 */
6942 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6943 
6944 	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6945 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6946 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6947 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6948 
6949 	/* pointer to stack or null */
6950 	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6951 
6952 	/* unused */
6953 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6954 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6955 	callee->in_callback_fn = true;
6956 	callee->callback_ret_range = tnum_range(0, 1);
6957 	return 0;
6958 }
6959 
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6960 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6961 					   struct bpf_func_state *caller,
6962 					   struct bpf_func_state *callee,
6963 					   int insn_idx)
6964 {
6965 	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6966 	 *			  callback_ctx, u64 flags);
6967 	 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6968 	 */
6969 	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6970 	callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6971 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6972 	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6973 
6974 	/* unused */
6975 	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6976 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6977 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6978 
6979 	callee->in_callback_fn = true;
6980 	callee->callback_ret_range = tnum_range(0, 1);
6981 	return 0;
6982 }
6983 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)6984 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6985 {
6986 	struct bpf_verifier_state *state = env->cur_state;
6987 	struct bpf_func_state *caller, *callee;
6988 	struct bpf_reg_state *r0;
6989 	int err;
6990 
6991 	callee = state->frame[state->curframe];
6992 	r0 = &callee->regs[BPF_REG_0];
6993 	if (r0->type == PTR_TO_STACK) {
6994 		/* technically it's ok to return caller's stack pointer
6995 		 * (or caller's caller's pointer) back to the caller,
6996 		 * since these pointers are valid. Only current stack
6997 		 * pointer will be invalid as soon as function exits,
6998 		 * but let's be conservative
6999 		 */
7000 		verbose(env, "cannot return stack pointer to the caller\n");
7001 		return -EINVAL;
7002 	}
7003 
7004 	caller = state->frame[state->curframe - 1];
7005 	if (callee->in_callback_fn) {
7006 		/* enforce R0 return value range [0, 1]. */
7007 		struct tnum range = callee->callback_ret_range;
7008 
7009 		if (r0->type != SCALAR_VALUE) {
7010 			verbose(env, "R0 not a scalar value\n");
7011 			return -EACCES;
7012 		}
7013 		if (!tnum_in(range, r0->var_off)) {
7014 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7015 			return -EINVAL;
7016 		}
7017 	} else {
7018 		/* return to the caller whatever r0 had in the callee */
7019 		caller->regs[BPF_REG_0] = *r0;
7020 	}
7021 
7022 	/* callback_fn frame should have released its own additions to parent's
7023 	 * reference state at this point, or check_reference_leak would
7024 	 * complain, hence it must be the same as the caller. There is no need
7025 	 * to copy it back.
7026 	 */
7027 	if (!callee->in_callback_fn) {
7028 		/* Transfer references to the caller */
7029 		err = copy_reference_state(caller, callee);
7030 		if (err)
7031 			return err;
7032 	}
7033 
7034 	*insn_idx = callee->callsite + 1;
7035 	if (env->log.level & BPF_LOG_LEVEL) {
7036 		verbose(env, "returning from callee:\n");
7037 		print_verifier_state(env, callee, true);
7038 		verbose(env, "to caller at %d:\n", *insn_idx);
7039 		print_verifier_state(env, caller, true);
7040 	}
7041 	/* clear everything in the callee */
7042 	free_func_state(callee);
7043 	state->frame[state->curframe--] = NULL;
7044 	return 0;
7045 }
7046 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)7047 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7048 				   int func_id,
7049 				   struct bpf_call_arg_meta *meta)
7050 {
7051 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7052 
7053 	if (ret_type != RET_INTEGER ||
7054 	    (func_id != BPF_FUNC_get_stack &&
7055 	     func_id != BPF_FUNC_get_task_stack &&
7056 	     func_id != BPF_FUNC_probe_read_str &&
7057 	     func_id != BPF_FUNC_probe_read_kernel_str &&
7058 	     func_id != BPF_FUNC_probe_read_user_str))
7059 		return;
7060 
7061 	ret_reg->smax_value = meta->msize_max_value;
7062 	ret_reg->s32_max_value = meta->msize_max_value;
7063 	ret_reg->smin_value = -MAX_ERRNO;
7064 	ret_reg->s32_min_value = -MAX_ERRNO;
7065 	reg_bounds_sync(ret_reg);
7066 }
7067 
7068 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)7069 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7070 		int func_id, int insn_idx)
7071 {
7072 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7073 	struct bpf_map *map = meta->map_ptr;
7074 
7075 	if (func_id != BPF_FUNC_tail_call &&
7076 	    func_id != BPF_FUNC_map_lookup_elem &&
7077 	    func_id != BPF_FUNC_map_update_elem &&
7078 	    func_id != BPF_FUNC_map_delete_elem &&
7079 	    func_id != BPF_FUNC_map_push_elem &&
7080 	    func_id != BPF_FUNC_map_pop_elem &&
7081 	    func_id != BPF_FUNC_map_peek_elem &&
7082 	    func_id != BPF_FUNC_for_each_map_elem &&
7083 	    func_id != BPF_FUNC_redirect_map &&
7084 	    func_id != BPF_FUNC_map_lookup_percpu_elem)
7085 		return 0;
7086 
7087 	if (map == NULL) {
7088 		verbose(env, "kernel subsystem misconfigured verifier\n");
7089 		return -EINVAL;
7090 	}
7091 
7092 	/* In case of read-only, some additional restrictions
7093 	 * need to be applied in order to prevent altering the
7094 	 * state of the map from program side.
7095 	 */
7096 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7097 	    (func_id == BPF_FUNC_map_delete_elem ||
7098 	     func_id == BPF_FUNC_map_update_elem ||
7099 	     func_id == BPF_FUNC_map_push_elem ||
7100 	     func_id == BPF_FUNC_map_pop_elem)) {
7101 		verbose(env, "write into map forbidden\n");
7102 		return -EACCES;
7103 	}
7104 
7105 	if (!BPF_MAP_PTR(aux->map_ptr_state))
7106 		bpf_map_ptr_store(aux, meta->map_ptr,
7107 				  !meta->map_ptr->bypass_spec_v1);
7108 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7109 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7110 				  !meta->map_ptr->bypass_spec_v1);
7111 	return 0;
7112 }
7113 
7114 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)7115 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7116 		int func_id, int insn_idx)
7117 {
7118 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7119 	struct bpf_reg_state *regs = cur_regs(env), *reg;
7120 	struct bpf_map *map = meta->map_ptr;
7121 	u64 val, max;
7122 	int err;
7123 
7124 	if (func_id != BPF_FUNC_tail_call)
7125 		return 0;
7126 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7127 		verbose(env, "kernel subsystem misconfigured verifier\n");
7128 		return -EINVAL;
7129 	}
7130 
7131 	reg = &regs[BPF_REG_3];
7132 	val = reg->var_off.value;
7133 	max = map->max_entries;
7134 
7135 	if (!(register_is_const(reg) && val < max)) {
7136 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7137 		return 0;
7138 	}
7139 
7140 	err = mark_chain_precision(env, BPF_REG_3);
7141 	if (err)
7142 		return err;
7143 	if (bpf_map_key_unseen(aux))
7144 		bpf_map_key_store(aux, val);
7145 	else if (!bpf_map_key_poisoned(aux) &&
7146 		  bpf_map_key_immediate(aux) != val)
7147 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7148 	return 0;
7149 }
7150 
check_reference_leak(struct bpf_verifier_env * env)7151 static int check_reference_leak(struct bpf_verifier_env *env)
7152 {
7153 	struct bpf_func_state *state = cur_func(env);
7154 	bool refs_lingering = false;
7155 	int i;
7156 
7157 	if (state->frameno && !state->in_callback_fn)
7158 		return 0;
7159 
7160 	for (i = 0; i < state->acquired_refs; i++) {
7161 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7162 			continue;
7163 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7164 			state->refs[i].id, state->refs[i].insn_idx);
7165 		refs_lingering = true;
7166 	}
7167 	return refs_lingering ? -EINVAL : 0;
7168 }
7169 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)7170 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7171 				   struct bpf_reg_state *regs)
7172 {
7173 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7174 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7175 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
7176 	int err, fmt_map_off, num_args;
7177 	u64 fmt_addr;
7178 	char *fmt;
7179 
7180 	/* data must be an array of u64 */
7181 	if (data_len_reg->var_off.value % 8)
7182 		return -EINVAL;
7183 	num_args = data_len_reg->var_off.value / 8;
7184 
7185 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7186 	 * and map_direct_value_addr is set.
7187 	 */
7188 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7189 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7190 						  fmt_map_off);
7191 	if (err) {
7192 		verbose(env, "verifier bug\n");
7193 		return -EFAULT;
7194 	}
7195 	fmt = (char *)(long)fmt_addr + fmt_map_off;
7196 
7197 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7198 	 * can focus on validating the format specifiers.
7199 	 */
7200 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7201 	if (err < 0)
7202 		verbose(env, "Invalid format string\n");
7203 
7204 	return err;
7205 }
7206 
check_get_func_ip(struct bpf_verifier_env * env)7207 static int check_get_func_ip(struct bpf_verifier_env *env)
7208 {
7209 	enum bpf_prog_type type = resolve_prog_type(env->prog);
7210 	int func_id = BPF_FUNC_get_func_ip;
7211 
7212 	if (type == BPF_PROG_TYPE_TRACING) {
7213 		if (!bpf_prog_has_trampoline(env->prog)) {
7214 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7215 				func_id_name(func_id), func_id);
7216 			return -ENOTSUPP;
7217 		}
7218 		return 0;
7219 	} else if (type == BPF_PROG_TYPE_KPROBE) {
7220 		return 0;
7221 	}
7222 
7223 	verbose(env, "func %s#%d not supported for program type %d\n",
7224 		func_id_name(func_id), func_id, type);
7225 	return -ENOTSUPP;
7226 }
7227 
cur_aux(struct bpf_verifier_env * env)7228 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7229 {
7230 	return &env->insn_aux_data[env->insn_idx];
7231 }
7232 
loop_flag_is_zero(struct bpf_verifier_env * env)7233 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7234 {
7235 	struct bpf_reg_state *regs = cur_regs(env);
7236 	struct bpf_reg_state *reg = &regs[BPF_REG_4];
7237 	bool reg_is_null = register_is_null(reg);
7238 
7239 	if (reg_is_null)
7240 		mark_chain_precision(env, BPF_REG_4);
7241 
7242 	return reg_is_null;
7243 }
7244 
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)7245 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7246 {
7247 	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7248 
7249 	if (!state->initialized) {
7250 		state->initialized = 1;
7251 		state->fit_for_inline = loop_flag_is_zero(env);
7252 		state->callback_subprogno = subprogno;
7253 		return;
7254 	}
7255 
7256 	if (!state->fit_for_inline)
7257 		return;
7258 
7259 	state->fit_for_inline = (loop_flag_is_zero(env) &&
7260 				 state->callback_subprogno == subprogno);
7261 }
7262 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)7263 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7264 			     int *insn_idx_p)
7265 {
7266 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7267 	const struct bpf_func_proto *fn = NULL;
7268 	enum bpf_return_type ret_type;
7269 	enum bpf_type_flag ret_flag;
7270 	struct bpf_reg_state *regs;
7271 	struct bpf_call_arg_meta meta;
7272 	int insn_idx = *insn_idx_p;
7273 	bool changes_data;
7274 	int i, err, func_id;
7275 
7276 	/* find function prototype */
7277 	func_id = insn->imm;
7278 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7279 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7280 			func_id);
7281 		return -EINVAL;
7282 	}
7283 
7284 	if (env->ops->get_func_proto)
7285 		fn = env->ops->get_func_proto(func_id, env->prog);
7286 	if (!fn) {
7287 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7288 			func_id);
7289 		return -EINVAL;
7290 	}
7291 
7292 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
7293 	if (!env->prog->gpl_compatible && fn->gpl_only) {
7294 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7295 		return -EINVAL;
7296 	}
7297 
7298 	if (fn->allowed && !fn->allowed(env->prog)) {
7299 		verbose(env, "helper call is not allowed in probe\n");
7300 		return -EINVAL;
7301 	}
7302 
7303 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
7304 	changes_data = bpf_helper_changes_pkt_data(fn->func);
7305 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7306 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7307 			func_id_name(func_id), func_id);
7308 		return -EINVAL;
7309 	}
7310 
7311 	memset(&meta, 0, sizeof(meta));
7312 	meta.pkt_access = fn->pkt_access;
7313 
7314 	err = check_func_proto(fn, func_id);
7315 	if (err) {
7316 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7317 			func_id_name(func_id), func_id);
7318 		return err;
7319 	}
7320 
7321 	meta.func_id = func_id;
7322 	/* check args */
7323 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7324 		err = check_func_arg(env, i, &meta, fn);
7325 		if (err)
7326 			return err;
7327 	}
7328 
7329 	err = record_func_map(env, &meta, func_id, insn_idx);
7330 	if (err)
7331 		return err;
7332 
7333 	err = record_func_key(env, &meta, func_id, insn_idx);
7334 	if (err)
7335 		return err;
7336 
7337 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
7338 	 * is inferred from register state.
7339 	 */
7340 	for (i = 0; i < meta.access_size; i++) {
7341 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7342 				       BPF_WRITE, -1, false);
7343 		if (err)
7344 			return err;
7345 	}
7346 
7347 	regs = cur_regs(env);
7348 
7349 	if (meta.uninit_dynptr_regno) {
7350 		/* we write BPF_DW bits (8 bytes) at a time */
7351 		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7352 			err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7353 					       i, BPF_DW, BPF_WRITE, -1, false);
7354 			if (err)
7355 				return err;
7356 		}
7357 
7358 		err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7359 					      fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7360 					      insn_idx);
7361 		if (err)
7362 			return err;
7363 	}
7364 
7365 	if (meta.release_regno) {
7366 		err = -EINVAL;
7367 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7368 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7369 		else if (meta.ref_obj_id)
7370 			err = release_reference(env, meta.ref_obj_id);
7371 		/* meta.ref_obj_id can only be 0 if register that is meant to be
7372 		 * released is NULL, which must be > R0.
7373 		 */
7374 		else if (register_is_null(&regs[meta.release_regno]))
7375 			err = 0;
7376 		if (err) {
7377 			verbose(env, "func %s#%d reference has not been acquired before\n",
7378 				func_id_name(func_id), func_id);
7379 			return err;
7380 		}
7381 	}
7382 
7383 	switch (func_id) {
7384 	case BPF_FUNC_tail_call:
7385 		err = check_reference_leak(env);
7386 		if (err) {
7387 			verbose(env, "tail_call would lead to reference leak\n");
7388 			return err;
7389 		}
7390 		break;
7391 	case BPF_FUNC_get_local_storage:
7392 		/* check that flags argument in get_local_storage(map, flags) is 0,
7393 		 * this is required because get_local_storage() can't return an error.
7394 		 */
7395 		if (!register_is_null(&regs[BPF_REG_2])) {
7396 			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7397 			return -EINVAL;
7398 		}
7399 		break;
7400 	case BPF_FUNC_for_each_map_elem:
7401 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7402 					set_map_elem_callback_state);
7403 		break;
7404 	case BPF_FUNC_timer_set_callback:
7405 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7406 					set_timer_callback_state);
7407 		break;
7408 	case BPF_FUNC_find_vma:
7409 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7410 					set_find_vma_callback_state);
7411 		break;
7412 	case BPF_FUNC_snprintf:
7413 		err = check_bpf_snprintf_call(env, regs);
7414 		break;
7415 	case BPF_FUNC_loop:
7416 		update_loop_inline_state(env, meta.subprogno);
7417 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7418 					set_loop_callback_state);
7419 		break;
7420 	case BPF_FUNC_dynptr_from_mem:
7421 		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7422 			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7423 				reg_type_str(env, regs[BPF_REG_1].type));
7424 			return -EACCES;
7425 		}
7426 		break;
7427 	case BPF_FUNC_set_retval:
7428 		if (prog_type == BPF_PROG_TYPE_LSM &&
7429 		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7430 			if (!env->prog->aux->attach_func_proto->type) {
7431 				/* Make sure programs that attach to void
7432 				 * hooks don't try to modify return value.
7433 				 */
7434 				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7435 				return -EINVAL;
7436 			}
7437 		}
7438 		break;
7439 	case BPF_FUNC_dynptr_data:
7440 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7441 			if (arg_type_is_dynptr(fn->arg_type[i])) {
7442 				struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7443 
7444 				if (meta.ref_obj_id) {
7445 					verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7446 					return -EFAULT;
7447 				}
7448 
7449 				if (base_type(reg->type) != PTR_TO_DYNPTR)
7450 					/* Find the id of the dynptr we're
7451 					 * tracking the reference of
7452 					 */
7453 					meta.ref_obj_id = stack_slot_get_id(env, reg);
7454 				break;
7455 			}
7456 		}
7457 		if (i == MAX_BPF_FUNC_REG_ARGS) {
7458 			verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7459 			return -EFAULT;
7460 		}
7461 		break;
7462 	case BPF_FUNC_user_ringbuf_drain:
7463 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7464 					set_user_ringbuf_callback_state);
7465 		break;
7466 	}
7467 
7468 	if (err)
7469 		return err;
7470 
7471 	/* reset caller saved regs */
7472 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
7473 		mark_reg_not_init(env, regs, caller_saved[i]);
7474 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7475 	}
7476 
7477 	/* helper call returns 64-bit value. */
7478 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7479 
7480 	/* update return register (already marked as written above) */
7481 	ret_type = fn->ret_type;
7482 	ret_flag = type_flag(ret_type);
7483 
7484 	switch (base_type(ret_type)) {
7485 	case RET_INTEGER:
7486 		/* sets type to SCALAR_VALUE */
7487 		mark_reg_unknown(env, regs, BPF_REG_0);
7488 		break;
7489 	case RET_VOID:
7490 		regs[BPF_REG_0].type = NOT_INIT;
7491 		break;
7492 	case RET_PTR_TO_MAP_VALUE:
7493 		/* There is no offset yet applied, variable or fixed */
7494 		mark_reg_known_zero(env, regs, BPF_REG_0);
7495 		/* remember map_ptr, so that check_map_access()
7496 		 * can check 'value_size' boundary of memory access
7497 		 * to map element returned from bpf_map_lookup_elem()
7498 		 */
7499 		if (meta.map_ptr == NULL) {
7500 			verbose(env,
7501 				"kernel subsystem misconfigured verifier\n");
7502 			return -EINVAL;
7503 		}
7504 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
7505 		regs[BPF_REG_0].map_uid = meta.map_uid;
7506 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7507 		if (!type_may_be_null(ret_type) &&
7508 		    map_value_has_spin_lock(meta.map_ptr)) {
7509 			regs[BPF_REG_0].id = ++env->id_gen;
7510 		}
7511 		break;
7512 	case RET_PTR_TO_SOCKET:
7513 		mark_reg_known_zero(env, regs, BPF_REG_0);
7514 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7515 		break;
7516 	case RET_PTR_TO_SOCK_COMMON:
7517 		mark_reg_known_zero(env, regs, BPF_REG_0);
7518 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7519 		break;
7520 	case RET_PTR_TO_TCP_SOCK:
7521 		mark_reg_known_zero(env, regs, BPF_REG_0);
7522 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7523 		break;
7524 	case RET_PTR_TO_ALLOC_MEM:
7525 		mark_reg_known_zero(env, regs, BPF_REG_0);
7526 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7527 		regs[BPF_REG_0].mem_size = meta.mem_size;
7528 		break;
7529 	case RET_PTR_TO_MEM_OR_BTF_ID:
7530 	{
7531 		const struct btf_type *t;
7532 
7533 		mark_reg_known_zero(env, regs, BPF_REG_0);
7534 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7535 		if (!btf_type_is_struct(t)) {
7536 			u32 tsize;
7537 			const struct btf_type *ret;
7538 			const char *tname;
7539 
7540 			/* resolve the type size of ksym. */
7541 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7542 			if (IS_ERR(ret)) {
7543 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7544 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
7545 					tname, PTR_ERR(ret));
7546 				return -EINVAL;
7547 			}
7548 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7549 			regs[BPF_REG_0].mem_size = tsize;
7550 		} else {
7551 			/* MEM_RDONLY may be carried from ret_flag, but it
7552 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7553 			 * it will confuse the check of PTR_TO_BTF_ID in
7554 			 * check_mem_access().
7555 			 */
7556 			ret_flag &= ~MEM_RDONLY;
7557 
7558 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7559 			regs[BPF_REG_0].btf = meta.ret_btf;
7560 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7561 		}
7562 		break;
7563 	}
7564 	case RET_PTR_TO_BTF_ID:
7565 	{
7566 		struct btf *ret_btf;
7567 		int ret_btf_id;
7568 
7569 		mark_reg_known_zero(env, regs, BPF_REG_0);
7570 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7571 		if (func_id == BPF_FUNC_kptr_xchg) {
7572 			ret_btf = meta.kptr_off_desc->kptr.btf;
7573 			ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7574 		} else {
7575 			if (fn->ret_btf_id == BPF_PTR_POISON) {
7576 				verbose(env, "verifier internal error:");
7577 				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7578 					func_id_name(func_id));
7579 				return -EINVAL;
7580 			}
7581 			ret_btf = btf_vmlinux;
7582 			ret_btf_id = *fn->ret_btf_id;
7583 		}
7584 		if (ret_btf_id == 0) {
7585 			verbose(env, "invalid return type %u of func %s#%d\n",
7586 				base_type(ret_type), func_id_name(func_id),
7587 				func_id);
7588 			return -EINVAL;
7589 		}
7590 		regs[BPF_REG_0].btf = ret_btf;
7591 		regs[BPF_REG_0].btf_id = ret_btf_id;
7592 		break;
7593 	}
7594 	default:
7595 		verbose(env, "unknown return type %u of func %s#%d\n",
7596 			base_type(ret_type), func_id_name(func_id), func_id);
7597 		return -EINVAL;
7598 	}
7599 
7600 	if (type_may_be_null(regs[BPF_REG_0].type))
7601 		regs[BPF_REG_0].id = ++env->id_gen;
7602 
7603 	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7604 		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7605 			func_id_name(func_id), func_id);
7606 		return -EFAULT;
7607 	}
7608 
7609 	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7610 		/* For release_reference() */
7611 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7612 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
7613 		int id = acquire_reference_state(env, insn_idx);
7614 
7615 		if (id < 0)
7616 			return id;
7617 		/* For mark_ptr_or_null_reg() */
7618 		regs[BPF_REG_0].id = id;
7619 		/* For release_reference() */
7620 		regs[BPF_REG_0].ref_obj_id = id;
7621 	}
7622 
7623 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7624 
7625 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7626 	if (err)
7627 		return err;
7628 
7629 	if ((func_id == BPF_FUNC_get_stack ||
7630 	     func_id == BPF_FUNC_get_task_stack) &&
7631 	    !env->prog->has_callchain_buf) {
7632 		const char *err_str;
7633 
7634 #ifdef CONFIG_PERF_EVENTS
7635 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
7636 		err_str = "cannot get callchain buffer for func %s#%d\n";
7637 #else
7638 		err = -ENOTSUPP;
7639 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7640 #endif
7641 		if (err) {
7642 			verbose(env, err_str, func_id_name(func_id), func_id);
7643 			return err;
7644 		}
7645 
7646 		env->prog->has_callchain_buf = true;
7647 	}
7648 
7649 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7650 		env->prog->call_get_stack = true;
7651 
7652 	if (func_id == BPF_FUNC_get_func_ip) {
7653 		if (check_get_func_ip(env))
7654 			return -ENOTSUPP;
7655 		env->prog->call_get_func_ip = true;
7656 	}
7657 
7658 	if (changes_data)
7659 		clear_all_pkt_pointers(env);
7660 	return 0;
7661 }
7662 
7663 /* mark_btf_func_reg_size() is used when the reg size is determined by
7664  * the BTF func_proto's return value size and argument.
7665  */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)7666 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7667 				   size_t reg_size)
7668 {
7669 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
7670 
7671 	if (regno == BPF_REG_0) {
7672 		/* Function return value */
7673 		reg->live |= REG_LIVE_WRITTEN;
7674 		reg->subreg_def = reg_size == sizeof(u64) ?
7675 			DEF_NOT_SUBREG : env->insn_idx + 1;
7676 	} else {
7677 		/* Function argument */
7678 		if (reg_size == sizeof(u64)) {
7679 			mark_insn_zext(env, reg);
7680 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7681 		} else {
7682 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7683 		}
7684 	}
7685 }
7686 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)7687 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7688 			    int *insn_idx_p)
7689 {
7690 	const struct btf_type *t, *func, *func_proto, *ptr_type;
7691 	struct bpf_reg_state *regs = cur_regs(env);
7692 	struct bpf_kfunc_arg_meta meta = { 0 };
7693 	const char *func_name, *ptr_type_name;
7694 	u32 i, nargs, func_id, ptr_type_id;
7695 	int err, insn_idx = *insn_idx_p;
7696 	const struct btf_param *args;
7697 	struct btf *desc_btf;
7698 	u32 *kfunc_flags;
7699 	bool acq;
7700 
7701 	/* skip for now, but return error when we find this in fixup_kfunc_call */
7702 	if (!insn->imm)
7703 		return 0;
7704 
7705 	desc_btf = find_kfunc_desc_btf(env, insn->off);
7706 	if (IS_ERR(desc_btf))
7707 		return PTR_ERR(desc_btf);
7708 
7709 	func_id = insn->imm;
7710 	func = btf_type_by_id(desc_btf, func_id);
7711 	func_name = btf_name_by_offset(desc_btf, func->name_off);
7712 	func_proto = btf_type_by_id(desc_btf, func->type);
7713 
7714 	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7715 	if (!kfunc_flags) {
7716 		verbose(env, "calling kernel function %s is not allowed\n",
7717 			func_name);
7718 		return -EACCES;
7719 	}
7720 	if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7721 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7722 		return -EACCES;
7723 	}
7724 
7725 	acq = *kfunc_flags & KF_ACQUIRE;
7726 
7727 	meta.flags = *kfunc_flags;
7728 
7729 	/* Check the arguments */
7730 	err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7731 	if (err < 0)
7732 		return err;
7733 	/* In case of release function, we get register number of refcounted
7734 	 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7735 	 */
7736 	if (err) {
7737 		err = release_reference(env, regs[err].ref_obj_id);
7738 		if (err) {
7739 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7740 				func_name, func_id);
7741 			return err;
7742 		}
7743 	}
7744 
7745 	for (i = 0; i < CALLER_SAVED_REGS; i++)
7746 		mark_reg_not_init(env, regs, caller_saved[i]);
7747 
7748 	/* Check return type */
7749 	t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7750 
7751 	if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7752 		verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7753 		return -EINVAL;
7754 	}
7755 
7756 	if (btf_type_is_scalar(t)) {
7757 		mark_reg_unknown(env, regs, BPF_REG_0);
7758 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7759 	} else if (btf_type_is_ptr(t)) {
7760 		ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7761 						   &ptr_type_id);
7762 		if (!btf_type_is_struct(ptr_type)) {
7763 			if (!meta.r0_size) {
7764 				ptr_type_name = btf_name_by_offset(desc_btf,
7765 								   ptr_type->name_off);
7766 				verbose(env,
7767 					"kernel function %s returns pointer type %s %s is not supported\n",
7768 					func_name,
7769 					btf_type_str(ptr_type),
7770 					ptr_type_name);
7771 				return -EINVAL;
7772 			}
7773 
7774 			mark_reg_known_zero(env, regs, BPF_REG_0);
7775 			regs[BPF_REG_0].type = PTR_TO_MEM;
7776 			regs[BPF_REG_0].mem_size = meta.r0_size;
7777 
7778 			if (meta.r0_rdonly)
7779 				regs[BPF_REG_0].type |= MEM_RDONLY;
7780 
7781 			/* Ensures we don't access the memory after a release_reference() */
7782 			if (meta.ref_obj_id)
7783 				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7784 		} else {
7785 			mark_reg_known_zero(env, regs, BPF_REG_0);
7786 			regs[BPF_REG_0].btf = desc_btf;
7787 			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7788 			regs[BPF_REG_0].btf_id = ptr_type_id;
7789 		}
7790 		if (*kfunc_flags & KF_RET_NULL) {
7791 			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7792 			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7793 			regs[BPF_REG_0].id = ++env->id_gen;
7794 		}
7795 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7796 		if (acq) {
7797 			int id = acquire_reference_state(env, insn_idx);
7798 
7799 			if (id < 0)
7800 				return id;
7801 			regs[BPF_REG_0].id = id;
7802 			regs[BPF_REG_0].ref_obj_id = id;
7803 		}
7804 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7805 
7806 	nargs = btf_type_vlen(func_proto);
7807 	args = (const struct btf_param *)(func_proto + 1);
7808 	for (i = 0; i < nargs; i++) {
7809 		u32 regno = i + 1;
7810 
7811 		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7812 		if (btf_type_is_ptr(t))
7813 			mark_btf_func_reg_size(env, regno, sizeof(void *));
7814 		else
7815 			/* scalar. ensured by btf_check_kfunc_arg_match() */
7816 			mark_btf_func_reg_size(env, regno, t->size);
7817 	}
7818 
7819 	return 0;
7820 }
7821 
signed_add_overflows(s64 a,s64 b)7822 static bool signed_add_overflows(s64 a, s64 b)
7823 {
7824 	/* Do the add in u64, where overflow is well-defined */
7825 	s64 res = (s64)((u64)a + (u64)b);
7826 
7827 	if (b < 0)
7828 		return res > a;
7829 	return res < a;
7830 }
7831 
signed_add32_overflows(s32 a,s32 b)7832 static bool signed_add32_overflows(s32 a, s32 b)
7833 {
7834 	/* Do the add in u32, where overflow is well-defined */
7835 	s32 res = (s32)((u32)a + (u32)b);
7836 
7837 	if (b < 0)
7838 		return res > a;
7839 	return res < a;
7840 }
7841 
signed_sub_overflows(s64 a,s64 b)7842 static bool signed_sub_overflows(s64 a, s64 b)
7843 {
7844 	/* Do the sub in u64, where overflow is well-defined */
7845 	s64 res = (s64)((u64)a - (u64)b);
7846 
7847 	if (b < 0)
7848 		return res < a;
7849 	return res > a;
7850 }
7851 
signed_sub32_overflows(s32 a,s32 b)7852 static bool signed_sub32_overflows(s32 a, s32 b)
7853 {
7854 	/* Do the sub in u32, where overflow is well-defined */
7855 	s32 res = (s32)((u32)a - (u32)b);
7856 
7857 	if (b < 0)
7858 		return res < a;
7859 	return res > a;
7860 }
7861 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)7862 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7863 				  const struct bpf_reg_state *reg,
7864 				  enum bpf_reg_type type)
7865 {
7866 	bool known = tnum_is_const(reg->var_off);
7867 	s64 val = reg->var_off.value;
7868 	s64 smin = reg->smin_value;
7869 
7870 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7871 		verbose(env, "math between %s pointer and %lld is not allowed\n",
7872 			reg_type_str(env, type), val);
7873 		return false;
7874 	}
7875 
7876 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7877 		verbose(env, "%s pointer offset %d is not allowed\n",
7878 			reg_type_str(env, type), reg->off);
7879 		return false;
7880 	}
7881 
7882 	if (smin == S64_MIN) {
7883 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7884 			reg_type_str(env, type));
7885 		return false;
7886 	}
7887 
7888 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7889 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
7890 			smin, reg_type_str(env, type));
7891 		return false;
7892 	}
7893 
7894 	return true;
7895 }
7896 
7897 enum {
7898 	REASON_BOUNDS	= -1,
7899 	REASON_TYPE	= -2,
7900 	REASON_PATHS	= -3,
7901 	REASON_LIMIT	= -4,
7902 	REASON_STACK	= -5,
7903 };
7904 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)7905 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7906 			      u32 *alu_limit, bool mask_to_left)
7907 {
7908 	u32 max = 0, ptr_limit = 0;
7909 
7910 	switch (ptr_reg->type) {
7911 	case PTR_TO_STACK:
7912 		/* Offset 0 is out-of-bounds, but acceptable start for the
7913 		 * left direction, see BPF_REG_FP. Also, unknown scalar
7914 		 * offset where we would need to deal with min/max bounds is
7915 		 * currently prohibited for unprivileged.
7916 		 */
7917 		max = MAX_BPF_STACK + mask_to_left;
7918 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7919 		break;
7920 	case PTR_TO_MAP_VALUE:
7921 		max = ptr_reg->map_ptr->value_size;
7922 		ptr_limit = (mask_to_left ?
7923 			     ptr_reg->smin_value :
7924 			     ptr_reg->umax_value) + ptr_reg->off;
7925 		break;
7926 	default:
7927 		return REASON_TYPE;
7928 	}
7929 
7930 	if (ptr_limit >= max)
7931 		return REASON_LIMIT;
7932 	*alu_limit = ptr_limit;
7933 	return 0;
7934 }
7935 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)7936 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7937 				    const struct bpf_insn *insn)
7938 {
7939 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7940 }
7941 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)7942 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7943 				       u32 alu_state, u32 alu_limit)
7944 {
7945 	/* If we arrived here from different branches with different
7946 	 * state or limits to sanitize, then this won't work.
7947 	 */
7948 	if (aux->alu_state &&
7949 	    (aux->alu_state != alu_state ||
7950 	     aux->alu_limit != alu_limit))
7951 		return REASON_PATHS;
7952 
7953 	/* Corresponding fixup done in do_misc_fixups(). */
7954 	aux->alu_state = alu_state;
7955 	aux->alu_limit = alu_limit;
7956 	return 0;
7957 }
7958 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)7959 static int sanitize_val_alu(struct bpf_verifier_env *env,
7960 			    struct bpf_insn *insn)
7961 {
7962 	struct bpf_insn_aux_data *aux = cur_aux(env);
7963 
7964 	if (can_skip_alu_sanitation(env, insn))
7965 		return 0;
7966 
7967 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7968 }
7969 
sanitize_needed(u8 opcode)7970 static bool sanitize_needed(u8 opcode)
7971 {
7972 	return opcode == BPF_ADD || opcode == BPF_SUB;
7973 }
7974 
7975 struct bpf_sanitize_info {
7976 	struct bpf_insn_aux_data aux;
7977 	bool mask_to_left;
7978 };
7979 
7980 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)7981 sanitize_speculative_path(struct bpf_verifier_env *env,
7982 			  const struct bpf_insn *insn,
7983 			  u32 next_idx, u32 curr_idx)
7984 {
7985 	struct bpf_verifier_state *branch;
7986 	struct bpf_reg_state *regs;
7987 
7988 	branch = push_stack(env, next_idx, curr_idx, true);
7989 	if (branch && insn) {
7990 		regs = branch->frame[branch->curframe]->regs;
7991 		if (BPF_SRC(insn->code) == BPF_K) {
7992 			mark_reg_unknown(env, regs, insn->dst_reg);
7993 		} else if (BPF_SRC(insn->code) == BPF_X) {
7994 			mark_reg_unknown(env, regs, insn->dst_reg);
7995 			mark_reg_unknown(env, regs, insn->src_reg);
7996 		}
7997 	}
7998 	return branch;
7999 }
8000 
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)8001 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8002 			    struct bpf_insn *insn,
8003 			    const struct bpf_reg_state *ptr_reg,
8004 			    const struct bpf_reg_state *off_reg,
8005 			    struct bpf_reg_state *dst_reg,
8006 			    struct bpf_sanitize_info *info,
8007 			    const bool commit_window)
8008 {
8009 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8010 	struct bpf_verifier_state *vstate = env->cur_state;
8011 	bool off_is_imm = tnum_is_const(off_reg->var_off);
8012 	bool off_is_neg = off_reg->smin_value < 0;
8013 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
8014 	u8 opcode = BPF_OP(insn->code);
8015 	u32 alu_state, alu_limit;
8016 	struct bpf_reg_state tmp;
8017 	bool ret;
8018 	int err;
8019 
8020 	if (can_skip_alu_sanitation(env, insn))
8021 		return 0;
8022 
8023 	/* We already marked aux for masking from non-speculative
8024 	 * paths, thus we got here in the first place. We only care
8025 	 * to explore bad access from here.
8026 	 */
8027 	if (vstate->speculative)
8028 		goto do_sim;
8029 
8030 	if (!commit_window) {
8031 		if (!tnum_is_const(off_reg->var_off) &&
8032 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8033 			return REASON_BOUNDS;
8034 
8035 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8036 				     (opcode == BPF_SUB && !off_is_neg);
8037 	}
8038 
8039 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8040 	if (err < 0)
8041 		return err;
8042 
8043 	if (commit_window) {
8044 		/* In commit phase we narrow the masking window based on
8045 		 * the observed pointer move after the simulated operation.
8046 		 */
8047 		alu_state = info->aux.alu_state;
8048 		alu_limit = abs(info->aux.alu_limit - alu_limit);
8049 	} else {
8050 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8051 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8052 		alu_state |= ptr_is_dst_reg ?
8053 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8054 
8055 		/* Limit pruning on unknown scalars to enable deep search for
8056 		 * potential masking differences from other program paths.
8057 		 */
8058 		if (!off_is_imm)
8059 			env->explore_alu_limits = true;
8060 	}
8061 
8062 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8063 	if (err < 0)
8064 		return err;
8065 do_sim:
8066 	/* If we're in commit phase, we're done here given we already
8067 	 * pushed the truncated dst_reg into the speculative verification
8068 	 * stack.
8069 	 *
8070 	 * Also, when register is a known constant, we rewrite register-based
8071 	 * operation to immediate-based, and thus do not need masking (and as
8072 	 * a consequence, do not need to simulate the zero-truncation either).
8073 	 */
8074 	if (commit_window || off_is_imm)
8075 		return 0;
8076 
8077 	/* Simulate and find potential out-of-bounds access under
8078 	 * speculative execution from truncation as a result of
8079 	 * masking when off was not within expected range. If off
8080 	 * sits in dst, then we temporarily need to move ptr there
8081 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8082 	 * for cases where we use K-based arithmetic in one direction
8083 	 * and truncated reg-based in the other in order to explore
8084 	 * bad access.
8085 	 */
8086 	if (!ptr_is_dst_reg) {
8087 		tmp = *dst_reg;
8088 		*dst_reg = *ptr_reg;
8089 	}
8090 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8091 					env->insn_idx);
8092 	if (!ptr_is_dst_reg && ret)
8093 		*dst_reg = tmp;
8094 	return !ret ? REASON_STACK : 0;
8095 }
8096 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)8097 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8098 {
8099 	struct bpf_verifier_state *vstate = env->cur_state;
8100 
8101 	/* If we simulate paths under speculation, we don't update the
8102 	 * insn as 'seen' such that when we verify unreachable paths in
8103 	 * the non-speculative domain, sanitize_dead_code() can still
8104 	 * rewrite/sanitize them.
8105 	 */
8106 	if (!vstate->speculative)
8107 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8108 }
8109 
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)8110 static int sanitize_err(struct bpf_verifier_env *env,
8111 			const struct bpf_insn *insn, int reason,
8112 			const struct bpf_reg_state *off_reg,
8113 			const struct bpf_reg_state *dst_reg)
8114 {
8115 	static const char *err = "pointer arithmetic with it prohibited for !root";
8116 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8117 	u32 dst = insn->dst_reg, src = insn->src_reg;
8118 
8119 	switch (reason) {
8120 	case REASON_BOUNDS:
8121 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8122 			off_reg == dst_reg ? dst : src, err);
8123 		break;
8124 	case REASON_TYPE:
8125 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8126 			off_reg == dst_reg ? src : dst, err);
8127 		break;
8128 	case REASON_PATHS:
8129 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8130 			dst, op, err);
8131 		break;
8132 	case REASON_LIMIT:
8133 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8134 			dst, op, err);
8135 		break;
8136 	case REASON_STACK:
8137 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8138 			dst, err);
8139 		break;
8140 	default:
8141 		verbose(env, "verifier internal error: unknown reason (%d)\n",
8142 			reason);
8143 		break;
8144 	}
8145 
8146 	return -EACCES;
8147 }
8148 
8149 /* check that stack access falls within stack limits and that 'reg' doesn't
8150  * have a variable offset.
8151  *
8152  * Variable offset is prohibited for unprivileged mode for simplicity since it
8153  * requires corresponding support in Spectre masking for stack ALU.  See also
8154  * retrieve_ptr_limit().
8155  *
8156  *
8157  * 'off' includes 'reg->off'.
8158  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)8159 static int check_stack_access_for_ptr_arithmetic(
8160 				struct bpf_verifier_env *env,
8161 				int regno,
8162 				const struct bpf_reg_state *reg,
8163 				int off)
8164 {
8165 	if (!tnum_is_const(reg->var_off)) {
8166 		char tn_buf[48];
8167 
8168 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8169 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8170 			regno, tn_buf, off);
8171 		return -EACCES;
8172 	}
8173 
8174 	if (off >= 0 || off < -MAX_BPF_STACK) {
8175 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
8176 			"prohibited for !root; off=%d\n", regno, off);
8177 		return -EACCES;
8178 	}
8179 
8180 	return 0;
8181 }
8182 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)8183 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8184 				 const struct bpf_insn *insn,
8185 				 const struct bpf_reg_state *dst_reg)
8186 {
8187 	u32 dst = insn->dst_reg;
8188 
8189 	/* For unprivileged we require that resulting offset must be in bounds
8190 	 * in order to be able to sanitize access later on.
8191 	 */
8192 	if (env->bypass_spec_v1)
8193 		return 0;
8194 
8195 	switch (dst_reg->type) {
8196 	case PTR_TO_STACK:
8197 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8198 					dst_reg->off + dst_reg->var_off.value))
8199 			return -EACCES;
8200 		break;
8201 	case PTR_TO_MAP_VALUE:
8202 		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8203 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8204 				"prohibited for !root\n", dst);
8205 			return -EACCES;
8206 		}
8207 		break;
8208 	default:
8209 		break;
8210 	}
8211 
8212 	return 0;
8213 }
8214 
8215 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8216  * Caller should also handle BPF_MOV case separately.
8217  * If we return -EACCES, caller may want to try again treating pointer as a
8218  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8219  */
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)8220 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8221 				   struct bpf_insn *insn,
8222 				   const struct bpf_reg_state *ptr_reg,
8223 				   const struct bpf_reg_state *off_reg)
8224 {
8225 	struct bpf_verifier_state *vstate = env->cur_state;
8226 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8227 	struct bpf_reg_state *regs = state->regs, *dst_reg;
8228 	bool known = tnum_is_const(off_reg->var_off);
8229 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8230 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8231 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8232 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8233 	struct bpf_sanitize_info info = {};
8234 	u8 opcode = BPF_OP(insn->code);
8235 	u32 dst = insn->dst_reg;
8236 	int ret;
8237 
8238 	dst_reg = &regs[dst];
8239 
8240 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8241 	    smin_val > smax_val || umin_val > umax_val) {
8242 		/* Taint dst register if offset had invalid bounds derived from
8243 		 * e.g. dead branches.
8244 		 */
8245 		__mark_reg_unknown(env, dst_reg);
8246 		return 0;
8247 	}
8248 
8249 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
8250 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
8251 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8252 			__mark_reg_unknown(env, dst_reg);
8253 			return 0;
8254 		}
8255 
8256 		verbose(env,
8257 			"R%d 32-bit pointer arithmetic prohibited\n",
8258 			dst);
8259 		return -EACCES;
8260 	}
8261 
8262 	if (ptr_reg->type & PTR_MAYBE_NULL) {
8263 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8264 			dst, reg_type_str(env, ptr_reg->type));
8265 		return -EACCES;
8266 	}
8267 
8268 	switch (base_type(ptr_reg->type)) {
8269 	case CONST_PTR_TO_MAP:
8270 		/* smin_val represents the known value */
8271 		if (known && smin_val == 0 && opcode == BPF_ADD)
8272 			break;
8273 		fallthrough;
8274 	case PTR_TO_PACKET_END:
8275 	case PTR_TO_SOCKET:
8276 	case PTR_TO_SOCK_COMMON:
8277 	case PTR_TO_TCP_SOCK:
8278 	case PTR_TO_XDP_SOCK:
8279 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8280 			dst, reg_type_str(env, ptr_reg->type));
8281 		return -EACCES;
8282 	default:
8283 		break;
8284 	}
8285 
8286 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8287 	 * The id may be overwritten later if we create a new variable offset.
8288 	 */
8289 	dst_reg->type = ptr_reg->type;
8290 	dst_reg->id = ptr_reg->id;
8291 
8292 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8293 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8294 		return -EINVAL;
8295 
8296 	/* pointer types do not carry 32-bit bounds at the moment. */
8297 	__mark_reg32_unbounded(dst_reg);
8298 
8299 	if (sanitize_needed(opcode)) {
8300 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8301 				       &info, false);
8302 		if (ret < 0)
8303 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8304 	}
8305 
8306 	switch (opcode) {
8307 	case BPF_ADD:
8308 		/* We can take a fixed offset as long as it doesn't overflow
8309 		 * the s32 'off' field
8310 		 */
8311 		if (known && (ptr_reg->off + smin_val ==
8312 			      (s64)(s32)(ptr_reg->off + smin_val))) {
8313 			/* pointer += K.  Accumulate it into fixed offset */
8314 			dst_reg->smin_value = smin_ptr;
8315 			dst_reg->smax_value = smax_ptr;
8316 			dst_reg->umin_value = umin_ptr;
8317 			dst_reg->umax_value = umax_ptr;
8318 			dst_reg->var_off = ptr_reg->var_off;
8319 			dst_reg->off = ptr_reg->off + smin_val;
8320 			dst_reg->raw = ptr_reg->raw;
8321 			break;
8322 		}
8323 		/* A new variable offset is created.  Note that off_reg->off
8324 		 * == 0, since it's a scalar.
8325 		 * dst_reg gets the pointer type and since some positive
8326 		 * integer value was added to the pointer, give it a new 'id'
8327 		 * if it's a PTR_TO_PACKET.
8328 		 * this creates a new 'base' pointer, off_reg (variable) gets
8329 		 * added into the variable offset, and we copy the fixed offset
8330 		 * from ptr_reg.
8331 		 */
8332 		if (signed_add_overflows(smin_ptr, smin_val) ||
8333 		    signed_add_overflows(smax_ptr, smax_val)) {
8334 			dst_reg->smin_value = S64_MIN;
8335 			dst_reg->smax_value = S64_MAX;
8336 		} else {
8337 			dst_reg->smin_value = smin_ptr + smin_val;
8338 			dst_reg->smax_value = smax_ptr + smax_val;
8339 		}
8340 		if (umin_ptr + umin_val < umin_ptr ||
8341 		    umax_ptr + umax_val < umax_ptr) {
8342 			dst_reg->umin_value = 0;
8343 			dst_reg->umax_value = U64_MAX;
8344 		} else {
8345 			dst_reg->umin_value = umin_ptr + umin_val;
8346 			dst_reg->umax_value = umax_ptr + umax_val;
8347 		}
8348 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8349 		dst_reg->off = ptr_reg->off;
8350 		dst_reg->raw = ptr_reg->raw;
8351 		if (reg_is_pkt_pointer(ptr_reg)) {
8352 			dst_reg->id = ++env->id_gen;
8353 			/* something was added to pkt_ptr, set range to zero */
8354 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8355 		}
8356 		break;
8357 	case BPF_SUB:
8358 		if (dst_reg == off_reg) {
8359 			/* scalar -= pointer.  Creates an unknown scalar */
8360 			verbose(env, "R%d tried to subtract pointer from scalar\n",
8361 				dst);
8362 			return -EACCES;
8363 		}
8364 		/* We don't allow subtraction from FP, because (according to
8365 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
8366 		 * be able to deal with it.
8367 		 */
8368 		if (ptr_reg->type == PTR_TO_STACK) {
8369 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
8370 				dst);
8371 			return -EACCES;
8372 		}
8373 		if (known && (ptr_reg->off - smin_val ==
8374 			      (s64)(s32)(ptr_reg->off - smin_val))) {
8375 			/* pointer -= K.  Subtract it from fixed offset */
8376 			dst_reg->smin_value = smin_ptr;
8377 			dst_reg->smax_value = smax_ptr;
8378 			dst_reg->umin_value = umin_ptr;
8379 			dst_reg->umax_value = umax_ptr;
8380 			dst_reg->var_off = ptr_reg->var_off;
8381 			dst_reg->id = ptr_reg->id;
8382 			dst_reg->off = ptr_reg->off - smin_val;
8383 			dst_reg->raw = ptr_reg->raw;
8384 			break;
8385 		}
8386 		/* A new variable offset is created.  If the subtrahend is known
8387 		 * nonnegative, then any reg->range we had before is still good.
8388 		 */
8389 		if (signed_sub_overflows(smin_ptr, smax_val) ||
8390 		    signed_sub_overflows(smax_ptr, smin_val)) {
8391 			/* Overflow possible, we know nothing */
8392 			dst_reg->smin_value = S64_MIN;
8393 			dst_reg->smax_value = S64_MAX;
8394 		} else {
8395 			dst_reg->smin_value = smin_ptr - smax_val;
8396 			dst_reg->smax_value = smax_ptr - smin_val;
8397 		}
8398 		if (umin_ptr < umax_val) {
8399 			/* Overflow possible, we know nothing */
8400 			dst_reg->umin_value = 0;
8401 			dst_reg->umax_value = U64_MAX;
8402 		} else {
8403 			/* Cannot overflow (as long as bounds are consistent) */
8404 			dst_reg->umin_value = umin_ptr - umax_val;
8405 			dst_reg->umax_value = umax_ptr - umin_val;
8406 		}
8407 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8408 		dst_reg->off = ptr_reg->off;
8409 		dst_reg->raw = ptr_reg->raw;
8410 		if (reg_is_pkt_pointer(ptr_reg)) {
8411 			dst_reg->id = ++env->id_gen;
8412 			/* something was added to pkt_ptr, set range to zero */
8413 			if (smin_val < 0)
8414 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8415 		}
8416 		break;
8417 	case BPF_AND:
8418 	case BPF_OR:
8419 	case BPF_XOR:
8420 		/* bitwise ops on pointers are troublesome, prohibit. */
8421 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8422 			dst, bpf_alu_string[opcode >> 4]);
8423 		return -EACCES;
8424 	default:
8425 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
8426 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8427 			dst, bpf_alu_string[opcode >> 4]);
8428 		return -EACCES;
8429 	}
8430 
8431 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8432 		return -EINVAL;
8433 	reg_bounds_sync(dst_reg);
8434 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8435 		return -EACCES;
8436 	if (sanitize_needed(opcode)) {
8437 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8438 				       &info, true);
8439 		if (ret < 0)
8440 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
8441 	}
8442 
8443 	return 0;
8444 }
8445 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8446 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8447 				 struct bpf_reg_state *src_reg)
8448 {
8449 	s32 smin_val = src_reg->s32_min_value;
8450 	s32 smax_val = src_reg->s32_max_value;
8451 	u32 umin_val = src_reg->u32_min_value;
8452 	u32 umax_val = src_reg->u32_max_value;
8453 
8454 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8455 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8456 		dst_reg->s32_min_value = S32_MIN;
8457 		dst_reg->s32_max_value = S32_MAX;
8458 	} else {
8459 		dst_reg->s32_min_value += smin_val;
8460 		dst_reg->s32_max_value += smax_val;
8461 	}
8462 	if (dst_reg->u32_min_value + umin_val < umin_val ||
8463 	    dst_reg->u32_max_value + umax_val < umax_val) {
8464 		dst_reg->u32_min_value = 0;
8465 		dst_reg->u32_max_value = U32_MAX;
8466 	} else {
8467 		dst_reg->u32_min_value += umin_val;
8468 		dst_reg->u32_max_value += umax_val;
8469 	}
8470 }
8471 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8472 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8473 			       struct bpf_reg_state *src_reg)
8474 {
8475 	s64 smin_val = src_reg->smin_value;
8476 	s64 smax_val = src_reg->smax_value;
8477 	u64 umin_val = src_reg->umin_value;
8478 	u64 umax_val = src_reg->umax_value;
8479 
8480 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8481 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
8482 		dst_reg->smin_value = S64_MIN;
8483 		dst_reg->smax_value = S64_MAX;
8484 	} else {
8485 		dst_reg->smin_value += smin_val;
8486 		dst_reg->smax_value += smax_val;
8487 	}
8488 	if (dst_reg->umin_value + umin_val < umin_val ||
8489 	    dst_reg->umax_value + umax_val < umax_val) {
8490 		dst_reg->umin_value = 0;
8491 		dst_reg->umax_value = U64_MAX;
8492 	} else {
8493 		dst_reg->umin_value += umin_val;
8494 		dst_reg->umax_value += umax_val;
8495 	}
8496 }
8497 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8498 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8499 				 struct bpf_reg_state *src_reg)
8500 {
8501 	s32 smin_val = src_reg->s32_min_value;
8502 	s32 smax_val = src_reg->s32_max_value;
8503 	u32 umin_val = src_reg->u32_min_value;
8504 	u32 umax_val = src_reg->u32_max_value;
8505 
8506 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8507 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8508 		/* Overflow possible, we know nothing */
8509 		dst_reg->s32_min_value = S32_MIN;
8510 		dst_reg->s32_max_value = S32_MAX;
8511 	} else {
8512 		dst_reg->s32_min_value -= smax_val;
8513 		dst_reg->s32_max_value -= smin_val;
8514 	}
8515 	if (dst_reg->u32_min_value < umax_val) {
8516 		/* Overflow possible, we know nothing */
8517 		dst_reg->u32_min_value = 0;
8518 		dst_reg->u32_max_value = U32_MAX;
8519 	} else {
8520 		/* Cannot overflow (as long as bounds are consistent) */
8521 		dst_reg->u32_min_value -= umax_val;
8522 		dst_reg->u32_max_value -= umin_val;
8523 	}
8524 }
8525 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8526 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8527 			       struct bpf_reg_state *src_reg)
8528 {
8529 	s64 smin_val = src_reg->smin_value;
8530 	s64 smax_val = src_reg->smax_value;
8531 	u64 umin_val = src_reg->umin_value;
8532 	u64 umax_val = src_reg->umax_value;
8533 
8534 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8535 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8536 		/* Overflow possible, we know nothing */
8537 		dst_reg->smin_value = S64_MIN;
8538 		dst_reg->smax_value = S64_MAX;
8539 	} else {
8540 		dst_reg->smin_value -= smax_val;
8541 		dst_reg->smax_value -= smin_val;
8542 	}
8543 	if (dst_reg->umin_value < umax_val) {
8544 		/* Overflow possible, we know nothing */
8545 		dst_reg->umin_value = 0;
8546 		dst_reg->umax_value = U64_MAX;
8547 	} else {
8548 		/* Cannot overflow (as long as bounds are consistent) */
8549 		dst_reg->umin_value -= umax_val;
8550 		dst_reg->umax_value -= umin_val;
8551 	}
8552 }
8553 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8554 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8555 				 struct bpf_reg_state *src_reg)
8556 {
8557 	s32 smin_val = src_reg->s32_min_value;
8558 	u32 umin_val = src_reg->u32_min_value;
8559 	u32 umax_val = src_reg->u32_max_value;
8560 
8561 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8562 		/* Ain't nobody got time to multiply that sign */
8563 		__mark_reg32_unbounded(dst_reg);
8564 		return;
8565 	}
8566 	/* Both values are positive, so we can work with unsigned and
8567 	 * copy the result to signed (unless it exceeds S32_MAX).
8568 	 */
8569 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8570 		/* Potential overflow, we know nothing */
8571 		__mark_reg32_unbounded(dst_reg);
8572 		return;
8573 	}
8574 	dst_reg->u32_min_value *= umin_val;
8575 	dst_reg->u32_max_value *= umax_val;
8576 	if (dst_reg->u32_max_value > S32_MAX) {
8577 		/* Overflow possible, we know nothing */
8578 		dst_reg->s32_min_value = S32_MIN;
8579 		dst_reg->s32_max_value = S32_MAX;
8580 	} else {
8581 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8582 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8583 	}
8584 }
8585 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8586 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8587 			       struct bpf_reg_state *src_reg)
8588 {
8589 	s64 smin_val = src_reg->smin_value;
8590 	u64 umin_val = src_reg->umin_value;
8591 	u64 umax_val = src_reg->umax_value;
8592 
8593 	if (smin_val < 0 || dst_reg->smin_value < 0) {
8594 		/* Ain't nobody got time to multiply that sign */
8595 		__mark_reg64_unbounded(dst_reg);
8596 		return;
8597 	}
8598 	/* Both values are positive, so we can work with unsigned and
8599 	 * copy the result to signed (unless it exceeds S64_MAX).
8600 	 */
8601 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8602 		/* Potential overflow, we know nothing */
8603 		__mark_reg64_unbounded(dst_reg);
8604 		return;
8605 	}
8606 	dst_reg->umin_value *= umin_val;
8607 	dst_reg->umax_value *= umax_val;
8608 	if (dst_reg->umax_value > S64_MAX) {
8609 		/* Overflow possible, we know nothing */
8610 		dst_reg->smin_value = S64_MIN;
8611 		dst_reg->smax_value = S64_MAX;
8612 	} else {
8613 		dst_reg->smin_value = dst_reg->umin_value;
8614 		dst_reg->smax_value = dst_reg->umax_value;
8615 	}
8616 }
8617 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8618 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8619 				 struct bpf_reg_state *src_reg)
8620 {
8621 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8622 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8623 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8624 	s32 smin_val = src_reg->s32_min_value;
8625 	u32 umax_val = src_reg->u32_max_value;
8626 
8627 	if (src_known && dst_known) {
8628 		__mark_reg32_known(dst_reg, var32_off.value);
8629 		return;
8630 	}
8631 
8632 	/* We get our minimum from the var_off, since that's inherently
8633 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8634 	 */
8635 	dst_reg->u32_min_value = var32_off.value;
8636 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8637 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8638 		/* Lose signed bounds when ANDing negative numbers,
8639 		 * ain't nobody got time for that.
8640 		 */
8641 		dst_reg->s32_min_value = S32_MIN;
8642 		dst_reg->s32_max_value = S32_MAX;
8643 	} else {
8644 		/* ANDing two positives gives a positive, so safe to
8645 		 * cast result into s64.
8646 		 */
8647 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8648 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8649 	}
8650 }
8651 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8652 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8653 			       struct bpf_reg_state *src_reg)
8654 {
8655 	bool src_known = tnum_is_const(src_reg->var_off);
8656 	bool dst_known = tnum_is_const(dst_reg->var_off);
8657 	s64 smin_val = src_reg->smin_value;
8658 	u64 umax_val = src_reg->umax_value;
8659 
8660 	if (src_known && dst_known) {
8661 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8662 		return;
8663 	}
8664 
8665 	/* We get our minimum from the var_off, since that's inherently
8666 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
8667 	 */
8668 	dst_reg->umin_value = dst_reg->var_off.value;
8669 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8670 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8671 		/* Lose signed bounds when ANDing negative numbers,
8672 		 * ain't nobody got time for that.
8673 		 */
8674 		dst_reg->smin_value = S64_MIN;
8675 		dst_reg->smax_value = S64_MAX;
8676 	} else {
8677 		/* ANDing two positives gives a positive, so safe to
8678 		 * cast result into s64.
8679 		 */
8680 		dst_reg->smin_value = dst_reg->umin_value;
8681 		dst_reg->smax_value = dst_reg->umax_value;
8682 	}
8683 	/* We may learn something more from the var_off */
8684 	__update_reg_bounds(dst_reg);
8685 }
8686 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8687 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8688 				struct bpf_reg_state *src_reg)
8689 {
8690 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8691 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8692 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8693 	s32 smin_val = src_reg->s32_min_value;
8694 	u32 umin_val = src_reg->u32_min_value;
8695 
8696 	if (src_known && dst_known) {
8697 		__mark_reg32_known(dst_reg, var32_off.value);
8698 		return;
8699 	}
8700 
8701 	/* We get our maximum from the var_off, and our minimum is the
8702 	 * maximum of the operands' minima
8703 	 */
8704 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8705 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8706 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8707 		/* Lose signed bounds when ORing negative numbers,
8708 		 * ain't nobody got time for that.
8709 		 */
8710 		dst_reg->s32_min_value = S32_MIN;
8711 		dst_reg->s32_max_value = S32_MAX;
8712 	} else {
8713 		/* ORing two positives gives a positive, so safe to
8714 		 * cast result into s64.
8715 		 */
8716 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8717 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8718 	}
8719 }
8720 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8721 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8722 			      struct bpf_reg_state *src_reg)
8723 {
8724 	bool src_known = tnum_is_const(src_reg->var_off);
8725 	bool dst_known = tnum_is_const(dst_reg->var_off);
8726 	s64 smin_val = src_reg->smin_value;
8727 	u64 umin_val = src_reg->umin_value;
8728 
8729 	if (src_known && dst_known) {
8730 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8731 		return;
8732 	}
8733 
8734 	/* We get our maximum from the var_off, and our minimum is the
8735 	 * maximum of the operands' minima
8736 	 */
8737 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8738 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8739 	if (dst_reg->smin_value < 0 || smin_val < 0) {
8740 		/* Lose signed bounds when ORing negative numbers,
8741 		 * ain't nobody got time for that.
8742 		 */
8743 		dst_reg->smin_value = S64_MIN;
8744 		dst_reg->smax_value = S64_MAX;
8745 	} else {
8746 		/* ORing two positives gives a positive, so safe to
8747 		 * cast result into s64.
8748 		 */
8749 		dst_reg->smin_value = dst_reg->umin_value;
8750 		dst_reg->smax_value = dst_reg->umax_value;
8751 	}
8752 	/* We may learn something more from the var_off */
8753 	__update_reg_bounds(dst_reg);
8754 }
8755 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8756 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8757 				 struct bpf_reg_state *src_reg)
8758 {
8759 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
8760 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8761 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8762 	s32 smin_val = src_reg->s32_min_value;
8763 
8764 	if (src_known && dst_known) {
8765 		__mark_reg32_known(dst_reg, var32_off.value);
8766 		return;
8767 	}
8768 
8769 	/* We get both minimum and maximum from the var32_off. */
8770 	dst_reg->u32_min_value = var32_off.value;
8771 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8772 
8773 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8774 		/* XORing two positive sign numbers gives a positive,
8775 		 * so safe to cast u32 result into s32.
8776 		 */
8777 		dst_reg->s32_min_value = dst_reg->u32_min_value;
8778 		dst_reg->s32_max_value = dst_reg->u32_max_value;
8779 	} else {
8780 		dst_reg->s32_min_value = S32_MIN;
8781 		dst_reg->s32_max_value = S32_MAX;
8782 	}
8783 }
8784 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8785 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8786 			       struct bpf_reg_state *src_reg)
8787 {
8788 	bool src_known = tnum_is_const(src_reg->var_off);
8789 	bool dst_known = tnum_is_const(dst_reg->var_off);
8790 	s64 smin_val = src_reg->smin_value;
8791 
8792 	if (src_known && dst_known) {
8793 		/* dst_reg->var_off.value has been updated earlier */
8794 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
8795 		return;
8796 	}
8797 
8798 	/* We get both minimum and maximum from the var_off. */
8799 	dst_reg->umin_value = dst_reg->var_off.value;
8800 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8801 
8802 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8803 		/* XORing two positive sign numbers gives a positive,
8804 		 * so safe to cast u64 result into s64.
8805 		 */
8806 		dst_reg->smin_value = dst_reg->umin_value;
8807 		dst_reg->smax_value = dst_reg->umax_value;
8808 	} else {
8809 		dst_reg->smin_value = S64_MIN;
8810 		dst_reg->smax_value = S64_MAX;
8811 	}
8812 
8813 	__update_reg_bounds(dst_reg);
8814 }
8815 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)8816 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8817 				   u64 umin_val, u64 umax_val)
8818 {
8819 	/* We lose all sign bit information (except what we can pick
8820 	 * up from var_off)
8821 	 */
8822 	dst_reg->s32_min_value = S32_MIN;
8823 	dst_reg->s32_max_value = S32_MAX;
8824 	/* If we might shift our top bit out, then we know nothing */
8825 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8826 		dst_reg->u32_min_value = 0;
8827 		dst_reg->u32_max_value = U32_MAX;
8828 	} else {
8829 		dst_reg->u32_min_value <<= umin_val;
8830 		dst_reg->u32_max_value <<= umax_val;
8831 	}
8832 }
8833 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8834 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8835 				 struct bpf_reg_state *src_reg)
8836 {
8837 	u32 umax_val = src_reg->u32_max_value;
8838 	u32 umin_val = src_reg->u32_min_value;
8839 	/* u32 alu operation will zext upper bits */
8840 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8841 
8842 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8843 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8844 	/* Not required but being careful mark reg64 bounds as unknown so
8845 	 * that we are forced to pick them up from tnum and zext later and
8846 	 * if some path skips this step we are still safe.
8847 	 */
8848 	__mark_reg64_unbounded(dst_reg);
8849 	__update_reg32_bounds(dst_reg);
8850 }
8851 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)8852 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8853 				   u64 umin_val, u64 umax_val)
8854 {
8855 	/* Special case <<32 because it is a common compiler pattern to sign
8856 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8857 	 * positive we know this shift will also be positive so we can track
8858 	 * bounds correctly. Otherwise we lose all sign bit information except
8859 	 * what we can pick up from var_off. Perhaps we can generalize this
8860 	 * later to shifts of any length.
8861 	 */
8862 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8863 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8864 	else
8865 		dst_reg->smax_value = S64_MAX;
8866 
8867 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8868 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8869 	else
8870 		dst_reg->smin_value = S64_MIN;
8871 
8872 	/* If we might shift our top bit out, then we know nothing */
8873 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8874 		dst_reg->umin_value = 0;
8875 		dst_reg->umax_value = U64_MAX;
8876 	} else {
8877 		dst_reg->umin_value <<= umin_val;
8878 		dst_reg->umax_value <<= umax_val;
8879 	}
8880 }
8881 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8882 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8883 			       struct bpf_reg_state *src_reg)
8884 {
8885 	u64 umax_val = src_reg->umax_value;
8886 	u64 umin_val = src_reg->umin_value;
8887 
8888 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
8889 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8890 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8891 
8892 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8893 	/* We may learn something more from the var_off */
8894 	__update_reg_bounds(dst_reg);
8895 }
8896 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8897 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8898 				 struct bpf_reg_state *src_reg)
8899 {
8900 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
8901 	u32 umax_val = src_reg->u32_max_value;
8902 	u32 umin_val = src_reg->u32_min_value;
8903 
8904 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8905 	 * be negative, then either:
8906 	 * 1) src_reg might be zero, so the sign bit of the result is
8907 	 *    unknown, so we lose our signed bounds
8908 	 * 2) it's known negative, thus the unsigned bounds capture the
8909 	 *    signed bounds
8910 	 * 3) the signed bounds cross zero, so they tell us nothing
8911 	 *    about the result
8912 	 * If the value in dst_reg is known nonnegative, then again the
8913 	 * unsigned bounds capture the signed bounds.
8914 	 * Thus, in all cases it suffices to blow away our signed bounds
8915 	 * and rely on inferring new ones from the unsigned bounds and
8916 	 * var_off of the result.
8917 	 */
8918 	dst_reg->s32_min_value = S32_MIN;
8919 	dst_reg->s32_max_value = S32_MAX;
8920 
8921 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
8922 	dst_reg->u32_min_value >>= umax_val;
8923 	dst_reg->u32_max_value >>= umin_val;
8924 
8925 	__mark_reg64_unbounded(dst_reg);
8926 	__update_reg32_bounds(dst_reg);
8927 }
8928 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8929 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8930 			       struct bpf_reg_state *src_reg)
8931 {
8932 	u64 umax_val = src_reg->umax_value;
8933 	u64 umin_val = src_reg->umin_value;
8934 
8935 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8936 	 * be negative, then either:
8937 	 * 1) src_reg might be zero, so the sign bit of the result is
8938 	 *    unknown, so we lose our signed bounds
8939 	 * 2) it's known negative, thus the unsigned bounds capture the
8940 	 *    signed bounds
8941 	 * 3) the signed bounds cross zero, so they tell us nothing
8942 	 *    about the result
8943 	 * If the value in dst_reg is known nonnegative, then again the
8944 	 * unsigned bounds capture the signed bounds.
8945 	 * Thus, in all cases it suffices to blow away our signed bounds
8946 	 * and rely on inferring new ones from the unsigned bounds and
8947 	 * var_off of the result.
8948 	 */
8949 	dst_reg->smin_value = S64_MIN;
8950 	dst_reg->smax_value = S64_MAX;
8951 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8952 	dst_reg->umin_value >>= umax_val;
8953 	dst_reg->umax_value >>= umin_val;
8954 
8955 	/* Its not easy to operate on alu32 bounds here because it depends
8956 	 * on bits being shifted in. Take easy way out and mark unbounded
8957 	 * so we can recalculate later from tnum.
8958 	 */
8959 	__mark_reg32_unbounded(dst_reg);
8960 	__update_reg_bounds(dst_reg);
8961 }
8962 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8963 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8964 				  struct bpf_reg_state *src_reg)
8965 {
8966 	u64 umin_val = src_reg->u32_min_value;
8967 
8968 	/* Upon reaching here, src_known is true and
8969 	 * umax_val is equal to umin_val.
8970 	 */
8971 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8972 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8973 
8974 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8975 
8976 	/* blow away the dst_reg umin_value/umax_value and rely on
8977 	 * dst_reg var_off to refine the result.
8978 	 */
8979 	dst_reg->u32_min_value = 0;
8980 	dst_reg->u32_max_value = U32_MAX;
8981 
8982 	__mark_reg64_unbounded(dst_reg);
8983 	__update_reg32_bounds(dst_reg);
8984 }
8985 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8986 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8987 				struct bpf_reg_state *src_reg)
8988 {
8989 	u64 umin_val = src_reg->umin_value;
8990 
8991 	/* Upon reaching here, src_known is true and umax_val is equal
8992 	 * to umin_val.
8993 	 */
8994 	dst_reg->smin_value >>= umin_val;
8995 	dst_reg->smax_value >>= umin_val;
8996 
8997 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8998 
8999 	/* blow away the dst_reg umin_value/umax_value and rely on
9000 	 * dst_reg var_off to refine the result.
9001 	 */
9002 	dst_reg->umin_value = 0;
9003 	dst_reg->umax_value = U64_MAX;
9004 
9005 	/* Its not easy to operate on alu32 bounds here because it depends
9006 	 * on bits being shifted in from upper 32-bits. Take easy way out
9007 	 * and mark unbounded so we can recalculate later from tnum.
9008 	 */
9009 	__mark_reg32_unbounded(dst_reg);
9010 	__update_reg_bounds(dst_reg);
9011 }
9012 
9013 /* WARNING: This function does calculations on 64-bit values, but the actual
9014  * execution may occur on 32-bit values. Therefore, things like bitshifts
9015  * need extra checks in the 32-bit case.
9016  */
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)9017 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9018 				      struct bpf_insn *insn,
9019 				      struct bpf_reg_state *dst_reg,
9020 				      struct bpf_reg_state src_reg)
9021 {
9022 	struct bpf_reg_state *regs = cur_regs(env);
9023 	u8 opcode = BPF_OP(insn->code);
9024 	bool src_known;
9025 	s64 smin_val, smax_val;
9026 	u64 umin_val, umax_val;
9027 	s32 s32_min_val, s32_max_val;
9028 	u32 u32_min_val, u32_max_val;
9029 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9030 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9031 	int ret;
9032 
9033 	smin_val = src_reg.smin_value;
9034 	smax_val = src_reg.smax_value;
9035 	umin_val = src_reg.umin_value;
9036 	umax_val = src_reg.umax_value;
9037 
9038 	s32_min_val = src_reg.s32_min_value;
9039 	s32_max_val = src_reg.s32_max_value;
9040 	u32_min_val = src_reg.u32_min_value;
9041 	u32_max_val = src_reg.u32_max_value;
9042 
9043 	if (alu32) {
9044 		src_known = tnum_subreg_is_const(src_reg.var_off);
9045 		if ((src_known &&
9046 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9047 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9048 			/* Taint dst register if offset had invalid bounds
9049 			 * derived from e.g. dead branches.
9050 			 */
9051 			__mark_reg_unknown(env, dst_reg);
9052 			return 0;
9053 		}
9054 	} else {
9055 		src_known = tnum_is_const(src_reg.var_off);
9056 		if ((src_known &&
9057 		     (smin_val != smax_val || umin_val != umax_val)) ||
9058 		    smin_val > smax_val || umin_val > umax_val) {
9059 			/* Taint dst register if offset had invalid bounds
9060 			 * derived from e.g. dead branches.
9061 			 */
9062 			__mark_reg_unknown(env, dst_reg);
9063 			return 0;
9064 		}
9065 	}
9066 
9067 	if (!src_known &&
9068 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9069 		__mark_reg_unknown(env, dst_reg);
9070 		return 0;
9071 	}
9072 
9073 	if (sanitize_needed(opcode)) {
9074 		ret = sanitize_val_alu(env, insn);
9075 		if (ret < 0)
9076 			return sanitize_err(env, insn, ret, NULL, NULL);
9077 	}
9078 
9079 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9080 	 * There are two classes of instructions: The first class we track both
9081 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
9082 	 * greatest amount of precision when alu operations are mixed with jmp32
9083 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9084 	 * and BPF_OR. This is possible because these ops have fairly easy to
9085 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9086 	 * See alu32 verifier tests for examples. The second class of
9087 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9088 	 * with regards to tracking sign/unsigned bounds because the bits may
9089 	 * cross subreg boundaries in the alu64 case. When this happens we mark
9090 	 * the reg unbounded in the subreg bound space and use the resulting
9091 	 * tnum to calculate an approximation of the sign/unsigned bounds.
9092 	 */
9093 	switch (opcode) {
9094 	case BPF_ADD:
9095 		scalar32_min_max_add(dst_reg, &src_reg);
9096 		scalar_min_max_add(dst_reg, &src_reg);
9097 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9098 		break;
9099 	case BPF_SUB:
9100 		scalar32_min_max_sub(dst_reg, &src_reg);
9101 		scalar_min_max_sub(dst_reg, &src_reg);
9102 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9103 		break;
9104 	case BPF_MUL:
9105 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9106 		scalar32_min_max_mul(dst_reg, &src_reg);
9107 		scalar_min_max_mul(dst_reg, &src_reg);
9108 		break;
9109 	case BPF_AND:
9110 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9111 		scalar32_min_max_and(dst_reg, &src_reg);
9112 		scalar_min_max_and(dst_reg, &src_reg);
9113 		break;
9114 	case BPF_OR:
9115 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9116 		scalar32_min_max_or(dst_reg, &src_reg);
9117 		scalar_min_max_or(dst_reg, &src_reg);
9118 		break;
9119 	case BPF_XOR:
9120 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9121 		scalar32_min_max_xor(dst_reg, &src_reg);
9122 		scalar_min_max_xor(dst_reg, &src_reg);
9123 		break;
9124 	case BPF_LSH:
9125 		if (umax_val >= insn_bitness) {
9126 			/* Shifts greater than 31 or 63 are undefined.
9127 			 * This includes shifts by a negative number.
9128 			 */
9129 			mark_reg_unknown(env, regs, insn->dst_reg);
9130 			break;
9131 		}
9132 		if (alu32)
9133 			scalar32_min_max_lsh(dst_reg, &src_reg);
9134 		else
9135 			scalar_min_max_lsh(dst_reg, &src_reg);
9136 		break;
9137 	case BPF_RSH:
9138 		if (umax_val >= insn_bitness) {
9139 			/* Shifts greater than 31 or 63 are undefined.
9140 			 * This includes shifts by a negative number.
9141 			 */
9142 			mark_reg_unknown(env, regs, insn->dst_reg);
9143 			break;
9144 		}
9145 		if (alu32)
9146 			scalar32_min_max_rsh(dst_reg, &src_reg);
9147 		else
9148 			scalar_min_max_rsh(dst_reg, &src_reg);
9149 		break;
9150 	case BPF_ARSH:
9151 		if (umax_val >= insn_bitness) {
9152 			/* Shifts greater than 31 or 63 are undefined.
9153 			 * This includes shifts by a negative number.
9154 			 */
9155 			mark_reg_unknown(env, regs, insn->dst_reg);
9156 			break;
9157 		}
9158 		if (alu32)
9159 			scalar32_min_max_arsh(dst_reg, &src_reg);
9160 		else
9161 			scalar_min_max_arsh(dst_reg, &src_reg);
9162 		break;
9163 	default:
9164 		mark_reg_unknown(env, regs, insn->dst_reg);
9165 		break;
9166 	}
9167 
9168 	/* ALU32 ops are zero extended into 64bit register */
9169 	if (alu32)
9170 		zext_32_to_64(dst_reg);
9171 	reg_bounds_sync(dst_reg);
9172 	return 0;
9173 }
9174 
9175 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9176  * and var_off.
9177  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)9178 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9179 				   struct bpf_insn *insn)
9180 {
9181 	struct bpf_verifier_state *vstate = env->cur_state;
9182 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9183 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9184 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9185 	u8 opcode = BPF_OP(insn->code);
9186 	int err;
9187 
9188 	dst_reg = &regs[insn->dst_reg];
9189 	src_reg = NULL;
9190 	if (dst_reg->type != SCALAR_VALUE)
9191 		ptr_reg = dst_reg;
9192 	else
9193 		/* Make sure ID is cleared otherwise dst_reg min/max could be
9194 		 * incorrectly propagated into other registers by find_equal_scalars()
9195 		 */
9196 		dst_reg->id = 0;
9197 	if (BPF_SRC(insn->code) == BPF_X) {
9198 		src_reg = &regs[insn->src_reg];
9199 		if (src_reg->type != SCALAR_VALUE) {
9200 			if (dst_reg->type != SCALAR_VALUE) {
9201 				/* Combining two pointers by any ALU op yields
9202 				 * an arbitrary scalar. Disallow all math except
9203 				 * pointer subtraction
9204 				 */
9205 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9206 					mark_reg_unknown(env, regs, insn->dst_reg);
9207 					return 0;
9208 				}
9209 				verbose(env, "R%d pointer %s pointer prohibited\n",
9210 					insn->dst_reg,
9211 					bpf_alu_string[opcode >> 4]);
9212 				return -EACCES;
9213 			} else {
9214 				/* scalar += pointer
9215 				 * This is legal, but we have to reverse our
9216 				 * src/dest handling in computing the range
9217 				 */
9218 				err = mark_chain_precision(env, insn->dst_reg);
9219 				if (err)
9220 					return err;
9221 				return adjust_ptr_min_max_vals(env, insn,
9222 							       src_reg, dst_reg);
9223 			}
9224 		} else if (ptr_reg) {
9225 			/* pointer += scalar */
9226 			err = mark_chain_precision(env, insn->src_reg);
9227 			if (err)
9228 				return err;
9229 			return adjust_ptr_min_max_vals(env, insn,
9230 						       dst_reg, src_reg);
9231 		} else if (dst_reg->precise) {
9232 			/* if dst_reg is precise, src_reg should be precise as well */
9233 			err = mark_chain_precision(env, insn->src_reg);
9234 			if (err)
9235 				return err;
9236 		}
9237 	} else {
9238 		/* Pretend the src is a reg with a known value, since we only
9239 		 * need to be able to read from this state.
9240 		 */
9241 		off_reg.type = SCALAR_VALUE;
9242 		__mark_reg_known(&off_reg, insn->imm);
9243 		src_reg = &off_reg;
9244 		if (ptr_reg) /* pointer += K */
9245 			return adjust_ptr_min_max_vals(env, insn,
9246 						       ptr_reg, src_reg);
9247 	}
9248 
9249 	/* Got here implies adding two SCALAR_VALUEs */
9250 	if (WARN_ON_ONCE(ptr_reg)) {
9251 		print_verifier_state(env, state, true);
9252 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
9253 		return -EINVAL;
9254 	}
9255 	if (WARN_ON(!src_reg)) {
9256 		print_verifier_state(env, state, true);
9257 		verbose(env, "verifier internal error: no src_reg\n");
9258 		return -EINVAL;
9259 	}
9260 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9261 }
9262 
9263 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)9264 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9265 {
9266 	struct bpf_reg_state *regs = cur_regs(env);
9267 	u8 opcode = BPF_OP(insn->code);
9268 	int err;
9269 
9270 	if (opcode == BPF_END || opcode == BPF_NEG) {
9271 		if (opcode == BPF_NEG) {
9272 			if (BPF_SRC(insn->code) != BPF_K ||
9273 			    insn->src_reg != BPF_REG_0 ||
9274 			    insn->off != 0 || insn->imm != 0) {
9275 				verbose(env, "BPF_NEG uses reserved fields\n");
9276 				return -EINVAL;
9277 			}
9278 		} else {
9279 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9280 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9281 			    BPF_CLASS(insn->code) == BPF_ALU64) {
9282 				verbose(env, "BPF_END uses reserved fields\n");
9283 				return -EINVAL;
9284 			}
9285 		}
9286 
9287 		/* check src operand */
9288 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9289 		if (err)
9290 			return err;
9291 
9292 		if (is_pointer_value(env, insn->dst_reg)) {
9293 			verbose(env, "R%d pointer arithmetic prohibited\n",
9294 				insn->dst_reg);
9295 			return -EACCES;
9296 		}
9297 
9298 		/* check dest operand */
9299 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
9300 		if (err)
9301 			return err;
9302 
9303 	} else if (opcode == BPF_MOV) {
9304 
9305 		if (BPF_SRC(insn->code) == BPF_X) {
9306 			if (insn->imm != 0 || insn->off != 0) {
9307 				verbose(env, "BPF_MOV uses reserved fields\n");
9308 				return -EINVAL;
9309 			}
9310 
9311 			/* check src operand */
9312 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9313 			if (err)
9314 				return err;
9315 		} else {
9316 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9317 				verbose(env, "BPF_MOV uses reserved fields\n");
9318 				return -EINVAL;
9319 			}
9320 		}
9321 
9322 		/* check dest operand, mark as required later */
9323 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9324 		if (err)
9325 			return err;
9326 
9327 		if (BPF_SRC(insn->code) == BPF_X) {
9328 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
9329 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9330 
9331 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9332 				/* case: R1 = R2
9333 				 * copy register state to dest reg
9334 				 */
9335 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9336 					/* Assign src and dst registers the same ID
9337 					 * that will be used by find_equal_scalars()
9338 					 * to propagate min/max range.
9339 					 */
9340 					src_reg->id = ++env->id_gen;
9341 				*dst_reg = *src_reg;
9342 				dst_reg->live |= REG_LIVE_WRITTEN;
9343 				dst_reg->subreg_def = DEF_NOT_SUBREG;
9344 			} else {
9345 				/* R1 = (u32) R2 */
9346 				if (is_pointer_value(env, insn->src_reg)) {
9347 					verbose(env,
9348 						"R%d partial copy of pointer\n",
9349 						insn->src_reg);
9350 					return -EACCES;
9351 				} else if (src_reg->type == SCALAR_VALUE) {
9352 					*dst_reg = *src_reg;
9353 					/* Make sure ID is cleared otherwise
9354 					 * dst_reg min/max could be incorrectly
9355 					 * propagated into src_reg by find_equal_scalars()
9356 					 */
9357 					dst_reg->id = 0;
9358 					dst_reg->live |= REG_LIVE_WRITTEN;
9359 					dst_reg->subreg_def = env->insn_idx + 1;
9360 				} else {
9361 					mark_reg_unknown(env, regs,
9362 							 insn->dst_reg);
9363 				}
9364 				zext_32_to_64(dst_reg);
9365 				reg_bounds_sync(dst_reg);
9366 			}
9367 		} else {
9368 			/* case: R = imm
9369 			 * remember the value we stored into this reg
9370 			 */
9371 			/* clear any state __mark_reg_known doesn't set */
9372 			mark_reg_unknown(env, regs, insn->dst_reg);
9373 			regs[insn->dst_reg].type = SCALAR_VALUE;
9374 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
9375 				__mark_reg_known(regs + insn->dst_reg,
9376 						 insn->imm);
9377 			} else {
9378 				__mark_reg_known(regs + insn->dst_reg,
9379 						 (u32)insn->imm);
9380 			}
9381 		}
9382 
9383 	} else if (opcode > BPF_END) {
9384 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9385 		return -EINVAL;
9386 
9387 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
9388 
9389 		if (BPF_SRC(insn->code) == BPF_X) {
9390 			if (insn->imm != 0 || insn->off != 0) {
9391 				verbose(env, "BPF_ALU uses reserved fields\n");
9392 				return -EINVAL;
9393 			}
9394 			/* check src1 operand */
9395 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9396 			if (err)
9397 				return err;
9398 		} else {
9399 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9400 				verbose(env, "BPF_ALU uses reserved fields\n");
9401 				return -EINVAL;
9402 			}
9403 		}
9404 
9405 		/* check src2 operand */
9406 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9407 		if (err)
9408 			return err;
9409 
9410 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9411 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9412 			verbose(env, "div by zero\n");
9413 			return -EINVAL;
9414 		}
9415 
9416 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9417 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9418 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9419 
9420 			if (insn->imm < 0 || insn->imm >= size) {
9421 				verbose(env, "invalid shift %d\n", insn->imm);
9422 				return -EINVAL;
9423 			}
9424 		}
9425 
9426 		/* check dest operand */
9427 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9428 		if (err)
9429 			return err;
9430 
9431 		return adjust_reg_min_max_vals(env, insn);
9432 	}
9433 
9434 	return 0;
9435 }
9436 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)9437 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9438 				   struct bpf_reg_state *dst_reg,
9439 				   enum bpf_reg_type type,
9440 				   bool range_right_open)
9441 {
9442 	struct bpf_func_state *state;
9443 	struct bpf_reg_state *reg;
9444 	int new_range;
9445 
9446 	if (dst_reg->off < 0 ||
9447 	    (dst_reg->off == 0 && range_right_open))
9448 		/* This doesn't give us any range */
9449 		return;
9450 
9451 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
9452 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9453 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
9454 		 * than pkt_end, but that's because it's also less than pkt.
9455 		 */
9456 		return;
9457 
9458 	new_range = dst_reg->off;
9459 	if (range_right_open)
9460 		new_range++;
9461 
9462 	/* Examples for register markings:
9463 	 *
9464 	 * pkt_data in dst register:
9465 	 *
9466 	 *   r2 = r3;
9467 	 *   r2 += 8;
9468 	 *   if (r2 > pkt_end) goto <handle exception>
9469 	 *   <access okay>
9470 	 *
9471 	 *   r2 = r3;
9472 	 *   r2 += 8;
9473 	 *   if (r2 < pkt_end) goto <access okay>
9474 	 *   <handle exception>
9475 	 *
9476 	 *   Where:
9477 	 *     r2 == dst_reg, pkt_end == src_reg
9478 	 *     r2=pkt(id=n,off=8,r=0)
9479 	 *     r3=pkt(id=n,off=0,r=0)
9480 	 *
9481 	 * pkt_data in src register:
9482 	 *
9483 	 *   r2 = r3;
9484 	 *   r2 += 8;
9485 	 *   if (pkt_end >= r2) goto <access okay>
9486 	 *   <handle exception>
9487 	 *
9488 	 *   r2 = r3;
9489 	 *   r2 += 8;
9490 	 *   if (pkt_end <= r2) goto <handle exception>
9491 	 *   <access okay>
9492 	 *
9493 	 *   Where:
9494 	 *     pkt_end == dst_reg, r2 == src_reg
9495 	 *     r2=pkt(id=n,off=8,r=0)
9496 	 *     r3=pkt(id=n,off=0,r=0)
9497 	 *
9498 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9499 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9500 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
9501 	 * the check.
9502 	 */
9503 
9504 	/* If our ids match, then we must have the same max_value.  And we
9505 	 * don't care about the other reg's fixed offset, since if it's too big
9506 	 * the range won't allow anything.
9507 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9508 	 */
9509 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9510 		if (reg->type == type && reg->id == dst_reg->id)
9511 			/* keep the maximum range already checked */
9512 			reg->range = max(reg->range, new_range);
9513 	}));
9514 }
9515 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)9516 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9517 {
9518 	struct tnum subreg = tnum_subreg(reg->var_off);
9519 	s32 sval = (s32)val;
9520 
9521 	switch (opcode) {
9522 	case BPF_JEQ:
9523 		if (tnum_is_const(subreg))
9524 			return !!tnum_equals_const(subreg, val);
9525 		break;
9526 	case BPF_JNE:
9527 		if (tnum_is_const(subreg))
9528 			return !tnum_equals_const(subreg, val);
9529 		break;
9530 	case BPF_JSET:
9531 		if ((~subreg.mask & subreg.value) & val)
9532 			return 1;
9533 		if (!((subreg.mask | subreg.value) & val))
9534 			return 0;
9535 		break;
9536 	case BPF_JGT:
9537 		if (reg->u32_min_value > val)
9538 			return 1;
9539 		else if (reg->u32_max_value <= val)
9540 			return 0;
9541 		break;
9542 	case BPF_JSGT:
9543 		if (reg->s32_min_value > sval)
9544 			return 1;
9545 		else if (reg->s32_max_value <= sval)
9546 			return 0;
9547 		break;
9548 	case BPF_JLT:
9549 		if (reg->u32_max_value < val)
9550 			return 1;
9551 		else if (reg->u32_min_value >= val)
9552 			return 0;
9553 		break;
9554 	case BPF_JSLT:
9555 		if (reg->s32_max_value < sval)
9556 			return 1;
9557 		else if (reg->s32_min_value >= sval)
9558 			return 0;
9559 		break;
9560 	case BPF_JGE:
9561 		if (reg->u32_min_value >= val)
9562 			return 1;
9563 		else if (reg->u32_max_value < val)
9564 			return 0;
9565 		break;
9566 	case BPF_JSGE:
9567 		if (reg->s32_min_value >= sval)
9568 			return 1;
9569 		else if (reg->s32_max_value < sval)
9570 			return 0;
9571 		break;
9572 	case BPF_JLE:
9573 		if (reg->u32_max_value <= val)
9574 			return 1;
9575 		else if (reg->u32_min_value > val)
9576 			return 0;
9577 		break;
9578 	case BPF_JSLE:
9579 		if (reg->s32_max_value <= sval)
9580 			return 1;
9581 		else if (reg->s32_min_value > sval)
9582 			return 0;
9583 		break;
9584 	}
9585 
9586 	return -1;
9587 }
9588 
9589 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)9590 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9591 {
9592 	s64 sval = (s64)val;
9593 
9594 	switch (opcode) {
9595 	case BPF_JEQ:
9596 		if (tnum_is_const(reg->var_off))
9597 			return !!tnum_equals_const(reg->var_off, val);
9598 		break;
9599 	case BPF_JNE:
9600 		if (tnum_is_const(reg->var_off))
9601 			return !tnum_equals_const(reg->var_off, val);
9602 		break;
9603 	case BPF_JSET:
9604 		if ((~reg->var_off.mask & reg->var_off.value) & val)
9605 			return 1;
9606 		if (!((reg->var_off.mask | reg->var_off.value) & val))
9607 			return 0;
9608 		break;
9609 	case BPF_JGT:
9610 		if (reg->umin_value > val)
9611 			return 1;
9612 		else if (reg->umax_value <= val)
9613 			return 0;
9614 		break;
9615 	case BPF_JSGT:
9616 		if (reg->smin_value > sval)
9617 			return 1;
9618 		else if (reg->smax_value <= sval)
9619 			return 0;
9620 		break;
9621 	case BPF_JLT:
9622 		if (reg->umax_value < val)
9623 			return 1;
9624 		else if (reg->umin_value >= val)
9625 			return 0;
9626 		break;
9627 	case BPF_JSLT:
9628 		if (reg->smax_value < sval)
9629 			return 1;
9630 		else if (reg->smin_value >= sval)
9631 			return 0;
9632 		break;
9633 	case BPF_JGE:
9634 		if (reg->umin_value >= val)
9635 			return 1;
9636 		else if (reg->umax_value < val)
9637 			return 0;
9638 		break;
9639 	case BPF_JSGE:
9640 		if (reg->smin_value >= sval)
9641 			return 1;
9642 		else if (reg->smax_value < sval)
9643 			return 0;
9644 		break;
9645 	case BPF_JLE:
9646 		if (reg->umax_value <= val)
9647 			return 1;
9648 		else if (reg->umin_value > val)
9649 			return 0;
9650 		break;
9651 	case BPF_JSLE:
9652 		if (reg->smax_value <= sval)
9653 			return 1;
9654 		else if (reg->smin_value > sval)
9655 			return 0;
9656 		break;
9657 	}
9658 
9659 	return -1;
9660 }
9661 
9662 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9663  * and return:
9664  *  1 - branch will be taken and "goto target" will be executed
9665  *  0 - branch will not be taken and fall-through to next insn
9666  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9667  *      range [0,10]
9668  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)9669 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9670 			   bool is_jmp32)
9671 {
9672 	if (__is_pointer_value(false, reg)) {
9673 		if (!reg_type_not_null(reg->type))
9674 			return -1;
9675 
9676 		/* If pointer is valid tests against zero will fail so we can
9677 		 * use this to direct branch taken.
9678 		 */
9679 		if (val != 0)
9680 			return -1;
9681 
9682 		switch (opcode) {
9683 		case BPF_JEQ:
9684 			return 0;
9685 		case BPF_JNE:
9686 			return 1;
9687 		default:
9688 			return -1;
9689 		}
9690 	}
9691 
9692 	if (is_jmp32)
9693 		return is_branch32_taken(reg, val, opcode);
9694 	return is_branch64_taken(reg, val, opcode);
9695 }
9696 
flip_opcode(u32 opcode)9697 static int flip_opcode(u32 opcode)
9698 {
9699 	/* How can we transform "a <op> b" into "b <op> a"? */
9700 	static const u8 opcode_flip[16] = {
9701 		/* these stay the same */
9702 		[BPF_JEQ  >> 4] = BPF_JEQ,
9703 		[BPF_JNE  >> 4] = BPF_JNE,
9704 		[BPF_JSET >> 4] = BPF_JSET,
9705 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
9706 		[BPF_JGE  >> 4] = BPF_JLE,
9707 		[BPF_JGT  >> 4] = BPF_JLT,
9708 		[BPF_JLE  >> 4] = BPF_JGE,
9709 		[BPF_JLT  >> 4] = BPF_JGT,
9710 		[BPF_JSGE >> 4] = BPF_JSLE,
9711 		[BPF_JSGT >> 4] = BPF_JSLT,
9712 		[BPF_JSLE >> 4] = BPF_JSGE,
9713 		[BPF_JSLT >> 4] = BPF_JSGT
9714 	};
9715 	return opcode_flip[opcode >> 4];
9716 }
9717 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)9718 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9719 				   struct bpf_reg_state *src_reg,
9720 				   u8 opcode)
9721 {
9722 	struct bpf_reg_state *pkt;
9723 
9724 	if (src_reg->type == PTR_TO_PACKET_END) {
9725 		pkt = dst_reg;
9726 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
9727 		pkt = src_reg;
9728 		opcode = flip_opcode(opcode);
9729 	} else {
9730 		return -1;
9731 	}
9732 
9733 	if (pkt->range >= 0)
9734 		return -1;
9735 
9736 	switch (opcode) {
9737 	case BPF_JLE:
9738 		/* pkt <= pkt_end */
9739 		fallthrough;
9740 	case BPF_JGT:
9741 		/* pkt > pkt_end */
9742 		if (pkt->range == BEYOND_PKT_END)
9743 			/* pkt has at last one extra byte beyond pkt_end */
9744 			return opcode == BPF_JGT;
9745 		break;
9746 	case BPF_JLT:
9747 		/* pkt < pkt_end */
9748 		fallthrough;
9749 	case BPF_JGE:
9750 		/* pkt >= pkt_end */
9751 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9752 			return opcode == BPF_JGE;
9753 		break;
9754 	}
9755 	return -1;
9756 }
9757 
9758 /* Adjusts the register min/max values in the case that the dst_reg is the
9759  * variable register that we are working on, and src_reg is a constant or we're
9760  * simply doing a BPF_K check.
9761  * In JEQ/JNE cases we also adjust the var_off values.
9762  */
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)9763 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9764 			    struct bpf_reg_state *false_reg,
9765 			    u64 val, u32 val32,
9766 			    u8 opcode, bool is_jmp32)
9767 {
9768 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
9769 	struct tnum false_64off = false_reg->var_off;
9770 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
9771 	struct tnum true_64off = true_reg->var_off;
9772 	s64 sval = (s64)val;
9773 	s32 sval32 = (s32)val32;
9774 
9775 	/* If the dst_reg is a pointer, we can't learn anything about its
9776 	 * variable offset from the compare (unless src_reg were a pointer into
9777 	 * the same object, but we don't bother with that.
9778 	 * Since false_reg and true_reg have the same type by construction, we
9779 	 * only need to check one of them for pointerness.
9780 	 */
9781 	if (__is_pointer_value(false, false_reg))
9782 		return;
9783 
9784 	switch (opcode) {
9785 	/* JEQ/JNE comparison doesn't change the register equivalence.
9786 	 *
9787 	 * r1 = r2;
9788 	 * if (r1 == 42) goto label;
9789 	 * ...
9790 	 * label: // here both r1 and r2 are known to be 42.
9791 	 *
9792 	 * Hence when marking register as known preserve it's ID.
9793 	 */
9794 	case BPF_JEQ:
9795 		if (is_jmp32) {
9796 			__mark_reg32_known(true_reg, val32);
9797 			true_32off = tnum_subreg(true_reg->var_off);
9798 		} else {
9799 			___mark_reg_known(true_reg, val);
9800 			true_64off = true_reg->var_off;
9801 		}
9802 		break;
9803 	case BPF_JNE:
9804 		if (is_jmp32) {
9805 			__mark_reg32_known(false_reg, val32);
9806 			false_32off = tnum_subreg(false_reg->var_off);
9807 		} else {
9808 			___mark_reg_known(false_reg, val);
9809 			false_64off = false_reg->var_off;
9810 		}
9811 		break;
9812 	case BPF_JSET:
9813 		if (is_jmp32) {
9814 			false_32off = tnum_and(false_32off, tnum_const(~val32));
9815 			if (is_power_of_2(val32))
9816 				true_32off = tnum_or(true_32off,
9817 						     tnum_const(val32));
9818 		} else {
9819 			false_64off = tnum_and(false_64off, tnum_const(~val));
9820 			if (is_power_of_2(val))
9821 				true_64off = tnum_or(true_64off,
9822 						     tnum_const(val));
9823 		}
9824 		break;
9825 	case BPF_JGE:
9826 	case BPF_JGT:
9827 	{
9828 		if (is_jmp32) {
9829 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9830 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9831 
9832 			false_reg->u32_max_value = min(false_reg->u32_max_value,
9833 						       false_umax);
9834 			true_reg->u32_min_value = max(true_reg->u32_min_value,
9835 						      true_umin);
9836 		} else {
9837 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9838 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9839 
9840 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
9841 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
9842 		}
9843 		break;
9844 	}
9845 	case BPF_JSGE:
9846 	case BPF_JSGT:
9847 	{
9848 		if (is_jmp32) {
9849 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9850 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9851 
9852 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9853 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9854 		} else {
9855 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9856 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9857 
9858 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
9859 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
9860 		}
9861 		break;
9862 	}
9863 	case BPF_JLE:
9864 	case BPF_JLT:
9865 	{
9866 		if (is_jmp32) {
9867 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9868 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9869 
9870 			false_reg->u32_min_value = max(false_reg->u32_min_value,
9871 						       false_umin);
9872 			true_reg->u32_max_value = min(true_reg->u32_max_value,
9873 						      true_umax);
9874 		} else {
9875 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9876 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9877 
9878 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
9879 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
9880 		}
9881 		break;
9882 	}
9883 	case BPF_JSLE:
9884 	case BPF_JSLT:
9885 	{
9886 		if (is_jmp32) {
9887 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9888 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9889 
9890 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9891 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9892 		} else {
9893 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9894 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9895 
9896 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
9897 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
9898 		}
9899 		break;
9900 	}
9901 	default:
9902 		return;
9903 	}
9904 
9905 	if (is_jmp32) {
9906 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9907 					     tnum_subreg(false_32off));
9908 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9909 					    tnum_subreg(true_32off));
9910 		__reg_combine_32_into_64(false_reg);
9911 		__reg_combine_32_into_64(true_reg);
9912 	} else {
9913 		false_reg->var_off = false_64off;
9914 		true_reg->var_off = true_64off;
9915 		__reg_combine_64_into_32(false_reg);
9916 		__reg_combine_64_into_32(true_reg);
9917 	}
9918 }
9919 
9920 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9921  * the variable reg.
9922  */
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)9923 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9924 				struct bpf_reg_state *false_reg,
9925 				u64 val, u32 val32,
9926 				u8 opcode, bool is_jmp32)
9927 {
9928 	opcode = flip_opcode(opcode);
9929 	/* This uses zero as "not present in table"; luckily the zero opcode,
9930 	 * BPF_JA, can't get here.
9931 	 */
9932 	if (opcode)
9933 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9934 }
9935 
9936 /* 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)9937 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9938 				  struct bpf_reg_state *dst_reg)
9939 {
9940 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9941 							dst_reg->umin_value);
9942 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9943 							dst_reg->umax_value);
9944 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9945 							dst_reg->smin_value);
9946 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9947 							dst_reg->smax_value);
9948 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9949 							     dst_reg->var_off);
9950 	reg_bounds_sync(src_reg);
9951 	reg_bounds_sync(dst_reg);
9952 }
9953 
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)9954 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9955 				struct bpf_reg_state *true_dst,
9956 				struct bpf_reg_state *false_src,
9957 				struct bpf_reg_state *false_dst,
9958 				u8 opcode)
9959 {
9960 	switch (opcode) {
9961 	case BPF_JEQ:
9962 		__reg_combine_min_max(true_src, true_dst);
9963 		break;
9964 	case BPF_JNE:
9965 		__reg_combine_min_max(false_src, false_dst);
9966 		break;
9967 	}
9968 }
9969 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)9970 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9971 				 struct bpf_reg_state *reg, u32 id,
9972 				 bool is_null)
9973 {
9974 	if (type_may_be_null(reg->type) && reg->id == id &&
9975 	    !WARN_ON_ONCE(!reg->id)) {
9976 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9977 				 !tnum_equals_const(reg->var_off, 0) ||
9978 				 reg->off)) {
9979 			/* Old offset (both fixed and variable parts) should
9980 			 * have been known-zero, because we don't allow pointer
9981 			 * arithmetic on pointers that might be NULL. If we
9982 			 * see this happening, don't convert the register.
9983 			 */
9984 			return;
9985 		}
9986 		if (is_null) {
9987 			reg->type = SCALAR_VALUE;
9988 			/* We don't need id and ref_obj_id from this point
9989 			 * onwards anymore, thus we should better reset it,
9990 			 * so that state pruning has chances to take effect.
9991 			 */
9992 			reg->id = 0;
9993 			reg->ref_obj_id = 0;
9994 
9995 			return;
9996 		}
9997 
9998 		mark_ptr_not_null_reg(reg);
9999 
10000 		if (!reg_may_point_to_spin_lock(reg)) {
10001 			/* For not-NULL ptr, reg->ref_obj_id will be reset
10002 			 * in release_reference().
10003 			 *
10004 			 * reg->id is still used by spin_lock ptr. Other
10005 			 * than spin_lock ptr type, reg->id can be reset.
10006 			 */
10007 			reg->id = 0;
10008 		}
10009 	}
10010 }
10011 
10012 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10013  * be folded together at some point.
10014  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)10015 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10016 				  bool is_null)
10017 {
10018 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
10019 	struct bpf_reg_state *regs = state->regs, *reg;
10020 	u32 ref_obj_id = regs[regno].ref_obj_id;
10021 	u32 id = regs[regno].id;
10022 
10023 	if (ref_obj_id && ref_obj_id == id && is_null)
10024 		/* regs[regno] is in the " == NULL" branch.
10025 		 * No one could have freed the reference state before
10026 		 * doing the NULL check.
10027 		 */
10028 		WARN_ON_ONCE(release_reference_state(state, id));
10029 
10030 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10031 		mark_ptr_or_null_reg(state, reg, id, is_null);
10032 	}));
10033 }
10034 
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)10035 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10036 				   struct bpf_reg_state *dst_reg,
10037 				   struct bpf_reg_state *src_reg,
10038 				   struct bpf_verifier_state *this_branch,
10039 				   struct bpf_verifier_state *other_branch)
10040 {
10041 	if (BPF_SRC(insn->code) != BPF_X)
10042 		return false;
10043 
10044 	/* Pointers are always 64-bit. */
10045 	if (BPF_CLASS(insn->code) == BPF_JMP32)
10046 		return false;
10047 
10048 	switch (BPF_OP(insn->code)) {
10049 	case BPF_JGT:
10050 		if ((dst_reg->type == PTR_TO_PACKET &&
10051 		     src_reg->type == PTR_TO_PACKET_END) ||
10052 		    (dst_reg->type == PTR_TO_PACKET_META &&
10053 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10054 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10055 			find_good_pkt_pointers(this_branch, dst_reg,
10056 					       dst_reg->type, false);
10057 			mark_pkt_end(other_branch, insn->dst_reg, true);
10058 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10059 			    src_reg->type == PTR_TO_PACKET) ||
10060 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10061 			    src_reg->type == PTR_TO_PACKET_META)) {
10062 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
10063 			find_good_pkt_pointers(other_branch, src_reg,
10064 					       src_reg->type, true);
10065 			mark_pkt_end(this_branch, insn->src_reg, false);
10066 		} else {
10067 			return false;
10068 		}
10069 		break;
10070 	case BPF_JLT:
10071 		if ((dst_reg->type == PTR_TO_PACKET &&
10072 		     src_reg->type == PTR_TO_PACKET_END) ||
10073 		    (dst_reg->type == PTR_TO_PACKET_META &&
10074 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10075 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10076 			find_good_pkt_pointers(other_branch, dst_reg,
10077 					       dst_reg->type, true);
10078 			mark_pkt_end(this_branch, insn->dst_reg, false);
10079 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10080 			    src_reg->type == PTR_TO_PACKET) ||
10081 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10082 			    src_reg->type == PTR_TO_PACKET_META)) {
10083 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
10084 			find_good_pkt_pointers(this_branch, src_reg,
10085 					       src_reg->type, false);
10086 			mark_pkt_end(other_branch, insn->src_reg, true);
10087 		} else {
10088 			return false;
10089 		}
10090 		break;
10091 	case BPF_JGE:
10092 		if ((dst_reg->type == PTR_TO_PACKET &&
10093 		     src_reg->type == PTR_TO_PACKET_END) ||
10094 		    (dst_reg->type == PTR_TO_PACKET_META &&
10095 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10096 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10097 			find_good_pkt_pointers(this_branch, dst_reg,
10098 					       dst_reg->type, true);
10099 			mark_pkt_end(other_branch, insn->dst_reg, false);
10100 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10101 			    src_reg->type == PTR_TO_PACKET) ||
10102 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10103 			    src_reg->type == PTR_TO_PACKET_META)) {
10104 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10105 			find_good_pkt_pointers(other_branch, src_reg,
10106 					       src_reg->type, false);
10107 			mark_pkt_end(this_branch, insn->src_reg, true);
10108 		} else {
10109 			return false;
10110 		}
10111 		break;
10112 	case BPF_JLE:
10113 		if ((dst_reg->type == PTR_TO_PACKET &&
10114 		     src_reg->type == PTR_TO_PACKET_END) ||
10115 		    (dst_reg->type == PTR_TO_PACKET_META &&
10116 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10117 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10118 			find_good_pkt_pointers(other_branch, dst_reg,
10119 					       dst_reg->type, false);
10120 			mark_pkt_end(this_branch, insn->dst_reg, true);
10121 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
10122 			    src_reg->type == PTR_TO_PACKET) ||
10123 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10124 			    src_reg->type == PTR_TO_PACKET_META)) {
10125 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10126 			find_good_pkt_pointers(this_branch, src_reg,
10127 					       src_reg->type, true);
10128 			mark_pkt_end(other_branch, insn->src_reg, false);
10129 		} else {
10130 			return false;
10131 		}
10132 		break;
10133 	default:
10134 		return false;
10135 	}
10136 
10137 	return true;
10138 }
10139 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)10140 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10141 			       struct bpf_reg_state *known_reg)
10142 {
10143 	struct bpf_func_state *state;
10144 	struct bpf_reg_state *reg;
10145 
10146 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10147 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10148 			*reg = *known_reg;
10149 	}));
10150 }
10151 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)10152 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10153 			     struct bpf_insn *insn, int *insn_idx)
10154 {
10155 	struct bpf_verifier_state *this_branch = env->cur_state;
10156 	struct bpf_verifier_state *other_branch;
10157 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10158 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10159 	u8 opcode = BPF_OP(insn->code);
10160 	bool is_jmp32;
10161 	int pred = -1;
10162 	int err;
10163 
10164 	/* Only conditional jumps are expected to reach here. */
10165 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
10166 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10167 		return -EINVAL;
10168 	}
10169 
10170 	if (BPF_SRC(insn->code) == BPF_X) {
10171 		if (insn->imm != 0) {
10172 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10173 			return -EINVAL;
10174 		}
10175 
10176 		/* check src1 operand */
10177 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10178 		if (err)
10179 			return err;
10180 
10181 		if (is_pointer_value(env, insn->src_reg)) {
10182 			verbose(env, "R%d pointer comparison prohibited\n",
10183 				insn->src_reg);
10184 			return -EACCES;
10185 		}
10186 		src_reg = &regs[insn->src_reg];
10187 	} else {
10188 		if (insn->src_reg != BPF_REG_0) {
10189 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10190 			return -EINVAL;
10191 		}
10192 	}
10193 
10194 	/* check src2 operand */
10195 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10196 	if (err)
10197 		return err;
10198 
10199 	dst_reg = &regs[insn->dst_reg];
10200 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10201 
10202 	if (BPF_SRC(insn->code) == BPF_K) {
10203 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10204 	} else if (src_reg->type == SCALAR_VALUE &&
10205 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10206 		pred = is_branch_taken(dst_reg,
10207 				       tnum_subreg(src_reg->var_off).value,
10208 				       opcode,
10209 				       is_jmp32);
10210 	} else if (src_reg->type == SCALAR_VALUE &&
10211 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10212 		pred = is_branch_taken(dst_reg,
10213 				       src_reg->var_off.value,
10214 				       opcode,
10215 				       is_jmp32);
10216 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
10217 		   reg_is_pkt_pointer_any(src_reg) &&
10218 		   !is_jmp32) {
10219 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10220 	}
10221 
10222 	if (pred >= 0) {
10223 		/* If we get here with a dst_reg pointer type it is because
10224 		 * above is_branch_taken() special cased the 0 comparison.
10225 		 */
10226 		if (!__is_pointer_value(false, dst_reg))
10227 			err = mark_chain_precision(env, insn->dst_reg);
10228 		if (BPF_SRC(insn->code) == BPF_X && !err &&
10229 		    !__is_pointer_value(false, src_reg))
10230 			err = mark_chain_precision(env, insn->src_reg);
10231 		if (err)
10232 			return err;
10233 	}
10234 
10235 	if (pred == 1) {
10236 		/* Only follow the goto, ignore fall-through. If needed, push
10237 		 * the fall-through branch for simulation under speculative
10238 		 * execution.
10239 		 */
10240 		if (!env->bypass_spec_v1 &&
10241 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
10242 					       *insn_idx))
10243 			return -EFAULT;
10244 		*insn_idx += insn->off;
10245 		return 0;
10246 	} else if (pred == 0) {
10247 		/* Only follow the fall-through branch, since that's where the
10248 		 * program will go. If needed, push the goto branch for
10249 		 * simulation under speculative execution.
10250 		 */
10251 		if (!env->bypass_spec_v1 &&
10252 		    !sanitize_speculative_path(env, insn,
10253 					       *insn_idx + insn->off + 1,
10254 					       *insn_idx))
10255 			return -EFAULT;
10256 		return 0;
10257 	}
10258 
10259 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10260 				  false);
10261 	if (!other_branch)
10262 		return -EFAULT;
10263 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10264 
10265 	/* detect if we are comparing against a constant value so we can adjust
10266 	 * our min/max values for our dst register.
10267 	 * this is only legit if both are scalars (or pointers to the same
10268 	 * object, I suppose, but we don't support that right now), because
10269 	 * otherwise the different base pointers mean the offsets aren't
10270 	 * comparable.
10271 	 */
10272 	if (BPF_SRC(insn->code) == BPF_X) {
10273 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10274 
10275 		if (dst_reg->type == SCALAR_VALUE &&
10276 		    src_reg->type == SCALAR_VALUE) {
10277 			if (tnum_is_const(src_reg->var_off) ||
10278 			    (is_jmp32 &&
10279 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
10280 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
10281 						dst_reg,
10282 						src_reg->var_off.value,
10283 						tnum_subreg(src_reg->var_off).value,
10284 						opcode, is_jmp32);
10285 			else if (tnum_is_const(dst_reg->var_off) ||
10286 				 (is_jmp32 &&
10287 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
10288 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10289 						    src_reg,
10290 						    dst_reg->var_off.value,
10291 						    tnum_subreg(dst_reg->var_off).value,
10292 						    opcode, is_jmp32);
10293 			else if (!is_jmp32 &&
10294 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
10295 				/* Comparing for equality, we can combine knowledge */
10296 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
10297 						    &other_branch_regs[insn->dst_reg],
10298 						    src_reg, dst_reg, opcode);
10299 			if (src_reg->id &&
10300 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10301 				find_equal_scalars(this_branch, src_reg);
10302 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10303 			}
10304 
10305 		}
10306 	} else if (dst_reg->type == SCALAR_VALUE) {
10307 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
10308 					dst_reg, insn->imm, (u32)insn->imm,
10309 					opcode, is_jmp32);
10310 	}
10311 
10312 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10313 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10314 		find_equal_scalars(this_branch, dst_reg);
10315 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10316 	}
10317 
10318 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10319 	 * NOTE: these optimizations below are related with pointer comparison
10320 	 *       which will never be JMP32.
10321 	 */
10322 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10323 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10324 	    type_may_be_null(dst_reg->type)) {
10325 		/* Mark all identical registers in each branch as either
10326 		 * safe or unknown depending R == 0 or R != 0 conditional.
10327 		 */
10328 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10329 				      opcode == BPF_JNE);
10330 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10331 				      opcode == BPF_JEQ);
10332 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10333 					   this_branch, other_branch) &&
10334 		   is_pointer_value(env, insn->dst_reg)) {
10335 		verbose(env, "R%d pointer comparison prohibited\n",
10336 			insn->dst_reg);
10337 		return -EACCES;
10338 	}
10339 	if (env->log.level & BPF_LOG_LEVEL)
10340 		print_insn_state(env, this_branch->frame[this_branch->curframe]);
10341 	return 0;
10342 }
10343 
10344 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)10345 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10346 {
10347 	struct bpf_insn_aux_data *aux = cur_aux(env);
10348 	struct bpf_reg_state *regs = cur_regs(env);
10349 	struct bpf_reg_state *dst_reg;
10350 	struct bpf_map *map;
10351 	int err;
10352 
10353 	if (BPF_SIZE(insn->code) != BPF_DW) {
10354 		verbose(env, "invalid BPF_LD_IMM insn\n");
10355 		return -EINVAL;
10356 	}
10357 	if (insn->off != 0) {
10358 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10359 		return -EINVAL;
10360 	}
10361 
10362 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
10363 	if (err)
10364 		return err;
10365 
10366 	dst_reg = &regs[insn->dst_reg];
10367 	if (insn->src_reg == 0) {
10368 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10369 
10370 		dst_reg->type = SCALAR_VALUE;
10371 		__mark_reg_known(&regs[insn->dst_reg], imm);
10372 		return 0;
10373 	}
10374 
10375 	/* All special src_reg cases are listed below. From this point onwards
10376 	 * we either succeed and assign a corresponding dst_reg->type after
10377 	 * zeroing the offset, or fail and reject the program.
10378 	 */
10379 	mark_reg_known_zero(env, regs, insn->dst_reg);
10380 
10381 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10382 		dst_reg->type = aux->btf_var.reg_type;
10383 		switch (base_type(dst_reg->type)) {
10384 		case PTR_TO_MEM:
10385 			dst_reg->mem_size = aux->btf_var.mem_size;
10386 			break;
10387 		case PTR_TO_BTF_ID:
10388 			dst_reg->btf = aux->btf_var.btf;
10389 			dst_reg->btf_id = aux->btf_var.btf_id;
10390 			break;
10391 		default:
10392 			verbose(env, "bpf verifier is misconfigured\n");
10393 			return -EFAULT;
10394 		}
10395 		return 0;
10396 	}
10397 
10398 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
10399 		struct bpf_prog_aux *aux = env->prog->aux;
10400 		u32 subprogno = find_subprog(env,
10401 					     env->insn_idx + insn->imm + 1);
10402 
10403 		if (!aux->func_info) {
10404 			verbose(env, "missing btf func_info\n");
10405 			return -EINVAL;
10406 		}
10407 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10408 			verbose(env, "callback function not static\n");
10409 			return -EINVAL;
10410 		}
10411 
10412 		dst_reg->type = PTR_TO_FUNC;
10413 		dst_reg->subprogno = subprogno;
10414 		return 0;
10415 	}
10416 
10417 	map = env->used_maps[aux->map_index];
10418 	dst_reg->map_ptr = map;
10419 
10420 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10421 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10422 		dst_reg->type = PTR_TO_MAP_VALUE;
10423 		dst_reg->off = aux->map_off;
10424 		if (map_value_has_spin_lock(map))
10425 			dst_reg->id = ++env->id_gen;
10426 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10427 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10428 		dst_reg->type = CONST_PTR_TO_MAP;
10429 	} else {
10430 		verbose(env, "bpf verifier is misconfigured\n");
10431 		return -EINVAL;
10432 	}
10433 
10434 	return 0;
10435 }
10436 
may_access_skb(enum bpf_prog_type type)10437 static bool may_access_skb(enum bpf_prog_type type)
10438 {
10439 	switch (type) {
10440 	case BPF_PROG_TYPE_SOCKET_FILTER:
10441 	case BPF_PROG_TYPE_SCHED_CLS:
10442 	case BPF_PROG_TYPE_SCHED_ACT:
10443 		return true;
10444 	default:
10445 		return false;
10446 	}
10447 }
10448 
10449 /* verify safety of LD_ABS|LD_IND instructions:
10450  * - they can only appear in the programs where ctx == skb
10451  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10452  *   preserve R6-R9, and store return value into R0
10453  *
10454  * Implicit input:
10455  *   ctx == skb == R6 == CTX
10456  *
10457  * Explicit input:
10458  *   SRC == any register
10459  *   IMM == 32-bit immediate
10460  *
10461  * Output:
10462  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10463  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)10464 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10465 {
10466 	struct bpf_reg_state *regs = cur_regs(env);
10467 	static const int ctx_reg = BPF_REG_6;
10468 	u8 mode = BPF_MODE(insn->code);
10469 	int i, err;
10470 
10471 	if (!may_access_skb(resolve_prog_type(env->prog))) {
10472 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10473 		return -EINVAL;
10474 	}
10475 
10476 	if (!env->ops->gen_ld_abs) {
10477 		verbose(env, "bpf verifier is misconfigured\n");
10478 		return -EINVAL;
10479 	}
10480 
10481 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10482 	    BPF_SIZE(insn->code) == BPF_DW ||
10483 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10484 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10485 		return -EINVAL;
10486 	}
10487 
10488 	/* check whether implicit source operand (register R6) is readable */
10489 	err = check_reg_arg(env, ctx_reg, SRC_OP);
10490 	if (err)
10491 		return err;
10492 
10493 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10494 	 * gen_ld_abs() may terminate the program at runtime, leading to
10495 	 * reference leak.
10496 	 */
10497 	err = check_reference_leak(env);
10498 	if (err) {
10499 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10500 		return err;
10501 	}
10502 
10503 	if (env->cur_state->active_spin_lock) {
10504 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10505 		return -EINVAL;
10506 	}
10507 
10508 	if (regs[ctx_reg].type != PTR_TO_CTX) {
10509 		verbose(env,
10510 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10511 		return -EINVAL;
10512 	}
10513 
10514 	if (mode == BPF_IND) {
10515 		/* check explicit source operand */
10516 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
10517 		if (err)
10518 			return err;
10519 	}
10520 
10521 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10522 	if (err < 0)
10523 		return err;
10524 
10525 	/* reset caller saved regs to unreadable */
10526 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10527 		mark_reg_not_init(env, regs, caller_saved[i]);
10528 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10529 	}
10530 
10531 	/* mark destination R0 register as readable, since it contains
10532 	 * the value fetched from the packet.
10533 	 * Already marked as written above.
10534 	 */
10535 	mark_reg_unknown(env, regs, BPF_REG_0);
10536 	/* ld_abs load up to 32-bit skb data. */
10537 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10538 	return 0;
10539 }
10540 
check_return_code(struct bpf_verifier_env * env)10541 static int check_return_code(struct bpf_verifier_env *env)
10542 {
10543 	struct tnum enforce_attach_type_range = tnum_unknown;
10544 	const struct bpf_prog *prog = env->prog;
10545 	struct bpf_reg_state *reg;
10546 	struct tnum range = tnum_range(0, 1);
10547 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10548 	int err;
10549 	struct bpf_func_state *frame = env->cur_state->frame[0];
10550 	const bool is_subprog = frame->subprogno;
10551 
10552 	/* LSM and struct_ops func-ptr's return type could be "void" */
10553 	if (!is_subprog) {
10554 		switch (prog_type) {
10555 		case BPF_PROG_TYPE_LSM:
10556 			if (prog->expected_attach_type == BPF_LSM_CGROUP)
10557 				/* See below, can be 0 or 0-1 depending on hook. */
10558 				break;
10559 			fallthrough;
10560 		case BPF_PROG_TYPE_STRUCT_OPS:
10561 			if (!prog->aux->attach_func_proto->type)
10562 				return 0;
10563 			break;
10564 		default:
10565 			break;
10566 		}
10567 	}
10568 
10569 	/* eBPF calling convention is such that R0 is used
10570 	 * to return the value from eBPF program.
10571 	 * Make sure that it's readable at this time
10572 	 * of bpf_exit, which means that program wrote
10573 	 * something into it earlier
10574 	 */
10575 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10576 	if (err)
10577 		return err;
10578 
10579 	if (is_pointer_value(env, BPF_REG_0)) {
10580 		verbose(env, "R0 leaks addr as return value\n");
10581 		return -EACCES;
10582 	}
10583 
10584 	reg = cur_regs(env) + BPF_REG_0;
10585 
10586 	if (frame->in_async_callback_fn) {
10587 		/* enforce return zero from async callbacks like timer */
10588 		if (reg->type != SCALAR_VALUE) {
10589 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10590 				reg_type_str(env, reg->type));
10591 			return -EINVAL;
10592 		}
10593 
10594 		if (!tnum_in(tnum_const(0), reg->var_off)) {
10595 			verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10596 			return -EINVAL;
10597 		}
10598 		return 0;
10599 	}
10600 
10601 	if (is_subprog) {
10602 		if (reg->type != SCALAR_VALUE) {
10603 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10604 				reg_type_str(env, reg->type));
10605 			return -EINVAL;
10606 		}
10607 		return 0;
10608 	}
10609 
10610 	switch (prog_type) {
10611 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10612 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10613 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10614 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10615 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10616 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10617 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10618 			range = tnum_range(1, 1);
10619 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10620 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10621 			range = tnum_range(0, 3);
10622 		break;
10623 	case BPF_PROG_TYPE_CGROUP_SKB:
10624 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10625 			range = tnum_range(0, 3);
10626 			enforce_attach_type_range = tnum_range(2, 3);
10627 		}
10628 		break;
10629 	case BPF_PROG_TYPE_CGROUP_SOCK:
10630 	case BPF_PROG_TYPE_SOCK_OPS:
10631 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10632 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10633 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10634 		break;
10635 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10636 		if (!env->prog->aux->attach_btf_id)
10637 			return 0;
10638 		range = tnum_const(0);
10639 		break;
10640 	case BPF_PROG_TYPE_TRACING:
10641 		switch (env->prog->expected_attach_type) {
10642 		case BPF_TRACE_FENTRY:
10643 		case BPF_TRACE_FEXIT:
10644 			range = tnum_const(0);
10645 			break;
10646 		case BPF_TRACE_RAW_TP:
10647 		case BPF_MODIFY_RETURN:
10648 			return 0;
10649 		case BPF_TRACE_ITER:
10650 			break;
10651 		default:
10652 			return -ENOTSUPP;
10653 		}
10654 		break;
10655 	case BPF_PROG_TYPE_SK_LOOKUP:
10656 		range = tnum_range(SK_DROP, SK_PASS);
10657 		break;
10658 
10659 	case BPF_PROG_TYPE_LSM:
10660 		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10661 			/* Regular BPF_PROG_TYPE_LSM programs can return
10662 			 * any value.
10663 			 */
10664 			return 0;
10665 		}
10666 		if (!env->prog->aux->attach_func_proto->type) {
10667 			/* Make sure programs that attach to void
10668 			 * hooks don't try to modify return value.
10669 			 */
10670 			range = tnum_range(1, 1);
10671 		}
10672 		break;
10673 
10674 	case BPF_PROG_TYPE_EXT:
10675 		/* freplace program can return anything as its return value
10676 		 * depends on the to-be-replaced kernel func or bpf program.
10677 		 */
10678 	default:
10679 		return 0;
10680 	}
10681 
10682 	if (reg->type != SCALAR_VALUE) {
10683 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10684 			reg_type_str(env, reg->type));
10685 		return -EINVAL;
10686 	}
10687 
10688 	if (!tnum_in(range, reg->var_off)) {
10689 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10690 		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10691 		    prog_type == BPF_PROG_TYPE_LSM &&
10692 		    !prog->aux->attach_func_proto->type)
10693 			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10694 		return -EINVAL;
10695 	}
10696 
10697 	if (!tnum_is_unknown(enforce_attach_type_range) &&
10698 	    tnum_in(enforce_attach_type_range, reg->var_off))
10699 		env->prog->enforce_expected_attach_type = 1;
10700 	return 0;
10701 }
10702 
10703 /* non-recursive DFS pseudo code
10704  * 1  procedure DFS-iterative(G,v):
10705  * 2      label v as discovered
10706  * 3      let S be a stack
10707  * 4      S.push(v)
10708  * 5      while S is not empty
10709  * 6            t <- S.pop()
10710  * 7            if t is what we're looking for:
10711  * 8                return t
10712  * 9            for all edges e in G.adjacentEdges(t) do
10713  * 10               if edge e is already labelled
10714  * 11                   continue with the next edge
10715  * 12               w <- G.adjacentVertex(t,e)
10716  * 13               if vertex w is not discovered and not explored
10717  * 14                   label e as tree-edge
10718  * 15                   label w as discovered
10719  * 16                   S.push(w)
10720  * 17                   continue at 5
10721  * 18               else if vertex w is discovered
10722  * 19                   label e as back-edge
10723  * 20               else
10724  * 21                   // vertex w is explored
10725  * 22                   label e as forward- or cross-edge
10726  * 23           label t as explored
10727  * 24           S.pop()
10728  *
10729  * convention:
10730  * 0x10 - discovered
10731  * 0x11 - discovered and fall-through edge labelled
10732  * 0x12 - discovered and fall-through and branch edges labelled
10733  * 0x20 - explored
10734  */
10735 
10736 enum {
10737 	DISCOVERED = 0x10,
10738 	EXPLORED = 0x20,
10739 	FALLTHROUGH = 1,
10740 	BRANCH = 2,
10741 };
10742 
state_htab_size(struct bpf_verifier_env * env)10743 static u32 state_htab_size(struct bpf_verifier_env *env)
10744 {
10745 	return env->prog->len;
10746 }
10747 
explored_state(struct bpf_verifier_env * env,int idx)10748 static struct bpf_verifier_state_list **explored_state(
10749 					struct bpf_verifier_env *env,
10750 					int idx)
10751 {
10752 	struct bpf_verifier_state *cur = env->cur_state;
10753 	struct bpf_func_state *state = cur->frame[cur->curframe];
10754 
10755 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10756 }
10757 
init_explored_state(struct bpf_verifier_env * env,int idx)10758 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10759 {
10760 	env->insn_aux_data[idx].prune_point = true;
10761 }
10762 
10763 enum {
10764 	DONE_EXPLORING = 0,
10765 	KEEP_EXPLORING = 1,
10766 };
10767 
10768 /* t, w, e - match pseudo-code above:
10769  * t - index of current instruction
10770  * w - next instruction
10771  * e - edge
10772  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)10773 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10774 		     bool loop_ok)
10775 {
10776 	int *insn_stack = env->cfg.insn_stack;
10777 	int *insn_state = env->cfg.insn_state;
10778 
10779 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10780 		return DONE_EXPLORING;
10781 
10782 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10783 		return DONE_EXPLORING;
10784 
10785 	if (w < 0 || w >= env->prog->len) {
10786 		verbose_linfo(env, t, "%d: ", t);
10787 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
10788 		return -EINVAL;
10789 	}
10790 
10791 	if (e == BRANCH)
10792 		/* mark branch target for state pruning */
10793 		init_explored_state(env, w);
10794 
10795 	if (insn_state[w] == 0) {
10796 		/* tree-edge */
10797 		insn_state[t] = DISCOVERED | e;
10798 		insn_state[w] = DISCOVERED;
10799 		if (env->cfg.cur_stack >= env->prog->len)
10800 			return -E2BIG;
10801 		insn_stack[env->cfg.cur_stack++] = w;
10802 		return KEEP_EXPLORING;
10803 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10804 		if (loop_ok && env->bpf_capable)
10805 			return DONE_EXPLORING;
10806 		verbose_linfo(env, t, "%d: ", t);
10807 		verbose_linfo(env, w, "%d: ", w);
10808 		verbose(env, "back-edge from insn %d to %d\n", t, w);
10809 		return -EINVAL;
10810 	} else if (insn_state[w] == EXPLORED) {
10811 		/* forward- or cross-edge */
10812 		insn_state[t] = DISCOVERED | e;
10813 	} else {
10814 		verbose(env, "insn state internal bug\n");
10815 		return -EFAULT;
10816 	}
10817 	return DONE_EXPLORING;
10818 }
10819 
visit_func_call_insn(int t,int insn_cnt,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)10820 static int visit_func_call_insn(int t, int insn_cnt,
10821 				struct bpf_insn *insns,
10822 				struct bpf_verifier_env *env,
10823 				bool visit_callee)
10824 {
10825 	int ret;
10826 
10827 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10828 	if (ret)
10829 		return ret;
10830 
10831 	if (t + 1 < insn_cnt)
10832 		init_explored_state(env, t + 1);
10833 	if (visit_callee) {
10834 		init_explored_state(env, t);
10835 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10836 				/* It's ok to allow recursion from CFG point of
10837 				 * view. __check_func_call() will do the actual
10838 				 * check.
10839 				 */
10840 				bpf_pseudo_func(insns + t));
10841 	}
10842 	return ret;
10843 }
10844 
10845 /* Visits the instruction at index t and returns one of the following:
10846  *  < 0 - an error occurred
10847  *  DONE_EXPLORING - the instruction was fully explored
10848  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10849  */
visit_insn(int t,int insn_cnt,struct bpf_verifier_env * env)10850 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10851 {
10852 	struct bpf_insn *insns = env->prog->insnsi;
10853 	int ret;
10854 
10855 	if (bpf_pseudo_func(insns + t))
10856 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
10857 
10858 	/* All non-branch instructions have a single fall-through edge. */
10859 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10860 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
10861 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
10862 
10863 	switch (BPF_OP(insns[t].code)) {
10864 	case BPF_EXIT:
10865 		return DONE_EXPLORING;
10866 
10867 	case BPF_CALL:
10868 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
10869 			/* Mark this call insn to trigger is_state_visited() check
10870 			 * before call itself is processed by __check_func_call().
10871 			 * Otherwise new async state will be pushed for further
10872 			 * exploration.
10873 			 */
10874 			init_explored_state(env, t);
10875 		return visit_func_call_insn(t, insn_cnt, insns, env,
10876 					    insns[t].src_reg == BPF_PSEUDO_CALL);
10877 
10878 	case BPF_JA:
10879 		if (BPF_SRC(insns[t].code) != BPF_K)
10880 			return -EINVAL;
10881 
10882 		/* unconditional jump with single edge */
10883 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10884 				true);
10885 		if (ret)
10886 			return ret;
10887 
10888 		/* unconditional jmp is not a good pruning point,
10889 		 * but it's marked, since backtracking needs
10890 		 * to record jmp history in is_state_visited().
10891 		 */
10892 		init_explored_state(env, t + insns[t].off + 1);
10893 		/* tell verifier to check for equivalent states
10894 		 * after every call and jump
10895 		 */
10896 		if (t + 1 < insn_cnt)
10897 			init_explored_state(env, t + 1);
10898 
10899 		return ret;
10900 
10901 	default:
10902 		/* conditional jump with two edges */
10903 		init_explored_state(env, t);
10904 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10905 		if (ret)
10906 			return ret;
10907 
10908 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10909 	}
10910 }
10911 
10912 /* non-recursive depth-first-search to detect loops in BPF program
10913  * loop == back-edge in directed graph
10914  */
check_cfg(struct bpf_verifier_env * env)10915 static int check_cfg(struct bpf_verifier_env *env)
10916 {
10917 	int insn_cnt = env->prog->len;
10918 	int *insn_stack, *insn_state;
10919 	int ret = 0;
10920 	int i;
10921 
10922 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10923 	if (!insn_state)
10924 		return -ENOMEM;
10925 
10926 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10927 	if (!insn_stack) {
10928 		kvfree(insn_state);
10929 		return -ENOMEM;
10930 	}
10931 
10932 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10933 	insn_stack[0] = 0; /* 0 is the first instruction */
10934 	env->cfg.cur_stack = 1;
10935 
10936 	while (env->cfg.cur_stack > 0) {
10937 		int t = insn_stack[env->cfg.cur_stack - 1];
10938 
10939 		ret = visit_insn(t, insn_cnt, env);
10940 		switch (ret) {
10941 		case DONE_EXPLORING:
10942 			insn_state[t] = EXPLORED;
10943 			env->cfg.cur_stack--;
10944 			break;
10945 		case KEEP_EXPLORING:
10946 			break;
10947 		default:
10948 			if (ret > 0) {
10949 				verbose(env, "visit_insn internal bug\n");
10950 				ret = -EFAULT;
10951 			}
10952 			goto err_free;
10953 		}
10954 	}
10955 
10956 	if (env->cfg.cur_stack < 0) {
10957 		verbose(env, "pop stack internal bug\n");
10958 		ret = -EFAULT;
10959 		goto err_free;
10960 	}
10961 
10962 	for (i = 0; i < insn_cnt; i++) {
10963 		if (insn_state[i] != EXPLORED) {
10964 			verbose(env, "unreachable insn %d\n", i);
10965 			ret = -EINVAL;
10966 			goto err_free;
10967 		}
10968 	}
10969 	ret = 0; /* cfg looks good */
10970 
10971 err_free:
10972 	kvfree(insn_state);
10973 	kvfree(insn_stack);
10974 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
10975 	return ret;
10976 }
10977 
check_abnormal_return(struct bpf_verifier_env * env)10978 static int check_abnormal_return(struct bpf_verifier_env *env)
10979 {
10980 	int i;
10981 
10982 	for (i = 1; i < env->subprog_cnt; i++) {
10983 		if (env->subprog_info[i].has_ld_abs) {
10984 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10985 			return -EINVAL;
10986 		}
10987 		if (env->subprog_info[i].has_tail_call) {
10988 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10989 			return -EINVAL;
10990 		}
10991 	}
10992 	return 0;
10993 }
10994 
10995 /* The minimum supported BTF func info size */
10996 #define MIN_BPF_FUNCINFO_SIZE	8
10997 #define MAX_FUNCINFO_REC_SIZE	252
10998 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)10999 static int check_btf_func(struct bpf_verifier_env *env,
11000 			  const union bpf_attr *attr,
11001 			  bpfptr_t uattr)
11002 {
11003 	const struct btf_type *type, *func_proto, *ret_type;
11004 	u32 i, nfuncs, urec_size, min_size;
11005 	u32 krec_size = sizeof(struct bpf_func_info);
11006 	struct bpf_func_info *krecord;
11007 	struct bpf_func_info_aux *info_aux = NULL;
11008 	struct bpf_prog *prog;
11009 	const struct btf *btf;
11010 	bpfptr_t urecord;
11011 	u32 prev_offset = 0;
11012 	bool scalar_return;
11013 	int ret = -ENOMEM;
11014 
11015 	nfuncs = attr->func_info_cnt;
11016 	if (!nfuncs) {
11017 		if (check_abnormal_return(env))
11018 			return -EINVAL;
11019 		return 0;
11020 	}
11021 
11022 	if (nfuncs != env->subprog_cnt) {
11023 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11024 		return -EINVAL;
11025 	}
11026 
11027 	urec_size = attr->func_info_rec_size;
11028 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11029 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
11030 	    urec_size % sizeof(u32)) {
11031 		verbose(env, "invalid func info rec size %u\n", urec_size);
11032 		return -EINVAL;
11033 	}
11034 
11035 	prog = env->prog;
11036 	btf = prog->aux->btf;
11037 
11038 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11039 	min_size = min_t(u32, krec_size, urec_size);
11040 
11041 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11042 	if (!krecord)
11043 		return -ENOMEM;
11044 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11045 	if (!info_aux)
11046 		goto err_free;
11047 
11048 	for (i = 0; i < nfuncs; i++) {
11049 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11050 		if (ret) {
11051 			if (ret == -E2BIG) {
11052 				verbose(env, "nonzero tailing record in func info");
11053 				/* set the size kernel expects so loader can zero
11054 				 * out the rest of the record.
11055 				 */
11056 				if (copy_to_bpfptr_offset(uattr,
11057 							  offsetof(union bpf_attr, func_info_rec_size),
11058 							  &min_size, sizeof(min_size)))
11059 					ret = -EFAULT;
11060 			}
11061 			goto err_free;
11062 		}
11063 
11064 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11065 			ret = -EFAULT;
11066 			goto err_free;
11067 		}
11068 
11069 		/* check insn_off */
11070 		ret = -EINVAL;
11071 		if (i == 0) {
11072 			if (krecord[i].insn_off) {
11073 				verbose(env,
11074 					"nonzero insn_off %u for the first func info record",
11075 					krecord[i].insn_off);
11076 				goto err_free;
11077 			}
11078 		} else if (krecord[i].insn_off <= prev_offset) {
11079 			verbose(env,
11080 				"same or smaller insn offset (%u) than previous func info record (%u)",
11081 				krecord[i].insn_off, prev_offset);
11082 			goto err_free;
11083 		}
11084 
11085 		if (env->subprog_info[i].start != krecord[i].insn_off) {
11086 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11087 			goto err_free;
11088 		}
11089 
11090 		/* check type_id */
11091 		type = btf_type_by_id(btf, krecord[i].type_id);
11092 		if (!type || !btf_type_is_func(type)) {
11093 			verbose(env, "invalid type id %d in func info",
11094 				krecord[i].type_id);
11095 			goto err_free;
11096 		}
11097 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11098 
11099 		func_proto = btf_type_by_id(btf, type->type);
11100 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11101 			/* btf_func_check() already verified it during BTF load */
11102 			goto err_free;
11103 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11104 		scalar_return =
11105 			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11106 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11107 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11108 			goto err_free;
11109 		}
11110 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11111 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11112 			goto err_free;
11113 		}
11114 
11115 		prev_offset = krecord[i].insn_off;
11116 		bpfptr_add(&urecord, urec_size);
11117 	}
11118 
11119 	prog->aux->func_info = krecord;
11120 	prog->aux->func_info_cnt = nfuncs;
11121 	prog->aux->func_info_aux = info_aux;
11122 	return 0;
11123 
11124 err_free:
11125 	kvfree(krecord);
11126 	kfree(info_aux);
11127 	return ret;
11128 }
11129 
adjust_btf_func(struct bpf_verifier_env * env)11130 static void adjust_btf_func(struct bpf_verifier_env *env)
11131 {
11132 	struct bpf_prog_aux *aux = env->prog->aux;
11133 	int i;
11134 
11135 	if (!aux->func_info)
11136 		return;
11137 
11138 	for (i = 0; i < env->subprog_cnt; i++)
11139 		aux->func_info[i].insn_off = env->subprog_info[i].start;
11140 }
11141 
11142 #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
11143 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
11144 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11145 static int check_btf_line(struct bpf_verifier_env *env,
11146 			  const union bpf_attr *attr,
11147 			  bpfptr_t uattr)
11148 {
11149 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11150 	struct bpf_subprog_info *sub;
11151 	struct bpf_line_info *linfo;
11152 	struct bpf_prog *prog;
11153 	const struct btf *btf;
11154 	bpfptr_t ulinfo;
11155 	int err;
11156 
11157 	nr_linfo = attr->line_info_cnt;
11158 	if (!nr_linfo)
11159 		return 0;
11160 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11161 		return -EINVAL;
11162 
11163 	rec_size = attr->line_info_rec_size;
11164 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11165 	    rec_size > MAX_LINEINFO_REC_SIZE ||
11166 	    rec_size & (sizeof(u32) - 1))
11167 		return -EINVAL;
11168 
11169 	/* Need to zero it in case the userspace may
11170 	 * pass in a smaller bpf_line_info object.
11171 	 */
11172 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11173 			 GFP_KERNEL | __GFP_NOWARN);
11174 	if (!linfo)
11175 		return -ENOMEM;
11176 
11177 	prog = env->prog;
11178 	btf = prog->aux->btf;
11179 
11180 	s = 0;
11181 	sub = env->subprog_info;
11182 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11183 	expected_size = sizeof(struct bpf_line_info);
11184 	ncopy = min_t(u32, expected_size, rec_size);
11185 	for (i = 0; i < nr_linfo; i++) {
11186 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11187 		if (err) {
11188 			if (err == -E2BIG) {
11189 				verbose(env, "nonzero tailing record in line_info");
11190 				if (copy_to_bpfptr_offset(uattr,
11191 							  offsetof(union bpf_attr, line_info_rec_size),
11192 							  &expected_size, sizeof(expected_size)))
11193 					err = -EFAULT;
11194 			}
11195 			goto err_free;
11196 		}
11197 
11198 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11199 			err = -EFAULT;
11200 			goto err_free;
11201 		}
11202 
11203 		/*
11204 		 * Check insn_off to ensure
11205 		 * 1) strictly increasing AND
11206 		 * 2) bounded by prog->len
11207 		 *
11208 		 * The linfo[0].insn_off == 0 check logically falls into
11209 		 * the later "missing bpf_line_info for func..." case
11210 		 * because the first linfo[0].insn_off must be the
11211 		 * first sub also and the first sub must have
11212 		 * subprog_info[0].start == 0.
11213 		 */
11214 		if ((i && linfo[i].insn_off <= prev_offset) ||
11215 		    linfo[i].insn_off >= prog->len) {
11216 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11217 				i, linfo[i].insn_off, prev_offset,
11218 				prog->len);
11219 			err = -EINVAL;
11220 			goto err_free;
11221 		}
11222 
11223 		if (!prog->insnsi[linfo[i].insn_off].code) {
11224 			verbose(env,
11225 				"Invalid insn code at line_info[%u].insn_off\n",
11226 				i);
11227 			err = -EINVAL;
11228 			goto err_free;
11229 		}
11230 
11231 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11232 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11233 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11234 			err = -EINVAL;
11235 			goto err_free;
11236 		}
11237 
11238 		if (s != env->subprog_cnt) {
11239 			if (linfo[i].insn_off == sub[s].start) {
11240 				sub[s].linfo_idx = i;
11241 				s++;
11242 			} else if (sub[s].start < linfo[i].insn_off) {
11243 				verbose(env, "missing bpf_line_info for func#%u\n", s);
11244 				err = -EINVAL;
11245 				goto err_free;
11246 			}
11247 		}
11248 
11249 		prev_offset = linfo[i].insn_off;
11250 		bpfptr_add(&ulinfo, rec_size);
11251 	}
11252 
11253 	if (s != env->subprog_cnt) {
11254 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11255 			env->subprog_cnt - s, s);
11256 		err = -EINVAL;
11257 		goto err_free;
11258 	}
11259 
11260 	prog->aux->linfo = linfo;
11261 	prog->aux->nr_linfo = nr_linfo;
11262 
11263 	return 0;
11264 
11265 err_free:
11266 	kvfree(linfo);
11267 	return err;
11268 }
11269 
11270 #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
11271 #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
11272 
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11273 static int check_core_relo(struct bpf_verifier_env *env,
11274 			   const union bpf_attr *attr,
11275 			   bpfptr_t uattr)
11276 {
11277 	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11278 	struct bpf_core_relo core_relo = {};
11279 	struct bpf_prog *prog = env->prog;
11280 	const struct btf *btf = prog->aux->btf;
11281 	struct bpf_core_ctx ctx = {
11282 		.log = &env->log,
11283 		.btf = btf,
11284 	};
11285 	bpfptr_t u_core_relo;
11286 	int err;
11287 
11288 	nr_core_relo = attr->core_relo_cnt;
11289 	if (!nr_core_relo)
11290 		return 0;
11291 	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11292 		return -EINVAL;
11293 
11294 	rec_size = attr->core_relo_rec_size;
11295 	if (rec_size < MIN_CORE_RELO_SIZE ||
11296 	    rec_size > MAX_CORE_RELO_SIZE ||
11297 	    rec_size % sizeof(u32))
11298 		return -EINVAL;
11299 
11300 	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11301 	expected_size = sizeof(struct bpf_core_relo);
11302 	ncopy = min_t(u32, expected_size, rec_size);
11303 
11304 	/* Unlike func_info and line_info, copy and apply each CO-RE
11305 	 * relocation record one at a time.
11306 	 */
11307 	for (i = 0; i < nr_core_relo; i++) {
11308 		/* future proofing when sizeof(bpf_core_relo) changes */
11309 		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11310 		if (err) {
11311 			if (err == -E2BIG) {
11312 				verbose(env, "nonzero tailing record in core_relo");
11313 				if (copy_to_bpfptr_offset(uattr,
11314 							  offsetof(union bpf_attr, core_relo_rec_size),
11315 							  &expected_size, sizeof(expected_size)))
11316 					err = -EFAULT;
11317 			}
11318 			break;
11319 		}
11320 
11321 		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11322 			err = -EFAULT;
11323 			break;
11324 		}
11325 
11326 		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11327 			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11328 				i, core_relo.insn_off, prog->len);
11329 			err = -EINVAL;
11330 			break;
11331 		}
11332 
11333 		err = bpf_core_apply(&ctx, &core_relo, i,
11334 				     &prog->insnsi[core_relo.insn_off / 8]);
11335 		if (err)
11336 			break;
11337 		bpfptr_add(&u_core_relo, rec_size);
11338 	}
11339 	return err;
11340 }
11341 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11342 static int check_btf_info(struct bpf_verifier_env *env,
11343 			  const union bpf_attr *attr,
11344 			  bpfptr_t uattr)
11345 {
11346 	struct btf *btf;
11347 	int err;
11348 
11349 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
11350 		if (check_abnormal_return(env))
11351 			return -EINVAL;
11352 		return 0;
11353 	}
11354 
11355 	btf = btf_get_by_fd(attr->prog_btf_fd);
11356 	if (IS_ERR(btf))
11357 		return PTR_ERR(btf);
11358 	if (btf_is_kernel(btf)) {
11359 		btf_put(btf);
11360 		return -EACCES;
11361 	}
11362 	env->prog->aux->btf = btf;
11363 
11364 	err = check_btf_func(env, attr, uattr);
11365 	if (err)
11366 		return err;
11367 
11368 	err = check_btf_line(env, attr, uattr);
11369 	if (err)
11370 		return err;
11371 
11372 	err = check_core_relo(env, attr, uattr);
11373 	if (err)
11374 		return err;
11375 
11376 	return 0;
11377 }
11378 
11379 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)11380 static bool range_within(struct bpf_reg_state *old,
11381 			 struct bpf_reg_state *cur)
11382 {
11383 	return old->umin_value <= cur->umin_value &&
11384 	       old->umax_value >= cur->umax_value &&
11385 	       old->smin_value <= cur->smin_value &&
11386 	       old->smax_value >= cur->smax_value &&
11387 	       old->u32_min_value <= cur->u32_min_value &&
11388 	       old->u32_max_value >= cur->u32_max_value &&
11389 	       old->s32_min_value <= cur->s32_min_value &&
11390 	       old->s32_max_value >= cur->s32_max_value;
11391 }
11392 
11393 /* If in the old state two registers had the same id, then they need to have
11394  * the same id in the new state as well.  But that id could be different from
11395  * the old state, so we need to track the mapping from old to new ids.
11396  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11397  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11398  * regs with a different old id could still have new id 9, we don't care about
11399  * that.
11400  * So we look through our idmap to see if this old id has been seen before.  If
11401  * so, we require the new id to match; otherwise, we add the id pair to the map.
11402  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)11403 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11404 {
11405 	unsigned int i;
11406 
11407 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11408 		if (!idmap[i].old) {
11409 			/* Reached an empty slot; haven't seen this id before */
11410 			idmap[i].old = old_id;
11411 			idmap[i].cur = cur_id;
11412 			return true;
11413 		}
11414 		if (idmap[i].old == old_id)
11415 			return idmap[i].cur == cur_id;
11416 	}
11417 	/* We ran out of idmap slots, which should be impossible */
11418 	WARN_ON_ONCE(1);
11419 	return false;
11420 }
11421 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)11422 static void clean_func_state(struct bpf_verifier_env *env,
11423 			     struct bpf_func_state *st)
11424 {
11425 	enum bpf_reg_liveness live;
11426 	int i, j;
11427 
11428 	for (i = 0; i < BPF_REG_FP; i++) {
11429 		live = st->regs[i].live;
11430 		/* liveness must not touch this register anymore */
11431 		st->regs[i].live |= REG_LIVE_DONE;
11432 		if (!(live & REG_LIVE_READ))
11433 			/* since the register is unused, clear its state
11434 			 * to make further comparison simpler
11435 			 */
11436 			__mark_reg_not_init(env, &st->regs[i]);
11437 	}
11438 
11439 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11440 		live = st->stack[i].spilled_ptr.live;
11441 		/* liveness must not touch this stack slot anymore */
11442 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11443 		if (!(live & REG_LIVE_READ)) {
11444 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11445 			for (j = 0; j < BPF_REG_SIZE; j++)
11446 				st->stack[i].slot_type[j] = STACK_INVALID;
11447 		}
11448 	}
11449 }
11450 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)11451 static void clean_verifier_state(struct bpf_verifier_env *env,
11452 				 struct bpf_verifier_state *st)
11453 {
11454 	int i;
11455 
11456 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11457 		/* all regs in this state in all frames were already marked */
11458 		return;
11459 
11460 	for (i = 0; i <= st->curframe; i++)
11461 		clean_func_state(env, st->frame[i]);
11462 }
11463 
11464 /* the parentage chains form a tree.
11465  * the verifier states are added to state lists at given insn and
11466  * pushed into state stack for future exploration.
11467  * when the verifier reaches bpf_exit insn some of the verifer states
11468  * stored in the state lists have their final liveness state already,
11469  * but a lot of states will get revised from liveness point of view when
11470  * the verifier explores other branches.
11471  * Example:
11472  * 1: r0 = 1
11473  * 2: if r1 == 100 goto pc+1
11474  * 3: r0 = 2
11475  * 4: exit
11476  * when the verifier reaches exit insn the register r0 in the state list of
11477  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11478  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11479  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11480  *
11481  * Since the verifier pushes the branch states as it sees them while exploring
11482  * the program the condition of walking the branch instruction for the second
11483  * time means that all states below this branch were already explored and
11484  * their final liveness marks are already propagated.
11485  * Hence when the verifier completes the search of state list in is_state_visited()
11486  * we can call this clean_live_states() function to mark all liveness states
11487  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11488  * will not be used.
11489  * This function also clears the registers and stack for states that !READ
11490  * to simplify state merging.
11491  *
11492  * Important note here that walking the same branch instruction in the callee
11493  * doesn't meant that the states are DONE. The verifier has to compare
11494  * the callsites
11495  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)11496 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11497 			      struct bpf_verifier_state *cur)
11498 {
11499 	struct bpf_verifier_state_list *sl;
11500 	int i;
11501 
11502 	sl = *explored_state(env, insn);
11503 	while (sl) {
11504 		if (sl->state.branches)
11505 			goto next;
11506 		if (sl->state.insn_idx != insn ||
11507 		    sl->state.curframe != cur->curframe)
11508 			goto next;
11509 		for (i = 0; i <= cur->curframe; i++)
11510 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11511 				goto next;
11512 		clean_verifier_state(env, &sl->state);
11513 next:
11514 		sl = sl->next;
11515 	}
11516 }
11517 
11518 /* 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_id_pair * idmap)11519 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11520 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11521 {
11522 	bool equal;
11523 
11524 	if (!(rold->live & REG_LIVE_READ))
11525 		/* explored state didn't use this */
11526 		return true;
11527 
11528 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11529 
11530 	if (rold->type == PTR_TO_STACK)
11531 		/* two stack pointers are equal only if they're pointing to
11532 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
11533 		 */
11534 		return equal && rold->frameno == rcur->frameno;
11535 
11536 	if (equal)
11537 		return true;
11538 
11539 	if (rold->type == NOT_INIT)
11540 		/* explored state can't have used this */
11541 		return true;
11542 	if (rcur->type == NOT_INIT)
11543 		return false;
11544 	switch (base_type(rold->type)) {
11545 	case SCALAR_VALUE:
11546 		if (env->explore_alu_limits)
11547 			return false;
11548 		if (rcur->type == SCALAR_VALUE) {
11549 			if (!rold->precise && !rcur->precise)
11550 				return true;
11551 			/* new val must satisfy old val knowledge */
11552 			return range_within(rold, rcur) &&
11553 			       tnum_in(rold->var_off, rcur->var_off);
11554 		} else {
11555 			/* We're trying to use a pointer in place of a scalar.
11556 			 * Even if the scalar was unbounded, this could lead to
11557 			 * pointer leaks because scalars are allowed to leak
11558 			 * while pointers are not. We could make this safe in
11559 			 * special cases if root is calling us, but it's
11560 			 * probably not worth the hassle.
11561 			 */
11562 			return false;
11563 		}
11564 	case PTR_TO_MAP_KEY:
11565 	case PTR_TO_MAP_VALUE:
11566 		/* a PTR_TO_MAP_VALUE could be safe to use as a
11567 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11568 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11569 		 * checked, doing so could have affected others with the same
11570 		 * id, and we can't check for that because we lost the id when
11571 		 * we converted to a PTR_TO_MAP_VALUE.
11572 		 */
11573 		if (type_may_be_null(rold->type)) {
11574 			if (!type_may_be_null(rcur->type))
11575 				return false;
11576 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11577 				return false;
11578 			/* Check our ids match any regs they're supposed to */
11579 			return check_ids(rold->id, rcur->id, idmap);
11580 		}
11581 
11582 		/* If the new min/max/var_off satisfy the old ones and
11583 		 * everything else matches, we are OK.
11584 		 * 'id' is not compared, since it's only used for maps with
11585 		 * bpf_spin_lock inside map element and in such cases if
11586 		 * the rest of the prog is valid for one map element then
11587 		 * it's valid for all map elements regardless of the key
11588 		 * used in bpf_map_lookup()
11589 		 */
11590 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11591 		       range_within(rold, rcur) &&
11592 		       tnum_in(rold->var_off, rcur->var_off);
11593 	case PTR_TO_PACKET_META:
11594 	case PTR_TO_PACKET:
11595 		if (rcur->type != rold->type)
11596 			return false;
11597 		/* We must have at least as much range as the old ptr
11598 		 * did, so that any accesses which were safe before are
11599 		 * still safe.  This is true even if old range < old off,
11600 		 * since someone could have accessed through (ptr - k), or
11601 		 * even done ptr -= k in a register, to get a safe access.
11602 		 */
11603 		if (rold->range > rcur->range)
11604 			return false;
11605 		/* If the offsets don't match, we can't trust our alignment;
11606 		 * nor can we be sure that we won't fall out of range.
11607 		 */
11608 		if (rold->off != rcur->off)
11609 			return false;
11610 		/* id relations must be preserved */
11611 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11612 			return false;
11613 		/* new val must satisfy old val knowledge */
11614 		return range_within(rold, rcur) &&
11615 		       tnum_in(rold->var_off, rcur->var_off);
11616 	case PTR_TO_CTX:
11617 	case CONST_PTR_TO_MAP:
11618 	case PTR_TO_PACKET_END:
11619 	case PTR_TO_FLOW_KEYS:
11620 	case PTR_TO_SOCKET:
11621 	case PTR_TO_SOCK_COMMON:
11622 	case PTR_TO_TCP_SOCK:
11623 	case PTR_TO_XDP_SOCK:
11624 		/* Only valid matches are exact, which memcmp() above
11625 		 * would have accepted
11626 		 */
11627 	default:
11628 		/* Don't know what's going on, just say it's not safe */
11629 		return false;
11630 	}
11631 
11632 	/* Shouldn't get here; if we do, say it's not safe */
11633 	WARN_ON_ONCE(1);
11634 	return false;
11635 }
11636 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)11637 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11638 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11639 {
11640 	int i, spi;
11641 
11642 	/* walk slots of the explored stack and ignore any additional
11643 	 * slots in the current stack, since explored(safe) state
11644 	 * didn't use them
11645 	 */
11646 	for (i = 0; i < old->allocated_stack; i++) {
11647 		spi = i / BPF_REG_SIZE;
11648 
11649 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11650 			i += BPF_REG_SIZE - 1;
11651 			/* explored state didn't use this */
11652 			continue;
11653 		}
11654 
11655 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11656 			continue;
11657 
11658 		/* explored stack has more populated slots than current stack
11659 		 * and these slots were used
11660 		 */
11661 		if (i >= cur->allocated_stack)
11662 			return false;
11663 
11664 		/* if old state was safe with misc data in the stack
11665 		 * it will be safe with zero-initialized stack.
11666 		 * The opposite is not true
11667 		 */
11668 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11669 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11670 			continue;
11671 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11672 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11673 			/* Ex: old explored (safe) state has STACK_SPILL in
11674 			 * this stack slot, but current has STACK_MISC ->
11675 			 * this verifier states are not equivalent,
11676 			 * return false to continue verification of this path
11677 			 */
11678 			return false;
11679 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11680 			continue;
11681 		if (!is_spilled_reg(&old->stack[spi]))
11682 			continue;
11683 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
11684 			     &cur->stack[spi].spilled_ptr, idmap))
11685 			/* when explored and current stack slot are both storing
11686 			 * spilled registers, check that stored pointers types
11687 			 * are the same as well.
11688 			 * Ex: explored safe path could have stored
11689 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11690 			 * but current path has stored:
11691 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11692 			 * such verifier states are not equivalent.
11693 			 * return false to continue verification of this path
11694 			 */
11695 			return false;
11696 	}
11697 	return true;
11698 }
11699 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)11700 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11701 {
11702 	if (old->acquired_refs != cur->acquired_refs)
11703 		return false;
11704 	return !memcmp(old->refs, cur->refs,
11705 		       sizeof(*old->refs) * old->acquired_refs);
11706 }
11707 
11708 /* compare two verifier states
11709  *
11710  * all states stored in state_list are known to be valid, since
11711  * verifier reached 'bpf_exit' instruction through them
11712  *
11713  * this function is called when verifier exploring different branches of
11714  * execution popped from the state stack. If it sees an old state that has
11715  * more strict register state and more strict stack state then this execution
11716  * branch doesn't need to be explored further, since verifier already
11717  * concluded that more strict state leads to valid finish.
11718  *
11719  * Therefore two states are equivalent if register state is more conservative
11720  * and explored stack state is more conservative than the current one.
11721  * Example:
11722  *       explored                   current
11723  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11724  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11725  *
11726  * In other words if current stack state (one being explored) has more
11727  * valid slots than old one that already passed validation, it means
11728  * the verifier can stop exploring and conclude that current state is valid too
11729  *
11730  * Similarly with registers. If explored state has register type as invalid
11731  * whereas register type in current state is meaningful, it means that
11732  * the current state will reach 'bpf_exit' instruction safely
11733  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)11734 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11735 			      struct bpf_func_state *cur)
11736 {
11737 	int i;
11738 
11739 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11740 	for (i = 0; i < MAX_BPF_REG; i++)
11741 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
11742 			     env->idmap_scratch))
11743 			return false;
11744 
11745 	if (!stacksafe(env, old, cur, env->idmap_scratch))
11746 		return false;
11747 
11748 	if (!refsafe(old, cur))
11749 		return false;
11750 
11751 	return true;
11752 }
11753 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)11754 static bool states_equal(struct bpf_verifier_env *env,
11755 			 struct bpf_verifier_state *old,
11756 			 struct bpf_verifier_state *cur)
11757 {
11758 	int i;
11759 
11760 	if (old->curframe != cur->curframe)
11761 		return false;
11762 
11763 	/* Verification state from speculative execution simulation
11764 	 * must never prune a non-speculative execution one.
11765 	 */
11766 	if (old->speculative && !cur->speculative)
11767 		return false;
11768 
11769 	if (old->active_spin_lock != cur->active_spin_lock)
11770 		return false;
11771 
11772 	/* for states to be equal callsites have to be the same
11773 	 * and all frame states need to be equivalent
11774 	 */
11775 	for (i = 0; i <= old->curframe; i++) {
11776 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
11777 			return false;
11778 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11779 			return false;
11780 	}
11781 	return true;
11782 }
11783 
11784 /* Return 0 if no propagation happened. Return negative error code if error
11785  * happened. Otherwise, return the propagated bit.
11786  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)11787 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11788 				  struct bpf_reg_state *reg,
11789 				  struct bpf_reg_state *parent_reg)
11790 {
11791 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11792 	u8 flag = reg->live & REG_LIVE_READ;
11793 	int err;
11794 
11795 	/* When comes here, read flags of PARENT_REG or REG could be any of
11796 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11797 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11798 	 */
11799 	if (parent_flag == REG_LIVE_READ64 ||
11800 	    /* Or if there is no read flag from REG. */
11801 	    !flag ||
11802 	    /* Or if the read flag from REG is the same as PARENT_REG. */
11803 	    parent_flag == flag)
11804 		return 0;
11805 
11806 	err = mark_reg_read(env, reg, parent_reg, flag);
11807 	if (err)
11808 		return err;
11809 
11810 	return flag;
11811 }
11812 
11813 /* A write screens off any subsequent reads; but write marks come from the
11814  * straight-line code between a state and its parent.  When we arrive at an
11815  * equivalent state (jump target or such) we didn't arrive by the straight-line
11816  * code, so read marks in the state must propagate to the parent regardless
11817  * of the state's write marks. That's what 'parent == state->parent' comparison
11818  * in mark_reg_read() is for.
11819  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)11820 static int propagate_liveness(struct bpf_verifier_env *env,
11821 			      const struct bpf_verifier_state *vstate,
11822 			      struct bpf_verifier_state *vparent)
11823 {
11824 	struct bpf_reg_state *state_reg, *parent_reg;
11825 	struct bpf_func_state *state, *parent;
11826 	int i, frame, err = 0;
11827 
11828 	if (vparent->curframe != vstate->curframe) {
11829 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
11830 		     vparent->curframe, vstate->curframe);
11831 		return -EFAULT;
11832 	}
11833 	/* Propagate read liveness of registers... */
11834 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11835 	for (frame = 0; frame <= vstate->curframe; frame++) {
11836 		parent = vparent->frame[frame];
11837 		state = vstate->frame[frame];
11838 		parent_reg = parent->regs;
11839 		state_reg = state->regs;
11840 		/* We don't need to worry about FP liveness, it's read-only */
11841 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11842 			err = propagate_liveness_reg(env, &state_reg[i],
11843 						     &parent_reg[i]);
11844 			if (err < 0)
11845 				return err;
11846 			if (err == REG_LIVE_READ64)
11847 				mark_insn_zext(env, &parent_reg[i]);
11848 		}
11849 
11850 		/* Propagate stack slots. */
11851 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11852 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11853 			parent_reg = &parent->stack[i].spilled_ptr;
11854 			state_reg = &state->stack[i].spilled_ptr;
11855 			err = propagate_liveness_reg(env, state_reg,
11856 						     parent_reg);
11857 			if (err < 0)
11858 				return err;
11859 		}
11860 	}
11861 	return 0;
11862 }
11863 
11864 /* find precise scalars in the previous equivalent state and
11865  * propagate them into the current state
11866  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)11867 static int propagate_precision(struct bpf_verifier_env *env,
11868 			       const struct bpf_verifier_state *old)
11869 {
11870 	struct bpf_reg_state *state_reg;
11871 	struct bpf_func_state *state;
11872 	int i, err = 0, fr;
11873 
11874 	for (fr = old->curframe; fr >= 0; fr--) {
11875 		state = old->frame[fr];
11876 		state_reg = state->regs;
11877 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11878 			if (state_reg->type != SCALAR_VALUE ||
11879 			    !state_reg->precise)
11880 				continue;
11881 			if (env->log.level & BPF_LOG_LEVEL2)
11882 				verbose(env, "frame %d: propagating r%d\n", i, fr);
11883 			err = mark_chain_precision_frame(env, fr, i);
11884 			if (err < 0)
11885 				return err;
11886 		}
11887 
11888 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11889 			if (!is_spilled_reg(&state->stack[i]))
11890 				continue;
11891 			state_reg = &state->stack[i].spilled_ptr;
11892 			if (state_reg->type != SCALAR_VALUE ||
11893 			    !state_reg->precise)
11894 				continue;
11895 			if (env->log.level & BPF_LOG_LEVEL2)
11896 				verbose(env, "frame %d: propagating fp%d\n",
11897 					(-i - 1) * BPF_REG_SIZE, fr);
11898 			err = mark_chain_precision_stack_frame(env, fr, i);
11899 			if (err < 0)
11900 				return err;
11901 		}
11902 	}
11903 	return 0;
11904 }
11905 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)11906 static bool states_maybe_looping(struct bpf_verifier_state *old,
11907 				 struct bpf_verifier_state *cur)
11908 {
11909 	struct bpf_func_state *fold, *fcur;
11910 	int i, fr = cur->curframe;
11911 
11912 	if (old->curframe != fr)
11913 		return false;
11914 
11915 	fold = old->frame[fr];
11916 	fcur = cur->frame[fr];
11917 	for (i = 0; i < MAX_BPF_REG; i++)
11918 		if (memcmp(&fold->regs[i], &fcur->regs[i],
11919 			   offsetof(struct bpf_reg_state, parent)))
11920 			return false;
11921 	return true;
11922 }
11923 
11924 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)11925 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11926 {
11927 	struct bpf_verifier_state_list *new_sl;
11928 	struct bpf_verifier_state_list *sl, **pprev;
11929 	struct bpf_verifier_state *cur = env->cur_state, *new;
11930 	int i, j, err, states_cnt = 0;
11931 	bool add_new_state = env->test_state_freq ? true : false;
11932 
11933 	cur->last_insn_idx = env->prev_insn_idx;
11934 	if (!env->insn_aux_data[insn_idx].prune_point)
11935 		/* this 'insn_idx' instruction wasn't marked, so we will not
11936 		 * be doing state search here
11937 		 */
11938 		return 0;
11939 
11940 	/* bpf progs typically have pruning point every 4 instructions
11941 	 * http://vger.kernel.org/bpfconf2019.html#session-1
11942 	 * Do not add new state for future pruning if the verifier hasn't seen
11943 	 * at least 2 jumps and at least 8 instructions.
11944 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11945 	 * In tests that amounts to up to 50% reduction into total verifier
11946 	 * memory consumption and 20% verifier time speedup.
11947 	 */
11948 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11949 	    env->insn_processed - env->prev_insn_processed >= 8)
11950 		add_new_state = true;
11951 
11952 	pprev = explored_state(env, insn_idx);
11953 	sl = *pprev;
11954 
11955 	clean_live_states(env, insn_idx, cur);
11956 
11957 	while (sl) {
11958 		states_cnt++;
11959 		if (sl->state.insn_idx != insn_idx)
11960 			goto next;
11961 
11962 		if (sl->state.branches) {
11963 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11964 
11965 			if (frame->in_async_callback_fn &&
11966 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11967 				/* Different async_entry_cnt means that the verifier is
11968 				 * processing another entry into async callback.
11969 				 * Seeing the same state is not an indication of infinite
11970 				 * loop or infinite recursion.
11971 				 * But finding the same state doesn't mean that it's safe
11972 				 * to stop processing the current state. The previous state
11973 				 * hasn't yet reached bpf_exit, since state.branches > 0.
11974 				 * Checking in_async_callback_fn alone is not enough either.
11975 				 * Since the verifier still needs to catch infinite loops
11976 				 * inside async callbacks.
11977 				 */
11978 			} else if (states_maybe_looping(&sl->state, cur) &&
11979 				   states_equal(env, &sl->state, cur)) {
11980 				verbose_linfo(env, insn_idx, "; ");
11981 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11982 				return -EINVAL;
11983 			}
11984 			/* if the verifier is processing a loop, avoid adding new state
11985 			 * too often, since different loop iterations have distinct
11986 			 * states and may not help future pruning.
11987 			 * This threshold shouldn't be too low to make sure that
11988 			 * a loop with large bound will be rejected quickly.
11989 			 * The most abusive loop will be:
11990 			 * r1 += 1
11991 			 * if r1 < 1000000 goto pc-2
11992 			 * 1M insn_procssed limit / 100 == 10k peak states.
11993 			 * This threshold shouldn't be too high either, since states
11994 			 * at the end of the loop are likely to be useful in pruning.
11995 			 */
11996 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11997 			    env->insn_processed - env->prev_insn_processed < 100)
11998 				add_new_state = false;
11999 			goto miss;
12000 		}
12001 		if (states_equal(env, &sl->state, cur)) {
12002 			sl->hit_cnt++;
12003 			/* reached equivalent register/stack state,
12004 			 * prune the search.
12005 			 * Registers read by the continuation are read by us.
12006 			 * If we have any write marks in env->cur_state, they
12007 			 * will prevent corresponding reads in the continuation
12008 			 * from reaching our parent (an explored_state).  Our
12009 			 * own state will get the read marks recorded, but
12010 			 * they'll be immediately forgotten as we're pruning
12011 			 * this state and will pop a new one.
12012 			 */
12013 			err = propagate_liveness(env, &sl->state, cur);
12014 
12015 			/* if previous state reached the exit with precision and
12016 			 * current state is equivalent to it (except precsion marks)
12017 			 * the precision needs to be propagated back in
12018 			 * the current state.
12019 			 */
12020 			err = err ? : push_jmp_history(env, cur);
12021 			err = err ? : propagate_precision(env, &sl->state);
12022 			if (err)
12023 				return err;
12024 			return 1;
12025 		}
12026 miss:
12027 		/* when new state is not going to be added do not increase miss count.
12028 		 * Otherwise several loop iterations will remove the state
12029 		 * recorded earlier. The goal of these heuristics is to have
12030 		 * states from some iterations of the loop (some in the beginning
12031 		 * and some at the end) to help pruning.
12032 		 */
12033 		if (add_new_state)
12034 			sl->miss_cnt++;
12035 		/* heuristic to determine whether this state is beneficial
12036 		 * to keep checking from state equivalence point of view.
12037 		 * Higher numbers increase max_states_per_insn and verification time,
12038 		 * but do not meaningfully decrease insn_processed.
12039 		 */
12040 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12041 			/* the state is unlikely to be useful. Remove it to
12042 			 * speed up verification
12043 			 */
12044 			*pprev = sl->next;
12045 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12046 				u32 br = sl->state.branches;
12047 
12048 				WARN_ONCE(br,
12049 					  "BUG live_done but branches_to_explore %d\n",
12050 					  br);
12051 				free_verifier_state(&sl->state, false);
12052 				kfree(sl);
12053 				env->peak_states--;
12054 			} else {
12055 				/* cannot free this state, since parentage chain may
12056 				 * walk it later. Add it for free_list instead to
12057 				 * be freed at the end of verification
12058 				 */
12059 				sl->next = env->free_list;
12060 				env->free_list = sl;
12061 			}
12062 			sl = *pprev;
12063 			continue;
12064 		}
12065 next:
12066 		pprev = &sl->next;
12067 		sl = *pprev;
12068 	}
12069 
12070 	if (env->max_states_per_insn < states_cnt)
12071 		env->max_states_per_insn = states_cnt;
12072 
12073 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12074 		return push_jmp_history(env, cur);
12075 
12076 	if (!add_new_state)
12077 		return push_jmp_history(env, cur);
12078 
12079 	/* There were no equivalent states, remember the current one.
12080 	 * Technically the current state is not proven to be safe yet,
12081 	 * but it will either reach outer most bpf_exit (which means it's safe)
12082 	 * or it will be rejected. When there are no loops the verifier won't be
12083 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12084 	 * again on the way to bpf_exit.
12085 	 * When looping the sl->state.branches will be > 0 and this state
12086 	 * will not be considered for equivalence until branches == 0.
12087 	 */
12088 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12089 	if (!new_sl)
12090 		return -ENOMEM;
12091 	env->total_states++;
12092 	env->peak_states++;
12093 	env->prev_jmps_processed = env->jmps_processed;
12094 	env->prev_insn_processed = env->insn_processed;
12095 
12096 	/* add new state to the head of linked list */
12097 	new = &new_sl->state;
12098 	err = copy_verifier_state(new, cur);
12099 	if (err) {
12100 		free_verifier_state(new, false);
12101 		kfree(new_sl);
12102 		return err;
12103 	}
12104 	new->insn_idx = insn_idx;
12105 	WARN_ONCE(new->branches != 1,
12106 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12107 
12108 	cur->parent = new;
12109 	cur->first_insn_idx = insn_idx;
12110 	clear_jmp_history(cur);
12111 	new_sl->next = *explored_state(env, insn_idx);
12112 	*explored_state(env, insn_idx) = new_sl;
12113 	/* connect new state to parentage chain. Current frame needs all
12114 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
12115 	 * to the stack implicitly by JITs) so in callers' frames connect just
12116 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12117 	 * the state of the call instruction (with WRITTEN set), and r0 comes
12118 	 * from callee with its full parentage chain, anyway.
12119 	 */
12120 	/* clear write marks in current state: the writes we did are not writes
12121 	 * our child did, so they don't screen off its reads from us.
12122 	 * (There are no read marks in current state, because reads always mark
12123 	 * their parent and current state never has children yet.  Only
12124 	 * explored_states can get read marks.)
12125 	 */
12126 	for (j = 0; j <= cur->curframe; j++) {
12127 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12128 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12129 		for (i = 0; i < BPF_REG_FP; i++)
12130 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12131 	}
12132 
12133 	/* all stack frames are accessible from callee, clear them all */
12134 	for (j = 0; j <= cur->curframe; j++) {
12135 		struct bpf_func_state *frame = cur->frame[j];
12136 		struct bpf_func_state *newframe = new->frame[j];
12137 
12138 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12139 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12140 			frame->stack[i].spilled_ptr.parent =
12141 						&newframe->stack[i].spilled_ptr;
12142 		}
12143 	}
12144 	return 0;
12145 }
12146 
12147 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)12148 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12149 {
12150 	switch (base_type(type)) {
12151 	case PTR_TO_CTX:
12152 	case PTR_TO_SOCKET:
12153 	case PTR_TO_SOCK_COMMON:
12154 	case PTR_TO_TCP_SOCK:
12155 	case PTR_TO_XDP_SOCK:
12156 	case PTR_TO_BTF_ID:
12157 		return false;
12158 	default:
12159 		return true;
12160 	}
12161 }
12162 
12163 /* If an instruction was previously used with particular pointer types, then we
12164  * need to be careful to avoid cases such as the below, where it may be ok
12165  * for one branch accessing the pointer, but not ok for the other branch:
12166  *
12167  * R1 = sock_ptr
12168  * goto X;
12169  * ...
12170  * R1 = some_other_valid_ptr;
12171  * goto X;
12172  * ...
12173  * R2 = *(u32 *)(R1 + 0);
12174  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)12175 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12176 {
12177 	return src != prev && (!reg_type_mismatch_ok(src) ||
12178 			       !reg_type_mismatch_ok(prev));
12179 }
12180 
do_check(struct bpf_verifier_env * env)12181 static int do_check(struct bpf_verifier_env *env)
12182 {
12183 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12184 	struct bpf_verifier_state *state = env->cur_state;
12185 	struct bpf_insn *insns = env->prog->insnsi;
12186 	struct bpf_reg_state *regs;
12187 	int insn_cnt = env->prog->len;
12188 	bool do_print_state = false;
12189 	int prev_insn_idx = -1;
12190 
12191 	for (;;) {
12192 		struct bpf_insn *insn;
12193 		u8 class;
12194 		int err;
12195 
12196 		env->prev_insn_idx = prev_insn_idx;
12197 		if (env->insn_idx >= insn_cnt) {
12198 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
12199 				env->insn_idx, insn_cnt);
12200 			return -EFAULT;
12201 		}
12202 
12203 		insn = &insns[env->insn_idx];
12204 		class = BPF_CLASS(insn->code);
12205 
12206 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12207 			verbose(env,
12208 				"BPF program is too large. Processed %d insn\n",
12209 				env->insn_processed);
12210 			return -E2BIG;
12211 		}
12212 
12213 		err = is_state_visited(env, env->insn_idx);
12214 		if (err < 0)
12215 			return err;
12216 		if (err == 1) {
12217 			/* found equivalent state, can prune the search */
12218 			if (env->log.level & BPF_LOG_LEVEL) {
12219 				if (do_print_state)
12220 					verbose(env, "\nfrom %d to %d%s: safe\n",
12221 						env->prev_insn_idx, env->insn_idx,
12222 						env->cur_state->speculative ?
12223 						" (speculative execution)" : "");
12224 				else
12225 					verbose(env, "%d: safe\n", env->insn_idx);
12226 			}
12227 			goto process_bpf_exit;
12228 		}
12229 
12230 		if (signal_pending(current))
12231 			return -EAGAIN;
12232 
12233 		if (need_resched())
12234 			cond_resched();
12235 
12236 		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12237 			verbose(env, "\nfrom %d to %d%s:",
12238 				env->prev_insn_idx, env->insn_idx,
12239 				env->cur_state->speculative ?
12240 				" (speculative execution)" : "");
12241 			print_verifier_state(env, state->frame[state->curframe], true);
12242 			do_print_state = false;
12243 		}
12244 
12245 		if (env->log.level & BPF_LOG_LEVEL) {
12246 			const struct bpf_insn_cbs cbs = {
12247 				.cb_call	= disasm_kfunc_name,
12248 				.cb_print	= verbose,
12249 				.private_data	= env,
12250 			};
12251 
12252 			if (verifier_state_scratched(env))
12253 				print_insn_state(env, state->frame[state->curframe]);
12254 
12255 			verbose_linfo(env, env->insn_idx, "; ");
12256 			env->prev_log_len = env->log.len_used;
12257 			verbose(env, "%d: ", env->insn_idx);
12258 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12259 			env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12260 			env->prev_log_len = env->log.len_used;
12261 		}
12262 
12263 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
12264 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12265 							   env->prev_insn_idx);
12266 			if (err)
12267 				return err;
12268 		}
12269 
12270 		regs = cur_regs(env);
12271 		sanitize_mark_insn_seen(env);
12272 		prev_insn_idx = env->insn_idx;
12273 
12274 		if (class == BPF_ALU || class == BPF_ALU64) {
12275 			err = check_alu_op(env, insn);
12276 			if (err)
12277 				return err;
12278 
12279 		} else if (class == BPF_LDX) {
12280 			enum bpf_reg_type *prev_src_type, src_reg_type;
12281 
12282 			/* check for reserved fields is already done */
12283 
12284 			/* check src operand */
12285 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12286 			if (err)
12287 				return err;
12288 
12289 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12290 			if (err)
12291 				return err;
12292 
12293 			src_reg_type = regs[insn->src_reg].type;
12294 
12295 			/* check that memory (src_reg + off) is readable,
12296 			 * the state of dst_reg will be updated by this func
12297 			 */
12298 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
12299 					       insn->off, BPF_SIZE(insn->code),
12300 					       BPF_READ, insn->dst_reg, false);
12301 			if (err)
12302 				return err;
12303 
12304 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12305 
12306 			if (*prev_src_type == NOT_INIT) {
12307 				/* saw a valid insn
12308 				 * dst_reg = *(u32 *)(src_reg + off)
12309 				 * save type to validate intersecting paths
12310 				 */
12311 				*prev_src_type = src_reg_type;
12312 
12313 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12314 				/* ABuser program is trying to use the same insn
12315 				 * dst_reg = *(u32*) (src_reg + off)
12316 				 * with different pointer types:
12317 				 * src_reg == ctx in one branch and
12318 				 * src_reg == stack|map in some other branch.
12319 				 * Reject it.
12320 				 */
12321 				verbose(env, "same insn cannot be used with different pointers\n");
12322 				return -EINVAL;
12323 			}
12324 
12325 		} else if (class == BPF_STX) {
12326 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
12327 
12328 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12329 				err = check_atomic(env, env->insn_idx, insn);
12330 				if (err)
12331 					return err;
12332 				env->insn_idx++;
12333 				continue;
12334 			}
12335 
12336 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12337 				verbose(env, "BPF_STX uses reserved fields\n");
12338 				return -EINVAL;
12339 			}
12340 
12341 			/* check src1 operand */
12342 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
12343 			if (err)
12344 				return err;
12345 			/* check src2 operand */
12346 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12347 			if (err)
12348 				return err;
12349 
12350 			dst_reg_type = regs[insn->dst_reg].type;
12351 
12352 			/* check that memory (dst_reg + off) is writeable */
12353 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12354 					       insn->off, BPF_SIZE(insn->code),
12355 					       BPF_WRITE, insn->src_reg, false);
12356 			if (err)
12357 				return err;
12358 
12359 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12360 
12361 			if (*prev_dst_type == NOT_INIT) {
12362 				*prev_dst_type = dst_reg_type;
12363 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12364 				verbose(env, "same insn cannot be used with different pointers\n");
12365 				return -EINVAL;
12366 			}
12367 
12368 		} else if (class == BPF_ST) {
12369 			if (BPF_MODE(insn->code) != BPF_MEM ||
12370 			    insn->src_reg != BPF_REG_0) {
12371 				verbose(env, "BPF_ST uses reserved fields\n");
12372 				return -EINVAL;
12373 			}
12374 			/* check src operand */
12375 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12376 			if (err)
12377 				return err;
12378 
12379 			if (is_ctx_reg(env, insn->dst_reg)) {
12380 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12381 					insn->dst_reg,
12382 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12383 				return -EACCES;
12384 			}
12385 
12386 			/* check that memory (dst_reg + off) is writeable */
12387 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12388 					       insn->off, BPF_SIZE(insn->code),
12389 					       BPF_WRITE, -1, false);
12390 			if (err)
12391 				return err;
12392 
12393 		} else if (class == BPF_JMP || class == BPF_JMP32) {
12394 			u8 opcode = BPF_OP(insn->code);
12395 
12396 			env->jmps_processed++;
12397 			if (opcode == BPF_CALL) {
12398 				if (BPF_SRC(insn->code) != BPF_K ||
12399 				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12400 				     && insn->off != 0) ||
12401 				    (insn->src_reg != BPF_REG_0 &&
12402 				     insn->src_reg != BPF_PSEUDO_CALL &&
12403 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12404 				    insn->dst_reg != BPF_REG_0 ||
12405 				    class == BPF_JMP32) {
12406 					verbose(env, "BPF_CALL uses reserved fields\n");
12407 					return -EINVAL;
12408 				}
12409 
12410 				if (env->cur_state->active_spin_lock &&
12411 				    (insn->src_reg == BPF_PSEUDO_CALL ||
12412 				     insn->imm != BPF_FUNC_spin_unlock)) {
12413 					verbose(env, "function calls are not allowed while holding a lock\n");
12414 					return -EINVAL;
12415 				}
12416 				if (insn->src_reg == BPF_PSEUDO_CALL)
12417 					err = check_func_call(env, insn, &env->insn_idx);
12418 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12419 					err = check_kfunc_call(env, insn, &env->insn_idx);
12420 				else
12421 					err = check_helper_call(env, insn, &env->insn_idx);
12422 				if (err)
12423 					return err;
12424 			} else if (opcode == BPF_JA) {
12425 				if (BPF_SRC(insn->code) != BPF_K ||
12426 				    insn->imm != 0 ||
12427 				    insn->src_reg != BPF_REG_0 ||
12428 				    insn->dst_reg != BPF_REG_0 ||
12429 				    class == BPF_JMP32) {
12430 					verbose(env, "BPF_JA uses reserved fields\n");
12431 					return -EINVAL;
12432 				}
12433 
12434 				env->insn_idx += insn->off + 1;
12435 				continue;
12436 
12437 			} else if (opcode == BPF_EXIT) {
12438 				if (BPF_SRC(insn->code) != BPF_K ||
12439 				    insn->imm != 0 ||
12440 				    insn->src_reg != BPF_REG_0 ||
12441 				    insn->dst_reg != BPF_REG_0 ||
12442 				    class == BPF_JMP32) {
12443 					verbose(env, "BPF_EXIT uses reserved fields\n");
12444 					return -EINVAL;
12445 				}
12446 
12447 				if (env->cur_state->active_spin_lock) {
12448 					verbose(env, "bpf_spin_unlock is missing\n");
12449 					return -EINVAL;
12450 				}
12451 
12452 				/* We must do check_reference_leak here before
12453 				 * prepare_func_exit to handle the case when
12454 				 * state->curframe > 0, it may be a callback
12455 				 * function, for which reference_state must
12456 				 * match caller reference state when it exits.
12457 				 */
12458 				err = check_reference_leak(env);
12459 				if (err)
12460 					return err;
12461 
12462 				if (state->curframe) {
12463 					/* exit from nested function */
12464 					err = prepare_func_exit(env, &env->insn_idx);
12465 					if (err)
12466 						return err;
12467 					do_print_state = true;
12468 					continue;
12469 				}
12470 
12471 				err = check_return_code(env);
12472 				if (err)
12473 					return err;
12474 process_bpf_exit:
12475 				mark_verifier_state_scratched(env);
12476 				update_branch_counts(env, env->cur_state);
12477 				err = pop_stack(env, &prev_insn_idx,
12478 						&env->insn_idx, pop_log);
12479 				if (err < 0) {
12480 					if (err != -ENOENT)
12481 						return err;
12482 					break;
12483 				} else {
12484 					do_print_state = true;
12485 					continue;
12486 				}
12487 			} else {
12488 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
12489 				if (err)
12490 					return err;
12491 			}
12492 		} else if (class == BPF_LD) {
12493 			u8 mode = BPF_MODE(insn->code);
12494 
12495 			if (mode == BPF_ABS || mode == BPF_IND) {
12496 				err = check_ld_abs(env, insn);
12497 				if (err)
12498 					return err;
12499 
12500 			} else if (mode == BPF_IMM) {
12501 				err = check_ld_imm(env, insn);
12502 				if (err)
12503 					return err;
12504 
12505 				env->insn_idx++;
12506 				sanitize_mark_insn_seen(env);
12507 			} else {
12508 				verbose(env, "invalid BPF_LD mode\n");
12509 				return -EINVAL;
12510 			}
12511 		} else {
12512 			verbose(env, "unknown insn class %d\n", class);
12513 			return -EINVAL;
12514 		}
12515 
12516 		env->insn_idx++;
12517 	}
12518 
12519 	return 0;
12520 }
12521 
find_btf_percpu_datasec(struct btf * btf)12522 static int find_btf_percpu_datasec(struct btf *btf)
12523 {
12524 	const struct btf_type *t;
12525 	const char *tname;
12526 	int i, n;
12527 
12528 	/*
12529 	 * Both vmlinux and module each have their own ".data..percpu"
12530 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12531 	 * types to look at only module's own BTF types.
12532 	 */
12533 	n = btf_nr_types(btf);
12534 	if (btf_is_module(btf))
12535 		i = btf_nr_types(btf_vmlinux);
12536 	else
12537 		i = 1;
12538 
12539 	for(; i < n; i++) {
12540 		t = btf_type_by_id(btf, i);
12541 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12542 			continue;
12543 
12544 		tname = btf_name_by_offset(btf, t->name_off);
12545 		if (!strcmp(tname, ".data..percpu"))
12546 			return i;
12547 	}
12548 
12549 	return -ENOENT;
12550 }
12551 
12552 /* 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)12553 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12554 			       struct bpf_insn *insn,
12555 			       struct bpf_insn_aux_data *aux)
12556 {
12557 	const struct btf_var_secinfo *vsi;
12558 	const struct btf_type *datasec;
12559 	struct btf_mod_pair *btf_mod;
12560 	const struct btf_type *t;
12561 	const char *sym_name;
12562 	bool percpu = false;
12563 	u32 type, id = insn->imm;
12564 	struct btf *btf;
12565 	s32 datasec_id;
12566 	u64 addr;
12567 	int i, btf_fd, err;
12568 
12569 	btf_fd = insn[1].imm;
12570 	if (btf_fd) {
12571 		btf = btf_get_by_fd(btf_fd);
12572 		if (IS_ERR(btf)) {
12573 			verbose(env, "invalid module BTF object FD specified.\n");
12574 			return -EINVAL;
12575 		}
12576 	} else {
12577 		if (!btf_vmlinux) {
12578 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12579 			return -EINVAL;
12580 		}
12581 		btf = btf_vmlinux;
12582 		btf_get(btf);
12583 	}
12584 
12585 	t = btf_type_by_id(btf, id);
12586 	if (!t) {
12587 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12588 		err = -ENOENT;
12589 		goto err_put;
12590 	}
12591 
12592 	if (!btf_type_is_var(t)) {
12593 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12594 		err = -EINVAL;
12595 		goto err_put;
12596 	}
12597 
12598 	sym_name = btf_name_by_offset(btf, t->name_off);
12599 	addr = kallsyms_lookup_name(sym_name);
12600 	if (!addr) {
12601 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12602 			sym_name);
12603 		err = -ENOENT;
12604 		goto err_put;
12605 	}
12606 
12607 	datasec_id = find_btf_percpu_datasec(btf);
12608 	if (datasec_id > 0) {
12609 		datasec = btf_type_by_id(btf, datasec_id);
12610 		for_each_vsi(i, datasec, vsi) {
12611 			if (vsi->type == id) {
12612 				percpu = true;
12613 				break;
12614 			}
12615 		}
12616 	}
12617 
12618 	insn[0].imm = (u32)addr;
12619 	insn[1].imm = addr >> 32;
12620 
12621 	type = t->type;
12622 	t = btf_type_skip_modifiers(btf, type, NULL);
12623 	if (percpu) {
12624 		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12625 		aux->btf_var.btf = btf;
12626 		aux->btf_var.btf_id = type;
12627 	} else if (!btf_type_is_struct(t)) {
12628 		const struct btf_type *ret;
12629 		const char *tname;
12630 		u32 tsize;
12631 
12632 		/* resolve the type size of ksym. */
12633 		ret = btf_resolve_size(btf, t, &tsize);
12634 		if (IS_ERR(ret)) {
12635 			tname = btf_name_by_offset(btf, t->name_off);
12636 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12637 				tname, PTR_ERR(ret));
12638 			err = -EINVAL;
12639 			goto err_put;
12640 		}
12641 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12642 		aux->btf_var.mem_size = tsize;
12643 	} else {
12644 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
12645 		aux->btf_var.btf = btf;
12646 		aux->btf_var.btf_id = type;
12647 	}
12648 
12649 	/* check whether we recorded this BTF (and maybe module) already */
12650 	for (i = 0; i < env->used_btf_cnt; i++) {
12651 		if (env->used_btfs[i].btf == btf) {
12652 			btf_put(btf);
12653 			return 0;
12654 		}
12655 	}
12656 
12657 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
12658 		err = -E2BIG;
12659 		goto err_put;
12660 	}
12661 
12662 	btf_mod = &env->used_btfs[env->used_btf_cnt];
12663 	btf_mod->btf = btf;
12664 	btf_mod->module = NULL;
12665 
12666 	/* if we reference variables from kernel module, bump its refcount */
12667 	if (btf_is_module(btf)) {
12668 		btf_mod->module = btf_try_get_module(btf);
12669 		if (!btf_mod->module) {
12670 			err = -ENXIO;
12671 			goto err_put;
12672 		}
12673 	}
12674 
12675 	env->used_btf_cnt++;
12676 
12677 	return 0;
12678 err_put:
12679 	btf_put(btf);
12680 	return err;
12681 }
12682 
is_tracing_prog_type(enum bpf_prog_type type)12683 static bool is_tracing_prog_type(enum bpf_prog_type type)
12684 {
12685 	switch (type) {
12686 	case BPF_PROG_TYPE_KPROBE:
12687 	case BPF_PROG_TYPE_TRACEPOINT:
12688 	case BPF_PROG_TYPE_PERF_EVENT:
12689 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
12690 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12691 		return true;
12692 	default:
12693 		return false;
12694 	}
12695 }
12696 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)12697 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12698 					struct bpf_map *map,
12699 					struct bpf_prog *prog)
12700 
12701 {
12702 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12703 
12704 	if (map_value_has_spin_lock(map)) {
12705 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12706 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12707 			return -EINVAL;
12708 		}
12709 
12710 		if (is_tracing_prog_type(prog_type)) {
12711 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12712 			return -EINVAL;
12713 		}
12714 
12715 		if (prog->aux->sleepable) {
12716 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12717 			return -EINVAL;
12718 		}
12719 	}
12720 
12721 	if (map_value_has_timer(map)) {
12722 		if (is_tracing_prog_type(prog_type)) {
12723 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
12724 			return -EINVAL;
12725 		}
12726 	}
12727 
12728 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12729 	    !bpf_offload_prog_map_match(prog, map)) {
12730 		verbose(env, "offload device mismatch between prog and map\n");
12731 		return -EINVAL;
12732 	}
12733 
12734 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12735 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12736 		return -EINVAL;
12737 	}
12738 
12739 	if (prog->aux->sleepable)
12740 		switch (map->map_type) {
12741 		case BPF_MAP_TYPE_HASH:
12742 		case BPF_MAP_TYPE_LRU_HASH:
12743 		case BPF_MAP_TYPE_ARRAY:
12744 		case BPF_MAP_TYPE_PERCPU_HASH:
12745 		case BPF_MAP_TYPE_PERCPU_ARRAY:
12746 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12747 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12748 		case BPF_MAP_TYPE_HASH_OF_MAPS:
12749 		case BPF_MAP_TYPE_RINGBUF:
12750 		case BPF_MAP_TYPE_USER_RINGBUF:
12751 		case BPF_MAP_TYPE_INODE_STORAGE:
12752 		case BPF_MAP_TYPE_SK_STORAGE:
12753 		case BPF_MAP_TYPE_TASK_STORAGE:
12754 			break;
12755 		default:
12756 			verbose(env,
12757 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
12758 			return -EINVAL;
12759 		}
12760 
12761 	return 0;
12762 }
12763 
bpf_map_is_cgroup_storage(struct bpf_map * map)12764 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12765 {
12766 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12767 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12768 }
12769 
12770 /* find and rewrite pseudo imm in ld_imm64 instructions:
12771  *
12772  * 1. if it accesses map FD, replace it with actual map pointer.
12773  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12774  *
12775  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12776  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)12777 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12778 {
12779 	struct bpf_insn *insn = env->prog->insnsi;
12780 	int insn_cnt = env->prog->len;
12781 	int i, j, err;
12782 
12783 	err = bpf_prog_calc_tag(env->prog);
12784 	if (err)
12785 		return err;
12786 
12787 	for (i = 0; i < insn_cnt; i++, insn++) {
12788 		if (BPF_CLASS(insn->code) == BPF_LDX &&
12789 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12790 			verbose(env, "BPF_LDX uses reserved fields\n");
12791 			return -EINVAL;
12792 		}
12793 
12794 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12795 			struct bpf_insn_aux_data *aux;
12796 			struct bpf_map *map;
12797 			struct fd f;
12798 			u64 addr;
12799 			u32 fd;
12800 
12801 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
12802 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12803 			    insn[1].off != 0) {
12804 				verbose(env, "invalid bpf_ld_imm64 insn\n");
12805 				return -EINVAL;
12806 			}
12807 
12808 			if (insn[0].src_reg == 0)
12809 				/* valid generic load 64-bit imm */
12810 				goto next_insn;
12811 
12812 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12813 				aux = &env->insn_aux_data[i];
12814 				err = check_pseudo_btf_id(env, insn, aux);
12815 				if (err)
12816 					return err;
12817 				goto next_insn;
12818 			}
12819 
12820 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12821 				aux = &env->insn_aux_data[i];
12822 				aux->ptr_type = PTR_TO_FUNC;
12823 				goto next_insn;
12824 			}
12825 
12826 			/* In final convert_pseudo_ld_imm64() step, this is
12827 			 * converted into regular 64-bit imm load insn.
12828 			 */
12829 			switch (insn[0].src_reg) {
12830 			case BPF_PSEUDO_MAP_VALUE:
12831 			case BPF_PSEUDO_MAP_IDX_VALUE:
12832 				break;
12833 			case BPF_PSEUDO_MAP_FD:
12834 			case BPF_PSEUDO_MAP_IDX:
12835 				if (insn[1].imm == 0)
12836 					break;
12837 				fallthrough;
12838 			default:
12839 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12840 				return -EINVAL;
12841 			}
12842 
12843 			switch (insn[0].src_reg) {
12844 			case BPF_PSEUDO_MAP_IDX_VALUE:
12845 			case BPF_PSEUDO_MAP_IDX:
12846 				if (bpfptr_is_null(env->fd_array)) {
12847 					verbose(env, "fd_idx without fd_array is invalid\n");
12848 					return -EPROTO;
12849 				}
12850 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
12851 							    insn[0].imm * sizeof(fd),
12852 							    sizeof(fd)))
12853 					return -EFAULT;
12854 				break;
12855 			default:
12856 				fd = insn[0].imm;
12857 				break;
12858 			}
12859 
12860 			f = fdget(fd);
12861 			map = __bpf_map_get(f);
12862 			if (IS_ERR(map)) {
12863 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
12864 					insn[0].imm);
12865 				return PTR_ERR(map);
12866 			}
12867 
12868 			err = check_map_prog_compatibility(env, map, env->prog);
12869 			if (err) {
12870 				fdput(f);
12871 				return err;
12872 			}
12873 
12874 			aux = &env->insn_aux_data[i];
12875 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12876 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12877 				addr = (unsigned long)map;
12878 			} else {
12879 				u32 off = insn[1].imm;
12880 
12881 				if (off >= BPF_MAX_VAR_OFF) {
12882 					verbose(env, "direct value offset of %u is not allowed\n", off);
12883 					fdput(f);
12884 					return -EINVAL;
12885 				}
12886 
12887 				if (!map->ops->map_direct_value_addr) {
12888 					verbose(env, "no direct value access support for this map type\n");
12889 					fdput(f);
12890 					return -EINVAL;
12891 				}
12892 
12893 				err = map->ops->map_direct_value_addr(map, &addr, off);
12894 				if (err) {
12895 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12896 						map->value_size, off);
12897 					fdput(f);
12898 					return err;
12899 				}
12900 
12901 				aux->map_off = off;
12902 				addr += off;
12903 			}
12904 
12905 			insn[0].imm = (u32)addr;
12906 			insn[1].imm = addr >> 32;
12907 
12908 			/* check whether we recorded this map already */
12909 			for (j = 0; j < env->used_map_cnt; j++) {
12910 				if (env->used_maps[j] == map) {
12911 					aux->map_index = j;
12912 					fdput(f);
12913 					goto next_insn;
12914 				}
12915 			}
12916 
12917 			if (env->used_map_cnt >= MAX_USED_MAPS) {
12918 				fdput(f);
12919 				return -E2BIG;
12920 			}
12921 
12922 			/* hold the map. If the program is rejected by verifier,
12923 			 * the map will be released by release_maps() or it
12924 			 * will be used by the valid program until it's unloaded
12925 			 * and all maps are released in free_used_maps()
12926 			 */
12927 			bpf_map_inc(map);
12928 
12929 			aux->map_index = env->used_map_cnt;
12930 			env->used_maps[env->used_map_cnt++] = map;
12931 
12932 			if (bpf_map_is_cgroup_storage(map) &&
12933 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
12934 				verbose(env, "only one cgroup storage of each type is allowed\n");
12935 				fdput(f);
12936 				return -EBUSY;
12937 			}
12938 
12939 			fdput(f);
12940 next_insn:
12941 			insn++;
12942 			i++;
12943 			continue;
12944 		}
12945 
12946 		/* Basic sanity check before we invest more work here. */
12947 		if (!bpf_opcode_in_insntable(insn->code)) {
12948 			verbose(env, "unknown opcode %02x\n", insn->code);
12949 			return -EINVAL;
12950 		}
12951 	}
12952 
12953 	/* now all pseudo BPF_LD_IMM64 instructions load valid
12954 	 * 'struct bpf_map *' into a register instead of user map_fd.
12955 	 * These pointers will be used later by verifier to validate map access.
12956 	 */
12957 	return 0;
12958 }
12959 
12960 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)12961 static void release_maps(struct bpf_verifier_env *env)
12962 {
12963 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
12964 			     env->used_map_cnt);
12965 }
12966 
12967 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)12968 static void release_btfs(struct bpf_verifier_env *env)
12969 {
12970 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12971 			     env->used_btf_cnt);
12972 }
12973 
12974 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)12975 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12976 {
12977 	struct bpf_insn *insn = env->prog->insnsi;
12978 	int insn_cnt = env->prog->len;
12979 	int i;
12980 
12981 	for (i = 0; i < insn_cnt; i++, insn++) {
12982 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12983 			continue;
12984 		if (insn->src_reg == BPF_PSEUDO_FUNC)
12985 			continue;
12986 		insn->src_reg = 0;
12987 	}
12988 }
12989 
12990 /* single env->prog->insni[off] instruction was replaced with the range
12991  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12992  * [0, off) and [off, end) to new locations, so the patched range stays zero
12993  */
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)12994 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12995 				 struct bpf_insn_aux_data *new_data,
12996 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
12997 {
12998 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12999 	struct bpf_insn *insn = new_prog->insnsi;
13000 	u32 old_seen = old_data[off].seen;
13001 	u32 prog_len;
13002 	int i;
13003 
13004 	/* aux info at OFF always needs adjustment, no matter fast path
13005 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13006 	 * original insn at old prog.
13007 	 */
13008 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13009 
13010 	if (cnt == 1)
13011 		return;
13012 	prog_len = new_prog->len;
13013 
13014 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13015 	memcpy(new_data + off + cnt - 1, old_data + off,
13016 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13017 	for (i = off; i < off + cnt - 1; i++) {
13018 		/* Expand insni[off]'s seen count to the patched range. */
13019 		new_data[i].seen = old_seen;
13020 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
13021 	}
13022 	env->insn_aux_data = new_data;
13023 	vfree(old_data);
13024 }
13025 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)13026 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13027 {
13028 	int i;
13029 
13030 	if (len == 1)
13031 		return;
13032 	/* NOTE: fake 'exit' subprog should be updated as well. */
13033 	for (i = 0; i <= env->subprog_cnt; i++) {
13034 		if (env->subprog_info[i].start <= off)
13035 			continue;
13036 		env->subprog_info[i].start += len - 1;
13037 	}
13038 }
13039 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)13040 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13041 {
13042 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13043 	int i, sz = prog->aux->size_poke_tab;
13044 	struct bpf_jit_poke_descriptor *desc;
13045 
13046 	for (i = 0; i < sz; i++) {
13047 		desc = &tab[i];
13048 		if (desc->insn_idx <= off)
13049 			continue;
13050 		desc->insn_idx += len - 1;
13051 	}
13052 }
13053 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)13054 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13055 					    const struct bpf_insn *patch, u32 len)
13056 {
13057 	struct bpf_prog *new_prog;
13058 	struct bpf_insn_aux_data *new_data = NULL;
13059 
13060 	if (len > 1) {
13061 		new_data = vzalloc(array_size(env->prog->len + len - 1,
13062 					      sizeof(struct bpf_insn_aux_data)));
13063 		if (!new_data)
13064 			return NULL;
13065 	}
13066 
13067 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13068 	if (IS_ERR(new_prog)) {
13069 		if (PTR_ERR(new_prog) == -ERANGE)
13070 			verbose(env,
13071 				"insn %d cannot be patched due to 16-bit range\n",
13072 				env->insn_aux_data[off].orig_idx);
13073 		vfree(new_data);
13074 		return NULL;
13075 	}
13076 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
13077 	adjust_subprog_starts(env, off, len);
13078 	adjust_poke_descs(new_prog, off, len);
13079 	return new_prog;
13080 }
13081 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)13082 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13083 					      u32 off, u32 cnt)
13084 {
13085 	int i, j;
13086 
13087 	/* find first prog starting at or after off (first to remove) */
13088 	for (i = 0; i < env->subprog_cnt; i++)
13089 		if (env->subprog_info[i].start >= off)
13090 			break;
13091 	/* find first prog starting at or after off + cnt (first to stay) */
13092 	for (j = i; j < env->subprog_cnt; j++)
13093 		if (env->subprog_info[j].start >= off + cnt)
13094 			break;
13095 	/* if j doesn't start exactly at off + cnt, we are just removing
13096 	 * the front of previous prog
13097 	 */
13098 	if (env->subprog_info[j].start != off + cnt)
13099 		j--;
13100 
13101 	if (j > i) {
13102 		struct bpf_prog_aux *aux = env->prog->aux;
13103 		int move;
13104 
13105 		/* move fake 'exit' subprog as well */
13106 		move = env->subprog_cnt + 1 - j;
13107 
13108 		memmove(env->subprog_info + i,
13109 			env->subprog_info + j,
13110 			sizeof(*env->subprog_info) * move);
13111 		env->subprog_cnt -= j - i;
13112 
13113 		/* remove func_info */
13114 		if (aux->func_info) {
13115 			move = aux->func_info_cnt - j;
13116 
13117 			memmove(aux->func_info + i,
13118 				aux->func_info + j,
13119 				sizeof(*aux->func_info) * move);
13120 			aux->func_info_cnt -= j - i;
13121 			/* func_info->insn_off is set after all code rewrites,
13122 			 * in adjust_btf_func() - no need to adjust
13123 			 */
13124 		}
13125 	} else {
13126 		/* convert i from "first prog to remove" to "first to adjust" */
13127 		if (env->subprog_info[i].start == off)
13128 			i++;
13129 	}
13130 
13131 	/* update fake 'exit' subprog as well */
13132 	for (; i <= env->subprog_cnt; i++)
13133 		env->subprog_info[i].start -= cnt;
13134 
13135 	return 0;
13136 }
13137 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)13138 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13139 				      u32 cnt)
13140 {
13141 	struct bpf_prog *prog = env->prog;
13142 	u32 i, l_off, l_cnt, nr_linfo;
13143 	struct bpf_line_info *linfo;
13144 
13145 	nr_linfo = prog->aux->nr_linfo;
13146 	if (!nr_linfo)
13147 		return 0;
13148 
13149 	linfo = prog->aux->linfo;
13150 
13151 	/* find first line info to remove, count lines to be removed */
13152 	for (i = 0; i < nr_linfo; i++)
13153 		if (linfo[i].insn_off >= off)
13154 			break;
13155 
13156 	l_off = i;
13157 	l_cnt = 0;
13158 	for (; i < nr_linfo; i++)
13159 		if (linfo[i].insn_off < off + cnt)
13160 			l_cnt++;
13161 		else
13162 			break;
13163 
13164 	/* First live insn doesn't match first live linfo, it needs to "inherit"
13165 	 * last removed linfo.  prog is already modified, so prog->len == off
13166 	 * means no live instructions after (tail of the program was removed).
13167 	 */
13168 	if (prog->len != off && l_cnt &&
13169 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13170 		l_cnt--;
13171 		linfo[--i].insn_off = off + cnt;
13172 	}
13173 
13174 	/* remove the line info which refer to the removed instructions */
13175 	if (l_cnt) {
13176 		memmove(linfo + l_off, linfo + i,
13177 			sizeof(*linfo) * (nr_linfo - i));
13178 
13179 		prog->aux->nr_linfo -= l_cnt;
13180 		nr_linfo = prog->aux->nr_linfo;
13181 	}
13182 
13183 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
13184 	for (i = l_off; i < nr_linfo; i++)
13185 		linfo[i].insn_off -= cnt;
13186 
13187 	/* fix up all subprogs (incl. 'exit') which start >= off */
13188 	for (i = 0; i <= env->subprog_cnt; i++)
13189 		if (env->subprog_info[i].linfo_idx > l_off) {
13190 			/* program may have started in the removed region but
13191 			 * may not be fully removed
13192 			 */
13193 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13194 				env->subprog_info[i].linfo_idx -= l_cnt;
13195 			else
13196 				env->subprog_info[i].linfo_idx = l_off;
13197 		}
13198 
13199 	return 0;
13200 }
13201 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)13202 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13203 {
13204 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13205 	unsigned int orig_prog_len = env->prog->len;
13206 	int err;
13207 
13208 	if (bpf_prog_is_dev_bound(env->prog->aux))
13209 		bpf_prog_offload_remove_insns(env, off, cnt);
13210 
13211 	err = bpf_remove_insns(env->prog, off, cnt);
13212 	if (err)
13213 		return err;
13214 
13215 	err = adjust_subprog_starts_after_remove(env, off, cnt);
13216 	if (err)
13217 		return err;
13218 
13219 	err = bpf_adj_linfo_after_remove(env, off, cnt);
13220 	if (err)
13221 		return err;
13222 
13223 	memmove(aux_data + off,	aux_data + off + cnt,
13224 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
13225 
13226 	return 0;
13227 }
13228 
13229 /* The verifier does more data flow analysis than llvm and will not
13230  * explore branches that are dead at run time. Malicious programs can
13231  * have dead code too. Therefore replace all dead at-run-time code
13232  * with 'ja -1'.
13233  *
13234  * Just nops are not optimal, e.g. if they would sit at the end of the
13235  * program and through another bug we would manage to jump there, then
13236  * we'd execute beyond program memory otherwise. Returning exception
13237  * code also wouldn't work since we can have subprogs where the dead
13238  * code could be located.
13239  */
sanitize_dead_code(struct bpf_verifier_env * env)13240 static void sanitize_dead_code(struct bpf_verifier_env *env)
13241 {
13242 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13243 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13244 	struct bpf_insn *insn = env->prog->insnsi;
13245 	const int insn_cnt = env->prog->len;
13246 	int i;
13247 
13248 	for (i = 0; i < insn_cnt; i++) {
13249 		if (aux_data[i].seen)
13250 			continue;
13251 		memcpy(insn + i, &trap, sizeof(trap));
13252 		aux_data[i].zext_dst = false;
13253 	}
13254 }
13255 
insn_is_cond_jump(u8 code)13256 static bool insn_is_cond_jump(u8 code)
13257 {
13258 	u8 op;
13259 
13260 	if (BPF_CLASS(code) == BPF_JMP32)
13261 		return true;
13262 
13263 	if (BPF_CLASS(code) != BPF_JMP)
13264 		return false;
13265 
13266 	op = BPF_OP(code);
13267 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13268 }
13269 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)13270 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13271 {
13272 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13273 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13274 	struct bpf_insn *insn = env->prog->insnsi;
13275 	const int insn_cnt = env->prog->len;
13276 	int i;
13277 
13278 	for (i = 0; i < insn_cnt; i++, insn++) {
13279 		if (!insn_is_cond_jump(insn->code))
13280 			continue;
13281 
13282 		if (!aux_data[i + 1].seen)
13283 			ja.off = insn->off;
13284 		else if (!aux_data[i + 1 + insn->off].seen)
13285 			ja.off = 0;
13286 		else
13287 			continue;
13288 
13289 		if (bpf_prog_is_dev_bound(env->prog->aux))
13290 			bpf_prog_offload_replace_insn(env, i, &ja);
13291 
13292 		memcpy(insn, &ja, sizeof(ja));
13293 	}
13294 }
13295 
opt_remove_dead_code(struct bpf_verifier_env * env)13296 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13297 {
13298 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13299 	int insn_cnt = env->prog->len;
13300 	int i, err;
13301 
13302 	for (i = 0; i < insn_cnt; i++) {
13303 		int j;
13304 
13305 		j = 0;
13306 		while (i + j < insn_cnt && !aux_data[i + j].seen)
13307 			j++;
13308 		if (!j)
13309 			continue;
13310 
13311 		err = verifier_remove_insns(env, i, j);
13312 		if (err)
13313 			return err;
13314 		insn_cnt = env->prog->len;
13315 	}
13316 
13317 	return 0;
13318 }
13319 
opt_remove_nops(struct bpf_verifier_env * env)13320 static int opt_remove_nops(struct bpf_verifier_env *env)
13321 {
13322 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13323 	struct bpf_insn *insn = env->prog->insnsi;
13324 	int insn_cnt = env->prog->len;
13325 	int i, err;
13326 
13327 	for (i = 0; i < insn_cnt; i++) {
13328 		if (memcmp(&insn[i], &ja, sizeof(ja)))
13329 			continue;
13330 
13331 		err = verifier_remove_insns(env, i, 1);
13332 		if (err)
13333 			return err;
13334 		insn_cnt--;
13335 		i--;
13336 	}
13337 
13338 	return 0;
13339 }
13340 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)13341 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13342 					 const union bpf_attr *attr)
13343 {
13344 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13345 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
13346 	int i, patch_len, delta = 0, len = env->prog->len;
13347 	struct bpf_insn *insns = env->prog->insnsi;
13348 	struct bpf_prog *new_prog;
13349 	bool rnd_hi32;
13350 
13351 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13352 	zext_patch[1] = BPF_ZEXT_REG(0);
13353 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13354 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13355 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13356 	for (i = 0; i < len; i++) {
13357 		int adj_idx = i + delta;
13358 		struct bpf_insn insn;
13359 		int load_reg;
13360 
13361 		insn = insns[adj_idx];
13362 		load_reg = insn_def_regno(&insn);
13363 		if (!aux[adj_idx].zext_dst) {
13364 			u8 code, class;
13365 			u32 imm_rnd;
13366 
13367 			if (!rnd_hi32)
13368 				continue;
13369 
13370 			code = insn.code;
13371 			class = BPF_CLASS(code);
13372 			if (load_reg == -1)
13373 				continue;
13374 
13375 			/* NOTE: arg "reg" (the fourth one) is only used for
13376 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
13377 			 *       here.
13378 			 */
13379 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13380 				if (class == BPF_LD &&
13381 				    BPF_MODE(code) == BPF_IMM)
13382 					i++;
13383 				continue;
13384 			}
13385 
13386 			/* ctx load could be transformed into wider load. */
13387 			if (class == BPF_LDX &&
13388 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
13389 				continue;
13390 
13391 			imm_rnd = get_random_u32();
13392 			rnd_hi32_patch[0] = insn;
13393 			rnd_hi32_patch[1].imm = imm_rnd;
13394 			rnd_hi32_patch[3].dst_reg = load_reg;
13395 			patch = rnd_hi32_patch;
13396 			patch_len = 4;
13397 			goto apply_patch_buffer;
13398 		}
13399 
13400 		/* Add in an zero-extend instruction if a) the JIT has requested
13401 		 * it or b) it's a CMPXCHG.
13402 		 *
13403 		 * The latter is because: BPF_CMPXCHG always loads a value into
13404 		 * R0, therefore always zero-extends. However some archs'
13405 		 * equivalent instruction only does this load when the
13406 		 * comparison is successful. This detail of CMPXCHG is
13407 		 * orthogonal to the general zero-extension behaviour of the
13408 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
13409 		 */
13410 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13411 			continue;
13412 
13413 		/* Zero-extension is done by the caller. */
13414 		if (bpf_pseudo_kfunc_call(&insn))
13415 			continue;
13416 
13417 		if (WARN_ON(load_reg == -1)) {
13418 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13419 			return -EFAULT;
13420 		}
13421 
13422 		zext_patch[0] = insn;
13423 		zext_patch[1].dst_reg = load_reg;
13424 		zext_patch[1].src_reg = load_reg;
13425 		patch = zext_patch;
13426 		patch_len = 2;
13427 apply_patch_buffer:
13428 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13429 		if (!new_prog)
13430 			return -ENOMEM;
13431 		env->prog = new_prog;
13432 		insns = new_prog->insnsi;
13433 		aux = env->insn_aux_data;
13434 		delta += patch_len - 1;
13435 	}
13436 
13437 	return 0;
13438 }
13439 
13440 /* convert load instructions that access fields of a context type into a
13441  * sequence of instructions that access fields of the underlying structure:
13442  *     struct __sk_buff    -> struct sk_buff
13443  *     struct bpf_sock_ops -> struct sock
13444  */
convert_ctx_accesses(struct bpf_verifier_env * env)13445 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13446 {
13447 	const struct bpf_verifier_ops *ops = env->ops;
13448 	int i, cnt, size, ctx_field_size, delta = 0;
13449 	const int insn_cnt = env->prog->len;
13450 	struct bpf_insn insn_buf[16], *insn;
13451 	u32 target_size, size_default, off;
13452 	struct bpf_prog *new_prog;
13453 	enum bpf_access_type type;
13454 	bool is_narrower_load;
13455 
13456 	if (ops->gen_prologue || env->seen_direct_write) {
13457 		if (!ops->gen_prologue) {
13458 			verbose(env, "bpf verifier is misconfigured\n");
13459 			return -EINVAL;
13460 		}
13461 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13462 					env->prog);
13463 		if (cnt >= ARRAY_SIZE(insn_buf)) {
13464 			verbose(env, "bpf verifier is misconfigured\n");
13465 			return -EINVAL;
13466 		} else if (cnt) {
13467 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13468 			if (!new_prog)
13469 				return -ENOMEM;
13470 
13471 			env->prog = new_prog;
13472 			delta += cnt - 1;
13473 		}
13474 	}
13475 
13476 	if (bpf_prog_is_dev_bound(env->prog->aux))
13477 		return 0;
13478 
13479 	insn = env->prog->insnsi + delta;
13480 
13481 	for (i = 0; i < insn_cnt; i++, insn++) {
13482 		bpf_convert_ctx_access_t convert_ctx_access;
13483 		bool ctx_access;
13484 
13485 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13486 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13487 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13488 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13489 			type = BPF_READ;
13490 			ctx_access = true;
13491 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13492 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13493 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13494 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13495 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13496 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13497 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13498 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13499 			type = BPF_WRITE;
13500 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13501 		} else {
13502 			continue;
13503 		}
13504 
13505 		if (type == BPF_WRITE &&
13506 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
13507 			struct bpf_insn patch[] = {
13508 				*insn,
13509 				BPF_ST_NOSPEC(),
13510 			};
13511 
13512 			cnt = ARRAY_SIZE(patch);
13513 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13514 			if (!new_prog)
13515 				return -ENOMEM;
13516 
13517 			delta    += cnt - 1;
13518 			env->prog = new_prog;
13519 			insn      = new_prog->insnsi + i + delta;
13520 			continue;
13521 		}
13522 
13523 		if (!ctx_access)
13524 			continue;
13525 
13526 		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13527 		case PTR_TO_CTX:
13528 			if (!ops->convert_ctx_access)
13529 				continue;
13530 			convert_ctx_access = ops->convert_ctx_access;
13531 			break;
13532 		case PTR_TO_SOCKET:
13533 		case PTR_TO_SOCK_COMMON:
13534 			convert_ctx_access = bpf_sock_convert_ctx_access;
13535 			break;
13536 		case PTR_TO_TCP_SOCK:
13537 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13538 			break;
13539 		case PTR_TO_XDP_SOCK:
13540 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13541 			break;
13542 		case PTR_TO_BTF_ID:
13543 		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13544 			if (type == BPF_READ) {
13545 				insn->code = BPF_LDX | BPF_PROBE_MEM |
13546 					BPF_SIZE((insn)->code);
13547 				env->prog->aux->num_exentries++;
13548 			}
13549 			continue;
13550 		default:
13551 			continue;
13552 		}
13553 
13554 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13555 		size = BPF_LDST_BYTES(insn);
13556 
13557 		/* If the read access is a narrower load of the field,
13558 		 * convert to a 4/8-byte load, to minimum program type specific
13559 		 * convert_ctx_access changes. If conversion is successful,
13560 		 * we will apply proper mask to the result.
13561 		 */
13562 		is_narrower_load = size < ctx_field_size;
13563 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13564 		off = insn->off;
13565 		if (is_narrower_load) {
13566 			u8 size_code;
13567 
13568 			if (type == BPF_WRITE) {
13569 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13570 				return -EINVAL;
13571 			}
13572 
13573 			size_code = BPF_H;
13574 			if (ctx_field_size == 4)
13575 				size_code = BPF_W;
13576 			else if (ctx_field_size == 8)
13577 				size_code = BPF_DW;
13578 
13579 			insn->off = off & ~(size_default - 1);
13580 			insn->code = BPF_LDX | BPF_MEM | size_code;
13581 		}
13582 
13583 		target_size = 0;
13584 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13585 					 &target_size);
13586 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13587 		    (ctx_field_size && !target_size)) {
13588 			verbose(env, "bpf verifier is misconfigured\n");
13589 			return -EINVAL;
13590 		}
13591 
13592 		if (is_narrower_load && size < target_size) {
13593 			u8 shift = bpf_ctx_narrow_access_offset(
13594 				off, size, size_default) * 8;
13595 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13596 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13597 				return -EINVAL;
13598 			}
13599 			if (ctx_field_size <= 4) {
13600 				if (shift)
13601 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13602 									insn->dst_reg,
13603 									shift);
13604 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13605 								(1 << size * 8) - 1);
13606 			} else {
13607 				if (shift)
13608 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13609 									insn->dst_reg,
13610 									shift);
13611 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13612 								(1ULL << size * 8) - 1);
13613 			}
13614 		}
13615 
13616 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13617 		if (!new_prog)
13618 			return -ENOMEM;
13619 
13620 		delta += cnt - 1;
13621 
13622 		/* keep walking new program and skip insns we just inserted */
13623 		env->prog = new_prog;
13624 		insn      = new_prog->insnsi + i + delta;
13625 	}
13626 
13627 	return 0;
13628 }
13629 
jit_subprogs(struct bpf_verifier_env * env)13630 static int jit_subprogs(struct bpf_verifier_env *env)
13631 {
13632 	struct bpf_prog *prog = env->prog, **func, *tmp;
13633 	int i, j, subprog_start, subprog_end = 0, len, subprog;
13634 	struct bpf_map *map_ptr;
13635 	struct bpf_insn *insn;
13636 	void *old_bpf_func;
13637 	int err, num_exentries;
13638 
13639 	if (env->subprog_cnt <= 1)
13640 		return 0;
13641 
13642 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13643 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13644 			continue;
13645 
13646 		/* Upon error here we cannot fall back to interpreter but
13647 		 * need a hard reject of the program. Thus -EFAULT is
13648 		 * propagated in any case.
13649 		 */
13650 		subprog = find_subprog(env, i + insn->imm + 1);
13651 		if (subprog < 0) {
13652 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13653 				  i + insn->imm + 1);
13654 			return -EFAULT;
13655 		}
13656 		/* temporarily remember subprog id inside insn instead of
13657 		 * aux_data, since next loop will split up all insns into funcs
13658 		 */
13659 		insn->off = subprog;
13660 		/* remember original imm in case JIT fails and fallback
13661 		 * to interpreter will be needed
13662 		 */
13663 		env->insn_aux_data[i].call_imm = insn->imm;
13664 		/* point imm to __bpf_call_base+1 from JITs point of view */
13665 		insn->imm = 1;
13666 		if (bpf_pseudo_func(insn))
13667 			/* jit (e.g. x86_64) may emit fewer instructions
13668 			 * if it learns a u32 imm is the same as a u64 imm.
13669 			 * Force a non zero here.
13670 			 */
13671 			insn[1].imm = 1;
13672 	}
13673 
13674 	err = bpf_prog_alloc_jited_linfo(prog);
13675 	if (err)
13676 		goto out_undo_insn;
13677 
13678 	err = -ENOMEM;
13679 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13680 	if (!func)
13681 		goto out_undo_insn;
13682 
13683 	for (i = 0; i < env->subprog_cnt; i++) {
13684 		subprog_start = subprog_end;
13685 		subprog_end = env->subprog_info[i + 1].start;
13686 
13687 		len = subprog_end - subprog_start;
13688 		/* bpf_prog_run() doesn't call subprogs directly,
13689 		 * hence main prog stats include the runtime of subprogs.
13690 		 * subprogs don't have IDs and not reachable via prog_get_next_id
13691 		 * func[i]->stats will never be accessed and stays NULL
13692 		 */
13693 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13694 		if (!func[i])
13695 			goto out_free;
13696 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13697 		       len * sizeof(struct bpf_insn));
13698 		func[i]->type = prog->type;
13699 		func[i]->len = len;
13700 		if (bpf_prog_calc_tag(func[i]))
13701 			goto out_free;
13702 		func[i]->is_func = 1;
13703 		func[i]->aux->func_idx = i;
13704 		/* Below members will be freed only at prog->aux */
13705 		func[i]->aux->btf = prog->aux->btf;
13706 		func[i]->aux->func_info = prog->aux->func_info;
13707 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13708 		func[i]->aux->poke_tab = prog->aux->poke_tab;
13709 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13710 
13711 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
13712 			struct bpf_jit_poke_descriptor *poke;
13713 
13714 			poke = &prog->aux->poke_tab[j];
13715 			if (poke->insn_idx < subprog_end &&
13716 			    poke->insn_idx >= subprog_start)
13717 				poke->aux = func[i]->aux;
13718 		}
13719 
13720 		func[i]->aux->name[0] = 'F';
13721 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13722 		func[i]->jit_requested = 1;
13723 		func[i]->blinding_requested = prog->blinding_requested;
13724 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13725 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13726 		func[i]->aux->linfo = prog->aux->linfo;
13727 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13728 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13729 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13730 		num_exentries = 0;
13731 		insn = func[i]->insnsi;
13732 		for (j = 0; j < func[i]->len; j++, insn++) {
13733 			if (BPF_CLASS(insn->code) == BPF_LDX &&
13734 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
13735 				num_exentries++;
13736 		}
13737 		func[i]->aux->num_exentries = num_exentries;
13738 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13739 		func[i] = bpf_int_jit_compile(func[i]);
13740 		if (!func[i]->jited) {
13741 			err = -ENOTSUPP;
13742 			goto out_free;
13743 		}
13744 		cond_resched();
13745 	}
13746 
13747 	/* at this point all bpf functions were successfully JITed
13748 	 * now populate all bpf_calls with correct addresses and
13749 	 * run last pass of JIT
13750 	 */
13751 	for (i = 0; i < env->subprog_cnt; i++) {
13752 		insn = func[i]->insnsi;
13753 		for (j = 0; j < func[i]->len; j++, insn++) {
13754 			if (bpf_pseudo_func(insn)) {
13755 				subprog = insn->off;
13756 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13757 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13758 				continue;
13759 			}
13760 			if (!bpf_pseudo_call(insn))
13761 				continue;
13762 			subprog = insn->off;
13763 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13764 		}
13765 
13766 		/* we use the aux data to keep a list of the start addresses
13767 		 * of the JITed images for each function in the program
13768 		 *
13769 		 * for some architectures, such as powerpc64, the imm field
13770 		 * might not be large enough to hold the offset of the start
13771 		 * address of the callee's JITed image from __bpf_call_base
13772 		 *
13773 		 * in such cases, we can lookup the start address of a callee
13774 		 * by using its subprog id, available from the off field of
13775 		 * the call instruction, as an index for this list
13776 		 */
13777 		func[i]->aux->func = func;
13778 		func[i]->aux->func_cnt = env->subprog_cnt;
13779 	}
13780 	for (i = 0; i < env->subprog_cnt; i++) {
13781 		old_bpf_func = func[i]->bpf_func;
13782 		tmp = bpf_int_jit_compile(func[i]);
13783 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13784 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13785 			err = -ENOTSUPP;
13786 			goto out_free;
13787 		}
13788 		cond_resched();
13789 	}
13790 
13791 	/* finally lock prog and jit images for all functions and
13792 	 * populate kallsysm
13793 	 */
13794 	for (i = 0; i < env->subprog_cnt; i++) {
13795 		bpf_prog_lock_ro(func[i]);
13796 		bpf_prog_kallsyms_add(func[i]);
13797 	}
13798 
13799 	/* Last step: make now unused interpreter insns from main
13800 	 * prog consistent for later dump requests, so they can
13801 	 * later look the same as if they were interpreted only.
13802 	 */
13803 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13804 		if (bpf_pseudo_func(insn)) {
13805 			insn[0].imm = env->insn_aux_data[i].call_imm;
13806 			insn[1].imm = insn->off;
13807 			insn->off = 0;
13808 			continue;
13809 		}
13810 		if (!bpf_pseudo_call(insn))
13811 			continue;
13812 		insn->off = env->insn_aux_data[i].call_imm;
13813 		subprog = find_subprog(env, i + insn->off + 1);
13814 		insn->imm = subprog;
13815 	}
13816 
13817 	prog->jited = 1;
13818 	prog->bpf_func = func[0]->bpf_func;
13819 	prog->jited_len = func[0]->jited_len;
13820 	prog->aux->func = func;
13821 	prog->aux->func_cnt = env->subprog_cnt;
13822 	bpf_prog_jit_attempt_done(prog);
13823 	return 0;
13824 out_free:
13825 	/* We failed JIT'ing, so at this point we need to unregister poke
13826 	 * descriptors from subprogs, so that kernel is not attempting to
13827 	 * patch it anymore as we're freeing the subprog JIT memory.
13828 	 */
13829 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13830 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13831 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13832 	}
13833 	/* At this point we're guaranteed that poke descriptors are not
13834 	 * live anymore. We can just unlink its descriptor table as it's
13835 	 * released with the main prog.
13836 	 */
13837 	for (i = 0; i < env->subprog_cnt; i++) {
13838 		if (!func[i])
13839 			continue;
13840 		func[i]->aux->poke_tab = NULL;
13841 		bpf_jit_free(func[i]);
13842 	}
13843 	kfree(func);
13844 out_undo_insn:
13845 	/* cleanup main prog to be interpreted */
13846 	prog->jit_requested = 0;
13847 	prog->blinding_requested = 0;
13848 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13849 		if (!bpf_pseudo_call(insn))
13850 			continue;
13851 		insn->off = 0;
13852 		insn->imm = env->insn_aux_data[i].call_imm;
13853 	}
13854 	bpf_prog_jit_attempt_done(prog);
13855 	return err;
13856 }
13857 
fixup_call_args(struct bpf_verifier_env * env)13858 static int fixup_call_args(struct bpf_verifier_env *env)
13859 {
13860 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13861 	struct bpf_prog *prog = env->prog;
13862 	struct bpf_insn *insn = prog->insnsi;
13863 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13864 	int i, depth;
13865 #endif
13866 	int err = 0;
13867 
13868 	if (env->prog->jit_requested &&
13869 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
13870 		err = jit_subprogs(env);
13871 		if (err == 0)
13872 			return 0;
13873 		if (err == -EFAULT)
13874 			return err;
13875 	}
13876 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13877 	if (has_kfunc_call) {
13878 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13879 		return -EINVAL;
13880 	}
13881 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13882 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
13883 		 * have to be rejected, since interpreter doesn't support them yet.
13884 		 */
13885 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13886 		return -EINVAL;
13887 	}
13888 	for (i = 0; i < prog->len; i++, insn++) {
13889 		if (bpf_pseudo_func(insn)) {
13890 			/* When JIT fails the progs with callback calls
13891 			 * have to be rejected, since interpreter doesn't support them yet.
13892 			 */
13893 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
13894 			return -EINVAL;
13895 		}
13896 
13897 		if (!bpf_pseudo_call(insn))
13898 			continue;
13899 		depth = get_callee_stack_depth(env, insn, i);
13900 		if (depth < 0)
13901 			return depth;
13902 		bpf_patch_call_args(insn, depth);
13903 	}
13904 	err = 0;
13905 #endif
13906 	return err;
13907 }
13908 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn)13909 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13910 			    struct bpf_insn *insn)
13911 {
13912 	const struct bpf_kfunc_desc *desc;
13913 
13914 	if (!insn->imm) {
13915 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13916 		return -EINVAL;
13917 	}
13918 
13919 	/* insn->imm has the btf func_id. Replace it with
13920 	 * an address (relative to __bpf_base_call).
13921 	 */
13922 	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13923 	if (!desc) {
13924 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13925 			insn->imm);
13926 		return -EFAULT;
13927 	}
13928 
13929 	insn->imm = desc->imm;
13930 
13931 	return 0;
13932 }
13933 
13934 /* Do various post-verification rewrites in a single program pass.
13935  * These rewrites simplify JIT and interpreter implementations.
13936  */
do_misc_fixups(struct bpf_verifier_env * env)13937 static int do_misc_fixups(struct bpf_verifier_env *env)
13938 {
13939 	struct bpf_prog *prog = env->prog;
13940 	enum bpf_attach_type eatype = prog->expected_attach_type;
13941 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
13942 	struct bpf_insn *insn = prog->insnsi;
13943 	const struct bpf_func_proto *fn;
13944 	const int insn_cnt = prog->len;
13945 	const struct bpf_map_ops *ops;
13946 	struct bpf_insn_aux_data *aux;
13947 	struct bpf_insn insn_buf[16];
13948 	struct bpf_prog *new_prog;
13949 	struct bpf_map *map_ptr;
13950 	int i, ret, cnt, delta = 0;
13951 
13952 	for (i = 0; i < insn_cnt; i++, insn++) {
13953 		/* Make divide-by-zero exceptions impossible. */
13954 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13955 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13956 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13957 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13958 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13959 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13960 			struct bpf_insn *patchlet;
13961 			struct bpf_insn chk_and_div[] = {
13962 				/* [R,W]x div 0 -> 0 */
13963 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13964 					     BPF_JNE | BPF_K, insn->src_reg,
13965 					     0, 2, 0),
13966 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13967 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13968 				*insn,
13969 			};
13970 			struct bpf_insn chk_and_mod[] = {
13971 				/* [R,W]x mod 0 -> [R,W]x */
13972 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13973 					     BPF_JEQ | BPF_K, insn->src_reg,
13974 					     0, 1 + (is64 ? 0 : 1), 0),
13975 				*insn,
13976 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13977 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13978 			};
13979 
13980 			patchlet = isdiv ? chk_and_div : chk_and_mod;
13981 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13982 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13983 
13984 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13985 			if (!new_prog)
13986 				return -ENOMEM;
13987 
13988 			delta    += cnt - 1;
13989 			env->prog = prog = new_prog;
13990 			insn      = new_prog->insnsi + i + delta;
13991 			continue;
13992 		}
13993 
13994 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13995 		if (BPF_CLASS(insn->code) == BPF_LD &&
13996 		    (BPF_MODE(insn->code) == BPF_ABS ||
13997 		     BPF_MODE(insn->code) == BPF_IND)) {
13998 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
13999 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14000 				verbose(env, "bpf verifier is misconfigured\n");
14001 				return -EINVAL;
14002 			}
14003 
14004 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14005 			if (!new_prog)
14006 				return -ENOMEM;
14007 
14008 			delta    += cnt - 1;
14009 			env->prog = prog = new_prog;
14010 			insn      = new_prog->insnsi + i + delta;
14011 			continue;
14012 		}
14013 
14014 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
14015 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14016 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14017 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14018 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14019 			struct bpf_insn *patch = &insn_buf[0];
14020 			bool issrc, isneg, isimm;
14021 			u32 off_reg;
14022 
14023 			aux = &env->insn_aux_data[i + delta];
14024 			if (!aux->alu_state ||
14025 			    aux->alu_state == BPF_ALU_NON_POINTER)
14026 				continue;
14027 
14028 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14029 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14030 				BPF_ALU_SANITIZE_SRC;
14031 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14032 
14033 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
14034 			if (isimm) {
14035 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14036 			} else {
14037 				if (isneg)
14038 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14039 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14040 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14041 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14042 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14043 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14044 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14045 			}
14046 			if (!issrc)
14047 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14048 			insn->src_reg = BPF_REG_AX;
14049 			if (isneg)
14050 				insn->code = insn->code == code_add ?
14051 					     code_sub : code_add;
14052 			*patch++ = *insn;
14053 			if (issrc && isneg && !isimm)
14054 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14055 			cnt = patch - insn_buf;
14056 
14057 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14058 			if (!new_prog)
14059 				return -ENOMEM;
14060 
14061 			delta    += cnt - 1;
14062 			env->prog = prog = new_prog;
14063 			insn      = new_prog->insnsi + i + delta;
14064 			continue;
14065 		}
14066 
14067 		if (insn->code != (BPF_JMP | BPF_CALL))
14068 			continue;
14069 		if (insn->src_reg == BPF_PSEUDO_CALL)
14070 			continue;
14071 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14072 			ret = fixup_kfunc_call(env, insn);
14073 			if (ret)
14074 				return ret;
14075 			continue;
14076 		}
14077 
14078 		if (insn->imm == BPF_FUNC_get_route_realm)
14079 			prog->dst_needed = 1;
14080 		if (insn->imm == BPF_FUNC_get_prandom_u32)
14081 			bpf_user_rnd_init_once();
14082 		if (insn->imm == BPF_FUNC_override_return)
14083 			prog->kprobe_override = 1;
14084 		if (insn->imm == BPF_FUNC_tail_call) {
14085 			/* If we tail call into other programs, we
14086 			 * cannot make any assumptions since they can
14087 			 * be replaced dynamically during runtime in
14088 			 * the program array.
14089 			 */
14090 			prog->cb_access = 1;
14091 			if (!allow_tail_call_in_subprogs(env))
14092 				prog->aux->stack_depth = MAX_BPF_STACK;
14093 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14094 
14095 			/* mark bpf_tail_call as different opcode to avoid
14096 			 * conditional branch in the interpreter for every normal
14097 			 * call and to prevent accidental JITing by JIT compiler
14098 			 * that doesn't support bpf_tail_call yet
14099 			 */
14100 			insn->imm = 0;
14101 			insn->code = BPF_JMP | BPF_TAIL_CALL;
14102 
14103 			aux = &env->insn_aux_data[i + delta];
14104 			if (env->bpf_capable && !prog->blinding_requested &&
14105 			    prog->jit_requested &&
14106 			    !bpf_map_key_poisoned(aux) &&
14107 			    !bpf_map_ptr_poisoned(aux) &&
14108 			    !bpf_map_ptr_unpriv(aux)) {
14109 				struct bpf_jit_poke_descriptor desc = {
14110 					.reason = BPF_POKE_REASON_TAIL_CALL,
14111 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14112 					.tail_call.key = bpf_map_key_immediate(aux),
14113 					.insn_idx = i + delta,
14114 				};
14115 
14116 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
14117 				if (ret < 0) {
14118 					verbose(env, "adding tail call poke descriptor failed\n");
14119 					return ret;
14120 				}
14121 
14122 				insn->imm = ret + 1;
14123 				continue;
14124 			}
14125 
14126 			if (!bpf_map_ptr_unpriv(aux))
14127 				continue;
14128 
14129 			/* instead of changing every JIT dealing with tail_call
14130 			 * emit two extra insns:
14131 			 * if (index >= max_entries) goto out;
14132 			 * index &= array->index_mask;
14133 			 * to avoid out-of-bounds cpu speculation
14134 			 */
14135 			if (bpf_map_ptr_poisoned(aux)) {
14136 				verbose(env, "tail_call abusing map_ptr\n");
14137 				return -EINVAL;
14138 			}
14139 
14140 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14141 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14142 						  map_ptr->max_entries, 2);
14143 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14144 						    container_of(map_ptr,
14145 								 struct bpf_array,
14146 								 map)->index_mask);
14147 			insn_buf[2] = *insn;
14148 			cnt = 3;
14149 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14150 			if (!new_prog)
14151 				return -ENOMEM;
14152 
14153 			delta    += cnt - 1;
14154 			env->prog = prog = new_prog;
14155 			insn      = new_prog->insnsi + i + delta;
14156 			continue;
14157 		}
14158 
14159 		if (insn->imm == BPF_FUNC_timer_set_callback) {
14160 			/* The verifier will process callback_fn as many times as necessary
14161 			 * with different maps and the register states prepared by
14162 			 * set_timer_callback_state will be accurate.
14163 			 *
14164 			 * The following use case is valid:
14165 			 *   map1 is shared by prog1, prog2, prog3.
14166 			 *   prog1 calls bpf_timer_init for some map1 elements
14167 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
14168 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
14169 			 *   prog3 calls bpf_timer_start for some map1 elements.
14170 			 *     Those that were not both bpf_timer_init-ed and
14171 			 *     bpf_timer_set_callback-ed will return -EINVAL.
14172 			 */
14173 			struct bpf_insn ld_addrs[2] = {
14174 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14175 			};
14176 
14177 			insn_buf[0] = ld_addrs[0];
14178 			insn_buf[1] = ld_addrs[1];
14179 			insn_buf[2] = *insn;
14180 			cnt = 3;
14181 
14182 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14183 			if (!new_prog)
14184 				return -ENOMEM;
14185 
14186 			delta    += cnt - 1;
14187 			env->prog = prog = new_prog;
14188 			insn      = new_prog->insnsi + i + delta;
14189 			goto patch_call_imm;
14190 		}
14191 
14192 		if (insn->imm == BPF_FUNC_task_storage_get ||
14193 		    insn->imm == BPF_FUNC_sk_storage_get ||
14194 		    insn->imm == BPF_FUNC_inode_storage_get) {
14195 			if (env->prog->aux->sleepable)
14196 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14197 			else
14198 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14199 			insn_buf[1] = *insn;
14200 			cnt = 2;
14201 
14202 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14203 			if (!new_prog)
14204 				return -ENOMEM;
14205 
14206 			delta += cnt - 1;
14207 			env->prog = prog = new_prog;
14208 			insn = new_prog->insnsi + i + delta;
14209 			goto patch_call_imm;
14210 		}
14211 
14212 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14213 		 * and other inlining handlers are currently limited to 64 bit
14214 		 * only.
14215 		 */
14216 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14217 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
14218 		     insn->imm == BPF_FUNC_map_update_elem ||
14219 		     insn->imm == BPF_FUNC_map_delete_elem ||
14220 		     insn->imm == BPF_FUNC_map_push_elem   ||
14221 		     insn->imm == BPF_FUNC_map_pop_elem    ||
14222 		     insn->imm == BPF_FUNC_map_peek_elem   ||
14223 		     insn->imm == BPF_FUNC_redirect_map    ||
14224 		     insn->imm == BPF_FUNC_for_each_map_elem ||
14225 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14226 			aux = &env->insn_aux_data[i + delta];
14227 			if (bpf_map_ptr_poisoned(aux))
14228 				goto patch_call_imm;
14229 
14230 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14231 			ops = map_ptr->ops;
14232 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
14233 			    ops->map_gen_lookup) {
14234 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14235 				if (cnt == -EOPNOTSUPP)
14236 					goto patch_map_ops_generic;
14237 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14238 					verbose(env, "bpf verifier is misconfigured\n");
14239 					return -EINVAL;
14240 				}
14241 
14242 				new_prog = bpf_patch_insn_data(env, i + delta,
14243 							       insn_buf, cnt);
14244 				if (!new_prog)
14245 					return -ENOMEM;
14246 
14247 				delta    += cnt - 1;
14248 				env->prog = prog = new_prog;
14249 				insn      = new_prog->insnsi + i + delta;
14250 				continue;
14251 			}
14252 
14253 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14254 				     (void *(*)(struct bpf_map *map, void *key))NULL));
14255 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14256 				     (int (*)(struct bpf_map *map, void *key))NULL));
14257 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14258 				     (int (*)(struct bpf_map *map, void *key, void *value,
14259 					      u64 flags))NULL));
14260 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14261 				     (int (*)(struct bpf_map *map, void *value,
14262 					      u64 flags))NULL));
14263 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14264 				     (int (*)(struct bpf_map *map, void *value))NULL));
14265 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14266 				     (int (*)(struct bpf_map *map, void *value))NULL));
14267 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
14268 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14269 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14270 				     (int (*)(struct bpf_map *map,
14271 					      bpf_callback_t callback_fn,
14272 					      void *callback_ctx,
14273 					      u64 flags))NULL));
14274 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14275 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14276 
14277 patch_map_ops_generic:
14278 			switch (insn->imm) {
14279 			case BPF_FUNC_map_lookup_elem:
14280 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14281 				continue;
14282 			case BPF_FUNC_map_update_elem:
14283 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14284 				continue;
14285 			case BPF_FUNC_map_delete_elem:
14286 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14287 				continue;
14288 			case BPF_FUNC_map_push_elem:
14289 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14290 				continue;
14291 			case BPF_FUNC_map_pop_elem:
14292 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14293 				continue;
14294 			case BPF_FUNC_map_peek_elem:
14295 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14296 				continue;
14297 			case BPF_FUNC_redirect_map:
14298 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
14299 				continue;
14300 			case BPF_FUNC_for_each_map_elem:
14301 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14302 				continue;
14303 			case BPF_FUNC_map_lookup_percpu_elem:
14304 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14305 				continue;
14306 			}
14307 
14308 			goto patch_call_imm;
14309 		}
14310 
14311 		/* Implement bpf_jiffies64 inline. */
14312 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
14313 		    insn->imm == BPF_FUNC_jiffies64) {
14314 			struct bpf_insn ld_jiffies_addr[2] = {
14315 				BPF_LD_IMM64(BPF_REG_0,
14316 					     (unsigned long)&jiffies),
14317 			};
14318 
14319 			insn_buf[0] = ld_jiffies_addr[0];
14320 			insn_buf[1] = ld_jiffies_addr[1];
14321 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14322 						  BPF_REG_0, 0);
14323 			cnt = 3;
14324 
14325 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14326 						       cnt);
14327 			if (!new_prog)
14328 				return -ENOMEM;
14329 
14330 			delta    += cnt - 1;
14331 			env->prog = prog = new_prog;
14332 			insn      = new_prog->insnsi + i + delta;
14333 			continue;
14334 		}
14335 
14336 		/* Implement bpf_get_func_arg inline. */
14337 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14338 		    insn->imm == BPF_FUNC_get_func_arg) {
14339 			/* Load nr_args from ctx - 8 */
14340 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14341 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14342 			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14343 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14344 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14345 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14346 			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14347 			insn_buf[7] = BPF_JMP_A(1);
14348 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14349 			cnt = 9;
14350 
14351 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14352 			if (!new_prog)
14353 				return -ENOMEM;
14354 
14355 			delta    += cnt - 1;
14356 			env->prog = prog = new_prog;
14357 			insn      = new_prog->insnsi + i + delta;
14358 			continue;
14359 		}
14360 
14361 		/* Implement bpf_get_func_ret inline. */
14362 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14363 		    insn->imm == BPF_FUNC_get_func_ret) {
14364 			if (eatype == BPF_TRACE_FEXIT ||
14365 			    eatype == BPF_MODIFY_RETURN) {
14366 				/* Load nr_args from ctx - 8 */
14367 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14368 				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14369 				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14370 				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14371 				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14372 				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14373 				cnt = 6;
14374 			} else {
14375 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14376 				cnt = 1;
14377 			}
14378 
14379 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14380 			if (!new_prog)
14381 				return -ENOMEM;
14382 
14383 			delta    += cnt - 1;
14384 			env->prog = prog = new_prog;
14385 			insn      = new_prog->insnsi + i + delta;
14386 			continue;
14387 		}
14388 
14389 		/* Implement get_func_arg_cnt inline. */
14390 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14391 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
14392 			/* Load nr_args from ctx - 8 */
14393 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14394 
14395 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14396 			if (!new_prog)
14397 				return -ENOMEM;
14398 
14399 			env->prog = prog = new_prog;
14400 			insn      = new_prog->insnsi + i + delta;
14401 			continue;
14402 		}
14403 
14404 		/* Implement bpf_get_func_ip inline. */
14405 		if (prog_type == BPF_PROG_TYPE_TRACING &&
14406 		    insn->imm == BPF_FUNC_get_func_ip) {
14407 			/* Load IP address from ctx - 16 */
14408 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14409 
14410 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14411 			if (!new_prog)
14412 				return -ENOMEM;
14413 
14414 			env->prog = prog = new_prog;
14415 			insn      = new_prog->insnsi + i + delta;
14416 			continue;
14417 		}
14418 
14419 patch_call_imm:
14420 		fn = env->ops->get_func_proto(insn->imm, env->prog);
14421 		/* all functions that have prototype and verifier allowed
14422 		 * programs to call them, must be real in-kernel functions
14423 		 */
14424 		if (!fn->func) {
14425 			verbose(env,
14426 				"kernel subsystem misconfigured func %s#%d\n",
14427 				func_id_name(insn->imm), insn->imm);
14428 			return -EFAULT;
14429 		}
14430 		insn->imm = fn->func - __bpf_call_base;
14431 	}
14432 
14433 	/* Since poke tab is now finalized, publish aux to tracker. */
14434 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
14435 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
14436 		if (!map_ptr->ops->map_poke_track ||
14437 		    !map_ptr->ops->map_poke_untrack ||
14438 		    !map_ptr->ops->map_poke_run) {
14439 			verbose(env, "bpf verifier is misconfigured\n");
14440 			return -EINVAL;
14441 		}
14442 
14443 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14444 		if (ret < 0) {
14445 			verbose(env, "tracking tail call prog failed\n");
14446 			return ret;
14447 		}
14448 	}
14449 
14450 	sort_kfunc_descs_by_imm(env->prog);
14451 
14452 	return 0;
14453 }
14454 
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * cnt)14455 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14456 					int position,
14457 					s32 stack_base,
14458 					u32 callback_subprogno,
14459 					u32 *cnt)
14460 {
14461 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14462 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14463 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14464 	int reg_loop_max = BPF_REG_6;
14465 	int reg_loop_cnt = BPF_REG_7;
14466 	int reg_loop_ctx = BPF_REG_8;
14467 
14468 	struct bpf_prog *new_prog;
14469 	u32 callback_start;
14470 	u32 call_insn_offset;
14471 	s32 callback_offset;
14472 
14473 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
14474 	 * be careful to modify this code in sync.
14475 	 */
14476 	struct bpf_insn insn_buf[] = {
14477 		/* Return error and jump to the end of the patch if
14478 		 * expected number of iterations is too big.
14479 		 */
14480 		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14481 		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14482 		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14483 		/* spill R6, R7, R8 to use these as loop vars */
14484 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14485 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14486 		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14487 		/* initialize loop vars */
14488 		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14489 		BPF_MOV32_IMM(reg_loop_cnt, 0),
14490 		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14491 		/* loop header,
14492 		 * if reg_loop_cnt >= reg_loop_max skip the loop body
14493 		 */
14494 		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14495 		/* callback call,
14496 		 * correct callback offset would be set after patching
14497 		 */
14498 		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14499 		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14500 		BPF_CALL_REL(0),
14501 		/* increment loop counter */
14502 		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14503 		/* jump to loop header if callback returned 0 */
14504 		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14505 		/* return value of bpf_loop,
14506 		 * set R0 to the number of iterations
14507 		 */
14508 		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14509 		/* restore original values of R6, R7, R8 */
14510 		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14511 		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14512 		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14513 	};
14514 
14515 	*cnt = ARRAY_SIZE(insn_buf);
14516 	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14517 	if (!new_prog)
14518 		return new_prog;
14519 
14520 	/* callback start is known only after patching */
14521 	callback_start = env->subprog_info[callback_subprogno].start;
14522 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14523 	call_insn_offset = position + 12;
14524 	callback_offset = callback_start - call_insn_offset - 1;
14525 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
14526 
14527 	return new_prog;
14528 }
14529 
is_bpf_loop_call(struct bpf_insn * insn)14530 static bool is_bpf_loop_call(struct bpf_insn *insn)
14531 {
14532 	return insn->code == (BPF_JMP | BPF_CALL) &&
14533 		insn->src_reg == 0 &&
14534 		insn->imm == BPF_FUNC_loop;
14535 }
14536 
14537 /* For all sub-programs in the program (including main) check
14538  * insn_aux_data to see if there are bpf_loop calls that require
14539  * inlining. If such calls are found the calls are replaced with a
14540  * sequence of instructions produced by `inline_bpf_loop` function and
14541  * subprog stack_depth is increased by the size of 3 registers.
14542  * This stack space is used to spill values of the R6, R7, R8.  These
14543  * registers are used to store the loop bound, counter and context
14544  * variables.
14545  */
optimize_bpf_loop(struct bpf_verifier_env * env)14546 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14547 {
14548 	struct bpf_subprog_info *subprogs = env->subprog_info;
14549 	int i, cur_subprog = 0, cnt, delta = 0;
14550 	struct bpf_insn *insn = env->prog->insnsi;
14551 	int insn_cnt = env->prog->len;
14552 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
14553 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14554 	u16 stack_depth_extra = 0;
14555 
14556 	for (i = 0; i < insn_cnt; i++, insn++) {
14557 		struct bpf_loop_inline_state *inline_state =
14558 			&env->insn_aux_data[i + delta].loop_inline_state;
14559 
14560 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14561 			struct bpf_prog *new_prog;
14562 
14563 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14564 			new_prog = inline_bpf_loop(env,
14565 						   i + delta,
14566 						   -(stack_depth + stack_depth_extra),
14567 						   inline_state->callback_subprogno,
14568 						   &cnt);
14569 			if (!new_prog)
14570 				return -ENOMEM;
14571 
14572 			delta     += cnt - 1;
14573 			env->prog  = new_prog;
14574 			insn       = new_prog->insnsi + i + delta;
14575 		}
14576 
14577 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14578 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
14579 			cur_subprog++;
14580 			stack_depth = subprogs[cur_subprog].stack_depth;
14581 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14582 			stack_depth_extra = 0;
14583 		}
14584 	}
14585 
14586 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14587 
14588 	return 0;
14589 }
14590 
free_states(struct bpf_verifier_env * env)14591 static void free_states(struct bpf_verifier_env *env)
14592 {
14593 	struct bpf_verifier_state_list *sl, *sln;
14594 	int i;
14595 
14596 	sl = env->free_list;
14597 	while (sl) {
14598 		sln = sl->next;
14599 		free_verifier_state(&sl->state, false);
14600 		kfree(sl);
14601 		sl = sln;
14602 	}
14603 	env->free_list = NULL;
14604 
14605 	if (!env->explored_states)
14606 		return;
14607 
14608 	for (i = 0; i < state_htab_size(env); i++) {
14609 		sl = env->explored_states[i];
14610 
14611 		while (sl) {
14612 			sln = sl->next;
14613 			free_verifier_state(&sl->state, false);
14614 			kfree(sl);
14615 			sl = sln;
14616 		}
14617 		env->explored_states[i] = NULL;
14618 	}
14619 }
14620 
do_check_common(struct bpf_verifier_env * env,int subprog)14621 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14622 {
14623 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14624 	struct bpf_verifier_state *state;
14625 	struct bpf_reg_state *regs;
14626 	int ret, i;
14627 
14628 	env->prev_linfo = NULL;
14629 	env->pass_cnt++;
14630 
14631 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14632 	if (!state)
14633 		return -ENOMEM;
14634 	state->curframe = 0;
14635 	state->speculative = false;
14636 	state->branches = 1;
14637 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14638 	if (!state->frame[0]) {
14639 		kfree(state);
14640 		return -ENOMEM;
14641 	}
14642 	env->cur_state = state;
14643 	init_func_state(env, state->frame[0],
14644 			BPF_MAIN_FUNC /* callsite */,
14645 			0 /* frameno */,
14646 			subprog);
14647 
14648 	regs = state->frame[state->curframe]->regs;
14649 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14650 		ret = btf_prepare_func_args(env, subprog, regs);
14651 		if (ret)
14652 			goto out;
14653 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14654 			if (regs[i].type == PTR_TO_CTX)
14655 				mark_reg_known_zero(env, regs, i);
14656 			else if (regs[i].type == SCALAR_VALUE)
14657 				mark_reg_unknown(env, regs, i);
14658 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
14659 				const u32 mem_size = regs[i].mem_size;
14660 
14661 				mark_reg_known_zero(env, regs, i);
14662 				regs[i].mem_size = mem_size;
14663 				regs[i].id = ++env->id_gen;
14664 			}
14665 		}
14666 	} else {
14667 		/* 1st arg to a function */
14668 		regs[BPF_REG_1].type = PTR_TO_CTX;
14669 		mark_reg_known_zero(env, regs, BPF_REG_1);
14670 		ret = btf_check_subprog_arg_match(env, subprog, regs);
14671 		if (ret == -EFAULT)
14672 			/* unlikely verifier bug. abort.
14673 			 * ret == 0 and ret < 0 are sadly acceptable for
14674 			 * main() function due to backward compatibility.
14675 			 * Like socket filter program may be written as:
14676 			 * int bpf_prog(struct pt_regs *ctx)
14677 			 * and never dereference that ctx in the program.
14678 			 * 'struct pt_regs' is a type mismatch for socket
14679 			 * filter that should be using 'struct __sk_buff'.
14680 			 */
14681 			goto out;
14682 	}
14683 
14684 	ret = do_check(env);
14685 out:
14686 	/* check for NULL is necessary, since cur_state can be freed inside
14687 	 * do_check() under memory pressure.
14688 	 */
14689 	if (env->cur_state) {
14690 		free_verifier_state(env->cur_state, true);
14691 		env->cur_state = NULL;
14692 	}
14693 	while (!pop_stack(env, NULL, NULL, false));
14694 	if (!ret && pop_log)
14695 		bpf_vlog_reset(&env->log, 0);
14696 	free_states(env);
14697 	return ret;
14698 }
14699 
14700 /* Verify all global functions in a BPF program one by one based on their BTF.
14701  * All global functions must pass verification. Otherwise the whole program is rejected.
14702  * Consider:
14703  * int bar(int);
14704  * int foo(int f)
14705  * {
14706  *    return bar(f);
14707  * }
14708  * int bar(int b)
14709  * {
14710  *    ...
14711  * }
14712  * foo() will be verified first for R1=any_scalar_value. During verification it
14713  * will be assumed that bar() already verified successfully and call to bar()
14714  * from foo() will be checked for type match only. Later bar() will be verified
14715  * independently to check that it's safe for R1=any_scalar_value.
14716  */
do_check_subprogs(struct bpf_verifier_env * env)14717 static int do_check_subprogs(struct bpf_verifier_env *env)
14718 {
14719 	struct bpf_prog_aux *aux = env->prog->aux;
14720 	int i, ret;
14721 
14722 	if (!aux->func_info)
14723 		return 0;
14724 
14725 	for (i = 1; i < env->subprog_cnt; i++) {
14726 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14727 			continue;
14728 		env->insn_idx = env->subprog_info[i].start;
14729 		WARN_ON_ONCE(env->insn_idx == 0);
14730 		ret = do_check_common(env, i);
14731 		if (ret) {
14732 			return ret;
14733 		} else if (env->log.level & BPF_LOG_LEVEL) {
14734 			verbose(env,
14735 				"Func#%d is safe for any args that match its prototype\n",
14736 				i);
14737 		}
14738 	}
14739 	return 0;
14740 }
14741 
do_check_main(struct bpf_verifier_env * env)14742 static int do_check_main(struct bpf_verifier_env *env)
14743 {
14744 	int ret;
14745 
14746 	env->insn_idx = 0;
14747 	ret = do_check_common(env, 0);
14748 	if (!ret)
14749 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14750 	return ret;
14751 }
14752 
14753 
print_verification_stats(struct bpf_verifier_env * env)14754 static void print_verification_stats(struct bpf_verifier_env *env)
14755 {
14756 	int i;
14757 
14758 	if (env->log.level & BPF_LOG_STATS) {
14759 		verbose(env, "verification time %lld usec\n",
14760 			div_u64(env->verification_time, 1000));
14761 		verbose(env, "stack depth ");
14762 		for (i = 0; i < env->subprog_cnt; i++) {
14763 			u32 depth = env->subprog_info[i].stack_depth;
14764 
14765 			verbose(env, "%d", depth);
14766 			if (i + 1 < env->subprog_cnt)
14767 				verbose(env, "+");
14768 		}
14769 		verbose(env, "\n");
14770 	}
14771 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14772 		"total_states %d peak_states %d mark_read %d\n",
14773 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14774 		env->max_states_per_insn, env->total_states,
14775 		env->peak_states, env->longest_mark_read_walk);
14776 }
14777 
check_struct_ops_btf_id(struct bpf_verifier_env * env)14778 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14779 {
14780 	const struct btf_type *t, *func_proto;
14781 	const struct bpf_struct_ops *st_ops;
14782 	const struct btf_member *member;
14783 	struct bpf_prog *prog = env->prog;
14784 	u32 btf_id, member_idx;
14785 	const char *mname;
14786 
14787 	if (!prog->gpl_compatible) {
14788 		verbose(env, "struct ops programs must have a GPL compatible license\n");
14789 		return -EINVAL;
14790 	}
14791 
14792 	btf_id = prog->aux->attach_btf_id;
14793 	st_ops = bpf_struct_ops_find(btf_id);
14794 	if (!st_ops) {
14795 		verbose(env, "attach_btf_id %u is not a supported struct\n",
14796 			btf_id);
14797 		return -ENOTSUPP;
14798 	}
14799 
14800 	t = st_ops->type;
14801 	member_idx = prog->expected_attach_type;
14802 	if (member_idx >= btf_type_vlen(t)) {
14803 		verbose(env, "attach to invalid member idx %u of struct %s\n",
14804 			member_idx, st_ops->name);
14805 		return -EINVAL;
14806 	}
14807 
14808 	member = &btf_type_member(t)[member_idx];
14809 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14810 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14811 					       NULL);
14812 	if (!func_proto) {
14813 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14814 			mname, member_idx, st_ops->name);
14815 		return -EINVAL;
14816 	}
14817 
14818 	if (st_ops->check_member) {
14819 		int err = st_ops->check_member(t, member);
14820 
14821 		if (err) {
14822 			verbose(env, "attach to unsupported member %s of struct %s\n",
14823 				mname, st_ops->name);
14824 			return err;
14825 		}
14826 	}
14827 
14828 	prog->aux->attach_func_proto = func_proto;
14829 	prog->aux->attach_func_name = mname;
14830 	env->ops = st_ops->verifier_ops;
14831 
14832 	return 0;
14833 }
14834 #define SECURITY_PREFIX "security_"
14835 
check_attach_modify_return(unsigned long addr,const char * func_name)14836 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14837 {
14838 	if (within_error_injection_list(addr) ||
14839 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14840 		return 0;
14841 
14842 	return -EINVAL;
14843 }
14844 
14845 /* list of non-sleepable functions that are otherwise on
14846  * ALLOW_ERROR_INJECTION list
14847  */
14848 BTF_SET_START(btf_non_sleepable_error_inject)
14849 /* Three functions below can be called from sleepable and non-sleepable context.
14850  * Assume non-sleepable from bpf safety point of view.
14851  */
BTF_ID(func,__filemap_add_folio)14852 BTF_ID(func, __filemap_add_folio)
14853 BTF_ID(func, should_fail_alloc_page)
14854 BTF_ID(func, should_failslab)
14855 BTF_SET_END(btf_non_sleepable_error_inject)
14856 
14857 static int check_non_sleepable_error_inject(u32 btf_id)
14858 {
14859 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14860 }
14861 
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)14862 int bpf_check_attach_target(struct bpf_verifier_log *log,
14863 			    const struct bpf_prog *prog,
14864 			    const struct bpf_prog *tgt_prog,
14865 			    u32 btf_id,
14866 			    struct bpf_attach_target_info *tgt_info)
14867 {
14868 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14869 	const char prefix[] = "btf_trace_";
14870 	int ret = 0, subprog = -1, i;
14871 	const struct btf_type *t;
14872 	bool conservative = true;
14873 	const char *tname;
14874 	struct btf *btf;
14875 	long addr = 0;
14876 
14877 	if (!btf_id) {
14878 		bpf_log(log, "Tracing programs must provide btf_id\n");
14879 		return -EINVAL;
14880 	}
14881 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14882 	if (!btf) {
14883 		bpf_log(log,
14884 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14885 		return -EINVAL;
14886 	}
14887 	t = btf_type_by_id(btf, btf_id);
14888 	if (!t) {
14889 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14890 		return -EINVAL;
14891 	}
14892 	tname = btf_name_by_offset(btf, t->name_off);
14893 	if (!tname) {
14894 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14895 		return -EINVAL;
14896 	}
14897 	if (tgt_prog) {
14898 		struct bpf_prog_aux *aux = tgt_prog->aux;
14899 
14900 		for (i = 0; i < aux->func_info_cnt; i++)
14901 			if (aux->func_info[i].type_id == btf_id) {
14902 				subprog = i;
14903 				break;
14904 			}
14905 		if (subprog == -1) {
14906 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
14907 			return -EINVAL;
14908 		}
14909 		conservative = aux->func_info_aux[subprog].unreliable;
14910 		if (prog_extension) {
14911 			if (conservative) {
14912 				bpf_log(log,
14913 					"Cannot replace static functions\n");
14914 				return -EINVAL;
14915 			}
14916 			if (!prog->jit_requested) {
14917 				bpf_log(log,
14918 					"Extension programs should be JITed\n");
14919 				return -EINVAL;
14920 			}
14921 		}
14922 		if (!tgt_prog->jited) {
14923 			bpf_log(log, "Can attach to only JITed progs\n");
14924 			return -EINVAL;
14925 		}
14926 		if (tgt_prog->type == prog->type) {
14927 			/* Cannot fentry/fexit another fentry/fexit program.
14928 			 * Cannot attach program extension to another extension.
14929 			 * It's ok to attach fentry/fexit to extension program.
14930 			 */
14931 			bpf_log(log, "Cannot recursively attach\n");
14932 			return -EINVAL;
14933 		}
14934 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14935 		    prog_extension &&
14936 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14937 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14938 			/* Program extensions can extend all program types
14939 			 * except fentry/fexit. The reason is the following.
14940 			 * The fentry/fexit programs are used for performance
14941 			 * analysis, stats and can be attached to any program
14942 			 * type except themselves. When extension program is
14943 			 * replacing XDP function it is necessary to allow
14944 			 * performance analysis of all functions. Both original
14945 			 * XDP program and its program extension. Hence
14946 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14947 			 * allowed. If extending of fentry/fexit was allowed it
14948 			 * would be possible to create long call chain
14949 			 * fentry->extension->fentry->extension beyond
14950 			 * reasonable stack size. Hence extending fentry is not
14951 			 * allowed.
14952 			 */
14953 			bpf_log(log, "Cannot extend fentry/fexit\n");
14954 			return -EINVAL;
14955 		}
14956 	} else {
14957 		if (prog_extension) {
14958 			bpf_log(log, "Cannot replace kernel functions\n");
14959 			return -EINVAL;
14960 		}
14961 	}
14962 
14963 	switch (prog->expected_attach_type) {
14964 	case BPF_TRACE_RAW_TP:
14965 		if (tgt_prog) {
14966 			bpf_log(log,
14967 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14968 			return -EINVAL;
14969 		}
14970 		if (!btf_type_is_typedef(t)) {
14971 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
14972 				btf_id);
14973 			return -EINVAL;
14974 		}
14975 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14976 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14977 				btf_id, tname);
14978 			return -EINVAL;
14979 		}
14980 		tname += sizeof(prefix) - 1;
14981 		t = btf_type_by_id(btf, t->type);
14982 		if (!btf_type_is_ptr(t))
14983 			/* should never happen in valid vmlinux build */
14984 			return -EINVAL;
14985 		t = btf_type_by_id(btf, t->type);
14986 		if (!btf_type_is_func_proto(t))
14987 			/* should never happen in valid vmlinux build */
14988 			return -EINVAL;
14989 
14990 		break;
14991 	case BPF_TRACE_ITER:
14992 		if (!btf_type_is_func(t)) {
14993 			bpf_log(log, "attach_btf_id %u is not a function\n",
14994 				btf_id);
14995 			return -EINVAL;
14996 		}
14997 		t = btf_type_by_id(btf, t->type);
14998 		if (!btf_type_is_func_proto(t))
14999 			return -EINVAL;
15000 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15001 		if (ret)
15002 			return ret;
15003 		break;
15004 	default:
15005 		if (!prog_extension)
15006 			return -EINVAL;
15007 		fallthrough;
15008 	case BPF_MODIFY_RETURN:
15009 	case BPF_LSM_MAC:
15010 	case BPF_LSM_CGROUP:
15011 	case BPF_TRACE_FENTRY:
15012 	case BPF_TRACE_FEXIT:
15013 		if (!btf_type_is_func(t)) {
15014 			bpf_log(log, "attach_btf_id %u is not a function\n",
15015 				btf_id);
15016 			return -EINVAL;
15017 		}
15018 		if (prog_extension &&
15019 		    btf_check_type_match(log, prog, btf, t))
15020 			return -EINVAL;
15021 		t = btf_type_by_id(btf, t->type);
15022 		if (!btf_type_is_func_proto(t))
15023 			return -EINVAL;
15024 
15025 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15026 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15027 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15028 			return -EINVAL;
15029 
15030 		if (tgt_prog && conservative)
15031 			t = NULL;
15032 
15033 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15034 		if (ret < 0)
15035 			return ret;
15036 
15037 		if (tgt_prog) {
15038 			if (subprog == 0)
15039 				addr = (long) tgt_prog->bpf_func;
15040 			else
15041 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15042 		} else {
15043 			addr = kallsyms_lookup_name(tname);
15044 			if (!addr) {
15045 				bpf_log(log,
15046 					"The address of function %s cannot be found\n",
15047 					tname);
15048 				return -ENOENT;
15049 			}
15050 		}
15051 
15052 		if (prog->aux->sleepable) {
15053 			ret = -EINVAL;
15054 			switch (prog->type) {
15055 			case BPF_PROG_TYPE_TRACING:
15056 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
15057 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15058 				 */
15059 				if (!check_non_sleepable_error_inject(btf_id) &&
15060 				    within_error_injection_list(addr))
15061 					ret = 0;
15062 				break;
15063 			case BPF_PROG_TYPE_LSM:
15064 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
15065 				 * Only some of them are sleepable.
15066 				 */
15067 				if (bpf_lsm_is_sleepable_hook(btf_id))
15068 					ret = 0;
15069 				break;
15070 			default:
15071 				break;
15072 			}
15073 			if (ret) {
15074 				bpf_log(log, "%s is not sleepable\n", tname);
15075 				return ret;
15076 			}
15077 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15078 			if (tgt_prog) {
15079 				bpf_log(log, "can't modify return codes of BPF programs\n");
15080 				return -EINVAL;
15081 			}
15082 			ret = check_attach_modify_return(addr, tname);
15083 			if (ret) {
15084 				bpf_log(log, "%s() is not modifiable\n", tname);
15085 				return ret;
15086 			}
15087 		}
15088 
15089 		break;
15090 	}
15091 	tgt_info->tgt_addr = addr;
15092 	tgt_info->tgt_name = tname;
15093 	tgt_info->tgt_type = t;
15094 	return 0;
15095 }
15096 
BTF_SET_START(btf_id_deny)15097 BTF_SET_START(btf_id_deny)
15098 BTF_ID_UNUSED
15099 #ifdef CONFIG_SMP
15100 BTF_ID(func, migrate_disable)
15101 BTF_ID(func, migrate_enable)
15102 #endif
15103 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15104 BTF_ID(func, rcu_read_unlock_strict)
15105 #endif
15106 BTF_SET_END(btf_id_deny)
15107 
15108 static int check_attach_btf_id(struct bpf_verifier_env *env)
15109 {
15110 	struct bpf_prog *prog = env->prog;
15111 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15112 	struct bpf_attach_target_info tgt_info = {};
15113 	u32 btf_id = prog->aux->attach_btf_id;
15114 	struct bpf_trampoline *tr;
15115 	int ret;
15116 	u64 key;
15117 
15118 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15119 		if (prog->aux->sleepable)
15120 			/* attach_btf_id checked to be zero already */
15121 			return 0;
15122 		verbose(env, "Syscall programs can only be sleepable\n");
15123 		return -EINVAL;
15124 	}
15125 
15126 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15127 	    prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15128 		verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15129 		return -EINVAL;
15130 	}
15131 
15132 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15133 		return check_struct_ops_btf_id(env);
15134 
15135 	if (prog->type != BPF_PROG_TYPE_TRACING &&
15136 	    prog->type != BPF_PROG_TYPE_LSM &&
15137 	    prog->type != BPF_PROG_TYPE_EXT)
15138 		return 0;
15139 
15140 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15141 	if (ret)
15142 		return ret;
15143 
15144 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15145 		/* to make freplace equivalent to their targets, they need to
15146 		 * inherit env->ops and expected_attach_type for the rest of the
15147 		 * verification
15148 		 */
15149 		env->ops = bpf_verifier_ops[tgt_prog->type];
15150 		prog->expected_attach_type = tgt_prog->expected_attach_type;
15151 	}
15152 
15153 	/* store info about the attachment target that will be used later */
15154 	prog->aux->attach_func_proto = tgt_info.tgt_type;
15155 	prog->aux->attach_func_name = tgt_info.tgt_name;
15156 
15157 	if (tgt_prog) {
15158 		prog->aux->saved_dst_prog_type = tgt_prog->type;
15159 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15160 	}
15161 
15162 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15163 		prog->aux->attach_btf_trace = true;
15164 		return 0;
15165 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15166 		if (!bpf_iter_prog_supported(prog))
15167 			return -EINVAL;
15168 		return 0;
15169 	}
15170 
15171 	if (prog->type == BPF_PROG_TYPE_LSM) {
15172 		ret = bpf_lsm_verify_prog(&env->log, prog);
15173 		if (ret < 0)
15174 			return ret;
15175 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
15176 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
15177 		return -EINVAL;
15178 	}
15179 
15180 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15181 	tr = bpf_trampoline_get(key, &tgt_info);
15182 	if (!tr)
15183 		return -ENOMEM;
15184 
15185 	prog->aux->dst_trampoline = tr;
15186 	return 0;
15187 }
15188 
bpf_get_btf_vmlinux(void)15189 struct btf *bpf_get_btf_vmlinux(void)
15190 {
15191 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15192 		mutex_lock(&bpf_verifier_lock);
15193 		if (!btf_vmlinux)
15194 			btf_vmlinux = btf_parse_vmlinux();
15195 		mutex_unlock(&bpf_verifier_lock);
15196 	}
15197 	return btf_vmlinux;
15198 }
15199 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr)15200 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15201 {
15202 	u64 start_time = ktime_get_ns();
15203 	struct bpf_verifier_env *env;
15204 	struct bpf_verifier_log *log;
15205 	int i, len, ret = -EINVAL;
15206 	bool is_priv;
15207 
15208 	/* no program is valid */
15209 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15210 		return -EINVAL;
15211 
15212 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
15213 	 * allocate/free it every time bpf_check() is called
15214 	 */
15215 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15216 	if (!env)
15217 		return -ENOMEM;
15218 	log = &env->log;
15219 
15220 	len = (*prog)->len;
15221 	env->insn_aux_data =
15222 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15223 	ret = -ENOMEM;
15224 	if (!env->insn_aux_data)
15225 		goto err_free_env;
15226 	for (i = 0; i < len; i++)
15227 		env->insn_aux_data[i].orig_idx = i;
15228 	env->prog = *prog;
15229 	env->ops = bpf_verifier_ops[env->prog->type];
15230 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15231 	is_priv = bpf_capable();
15232 
15233 	bpf_get_btf_vmlinux();
15234 
15235 	/* grab the mutex to protect few globals used by verifier */
15236 	if (!is_priv)
15237 		mutex_lock(&bpf_verifier_lock);
15238 
15239 	if (attr->log_level || attr->log_buf || attr->log_size) {
15240 		/* user requested verbose verifier output
15241 		 * and supplied buffer to store the verification trace
15242 		 */
15243 		log->level = attr->log_level;
15244 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15245 		log->len_total = attr->log_size;
15246 
15247 		/* log attributes have to be sane */
15248 		if (!bpf_verifier_log_attr_valid(log)) {
15249 			ret = -EINVAL;
15250 			goto err_unlock;
15251 		}
15252 	}
15253 
15254 	mark_verifier_state_clean(env);
15255 
15256 	if (IS_ERR(btf_vmlinux)) {
15257 		/* Either gcc or pahole or kernel are broken. */
15258 		verbose(env, "in-kernel BTF is malformed\n");
15259 		ret = PTR_ERR(btf_vmlinux);
15260 		goto skip_full_check;
15261 	}
15262 
15263 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15264 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15265 		env->strict_alignment = true;
15266 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15267 		env->strict_alignment = false;
15268 
15269 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15270 	env->allow_uninit_stack = bpf_allow_uninit_stack();
15271 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15272 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
15273 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
15274 	env->bpf_capable = bpf_capable();
15275 
15276 	if (is_priv)
15277 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15278 
15279 	env->explored_states = kvcalloc(state_htab_size(env),
15280 				       sizeof(struct bpf_verifier_state_list *),
15281 				       GFP_USER);
15282 	ret = -ENOMEM;
15283 	if (!env->explored_states)
15284 		goto skip_full_check;
15285 
15286 	ret = add_subprog_and_kfunc(env);
15287 	if (ret < 0)
15288 		goto skip_full_check;
15289 
15290 	ret = check_subprogs(env);
15291 	if (ret < 0)
15292 		goto skip_full_check;
15293 
15294 	ret = check_btf_info(env, attr, uattr);
15295 	if (ret < 0)
15296 		goto skip_full_check;
15297 
15298 	ret = check_attach_btf_id(env);
15299 	if (ret)
15300 		goto skip_full_check;
15301 
15302 	ret = resolve_pseudo_ldimm64(env);
15303 	if (ret < 0)
15304 		goto skip_full_check;
15305 
15306 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
15307 		ret = bpf_prog_offload_verifier_prep(env->prog);
15308 		if (ret)
15309 			goto skip_full_check;
15310 	}
15311 
15312 	ret = check_cfg(env);
15313 	if (ret < 0)
15314 		goto skip_full_check;
15315 
15316 	ret = do_check_subprogs(env);
15317 	ret = ret ?: do_check_main(env);
15318 
15319 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15320 		ret = bpf_prog_offload_finalize(env);
15321 
15322 skip_full_check:
15323 	kvfree(env->explored_states);
15324 
15325 	if (ret == 0)
15326 		ret = check_max_stack_depth(env);
15327 
15328 	/* instruction rewrites happen after this point */
15329 	if (ret == 0)
15330 		ret = optimize_bpf_loop(env);
15331 
15332 	if (is_priv) {
15333 		if (ret == 0)
15334 			opt_hard_wire_dead_code_branches(env);
15335 		if (ret == 0)
15336 			ret = opt_remove_dead_code(env);
15337 		if (ret == 0)
15338 			ret = opt_remove_nops(env);
15339 	} else {
15340 		if (ret == 0)
15341 			sanitize_dead_code(env);
15342 	}
15343 
15344 	if (ret == 0)
15345 		/* program is valid, convert *(u32*)(ctx + off) accesses */
15346 		ret = convert_ctx_accesses(env);
15347 
15348 	if (ret == 0)
15349 		ret = do_misc_fixups(env);
15350 
15351 	/* do 32-bit optimization after insn patching has done so those patched
15352 	 * insns could be handled correctly.
15353 	 */
15354 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15355 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15356 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15357 								     : false;
15358 	}
15359 
15360 	if (ret == 0)
15361 		ret = fixup_call_args(env);
15362 
15363 	env->verification_time = ktime_get_ns() - start_time;
15364 	print_verification_stats(env);
15365 	env->prog->aux->verified_insns = env->insn_processed;
15366 
15367 	if (log->level && bpf_verifier_log_full(log))
15368 		ret = -ENOSPC;
15369 	if (log->level && !log->ubuf) {
15370 		ret = -EFAULT;
15371 		goto err_release_maps;
15372 	}
15373 
15374 	if (ret)
15375 		goto err_release_maps;
15376 
15377 	if (env->used_map_cnt) {
15378 		/* if program passed verifier, update used_maps in bpf_prog_info */
15379 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15380 							  sizeof(env->used_maps[0]),
15381 							  GFP_KERNEL);
15382 
15383 		if (!env->prog->aux->used_maps) {
15384 			ret = -ENOMEM;
15385 			goto err_release_maps;
15386 		}
15387 
15388 		memcpy(env->prog->aux->used_maps, env->used_maps,
15389 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
15390 		env->prog->aux->used_map_cnt = env->used_map_cnt;
15391 	}
15392 	if (env->used_btf_cnt) {
15393 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
15394 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15395 							  sizeof(env->used_btfs[0]),
15396 							  GFP_KERNEL);
15397 		if (!env->prog->aux->used_btfs) {
15398 			ret = -ENOMEM;
15399 			goto err_release_maps;
15400 		}
15401 
15402 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
15403 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15404 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15405 	}
15406 	if (env->used_map_cnt || env->used_btf_cnt) {
15407 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
15408 		 * bpf_ld_imm64 instructions
15409 		 */
15410 		convert_pseudo_ld_imm64(env);
15411 	}
15412 
15413 	adjust_btf_func(env);
15414 
15415 err_release_maps:
15416 	if (!env->prog->aux->used_maps)
15417 		/* if we didn't copy map pointers into bpf_prog_info, release
15418 		 * them now. Otherwise free_used_maps() will release them.
15419 		 */
15420 		release_maps(env);
15421 	if (!env->prog->aux->used_btfs)
15422 		release_btfs(env);
15423 
15424 	/* extension progs temporarily inherit the attach_type of their targets
15425 	   for verification purposes, so set it back to zero before returning
15426 	 */
15427 	if (env->prog->type == BPF_PROG_TYPE_EXT)
15428 		env->prog->expected_attach_type = 0;
15429 
15430 	*prog = env->prog;
15431 err_unlock:
15432 	if (!is_priv)
15433 		mutex_unlock(&bpf_verifier_lock);
15434 	vfree(env->insn_aux_data);
15435 err_free_env:
15436 	kfree(env);
15437 	return ret;
15438 }
15439