• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25 
26 #include "disasm.h"
27 
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 	[_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38 
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all pathes through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns ether pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163 
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 	/* verifer state is 'st'
167 	 * before processing instruction 'insn_idx'
168 	 * and after processing instruction 'prev_insn_idx'
169 	 */
170 	struct bpf_verifier_state st;
171 	int insn_idx;
172 	int prev_insn_idx;
173 	struct bpf_verifier_stack_elem *next;
174 	/* length of verifier log at the time this state was pushed on stack */
175 	u32 log_pos;
176 };
177 
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
179 #define BPF_COMPLEXITY_LIMIT_STATES	64
180 
181 #define BPF_MAP_KEY_POISON	(1ULL << 63)
182 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
183 
184 #define BPF_MAP_PTR_UNPRIV	1UL
185 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
186 					  POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198 
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 			      const struct bpf_map *map, bool unpriv)
201 {
202 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 	unpriv |= bpf_map_ptr_unpriv(aux);
204 	aux->map_ptr_state = (unsigned long)map |
205 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222 
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225 	bool poisoned = bpf_map_key_poisoned(aux);
226 
227 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230 
231 struct bpf_call_arg_meta {
232 	struct bpf_map *map_ptr;
233 	bool raw_mode;
234 	bool pkt_access;
235 	int regno;
236 	int access_size;
237 	int mem_size;
238 	u64 msize_max_value;
239 	int ref_obj_id;
240 	int func_id;
241 	u32 btf_id;
242 	u32 ret_btf_id;
243 };
244 
245 struct btf *btf_vmlinux;
246 
247 static DEFINE_MUTEX(bpf_verifier_lock);
248 
249 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)250 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
251 {
252 	const struct bpf_line_info *linfo;
253 	const struct bpf_prog *prog;
254 	u32 i, nr_linfo;
255 
256 	prog = env->prog;
257 	nr_linfo = prog->aux->nr_linfo;
258 
259 	if (!nr_linfo || insn_off >= prog->len)
260 		return NULL;
261 
262 	linfo = prog->aux->linfo;
263 	for (i = 1; i < nr_linfo; i++)
264 		if (insn_off < linfo[i].insn_off)
265 			break;
266 
267 	return &linfo[i - 1];
268 }
269 
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)270 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
271 		       va_list args)
272 {
273 	unsigned int n;
274 
275 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
276 
277 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278 		  "verifier log line truncated - local buffer too short\n");
279 
280 	n = min(log->len_total - log->len_used - 1, n);
281 	log->kbuf[n] = '\0';
282 
283 	if (log->level == BPF_LOG_KERNEL) {
284 		pr_err("BPF:%s\n", log->kbuf);
285 		return;
286 	}
287 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
288 		log->len_used += n;
289 	else
290 		log->ubuf = NULL;
291 }
292 
bpf_vlog_reset(struct bpf_verifier_log * log,u32 new_pos)293 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
294 {
295 	char zero = 0;
296 
297 	if (!bpf_verifier_log_needed(log))
298 		return;
299 
300 	log->len_used = new_pos;
301 	if (put_user(zero, log->ubuf + new_pos))
302 		log->ubuf = NULL;
303 }
304 
305 /* log_level controls verbosity level of eBPF verifier.
306  * bpf_verifier_log_write() is used to dump the verification trace to the log,
307  * so the user can figure out what's wrong with the program
308  */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)309 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310 					   const char *fmt, ...)
311 {
312 	va_list args;
313 
314 	if (!bpf_verifier_log_needed(&env->log))
315 		return;
316 
317 	va_start(args, fmt);
318 	bpf_verifier_vlog(&env->log, fmt, args);
319 	va_end(args);
320 }
321 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
322 
verbose(void * private_data,const char * fmt,...)323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
324 {
325 	struct bpf_verifier_env *env = private_data;
326 	va_list args;
327 
328 	if (!bpf_verifier_log_needed(&env->log))
329 		return;
330 
331 	va_start(args, fmt);
332 	bpf_verifier_vlog(&env->log, fmt, args);
333 	va_end(args);
334 }
335 
bpf_log(struct bpf_verifier_log * log,const char * fmt,...)336 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337 			    const char *fmt, ...)
338 {
339 	va_list args;
340 
341 	if (!bpf_verifier_log_needed(log))
342 		return;
343 
344 	va_start(args, fmt);
345 	bpf_verifier_vlog(log, fmt, args);
346 	va_end(args);
347 }
348 
ltrim(const char * s)349 static const char *ltrim(const char *s)
350 {
351 	while (isspace(*s))
352 		s++;
353 
354 	return s;
355 }
356 
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)357 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
358 					 u32 insn_off,
359 					 const char *prefix_fmt, ...)
360 {
361 	const struct bpf_line_info *linfo;
362 
363 	if (!bpf_verifier_log_needed(&env->log))
364 		return;
365 
366 	linfo = find_linfo(env, insn_off);
367 	if (!linfo || linfo == env->prev_linfo)
368 		return;
369 
370 	if (prefix_fmt) {
371 		va_list args;
372 
373 		va_start(args, prefix_fmt);
374 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
375 		va_end(args);
376 	}
377 
378 	verbose(env, "%s\n",
379 		ltrim(btf_name_by_offset(env->prog->aux->btf,
380 					 linfo->line_off)));
381 
382 	env->prev_linfo = linfo;
383 }
384 
type_is_pkt_pointer(enum bpf_reg_type type)385 static bool type_is_pkt_pointer(enum bpf_reg_type type)
386 {
387 	return type == PTR_TO_PACKET ||
388 	       type == PTR_TO_PACKET_META;
389 }
390 
type_is_sk_pointer(enum bpf_reg_type type)391 static bool type_is_sk_pointer(enum bpf_reg_type type)
392 {
393 	return type == PTR_TO_SOCKET ||
394 		type == PTR_TO_SOCK_COMMON ||
395 		type == PTR_TO_TCP_SOCK ||
396 		type == PTR_TO_XDP_SOCK;
397 }
398 
reg_type_not_null(enum bpf_reg_type type)399 static bool reg_type_not_null(enum bpf_reg_type type)
400 {
401 	return type == PTR_TO_SOCKET ||
402 		type == PTR_TO_TCP_SOCK ||
403 		type == PTR_TO_MAP_VALUE ||
404 		type == PTR_TO_SOCK_COMMON;
405 }
406 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)407 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
408 {
409 	return reg->type == PTR_TO_MAP_VALUE &&
410 		map_value_has_spin_lock(reg->map_ptr);
411 }
412 
reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)413 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
414 {
415 	return base_type(type) == PTR_TO_SOCKET ||
416 	       base_type(type) == PTR_TO_TCP_SOCK ||
417 	       base_type(type) == PTR_TO_MEM;
418 }
419 
type_is_rdonly_mem(u32 type)420 static bool type_is_rdonly_mem(u32 type)
421 {
422 	return type & MEM_RDONLY;
423 }
424 
arg_type_may_be_refcounted(enum bpf_arg_type type)425 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
426 {
427 	return type == ARG_PTR_TO_SOCK_COMMON;
428 }
429 
type_may_be_null(u32 type)430 static bool type_may_be_null(u32 type)
431 {
432 	return type & PTR_MAYBE_NULL;
433 }
434 
435 /* Determine whether the function releases some resources allocated by another
436  * function call. The first reference type argument will be assumed to be
437  * released by release_reference().
438  */
is_release_function(enum bpf_func_id func_id)439 static bool is_release_function(enum bpf_func_id func_id)
440 {
441 	return func_id == BPF_FUNC_sk_release ||
442 	       func_id == BPF_FUNC_ringbuf_submit ||
443 	       func_id == BPF_FUNC_ringbuf_discard;
444 }
445 
may_be_acquire_function(enum bpf_func_id func_id)446 static bool may_be_acquire_function(enum bpf_func_id func_id)
447 {
448 	return func_id == BPF_FUNC_sk_lookup_tcp ||
449 		func_id == BPF_FUNC_sk_lookup_udp ||
450 		func_id == BPF_FUNC_skc_lookup_tcp ||
451 		func_id == BPF_FUNC_map_lookup_elem ||
452 	        func_id == BPF_FUNC_ringbuf_reserve;
453 }
454 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)455 static bool is_acquire_function(enum bpf_func_id func_id,
456 				const struct bpf_map *map)
457 {
458 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
459 
460 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
461 	    func_id == BPF_FUNC_sk_lookup_udp ||
462 	    func_id == BPF_FUNC_skc_lookup_tcp ||
463 	    func_id == BPF_FUNC_ringbuf_reserve)
464 		return true;
465 
466 	if (func_id == BPF_FUNC_map_lookup_elem &&
467 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
468 	     map_type == BPF_MAP_TYPE_SOCKHASH))
469 		return true;
470 
471 	return false;
472 }
473 
is_ptr_cast_function(enum bpf_func_id func_id)474 static bool is_ptr_cast_function(enum bpf_func_id func_id)
475 {
476 	return func_id == BPF_FUNC_tcp_sock ||
477 		func_id == BPF_FUNC_sk_fullsock ||
478 		func_id == BPF_FUNC_skc_to_tcp_sock ||
479 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
480 		func_id == BPF_FUNC_skc_to_udp6_sock ||
481 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
482 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
483 }
484 
485 /* string representation of 'enum bpf_reg_type'
486  *
487  * Note that reg_type_str() can not appear more than once in a single verbose()
488  * statement.
489  */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)490 static const char *reg_type_str(struct bpf_verifier_env *env,
491 		enum bpf_reg_type type)
492 {
493 	char postfix[16] = {0}, prefix[16] = {0};
494 	static const char * const str[] = {
495 		[NOT_INIT]		= "?",
496 		[SCALAR_VALUE]		= "inv",
497 		[PTR_TO_CTX]		= "ctx",
498 		[CONST_PTR_TO_MAP]	= "map_ptr",
499 		[PTR_TO_MAP_VALUE]	= "map_value",
500 		[PTR_TO_STACK]		= "fp",
501 		[PTR_TO_PACKET]		= "pkt",
502 		[PTR_TO_PACKET_META]	= "pkt_meta",
503 		[PTR_TO_PACKET_END]	= "pkt_end",
504 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
505 		[PTR_TO_SOCKET]		= "sock",
506 		[PTR_TO_SOCK_COMMON]	= "sock_common",
507 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
508 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
509 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
510 		[PTR_TO_BTF_ID]		= "ptr_",
511 		[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
512 		[PTR_TO_MEM]		= "mem",
513 		[PTR_TO_BUF]		= "buf",
514 	};
515 
516 	if (type & PTR_MAYBE_NULL) {
517 		if (base_type(type) == PTR_TO_BTF_ID ||
518 		    base_type(type) == PTR_TO_PERCPU_BTF_ID)
519 			strncpy(postfix, "or_null_", 16);
520 		else
521 			strncpy(postfix, "_or_null", 16);
522 	}
523 
524 	if (type & MEM_RDONLY)
525 		strncpy(prefix, "rdonly_", 16);
526 	if (type & MEM_ALLOC)
527 		strncpy(prefix, "alloc_", 16);
528 
529 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
530 		 prefix, str[base_type(type)], postfix);
531 	return env->type_str_buf;
532 }
533 
534 static char slot_type_char[] = {
535 	[STACK_INVALID]	= '?',
536 	[STACK_SPILL]	= 'r',
537 	[STACK_MISC]	= 'm',
538 	[STACK_ZERO]	= '0',
539 };
540 
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)541 static void print_liveness(struct bpf_verifier_env *env,
542 			   enum bpf_reg_liveness live)
543 {
544 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
545 	    verbose(env, "_");
546 	if (live & REG_LIVE_READ)
547 		verbose(env, "r");
548 	if (live & REG_LIVE_WRITTEN)
549 		verbose(env, "w");
550 	if (live & REG_LIVE_DONE)
551 		verbose(env, "D");
552 }
553 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)554 static struct bpf_func_state *func(struct bpf_verifier_env *env,
555 				   const struct bpf_reg_state *reg)
556 {
557 	struct bpf_verifier_state *cur = env->cur_state;
558 
559 	return cur->frame[reg->frameno];
560 }
561 
kernel_type_name(u32 id)562 const char *kernel_type_name(u32 id)
563 {
564 	return btf_name_by_offset(btf_vmlinux,
565 				  btf_type_by_id(btf_vmlinux, id)->name_off);
566 }
567 
568 /* The reg state of a pointer or a bounded scalar was saved when
569  * it was spilled to the stack.
570  */
is_spilled_reg(const struct bpf_stack_state * stack)571 static bool is_spilled_reg(const struct bpf_stack_state *stack)
572 {
573 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
574 }
575 
scrub_spilled_slot(u8 * stype)576 static void scrub_spilled_slot(u8 *stype)
577 {
578 	if (*stype != STACK_INVALID)
579 		*stype = STACK_MISC;
580 }
581 
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)582 static void print_verifier_state(struct bpf_verifier_env *env,
583 				 const struct bpf_func_state *state)
584 {
585 	const struct bpf_reg_state *reg;
586 	enum bpf_reg_type t;
587 	int i;
588 
589 	if (state->frameno)
590 		verbose(env, " frame%d:", state->frameno);
591 	for (i = 0; i < MAX_BPF_REG; i++) {
592 		reg = &state->regs[i];
593 		t = reg->type;
594 		if (t == NOT_INIT)
595 			continue;
596 		verbose(env, " R%d", i);
597 		print_liveness(env, reg->live);
598 		verbose(env, "=%s", reg_type_str(env, t));
599 		if (t == SCALAR_VALUE && reg->precise)
600 			verbose(env, "P");
601 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
602 		    tnum_is_const(reg->var_off)) {
603 			/* reg->off should be 0 for SCALAR_VALUE */
604 			verbose(env, "%lld", reg->var_off.value + reg->off);
605 		} else {
606 			if (base_type(t) == PTR_TO_BTF_ID ||
607 			    base_type(t) == PTR_TO_PERCPU_BTF_ID)
608 				verbose(env, "%s", kernel_type_name(reg->btf_id));
609 			verbose(env, "(id=%d", reg->id);
610 			if (reg_type_may_be_refcounted_or_null(t))
611 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
612 			if (t != SCALAR_VALUE)
613 				verbose(env, ",off=%d", reg->off);
614 			if (type_is_pkt_pointer(t))
615 				verbose(env, ",r=%d", reg->range);
616 			else if (base_type(t) == CONST_PTR_TO_MAP ||
617 				 base_type(t) == PTR_TO_MAP_VALUE)
618 				verbose(env, ",ks=%d,vs=%d",
619 					reg->map_ptr->key_size,
620 					reg->map_ptr->value_size);
621 			if (tnum_is_const(reg->var_off)) {
622 				/* Typically an immediate SCALAR_VALUE, but
623 				 * could be a pointer whose offset is too big
624 				 * for reg->off
625 				 */
626 				verbose(env, ",imm=%llx", reg->var_off.value);
627 			} else {
628 				if (reg->smin_value != reg->umin_value &&
629 				    reg->smin_value != S64_MIN)
630 					verbose(env, ",smin_value=%lld",
631 						(long long)reg->smin_value);
632 				if (reg->smax_value != reg->umax_value &&
633 				    reg->smax_value != S64_MAX)
634 					verbose(env, ",smax_value=%lld",
635 						(long long)reg->smax_value);
636 				if (reg->umin_value != 0)
637 					verbose(env, ",umin_value=%llu",
638 						(unsigned long long)reg->umin_value);
639 				if (reg->umax_value != U64_MAX)
640 					verbose(env, ",umax_value=%llu",
641 						(unsigned long long)reg->umax_value);
642 				if (!tnum_is_unknown(reg->var_off)) {
643 					char tn_buf[48];
644 
645 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
646 					verbose(env, ",var_off=%s", tn_buf);
647 				}
648 				if (reg->s32_min_value != reg->smin_value &&
649 				    reg->s32_min_value != S32_MIN)
650 					verbose(env, ",s32_min_value=%d",
651 						(int)(reg->s32_min_value));
652 				if (reg->s32_max_value != reg->smax_value &&
653 				    reg->s32_max_value != S32_MAX)
654 					verbose(env, ",s32_max_value=%d",
655 						(int)(reg->s32_max_value));
656 				if (reg->u32_min_value != reg->umin_value &&
657 				    reg->u32_min_value != U32_MIN)
658 					verbose(env, ",u32_min_value=%d",
659 						(int)(reg->u32_min_value));
660 				if (reg->u32_max_value != reg->umax_value &&
661 				    reg->u32_max_value != U32_MAX)
662 					verbose(env, ",u32_max_value=%d",
663 						(int)(reg->u32_max_value));
664 			}
665 			verbose(env, ")");
666 		}
667 	}
668 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
669 		char types_buf[BPF_REG_SIZE + 1];
670 		bool valid = false;
671 		int j;
672 
673 		for (j = 0; j < BPF_REG_SIZE; j++) {
674 			if (state->stack[i].slot_type[j] != STACK_INVALID)
675 				valid = true;
676 			types_buf[j] = slot_type_char[
677 					state->stack[i].slot_type[j]];
678 		}
679 		types_buf[BPF_REG_SIZE] = 0;
680 		if (!valid)
681 			continue;
682 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
683 		print_liveness(env, state->stack[i].spilled_ptr.live);
684 		if (is_spilled_reg(&state->stack[i])) {
685 			reg = &state->stack[i].spilled_ptr;
686 			t = reg->type;
687 			verbose(env, "=%s", reg_type_str(env, t));
688 			if (t == SCALAR_VALUE && reg->precise)
689 				verbose(env, "P");
690 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
691 				verbose(env, "%lld", reg->var_off.value + reg->off);
692 		} else {
693 			verbose(env, "=%s", types_buf);
694 		}
695 	}
696 	if (state->acquired_refs && state->refs[0].id) {
697 		verbose(env, " refs=%d", state->refs[0].id);
698 		for (i = 1; i < state->acquired_refs; i++)
699 			if (state->refs[i].id)
700 				verbose(env, ",%d", state->refs[i].id);
701 	}
702 	verbose(env, "\n");
703 }
704 
705 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
706 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
707 			       const struct bpf_func_state *src)	\
708 {									\
709 	if (!src->FIELD)						\
710 		return 0;						\
711 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
712 		/* internal bug, make state invalid to reject the program */ \
713 		memset(dst, 0, sizeof(*dst));				\
714 		return -EFAULT;						\
715 	}								\
716 	memcpy(dst->FIELD, src->FIELD,					\
717 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
718 	return 0;							\
719 }
720 /* copy_reference_state() */
721 COPY_STATE_FN(reference, acquired_refs, refs, 1)
722 /* copy_stack_state() */
COPY_STATE_FN(stack,allocated_stack,stack,BPF_REG_SIZE)723 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
724 #undef COPY_STATE_FN
725 
726 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
727 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
728 				  bool copy_old)			\
729 {									\
730 	u32 old_size = state->COUNT;					\
731 	struct bpf_##NAME##_state *new_##FIELD;				\
732 	int slot = size / SIZE;						\
733 									\
734 	if (size <= old_size || !size) {				\
735 		if (copy_old)						\
736 			return 0;					\
737 		state->COUNT = slot * SIZE;				\
738 		if (!size && old_size) {				\
739 			kfree(state->FIELD);				\
740 			state->FIELD = NULL;				\
741 		}							\
742 		return 0;						\
743 	}								\
744 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
745 				    GFP_KERNEL);			\
746 	if (!new_##FIELD)						\
747 		return -ENOMEM;						\
748 	if (copy_old) {							\
749 		if (state->FIELD)					\
750 			memcpy(new_##FIELD, state->FIELD,		\
751 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
752 		memset(new_##FIELD + old_size / SIZE, 0,		\
753 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
754 	}								\
755 	state->COUNT = slot * SIZE;					\
756 	kfree(state->FIELD);						\
757 	state->FIELD = new_##FIELD;					\
758 	return 0;							\
759 }
760 /* realloc_reference_state() */
761 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
762 /* realloc_stack_state() */
763 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
764 #undef REALLOC_STATE_FN
765 
766 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
767  * make it consume minimal amount of memory. check_stack_write() access from
768  * the program calls into realloc_func_state() to grow the stack size.
769  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
770  * which realloc_stack_state() copies over. It points to previous
771  * bpf_verifier_state which is never reallocated.
772  */
773 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
774 			      int refs_size, bool copy_old)
775 {
776 	int err = realloc_reference_state(state, refs_size, copy_old);
777 	if (err)
778 		return err;
779 	return realloc_stack_state(state, stack_size, copy_old);
780 }
781 
782 /* Acquire a pointer id from the env and update the state->refs to include
783  * this new pointer reference.
784  * On success, returns a valid pointer id to associate with the register
785  * On failure, returns a negative errno.
786  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)787 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
788 {
789 	struct bpf_func_state *state = cur_func(env);
790 	int new_ofs = state->acquired_refs;
791 	int id, err;
792 
793 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
794 	if (err)
795 		return err;
796 	id = ++env->id_gen;
797 	state->refs[new_ofs].id = id;
798 	state->refs[new_ofs].insn_idx = insn_idx;
799 
800 	return id;
801 }
802 
803 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)804 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
805 {
806 	int i, last_idx;
807 
808 	last_idx = state->acquired_refs - 1;
809 	for (i = 0; i < state->acquired_refs; i++) {
810 		if (state->refs[i].id == ptr_id) {
811 			if (last_idx && i != last_idx)
812 				memcpy(&state->refs[i], &state->refs[last_idx],
813 				       sizeof(*state->refs));
814 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
815 			state->acquired_refs--;
816 			return 0;
817 		}
818 	}
819 	return -EINVAL;
820 }
821 
transfer_reference_state(struct bpf_func_state * dst,struct bpf_func_state * src)822 static int transfer_reference_state(struct bpf_func_state *dst,
823 				    struct bpf_func_state *src)
824 {
825 	int err = realloc_reference_state(dst, src->acquired_refs, false);
826 	if (err)
827 		return err;
828 	err = copy_reference_state(dst, src);
829 	if (err)
830 		return err;
831 	return 0;
832 }
833 
free_func_state(struct bpf_func_state * state)834 static void free_func_state(struct bpf_func_state *state)
835 {
836 	if (!state)
837 		return;
838 	kfree(state->refs);
839 	kfree(state->stack);
840 	kfree(state);
841 }
842 
clear_jmp_history(struct bpf_verifier_state * state)843 static void clear_jmp_history(struct bpf_verifier_state *state)
844 {
845 	kfree(state->jmp_history);
846 	state->jmp_history = NULL;
847 	state->jmp_history_cnt = 0;
848 }
849 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)850 static void free_verifier_state(struct bpf_verifier_state *state,
851 				bool free_self)
852 {
853 	int i;
854 
855 	for (i = 0; i <= state->curframe; i++) {
856 		free_func_state(state->frame[i]);
857 		state->frame[i] = NULL;
858 	}
859 	clear_jmp_history(state);
860 	if (free_self)
861 		kfree(state);
862 }
863 
864 /* copy verifier state from src to dst growing dst stack space
865  * when necessary to accommodate larger src stack
866  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)867 static int copy_func_state(struct bpf_func_state *dst,
868 			   const struct bpf_func_state *src)
869 {
870 	int err;
871 
872 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
873 				 false);
874 	if (err)
875 		return err;
876 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
877 	err = copy_reference_state(dst, src);
878 	if (err)
879 		return err;
880 	return copy_stack_state(dst, src);
881 }
882 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)883 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
884 			       const struct bpf_verifier_state *src)
885 {
886 	struct bpf_func_state *dst;
887 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
888 	int i, err;
889 
890 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
891 		kfree(dst_state->jmp_history);
892 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
893 		if (!dst_state->jmp_history)
894 			return -ENOMEM;
895 	}
896 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
897 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
898 
899 	/* if dst has more stack frames then src frame, free them */
900 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
901 		free_func_state(dst_state->frame[i]);
902 		dst_state->frame[i] = NULL;
903 	}
904 	dst_state->speculative = src->speculative;
905 	dst_state->curframe = src->curframe;
906 	dst_state->active_spin_lock = src->active_spin_lock;
907 	dst_state->branches = src->branches;
908 	dst_state->parent = src->parent;
909 	dst_state->first_insn_idx = src->first_insn_idx;
910 	dst_state->last_insn_idx = src->last_insn_idx;
911 	for (i = 0; i <= src->curframe; i++) {
912 		dst = dst_state->frame[i];
913 		if (!dst) {
914 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
915 			if (!dst)
916 				return -ENOMEM;
917 			dst_state->frame[i] = dst;
918 		}
919 		err = copy_func_state(dst, src->frame[i]);
920 		if (err)
921 			return err;
922 	}
923 	return 0;
924 }
925 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)926 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
927 {
928 	while (st) {
929 		u32 br = --st->branches;
930 
931 		/* WARN_ON(br > 1) technically makes sense here,
932 		 * but see comment in push_stack(), hence:
933 		 */
934 		WARN_ONCE((int)br < 0,
935 			  "BUG update_branch_counts:branches_to_explore=%d\n",
936 			  br);
937 		if (br)
938 			break;
939 		st = st->parent;
940 	}
941 }
942 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)943 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
944 		     int *insn_idx, bool pop_log)
945 {
946 	struct bpf_verifier_state *cur = env->cur_state;
947 	struct bpf_verifier_stack_elem *elem, *head = env->head;
948 	int err;
949 
950 	if (env->head == NULL)
951 		return -ENOENT;
952 
953 	if (cur) {
954 		err = copy_verifier_state(cur, &head->st);
955 		if (err)
956 			return err;
957 	}
958 	if (pop_log)
959 		bpf_vlog_reset(&env->log, head->log_pos);
960 	if (insn_idx)
961 		*insn_idx = head->insn_idx;
962 	if (prev_insn_idx)
963 		*prev_insn_idx = head->prev_insn_idx;
964 	elem = head->next;
965 	free_verifier_state(&head->st, false);
966 	kfree(head);
967 	env->head = elem;
968 	env->stack_size--;
969 	return 0;
970 }
971 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)972 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
973 					     int insn_idx, int prev_insn_idx,
974 					     bool speculative)
975 {
976 	struct bpf_verifier_state *cur = env->cur_state;
977 	struct bpf_verifier_stack_elem *elem;
978 	int err;
979 
980 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
981 	if (!elem)
982 		goto err;
983 
984 	elem->insn_idx = insn_idx;
985 	elem->prev_insn_idx = prev_insn_idx;
986 	elem->next = env->head;
987 	elem->log_pos = env->log.len_used;
988 	env->head = elem;
989 	env->stack_size++;
990 	err = copy_verifier_state(&elem->st, cur);
991 	if (err)
992 		goto err;
993 	elem->st.speculative |= speculative;
994 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
995 		verbose(env, "The sequence of %d jumps is too complex.\n",
996 			env->stack_size);
997 		goto err;
998 	}
999 	if (elem->st.parent) {
1000 		++elem->st.parent->branches;
1001 		/* WARN_ON(branches > 2) technically makes sense here,
1002 		 * but
1003 		 * 1. speculative states will bump 'branches' for non-branch
1004 		 * instructions
1005 		 * 2. is_state_visited() heuristics may decide not to create
1006 		 * a new state for a sequence of branches and all such current
1007 		 * and cloned states will be pointing to a single parent state
1008 		 * which might have large 'branches' count.
1009 		 */
1010 	}
1011 	return &elem->st;
1012 err:
1013 	free_verifier_state(env->cur_state, true);
1014 	env->cur_state = NULL;
1015 	/* pop all elements and return */
1016 	while (!pop_stack(env, NULL, NULL, false));
1017 	return NULL;
1018 }
1019 
1020 #define CALLER_SAVED_REGS 6
1021 static const int caller_saved[CALLER_SAVED_REGS] = {
1022 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1023 };
1024 
1025 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1026 				struct bpf_reg_state *reg);
1027 
1028 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1029 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1030 {
1031 	reg->var_off = tnum_const(imm);
1032 	reg->smin_value = (s64)imm;
1033 	reg->smax_value = (s64)imm;
1034 	reg->umin_value = imm;
1035 	reg->umax_value = imm;
1036 
1037 	reg->s32_min_value = (s32)imm;
1038 	reg->s32_max_value = (s32)imm;
1039 	reg->u32_min_value = (u32)imm;
1040 	reg->u32_max_value = (u32)imm;
1041 }
1042 
1043 /* Mark the unknown part of a register (variable offset or scalar value) as
1044  * known to have the value @imm.
1045  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1046 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1047 {
1048 	/* Clear id, off, and union(map_ptr, range) */
1049 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1050 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1051 	___mark_reg_known(reg, imm);
1052 }
1053 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1054 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1055 {
1056 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1057 	reg->s32_min_value = (s32)imm;
1058 	reg->s32_max_value = (s32)imm;
1059 	reg->u32_min_value = (u32)imm;
1060 	reg->u32_max_value = (u32)imm;
1061 }
1062 
1063 /* Mark the 'variable offset' part of a register as zero.  This should be
1064  * used only on registers holding a pointer type.
1065  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1066 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1067 {
1068 	__mark_reg_known(reg, 0);
1069 }
1070 
__mark_reg_const_zero(struct bpf_reg_state * reg)1071 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1072 {
1073 	__mark_reg_known(reg, 0);
1074 	reg->type = SCALAR_VALUE;
1075 }
1076 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1077 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1078 				struct bpf_reg_state *regs, u32 regno)
1079 {
1080 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1081 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1082 		/* Something bad happened, let's kill all regs */
1083 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1084 			__mark_reg_not_init(env, regs + regno);
1085 		return;
1086 	}
1087 	__mark_reg_known_zero(regs + regno);
1088 }
1089 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1090 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1091 {
1092 	return type_is_pkt_pointer(reg->type);
1093 }
1094 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1095 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1096 {
1097 	return reg_is_pkt_pointer(reg) ||
1098 	       reg->type == PTR_TO_PACKET_END;
1099 }
1100 
1101 /* 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)1102 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1103 				    enum bpf_reg_type which)
1104 {
1105 	/* The register can already have a range from prior markings.
1106 	 * This is fine as long as it hasn't been advanced from its
1107 	 * origin.
1108 	 */
1109 	return reg->type == which &&
1110 	       reg->id == 0 &&
1111 	       reg->off == 0 &&
1112 	       tnum_equals_const(reg->var_off, 0);
1113 }
1114 
1115 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1116 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1117 {
1118 	reg->smin_value = S64_MIN;
1119 	reg->smax_value = S64_MAX;
1120 	reg->umin_value = 0;
1121 	reg->umax_value = U64_MAX;
1122 
1123 	reg->s32_min_value = S32_MIN;
1124 	reg->s32_max_value = S32_MAX;
1125 	reg->u32_min_value = 0;
1126 	reg->u32_max_value = U32_MAX;
1127 }
1128 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1129 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1130 {
1131 	reg->smin_value = S64_MIN;
1132 	reg->smax_value = S64_MAX;
1133 	reg->umin_value = 0;
1134 	reg->umax_value = U64_MAX;
1135 }
1136 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1137 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1138 {
1139 	reg->s32_min_value = S32_MIN;
1140 	reg->s32_max_value = S32_MAX;
1141 	reg->u32_min_value = 0;
1142 	reg->u32_max_value = U32_MAX;
1143 }
1144 
__update_reg32_bounds(struct bpf_reg_state * reg)1145 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1146 {
1147 	struct tnum var32_off = tnum_subreg(reg->var_off);
1148 
1149 	/* min signed is max(sign bit) | min(other bits) */
1150 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1151 			var32_off.value | (var32_off.mask & S32_MIN));
1152 	/* max signed is min(sign bit) | max(other bits) */
1153 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1154 			var32_off.value | (var32_off.mask & S32_MAX));
1155 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1156 	reg->u32_max_value = min(reg->u32_max_value,
1157 				 (u32)(var32_off.value | var32_off.mask));
1158 }
1159 
__update_reg64_bounds(struct bpf_reg_state * reg)1160 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1161 {
1162 	/* min signed is max(sign bit) | min(other bits) */
1163 	reg->smin_value = max_t(s64, reg->smin_value,
1164 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1165 	/* max signed is min(sign bit) | max(other bits) */
1166 	reg->smax_value = min_t(s64, reg->smax_value,
1167 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1168 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1169 	reg->umax_value = min(reg->umax_value,
1170 			      reg->var_off.value | reg->var_off.mask);
1171 }
1172 
__update_reg_bounds(struct bpf_reg_state * reg)1173 static void __update_reg_bounds(struct bpf_reg_state *reg)
1174 {
1175 	__update_reg32_bounds(reg);
1176 	__update_reg64_bounds(reg);
1177 }
1178 
1179 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1180 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1181 {
1182 	/* Learn sign from signed bounds.
1183 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1184 	 * are the same, so combine.  This works even in the negative case, e.g.
1185 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1186 	 */
1187 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1188 		reg->s32_min_value = reg->u32_min_value =
1189 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1190 		reg->s32_max_value = reg->u32_max_value =
1191 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1192 		return;
1193 	}
1194 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1195 	 * boundary, so we must be careful.
1196 	 */
1197 	if ((s32)reg->u32_max_value >= 0) {
1198 		/* Positive.  We can't learn anything from the smin, but smax
1199 		 * is positive, hence safe.
1200 		 */
1201 		reg->s32_min_value = reg->u32_min_value;
1202 		reg->s32_max_value = reg->u32_max_value =
1203 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1204 	} else if ((s32)reg->u32_min_value < 0) {
1205 		/* Negative.  We can't learn anything from the smax, but smin
1206 		 * is negative, hence safe.
1207 		 */
1208 		reg->s32_min_value = reg->u32_min_value =
1209 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1210 		reg->s32_max_value = reg->u32_max_value;
1211 	}
1212 }
1213 
__reg64_deduce_bounds(struct bpf_reg_state * reg)1214 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1215 {
1216 	/* Learn sign from signed bounds.
1217 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1218 	 * are the same, so combine.  This works even in the negative case, e.g.
1219 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1220 	 */
1221 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1222 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1223 							  reg->umin_value);
1224 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1225 							  reg->umax_value);
1226 		return;
1227 	}
1228 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1229 	 * boundary, so we must be careful.
1230 	 */
1231 	if ((s64)reg->umax_value >= 0) {
1232 		/* Positive.  We can't learn anything from the smin, but smax
1233 		 * is positive, hence safe.
1234 		 */
1235 		reg->smin_value = reg->umin_value;
1236 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1237 							  reg->umax_value);
1238 	} else if ((s64)reg->umin_value < 0) {
1239 		/* Negative.  We can't learn anything from the smax, but smin
1240 		 * is negative, hence safe.
1241 		 */
1242 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1243 							  reg->umin_value);
1244 		reg->smax_value = reg->umax_value;
1245 	}
1246 }
1247 
__reg_deduce_bounds(struct bpf_reg_state * reg)1248 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1249 {
1250 	__reg32_deduce_bounds(reg);
1251 	__reg64_deduce_bounds(reg);
1252 }
1253 
1254 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1255 static void __reg_bound_offset(struct bpf_reg_state *reg)
1256 {
1257 	struct tnum var64_off = tnum_intersect(reg->var_off,
1258 					       tnum_range(reg->umin_value,
1259 							  reg->umax_value));
1260 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1261 						tnum_range(reg->u32_min_value,
1262 							   reg->u32_max_value));
1263 
1264 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1265 }
1266 
reg_bounds_sync(struct bpf_reg_state * reg)1267 static void reg_bounds_sync(struct bpf_reg_state *reg)
1268 {
1269 	/* We might have learned new bounds from the var_off. */
1270 	__update_reg_bounds(reg);
1271 	/* We might have learned something about the sign bit. */
1272 	__reg_deduce_bounds(reg);
1273 	/* We might have learned some bits from the bounds. */
1274 	__reg_bound_offset(reg);
1275 	/* Intersecting with the old var_off might have improved our bounds
1276 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1277 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1278 	 */
1279 	__update_reg_bounds(reg);
1280 }
1281 
__reg32_bound_s64(s32 a)1282 static bool __reg32_bound_s64(s32 a)
1283 {
1284 	return a >= 0 && a <= S32_MAX;
1285 }
1286 
__reg_assign_32_into_64(struct bpf_reg_state * reg)1287 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1288 {
1289 	reg->umin_value = reg->u32_min_value;
1290 	reg->umax_value = reg->u32_max_value;
1291 
1292 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1293 	 * be positive otherwise set to worse case bounds and refine later
1294 	 * from tnum.
1295 	 */
1296 	if (__reg32_bound_s64(reg->s32_min_value) &&
1297 	    __reg32_bound_s64(reg->s32_max_value)) {
1298 		reg->smin_value = reg->s32_min_value;
1299 		reg->smax_value = reg->s32_max_value;
1300 	} else {
1301 		reg->smin_value = 0;
1302 		reg->smax_value = U32_MAX;
1303 	}
1304 }
1305 
__reg_combine_32_into_64(struct bpf_reg_state * reg)1306 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1307 {
1308 	/* special case when 64-bit register has upper 32-bit register
1309 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1310 	 * allowing us to use 32-bit bounds directly,
1311 	 */
1312 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1313 		__reg_assign_32_into_64(reg);
1314 	} else {
1315 		/* Otherwise the best we can do is push lower 32bit known and
1316 		 * unknown bits into register (var_off set from jmp logic)
1317 		 * then learn as much as possible from the 64-bit tnum
1318 		 * known and unknown bits. The previous smin/smax bounds are
1319 		 * invalid here because of jmp32 compare so mark them unknown
1320 		 * so they do not impact tnum bounds calculation.
1321 		 */
1322 		__mark_reg64_unbounded(reg);
1323 	}
1324 	reg_bounds_sync(reg);
1325 }
1326 
__reg64_bound_s32(s64 a)1327 static bool __reg64_bound_s32(s64 a)
1328 {
1329 	return a >= S32_MIN && a <= S32_MAX;
1330 }
1331 
__reg64_bound_u32(u64 a)1332 static bool __reg64_bound_u32(u64 a)
1333 {
1334 	return a >= U32_MIN && a <= U32_MAX;
1335 }
1336 
__reg_combine_64_into_32(struct bpf_reg_state * reg)1337 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1338 {
1339 	__mark_reg32_unbounded(reg);
1340 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1341 		reg->s32_min_value = (s32)reg->smin_value;
1342 		reg->s32_max_value = (s32)reg->smax_value;
1343 	}
1344 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1345 		reg->u32_min_value = (u32)reg->umin_value;
1346 		reg->u32_max_value = (u32)reg->umax_value;
1347 	}
1348 	reg_bounds_sync(reg);
1349 }
1350 
1351 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1352 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1353 			       struct bpf_reg_state *reg)
1354 {
1355 	/*
1356 	 * Clear type, id, off, and union(map_ptr, range) and
1357 	 * padding between 'type' and union
1358 	 */
1359 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1360 	reg->type = SCALAR_VALUE;
1361 	reg->var_off = tnum_unknown;
1362 	reg->frameno = 0;
1363 	reg->precise = !env->bpf_capable;
1364 	__mark_reg_unbounded(reg);
1365 }
1366 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1367 static void mark_reg_unknown(struct bpf_verifier_env *env,
1368 			     struct bpf_reg_state *regs, u32 regno)
1369 {
1370 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1371 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1372 		/* Something bad happened, let's kill all regs except FP */
1373 		for (regno = 0; regno < BPF_REG_FP; regno++)
1374 			__mark_reg_not_init(env, regs + regno);
1375 		return;
1376 	}
1377 	__mark_reg_unknown(env, regs + regno);
1378 }
1379 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1380 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1381 				struct bpf_reg_state *reg)
1382 {
1383 	__mark_reg_unknown(env, reg);
1384 	reg->type = NOT_INIT;
1385 }
1386 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1387 static void mark_reg_not_init(struct bpf_verifier_env *env,
1388 			      struct bpf_reg_state *regs, u32 regno)
1389 {
1390 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1391 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1392 		/* Something bad happened, let's kill all regs except FP */
1393 		for (regno = 0; regno < BPF_REG_FP; regno++)
1394 			__mark_reg_not_init(env, regs + regno);
1395 		return;
1396 	}
1397 	__mark_reg_not_init(env, regs + regno);
1398 }
1399 
mark_btf_ld_reg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum bpf_reg_type reg_type,u32 btf_id)1400 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1401 			    struct bpf_reg_state *regs, u32 regno,
1402 			    enum bpf_reg_type reg_type, u32 btf_id)
1403 {
1404 	if (reg_type == SCALAR_VALUE) {
1405 		mark_reg_unknown(env, regs, regno);
1406 		return;
1407 	}
1408 	mark_reg_known_zero(env, regs, regno);
1409 	regs[regno].type = PTR_TO_BTF_ID;
1410 	regs[regno].btf_id = btf_id;
1411 }
1412 
1413 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1414 static void init_reg_state(struct bpf_verifier_env *env,
1415 			   struct bpf_func_state *state)
1416 {
1417 	struct bpf_reg_state *regs = state->regs;
1418 	int i;
1419 
1420 	for (i = 0; i < MAX_BPF_REG; i++) {
1421 		mark_reg_not_init(env, regs, i);
1422 		regs[i].live = REG_LIVE_NONE;
1423 		regs[i].parent = NULL;
1424 		regs[i].subreg_def = DEF_NOT_SUBREG;
1425 	}
1426 
1427 	/* frame pointer */
1428 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1429 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1430 	regs[BPF_REG_FP].frameno = state->frameno;
1431 }
1432 
1433 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1434 static void init_func_state(struct bpf_verifier_env *env,
1435 			    struct bpf_func_state *state,
1436 			    int callsite, int frameno, int subprogno)
1437 {
1438 	state->callsite = callsite;
1439 	state->frameno = frameno;
1440 	state->subprogno = subprogno;
1441 	init_reg_state(env, state);
1442 }
1443 
1444 enum reg_arg_type {
1445 	SRC_OP,		/* register is used as source operand */
1446 	DST_OP,		/* register is used as destination operand */
1447 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1448 };
1449 
cmp_subprogs(const void * a,const void * b)1450 static int cmp_subprogs(const void *a, const void *b)
1451 {
1452 	return ((struct bpf_subprog_info *)a)->start -
1453 	       ((struct bpf_subprog_info *)b)->start;
1454 }
1455 
find_subprog(struct bpf_verifier_env * env,int off)1456 static int find_subprog(struct bpf_verifier_env *env, int off)
1457 {
1458 	struct bpf_subprog_info *p;
1459 
1460 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1461 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1462 	if (!p)
1463 		return -ENOENT;
1464 	return p - env->subprog_info;
1465 
1466 }
1467 
add_subprog(struct bpf_verifier_env * env,int off)1468 static int add_subprog(struct bpf_verifier_env *env, int off)
1469 {
1470 	int insn_cnt = env->prog->len;
1471 	int ret;
1472 
1473 	if (off >= insn_cnt || off < 0) {
1474 		verbose(env, "call to invalid destination\n");
1475 		return -EINVAL;
1476 	}
1477 	ret = find_subprog(env, off);
1478 	if (ret >= 0)
1479 		return 0;
1480 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1481 		verbose(env, "too many subprograms\n");
1482 		return -E2BIG;
1483 	}
1484 	env->subprog_info[env->subprog_cnt++].start = off;
1485 	sort(env->subprog_info, env->subprog_cnt,
1486 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1487 	return 0;
1488 }
1489 
check_subprogs(struct bpf_verifier_env * env)1490 static int check_subprogs(struct bpf_verifier_env *env)
1491 {
1492 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1493 	struct bpf_subprog_info *subprog = env->subprog_info;
1494 	struct bpf_insn *insn = env->prog->insnsi;
1495 	int insn_cnt = env->prog->len;
1496 
1497 	/* Add entry function. */
1498 	ret = add_subprog(env, 0);
1499 	if (ret < 0)
1500 		return ret;
1501 
1502 	/* determine subprog starts. The end is one before the next starts */
1503 	for (i = 0; i < insn_cnt; i++) {
1504 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1505 			continue;
1506 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1507 			continue;
1508 		if (!env->bpf_capable) {
1509 			verbose(env,
1510 				"function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1511 			return -EPERM;
1512 		}
1513 		ret = add_subprog(env, i + insn[i].imm + 1);
1514 		if (ret < 0)
1515 			return ret;
1516 	}
1517 
1518 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1519 	 * logic. 'subprog_cnt' should not be increased.
1520 	 */
1521 	subprog[env->subprog_cnt].start = insn_cnt;
1522 
1523 	if (env->log.level & BPF_LOG_LEVEL2)
1524 		for (i = 0; i < env->subprog_cnt; i++)
1525 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1526 
1527 	/* now check that all jumps are within the same subprog */
1528 	subprog_start = subprog[cur_subprog].start;
1529 	subprog_end = subprog[cur_subprog + 1].start;
1530 	for (i = 0; i < insn_cnt; i++) {
1531 		u8 code = insn[i].code;
1532 
1533 		if (code == (BPF_JMP | BPF_CALL) &&
1534 		    insn[i].imm == BPF_FUNC_tail_call &&
1535 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1536 			subprog[cur_subprog].has_tail_call = true;
1537 		if (BPF_CLASS(code) == BPF_LD &&
1538 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1539 			subprog[cur_subprog].has_ld_abs = true;
1540 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1541 			goto next;
1542 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1543 			goto next;
1544 		off = i + insn[i].off + 1;
1545 		if (off < subprog_start || off >= subprog_end) {
1546 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1547 			return -EINVAL;
1548 		}
1549 next:
1550 		if (i == subprog_end - 1) {
1551 			/* to avoid fall-through from one subprog into another
1552 			 * the last insn of the subprog should be either exit
1553 			 * or unconditional jump back
1554 			 */
1555 			if (code != (BPF_JMP | BPF_EXIT) &&
1556 			    code != (BPF_JMP | BPF_JA)) {
1557 				verbose(env, "last insn is not an exit or jmp\n");
1558 				return -EINVAL;
1559 			}
1560 			subprog_start = subprog_end;
1561 			cur_subprog++;
1562 			if (cur_subprog < env->subprog_cnt)
1563 				subprog_end = subprog[cur_subprog + 1].start;
1564 		}
1565 	}
1566 	return 0;
1567 }
1568 
1569 /* Parentage chain of this register (or stack slot) should take care of all
1570  * issues like callee-saved registers, stack slot allocation time, etc.
1571  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1572 static int mark_reg_read(struct bpf_verifier_env *env,
1573 			 const struct bpf_reg_state *state,
1574 			 struct bpf_reg_state *parent, u8 flag)
1575 {
1576 	bool writes = parent == state->parent; /* Observe write marks */
1577 	int cnt = 0;
1578 
1579 	while (parent) {
1580 		/* if read wasn't screened by an earlier write ... */
1581 		if (writes && state->live & REG_LIVE_WRITTEN)
1582 			break;
1583 		if (parent->live & REG_LIVE_DONE) {
1584 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1585 				reg_type_str(env, parent->type),
1586 				parent->var_off.value, parent->off);
1587 			return -EFAULT;
1588 		}
1589 		/* The first condition is more likely to be true than the
1590 		 * second, checked it first.
1591 		 */
1592 		if ((parent->live & REG_LIVE_READ) == flag ||
1593 		    parent->live & REG_LIVE_READ64)
1594 			/* The parentage chain never changes and
1595 			 * this parent was already marked as LIVE_READ.
1596 			 * There is no need to keep walking the chain again and
1597 			 * keep re-marking all parents as LIVE_READ.
1598 			 * This case happens when the same register is read
1599 			 * multiple times without writes into it in-between.
1600 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1601 			 * then no need to set the weak REG_LIVE_READ32.
1602 			 */
1603 			break;
1604 		/* ... then we depend on parent's value */
1605 		parent->live |= flag;
1606 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1607 		if (flag == REG_LIVE_READ64)
1608 			parent->live &= ~REG_LIVE_READ32;
1609 		state = parent;
1610 		parent = state->parent;
1611 		writes = true;
1612 		cnt++;
1613 	}
1614 
1615 	if (env->longest_mark_read_walk < cnt)
1616 		env->longest_mark_read_walk = cnt;
1617 	return 0;
1618 }
1619 
1620 /* This function is supposed to be used by the following 32-bit optimization
1621  * code only. It returns TRUE if the source or destination register operates
1622  * on 64-bit, otherwise return FALSE.
1623  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1624 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1625 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1626 {
1627 	u8 code, class, op;
1628 
1629 	code = insn->code;
1630 	class = BPF_CLASS(code);
1631 	op = BPF_OP(code);
1632 	if (class == BPF_JMP) {
1633 		/* BPF_EXIT for "main" will reach here. Return TRUE
1634 		 * conservatively.
1635 		 */
1636 		if (op == BPF_EXIT)
1637 			return true;
1638 		if (op == BPF_CALL) {
1639 			/* BPF to BPF call will reach here because of marking
1640 			 * caller saved clobber with DST_OP_NO_MARK for which we
1641 			 * don't care the register def because they are anyway
1642 			 * marked as NOT_INIT already.
1643 			 */
1644 			if (insn->src_reg == BPF_PSEUDO_CALL)
1645 				return false;
1646 			/* Helper call will reach here because of arg type
1647 			 * check, conservatively return TRUE.
1648 			 */
1649 			if (t == SRC_OP)
1650 				return true;
1651 
1652 			return false;
1653 		}
1654 	}
1655 
1656 	if (class == BPF_ALU64 || class == BPF_JMP ||
1657 	    /* BPF_END always use BPF_ALU class. */
1658 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1659 		return true;
1660 
1661 	if (class == BPF_ALU || class == BPF_JMP32)
1662 		return false;
1663 
1664 	if (class == BPF_LDX) {
1665 		if (t != SRC_OP)
1666 			return BPF_SIZE(code) == BPF_DW;
1667 		/* LDX source must be ptr. */
1668 		return true;
1669 	}
1670 
1671 	if (class == BPF_STX) {
1672 		if (reg->type != SCALAR_VALUE)
1673 			return true;
1674 		return BPF_SIZE(code) == BPF_DW;
1675 	}
1676 
1677 	if (class == BPF_LD) {
1678 		u8 mode = BPF_MODE(code);
1679 
1680 		/* LD_IMM64 */
1681 		if (mode == BPF_IMM)
1682 			return true;
1683 
1684 		/* Both LD_IND and LD_ABS return 32-bit data. */
1685 		if (t != SRC_OP)
1686 			return  false;
1687 
1688 		/* Implicit ctx ptr. */
1689 		if (regno == BPF_REG_6)
1690 			return true;
1691 
1692 		/* Explicit source could be any width. */
1693 		return true;
1694 	}
1695 
1696 	if (class == BPF_ST)
1697 		/* The only source register for BPF_ST is a ptr. */
1698 		return true;
1699 
1700 	/* Conservatively return true at default. */
1701 	return true;
1702 }
1703 
1704 /* Return TRUE if INSN doesn't have explicit value define. */
insn_no_def(struct bpf_insn * insn)1705 static bool insn_no_def(struct bpf_insn *insn)
1706 {
1707 	u8 class = BPF_CLASS(insn->code);
1708 
1709 	return (class == BPF_JMP || class == BPF_JMP32 ||
1710 		class == BPF_STX || class == BPF_ST);
1711 }
1712 
1713 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)1714 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1715 {
1716 	if (insn_no_def(insn))
1717 		return false;
1718 
1719 	return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1720 }
1721 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1722 static void mark_insn_zext(struct bpf_verifier_env *env,
1723 			   struct bpf_reg_state *reg)
1724 {
1725 	s32 def_idx = reg->subreg_def;
1726 
1727 	if (def_idx == DEF_NOT_SUBREG)
1728 		return;
1729 
1730 	env->insn_aux_data[def_idx - 1].zext_dst = true;
1731 	/* The dst will be zero extended, so won't be sub-register anymore. */
1732 	reg->subreg_def = DEF_NOT_SUBREG;
1733 }
1734 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)1735 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1736 			 enum reg_arg_type t)
1737 {
1738 	struct bpf_verifier_state *vstate = env->cur_state;
1739 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1740 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1741 	struct bpf_reg_state *reg, *regs = state->regs;
1742 	bool rw64;
1743 
1744 	if (regno >= MAX_BPF_REG) {
1745 		verbose(env, "R%d is invalid\n", regno);
1746 		return -EINVAL;
1747 	}
1748 
1749 	reg = &regs[regno];
1750 	rw64 = is_reg64(env, insn, regno, reg, t);
1751 	if (t == SRC_OP) {
1752 		/* check whether register used as source operand can be read */
1753 		if (reg->type == NOT_INIT) {
1754 			verbose(env, "R%d !read_ok\n", regno);
1755 			return -EACCES;
1756 		}
1757 		/* We don't need to worry about FP liveness because it's read-only */
1758 		if (regno == BPF_REG_FP)
1759 			return 0;
1760 
1761 		if (rw64)
1762 			mark_insn_zext(env, reg);
1763 
1764 		return mark_reg_read(env, reg, reg->parent,
1765 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1766 	} else {
1767 		/* check whether register used as dest operand can be written to */
1768 		if (regno == BPF_REG_FP) {
1769 			verbose(env, "frame pointer is read only\n");
1770 			return -EACCES;
1771 		}
1772 		reg->live |= REG_LIVE_WRITTEN;
1773 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1774 		if (t == DST_OP)
1775 			mark_reg_unknown(env, regs, regno);
1776 	}
1777 	return 0;
1778 }
1779 
1780 /* 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)1781 static int push_jmp_history(struct bpf_verifier_env *env,
1782 			    struct bpf_verifier_state *cur)
1783 {
1784 	u32 cnt = cur->jmp_history_cnt;
1785 	struct bpf_idx_pair *p;
1786 
1787 	cnt++;
1788 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1789 	if (!p)
1790 		return -ENOMEM;
1791 	p[cnt - 1].idx = env->insn_idx;
1792 	p[cnt - 1].prev_idx = env->prev_insn_idx;
1793 	cur->jmp_history = p;
1794 	cur->jmp_history_cnt = cnt;
1795 	return 0;
1796 }
1797 
1798 /* Backtrack one insn at a time. If idx is not at the top of recorded
1799  * history then previous instruction came from straight line execution.
1800  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)1801 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1802 			     u32 *history)
1803 {
1804 	u32 cnt = *history;
1805 
1806 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
1807 		i = st->jmp_history[cnt - 1].prev_idx;
1808 		(*history)--;
1809 	} else {
1810 		i--;
1811 	}
1812 	return i;
1813 }
1814 
1815 /* For given verifier state backtrack_insn() is called from the last insn to
1816  * the first insn. Its purpose is to compute a bitmask of registers and
1817  * stack slots that needs precision in the parent verifier state.
1818  */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)1819 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1820 			  u32 *reg_mask, u64 *stack_mask)
1821 {
1822 	const struct bpf_insn_cbs cbs = {
1823 		.cb_print	= verbose,
1824 		.private_data	= env,
1825 	};
1826 	struct bpf_insn *insn = env->prog->insnsi + idx;
1827 	u8 class = BPF_CLASS(insn->code);
1828 	u8 opcode = BPF_OP(insn->code);
1829 	u8 mode = BPF_MODE(insn->code);
1830 	u32 dreg = 1u << insn->dst_reg;
1831 	u32 sreg = 1u << insn->src_reg;
1832 	u32 spi;
1833 
1834 	if (insn->code == 0)
1835 		return 0;
1836 	if (env->log.level & BPF_LOG_LEVEL) {
1837 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1838 		verbose(env, "%d: ", idx);
1839 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1840 	}
1841 
1842 	if (class == BPF_ALU || class == BPF_ALU64) {
1843 		if (!(*reg_mask & dreg))
1844 			return 0;
1845 		if (opcode == BPF_END || opcode == BPF_NEG) {
1846 			/* sreg is reserved and unused
1847 			 * dreg still need precision before this insn
1848 			 */
1849 			return 0;
1850 		} else if (opcode == BPF_MOV) {
1851 			if (BPF_SRC(insn->code) == BPF_X) {
1852 				/* dreg = sreg
1853 				 * dreg needs precision after this insn
1854 				 * sreg needs precision before this insn
1855 				 */
1856 				*reg_mask &= ~dreg;
1857 				*reg_mask |= sreg;
1858 			} else {
1859 				/* dreg = K
1860 				 * dreg needs precision after this insn.
1861 				 * Corresponding register is already marked
1862 				 * as precise=true in this verifier state.
1863 				 * No further markings in parent are necessary
1864 				 */
1865 				*reg_mask &= ~dreg;
1866 			}
1867 		} else {
1868 			if (BPF_SRC(insn->code) == BPF_X) {
1869 				/* dreg += sreg
1870 				 * both dreg and sreg need precision
1871 				 * before this insn
1872 				 */
1873 				*reg_mask |= sreg;
1874 			} /* else dreg += K
1875 			   * dreg still needs precision before this insn
1876 			   */
1877 		}
1878 	} else if (class == BPF_LDX) {
1879 		if (!(*reg_mask & dreg))
1880 			return 0;
1881 		*reg_mask &= ~dreg;
1882 
1883 		/* scalars can only be spilled into stack w/o losing precision.
1884 		 * Load from any other memory can be zero extended.
1885 		 * The desire to keep that precision is already indicated
1886 		 * by 'precise' mark in corresponding register of this state.
1887 		 * No further tracking necessary.
1888 		 */
1889 		if (insn->src_reg != BPF_REG_FP)
1890 			return 0;
1891 
1892 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
1893 		 * that [fp - off] slot contains scalar that needs to be
1894 		 * tracked with precision
1895 		 */
1896 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1897 		if (spi >= 64) {
1898 			verbose(env, "BUG spi %d\n", spi);
1899 			WARN_ONCE(1, "verifier backtracking bug");
1900 			return -EFAULT;
1901 		}
1902 		*stack_mask |= 1ull << spi;
1903 	} else if (class == BPF_STX || class == BPF_ST) {
1904 		if (*reg_mask & dreg)
1905 			/* stx & st shouldn't be using _scalar_ dst_reg
1906 			 * to access memory. It means backtracking
1907 			 * encountered a case of pointer subtraction.
1908 			 */
1909 			return -ENOTSUPP;
1910 		/* scalars can only be spilled into stack */
1911 		if (insn->dst_reg != BPF_REG_FP)
1912 			return 0;
1913 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1914 		if (spi >= 64) {
1915 			verbose(env, "BUG spi %d\n", spi);
1916 			WARN_ONCE(1, "verifier backtracking bug");
1917 			return -EFAULT;
1918 		}
1919 		if (!(*stack_mask & (1ull << spi)))
1920 			return 0;
1921 		*stack_mask &= ~(1ull << spi);
1922 		if (class == BPF_STX)
1923 			*reg_mask |= sreg;
1924 	} else if (class == BPF_JMP || class == BPF_JMP32) {
1925 		if (opcode == BPF_CALL) {
1926 			if (insn->src_reg == BPF_PSEUDO_CALL)
1927 				return -ENOTSUPP;
1928 			/* regular helper call sets R0 */
1929 			*reg_mask &= ~1;
1930 			if (*reg_mask & 0x3f) {
1931 				/* if backtracing was looking for registers R1-R5
1932 				 * they should have been found already.
1933 				 */
1934 				verbose(env, "BUG regs %x\n", *reg_mask);
1935 				WARN_ONCE(1, "verifier backtracking bug");
1936 				return -EFAULT;
1937 			}
1938 		} else if (opcode == BPF_EXIT) {
1939 			return -ENOTSUPP;
1940 		} else if (BPF_SRC(insn->code) == BPF_X) {
1941 			if (!(*reg_mask & (dreg | sreg)))
1942 				return 0;
1943 			/* dreg <cond> sreg
1944 			 * Both dreg and sreg need precision before
1945 			 * this insn. If only sreg was marked precise
1946 			 * before it would be equally necessary to
1947 			 * propagate it to dreg.
1948 			 */
1949 			*reg_mask |= (sreg | dreg);
1950 			 /* else dreg <cond> K
1951 			  * Only dreg still needs precision before
1952 			  * this insn, so for the K-based conditional
1953 			  * there is nothing new to be marked.
1954 			  */
1955 		}
1956 	} else if (class == BPF_LD) {
1957 		if (!(*reg_mask & dreg))
1958 			return 0;
1959 		*reg_mask &= ~dreg;
1960 		/* It's ld_imm64 or ld_abs or ld_ind.
1961 		 * For ld_imm64 no further tracking of precision
1962 		 * into parent is necessary
1963 		 */
1964 		if (mode == BPF_IND || mode == BPF_ABS)
1965 			/* to be analyzed */
1966 			return -ENOTSUPP;
1967 	}
1968 	return 0;
1969 }
1970 
1971 /* the scalar precision tracking algorithm:
1972  * . at the start all registers have precise=false.
1973  * . scalar ranges are tracked as normal through alu and jmp insns.
1974  * . once precise value of the scalar register is used in:
1975  *   .  ptr + scalar alu
1976  *   . if (scalar cond K|scalar)
1977  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1978  *   backtrack through the verifier states and mark all registers and
1979  *   stack slots with spilled constants that these scalar regisers
1980  *   should be precise.
1981  * . during state pruning two registers (or spilled stack slots)
1982  *   are equivalent if both are not precise.
1983  *
1984  * Note the verifier cannot simply walk register parentage chain,
1985  * since many different registers and stack slots could have been
1986  * used to compute single precise scalar.
1987  *
1988  * The approach of starting with precise=true for all registers and then
1989  * backtrack to mark a register as not precise when the verifier detects
1990  * that program doesn't care about specific value (e.g., when helper
1991  * takes register as ARG_ANYTHING parameter) is not safe.
1992  *
1993  * It's ok to walk single parentage chain of the verifier states.
1994  * It's possible that this backtracking will go all the way till 1st insn.
1995  * All other branches will be explored for needing precision later.
1996  *
1997  * The backtracking needs to deal with cases like:
1998  *   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)
1999  * r9 -= r8
2000  * r5 = r9
2001  * if r5 > 0x79f goto pc+7
2002  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2003  * r5 += 1
2004  * ...
2005  * call bpf_perf_event_output#25
2006  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2007  *
2008  * and this case:
2009  * r6 = 1
2010  * call foo // uses callee's r6 inside to compute r0
2011  * r0 += r6
2012  * if r0 == 0 goto
2013  *
2014  * to track above reg_mask/stack_mask needs to be independent for each frame.
2015  *
2016  * Also if parent's curframe > frame where backtracking started,
2017  * the verifier need to mark registers in both frames, otherwise callees
2018  * may incorrectly prune callers. This is similar to
2019  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2020  *
2021  * For now backtracking falls back into conservative marking.
2022  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2023 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2024 				     struct bpf_verifier_state *st)
2025 {
2026 	struct bpf_func_state *func;
2027 	struct bpf_reg_state *reg;
2028 	int i, j;
2029 
2030 	/* big hammer: mark all scalars precise in this path.
2031 	 * pop_stack may still get !precise scalars.
2032 	 * We also skip current state and go straight to first parent state,
2033 	 * because precision markings in current non-checkpointed state are
2034 	 * not needed. See why in the comment in __mark_chain_precision below.
2035 	 */
2036 	for (st = st->parent; st; st = st->parent) {
2037 		for (i = 0; i <= st->curframe; i++) {
2038 			func = st->frame[i];
2039 			for (j = 0; j < BPF_REG_FP; j++) {
2040 				reg = &func->regs[j];
2041 				if (reg->type != SCALAR_VALUE)
2042 					continue;
2043 				reg->precise = true;
2044 			}
2045 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2046 				if (!is_spilled_reg(&func->stack[j]))
2047 					continue;
2048 				reg = &func->stack[j].spilled_ptr;
2049 				if (reg->type != SCALAR_VALUE)
2050 					continue;
2051 				reg->precise = true;
2052 			}
2053 		}
2054 	}
2055 }
2056 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2057 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2058 {
2059 	struct bpf_func_state *func;
2060 	struct bpf_reg_state *reg;
2061 	int i, j;
2062 
2063 	for (i = 0; i <= st->curframe; i++) {
2064 		func = st->frame[i];
2065 		for (j = 0; j < BPF_REG_FP; j++) {
2066 			reg = &func->regs[j];
2067 			if (reg->type != SCALAR_VALUE)
2068 				continue;
2069 			reg->precise = false;
2070 		}
2071 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2072 			if (!is_spilled_reg(&func->stack[j]))
2073 				continue;
2074 			reg = &func->stack[j].spilled_ptr;
2075 			if (reg->type != SCALAR_VALUE)
2076 				continue;
2077 			reg->precise = false;
2078 		}
2079 	}
2080 }
2081 
2082 /*
2083  * __mark_chain_precision() backtracks BPF program instruction sequence and
2084  * chain of verifier states making sure that register *regno* (if regno >= 0)
2085  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2086  * SCALARS, as well as any other registers and slots that contribute to
2087  * a tracked state of given registers/stack slots, depending on specific BPF
2088  * assembly instructions (see backtrack_insns() for exact instruction handling
2089  * logic). This backtracking relies on recorded jmp_history and is able to
2090  * traverse entire chain of parent states. This process ends only when all the
2091  * necessary registers/slots and their transitive dependencies are marked as
2092  * precise.
2093  *
2094  * One important and subtle aspect is that precise marks *do not matter* in
2095  * the currently verified state (current state). It is important to understand
2096  * why this is the case.
2097  *
2098  * First, note that current state is the state that is not yet "checkpointed",
2099  * i.e., it is not yet put into env->explored_states, and it has no children
2100  * states as well. It's ephemeral, and can end up either a) being discarded if
2101  * compatible explored state is found at some point or BPF_EXIT instruction is
2102  * reached or b) checkpointed and put into env->explored_states, branching out
2103  * into one or more children states.
2104  *
2105  * In the former case, precise markings in current state are completely
2106  * ignored by state comparison code (see regsafe() for details). Only
2107  * checkpointed ("old") state precise markings are important, and if old
2108  * state's register/slot is precise, regsafe() assumes current state's
2109  * register/slot as precise and checks value ranges exactly and precisely. If
2110  * states turn out to be compatible, current state's necessary precise
2111  * markings and any required parent states' precise markings are enforced
2112  * after the fact with propagate_precision() logic, after the fact. But it's
2113  * important to realize that in this case, even after marking current state
2114  * registers/slots as precise, we immediately discard current state. So what
2115  * actually matters is any of the precise markings propagated into current
2116  * state's parent states, which are always checkpointed (due to b) case above).
2117  * As such, for scenario a) it doesn't matter if current state has precise
2118  * markings set or not.
2119  *
2120  * Now, for the scenario b), checkpointing and forking into child(ren)
2121  * state(s). Note that before current state gets to checkpointing step, any
2122  * processed instruction always assumes precise SCALAR register/slot
2123  * knowledge: if precise value or range is useful to prune jump branch, BPF
2124  * verifier takes this opportunity enthusiastically. Similarly, when
2125  * register's value is used to calculate offset or memory address, exact
2126  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2127  * what we mentioned above about state comparison ignoring precise markings
2128  * during state comparison, BPF verifier ignores and also assumes precise
2129  * markings *at will* during instruction verification process. But as verifier
2130  * assumes precision, it also propagates any precision dependencies across
2131  * parent states, which are not yet finalized, so can be further restricted
2132  * based on new knowledge gained from restrictions enforced by their children
2133  * states. This is so that once those parent states are finalized, i.e., when
2134  * they have no more active children state, state comparison logic in
2135  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2136  * required for correctness.
2137  *
2138  * To build a bit more intuition, note also that once a state is checkpointed,
2139  * the path we took to get to that state is not important. This is crucial
2140  * property for state pruning. When state is checkpointed and finalized at
2141  * some instruction index, it can be correctly and safely used to "short
2142  * circuit" any *compatible* state that reaches exactly the same instruction
2143  * index. I.e., if we jumped to that instruction from a completely different
2144  * code path than original finalized state was derived from, it doesn't
2145  * matter, current state can be discarded because from that instruction
2146  * forward having a compatible state will ensure we will safely reach the
2147  * exit. States describe preconditions for further exploration, but completely
2148  * forget the history of how we got here.
2149  *
2150  * This also means that even if we needed precise SCALAR range to get to
2151  * finalized state, but from that point forward *that same* SCALAR register is
2152  * never used in a precise context (i.e., it's precise value is not needed for
2153  * correctness), it's correct and safe to mark such register as "imprecise"
2154  * (i.e., precise marking set to false). This is what we rely on when we do
2155  * not set precise marking in current state. If no child state requires
2156  * precision for any given SCALAR register, it's safe to dictate that it can
2157  * be imprecise. If any child state does require this register to be precise,
2158  * we'll mark it precise later retroactively during precise markings
2159  * propagation from child state to parent states.
2160  *
2161  * Skipping precise marking setting in current state is a mild version of
2162  * relying on the above observation. But we can utilize this property even
2163  * more aggressively by proactively forgetting any precise marking in the
2164  * current state (which we inherited from the parent state), right before we
2165  * checkpoint it and branch off into new child state. This is done by
2166  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2167  * finalized states which help in short circuiting more future states.
2168  */
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2169 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2170 				  int spi)
2171 {
2172 	struct bpf_verifier_state *st = env->cur_state;
2173 	int first_idx = st->first_insn_idx;
2174 	int last_idx = env->insn_idx;
2175 	struct bpf_func_state *func;
2176 	struct bpf_reg_state *reg;
2177 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2178 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2179 	bool skip_first = true;
2180 	bool new_marks = false;
2181 	int i, err;
2182 
2183 	if (!env->bpf_capable)
2184 		return 0;
2185 
2186 	/* Do sanity checks against current state of register and/or stack
2187 	 * slot, but don't set precise flag in current state, as precision
2188 	 * tracking in the current state is unnecessary.
2189 	 */
2190 	func = st->frame[frame];
2191 	if (regno >= 0) {
2192 		reg = &func->regs[regno];
2193 		if (reg->type != SCALAR_VALUE) {
2194 			WARN_ONCE(1, "backtracing misuse");
2195 			return -EFAULT;
2196 		}
2197 		new_marks = true;
2198 	}
2199 
2200 	while (spi >= 0) {
2201 		if (!is_spilled_reg(&func->stack[spi])) {
2202 			stack_mask = 0;
2203 			break;
2204 		}
2205 		reg = &func->stack[spi].spilled_ptr;
2206 		if (reg->type != SCALAR_VALUE) {
2207 			stack_mask = 0;
2208 			break;
2209 		}
2210 		new_marks = true;
2211 		break;
2212 	}
2213 
2214 	if (!new_marks)
2215 		return 0;
2216 	if (!reg_mask && !stack_mask)
2217 		return 0;
2218 
2219 	for (;;) {
2220 		DECLARE_BITMAP(mask, 64);
2221 		u32 history = st->jmp_history_cnt;
2222 
2223 		if (env->log.level & BPF_LOG_LEVEL)
2224 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2225 
2226 		if (last_idx < 0) {
2227 			/* we are at the entry into subprog, which
2228 			 * is expected for global funcs, but only if
2229 			 * requested precise registers are R1-R5
2230 			 * (which are global func's input arguments)
2231 			 */
2232 			if (st->curframe == 0 &&
2233 			    st->frame[0]->subprogno > 0 &&
2234 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
2235 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2236 				bitmap_from_u64(mask, reg_mask);
2237 				for_each_set_bit(i, mask, 32) {
2238 					reg = &st->frame[0]->regs[i];
2239 					if (reg->type != SCALAR_VALUE) {
2240 						reg_mask &= ~(1u << i);
2241 						continue;
2242 					}
2243 					reg->precise = true;
2244 				}
2245 				return 0;
2246 			}
2247 
2248 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2249 				st->frame[0]->subprogno, reg_mask, stack_mask);
2250 			WARN_ONCE(1, "verifier backtracking bug");
2251 			return -EFAULT;
2252 		}
2253 
2254 		for (i = last_idx;;) {
2255 			if (skip_first) {
2256 				err = 0;
2257 				skip_first = false;
2258 			} else {
2259 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2260 			}
2261 			if (err == -ENOTSUPP) {
2262 				mark_all_scalars_precise(env, st);
2263 				return 0;
2264 			} else if (err) {
2265 				return err;
2266 			}
2267 			if (!reg_mask && !stack_mask)
2268 				/* Found assignment(s) into tracked register in this state.
2269 				 * Since this state is already marked, just return.
2270 				 * Nothing to be tracked further in the parent state.
2271 				 */
2272 				return 0;
2273 			if (i == first_idx)
2274 				break;
2275 			i = get_prev_insn_idx(st, i, &history);
2276 			if (i >= env->prog->len) {
2277 				/* This can happen if backtracking reached insn 0
2278 				 * and there are still reg_mask or stack_mask
2279 				 * to backtrack.
2280 				 * It means the backtracking missed the spot where
2281 				 * particular register was initialized with a constant.
2282 				 */
2283 				verbose(env, "BUG backtracking idx %d\n", i);
2284 				WARN_ONCE(1, "verifier backtracking bug");
2285 				return -EFAULT;
2286 			}
2287 		}
2288 		st = st->parent;
2289 		if (!st)
2290 			break;
2291 
2292 		new_marks = false;
2293 		func = st->frame[frame];
2294 		bitmap_from_u64(mask, reg_mask);
2295 		for_each_set_bit(i, mask, 32) {
2296 			reg = &func->regs[i];
2297 			if (reg->type != SCALAR_VALUE) {
2298 				reg_mask &= ~(1u << i);
2299 				continue;
2300 			}
2301 			if (!reg->precise)
2302 				new_marks = true;
2303 			reg->precise = true;
2304 		}
2305 
2306 		bitmap_from_u64(mask, stack_mask);
2307 		for_each_set_bit(i, mask, 64) {
2308 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2309 				/* the sequence of instructions:
2310 				 * 2: (bf) r3 = r10
2311 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2312 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2313 				 * doesn't contain jmps. It's backtracked
2314 				 * as a single block.
2315 				 * During backtracking insn 3 is not recognized as
2316 				 * stack access, so at the end of backtracking
2317 				 * stack slot fp-8 is still marked in stack_mask.
2318 				 * However the parent state may not have accessed
2319 				 * fp-8 and it's "unallocated" stack space.
2320 				 * In such case fallback to conservative.
2321 				 */
2322 				mark_all_scalars_precise(env, st);
2323 				return 0;
2324 			}
2325 
2326 			if (!is_spilled_reg(&func->stack[i])) {
2327 				stack_mask &= ~(1ull << i);
2328 				continue;
2329 			}
2330 			reg = &func->stack[i].spilled_ptr;
2331 			if (reg->type != SCALAR_VALUE) {
2332 				stack_mask &= ~(1ull << i);
2333 				continue;
2334 			}
2335 			if (!reg->precise)
2336 				new_marks = true;
2337 			reg->precise = true;
2338 		}
2339 		if (env->log.level & BPF_LOG_LEVEL) {
2340 			print_verifier_state(env, func);
2341 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2342 				new_marks ? "didn't have" : "already had",
2343 				reg_mask, stack_mask);
2344 		}
2345 
2346 		if (!reg_mask && !stack_mask)
2347 			break;
2348 		if (!new_marks)
2349 			break;
2350 
2351 		last_idx = st->last_insn_idx;
2352 		first_idx = st->first_insn_idx;
2353 	}
2354 	return 0;
2355 }
2356 
mark_chain_precision(struct bpf_verifier_env * env,int regno)2357 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2358 {
2359 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2360 }
2361 
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2362 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2363 {
2364 	return __mark_chain_precision(env, frame, regno, -1);
2365 }
2366 
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2367 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2368 {
2369 	return __mark_chain_precision(env, frame, -1, spi);
2370 }
2371 
is_spillable_regtype(enum bpf_reg_type type)2372 static bool is_spillable_regtype(enum bpf_reg_type type)
2373 {
2374 	switch (base_type(type)) {
2375 	case PTR_TO_MAP_VALUE:
2376 	case PTR_TO_STACK:
2377 	case PTR_TO_CTX:
2378 	case PTR_TO_PACKET:
2379 	case PTR_TO_PACKET_META:
2380 	case PTR_TO_PACKET_END:
2381 	case PTR_TO_FLOW_KEYS:
2382 	case CONST_PTR_TO_MAP:
2383 	case PTR_TO_SOCKET:
2384 	case PTR_TO_SOCK_COMMON:
2385 	case PTR_TO_TCP_SOCK:
2386 	case PTR_TO_XDP_SOCK:
2387 	case PTR_TO_BTF_ID:
2388 	case PTR_TO_BUF:
2389 	case PTR_TO_PERCPU_BTF_ID:
2390 	case PTR_TO_MEM:
2391 		return true;
2392 	default:
2393 		return false;
2394 	}
2395 }
2396 
2397 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2398 static bool register_is_null(struct bpf_reg_state *reg)
2399 {
2400 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2401 }
2402 
register_is_const(struct bpf_reg_state * reg)2403 static bool register_is_const(struct bpf_reg_state *reg)
2404 {
2405 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2406 }
2407 
__is_scalar_unbounded(struct bpf_reg_state * reg)2408 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2409 {
2410 	return tnum_is_unknown(reg->var_off) &&
2411 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2412 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2413 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2414 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2415 }
2416 
register_is_bounded(struct bpf_reg_state * reg)2417 static bool register_is_bounded(struct bpf_reg_state *reg)
2418 {
2419 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2420 }
2421 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)2422 static bool __is_pointer_value(bool allow_ptr_leaks,
2423 			       const struct bpf_reg_state *reg)
2424 {
2425 	if (allow_ptr_leaks)
2426 		return false;
2427 
2428 	return reg->type != SCALAR_VALUE;
2429 }
2430 
2431 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)2432 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2433 {
2434 	struct bpf_reg_state *parent = dst->parent;
2435 	enum bpf_reg_liveness live = dst->live;
2436 
2437 	*dst = *src;
2438 	dst->parent = parent;
2439 	dst->live = live;
2440 }
2441 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)2442 static void save_register_state(struct bpf_func_state *state,
2443 				int spi, struct bpf_reg_state *reg,
2444 				int size)
2445 {
2446 	int i;
2447 
2448 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
2449 	if (size == BPF_REG_SIZE)
2450 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2451 
2452 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2453 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2454 
2455 	/* size < 8 bytes spill */
2456 	for (; i; i--)
2457 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2458 }
2459 
is_bpf_st_mem(struct bpf_insn * insn)2460 static bool is_bpf_st_mem(struct bpf_insn *insn)
2461 {
2462 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
2463 }
2464 
2465 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2466  * stack boundary and alignment are checked in check_mem_access()
2467  */
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)2468 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2469 				       /* stack frame we're writing to */
2470 				       struct bpf_func_state *state,
2471 				       int off, int size, int value_regno,
2472 				       int insn_idx)
2473 {
2474 	struct bpf_func_state *cur; /* state of the current function */
2475 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2476 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
2477 	struct bpf_reg_state *reg = NULL;
2478 	u32 dst_reg = insn->dst_reg;
2479 
2480 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2481 				 state->acquired_refs, true);
2482 	if (err)
2483 		return err;
2484 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2485 	 * so it's aligned access and [off, off + size) are within stack limits
2486 	 */
2487 	if (!env->allow_ptr_leaks &&
2488 	    is_spilled_reg(&state->stack[spi]) &&
2489 	    size != BPF_REG_SIZE) {
2490 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2491 		return -EACCES;
2492 	}
2493 
2494 	cur = env->cur_state->frame[env->cur_state->curframe];
2495 	if (value_regno >= 0)
2496 		reg = &cur->regs[value_regno];
2497 	if (!env->bypass_spec_v4) {
2498 		bool sanitize = reg && is_spillable_regtype(reg->type);
2499 
2500 		for (i = 0; i < size; i++) {
2501 			u8 type = state->stack[spi].slot_type[i];
2502 
2503 			if (type != STACK_MISC && type != STACK_ZERO) {
2504 				sanitize = true;
2505 				break;
2506 			}
2507 		}
2508 
2509 		if (sanitize)
2510 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2511 	}
2512 
2513 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2514 	    !register_is_null(reg) && env->bpf_capable) {
2515 		if (dst_reg != BPF_REG_FP) {
2516 			/* The backtracking logic can only recognize explicit
2517 			 * stack slot address like [fp - 8]. Other spill of
2518 			 * scalar via different register has to be conervative.
2519 			 * Backtrack from here and mark all registers as precise
2520 			 * that contributed into 'reg' being a constant.
2521 			 */
2522 			err = mark_chain_precision(env, value_regno);
2523 			if (err)
2524 				return err;
2525 		}
2526 		save_register_state(state, spi, reg, size);
2527 		/* Break the relation on a narrowing spill. */
2528 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
2529 			state->stack[spi].spilled_ptr.id = 0;
2530 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
2531 		   insn->imm != 0 && env->bpf_capable) {
2532 		struct bpf_reg_state fake_reg = {};
2533 
2534 		__mark_reg_known(&fake_reg, insn->imm);
2535 		fake_reg.type = SCALAR_VALUE;
2536 		save_register_state(state, spi, &fake_reg, size);
2537 	} else if (reg && is_spillable_regtype(reg->type)) {
2538 		/* register containing pointer is being spilled into stack */
2539 		if (size != BPF_REG_SIZE) {
2540 			verbose_linfo(env, insn_idx, "; ");
2541 			verbose(env, "invalid size of register spill\n");
2542 			return -EACCES;
2543 		}
2544 		if (state != cur && reg->type == PTR_TO_STACK) {
2545 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2546 			return -EINVAL;
2547 		}
2548 		save_register_state(state, spi, reg, size);
2549 	} else {
2550 		u8 type = STACK_MISC;
2551 
2552 		/* regular write of data into stack destroys any spilled ptr */
2553 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2554 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2555 		if (is_spilled_reg(&state->stack[spi]))
2556 			for (i = 0; i < BPF_REG_SIZE; i++)
2557 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2558 
2559 		/* only mark the slot as written if all 8 bytes were written
2560 		 * otherwise read propagation may incorrectly stop too soon
2561 		 * when stack slots are partially written.
2562 		 * This heuristic means that read propagation will be
2563 		 * conservative, since it will add reg_live_read marks
2564 		 * to stack slots all the way to first state when programs
2565 		 * writes+reads less than 8 bytes
2566 		 */
2567 		if (size == BPF_REG_SIZE)
2568 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2569 
2570 		/* when we zero initialize stack slots mark them as such */
2571 		if ((reg && register_is_null(reg)) ||
2572 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
2573 			/* backtracking doesn't work for STACK_ZERO yet. */
2574 			err = mark_chain_precision(env, value_regno);
2575 			if (err)
2576 				return err;
2577 			type = STACK_ZERO;
2578 		}
2579 
2580 		/* Mark slots affected by this stack write. */
2581 		for (i = 0; i < size; i++)
2582 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2583 				type;
2584 	}
2585 	return 0;
2586 }
2587 
2588 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2589  * known to contain a variable offset.
2590  * This function checks whether the write is permitted and conservatively
2591  * tracks the effects of the write, considering that each stack slot in the
2592  * dynamic range is potentially written to.
2593  *
2594  * 'off' includes 'regno->off'.
2595  * 'value_regno' can be -1, meaning that an unknown value is being written to
2596  * the stack.
2597  *
2598  * Spilled pointers in range are not marked as written because we don't know
2599  * what's going to be actually written. This means that read propagation for
2600  * future reads cannot be terminated by this write.
2601  *
2602  * For privileged programs, uninitialized stack slots are considered
2603  * initialized by this write (even though we don't know exactly what offsets
2604  * are going to be written to). The idea is that we don't want the verifier to
2605  * reject future reads that access slots written to through variable offsets.
2606  */
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)2607 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2608 				     /* func where register points to */
2609 				     struct bpf_func_state *state,
2610 				     int ptr_regno, int off, int size,
2611 				     int value_regno, int insn_idx)
2612 {
2613 	struct bpf_func_state *cur; /* state of the current function */
2614 	int min_off, max_off;
2615 	int i, err;
2616 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2617 	bool writing_zero = false;
2618 	/* set if the fact that we're writing a zero is used to let any
2619 	 * stack slots remain STACK_ZERO
2620 	 */
2621 	bool zero_used = false;
2622 
2623 	cur = env->cur_state->frame[env->cur_state->curframe];
2624 	ptr_reg = &cur->regs[ptr_regno];
2625 	min_off = ptr_reg->smin_value + off;
2626 	max_off = ptr_reg->smax_value + off + size;
2627 	if (value_regno >= 0)
2628 		value_reg = &cur->regs[value_regno];
2629 	if (value_reg && register_is_null(value_reg))
2630 		writing_zero = true;
2631 
2632 	err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2633 				 state->acquired_refs, true);
2634 	if (err)
2635 		return err;
2636 
2637 
2638 	/* Variable offset writes destroy any spilled pointers in range. */
2639 	for (i = min_off; i < max_off; i++) {
2640 		u8 new_type, *stype;
2641 		int slot, spi;
2642 
2643 		slot = -i - 1;
2644 		spi = slot / BPF_REG_SIZE;
2645 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2646 
2647 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
2648 			/* Reject the write if range we may write to has not
2649 			 * been initialized beforehand. If we didn't reject
2650 			 * here, the ptr status would be erased below (even
2651 			 * though not all slots are actually overwritten),
2652 			 * possibly opening the door to leaks.
2653 			 *
2654 			 * We do however catch STACK_INVALID case below, and
2655 			 * only allow reading possibly uninitialized memory
2656 			 * later for CAP_PERFMON, as the write may not happen to
2657 			 * that slot.
2658 			 */
2659 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2660 				insn_idx, i);
2661 			return -EINVAL;
2662 		}
2663 
2664 		/* Erase all spilled pointers. */
2665 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2666 
2667 		/* Update the slot type. */
2668 		new_type = STACK_MISC;
2669 		if (writing_zero && *stype == STACK_ZERO) {
2670 			new_type = STACK_ZERO;
2671 			zero_used = true;
2672 		}
2673 		/* If the slot is STACK_INVALID, we check whether it's OK to
2674 		 * pretend that it will be initialized by this write. The slot
2675 		 * might not actually be written to, and so if we mark it as
2676 		 * initialized future reads might leak uninitialized memory.
2677 		 * For privileged programs, we will accept such reads to slots
2678 		 * that may or may not be written because, if we're reject
2679 		 * them, the error would be too confusing.
2680 		 */
2681 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2682 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2683 					insn_idx, i);
2684 			return -EINVAL;
2685 		}
2686 		*stype = new_type;
2687 	}
2688 	if (zero_used) {
2689 		/* backtracking doesn't work for STACK_ZERO yet. */
2690 		err = mark_chain_precision(env, value_regno);
2691 		if (err)
2692 			return err;
2693 	}
2694 	return 0;
2695 }
2696 
2697 /* When register 'dst_regno' is assigned some values from stack[min_off,
2698  * max_off), we set the register's type according to the types of the
2699  * respective stack slots. If all the stack values are known to be zeros, then
2700  * so is the destination reg. Otherwise, the register is considered to be
2701  * SCALAR. This function does not deal with register filling; the caller must
2702  * ensure that all spilled registers in the stack range have been marked as
2703  * read.
2704  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)2705 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2706 				/* func where src register points to */
2707 				struct bpf_func_state *ptr_state,
2708 				int min_off, int max_off, int dst_regno)
2709 {
2710 	struct bpf_verifier_state *vstate = env->cur_state;
2711 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2712 	int i, slot, spi;
2713 	u8 *stype;
2714 	int zeros = 0;
2715 
2716 	for (i = min_off; i < max_off; i++) {
2717 		slot = -i - 1;
2718 		spi = slot / BPF_REG_SIZE;
2719 		stype = ptr_state->stack[spi].slot_type;
2720 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2721 			break;
2722 		zeros++;
2723 	}
2724 	if (zeros == max_off - min_off) {
2725 		/* any access_size read into register is zero extended,
2726 		 * so the whole register == const_zero
2727 		 */
2728 		__mark_reg_const_zero(&state->regs[dst_regno]);
2729 		/* backtracking doesn't support STACK_ZERO yet,
2730 		 * so mark it precise here, so that later
2731 		 * backtracking can stop here.
2732 		 * Backtracking may not need this if this register
2733 		 * doesn't participate in pointer adjustment.
2734 		 * Forward propagation of precise flag is not
2735 		 * necessary either. This mark is only to stop
2736 		 * backtracking. Any register that contributed
2737 		 * to const 0 was marked precise before spill.
2738 		 */
2739 		state->regs[dst_regno].precise = true;
2740 	} else {
2741 		/* have read misc data from the stack */
2742 		mark_reg_unknown(env, state->regs, dst_regno);
2743 	}
2744 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2745 }
2746 
2747 /* Read the stack at 'off' and put the results into the register indicated by
2748  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2749  * spilled reg.
2750  *
2751  * 'dst_regno' can be -1, meaning that the read value is not going to a
2752  * register.
2753  *
2754  * The access is assumed to be within the current stack bounds.
2755  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)2756 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2757 				      /* func where src register points to */
2758 				      struct bpf_func_state *reg_state,
2759 				      int off, int size, int dst_regno)
2760 {
2761 	struct bpf_verifier_state *vstate = env->cur_state;
2762 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2763 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2764 	struct bpf_reg_state *reg;
2765 	u8 *stype, type;
2766 
2767 	stype = reg_state->stack[spi].slot_type;
2768 	reg = &reg_state->stack[spi].spilled_ptr;
2769 
2770 	if (is_spilled_reg(&reg_state->stack[spi])) {
2771 		u8 spill_size = 1;
2772 
2773 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
2774 			spill_size++;
2775 
2776 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
2777 			if (reg->type != SCALAR_VALUE) {
2778 				verbose_linfo(env, env->insn_idx, "; ");
2779 				verbose(env, "invalid size of register fill\n");
2780 				return -EACCES;
2781 			}
2782 
2783 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2784 			if (dst_regno < 0)
2785 				return 0;
2786 
2787 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
2788 				/* The earlier check_reg_arg() has decided the
2789 				 * subreg_def for this insn.  Save it first.
2790 				 */
2791 				s32 subreg_def = state->regs[dst_regno].subreg_def;
2792 
2793 				copy_register_state(&state->regs[dst_regno], reg);
2794 				state->regs[dst_regno].subreg_def = subreg_def;
2795 			} else {
2796 				for (i = 0; i < size; i++) {
2797 					type = stype[(slot - i) % BPF_REG_SIZE];
2798 					if (type == STACK_SPILL)
2799 						continue;
2800 					if (type == STACK_MISC)
2801 						continue;
2802 					verbose(env, "invalid read from stack off %d+%d size %d\n",
2803 						off, i, size);
2804 					return -EACCES;
2805 				}
2806 				mark_reg_unknown(env, state->regs, dst_regno);
2807 			}
2808 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2809 			return 0;
2810 		}
2811 
2812 		if (dst_regno >= 0) {
2813 			/* restore register state from stack */
2814 			copy_register_state(&state->regs[dst_regno], reg);
2815 			/* mark reg as written since spilled pointer state likely
2816 			 * has its liveness marks cleared by is_state_visited()
2817 			 * which resets stack/reg liveness for state transitions
2818 			 */
2819 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2820 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2821 			/* If dst_regno==-1, the caller is asking us whether
2822 			 * it is acceptable to use this value as a SCALAR_VALUE
2823 			 * (e.g. for XADD).
2824 			 * We must not allow unprivileged callers to do that
2825 			 * with spilled pointers.
2826 			 */
2827 			verbose(env, "leaking pointer from stack off %d\n",
2828 				off);
2829 			return -EACCES;
2830 		}
2831 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2832 	} else {
2833 		for (i = 0; i < size; i++) {
2834 			type = stype[(slot - i) % BPF_REG_SIZE];
2835 			if (type == STACK_MISC)
2836 				continue;
2837 			if (type == STACK_ZERO)
2838 				continue;
2839 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2840 				off, i, size);
2841 			return -EACCES;
2842 		}
2843 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2844 		if (dst_regno >= 0)
2845 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2846 	}
2847 	return 0;
2848 }
2849 
2850 enum stack_access_src {
2851 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2852 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
2853 };
2854 
2855 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2856 					 int regno, int off, int access_size,
2857 					 bool zero_size_allowed,
2858 					 enum stack_access_src type,
2859 					 struct bpf_call_arg_meta *meta);
2860 
reg_state(struct bpf_verifier_env * env,int regno)2861 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2862 {
2863 	return cur_regs(env) + regno;
2864 }
2865 
2866 /* Read the stack at 'ptr_regno + off' and put the result into the register
2867  * 'dst_regno'.
2868  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2869  * but not its variable offset.
2870  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2871  *
2872  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2873  * filling registers (i.e. reads of spilled register cannot be detected when
2874  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2875  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2876  * offset; for a fixed offset check_stack_read_fixed_off should be used
2877  * instead.
2878  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2879 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2880 				    int ptr_regno, int off, int size, int dst_regno)
2881 {
2882 	/* The state of the source register. */
2883 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2884 	struct bpf_func_state *ptr_state = func(env, reg);
2885 	int err;
2886 	int min_off, max_off;
2887 
2888 	/* Note that we pass a NULL meta, so raw access will not be permitted.
2889 	 */
2890 	err = check_stack_range_initialized(env, ptr_regno, off, size,
2891 					    false, ACCESS_DIRECT, NULL);
2892 	if (err)
2893 		return err;
2894 
2895 	min_off = reg->smin_value + off;
2896 	max_off = reg->smax_value + off;
2897 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2898 	return 0;
2899 }
2900 
2901 /* check_stack_read dispatches to check_stack_read_fixed_off or
2902  * check_stack_read_var_off.
2903  *
2904  * The caller must ensure that the offset falls within the allocated stack
2905  * bounds.
2906  *
2907  * 'dst_regno' is a register which will receive the value from the stack. It
2908  * can be -1, meaning that the read value is not going to a register.
2909  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2910 static int check_stack_read(struct bpf_verifier_env *env,
2911 			    int ptr_regno, int off, int size,
2912 			    int dst_regno)
2913 {
2914 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2915 	struct bpf_func_state *state = func(env, reg);
2916 	int err;
2917 	/* Some accesses are only permitted with a static offset. */
2918 	bool var_off = !tnum_is_const(reg->var_off);
2919 
2920 	/* The offset is required to be static when reads don't go to a
2921 	 * register, in order to not leak pointers (see
2922 	 * check_stack_read_fixed_off).
2923 	 */
2924 	if (dst_regno < 0 && var_off) {
2925 		char tn_buf[48];
2926 
2927 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2928 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2929 			tn_buf, off, size);
2930 		return -EACCES;
2931 	}
2932 	/* Variable offset is prohibited for unprivileged mode for simplicity
2933 	 * since it requires corresponding support in Spectre masking for stack
2934 	 * ALU. See also retrieve_ptr_limit(). The check in
2935 	 * check_stack_access_for_ptr_arithmetic() called by
2936 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
2937 	 * with variable offsets, therefore no check is required here. Further,
2938 	 * just checking it here would be insufficient as speculative stack
2939 	 * writes could still lead to unsafe speculative behaviour.
2940 	 */
2941 	if (!var_off) {
2942 		off += reg->var_off.value;
2943 		err = check_stack_read_fixed_off(env, state, off, size,
2944 						 dst_regno);
2945 	} else {
2946 		/* Variable offset stack reads need more conservative handling
2947 		 * than fixed offset ones. Note that dst_regno >= 0 on this
2948 		 * branch.
2949 		 */
2950 		err = check_stack_read_var_off(env, ptr_regno, off, size,
2951 					       dst_regno);
2952 	}
2953 	return err;
2954 }
2955 
2956 
2957 /* check_stack_write dispatches to check_stack_write_fixed_off or
2958  * check_stack_write_var_off.
2959  *
2960  * 'ptr_regno' is the register used as a pointer into the stack.
2961  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2962  * 'value_regno' is the register whose value we're writing to the stack. It can
2963  * be -1, meaning that we're not writing from a register.
2964  *
2965  * The caller must ensure that the offset falls within the maximum stack size.
2966  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)2967 static int check_stack_write(struct bpf_verifier_env *env,
2968 			     int ptr_regno, int off, int size,
2969 			     int value_regno, int insn_idx)
2970 {
2971 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2972 	struct bpf_func_state *state = func(env, reg);
2973 	int err;
2974 
2975 	if (tnum_is_const(reg->var_off)) {
2976 		off += reg->var_off.value;
2977 		err = check_stack_write_fixed_off(env, state, off, size,
2978 						  value_regno, insn_idx);
2979 	} else {
2980 		/* Variable offset stack reads need more conservative handling
2981 		 * than fixed offset ones.
2982 		 */
2983 		err = check_stack_write_var_off(env, state,
2984 						ptr_regno, off, size,
2985 						value_regno, insn_idx);
2986 	}
2987 	return err;
2988 }
2989 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)2990 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2991 				 int off, int size, enum bpf_access_type type)
2992 {
2993 	struct bpf_reg_state *regs = cur_regs(env);
2994 	struct bpf_map *map = regs[regno].map_ptr;
2995 	u32 cap = bpf_map_flags_to_cap(map);
2996 
2997 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2998 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2999 			map->value_size, off, size);
3000 		return -EACCES;
3001 	}
3002 
3003 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3004 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3005 			map->value_size, off, size);
3006 		return -EACCES;
3007 	}
3008 
3009 	return 0;
3010 }
3011 
3012 /* 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)3013 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3014 			      int off, int size, u32 mem_size,
3015 			      bool zero_size_allowed)
3016 {
3017 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3018 	struct bpf_reg_state *reg;
3019 
3020 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3021 		return 0;
3022 
3023 	reg = &cur_regs(env)[regno];
3024 	switch (reg->type) {
3025 	case PTR_TO_MAP_VALUE:
3026 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3027 			mem_size, off, size);
3028 		break;
3029 	case PTR_TO_PACKET:
3030 	case PTR_TO_PACKET_META:
3031 	case PTR_TO_PACKET_END:
3032 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3033 			off, size, regno, reg->id, off, mem_size);
3034 		break;
3035 	case PTR_TO_MEM:
3036 	default:
3037 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3038 			mem_size, off, size);
3039 	}
3040 
3041 	return -EACCES;
3042 }
3043 
3044 /* 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)3045 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3046 				   int off, int size, u32 mem_size,
3047 				   bool zero_size_allowed)
3048 {
3049 	struct bpf_verifier_state *vstate = env->cur_state;
3050 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3051 	struct bpf_reg_state *reg = &state->regs[regno];
3052 	int err;
3053 
3054 	/* We may have adjusted the register pointing to memory region, so we
3055 	 * need to try adding each of min_value and max_value to off
3056 	 * to make sure our theoretical access will be safe.
3057 	 */
3058 	if (env->log.level & BPF_LOG_LEVEL)
3059 		print_verifier_state(env, state);
3060 
3061 	/* The minimum value is only important with signed
3062 	 * comparisons where we can't assume the floor of a
3063 	 * value is 0.  If we are using signed variables for our
3064 	 * index'es we need to make sure that whatever we use
3065 	 * will have a set floor within our range.
3066 	 */
3067 	if (reg->smin_value < 0 &&
3068 	    (reg->smin_value == S64_MIN ||
3069 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3070 	      reg->smin_value + off < 0)) {
3071 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3072 			regno);
3073 		return -EACCES;
3074 	}
3075 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3076 				 mem_size, zero_size_allowed);
3077 	if (err) {
3078 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3079 			regno);
3080 		return err;
3081 	}
3082 
3083 	/* If we haven't set a max value then we need to bail since we can't be
3084 	 * sure we won't do bad things.
3085 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3086 	 */
3087 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3088 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3089 			regno);
3090 		return -EACCES;
3091 	}
3092 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3093 				 mem_size, zero_size_allowed);
3094 	if (err) {
3095 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3096 			regno);
3097 		return err;
3098 	}
3099 
3100 	return 0;
3101 }
3102 
3103 /* 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)3104 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3105 			    int off, int size, bool zero_size_allowed)
3106 {
3107 	struct bpf_verifier_state *vstate = env->cur_state;
3108 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3109 	struct bpf_reg_state *reg = &state->regs[regno];
3110 	struct bpf_map *map = reg->map_ptr;
3111 	int err;
3112 
3113 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3114 				      zero_size_allowed);
3115 	if (err)
3116 		return err;
3117 
3118 	if (map_value_has_spin_lock(map)) {
3119 		u32 lock = map->spin_lock_off;
3120 
3121 		/* if any part of struct bpf_spin_lock can be touched by
3122 		 * load/store reject this program.
3123 		 * To check that [x1, x2) overlaps with [y1, y2)
3124 		 * it is sufficient to check x1 < y2 && y1 < x2.
3125 		 */
3126 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3127 		     lock < reg->umax_value + off + size) {
3128 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3129 			return -EACCES;
3130 		}
3131 	}
3132 	return err;
3133 }
3134 
3135 #define MAX_PACKET_OFF 0xffff
3136 
resolve_prog_type(struct bpf_prog * prog)3137 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3138 {
3139 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3140 }
3141 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)3142 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3143 				       const struct bpf_call_arg_meta *meta,
3144 				       enum bpf_access_type t)
3145 {
3146 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3147 
3148 	switch (prog_type) {
3149 	/* Program types only with direct read access go here! */
3150 	case BPF_PROG_TYPE_LWT_IN:
3151 	case BPF_PROG_TYPE_LWT_OUT:
3152 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3153 	case BPF_PROG_TYPE_SK_REUSEPORT:
3154 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3155 	case BPF_PROG_TYPE_CGROUP_SKB:
3156 		if (t == BPF_WRITE)
3157 			return false;
3158 		fallthrough;
3159 
3160 	/* Program types with direct read + write access go here! */
3161 	case BPF_PROG_TYPE_SCHED_CLS:
3162 	case BPF_PROG_TYPE_SCHED_ACT:
3163 	case BPF_PROG_TYPE_XDP:
3164 	case BPF_PROG_TYPE_LWT_XMIT:
3165 	case BPF_PROG_TYPE_SK_SKB:
3166 	case BPF_PROG_TYPE_SK_MSG:
3167 		if (meta)
3168 			return meta->pkt_access;
3169 
3170 		env->seen_direct_write = true;
3171 		return true;
3172 
3173 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3174 		if (t == BPF_WRITE)
3175 			env->seen_direct_write = true;
3176 
3177 		return true;
3178 
3179 	default:
3180 		return false;
3181 	}
3182 }
3183 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)3184 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3185 			       int size, bool zero_size_allowed)
3186 {
3187 	struct bpf_reg_state *regs = cur_regs(env);
3188 	struct bpf_reg_state *reg = &regs[regno];
3189 	int err;
3190 
3191 	/* We may have added a variable offset to the packet pointer; but any
3192 	 * reg->range we have comes after that.  We are only checking the fixed
3193 	 * offset.
3194 	 */
3195 
3196 	/* We don't allow negative numbers, because we aren't tracking enough
3197 	 * detail to prove they're safe.
3198 	 */
3199 	if (reg->smin_value < 0) {
3200 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3201 			regno);
3202 		return -EACCES;
3203 	}
3204 
3205 	err = reg->range < 0 ? -EINVAL :
3206 	      __check_mem_access(env, regno, off, size, reg->range,
3207 				 zero_size_allowed);
3208 	if (err) {
3209 		verbose(env, "R%d offset is outside of the packet\n", regno);
3210 		return err;
3211 	}
3212 
3213 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3214 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3215 	 * otherwise find_good_pkt_pointers would have refused to set range info
3216 	 * that __check_mem_access would have rejected this pkt access.
3217 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3218 	 */
3219 	env->prog->aux->max_pkt_offset =
3220 		max_t(u32, env->prog->aux->max_pkt_offset,
3221 		      off + reg->umax_value + size - 1);
3222 
3223 	return err;
3224 }
3225 
3226 /* 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,u32 * btf_id)3227 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3228 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3229 			    u32 *btf_id)
3230 {
3231 	struct bpf_insn_access_aux info = {
3232 		.reg_type = *reg_type,
3233 		.log = &env->log,
3234 	};
3235 
3236 	if (env->ops->is_valid_access &&
3237 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3238 		/* A non zero info.ctx_field_size indicates that this field is a
3239 		 * candidate for later verifier transformation to load the whole
3240 		 * field and then apply a mask when accessed with a narrower
3241 		 * access than actual ctx access size. A zero info.ctx_field_size
3242 		 * will only allow for whole field access and rejects any other
3243 		 * type of narrower access.
3244 		 */
3245 		*reg_type = info.reg_type;
3246 
3247 		if (base_type(*reg_type) == PTR_TO_BTF_ID)
3248 			*btf_id = info.btf_id;
3249 		else
3250 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3251 		/* remember the offset of last byte accessed in ctx */
3252 		if (env->prog->aux->max_ctx_offset < off + size)
3253 			env->prog->aux->max_ctx_offset = off + size;
3254 		return 0;
3255 	}
3256 
3257 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3258 	return -EACCES;
3259 }
3260 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)3261 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3262 				  int size)
3263 {
3264 	if (size < 0 || off < 0 ||
3265 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3266 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3267 			off, size);
3268 		return -EACCES;
3269 	}
3270 	return 0;
3271 }
3272 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)3273 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3274 			     u32 regno, int off, int size,
3275 			     enum bpf_access_type t)
3276 {
3277 	struct bpf_reg_state *regs = cur_regs(env);
3278 	struct bpf_reg_state *reg = &regs[regno];
3279 	struct bpf_insn_access_aux info = {};
3280 	bool valid;
3281 
3282 	if (reg->smin_value < 0) {
3283 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3284 			regno);
3285 		return -EACCES;
3286 	}
3287 
3288 	switch (reg->type) {
3289 	case PTR_TO_SOCK_COMMON:
3290 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3291 		break;
3292 	case PTR_TO_SOCKET:
3293 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3294 		break;
3295 	case PTR_TO_TCP_SOCK:
3296 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3297 		break;
3298 	case PTR_TO_XDP_SOCK:
3299 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3300 		break;
3301 	default:
3302 		valid = false;
3303 	}
3304 
3305 
3306 	if (valid) {
3307 		env->insn_aux_data[insn_idx].ctx_field_size =
3308 			info.ctx_field_size;
3309 		return 0;
3310 	}
3311 
3312 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3313 		regno, reg_type_str(env, reg->type), off, size);
3314 
3315 	return -EACCES;
3316 }
3317 
is_pointer_value(struct bpf_verifier_env * env,int regno)3318 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3319 {
3320 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3321 }
3322 
is_ctx_reg(struct bpf_verifier_env * env,int regno)3323 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3324 {
3325 	const struct bpf_reg_state *reg = reg_state(env, regno);
3326 
3327 	return reg->type == PTR_TO_CTX;
3328 }
3329 
is_sk_reg(struct bpf_verifier_env * env,int regno)3330 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3331 {
3332 	const struct bpf_reg_state *reg = reg_state(env, regno);
3333 
3334 	return type_is_sk_pointer(reg->type);
3335 }
3336 
is_pkt_reg(struct bpf_verifier_env * env,int regno)3337 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3338 {
3339 	const struct bpf_reg_state *reg = reg_state(env, regno);
3340 
3341 	return type_is_pkt_pointer(reg->type);
3342 }
3343 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)3344 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3345 {
3346 	const struct bpf_reg_state *reg = reg_state(env, regno);
3347 
3348 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3349 	return reg->type == PTR_TO_FLOW_KEYS;
3350 }
3351 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)3352 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3353 				   const struct bpf_reg_state *reg,
3354 				   int off, int size, bool strict)
3355 {
3356 	struct tnum reg_off;
3357 	int ip_align;
3358 
3359 	/* Byte size accesses are always allowed. */
3360 	if (!strict || size == 1)
3361 		return 0;
3362 
3363 	/* For platforms that do not have a Kconfig enabling
3364 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3365 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3366 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3367 	 * to this code only in strict mode where we want to emulate
3368 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3369 	 * unconditional IP align value of '2'.
3370 	 */
3371 	ip_align = 2;
3372 
3373 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3374 	if (!tnum_is_aligned(reg_off, size)) {
3375 		char tn_buf[48];
3376 
3377 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3378 		verbose(env,
3379 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3380 			ip_align, tn_buf, reg->off, off, size);
3381 		return -EACCES;
3382 	}
3383 
3384 	return 0;
3385 }
3386 
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)3387 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3388 				       const struct bpf_reg_state *reg,
3389 				       const char *pointer_desc,
3390 				       int off, int size, bool strict)
3391 {
3392 	struct tnum reg_off;
3393 
3394 	/* Byte size accesses are always allowed. */
3395 	if (!strict || size == 1)
3396 		return 0;
3397 
3398 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3399 	if (!tnum_is_aligned(reg_off, size)) {
3400 		char tn_buf[48];
3401 
3402 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3403 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3404 			pointer_desc, tn_buf, reg->off, off, size);
3405 		return -EACCES;
3406 	}
3407 
3408 	return 0;
3409 }
3410 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)3411 static int check_ptr_alignment(struct bpf_verifier_env *env,
3412 			       const struct bpf_reg_state *reg, int off,
3413 			       int size, bool strict_alignment_once)
3414 {
3415 	bool strict = env->strict_alignment || strict_alignment_once;
3416 	const char *pointer_desc = "";
3417 
3418 	switch (reg->type) {
3419 	case PTR_TO_PACKET:
3420 	case PTR_TO_PACKET_META:
3421 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3422 		 * right in front, treat it the very same way.
3423 		 */
3424 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3425 	case PTR_TO_FLOW_KEYS:
3426 		pointer_desc = "flow keys ";
3427 		break;
3428 	case PTR_TO_MAP_VALUE:
3429 		pointer_desc = "value ";
3430 		break;
3431 	case PTR_TO_CTX:
3432 		pointer_desc = "context ";
3433 		break;
3434 	case PTR_TO_STACK:
3435 		pointer_desc = "stack ";
3436 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3437 		 * and check_stack_read_fixed_off() relies on stack accesses being
3438 		 * aligned.
3439 		 */
3440 		strict = true;
3441 		break;
3442 	case PTR_TO_SOCKET:
3443 		pointer_desc = "sock ";
3444 		break;
3445 	case PTR_TO_SOCK_COMMON:
3446 		pointer_desc = "sock_common ";
3447 		break;
3448 	case PTR_TO_TCP_SOCK:
3449 		pointer_desc = "tcp_sock ";
3450 		break;
3451 	case PTR_TO_XDP_SOCK:
3452 		pointer_desc = "xdp_sock ";
3453 		break;
3454 	default:
3455 		break;
3456 	}
3457 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3458 					   strict);
3459 }
3460 
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)3461 static int update_stack_depth(struct bpf_verifier_env *env,
3462 			      const struct bpf_func_state *func,
3463 			      int off)
3464 {
3465 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3466 
3467 	if (stack >= -off)
3468 		return 0;
3469 
3470 	/* update known max for given subprogram */
3471 	env->subprog_info[func->subprogno].stack_depth = -off;
3472 	return 0;
3473 }
3474 
3475 /* starting from main bpf function walk all instructions of the function
3476  * and recursively walk all callees that given function can call.
3477  * Ignore jump and exit insns.
3478  * Since recursion is prevented by check_cfg() this algorithm
3479  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3480  */
check_max_stack_depth(struct bpf_verifier_env * env)3481 static int check_max_stack_depth(struct bpf_verifier_env *env)
3482 {
3483 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3484 	struct bpf_subprog_info *subprog = env->subprog_info;
3485 	struct bpf_insn *insn = env->prog->insnsi;
3486 	bool tail_call_reachable = false;
3487 	int ret_insn[MAX_CALL_FRAMES];
3488 	int ret_prog[MAX_CALL_FRAMES];
3489 	int j;
3490 
3491 process_func:
3492 	/* protect against potential stack overflow that might happen when
3493 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3494 	 * depth for such case down to 256 so that the worst case scenario
3495 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3496 	 * 8k).
3497 	 *
3498 	 * To get the idea what might happen, see an example:
3499 	 * func1 -> sub rsp, 128
3500 	 *  subfunc1 -> sub rsp, 256
3501 	 *  tailcall1 -> add rsp, 256
3502 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3503 	 *   subfunc2 -> sub rsp, 64
3504 	 *   subfunc22 -> sub rsp, 128
3505 	 *   tailcall2 -> add rsp, 128
3506 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3507 	 *
3508 	 * tailcall will unwind the current stack frame but it will not get rid
3509 	 * of caller's stack as shown on the example above.
3510 	 */
3511 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3512 		verbose(env,
3513 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3514 			depth);
3515 		return -EACCES;
3516 	}
3517 	/* round up to 32-bytes, since this is granularity
3518 	 * of interpreter stack size
3519 	 */
3520 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3521 	if (depth > MAX_BPF_STACK) {
3522 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3523 			frame + 1, depth);
3524 		return -EACCES;
3525 	}
3526 continue_func:
3527 	subprog_end = subprog[idx + 1].start;
3528 	for (; i < subprog_end; i++) {
3529 		if (insn[i].code != (BPF_JMP | BPF_CALL))
3530 			continue;
3531 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
3532 			continue;
3533 		/* remember insn and function to return to */
3534 		ret_insn[frame] = i + 1;
3535 		ret_prog[frame] = idx;
3536 
3537 		/* find the callee */
3538 		i = i + insn[i].imm + 1;
3539 		idx = find_subprog(env, i);
3540 		if (idx < 0) {
3541 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3542 				  i);
3543 			return -EFAULT;
3544 		}
3545 
3546 		if (subprog[idx].has_tail_call)
3547 			tail_call_reachable = true;
3548 
3549 		frame++;
3550 		if (frame >= MAX_CALL_FRAMES) {
3551 			verbose(env, "the call stack of %d frames is too deep !\n",
3552 				frame);
3553 			return -E2BIG;
3554 		}
3555 		goto process_func;
3556 	}
3557 	/* if tail call got detected across bpf2bpf calls then mark each of the
3558 	 * currently present subprog frames as tail call reachable subprogs;
3559 	 * this info will be utilized by JIT so that we will be preserving the
3560 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3561 	 */
3562 	if (tail_call_reachable)
3563 		for (j = 0; j < frame; j++)
3564 			subprog[ret_prog[j]].tail_call_reachable = true;
3565 	if (subprog[0].tail_call_reachable)
3566 		env->prog->aux->tail_call_reachable = true;
3567 
3568 	/* end of for() loop means the last insn of the 'subprog'
3569 	 * was reached. Doesn't matter whether it was JA or EXIT
3570 	 */
3571 	if (frame == 0)
3572 		return 0;
3573 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3574 	frame--;
3575 	i = ret_insn[frame];
3576 	idx = ret_prog[frame];
3577 	goto continue_func;
3578 }
3579 
3580 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)3581 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3582 				  const struct bpf_insn *insn, int idx)
3583 {
3584 	int start = idx + insn->imm + 1, subprog;
3585 
3586 	subprog = find_subprog(env, start);
3587 	if (subprog < 0) {
3588 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3589 			  start);
3590 		return -EFAULT;
3591 	}
3592 	return env->subprog_info[subprog].stack_depth;
3593 }
3594 #endif
3595 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)3596 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3597 			       const struct bpf_reg_state *reg, int regno,
3598 			       bool fixed_off_ok)
3599 {
3600 	/* Access to this pointer-typed register or passing it to a helper
3601 	 * is only allowed in its original, unmodified form.
3602 	 */
3603 
3604 	if (!fixed_off_ok && reg->off) {
3605 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3606 			reg_type_str(env, reg->type), regno, reg->off);
3607 		return -EACCES;
3608 	}
3609 
3610 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3611 		char tn_buf[48];
3612 
3613 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3614 		verbose(env, "variable %s access var_off=%s disallowed\n",
3615 			reg_type_str(env, reg->type), tn_buf);
3616 		return -EACCES;
3617 	}
3618 
3619 	return 0;
3620 }
3621 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3622 int check_ptr_off_reg(struct bpf_verifier_env *env,
3623 		      const struct bpf_reg_state *reg, int regno)
3624 {
3625 	return __check_ptr_off_reg(env, reg, regno, false);
3626 }
3627 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)3628 static int __check_buffer_access(struct bpf_verifier_env *env,
3629 				 const char *buf_info,
3630 				 const struct bpf_reg_state *reg,
3631 				 int regno, int off, int size)
3632 {
3633 	if (off < 0) {
3634 		verbose(env,
3635 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3636 			regno, buf_info, off, size);
3637 		return -EACCES;
3638 	}
3639 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3640 		char tn_buf[48];
3641 
3642 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3643 		verbose(env,
3644 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3645 			regno, off, tn_buf);
3646 		return -EACCES;
3647 	}
3648 
3649 	return 0;
3650 }
3651 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)3652 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3653 				  const struct bpf_reg_state *reg,
3654 				  int regno, int off, int size)
3655 {
3656 	int err;
3657 
3658 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3659 	if (err)
3660 		return err;
3661 
3662 	if (off + size > env->prog->aux->max_tp_access)
3663 		env->prog->aux->max_tp_access = off + size;
3664 
3665 	return 0;
3666 }
3667 
check_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size,bool zero_size_allowed,const char * buf_info,u32 * max_access)3668 static int check_buffer_access(struct bpf_verifier_env *env,
3669 			       const struct bpf_reg_state *reg,
3670 			       int regno, int off, int size,
3671 			       bool zero_size_allowed,
3672 			       const char *buf_info,
3673 			       u32 *max_access)
3674 {
3675 	int err;
3676 
3677 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3678 	if (err)
3679 		return err;
3680 
3681 	if (off + size > *max_access)
3682 		*max_access = off + size;
3683 
3684 	return 0;
3685 }
3686 
3687 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)3688 static void zext_32_to_64(struct bpf_reg_state *reg)
3689 {
3690 	reg->var_off = tnum_subreg(reg->var_off);
3691 	__reg_assign_32_into_64(reg);
3692 }
3693 
3694 /* truncate register to smaller size (in bytes)
3695  * must be called with size < BPF_REG_SIZE
3696  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)3697 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3698 {
3699 	u64 mask;
3700 
3701 	/* clear high bits in bit representation */
3702 	reg->var_off = tnum_cast(reg->var_off, size);
3703 
3704 	/* fix arithmetic bounds */
3705 	mask = ((u64)1 << (size * 8)) - 1;
3706 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3707 		reg->umin_value &= mask;
3708 		reg->umax_value &= mask;
3709 	} else {
3710 		reg->umin_value = 0;
3711 		reg->umax_value = mask;
3712 	}
3713 	reg->smin_value = reg->umin_value;
3714 	reg->smax_value = reg->umax_value;
3715 
3716 	/* If size is smaller than 32bit register the 32bit register
3717 	 * values are also truncated so we push 64-bit bounds into
3718 	 * 32-bit bounds. Above were truncated < 32-bits already.
3719 	 */
3720 	if (size >= 4)
3721 		return;
3722 	__reg_combine_64_into_32(reg);
3723 }
3724 
bpf_map_is_rdonly(const struct bpf_map * map)3725 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3726 {
3727 	/* A map is considered read-only if the following condition are true:
3728 	 *
3729 	 * 1) BPF program side cannot change any of the map content. The
3730 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3731 	 *    and was set at map creation time.
3732 	 * 2) The map value(s) have been initialized from user space by a
3733 	 *    loader and then "frozen", such that no new map update/delete
3734 	 *    operations from syscall side are possible for the rest of
3735 	 *    the map's lifetime from that point onwards.
3736 	 * 3) Any parallel/pending map update/delete operations from syscall
3737 	 *    side have been completed. Only after that point, it's safe to
3738 	 *    assume that map value(s) are immutable.
3739 	 */
3740 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
3741 	       READ_ONCE(map->frozen) &&
3742 	       !bpf_map_write_active(map);
3743 }
3744 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)3745 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3746 {
3747 	void *ptr;
3748 	u64 addr;
3749 	int err;
3750 
3751 	err = map->ops->map_direct_value_addr(map, &addr, off);
3752 	if (err)
3753 		return err;
3754 	ptr = (void *)(long)addr + off;
3755 
3756 	switch (size) {
3757 	case sizeof(u8):
3758 		*val = (u64)*(u8 *)ptr;
3759 		break;
3760 	case sizeof(u16):
3761 		*val = (u64)*(u16 *)ptr;
3762 		break;
3763 	case sizeof(u32):
3764 		*val = (u64)*(u32 *)ptr;
3765 		break;
3766 	case sizeof(u64):
3767 		*val = *(u64 *)ptr;
3768 		break;
3769 	default:
3770 		return -EINVAL;
3771 	}
3772 	return 0;
3773 }
3774 
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)3775 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3776 				   struct bpf_reg_state *regs,
3777 				   int regno, int off, int size,
3778 				   enum bpf_access_type atype,
3779 				   int value_regno)
3780 {
3781 	struct bpf_reg_state *reg = regs + regno;
3782 	const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3783 	const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3784 	u32 btf_id;
3785 	int ret;
3786 
3787 	if (off < 0) {
3788 		verbose(env,
3789 			"R%d is ptr_%s invalid negative access: off=%d\n",
3790 			regno, tname, off);
3791 		return -EACCES;
3792 	}
3793 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3794 		char tn_buf[48];
3795 
3796 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3797 		verbose(env,
3798 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3799 			regno, tname, off, tn_buf);
3800 		return -EACCES;
3801 	}
3802 
3803 	if (env->ops->btf_struct_access) {
3804 		ret = env->ops->btf_struct_access(&env->log, t, off, size,
3805 						  atype, &btf_id);
3806 	} else {
3807 		if (atype != BPF_READ) {
3808 			verbose(env, "only read is supported\n");
3809 			return -EACCES;
3810 		}
3811 
3812 		ret = btf_struct_access(&env->log, t, off, size, atype,
3813 					&btf_id);
3814 	}
3815 
3816 	if (ret < 0)
3817 		return ret;
3818 
3819 	if (atype == BPF_READ && value_regno >= 0)
3820 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3821 
3822 	return 0;
3823 }
3824 
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)3825 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3826 				   struct bpf_reg_state *regs,
3827 				   int regno, int off, int size,
3828 				   enum bpf_access_type atype,
3829 				   int value_regno)
3830 {
3831 	struct bpf_reg_state *reg = regs + regno;
3832 	struct bpf_map *map = reg->map_ptr;
3833 	const struct btf_type *t;
3834 	const char *tname;
3835 	u32 btf_id;
3836 	int ret;
3837 
3838 	if (!btf_vmlinux) {
3839 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3840 		return -ENOTSUPP;
3841 	}
3842 
3843 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3844 		verbose(env, "map_ptr access not supported for map type %d\n",
3845 			map->map_type);
3846 		return -ENOTSUPP;
3847 	}
3848 
3849 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3850 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3851 
3852 	if (!env->allow_ptr_to_map_access) {
3853 		verbose(env,
3854 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3855 			tname);
3856 		return -EPERM;
3857 	}
3858 
3859 	if (off < 0) {
3860 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
3861 			regno, tname, off);
3862 		return -EACCES;
3863 	}
3864 
3865 	if (atype != BPF_READ) {
3866 		verbose(env, "only read from %s is supported\n", tname);
3867 		return -EACCES;
3868 	}
3869 
3870 	ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3871 	if (ret < 0)
3872 		return ret;
3873 
3874 	if (value_regno >= 0)
3875 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3876 
3877 	return 0;
3878 }
3879 
3880 /* Check that the stack access at the given offset is within bounds. The
3881  * maximum valid offset is -1.
3882  *
3883  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3884  * -state->allocated_stack for reads.
3885  */
check_stack_slot_within_bounds(s64 off,struct bpf_func_state * state,enum bpf_access_type t)3886 static int check_stack_slot_within_bounds(s64 off,
3887 					  struct bpf_func_state *state,
3888 					  enum bpf_access_type t)
3889 {
3890 	int min_valid_off;
3891 
3892 	if (t == BPF_WRITE)
3893 		min_valid_off = -MAX_BPF_STACK;
3894 	else
3895 		min_valid_off = -state->allocated_stack;
3896 
3897 	if (off < min_valid_off || off > -1)
3898 		return -EACCES;
3899 	return 0;
3900 }
3901 
3902 /* Check that the stack access at 'regno + off' falls within the maximum stack
3903  * bounds.
3904  *
3905  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3906  */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum stack_access_src src,enum bpf_access_type type)3907 static int check_stack_access_within_bounds(
3908 		struct bpf_verifier_env *env,
3909 		int regno, int off, int access_size,
3910 		enum stack_access_src src, enum bpf_access_type type)
3911 {
3912 	struct bpf_reg_state *regs = cur_regs(env);
3913 	struct bpf_reg_state *reg = regs + regno;
3914 	struct bpf_func_state *state = func(env, reg);
3915 	s64 min_off, max_off;
3916 	int err;
3917 	char *err_extra;
3918 
3919 	if (src == ACCESS_HELPER)
3920 		/* We don't know if helpers are reading or writing (or both). */
3921 		err_extra = " indirect access to";
3922 	else if (type == BPF_READ)
3923 		err_extra = " read from";
3924 	else
3925 		err_extra = " write to";
3926 
3927 	if (tnum_is_const(reg->var_off)) {
3928 		min_off = (s64)reg->var_off.value + off;
3929 		max_off = min_off + access_size;
3930 	} else {
3931 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3932 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
3933 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3934 				err_extra, regno);
3935 			return -EACCES;
3936 		}
3937 		min_off = (s64)reg->smin_value + off;
3938 		max_off = (s64)reg->smax_value + off + access_size;
3939 	}
3940 
3941 	err = check_stack_slot_within_bounds(min_off, state, type);
3942 	if (!err && max_off > 0)
3943 		err = -EINVAL; /* out of stack access into non-negative offsets */
3944 	if (!err && access_size < 0)
3945 		/* access_size should not be negative (or overflow an int); others checks
3946 		 * along the way should have prevented such an access.
3947 		 */
3948 		err = -EFAULT; /* invalid negative access size; integer overflow? */
3949 
3950 	if (err) {
3951 		if (tnum_is_const(reg->var_off)) {
3952 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3953 				err_extra, regno, off, access_size);
3954 		} else {
3955 			char tn_buf[48];
3956 
3957 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3958 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3959 				err_extra, regno, tn_buf, access_size);
3960 		}
3961 	}
3962 	return err;
3963 }
3964 
3965 /* check whether memory at (regno + off) is accessible for t = (read | write)
3966  * if t==write, value_regno is a register which value is stored into memory
3967  * if t==read, value_regno is a register which will receive the value from memory
3968  * if t==write && value_regno==-1, some unknown value is stored into memory
3969  * if t==read && value_regno==-1, don't care what we read from memory
3970  */
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)3971 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3972 			    int off, int bpf_size, enum bpf_access_type t,
3973 			    int value_regno, bool strict_alignment_once)
3974 {
3975 	struct bpf_reg_state *regs = cur_regs(env);
3976 	struct bpf_reg_state *reg = regs + regno;
3977 	struct bpf_func_state *state;
3978 	int size, err = 0;
3979 
3980 	size = bpf_size_to_bytes(bpf_size);
3981 	if (size < 0)
3982 		return size;
3983 
3984 	/* alignment checks will add in reg->off themselves */
3985 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3986 	if (err)
3987 		return err;
3988 
3989 	/* for access checks, reg->off is just part of off */
3990 	off += reg->off;
3991 
3992 	if (reg->type == PTR_TO_MAP_VALUE) {
3993 		if (t == BPF_WRITE && value_regno >= 0 &&
3994 		    is_pointer_value(env, value_regno)) {
3995 			verbose(env, "R%d leaks addr into map\n", value_regno);
3996 			return -EACCES;
3997 		}
3998 		err = check_map_access_type(env, regno, off, size, t);
3999 		if (err)
4000 			return err;
4001 		err = check_map_access(env, regno, off, size, false);
4002 		if (!err && t == BPF_READ && value_regno >= 0) {
4003 			struct bpf_map *map = reg->map_ptr;
4004 
4005 			/* if map is read-only, track its contents as scalars */
4006 			if (tnum_is_const(reg->var_off) &&
4007 			    bpf_map_is_rdonly(map) &&
4008 			    map->ops->map_direct_value_addr) {
4009 				int map_off = off + reg->var_off.value;
4010 				u64 val = 0;
4011 
4012 				err = bpf_map_direct_read(map, map_off, size,
4013 							  &val);
4014 				if (err)
4015 					return err;
4016 
4017 				regs[value_regno].type = SCALAR_VALUE;
4018 				__mark_reg_known(&regs[value_regno], val);
4019 			} else {
4020 				mark_reg_unknown(env, regs, value_regno);
4021 			}
4022 		}
4023 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4024 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4025 
4026 		if (type_may_be_null(reg->type)) {
4027 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4028 				reg_type_str(env, reg->type));
4029 			return -EACCES;
4030 		}
4031 
4032 		if (t == BPF_WRITE && rdonly_mem) {
4033 			verbose(env, "R%d cannot write into %s\n",
4034 				regno, reg_type_str(env, reg->type));
4035 			return -EACCES;
4036 		}
4037 
4038 		if (t == BPF_WRITE && value_regno >= 0 &&
4039 		    is_pointer_value(env, value_regno)) {
4040 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4041 			return -EACCES;
4042 		}
4043 
4044 		err = check_mem_region_access(env, regno, off, size,
4045 					      reg->mem_size, false);
4046 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4047 			mark_reg_unknown(env, regs, value_regno);
4048 	} else if (reg->type == PTR_TO_CTX) {
4049 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4050 		u32 btf_id = 0;
4051 
4052 		if (t == BPF_WRITE && value_regno >= 0 &&
4053 		    is_pointer_value(env, value_regno)) {
4054 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4055 			return -EACCES;
4056 		}
4057 
4058 		err = check_ptr_off_reg(env, reg, regno);
4059 		if (err < 0)
4060 			return err;
4061 
4062 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
4063 		if (err)
4064 			verbose_linfo(env, insn_idx, "; ");
4065 		if (!err && t == BPF_READ && value_regno >= 0) {
4066 			/* ctx access returns either a scalar, or a
4067 			 * PTR_TO_PACKET[_META,_END]. In the latter
4068 			 * case, we know the offset is zero.
4069 			 */
4070 			if (reg_type == SCALAR_VALUE) {
4071 				mark_reg_unknown(env, regs, value_regno);
4072 			} else {
4073 				mark_reg_known_zero(env, regs,
4074 						    value_regno);
4075 				if (type_may_be_null(reg_type))
4076 					regs[value_regno].id = ++env->id_gen;
4077 				/* A load of ctx field could have different
4078 				 * actual load size with the one encoded in the
4079 				 * insn. When the dst is PTR, it is for sure not
4080 				 * a sub-register.
4081 				 */
4082 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4083 				if (base_type(reg_type) == PTR_TO_BTF_ID)
4084 					regs[value_regno].btf_id = btf_id;
4085 			}
4086 			regs[value_regno].type = reg_type;
4087 		}
4088 
4089 	} else if (reg->type == PTR_TO_STACK) {
4090 		/* Basic bounds checks. */
4091 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4092 		if (err)
4093 			return err;
4094 
4095 		state = func(env, reg);
4096 		err = update_stack_depth(env, state, off);
4097 		if (err)
4098 			return err;
4099 
4100 		if (t == BPF_READ)
4101 			err = check_stack_read(env, regno, off, size,
4102 					       value_regno);
4103 		else
4104 			err = check_stack_write(env, regno, off, size,
4105 						value_regno, insn_idx);
4106 	} else if (reg_is_pkt_pointer(reg)) {
4107 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4108 			verbose(env, "cannot write into packet\n");
4109 			return -EACCES;
4110 		}
4111 		if (t == BPF_WRITE && value_regno >= 0 &&
4112 		    is_pointer_value(env, value_regno)) {
4113 			verbose(env, "R%d leaks addr into packet\n",
4114 				value_regno);
4115 			return -EACCES;
4116 		}
4117 		err = check_packet_access(env, regno, off, size, false);
4118 		if (!err && t == BPF_READ && value_regno >= 0)
4119 			mark_reg_unknown(env, regs, value_regno);
4120 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4121 		if (t == BPF_WRITE && value_regno >= 0 &&
4122 		    is_pointer_value(env, value_regno)) {
4123 			verbose(env, "R%d leaks addr into flow keys\n",
4124 				value_regno);
4125 			return -EACCES;
4126 		}
4127 
4128 		err = check_flow_keys_access(env, off, size);
4129 		if (!err && t == BPF_READ && value_regno >= 0)
4130 			mark_reg_unknown(env, regs, value_regno);
4131 	} else if (type_is_sk_pointer(reg->type)) {
4132 		if (t == BPF_WRITE) {
4133 			verbose(env, "R%d cannot write into %s\n",
4134 				regno, reg_type_str(env, reg->type));
4135 			return -EACCES;
4136 		}
4137 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4138 		if (!err && value_regno >= 0)
4139 			mark_reg_unknown(env, regs, value_regno);
4140 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4141 		err = check_tp_buffer_access(env, reg, regno, off, size);
4142 		if (!err && t == BPF_READ && value_regno >= 0)
4143 			mark_reg_unknown(env, regs, value_regno);
4144 	} else if (reg->type == PTR_TO_BTF_ID) {
4145 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4146 					      value_regno);
4147 	} else if (reg->type == CONST_PTR_TO_MAP) {
4148 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4149 					      value_regno);
4150 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4151 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4152 		const char *buf_info;
4153 		u32 *max_access;
4154 
4155 		if (rdonly_mem) {
4156 			if (t == BPF_WRITE) {
4157 				verbose(env, "R%d cannot write into %s\n",
4158 						regno, reg_type_str(env, reg->type));
4159 				return -EACCES;
4160 			}
4161 			buf_info = "rdonly";
4162 			max_access = &env->prog->aux->max_rdonly_access;
4163 		} else {
4164 			buf_info = "rdwr";
4165 			max_access = &env->prog->aux->max_rdwr_access;
4166 		}
4167 
4168 		err = check_buffer_access(env, reg, regno, off, size, false,
4169 					  buf_info, max_access);
4170 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4171 			mark_reg_unknown(env, regs, value_regno);
4172 	} else {
4173 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4174 			reg_type_str(env, reg->type));
4175 		return -EACCES;
4176 	}
4177 
4178 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4179 	    regs[value_regno].type == SCALAR_VALUE) {
4180 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4181 		coerce_reg_to_size(&regs[value_regno], size);
4182 	}
4183 	return err;
4184 }
4185 
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)4186 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4187 {
4188 	int err;
4189 
4190 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
4191 	    insn->imm != 0) {
4192 		verbose(env, "BPF_XADD uses reserved fields\n");
4193 		return -EINVAL;
4194 	}
4195 
4196 	/* check src1 operand */
4197 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4198 	if (err)
4199 		return err;
4200 
4201 	/* check src2 operand */
4202 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4203 	if (err)
4204 		return err;
4205 
4206 	if (is_pointer_value(env, insn->src_reg)) {
4207 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4208 		return -EACCES;
4209 	}
4210 
4211 	if (is_ctx_reg(env, insn->dst_reg) ||
4212 	    is_pkt_reg(env, insn->dst_reg) ||
4213 	    is_flow_key_reg(env, insn->dst_reg) ||
4214 	    is_sk_reg(env, insn->dst_reg)) {
4215 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
4216 			insn->dst_reg,
4217 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4218 		return -EACCES;
4219 	}
4220 
4221 	/* check whether atomic_add can read the memory */
4222 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4223 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4224 	if (err)
4225 		return err;
4226 
4227 	/* check whether atomic_add can write into the same memory */
4228 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4229 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4230 }
4231 
4232 /* When register 'regno' is used to read the stack (either directly or through
4233  * a helper function) make sure that it's within stack boundary and, depending
4234  * on the access type, that all elements of the stack are initialized.
4235  *
4236  * 'off' includes 'regno->off', but not its dynamic part (if any).
4237  *
4238  * All registers that have been spilled on the stack in the slots within the
4239  * read offsets are marked as read.
4240  */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum stack_access_src type,struct bpf_call_arg_meta * meta)4241 static int check_stack_range_initialized(
4242 		struct bpf_verifier_env *env, int regno, int off,
4243 		int access_size, bool zero_size_allowed,
4244 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4245 {
4246 	struct bpf_reg_state *reg = reg_state(env, regno);
4247 	struct bpf_func_state *state = func(env, reg);
4248 	int err, min_off, max_off, i, j, slot, spi;
4249 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4250 	enum bpf_access_type bounds_check_type;
4251 	/* Some accesses can write anything into the stack, others are
4252 	 * read-only.
4253 	 */
4254 	bool clobber = false;
4255 
4256 	if (access_size == 0 && !zero_size_allowed) {
4257 		verbose(env, "invalid zero-sized read\n");
4258 		return -EACCES;
4259 	}
4260 
4261 	if (type == ACCESS_HELPER) {
4262 		/* The bounds checks for writes are more permissive than for
4263 		 * reads. However, if raw_mode is not set, we'll do extra
4264 		 * checks below.
4265 		 */
4266 		bounds_check_type = BPF_WRITE;
4267 		clobber = true;
4268 	} else {
4269 		bounds_check_type = BPF_READ;
4270 	}
4271 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4272 					       type, bounds_check_type);
4273 	if (err)
4274 		return err;
4275 
4276 
4277 	if (tnum_is_const(reg->var_off)) {
4278 		min_off = max_off = reg->var_off.value + off;
4279 	} else {
4280 		/* Variable offset is prohibited for unprivileged mode for
4281 		 * simplicity since it requires corresponding support in
4282 		 * Spectre masking for stack ALU.
4283 		 * See also retrieve_ptr_limit().
4284 		 */
4285 		if (!env->bypass_spec_v1) {
4286 			char tn_buf[48];
4287 
4288 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4289 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4290 				regno, err_extra, tn_buf);
4291 			return -EACCES;
4292 		}
4293 		/* Only initialized buffer on stack is allowed to be accessed
4294 		 * with variable offset. With uninitialized buffer it's hard to
4295 		 * guarantee that whole memory is marked as initialized on
4296 		 * helper return since specific bounds are unknown what may
4297 		 * cause uninitialized stack leaking.
4298 		 */
4299 		if (meta && meta->raw_mode)
4300 			meta = NULL;
4301 
4302 		min_off = reg->smin_value + off;
4303 		max_off = reg->smax_value + off;
4304 	}
4305 
4306 	if (meta && meta->raw_mode) {
4307 		meta->access_size = access_size;
4308 		meta->regno = regno;
4309 		return 0;
4310 	}
4311 
4312 	for (i = min_off; i < max_off + access_size; i++) {
4313 		u8 *stype;
4314 
4315 		slot = -i - 1;
4316 		spi = slot / BPF_REG_SIZE;
4317 		if (state->allocated_stack <= slot)
4318 			goto err;
4319 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4320 		if (*stype == STACK_MISC)
4321 			goto mark;
4322 		if (*stype == STACK_ZERO) {
4323 			if (clobber) {
4324 				/* helper can write anything into the stack */
4325 				*stype = STACK_MISC;
4326 			}
4327 			goto mark;
4328 		}
4329 
4330 		if (is_spilled_reg(&state->stack[spi]) &&
4331 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4332 			goto mark;
4333 
4334 		if (is_spilled_reg(&state->stack[spi]) &&
4335 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4336 		     env->allow_ptr_leaks)) {
4337 			if (clobber) {
4338 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4339 				for (j = 0; j < BPF_REG_SIZE; j++)
4340 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4341 			}
4342 			goto mark;
4343 		}
4344 
4345 err:
4346 		if (tnum_is_const(reg->var_off)) {
4347 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4348 				err_extra, regno, min_off, i - min_off, access_size);
4349 		} else {
4350 			char tn_buf[48];
4351 
4352 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4353 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4354 				err_extra, regno, tn_buf, i - min_off, access_size);
4355 		}
4356 		return -EACCES;
4357 mark:
4358 		/* reading any byte out of 8-byte 'spill_slot' will cause
4359 		 * the whole slot to be marked as 'read'
4360 		 */
4361 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4362 			      state->stack[spi].spilled_ptr.parent,
4363 			      REG_LIVE_READ64);
4364 	}
4365 	return update_stack_depth(env, state, min_off);
4366 }
4367 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)4368 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4369 				   int access_size, bool zero_size_allowed,
4370 				   struct bpf_call_arg_meta *meta)
4371 {
4372 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4373 	const char *buf_info;
4374 	u32 *max_access;
4375 
4376 	switch (base_type(reg->type)) {
4377 	case PTR_TO_PACKET:
4378 	case PTR_TO_PACKET_META:
4379 		return check_packet_access(env, regno, reg->off, access_size,
4380 					   zero_size_allowed);
4381 	case PTR_TO_MAP_VALUE:
4382 		if (check_map_access_type(env, regno, reg->off, access_size,
4383 					  meta && meta->raw_mode ? BPF_WRITE :
4384 					  BPF_READ))
4385 			return -EACCES;
4386 		return check_map_access(env, regno, reg->off, access_size,
4387 					zero_size_allowed);
4388 	case PTR_TO_MEM:
4389 		return check_mem_region_access(env, regno, reg->off,
4390 					       access_size, reg->mem_size,
4391 					       zero_size_allowed);
4392 	case PTR_TO_BUF:
4393 		if (type_is_rdonly_mem(reg->type)) {
4394 			if (meta && meta->raw_mode)
4395 				return -EACCES;
4396 
4397 			buf_info = "rdonly";
4398 			max_access = &env->prog->aux->max_rdonly_access;
4399 		} else {
4400 			buf_info = "rdwr";
4401 			max_access = &env->prog->aux->max_rdwr_access;
4402 		}
4403 		return check_buffer_access(env, reg, regno, reg->off,
4404 					   access_size, zero_size_allowed,
4405 					   buf_info, max_access);
4406 	case PTR_TO_STACK:
4407 		return check_stack_range_initialized(
4408 				env,
4409 				regno, reg->off, access_size,
4410 				zero_size_allowed, ACCESS_HELPER, meta);
4411 	default: /* scalar_value or invalid ptr */
4412 		/* Allow zero-byte read from NULL, regardless of pointer type */
4413 		if (zero_size_allowed && access_size == 0 &&
4414 		    register_is_null(reg))
4415 			return 0;
4416 
4417 		verbose(env, "R%d type=%s ", regno,
4418 			reg_type_str(env, reg->type));
4419 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4420 		return -EACCES;
4421 	}
4422 }
4423 
4424 /* Implementation details:
4425  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4426  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4427  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4428  * value_or_null->value transition, since the verifier only cares about
4429  * the range of access to valid map value pointer and doesn't care about actual
4430  * address of the map element.
4431  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4432  * reg->id > 0 after value_or_null->value transition. By doing so
4433  * two bpf_map_lookups will be considered two different pointers that
4434  * point to different bpf_spin_locks.
4435  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4436  * dead-locks.
4437  * Since only one bpf_spin_lock is allowed the checks are simpler than
4438  * reg_is_refcounted() logic. The verifier needs to remember only
4439  * one spin_lock instead of array of acquired_refs.
4440  * cur_state->active_spin_lock remembers which map value element got locked
4441  * and clears it after bpf_spin_unlock.
4442  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)4443 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4444 			     bool is_lock)
4445 {
4446 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4447 	struct bpf_verifier_state *cur = env->cur_state;
4448 	bool is_const = tnum_is_const(reg->var_off);
4449 	struct bpf_map *map = reg->map_ptr;
4450 	u64 val = reg->var_off.value;
4451 
4452 	if (!is_const) {
4453 		verbose(env,
4454 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4455 			regno);
4456 		return -EINVAL;
4457 	}
4458 	if (!map->btf) {
4459 		verbose(env,
4460 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4461 			map->name);
4462 		return -EINVAL;
4463 	}
4464 	if (!map_value_has_spin_lock(map)) {
4465 		if (map->spin_lock_off == -E2BIG)
4466 			verbose(env,
4467 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4468 				map->name);
4469 		else if (map->spin_lock_off == -ENOENT)
4470 			verbose(env,
4471 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4472 				map->name);
4473 		else
4474 			verbose(env,
4475 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4476 				map->name);
4477 		return -EINVAL;
4478 	}
4479 	if (map->spin_lock_off != val + reg->off) {
4480 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4481 			val + reg->off);
4482 		return -EINVAL;
4483 	}
4484 	if (is_lock) {
4485 		if (cur->active_spin_lock) {
4486 			verbose(env,
4487 				"Locking two bpf_spin_locks are not allowed\n");
4488 			return -EINVAL;
4489 		}
4490 		cur->active_spin_lock = reg->id;
4491 	} else {
4492 		if (!cur->active_spin_lock) {
4493 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4494 			return -EINVAL;
4495 		}
4496 		if (cur->active_spin_lock != reg->id) {
4497 			verbose(env, "bpf_spin_unlock of different lock\n");
4498 			return -EINVAL;
4499 		}
4500 		cur->active_spin_lock = 0;
4501 	}
4502 	return 0;
4503 }
4504 
arg_type_is_mem_ptr(enum bpf_arg_type type)4505 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4506 {
4507 	return base_type(type) == ARG_PTR_TO_MEM ||
4508 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
4509 }
4510 
arg_type_is_mem_size(enum bpf_arg_type type)4511 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4512 {
4513 	return type == ARG_CONST_SIZE ||
4514 	       type == ARG_CONST_SIZE_OR_ZERO;
4515 }
4516 
arg_type_is_alloc_size(enum bpf_arg_type type)4517 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4518 {
4519 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4520 }
4521 
arg_type_is_int_ptr(enum bpf_arg_type type)4522 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4523 {
4524 	return type == ARG_PTR_TO_INT ||
4525 	       type == ARG_PTR_TO_LONG;
4526 }
4527 
int_ptr_type_to_size(enum bpf_arg_type type)4528 static int int_ptr_type_to_size(enum bpf_arg_type type)
4529 {
4530 	if (type == ARG_PTR_TO_INT)
4531 		return sizeof(u32);
4532 	else if (type == ARG_PTR_TO_LONG)
4533 		return sizeof(u64);
4534 
4535 	return -EINVAL;
4536 }
4537 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)4538 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4539 				 const struct bpf_call_arg_meta *meta,
4540 				 enum bpf_arg_type *arg_type)
4541 {
4542 	if (!meta->map_ptr) {
4543 		/* kernel subsystem misconfigured verifier */
4544 		verbose(env, "invalid map_ptr to access map->type\n");
4545 		return -EACCES;
4546 	}
4547 
4548 	switch (meta->map_ptr->map_type) {
4549 	case BPF_MAP_TYPE_SOCKMAP:
4550 	case BPF_MAP_TYPE_SOCKHASH:
4551 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4552 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4553 		} else {
4554 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4555 			return -EINVAL;
4556 		}
4557 		break;
4558 
4559 	default:
4560 		break;
4561 	}
4562 	return 0;
4563 }
4564 
4565 struct bpf_reg_types {
4566 	const enum bpf_reg_type types[10];
4567 	u32 *btf_id;
4568 };
4569 
4570 static const struct bpf_reg_types map_key_value_types = {
4571 	.types = {
4572 		PTR_TO_STACK,
4573 		PTR_TO_PACKET,
4574 		PTR_TO_PACKET_META,
4575 		PTR_TO_MAP_VALUE,
4576 	},
4577 };
4578 
4579 static const struct bpf_reg_types sock_types = {
4580 	.types = {
4581 		PTR_TO_SOCK_COMMON,
4582 		PTR_TO_SOCKET,
4583 		PTR_TO_TCP_SOCK,
4584 		PTR_TO_XDP_SOCK,
4585 	},
4586 };
4587 
4588 #ifdef CONFIG_NET
4589 static const struct bpf_reg_types btf_id_sock_common_types = {
4590 	.types = {
4591 		PTR_TO_SOCK_COMMON,
4592 		PTR_TO_SOCKET,
4593 		PTR_TO_TCP_SOCK,
4594 		PTR_TO_XDP_SOCK,
4595 		PTR_TO_BTF_ID,
4596 	},
4597 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4598 };
4599 #endif
4600 
4601 static const struct bpf_reg_types mem_types = {
4602 	.types = {
4603 		PTR_TO_STACK,
4604 		PTR_TO_PACKET,
4605 		PTR_TO_PACKET_META,
4606 		PTR_TO_MAP_VALUE,
4607 		PTR_TO_MEM,
4608 		PTR_TO_MEM | MEM_ALLOC,
4609 		PTR_TO_BUF,
4610 	},
4611 };
4612 
4613 static const struct bpf_reg_types int_ptr_types = {
4614 	.types = {
4615 		PTR_TO_STACK,
4616 		PTR_TO_PACKET,
4617 		PTR_TO_PACKET_META,
4618 		PTR_TO_MAP_VALUE,
4619 	},
4620 };
4621 
4622 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4623 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4624 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4625 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
4626 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4627 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4628 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4629 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4630 
4631 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4632 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4633 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4634 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4635 	[ARG_CONST_SIZE]		= &scalar_types,
4636 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4637 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4638 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4639 	[ARG_PTR_TO_CTX]		= &context_types,
4640 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4641 #ifdef CONFIG_NET
4642 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4643 #endif
4644 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4645 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4646 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4647 	[ARG_PTR_TO_MEM]		= &mem_types,
4648 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4649 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4650 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4651 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4652 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4653 };
4654 
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id)4655 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4656 			  enum bpf_arg_type arg_type,
4657 			  const u32 *arg_btf_id)
4658 {
4659 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4660 	enum bpf_reg_type expected, type = reg->type;
4661 	const struct bpf_reg_types *compatible;
4662 	int i, j;
4663 
4664 	compatible = compatible_reg_types[base_type(arg_type)];
4665 	if (!compatible) {
4666 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4667 		return -EFAULT;
4668 	}
4669 
4670 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
4671 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
4672 	 *
4673 	 * Same for MAYBE_NULL:
4674 	 *
4675 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
4676 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
4677 	 *
4678 	 * Therefore we fold these flags depending on the arg_type before comparison.
4679 	 */
4680 	if (arg_type & MEM_RDONLY)
4681 		type &= ~MEM_RDONLY;
4682 	if (arg_type & PTR_MAYBE_NULL)
4683 		type &= ~PTR_MAYBE_NULL;
4684 
4685 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4686 		expected = compatible->types[i];
4687 		if (expected == NOT_INIT)
4688 			break;
4689 
4690 		if (type == expected)
4691 			goto found;
4692 	}
4693 
4694 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
4695 	for (j = 0; j + 1 < i; j++)
4696 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
4697 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
4698 	return -EACCES;
4699 
4700 found:
4701 	if (reg->type == PTR_TO_BTF_ID) {
4702 		if (!arg_btf_id) {
4703 			if (!compatible->btf_id) {
4704 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4705 				return -EFAULT;
4706 			}
4707 			arg_btf_id = compatible->btf_id;
4708 		}
4709 
4710 		if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4711 					  *arg_btf_id)) {
4712 			verbose(env, "R%d is of type %s but %s is expected\n",
4713 				regno, kernel_type_name(reg->btf_id),
4714 				kernel_type_name(*arg_btf_id));
4715 			return -EACCES;
4716 		}
4717 	}
4718 
4719 	return 0;
4720 }
4721 
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)4722 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4723 			  struct bpf_call_arg_meta *meta,
4724 			  const struct bpf_func_proto *fn)
4725 {
4726 	u32 regno = BPF_REG_1 + arg;
4727 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4728 	enum bpf_arg_type arg_type = fn->arg_type[arg];
4729 	enum bpf_reg_type type = reg->type;
4730 	int err = 0;
4731 
4732 	if (arg_type == ARG_DONTCARE)
4733 		return 0;
4734 
4735 	err = check_reg_arg(env, regno, SRC_OP);
4736 	if (err)
4737 		return err;
4738 
4739 	if (arg_type == ARG_ANYTHING) {
4740 		if (is_pointer_value(env, regno)) {
4741 			verbose(env, "R%d leaks addr into helper function\n",
4742 				regno);
4743 			return -EACCES;
4744 		}
4745 		return 0;
4746 	}
4747 
4748 	if (type_is_pkt_pointer(type) &&
4749 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4750 		verbose(env, "helper access to the packet is not allowed\n");
4751 		return -EACCES;
4752 	}
4753 
4754 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
4755 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4756 		err = resolve_map_arg_type(env, meta, &arg_type);
4757 		if (err)
4758 			return err;
4759 	}
4760 
4761 	if (register_is_null(reg) && type_may_be_null(arg_type))
4762 		/* A NULL register has a SCALAR_VALUE type, so skip
4763 		 * type checking.
4764 		 */
4765 		goto skip_type_check;
4766 
4767 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4768 	if (err)
4769 		return err;
4770 
4771 	switch ((u32)type) {
4772 	case SCALAR_VALUE:
4773 	/* Pointer types where reg offset is explicitly allowed: */
4774 	case PTR_TO_PACKET:
4775 	case PTR_TO_PACKET_META:
4776 	case PTR_TO_MAP_VALUE:
4777 	case PTR_TO_MEM:
4778 	case PTR_TO_MEM | MEM_RDONLY:
4779 	case PTR_TO_MEM | MEM_ALLOC:
4780 	case PTR_TO_BUF:
4781 	case PTR_TO_BUF | MEM_RDONLY:
4782 	case PTR_TO_STACK:
4783 		/* Some of the argument types nevertheless require a
4784 		 * zero register offset.
4785 		 */
4786 		if (arg_type == ARG_PTR_TO_ALLOC_MEM)
4787 			goto force_off_check;
4788 		break;
4789 	/* All the rest must be rejected: */
4790 	default:
4791 force_off_check:
4792 		err = __check_ptr_off_reg(env, reg, regno,
4793 					  type == PTR_TO_BTF_ID);
4794 		if (err < 0)
4795 			return err;
4796 		break;
4797 	}
4798 
4799 skip_type_check:
4800 	if (reg->ref_obj_id) {
4801 		if (meta->ref_obj_id) {
4802 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4803 				regno, reg->ref_obj_id,
4804 				meta->ref_obj_id);
4805 			return -EFAULT;
4806 		}
4807 		meta->ref_obj_id = reg->ref_obj_id;
4808 	}
4809 
4810 	if (arg_type == ARG_CONST_MAP_PTR) {
4811 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4812 		meta->map_ptr = reg->map_ptr;
4813 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4814 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
4815 		 * check that [key, key + map->key_size) are within
4816 		 * stack limits and initialized
4817 		 */
4818 		if (!meta->map_ptr) {
4819 			/* in function declaration map_ptr must come before
4820 			 * map_key, so that it's verified and known before
4821 			 * we have to check map_key here. Otherwise it means
4822 			 * that kernel subsystem misconfigured verifier
4823 			 */
4824 			verbose(env, "invalid map_ptr to access map->key\n");
4825 			return -EACCES;
4826 		}
4827 		err = check_helper_mem_access(env, regno,
4828 					      meta->map_ptr->key_size, false,
4829 					      NULL);
4830 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
4831 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4832 		if (type_may_be_null(arg_type) && register_is_null(reg))
4833 			return 0;
4834 
4835 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
4836 		 * check [value, value + map->value_size) validity
4837 		 */
4838 		if (!meta->map_ptr) {
4839 			/* kernel subsystem misconfigured verifier */
4840 			verbose(env, "invalid map_ptr to access map->value\n");
4841 			return -EACCES;
4842 		}
4843 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4844 		err = check_helper_mem_access(env, regno,
4845 					      meta->map_ptr->value_size, false,
4846 					      meta);
4847 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4848 		if (!reg->btf_id) {
4849 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4850 			return -EACCES;
4851 		}
4852 		meta->ret_btf_id = reg->btf_id;
4853 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4854 		if (meta->func_id == BPF_FUNC_spin_lock) {
4855 			if (process_spin_lock(env, regno, true))
4856 				return -EACCES;
4857 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
4858 			if (process_spin_lock(env, regno, false))
4859 				return -EACCES;
4860 		} else {
4861 			verbose(env, "verifier internal error\n");
4862 			return -EFAULT;
4863 		}
4864 	} else if (arg_type_is_mem_ptr(arg_type)) {
4865 		/* The access to this pointer is only checked when we hit the
4866 		 * next is_mem_size argument below.
4867 		 */
4868 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4869 	} else if (arg_type_is_mem_size(arg_type)) {
4870 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4871 
4872 		/* This is used to refine r0 return value bounds for helpers
4873 		 * that enforce this value as an upper bound on return values.
4874 		 * See do_refine_retval_range() for helpers that can refine
4875 		 * the return value. C type of helper is u32 so we pull register
4876 		 * bound from umax_value however, if negative verifier errors
4877 		 * out. Only upper bounds can be learned because retval is an
4878 		 * int type and negative retvals are allowed.
4879 		 */
4880 		meta->msize_max_value = reg->umax_value;
4881 
4882 		/* The register is SCALAR_VALUE; the access check
4883 		 * happens using its boundaries.
4884 		 */
4885 		if (!tnum_is_const(reg->var_off))
4886 			/* For unprivileged variable accesses, disable raw
4887 			 * mode so that the program is required to
4888 			 * initialize all the memory that the helper could
4889 			 * just partially fill up.
4890 			 */
4891 			meta = NULL;
4892 
4893 		if (reg->smin_value < 0) {
4894 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4895 				regno);
4896 			return -EACCES;
4897 		}
4898 
4899 		if (reg->umin_value == 0) {
4900 			err = check_helper_mem_access(env, regno - 1, 0,
4901 						      zero_size_allowed,
4902 						      meta);
4903 			if (err)
4904 				return err;
4905 		}
4906 
4907 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4908 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4909 				regno);
4910 			return -EACCES;
4911 		}
4912 		err = check_helper_mem_access(env, regno - 1,
4913 					      reg->umax_value,
4914 					      zero_size_allowed, meta);
4915 		if (!err)
4916 			err = mark_chain_precision(env, regno);
4917 	} else if (arg_type_is_alloc_size(arg_type)) {
4918 		if (!tnum_is_const(reg->var_off)) {
4919 			verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4920 				regno);
4921 			return -EACCES;
4922 		}
4923 		meta->mem_size = reg->var_off.value;
4924 	} else if (arg_type_is_int_ptr(arg_type)) {
4925 		int size = int_ptr_type_to_size(arg_type);
4926 
4927 		err = check_helper_mem_access(env, regno, size, false, meta);
4928 		if (err)
4929 			return err;
4930 		err = check_ptr_alignment(env, reg, 0, size, true);
4931 	}
4932 
4933 	return err;
4934 }
4935 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)4936 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4937 {
4938 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
4939 	enum bpf_prog_type type = resolve_prog_type(env->prog);
4940 
4941 	if (func_id != BPF_FUNC_map_update_elem)
4942 		return false;
4943 
4944 	/* It's not possible to get access to a locked struct sock in these
4945 	 * contexts, so updating is safe.
4946 	 */
4947 	switch (type) {
4948 	case BPF_PROG_TYPE_TRACING:
4949 		if (eatype == BPF_TRACE_ITER)
4950 			return true;
4951 		break;
4952 	case BPF_PROG_TYPE_SOCKET_FILTER:
4953 	case BPF_PROG_TYPE_SCHED_CLS:
4954 	case BPF_PROG_TYPE_SCHED_ACT:
4955 	case BPF_PROG_TYPE_XDP:
4956 	case BPF_PROG_TYPE_SK_REUSEPORT:
4957 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4958 	case BPF_PROG_TYPE_SK_LOOKUP:
4959 		return true;
4960 	default:
4961 		break;
4962 	}
4963 
4964 	verbose(env, "cannot update sockmap in this context\n");
4965 	return false;
4966 }
4967 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)4968 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4969 {
4970 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4971 }
4972 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)4973 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4974 					struct bpf_map *map, int func_id)
4975 {
4976 	if (!map)
4977 		return 0;
4978 
4979 	/* We need a two way check, first is from map perspective ... */
4980 	switch (map->map_type) {
4981 	case BPF_MAP_TYPE_PROG_ARRAY:
4982 		if (func_id != BPF_FUNC_tail_call)
4983 			goto error;
4984 		break;
4985 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4986 		if (func_id != BPF_FUNC_perf_event_read &&
4987 		    func_id != BPF_FUNC_perf_event_output &&
4988 		    func_id != BPF_FUNC_skb_output &&
4989 		    func_id != BPF_FUNC_perf_event_read_value &&
4990 		    func_id != BPF_FUNC_xdp_output)
4991 			goto error;
4992 		break;
4993 	case BPF_MAP_TYPE_RINGBUF:
4994 		if (func_id != BPF_FUNC_ringbuf_output &&
4995 		    func_id != BPF_FUNC_ringbuf_reserve &&
4996 		    func_id != BPF_FUNC_ringbuf_query)
4997 			goto error;
4998 		break;
4999 	case BPF_MAP_TYPE_STACK_TRACE:
5000 		if (func_id != BPF_FUNC_get_stackid)
5001 			goto error;
5002 		break;
5003 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5004 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5005 		    func_id != BPF_FUNC_current_task_under_cgroup)
5006 			goto error;
5007 		break;
5008 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5009 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5010 		if (func_id != BPF_FUNC_get_local_storage)
5011 			goto error;
5012 		break;
5013 	case BPF_MAP_TYPE_DEVMAP:
5014 	case BPF_MAP_TYPE_DEVMAP_HASH:
5015 		if (func_id != BPF_FUNC_redirect_map &&
5016 		    func_id != BPF_FUNC_map_lookup_elem)
5017 			goto error;
5018 		break;
5019 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5020 	 * appear.
5021 	 */
5022 	case BPF_MAP_TYPE_CPUMAP:
5023 		if (func_id != BPF_FUNC_redirect_map)
5024 			goto error;
5025 		break;
5026 	case BPF_MAP_TYPE_XSKMAP:
5027 		if (func_id != BPF_FUNC_redirect_map &&
5028 		    func_id != BPF_FUNC_map_lookup_elem)
5029 			goto error;
5030 		break;
5031 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5032 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5033 		if (func_id != BPF_FUNC_map_lookup_elem)
5034 			goto error;
5035 		break;
5036 	case BPF_MAP_TYPE_SOCKMAP:
5037 		if (func_id != BPF_FUNC_sk_redirect_map &&
5038 		    func_id != BPF_FUNC_sock_map_update &&
5039 		    func_id != BPF_FUNC_map_delete_elem &&
5040 		    func_id != BPF_FUNC_msg_redirect_map &&
5041 		    func_id != BPF_FUNC_sk_select_reuseport &&
5042 		    func_id != BPF_FUNC_map_lookup_elem &&
5043 		    !may_update_sockmap(env, func_id))
5044 			goto error;
5045 		break;
5046 	case BPF_MAP_TYPE_SOCKHASH:
5047 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5048 		    func_id != BPF_FUNC_sock_hash_update &&
5049 		    func_id != BPF_FUNC_map_delete_elem &&
5050 		    func_id != BPF_FUNC_msg_redirect_hash &&
5051 		    func_id != BPF_FUNC_sk_select_reuseport &&
5052 		    func_id != BPF_FUNC_map_lookup_elem &&
5053 		    !may_update_sockmap(env, func_id))
5054 			goto error;
5055 		break;
5056 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5057 		if (func_id != BPF_FUNC_sk_select_reuseport)
5058 			goto error;
5059 		break;
5060 	case BPF_MAP_TYPE_QUEUE:
5061 	case BPF_MAP_TYPE_STACK:
5062 		if (func_id != BPF_FUNC_map_peek_elem &&
5063 		    func_id != BPF_FUNC_map_pop_elem &&
5064 		    func_id != BPF_FUNC_map_push_elem)
5065 			goto error;
5066 		break;
5067 	case BPF_MAP_TYPE_SK_STORAGE:
5068 		if (func_id != BPF_FUNC_sk_storage_get &&
5069 		    func_id != BPF_FUNC_sk_storage_delete)
5070 			goto error;
5071 		break;
5072 	case BPF_MAP_TYPE_INODE_STORAGE:
5073 		if (func_id != BPF_FUNC_inode_storage_get &&
5074 		    func_id != BPF_FUNC_inode_storage_delete)
5075 			goto error;
5076 		break;
5077 	default:
5078 		break;
5079 	}
5080 
5081 	/* ... and second from the function itself. */
5082 	switch (func_id) {
5083 	case BPF_FUNC_tail_call:
5084 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5085 			goto error;
5086 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5087 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5088 			return -EINVAL;
5089 		}
5090 		break;
5091 	case BPF_FUNC_perf_event_read:
5092 	case BPF_FUNC_perf_event_output:
5093 	case BPF_FUNC_perf_event_read_value:
5094 	case BPF_FUNC_skb_output:
5095 	case BPF_FUNC_xdp_output:
5096 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5097 			goto error;
5098 		break;
5099 	case BPF_FUNC_ringbuf_output:
5100 	case BPF_FUNC_ringbuf_reserve:
5101 	case BPF_FUNC_ringbuf_query:
5102 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5103 			goto error;
5104 		break;
5105 	case BPF_FUNC_get_stackid:
5106 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5107 			goto error;
5108 		break;
5109 	case BPF_FUNC_current_task_under_cgroup:
5110 	case BPF_FUNC_skb_under_cgroup:
5111 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5112 			goto error;
5113 		break;
5114 	case BPF_FUNC_redirect_map:
5115 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5116 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5117 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5118 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5119 			goto error;
5120 		break;
5121 	case BPF_FUNC_sk_redirect_map:
5122 	case BPF_FUNC_msg_redirect_map:
5123 	case BPF_FUNC_sock_map_update:
5124 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5125 			goto error;
5126 		break;
5127 	case BPF_FUNC_sk_redirect_hash:
5128 	case BPF_FUNC_msg_redirect_hash:
5129 	case BPF_FUNC_sock_hash_update:
5130 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5131 			goto error;
5132 		break;
5133 	case BPF_FUNC_get_local_storage:
5134 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5135 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5136 			goto error;
5137 		break;
5138 	case BPF_FUNC_sk_select_reuseport:
5139 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5140 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5141 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5142 			goto error;
5143 		break;
5144 	case BPF_FUNC_map_peek_elem:
5145 	case BPF_FUNC_map_pop_elem:
5146 	case BPF_FUNC_map_push_elem:
5147 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5148 		    map->map_type != BPF_MAP_TYPE_STACK)
5149 			goto error;
5150 		break;
5151 	case BPF_FUNC_sk_storage_get:
5152 	case BPF_FUNC_sk_storage_delete:
5153 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5154 			goto error;
5155 		break;
5156 	case BPF_FUNC_inode_storage_get:
5157 	case BPF_FUNC_inode_storage_delete:
5158 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5159 			goto error;
5160 		break;
5161 	default:
5162 		break;
5163 	}
5164 
5165 	return 0;
5166 error:
5167 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5168 		map->map_type, func_id_name(func_id), func_id);
5169 	return -EINVAL;
5170 }
5171 
check_raw_mode_ok(const struct bpf_func_proto * fn)5172 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5173 {
5174 	int count = 0;
5175 
5176 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5177 		count++;
5178 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5179 		count++;
5180 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5181 		count++;
5182 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5183 		count++;
5184 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5185 		count++;
5186 
5187 	/* We only support one arg being in raw mode at the moment,
5188 	 * which is sufficient for the helper functions we have
5189 	 * right now.
5190 	 */
5191 	return count <= 1;
5192 }
5193 
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)5194 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5195 				    enum bpf_arg_type arg_next)
5196 {
5197 	return (arg_type_is_mem_ptr(arg_curr) &&
5198 	        !arg_type_is_mem_size(arg_next)) ||
5199 	       (!arg_type_is_mem_ptr(arg_curr) &&
5200 		arg_type_is_mem_size(arg_next));
5201 }
5202 
check_arg_pair_ok(const struct bpf_func_proto * fn)5203 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5204 {
5205 	/* bpf_xxx(..., buf, len) call will access 'len'
5206 	 * bytes from memory 'buf'. Both arg types need
5207 	 * to be paired, so make sure there's no buggy
5208 	 * helper function specification.
5209 	 */
5210 	if (arg_type_is_mem_size(fn->arg1_type) ||
5211 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5212 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5213 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5214 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5215 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5216 		return false;
5217 
5218 	return true;
5219 }
5220 
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5221 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5222 {
5223 	int count = 0;
5224 
5225 	if (arg_type_may_be_refcounted(fn->arg1_type))
5226 		count++;
5227 	if (arg_type_may_be_refcounted(fn->arg2_type))
5228 		count++;
5229 	if (arg_type_may_be_refcounted(fn->arg3_type))
5230 		count++;
5231 	if (arg_type_may_be_refcounted(fn->arg4_type))
5232 		count++;
5233 	if (arg_type_may_be_refcounted(fn->arg5_type))
5234 		count++;
5235 
5236 	/* A reference acquiring function cannot acquire
5237 	 * another refcounted ptr.
5238 	 */
5239 	if (may_be_acquire_function(func_id) && count)
5240 		return false;
5241 
5242 	/* We only support one arg being unreferenced at the moment,
5243 	 * which is sufficient for the helper functions we have right now.
5244 	 */
5245 	return count <= 1;
5246 }
5247 
check_btf_id_ok(const struct bpf_func_proto * fn)5248 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5249 {
5250 	int i;
5251 
5252 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5253 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5254 			return false;
5255 
5256 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5257 			return false;
5258 	}
5259 
5260 	return true;
5261 }
5262 
check_func_proto(const struct bpf_func_proto * fn,int func_id)5263 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5264 {
5265 	return check_raw_mode_ok(fn) &&
5266 	       check_arg_pair_ok(fn) &&
5267 	       check_btf_id_ok(fn) &&
5268 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5269 }
5270 
5271 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5272  * are now invalid, so turn them into unknown SCALAR_VALUE.
5273  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5274 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5275 {
5276 	struct bpf_func_state *state;
5277 	struct bpf_reg_state *reg;
5278 
5279 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5280 		if (reg_is_pkt_pointer_any(reg))
5281 			__mark_reg_unknown(env, reg);
5282 	}));
5283 }
5284 
5285 enum {
5286 	AT_PKT_END = -1,
5287 	BEYOND_PKT_END = -2,
5288 };
5289 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5290 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5291 {
5292 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5293 	struct bpf_reg_state *reg = &state->regs[regn];
5294 
5295 	if (reg->type != PTR_TO_PACKET)
5296 		/* PTR_TO_PACKET_META is not supported yet */
5297 		return;
5298 
5299 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5300 	 * How far beyond pkt_end it goes is unknown.
5301 	 * if (!range_open) it's the case of pkt >= pkt_end
5302 	 * if (range_open) it's the case of pkt > pkt_end
5303 	 * hence this pointer is at least 1 byte bigger than pkt_end
5304 	 */
5305 	if (range_open)
5306 		reg->range = BEYOND_PKT_END;
5307 	else
5308 		reg->range = AT_PKT_END;
5309 }
5310 
5311 /* The pointer with the specified id has released its reference to kernel
5312  * resources. Identify all copies of the same pointer and clear the reference.
5313  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5314 static int release_reference(struct bpf_verifier_env *env,
5315 			     int ref_obj_id)
5316 {
5317 	struct bpf_func_state *state;
5318 	struct bpf_reg_state *reg;
5319 	int err;
5320 
5321 	err = release_reference_state(cur_func(env), ref_obj_id);
5322 	if (err)
5323 		return err;
5324 
5325 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5326 		if (reg->ref_obj_id == ref_obj_id) {
5327 			if (!env->allow_ptr_leaks)
5328 				__mark_reg_not_init(env, reg);
5329 			else
5330 				__mark_reg_unknown(env, reg);
5331 		}
5332 	}));
5333 
5334 	return 0;
5335 }
5336 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5337 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5338 				    struct bpf_reg_state *regs)
5339 {
5340 	int i;
5341 
5342 	/* after the call registers r0 - r5 were scratched */
5343 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5344 		mark_reg_not_init(env, regs, caller_saved[i]);
5345 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5346 	}
5347 }
5348 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)5349 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5350 			   int *insn_idx)
5351 {
5352 	struct bpf_verifier_state *state = env->cur_state;
5353 	struct bpf_func_info_aux *func_info_aux;
5354 	struct bpf_func_state *caller, *callee;
5355 	int i, err, subprog, target_insn;
5356 	bool is_global = false;
5357 
5358 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5359 		verbose(env, "the call stack of %d frames is too deep\n",
5360 			state->curframe + 2);
5361 		return -E2BIG;
5362 	}
5363 
5364 	target_insn = *insn_idx + insn->imm;
5365 	subprog = find_subprog(env, target_insn + 1);
5366 	if (subprog < 0) {
5367 		verbose(env, "verifier bug. No program starts at insn %d\n",
5368 			target_insn + 1);
5369 		return -EFAULT;
5370 	}
5371 
5372 	caller = state->frame[state->curframe];
5373 	if (state->frame[state->curframe + 1]) {
5374 		verbose(env, "verifier bug. Frame %d already allocated\n",
5375 			state->curframe + 1);
5376 		return -EFAULT;
5377 	}
5378 
5379 	func_info_aux = env->prog->aux->func_info_aux;
5380 	if (func_info_aux)
5381 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5382 	err = btf_check_func_arg_match(env, subprog, caller->regs);
5383 	if (err == -EFAULT)
5384 		return err;
5385 	if (is_global) {
5386 		if (err) {
5387 			verbose(env, "Caller passes invalid args into func#%d\n",
5388 				subprog);
5389 			return err;
5390 		} else {
5391 			if (env->log.level & BPF_LOG_LEVEL)
5392 				verbose(env,
5393 					"Func#%d is global and valid. Skipping.\n",
5394 					subprog);
5395 			clear_caller_saved_regs(env, caller->regs);
5396 
5397 			/* All global functions return a 64-bit SCALAR_VALUE */
5398 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5399 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5400 
5401 			/* continue with next insn after call */
5402 			return 0;
5403 		}
5404 	}
5405 
5406 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5407 	if (!callee)
5408 		return -ENOMEM;
5409 	state->frame[state->curframe + 1] = callee;
5410 
5411 	/* callee cannot access r0, r6 - r9 for reading and has to write
5412 	 * into its own stack before reading from it.
5413 	 * callee can read/write into caller's stack
5414 	 */
5415 	init_func_state(env, callee,
5416 			/* remember the callsite, it will be used by bpf_exit */
5417 			*insn_idx /* callsite */,
5418 			state->curframe + 1 /* frameno within this callchain */,
5419 			subprog /* subprog number within this prog */);
5420 
5421 	/* Transfer references to the callee */
5422 	err = transfer_reference_state(callee, caller);
5423 	if (err)
5424 		return err;
5425 
5426 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5427 	 * pointers, which connects us up to the liveness chain
5428 	 */
5429 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5430 		callee->regs[i] = caller->regs[i];
5431 
5432 	clear_caller_saved_regs(env, caller->regs);
5433 
5434 	/* only increment it after check_reg_arg() finished */
5435 	state->curframe++;
5436 
5437 	/* and go analyze first insn of the callee */
5438 	*insn_idx = target_insn;
5439 
5440 	if (env->log.level & BPF_LOG_LEVEL) {
5441 		verbose(env, "caller:\n");
5442 		print_verifier_state(env, caller);
5443 		verbose(env, "callee:\n");
5444 		print_verifier_state(env, callee);
5445 	}
5446 	return 0;
5447 }
5448 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)5449 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5450 {
5451 	struct bpf_verifier_state *state = env->cur_state;
5452 	struct bpf_func_state *caller, *callee;
5453 	struct bpf_reg_state *r0;
5454 	int err;
5455 
5456 	callee = state->frame[state->curframe];
5457 	r0 = &callee->regs[BPF_REG_0];
5458 	if (r0->type == PTR_TO_STACK) {
5459 		/* technically it's ok to return caller's stack pointer
5460 		 * (or caller's caller's pointer) back to the caller,
5461 		 * since these pointers are valid. Only current stack
5462 		 * pointer will be invalid as soon as function exits,
5463 		 * but let's be conservative
5464 		 */
5465 		verbose(env, "cannot return stack pointer to the caller\n");
5466 		return -EINVAL;
5467 	}
5468 
5469 	state->curframe--;
5470 	caller = state->frame[state->curframe];
5471 	/* return to the caller whatever r0 had in the callee */
5472 	caller->regs[BPF_REG_0] = *r0;
5473 
5474 	/* Transfer references to the caller */
5475 	err = transfer_reference_state(caller, callee);
5476 	if (err)
5477 		return err;
5478 
5479 	*insn_idx = callee->callsite + 1;
5480 	if (env->log.level & BPF_LOG_LEVEL) {
5481 		verbose(env, "returning from callee:\n");
5482 		print_verifier_state(env, callee);
5483 		verbose(env, "to caller at %d:\n", *insn_idx);
5484 		print_verifier_state(env, caller);
5485 	}
5486 	/* clear everything in the callee */
5487 	free_func_state(callee);
5488 	state->frame[state->curframe + 1] = NULL;
5489 	return 0;
5490 }
5491 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)5492 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5493 				   int func_id,
5494 				   struct bpf_call_arg_meta *meta)
5495 {
5496 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5497 
5498 	if (ret_type != RET_INTEGER ||
5499 	    (func_id != BPF_FUNC_get_stack &&
5500 	     func_id != BPF_FUNC_probe_read_str &&
5501 	     func_id != BPF_FUNC_probe_read_kernel_str &&
5502 	     func_id != BPF_FUNC_probe_read_user_str))
5503 		return;
5504 
5505 	ret_reg->smax_value = meta->msize_max_value;
5506 	ret_reg->s32_max_value = meta->msize_max_value;
5507 	ret_reg->smin_value = -MAX_ERRNO;
5508 	ret_reg->s32_min_value = -MAX_ERRNO;
5509 	reg_bounds_sync(ret_reg);
5510 }
5511 
5512 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5513 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5514 		int func_id, int insn_idx)
5515 {
5516 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5517 	struct bpf_map *map = meta->map_ptr;
5518 
5519 	if (func_id != BPF_FUNC_tail_call &&
5520 	    func_id != BPF_FUNC_map_lookup_elem &&
5521 	    func_id != BPF_FUNC_map_update_elem &&
5522 	    func_id != BPF_FUNC_map_delete_elem &&
5523 	    func_id != BPF_FUNC_map_push_elem &&
5524 	    func_id != BPF_FUNC_map_pop_elem &&
5525 	    func_id != BPF_FUNC_map_peek_elem)
5526 		return 0;
5527 
5528 	if (map == NULL) {
5529 		verbose(env, "kernel subsystem misconfigured verifier\n");
5530 		return -EINVAL;
5531 	}
5532 
5533 	/* In case of read-only, some additional restrictions
5534 	 * need to be applied in order to prevent altering the
5535 	 * state of the map from program side.
5536 	 */
5537 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5538 	    (func_id == BPF_FUNC_map_delete_elem ||
5539 	     func_id == BPF_FUNC_map_update_elem ||
5540 	     func_id == BPF_FUNC_map_push_elem ||
5541 	     func_id == BPF_FUNC_map_pop_elem)) {
5542 		verbose(env, "write into map forbidden\n");
5543 		return -EACCES;
5544 	}
5545 
5546 	if (!BPF_MAP_PTR(aux->map_ptr_state))
5547 		bpf_map_ptr_store(aux, meta->map_ptr,
5548 				  !meta->map_ptr->bypass_spec_v1);
5549 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5550 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5551 				  !meta->map_ptr->bypass_spec_v1);
5552 	return 0;
5553 }
5554 
5555 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5556 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5557 		int func_id, int insn_idx)
5558 {
5559 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5560 	struct bpf_reg_state *regs = cur_regs(env), *reg;
5561 	struct bpf_map *map = meta->map_ptr;
5562 	u64 val, max;
5563 	int err;
5564 
5565 	if (func_id != BPF_FUNC_tail_call)
5566 		return 0;
5567 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5568 		verbose(env, "kernel subsystem misconfigured verifier\n");
5569 		return -EINVAL;
5570 	}
5571 
5572 	reg = &regs[BPF_REG_3];
5573 	val = reg->var_off.value;
5574 	max = map->max_entries;
5575 
5576 	if (!(register_is_const(reg) && val < max)) {
5577 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5578 		return 0;
5579 	}
5580 
5581 	err = mark_chain_precision(env, BPF_REG_3);
5582 	if (err)
5583 		return err;
5584 	if (bpf_map_key_unseen(aux))
5585 		bpf_map_key_store(aux, val);
5586 	else if (!bpf_map_key_poisoned(aux) &&
5587 		  bpf_map_key_immediate(aux) != val)
5588 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5589 	return 0;
5590 }
5591 
check_reference_leak(struct bpf_verifier_env * env)5592 static int check_reference_leak(struct bpf_verifier_env *env)
5593 {
5594 	struct bpf_func_state *state = cur_func(env);
5595 	int i;
5596 
5597 	for (i = 0; i < state->acquired_refs; i++) {
5598 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5599 			state->refs[i].id, state->refs[i].insn_idx);
5600 	}
5601 	return state->acquired_refs ? -EINVAL : 0;
5602 }
5603 
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)5604 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5605 {
5606 	const struct bpf_func_proto *fn = NULL;
5607 	enum bpf_return_type ret_type;
5608 	enum bpf_type_flag ret_flag;
5609 	struct bpf_reg_state *regs;
5610 	struct bpf_call_arg_meta meta;
5611 	bool changes_data;
5612 	int i, err;
5613 
5614 	/* find function prototype */
5615 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5616 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5617 			func_id);
5618 		return -EINVAL;
5619 	}
5620 
5621 	if (env->ops->get_func_proto)
5622 		fn = env->ops->get_func_proto(func_id, env->prog);
5623 	if (!fn) {
5624 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5625 			func_id);
5626 		return -EINVAL;
5627 	}
5628 
5629 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5630 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5631 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5632 		return -EINVAL;
5633 	}
5634 
5635 	if (fn->allowed && !fn->allowed(env->prog)) {
5636 		verbose(env, "helper call is not allowed in probe\n");
5637 		return -EINVAL;
5638 	}
5639 
5640 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5641 	changes_data = bpf_helper_changes_pkt_data(fn->func);
5642 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5643 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5644 			func_id_name(func_id), func_id);
5645 		return -EINVAL;
5646 	}
5647 
5648 	memset(&meta, 0, sizeof(meta));
5649 	meta.pkt_access = fn->pkt_access;
5650 
5651 	err = check_func_proto(fn, func_id);
5652 	if (err) {
5653 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5654 			func_id_name(func_id), func_id);
5655 		return err;
5656 	}
5657 
5658 	meta.func_id = func_id;
5659 	/* check args */
5660 	for (i = 0; i < 5; i++) {
5661 		err = check_func_arg(env, i, &meta, fn);
5662 		if (err)
5663 			return err;
5664 	}
5665 
5666 	err = record_func_map(env, &meta, func_id, insn_idx);
5667 	if (err)
5668 		return err;
5669 
5670 	err = record_func_key(env, &meta, func_id, insn_idx);
5671 	if (err)
5672 		return err;
5673 
5674 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5675 	 * is inferred from register state.
5676 	 */
5677 	for (i = 0; i < meta.access_size; i++) {
5678 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5679 				       BPF_WRITE, -1, false);
5680 		if (err)
5681 			return err;
5682 	}
5683 
5684 	if (func_id == BPF_FUNC_tail_call) {
5685 		err = check_reference_leak(env);
5686 		if (err) {
5687 			verbose(env, "tail_call would lead to reference leak\n");
5688 			return err;
5689 		}
5690 	} else if (is_release_function(func_id)) {
5691 		err = release_reference(env, meta.ref_obj_id);
5692 		if (err) {
5693 			verbose(env, "func %s#%d reference has not been acquired before\n",
5694 				func_id_name(func_id), func_id);
5695 			return err;
5696 		}
5697 	}
5698 
5699 	regs = cur_regs(env);
5700 
5701 	/* check that flags argument in get_local_storage(map, flags) is 0,
5702 	 * this is required because get_local_storage() can't return an error.
5703 	 */
5704 	if (func_id == BPF_FUNC_get_local_storage &&
5705 	    !register_is_null(&regs[BPF_REG_2])) {
5706 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5707 		return -EINVAL;
5708 	}
5709 
5710 	/* reset caller saved regs */
5711 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5712 		mark_reg_not_init(env, regs, caller_saved[i]);
5713 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5714 	}
5715 
5716 	/* helper call returns 64-bit value. */
5717 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5718 
5719 	/* update return register (already marked as written above) */
5720 	ret_type = fn->ret_type;
5721 	ret_flag = type_flag(fn->ret_type);
5722 	if (ret_type == RET_INTEGER) {
5723 		/* sets type to SCALAR_VALUE */
5724 		mark_reg_unknown(env, regs, BPF_REG_0);
5725 	} else if (ret_type == RET_VOID) {
5726 		regs[BPF_REG_0].type = NOT_INIT;
5727 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
5728 		/* There is no offset yet applied, variable or fixed */
5729 		mark_reg_known_zero(env, regs, BPF_REG_0);
5730 		/* remember map_ptr, so that check_map_access()
5731 		 * can check 'value_size' boundary of memory access
5732 		 * to map element returned from bpf_map_lookup_elem()
5733 		 */
5734 		if (meta.map_ptr == NULL) {
5735 			verbose(env,
5736 				"kernel subsystem misconfigured verifier\n");
5737 			return -EINVAL;
5738 		}
5739 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
5740 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
5741 		if (!type_may_be_null(ret_type) &&
5742 		    map_value_has_spin_lock(meta.map_ptr)) {
5743 			regs[BPF_REG_0].id = ++env->id_gen;
5744 		}
5745 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
5746 		mark_reg_known_zero(env, regs, BPF_REG_0);
5747 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
5748 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
5749 		mark_reg_known_zero(env, regs, BPF_REG_0);
5750 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
5751 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
5752 		mark_reg_known_zero(env, regs, BPF_REG_0);
5753 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
5754 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
5755 		mark_reg_known_zero(env, regs, BPF_REG_0);
5756 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5757 		regs[BPF_REG_0].mem_size = meta.mem_size;
5758 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
5759 		const struct btf_type *t;
5760 
5761 		mark_reg_known_zero(env, regs, BPF_REG_0);
5762 		t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5763 		if (!btf_type_is_struct(t)) {
5764 			u32 tsize;
5765 			const struct btf_type *ret;
5766 			const char *tname;
5767 
5768 			/* resolve the type size of ksym. */
5769 			ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5770 			if (IS_ERR(ret)) {
5771 				tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5772 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
5773 					tname, PTR_ERR(ret));
5774 				return -EINVAL;
5775 			}
5776 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5777 			regs[BPF_REG_0].mem_size = tsize;
5778 		} else {
5779 			/* MEM_RDONLY may be carried from ret_flag, but it
5780 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
5781 			 * it will confuse the check of PTR_TO_BTF_ID in
5782 			 * check_mem_access().
5783 			 */
5784 			ret_flag &= ~MEM_RDONLY;
5785 
5786 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5787 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5788 		}
5789 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
5790 		int ret_btf_id;
5791 
5792 		mark_reg_known_zero(env, regs, BPF_REG_0);
5793 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5794 		ret_btf_id = *fn->ret_btf_id;
5795 		if (ret_btf_id == 0) {
5796 			verbose(env, "invalid return type %u of func %s#%d\n",
5797 				base_type(ret_type), func_id_name(func_id),
5798 				func_id);
5799 			return -EINVAL;
5800 		}
5801 		regs[BPF_REG_0].btf_id = ret_btf_id;
5802 	} else {
5803 		verbose(env, "unknown return type %u of func %s#%d\n",
5804 			base_type(ret_type), func_id_name(func_id), func_id);
5805 		return -EINVAL;
5806 	}
5807 
5808 	if (type_may_be_null(regs[BPF_REG_0].type))
5809 		regs[BPF_REG_0].id = ++env->id_gen;
5810 
5811 	if (is_ptr_cast_function(func_id)) {
5812 		/* For release_reference() */
5813 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5814 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
5815 		int id = acquire_reference_state(env, insn_idx);
5816 
5817 		if (id < 0)
5818 			return id;
5819 		/* For mark_ptr_or_null_reg() */
5820 		regs[BPF_REG_0].id = id;
5821 		/* For release_reference() */
5822 		regs[BPF_REG_0].ref_obj_id = id;
5823 	}
5824 
5825 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5826 
5827 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5828 	if (err)
5829 		return err;
5830 
5831 	if ((func_id == BPF_FUNC_get_stack ||
5832 	     func_id == BPF_FUNC_get_task_stack) &&
5833 	    !env->prog->has_callchain_buf) {
5834 		const char *err_str;
5835 
5836 #ifdef CONFIG_PERF_EVENTS
5837 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
5838 		err_str = "cannot get callchain buffer for func %s#%d\n";
5839 #else
5840 		err = -ENOTSUPP;
5841 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5842 #endif
5843 		if (err) {
5844 			verbose(env, err_str, func_id_name(func_id), func_id);
5845 			return err;
5846 		}
5847 
5848 		env->prog->has_callchain_buf = true;
5849 	}
5850 
5851 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5852 		env->prog->call_get_stack = true;
5853 
5854 	if (changes_data)
5855 		clear_all_pkt_pointers(env);
5856 	return 0;
5857 }
5858 
signed_add_overflows(s64 a,s64 b)5859 static bool signed_add_overflows(s64 a, s64 b)
5860 {
5861 	/* Do the add in u64, where overflow is well-defined */
5862 	s64 res = (s64)((u64)a + (u64)b);
5863 
5864 	if (b < 0)
5865 		return res > a;
5866 	return res < a;
5867 }
5868 
signed_add32_overflows(s32 a,s32 b)5869 static bool signed_add32_overflows(s32 a, s32 b)
5870 {
5871 	/* Do the add in u32, where overflow is well-defined */
5872 	s32 res = (s32)((u32)a + (u32)b);
5873 
5874 	if (b < 0)
5875 		return res > a;
5876 	return res < a;
5877 }
5878 
signed_sub_overflows(s64 a,s64 b)5879 static bool signed_sub_overflows(s64 a, s64 b)
5880 {
5881 	/* Do the sub in u64, where overflow is well-defined */
5882 	s64 res = (s64)((u64)a - (u64)b);
5883 
5884 	if (b < 0)
5885 		return res < a;
5886 	return res > a;
5887 }
5888 
signed_sub32_overflows(s32 a,s32 b)5889 static bool signed_sub32_overflows(s32 a, s32 b)
5890 {
5891 	/* Do the sub in u32, where overflow is well-defined */
5892 	s32 res = (s32)((u32)a - (u32)b);
5893 
5894 	if (b < 0)
5895 		return res < a;
5896 	return res > a;
5897 }
5898 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)5899 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5900 				  const struct bpf_reg_state *reg,
5901 				  enum bpf_reg_type type)
5902 {
5903 	bool known = tnum_is_const(reg->var_off);
5904 	s64 val = reg->var_off.value;
5905 	s64 smin = reg->smin_value;
5906 
5907 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5908 		verbose(env, "math between %s pointer and %lld is not allowed\n",
5909 			reg_type_str(env, type), val);
5910 		return false;
5911 	}
5912 
5913 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5914 		verbose(env, "%s pointer offset %d is not allowed\n",
5915 			reg_type_str(env, type), reg->off);
5916 		return false;
5917 	}
5918 
5919 	if (smin == S64_MIN) {
5920 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5921 			reg_type_str(env, type));
5922 		return false;
5923 	}
5924 
5925 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5926 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
5927 			smin, reg_type_str(env, type));
5928 		return false;
5929 	}
5930 
5931 	return true;
5932 }
5933 
cur_aux(struct bpf_verifier_env * env)5934 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5935 {
5936 	return &env->insn_aux_data[env->insn_idx];
5937 }
5938 
5939 enum {
5940 	REASON_BOUNDS	= -1,
5941 	REASON_TYPE	= -2,
5942 	REASON_PATHS	= -3,
5943 	REASON_LIMIT	= -4,
5944 	REASON_STACK	= -5,
5945 };
5946 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)5947 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5948 			      u32 *alu_limit, bool mask_to_left)
5949 {
5950 	u32 max = 0, ptr_limit = 0;
5951 
5952 	switch (ptr_reg->type) {
5953 	case PTR_TO_STACK:
5954 		/* Offset 0 is out-of-bounds, but acceptable start for the
5955 		 * left direction, see BPF_REG_FP. Also, unknown scalar
5956 		 * offset where we would need to deal with min/max bounds is
5957 		 * currently prohibited for unprivileged.
5958 		 */
5959 		max = MAX_BPF_STACK + mask_to_left;
5960 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5961 		break;
5962 	case PTR_TO_MAP_VALUE:
5963 		max = ptr_reg->map_ptr->value_size;
5964 		ptr_limit = (mask_to_left ?
5965 			     ptr_reg->smin_value :
5966 			     ptr_reg->umax_value) + ptr_reg->off;
5967 		break;
5968 	default:
5969 		return REASON_TYPE;
5970 	}
5971 
5972 	if (ptr_limit >= max)
5973 		return REASON_LIMIT;
5974 	*alu_limit = ptr_limit;
5975 	return 0;
5976 }
5977 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)5978 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5979 				    const struct bpf_insn *insn)
5980 {
5981 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5982 }
5983 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)5984 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5985 				       u32 alu_state, u32 alu_limit)
5986 {
5987 	/* If we arrived here from different branches with different
5988 	 * state or limits to sanitize, then this won't work.
5989 	 */
5990 	if (aux->alu_state &&
5991 	    (aux->alu_state != alu_state ||
5992 	     aux->alu_limit != alu_limit))
5993 		return REASON_PATHS;
5994 
5995 	/* Corresponding fixup done in fixup_bpf_calls(). */
5996 	aux->alu_state = alu_state;
5997 	aux->alu_limit = alu_limit;
5998 	return 0;
5999 }
6000 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)6001 static int sanitize_val_alu(struct bpf_verifier_env *env,
6002 			    struct bpf_insn *insn)
6003 {
6004 	struct bpf_insn_aux_data *aux = cur_aux(env);
6005 
6006 	if (can_skip_alu_sanitation(env, insn))
6007 		return 0;
6008 
6009 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6010 }
6011 
sanitize_needed(u8 opcode)6012 static bool sanitize_needed(u8 opcode)
6013 {
6014 	return opcode == BPF_ADD || opcode == BPF_SUB;
6015 }
6016 
6017 struct bpf_sanitize_info {
6018 	struct bpf_insn_aux_data aux;
6019 	bool mask_to_left;
6020 };
6021 
6022 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)6023 sanitize_speculative_path(struct bpf_verifier_env *env,
6024 			  const struct bpf_insn *insn,
6025 			  u32 next_idx, u32 curr_idx)
6026 {
6027 	struct bpf_verifier_state *branch;
6028 	struct bpf_reg_state *regs;
6029 
6030 	branch = push_stack(env, next_idx, curr_idx, true);
6031 	if (branch && insn) {
6032 		regs = branch->frame[branch->curframe]->regs;
6033 		if (BPF_SRC(insn->code) == BPF_K) {
6034 			mark_reg_unknown(env, regs, insn->dst_reg);
6035 		} else if (BPF_SRC(insn->code) == BPF_X) {
6036 			mark_reg_unknown(env, regs, insn->dst_reg);
6037 			mark_reg_unknown(env, regs, insn->src_reg);
6038 		}
6039 	}
6040 	return branch;
6041 }
6042 
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)6043 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6044 			    struct bpf_insn *insn,
6045 			    const struct bpf_reg_state *ptr_reg,
6046 			    const struct bpf_reg_state *off_reg,
6047 			    struct bpf_reg_state *dst_reg,
6048 			    struct bpf_sanitize_info *info,
6049 			    const bool commit_window)
6050 {
6051 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6052 	struct bpf_verifier_state *vstate = env->cur_state;
6053 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6054 	bool off_is_neg = off_reg->smin_value < 0;
6055 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6056 	u8 opcode = BPF_OP(insn->code);
6057 	u32 alu_state, alu_limit;
6058 	struct bpf_reg_state tmp;
6059 	bool ret;
6060 	int err;
6061 
6062 	if (can_skip_alu_sanitation(env, insn))
6063 		return 0;
6064 
6065 	/* We already marked aux for masking from non-speculative
6066 	 * paths, thus we got here in the first place. We only care
6067 	 * to explore bad access from here.
6068 	 */
6069 	if (vstate->speculative)
6070 		goto do_sim;
6071 
6072 	if (!commit_window) {
6073 		if (!tnum_is_const(off_reg->var_off) &&
6074 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6075 			return REASON_BOUNDS;
6076 
6077 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6078 				     (opcode == BPF_SUB && !off_is_neg);
6079 	}
6080 
6081 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6082 	if (err < 0)
6083 		return err;
6084 
6085 	if (commit_window) {
6086 		/* In commit phase we narrow the masking window based on
6087 		 * the observed pointer move after the simulated operation.
6088 		 */
6089 		alu_state = info->aux.alu_state;
6090 		alu_limit = abs(info->aux.alu_limit - alu_limit);
6091 	} else {
6092 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6093 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6094 		alu_state |= ptr_is_dst_reg ?
6095 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6096 
6097 		/* Limit pruning on unknown scalars to enable deep search for
6098 		 * potential masking differences from other program paths.
6099 		 */
6100 		if (!off_is_imm)
6101 			env->explore_alu_limits = true;
6102 	}
6103 
6104 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6105 	if (err < 0)
6106 		return err;
6107 do_sim:
6108 	/* If we're in commit phase, we're done here given we already
6109 	 * pushed the truncated dst_reg into the speculative verification
6110 	 * stack.
6111 	 *
6112 	 * Also, when register is a known constant, we rewrite register-based
6113 	 * operation to immediate-based, and thus do not need masking (and as
6114 	 * a consequence, do not need to simulate the zero-truncation either).
6115 	 */
6116 	if (commit_window || off_is_imm)
6117 		return 0;
6118 
6119 	/* Simulate and find potential out-of-bounds access under
6120 	 * speculative execution from truncation as a result of
6121 	 * masking when off was not within expected range. If off
6122 	 * sits in dst, then we temporarily need to move ptr there
6123 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6124 	 * for cases where we use K-based arithmetic in one direction
6125 	 * and truncated reg-based in the other in order to explore
6126 	 * bad access.
6127 	 */
6128 	if (!ptr_is_dst_reg) {
6129 		tmp = *dst_reg;
6130 		copy_register_state(dst_reg, ptr_reg);
6131 	}
6132 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6133 					env->insn_idx);
6134 	if (!ptr_is_dst_reg && ret)
6135 		*dst_reg = tmp;
6136 	return !ret ? REASON_STACK : 0;
6137 }
6138 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)6139 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6140 {
6141 	struct bpf_verifier_state *vstate = env->cur_state;
6142 
6143 	/* If we simulate paths under speculation, we don't update the
6144 	 * insn as 'seen' such that when we verify unreachable paths in
6145 	 * the non-speculative domain, sanitize_dead_code() can still
6146 	 * rewrite/sanitize them.
6147 	 */
6148 	if (!vstate->speculative)
6149 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6150 }
6151 
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)6152 static int sanitize_err(struct bpf_verifier_env *env,
6153 			const struct bpf_insn *insn, int reason,
6154 			const struct bpf_reg_state *off_reg,
6155 			const struct bpf_reg_state *dst_reg)
6156 {
6157 	static const char *err = "pointer arithmetic with it prohibited for !root";
6158 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6159 	u32 dst = insn->dst_reg, src = insn->src_reg;
6160 
6161 	switch (reason) {
6162 	case REASON_BOUNDS:
6163 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6164 			off_reg == dst_reg ? dst : src, err);
6165 		break;
6166 	case REASON_TYPE:
6167 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6168 			off_reg == dst_reg ? src : dst, err);
6169 		break;
6170 	case REASON_PATHS:
6171 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6172 			dst, op, err);
6173 		break;
6174 	case REASON_LIMIT:
6175 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6176 			dst, op, err);
6177 		break;
6178 	case REASON_STACK:
6179 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6180 			dst, err);
6181 		break;
6182 	default:
6183 		verbose(env, "verifier internal error: unknown reason (%d)\n",
6184 			reason);
6185 		break;
6186 	}
6187 
6188 	return -EACCES;
6189 }
6190 
6191 /* check that stack access falls within stack limits and that 'reg' doesn't
6192  * have a variable offset.
6193  *
6194  * Variable offset is prohibited for unprivileged mode for simplicity since it
6195  * requires corresponding support in Spectre masking for stack ALU.  See also
6196  * retrieve_ptr_limit().
6197  *
6198  *
6199  * 'off' includes 'reg->off'.
6200  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)6201 static int check_stack_access_for_ptr_arithmetic(
6202 				struct bpf_verifier_env *env,
6203 				int regno,
6204 				const struct bpf_reg_state *reg,
6205 				int off)
6206 {
6207 	if (!tnum_is_const(reg->var_off)) {
6208 		char tn_buf[48];
6209 
6210 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6211 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6212 			regno, tn_buf, off);
6213 		return -EACCES;
6214 	}
6215 
6216 	if (off >= 0 || off < -MAX_BPF_STACK) {
6217 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6218 			"prohibited for !root; off=%d\n", regno, off);
6219 		return -EACCES;
6220 	}
6221 
6222 	return 0;
6223 }
6224 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)6225 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6226 				 const struct bpf_insn *insn,
6227 				 const struct bpf_reg_state *dst_reg)
6228 {
6229 	u32 dst = insn->dst_reg;
6230 
6231 	/* For unprivileged we require that resulting offset must be in bounds
6232 	 * in order to be able to sanitize access later on.
6233 	 */
6234 	if (env->bypass_spec_v1)
6235 		return 0;
6236 
6237 	switch (dst_reg->type) {
6238 	case PTR_TO_STACK:
6239 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6240 					dst_reg->off + dst_reg->var_off.value))
6241 			return -EACCES;
6242 		break;
6243 	case PTR_TO_MAP_VALUE:
6244 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6245 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6246 				"prohibited for !root\n", dst);
6247 			return -EACCES;
6248 		}
6249 		break;
6250 	default:
6251 		break;
6252 	}
6253 
6254 	return 0;
6255 }
6256 
6257 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6258  * Caller should also handle BPF_MOV case separately.
6259  * If we return -EACCES, caller may want to try again treating pointer as a
6260  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6261  */
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)6262 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6263 				   struct bpf_insn *insn,
6264 				   const struct bpf_reg_state *ptr_reg,
6265 				   const struct bpf_reg_state *off_reg)
6266 {
6267 	struct bpf_verifier_state *vstate = env->cur_state;
6268 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6269 	struct bpf_reg_state *regs = state->regs, *dst_reg;
6270 	bool known = tnum_is_const(off_reg->var_off);
6271 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6272 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6273 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6274 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6275 	struct bpf_sanitize_info info = {};
6276 	u8 opcode = BPF_OP(insn->code);
6277 	u32 dst = insn->dst_reg;
6278 	int ret;
6279 
6280 	dst_reg = &regs[dst];
6281 
6282 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6283 	    smin_val > smax_val || umin_val > umax_val) {
6284 		/* Taint dst register if offset had invalid bounds derived from
6285 		 * e.g. dead branches.
6286 		 */
6287 		__mark_reg_unknown(env, dst_reg);
6288 		return 0;
6289 	}
6290 
6291 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6292 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6293 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6294 			__mark_reg_unknown(env, dst_reg);
6295 			return 0;
6296 		}
6297 
6298 		verbose(env,
6299 			"R%d 32-bit pointer arithmetic prohibited\n",
6300 			dst);
6301 		return -EACCES;
6302 	}
6303 
6304 	if (ptr_reg->type & PTR_MAYBE_NULL) {
6305 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6306 			dst, reg_type_str(env, ptr_reg->type));
6307 		return -EACCES;
6308 	}
6309 
6310 	switch (base_type(ptr_reg->type)) {
6311 	case PTR_TO_FLOW_KEYS:
6312 		if (known)
6313 			break;
6314 		fallthrough;
6315 	case CONST_PTR_TO_MAP:
6316 		/* smin_val represents the known value */
6317 		if (known && smin_val == 0 && opcode == BPF_ADD)
6318 			break;
6319 		fallthrough;
6320 	case PTR_TO_PACKET_END:
6321 	case PTR_TO_SOCKET:
6322 	case PTR_TO_SOCK_COMMON:
6323 	case PTR_TO_TCP_SOCK:
6324 	case PTR_TO_XDP_SOCK:
6325 reject:
6326 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6327 			dst, reg_type_str(env, ptr_reg->type));
6328 		return -EACCES;
6329 	default:
6330 		if (type_may_be_null(ptr_reg->type))
6331 			goto reject;
6332 		break;
6333 	}
6334 
6335 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6336 	 * The id may be overwritten later if we create a new variable offset.
6337 	 */
6338 	dst_reg->type = ptr_reg->type;
6339 	dst_reg->id = ptr_reg->id;
6340 
6341 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6342 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6343 		return -EINVAL;
6344 
6345 	/* pointer types do not carry 32-bit bounds at the moment. */
6346 	__mark_reg32_unbounded(dst_reg);
6347 
6348 	if (sanitize_needed(opcode)) {
6349 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6350 				       &info, false);
6351 		if (ret < 0)
6352 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6353 	}
6354 
6355 	switch (opcode) {
6356 	case BPF_ADD:
6357 		/* We can take a fixed offset as long as it doesn't overflow
6358 		 * the s32 'off' field
6359 		 */
6360 		if (known && (ptr_reg->off + smin_val ==
6361 			      (s64)(s32)(ptr_reg->off + smin_val))) {
6362 			/* pointer += K.  Accumulate it into fixed offset */
6363 			dst_reg->smin_value = smin_ptr;
6364 			dst_reg->smax_value = smax_ptr;
6365 			dst_reg->umin_value = umin_ptr;
6366 			dst_reg->umax_value = umax_ptr;
6367 			dst_reg->var_off = ptr_reg->var_off;
6368 			dst_reg->off = ptr_reg->off + smin_val;
6369 			dst_reg->raw = ptr_reg->raw;
6370 			break;
6371 		}
6372 		/* A new variable offset is created.  Note that off_reg->off
6373 		 * == 0, since it's a scalar.
6374 		 * dst_reg gets the pointer type and since some positive
6375 		 * integer value was added to the pointer, give it a new 'id'
6376 		 * if it's a PTR_TO_PACKET.
6377 		 * this creates a new 'base' pointer, off_reg (variable) gets
6378 		 * added into the variable offset, and we copy the fixed offset
6379 		 * from ptr_reg.
6380 		 */
6381 		if (signed_add_overflows(smin_ptr, smin_val) ||
6382 		    signed_add_overflows(smax_ptr, smax_val)) {
6383 			dst_reg->smin_value = S64_MIN;
6384 			dst_reg->smax_value = S64_MAX;
6385 		} else {
6386 			dst_reg->smin_value = smin_ptr + smin_val;
6387 			dst_reg->smax_value = smax_ptr + smax_val;
6388 		}
6389 		if (umin_ptr + umin_val < umin_ptr ||
6390 		    umax_ptr + umax_val < umax_ptr) {
6391 			dst_reg->umin_value = 0;
6392 			dst_reg->umax_value = U64_MAX;
6393 		} else {
6394 			dst_reg->umin_value = umin_ptr + umin_val;
6395 			dst_reg->umax_value = umax_ptr + umax_val;
6396 		}
6397 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6398 		dst_reg->off = ptr_reg->off;
6399 		dst_reg->raw = ptr_reg->raw;
6400 		if (reg_is_pkt_pointer(ptr_reg)) {
6401 			dst_reg->id = ++env->id_gen;
6402 			/* something was added to pkt_ptr, set range to zero */
6403 			dst_reg->raw = 0;
6404 		}
6405 		break;
6406 	case BPF_SUB:
6407 		if (dst_reg == off_reg) {
6408 			/* scalar -= pointer.  Creates an unknown scalar */
6409 			verbose(env, "R%d tried to subtract pointer from scalar\n",
6410 				dst);
6411 			return -EACCES;
6412 		}
6413 		/* We don't allow subtraction from FP, because (according to
6414 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
6415 		 * be able to deal with it.
6416 		 */
6417 		if (ptr_reg->type == PTR_TO_STACK) {
6418 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
6419 				dst);
6420 			return -EACCES;
6421 		}
6422 		if (known && (ptr_reg->off - smin_val ==
6423 			      (s64)(s32)(ptr_reg->off - smin_val))) {
6424 			/* pointer -= K.  Subtract it from fixed offset */
6425 			dst_reg->smin_value = smin_ptr;
6426 			dst_reg->smax_value = smax_ptr;
6427 			dst_reg->umin_value = umin_ptr;
6428 			dst_reg->umax_value = umax_ptr;
6429 			dst_reg->var_off = ptr_reg->var_off;
6430 			dst_reg->id = ptr_reg->id;
6431 			dst_reg->off = ptr_reg->off - smin_val;
6432 			dst_reg->raw = ptr_reg->raw;
6433 			break;
6434 		}
6435 		/* A new variable offset is created.  If the subtrahend is known
6436 		 * nonnegative, then any reg->range we had before is still good.
6437 		 */
6438 		if (signed_sub_overflows(smin_ptr, smax_val) ||
6439 		    signed_sub_overflows(smax_ptr, smin_val)) {
6440 			/* Overflow possible, we know nothing */
6441 			dst_reg->smin_value = S64_MIN;
6442 			dst_reg->smax_value = S64_MAX;
6443 		} else {
6444 			dst_reg->smin_value = smin_ptr - smax_val;
6445 			dst_reg->smax_value = smax_ptr - smin_val;
6446 		}
6447 		if (umin_ptr < umax_val) {
6448 			/* Overflow possible, we know nothing */
6449 			dst_reg->umin_value = 0;
6450 			dst_reg->umax_value = U64_MAX;
6451 		} else {
6452 			/* Cannot overflow (as long as bounds are consistent) */
6453 			dst_reg->umin_value = umin_ptr - umax_val;
6454 			dst_reg->umax_value = umax_ptr - umin_val;
6455 		}
6456 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6457 		dst_reg->off = ptr_reg->off;
6458 		dst_reg->raw = ptr_reg->raw;
6459 		if (reg_is_pkt_pointer(ptr_reg)) {
6460 			dst_reg->id = ++env->id_gen;
6461 			/* something was added to pkt_ptr, set range to zero */
6462 			if (smin_val < 0)
6463 				dst_reg->raw = 0;
6464 		}
6465 		break;
6466 	case BPF_AND:
6467 	case BPF_OR:
6468 	case BPF_XOR:
6469 		/* bitwise ops on pointers are troublesome, prohibit. */
6470 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6471 			dst, bpf_alu_string[opcode >> 4]);
6472 		return -EACCES;
6473 	default:
6474 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
6475 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6476 			dst, bpf_alu_string[opcode >> 4]);
6477 		return -EACCES;
6478 	}
6479 
6480 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6481 		return -EINVAL;
6482 	reg_bounds_sync(dst_reg);
6483 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6484 		return -EACCES;
6485 	if (sanitize_needed(opcode)) {
6486 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6487 				       &info, true);
6488 		if (ret < 0)
6489 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6490 	}
6491 
6492 	return 0;
6493 }
6494 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6495 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6496 				 struct bpf_reg_state *src_reg)
6497 {
6498 	s32 smin_val = src_reg->s32_min_value;
6499 	s32 smax_val = src_reg->s32_max_value;
6500 	u32 umin_val = src_reg->u32_min_value;
6501 	u32 umax_val = src_reg->u32_max_value;
6502 
6503 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6504 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6505 		dst_reg->s32_min_value = S32_MIN;
6506 		dst_reg->s32_max_value = S32_MAX;
6507 	} else {
6508 		dst_reg->s32_min_value += smin_val;
6509 		dst_reg->s32_max_value += smax_val;
6510 	}
6511 	if (dst_reg->u32_min_value + umin_val < umin_val ||
6512 	    dst_reg->u32_max_value + umax_val < umax_val) {
6513 		dst_reg->u32_min_value = 0;
6514 		dst_reg->u32_max_value = U32_MAX;
6515 	} else {
6516 		dst_reg->u32_min_value += umin_val;
6517 		dst_reg->u32_max_value += umax_val;
6518 	}
6519 }
6520 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6521 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6522 			       struct bpf_reg_state *src_reg)
6523 {
6524 	s64 smin_val = src_reg->smin_value;
6525 	s64 smax_val = src_reg->smax_value;
6526 	u64 umin_val = src_reg->umin_value;
6527 	u64 umax_val = src_reg->umax_value;
6528 
6529 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6530 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
6531 		dst_reg->smin_value = S64_MIN;
6532 		dst_reg->smax_value = S64_MAX;
6533 	} else {
6534 		dst_reg->smin_value += smin_val;
6535 		dst_reg->smax_value += smax_val;
6536 	}
6537 	if (dst_reg->umin_value + umin_val < umin_val ||
6538 	    dst_reg->umax_value + umax_val < umax_val) {
6539 		dst_reg->umin_value = 0;
6540 		dst_reg->umax_value = U64_MAX;
6541 	} else {
6542 		dst_reg->umin_value += umin_val;
6543 		dst_reg->umax_value += umax_val;
6544 	}
6545 }
6546 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6547 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6548 				 struct bpf_reg_state *src_reg)
6549 {
6550 	s32 smin_val = src_reg->s32_min_value;
6551 	s32 smax_val = src_reg->s32_max_value;
6552 	u32 umin_val = src_reg->u32_min_value;
6553 	u32 umax_val = src_reg->u32_max_value;
6554 
6555 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6556 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6557 		/* Overflow possible, we know nothing */
6558 		dst_reg->s32_min_value = S32_MIN;
6559 		dst_reg->s32_max_value = S32_MAX;
6560 	} else {
6561 		dst_reg->s32_min_value -= smax_val;
6562 		dst_reg->s32_max_value -= smin_val;
6563 	}
6564 	if (dst_reg->u32_min_value < umax_val) {
6565 		/* Overflow possible, we know nothing */
6566 		dst_reg->u32_min_value = 0;
6567 		dst_reg->u32_max_value = U32_MAX;
6568 	} else {
6569 		/* Cannot overflow (as long as bounds are consistent) */
6570 		dst_reg->u32_min_value -= umax_val;
6571 		dst_reg->u32_max_value -= umin_val;
6572 	}
6573 }
6574 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6575 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6576 			       struct bpf_reg_state *src_reg)
6577 {
6578 	s64 smin_val = src_reg->smin_value;
6579 	s64 smax_val = src_reg->smax_value;
6580 	u64 umin_val = src_reg->umin_value;
6581 	u64 umax_val = src_reg->umax_value;
6582 
6583 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6584 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6585 		/* Overflow possible, we know nothing */
6586 		dst_reg->smin_value = S64_MIN;
6587 		dst_reg->smax_value = S64_MAX;
6588 	} else {
6589 		dst_reg->smin_value -= smax_val;
6590 		dst_reg->smax_value -= smin_val;
6591 	}
6592 	if (dst_reg->umin_value < umax_val) {
6593 		/* Overflow possible, we know nothing */
6594 		dst_reg->umin_value = 0;
6595 		dst_reg->umax_value = U64_MAX;
6596 	} else {
6597 		/* Cannot overflow (as long as bounds are consistent) */
6598 		dst_reg->umin_value -= umax_val;
6599 		dst_reg->umax_value -= umin_val;
6600 	}
6601 }
6602 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6603 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6604 				 struct bpf_reg_state *src_reg)
6605 {
6606 	s32 smin_val = src_reg->s32_min_value;
6607 	u32 umin_val = src_reg->u32_min_value;
6608 	u32 umax_val = src_reg->u32_max_value;
6609 
6610 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6611 		/* Ain't nobody got time to multiply that sign */
6612 		__mark_reg32_unbounded(dst_reg);
6613 		return;
6614 	}
6615 	/* Both values are positive, so we can work with unsigned and
6616 	 * copy the result to signed (unless it exceeds S32_MAX).
6617 	 */
6618 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6619 		/* Potential overflow, we know nothing */
6620 		__mark_reg32_unbounded(dst_reg);
6621 		return;
6622 	}
6623 	dst_reg->u32_min_value *= umin_val;
6624 	dst_reg->u32_max_value *= umax_val;
6625 	if (dst_reg->u32_max_value > S32_MAX) {
6626 		/* Overflow possible, we know nothing */
6627 		dst_reg->s32_min_value = S32_MIN;
6628 		dst_reg->s32_max_value = S32_MAX;
6629 	} else {
6630 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6631 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6632 	}
6633 }
6634 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6635 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6636 			       struct bpf_reg_state *src_reg)
6637 {
6638 	s64 smin_val = src_reg->smin_value;
6639 	u64 umin_val = src_reg->umin_value;
6640 	u64 umax_val = src_reg->umax_value;
6641 
6642 	if (smin_val < 0 || dst_reg->smin_value < 0) {
6643 		/* Ain't nobody got time to multiply that sign */
6644 		__mark_reg64_unbounded(dst_reg);
6645 		return;
6646 	}
6647 	/* Both values are positive, so we can work with unsigned and
6648 	 * copy the result to signed (unless it exceeds S64_MAX).
6649 	 */
6650 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6651 		/* Potential overflow, we know nothing */
6652 		__mark_reg64_unbounded(dst_reg);
6653 		return;
6654 	}
6655 	dst_reg->umin_value *= umin_val;
6656 	dst_reg->umax_value *= umax_val;
6657 	if (dst_reg->umax_value > S64_MAX) {
6658 		/* Overflow possible, we know nothing */
6659 		dst_reg->smin_value = S64_MIN;
6660 		dst_reg->smax_value = S64_MAX;
6661 	} else {
6662 		dst_reg->smin_value = dst_reg->umin_value;
6663 		dst_reg->smax_value = dst_reg->umax_value;
6664 	}
6665 }
6666 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6667 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6668 				 struct bpf_reg_state *src_reg)
6669 {
6670 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6671 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6672 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6673 	s32 smin_val = src_reg->s32_min_value;
6674 	u32 umax_val = src_reg->u32_max_value;
6675 
6676 	if (src_known && dst_known) {
6677 		__mark_reg32_known(dst_reg, var32_off.value);
6678 		return;
6679 	}
6680 
6681 	/* We get our minimum from the var_off, since that's inherently
6682 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6683 	 */
6684 	dst_reg->u32_min_value = var32_off.value;
6685 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6686 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6687 		/* Lose signed bounds when ANDing negative numbers,
6688 		 * ain't nobody got time for that.
6689 		 */
6690 		dst_reg->s32_min_value = S32_MIN;
6691 		dst_reg->s32_max_value = S32_MAX;
6692 	} else {
6693 		/* ANDing two positives gives a positive, so safe to
6694 		 * cast result into s64.
6695 		 */
6696 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6697 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6698 	}
6699 }
6700 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6701 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6702 			       struct bpf_reg_state *src_reg)
6703 {
6704 	bool src_known = tnum_is_const(src_reg->var_off);
6705 	bool dst_known = tnum_is_const(dst_reg->var_off);
6706 	s64 smin_val = src_reg->smin_value;
6707 	u64 umax_val = src_reg->umax_value;
6708 
6709 	if (src_known && dst_known) {
6710 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6711 		return;
6712 	}
6713 
6714 	/* We get our minimum from the var_off, since that's inherently
6715 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6716 	 */
6717 	dst_reg->umin_value = dst_reg->var_off.value;
6718 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6719 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6720 		/* Lose signed bounds when ANDing negative numbers,
6721 		 * ain't nobody got time for that.
6722 		 */
6723 		dst_reg->smin_value = S64_MIN;
6724 		dst_reg->smax_value = S64_MAX;
6725 	} else {
6726 		/* ANDing two positives gives a positive, so safe to
6727 		 * cast result into s64.
6728 		 */
6729 		dst_reg->smin_value = dst_reg->umin_value;
6730 		dst_reg->smax_value = dst_reg->umax_value;
6731 	}
6732 	/* We may learn something more from the var_off */
6733 	__update_reg_bounds(dst_reg);
6734 }
6735 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6736 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6737 				struct bpf_reg_state *src_reg)
6738 {
6739 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6740 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6741 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6742 	s32 smin_val = src_reg->s32_min_value;
6743 	u32 umin_val = src_reg->u32_min_value;
6744 
6745 	if (src_known && dst_known) {
6746 		__mark_reg32_known(dst_reg, var32_off.value);
6747 		return;
6748 	}
6749 
6750 	/* We get our maximum from the var_off, and our minimum is the
6751 	 * maximum of the operands' minima
6752 	 */
6753 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6754 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6755 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6756 		/* Lose signed bounds when ORing negative numbers,
6757 		 * ain't nobody got time for that.
6758 		 */
6759 		dst_reg->s32_min_value = S32_MIN;
6760 		dst_reg->s32_max_value = S32_MAX;
6761 	} else {
6762 		/* ORing two positives gives a positive, so safe to
6763 		 * cast result into s64.
6764 		 */
6765 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6766 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6767 	}
6768 }
6769 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6770 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6771 			      struct bpf_reg_state *src_reg)
6772 {
6773 	bool src_known = tnum_is_const(src_reg->var_off);
6774 	bool dst_known = tnum_is_const(dst_reg->var_off);
6775 	s64 smin_val = src_reg->smin_value;
6776 	u64 umin_val = src_reg->umin_value;
6777 
6778 	if (src_known && dst_known) {
6779 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6780 		return;
6781 	}
6782 
6783 	/* We get our maximum from the var_off, and our minimum is the
6784 	 * maximum of the operands' minima
6785 	 */
6786 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6787 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6788 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6789 		/* Lose signed bounds when ORing negative numbers,
6790 		 * ain't nobody got time for that.
6791 		 */
6792 		dst_reg->smin_value = S64_MIN;
6793 		dst_reg->smax_value = S64_MAX;
6794 	} else {
6795 		/* ORing two positives gives a positive, so safe to
6796 		 * cast result into s64.
6797 		 */
6798 		dst_reg->smin_value = dst_reg->umin_value;
6799 		dst_reg->smax_value = dst_reg->umax_value;
6800 	}
6801 	/* We may learn something more from the var_off */
6802 	__update_reg_bounds(dst_reg);
6803 }
6804 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6805 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6806 				 struct bpf_reg_state *src_reg)
6807 {
6808 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6809 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6810 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6811 	s32 smin_val = src_reg->s32_min_value;
6812 
6813 	if (src_known && dst_known) {
6814 		__mark_reg32_known(dst_reg, var32_off.value);
6815 		return;
6816 	}
6817 
6818 	/* We get both minimum and maximum from the var32_off. */
6819 	dst_reg->u32_min_value = var32_off.value;
6820 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6821 
6822 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6823 		/* XORing two positive sign numbers gives a positive,
6824 		 * so safe to cast u32 result into s32.
6825 		 */
6826 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6827 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6828 	} else {
6829 		dst_reg->s32_min_value = S32_MIN;
6830 		dst_reg->s32_max_value = S32_MAX;
6831 	}
6832 }
6833 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6834 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6835 			       struct bpf_reg_state *src_reg)
6836 {
6837 	bool src_known = tnum_is_const(src_reg->var_off);
6838 	bool dst_known = tnum_is_const(dst_reg->var_off);
6839 	s64 smin_val = src_reg->smin_value;
6840 
6841 	if (src_known && dst_known) {
6842 		/* dst_reg->var_off.value has been updated earlier */
6843 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6844 		return;
6845 	}
6846 
6847 	/* We get both minimum and maximum from the var_off. */
6848 	dst_reg->umin_value = dst_reg->var_off.value;
6849 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6850 
6851 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6852 		/* XORing two positive sign numbers gives a positive,
6853 		 * so safe to cast u64 result into s64.
6854 		 */
6855 		dst_reg->smin_value = dst_reg->umin_value;
6856 		dst_reg->smax_value = dst_reg->umax_value;
6857 	} else {
6858 		dst_reg->smin_value = S64_MIN;
6859 		dst_reg->smax_value = S64_MAX;
6860 	}
6861 
6862 	__update_reg_bounds(dst_reg);
6863 }
6864 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6865 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6866 				   u64 umin_val, u64 umax_val)
6867 {
6868 	/* We lose all sign bit information (except what we can pick
6869 	 * up from var_off)
6870 	 */
6871 	dst_reg->s32_min_value = S32_MIN;
6872 	dst_reg->s32_max_value = S32_MAX;
6873 	/* If we might shift our top bit out, then we know nothing */
6874 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6875 		dst_reg->u32_min_value = 0;
6876 		dst_reg->u32_max_value = U32_MAX;
6877 	} else {
6878 		dst_reg->u32_min_value <<= umin_val;
6879 		dst_reg->u32_max_value <<= umax_val;
6880 	}
6881 }
6882 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6883 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6884 				 struct bpf_reg_state *src_reg)
6885 {
6886 	u32 umax_val = src_reg->u32_max_value;
6887 	u32 umin_val = src_reg->u32_min_value;
6888 	/* u32 alu operation will zext upper bits */
6889 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6890 
6891 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6892 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6893 	/* Not required but being careful mark reg64 bounds as unknown so
6894 	 * that we are forced to pick them up from tnum and zext later and
6895 	 * if some path skips this step we are still safe.
6896 	 */
6897 	__mark_reg64_unbounded(dst_reg);
6898 	__update_reg32_bounds(dst_reg);
6899 }
6900 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6901 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6902 				   u64 umin_val, u64 umax_val)
6903 {
6904 	/* Special case <<32 because it is a common compiler pattern to sign
6905 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6906 	 * positive we know this shift will also be positive so we can track
6907 	 * bounds correctly. Otherwise we lose all sign bit information except
6908 	 * what we can pick up from var_off. Perhaps we can generalize this
6909 	 * later to shifts of any length.
6910 	 */
6911 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6912 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6913 	else
6914 		dst_reg->smax_value = S64_MAX;
6915 
6916 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6917 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6918 	else
6919 		dst_reg->smin_value = S64_MIN;
6920 
6921 	/* If we might shift our top bit out, then we know nothing */
6922 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6923 		dst_reg->umin_value = 0;
6924 		dst_reg->umax_value = U64_MAX;
6925 	} else {
6926 		dst_reg->umin_value <<= umin_val;
6927 		dst_reg->umax_value <<= umax_val;
6928 	}
6929 }
6930 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6931 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6932 			       struct bpf_reg_state *src_reg)
6933 {
6934 	u64 umax_val = src_reg->umax_value;
6935 	u64 umin_val = src_reg->umin_value;
6936 
6937 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
6938 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6939 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6940 
6941 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6942 	/* We may learn something more from the var_off */
6943 	__update_reg_bounds(dst_reg);
6944 }
6945 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6946 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6947 				 struct bpf_reg_state *src_reg)
6948 {
6949 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6950 	u32 umax_val = src_reg->u32_max_value;
6951 	u32 umin_val = src_reg->u32_min_value;
6952 
6953 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6954 	 * be negative, then either:
6955 	 * 1) src_reg might be zero, so the sign bit of the result is
6956 	 *    unknown, so we lose our signed bounds
6957 	 * 2) it's known negative, thus the unsigned bounds capture the
6958 	 *    signed bounds
6959 	 * 3) the signed bounds cross zero, so they tell us nothing
6960 	 *    about the result
6961 	 * If the value in dst_reg is known nonnegative, then again the
6962 	 * unsigned bounts capture the signed bounds.
6963 	 * Thus, in all cases it suffices to blow away our signed bounds
6964 	 * and rely on inferring new ones from the unsigned bounds and
6965 	 * var_off of the result.
6966 	 */
6967 	dst_reg->s32_min_value = S32_MIN;
6968 	dst_reg->s32_max_value = S32_MAX;
6969 
6970 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
6971 	dst_reg->u32_min_value >>= umax_val;
6972 	dst_reg->u32_max_value >>= umin_val;
6973 
6974 	__mark_reg64_unbounded(dst_reg);
6975 	__update_reg32_bounds(dst_reg);
6976 }
6977 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6978 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6979 			       struct bpf_reg_state *src_reg)
6980 {
6981 	u64 umax_val = src_reg->umax_value;
6982 	u64 umin_val = src_reg->umin_value;
6983 
6984 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6985 	 * be negative, then either:
6986 	 * 1) src_reg might be zero, so the sign bit of the result is
6987 	 *    unknown, so we lose our signed bounds
6988 	 * 2) it's known negative, thus the unsigned bounds capture the
6989 	 *    signed bounds
6990 	 * 3) the signed bounds cross zero, so they tell us nothing
6991 	 *    about the result
6992 	 * If the value in dst_reg is known nonnegative, then again the
6993 	 * unsigned bounts capture the signed bounds.
6994 	 * Thus, in all cases it suffices to blow away our signed bounds
6995 	 * and rely on inferring new ones from the unsigned bounds and
6996 	 * var_off of the result.
6997 	 */
6998 	dst_reg->smin_value = S64_MIN;
6999 	dst_reg->smax_value = S64_MAX;
7000 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7001 	dst_reg->umin_value >>= umax_val;
7002 	dst_reg->umax_value >>= umin_val;
7003 
7004 	/* Its not easy to operate on alu32 bounds here because it depends
7005 	 * on bits being shifted in. Take easy way out and mark unbounded
7006 	 * so we can recalculate later from tnum.
7007 	 */
7008 	__mark_reg32_unbounded(dst_reg);
7009 	__update_reg_bounds(dst_reg);
7010 }
7011 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7012 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7013 				  struct bpf_reg_state *src_reg)
7014 {
7015 	u64 umin_val = src_reg->u32_min_value;
7016 
7017 	/* Upon reaching here, src_known is true and
7018 	 * umax_val is equal to umin_val.
7019 	 */
7020 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7021 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7022 
7023 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7024 
7025 	/* blow away the dst_reg umin_value/umax_value and rely on
7026 	 * dst_reg var_off to refine the result.
7027 	 */
7028 	dst_reg->u32_min_value = 0;
7029 	dst_reg->u32_max_value = U32_MAX;
7030 
7031 	__mark_reg64_unbounded(dst_reg);
7032 	__update_reg32_bounds(dst_reg);
7033 }
7034 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7035 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7036 				struct bpf_reg_state *src_reg)
7037 {
7038 	u64 umin_val = src_reg->umin_value;
7039 
7040 	/* Upon reaching here, src_known is true and umax_val is equal
7041 	 * to umin_val.
7042 	 */
7043 	dst_reg->smin_value >>= umin_val;
7044 	dst_reg->smax_value >>= umin_val;
7045 
7046 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7047 
7048 	/* blow away the dst_reg umin_value/umax_value and rely on
7049 	 * dst_reg var_off to refine the result.
7050 	 */
7051 	dst_reg->umin_value = 0;
7052 	dst_reg->umax_value = U64_MAX;
7053 
7054 	/* Its not easy to operate on alu32 bounds here because it depends
7055 	 * on bits being shifted in from upper 32-bits. Take easy way out
7056 	 * and mark unbounded so we can recalculate later from tnum.
7057 	 */
7058 	__mark_reg32_unbounded(dst_reg);
7059 	__update_reg_bounds(dst_reg);
7060 }
7061 
7062 /* WARNING: This function does calculations on 64-bit values, but the actual
7063  * execution may occur on 32-bit values. Therefore, things like bitshifts
7064  * need extra checks in the 32-bit case.
7065  */
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)7066 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7067 				      struct bpf_insn *insn,
7068 				      struct bpf_reg_state *dst_reg,
7069 				      struct bpf_reg_state src_reg)
7070 {
7071 	struct bpf_reg_state *regs = cur_regs(env);
7072 	u8 opcode = BPF_OP(insn->code);
7073 	bool src_known;
7074 	s64 smin_val, smax_val;
7075 	u64 umin_val, umax_val;
7076 	s32 s32_min_val, s32_max_val;
7077 	u32 u32_min_val, u32_max_val;
7078 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7079 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7080 	int ret;
7081 
7082 	smin_val = src_reg.smin_value;
7083 	smax_val = src_reg.smax_value;
7084 	umin_val = src_reg.umin_value;
7085 	umax_val = src_reg.umax_value;
7086 
7087 	s32_min_val = src_reg.s32_min_value;
7088 	s32_max_val = src_reg.s32_max_value;
7089 	u32_min_val = src_reg.u32_min_value;
7090 	u32_max_val = src_reg.u32_max_value;
7091 
7092 	if (alu32) {
7093 		src_known = tnum_subreg_is_const(src_reg.var_off);
7094 		if ((src_known &&
7095 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7096 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7097 			/* Taint dst register if offset had invalid bounds
7098 			 * derived from e.g. dead branches.
7099 			 */
7100 			__mark_reg_unknown(env, dst_reg);
7101 			return 0;
7102 		}
7103 	} else {
7104 		src_known = tnum_is_const(src_reg.var_off);
7105 		if ((src_known &&
7106 		     (smin_val != smax_val || umin_val != umax_val)) ||
7107 		    smin_val > smax_val || umin_val > umax_val) {
7108 			/* Taint dst register if offset had invalid bounds
7109 			 * derived from e.g. dead branches.
7110 			 */
7111 			__mark_reg_unknown(env, dst_reg);
7112 			return 0;
7113 		}
7114 	}
7115 
7116 	if (!src_known &&
7117 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7118 		__mark_reg_unknown(env, dst_reg);
7119 		return 0;
7120 	}
7121 
7122 	if (sanitize_needed(opcode)) {
7123 		ret = sanitize_val_alu(env, insn);
7124 		if (ret < 0)
7125 			return sanitize_err(env, insn, ret, NULL, NULL);
7126 	}
7127 
7128 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7129 	 * There are two classes of instructions: The first class we track both
7130 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
7131 	 * greatest amount of precision when alu operations are mixed with jmp32
7132 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7133 	 * and BPF_OR. This is possible because these ops have fairly easy to
7134 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7135 	 * See alu32 verifier tests for examples. The second class of
7136 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7137 	 * with regards to tracking sign/unsigned bounds because the bits may
7138 	 * cross subreg boundaries in the alu64 case. When this happens we mark
7139 	 * the reg unbounded in the subreg bound space and use the resulting
7140 	 * tnum to calculate an approximation of the sign/unsigned bounds.
7141 	 */
7142 	switch (opcode) {
7143 	case BPF_ADD:
7144 		scalar32_min_max_add(dst_reg, &src_reg);
7145 		scalar_min_max_add(dst_reg, &src_reg);
7146 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7147 		break;
7148 	case BPF_SUB:
7149 		scalar32_min_max_sub(dst_reg, &src_reg);
7150 		scalar_min_max_sub(dst_reg, &src_reg);
7151 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7152 		break;
7153 	case BPF_MUL:
7154 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7155 		scalar32_min_max_mul(dst_reg, &src_reg);
7156 		scalar_min_max_mul(dst_reg, &src_reg);
7157 		break;
7158 	case BPF_AND:
7159 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7160 		scalar32_min_max_and(dst_reg, &src_reg);
7161 		scalar_min_max_and(dst_reg, &src_reg);
7162 		break;
7163 	case BPF_OR:
7164 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7165 		scalar32_min_max_or(dst_reg, &src_reg);
7166 		scalar_min_max_or(dst_reg, &src_reg);
7167 		break;
7168 	case BPF_XOR:
7169 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7170 		scalar32_min_max_xor(dst_reg, &src_reg);
7171 		scalar_min_max_xor(dst_reg, &src_reg);
7172 		break;
7173 	case BPF_LSH:
7174 		if (umax_val >= insn_bitness) {
7175 			/* Shifts greater than 31 or 63 are undefined.
7176 			 * This includes shifts by a negative number.
7177 			 */
7178 			mark_reg_unknown(env, regs, insn->dst_reg);
7179 			break;
7180 		}
7181 		if (alu32)
7182 			scalar32_min_max_lsh(dst_reg, &src_reg);
7183 		else
7184 			scalar_min_max_lsh(dst_reg, &src_reg);
7185 		break;
7186 	case BPF_RSH:
7187 		if (umax_val >= insn_bitness) {
7188 			/* Shifts greater than 31 or 63 are undefined.
7189 			 * This includes shifts by a negative number.
7190 			 */
7191 			mark_reg_unknown(env, regs, insn->dst_reg);
7192 			break;
7193 		}
7194 		if (alu32)
7195 			scalar32_min_max_rsh(dst_reg, &src_reg);
7196 		else
7197 			scalar_min_max_rsh(dst_reg, &src_reg);
7198 		break;
7199 	case BPF_ARSH:
7200 		if (umax_val >= insn_bitness) {
7201 			/* Shifts greater than 31 or 63 are undefined.
7202 			 * This includes shifts by a negative number.
7203 			 */
7204 			mark_reg_unknown(env, regs, insn->dst_reg);
7205 			break;
7206 		}
7207 		if (alu32)
7208 			scalar32_min_max_arsh(dst_reg, &src_reg);
7209 		else
7210 			scalar_min_max_arsh(dst_reg, &src_reg);
7211 		break;
7212 	default:
7213 		mark_reg_unknown(env, regs, insn->dst_reg);
7214 		break;
7215 	}
7216 
7217 	/* ALU32 ops are zero extended into 64bit register */
7218 	if (alu32)
7219 		zext_32_to_64(dst_reg);
7220 	reg_bounds_sync(dst_reg);
7221 	return 0;
7222 }
7223 
7224 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7225  * and var_off.
7226  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)7227 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7228 				   struct bpf_insn *insn)
7229 {
7230 	struct bpf_verifier_state *vstate = env->cur_state;
7231 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7232 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7233 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7234 	u8 opcode = BPF_OP(insn->code);
7235 	int err;
7236 
7237 	dst_reg = &regs[insn->dst_reg];
7238 	src_reg = NULL;
7239 	if (dst_reg->type != SCALAR_VALUE)
7240 		ptr_reg = dst_reg;
7241 	else
7242 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7243 		 * incorrectly propagated into other registers by find_equal_scalars()
7244 		 */
7245 		dst_reg->id = 0;
7246 	if (BPF_SRC(insn->code) == BPF_X) {
7247 		src_reg = &regs[insn->src_reg];
7248 		if (src_reg->type != SCALAR_VALUE) {
7249 			if (dst_reg->type != SCALAR_VALUE) {
7250 				/* Combining two pointers by any ALU op yields
7251 				 * an arbitrary scalar. Disallow all math except
7252 				 * pointer subtraction
7253 				 */
7254 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7255 					mark_reg_unknown(env, regs, insn->dst_reg);
7256 					return 0;
7257 				}
7258 				verbose(env, "R%d pointer %s pointer prohibited\n",
7259 					insn->dst_reg,
7260 					bpf_alu_string[opcode >> 4]);
7261 				return -EACCES;
7262 			} else {
7263 				/* scalar += pointer
7264 				 * This is legal, but we have to reverse our
7265 				 * src/dest handling in computing the range
7266 				 */
7267 				err = mark_chain_precision(env, insn->dst_reg);
7268 				if (err)
7269 					return err;
7270 				return adjust_ptr_min_max_vals(env, insn,
7271 							       src_reg, dst_reg);
7272 			}
7273 		} else if (ptr_reg) {
7274 			/* pointer += scalar */
7275 			err = mark_chain_precision(env, insn->src_reg);
7276 			if (err)
7277 				return err;
7278 			return adjust_ptr_min_max_vals(env, insn,
7279 						       dst_reg, src_reg);
7280 		} else if (dst_reg->precise) {
7281 			/* if dst_reg is precise, src_reg should be precise as well */
7282 			err = mark_chain_precision(env, insn->src_reg);
7283 			if (err)
7284 				return err;
7285 		}
7286 	} else {
7287 		/* Pretend the src is a reg with a known value, since we only
7288 		 * need to be able to read from this state.
7289 		 */
7290 		off_reg.type = SCALAR_VALUE;
7291 		__mark_reg_known(&off_reg, insn->imm);
7292 		src_reg = &off_reg;
7293 		if (ptr_reg) /* pointer += K */
7294 			return adjust_ptr_min_max_vals(env, insn,
7295 						       ptr_reg, src_reg);
7296 	}
7297 
7298 	/* Got here implies adding two SCALAR_VALUEs */
7299 	if (WARN_ON_ONCE(ptr_reg)) {
7300 		print_verifier_state(env, state);
7301 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
7302 		return -EINVAL;
7303 	}
7304 	if (WARN_ON(!src_reg)) {
7305 		print_verifier_state(env, state);
7306 		verbose(env, "verifier internal error: no src_reg\n");
7307 		return -EINVAL;
7308 	}
7309 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7310 }
7311 
7312 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)7313 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7314 {
7315 	struct bpf_reg_state *regs = cur_regs(env);
7316 	u8 opcode = BPF_OP(insn->code);
7317 	int err;
7318 
7319 	if (opcode == BPF_END || opcode == BPF_NEG) {
7320 		if (opcode == BPF_NEG) {
7321 			if (BPF_SRC(insn->code) != 0 ||
7322 			    insn->src_reg != BPF_REG_0 ||
7323 			    insn->off != 0 || insn->imm != 0) {
7324 				verbose(env, "BPF_NEG uses reserved fields\n");
7325 				return -EINVAL;
7326 			}
7327 		} else {
7328 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7329 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7330 			    BPF_CLASS(insn->code) == BPF_ALU64) {
7331 				verbose(env, "BPF_END uses reserved fields\n");
7332 				return -EINVAL;
7333 			}
7334 		}
7335 
7336 		/* check src operand */
7337 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7338 		if (err)
7339 			return err;
7340 
7341 		if (is_pointer_value(env, insn->dst_reg)) {
7342 			verbose(env, "R%d pointer arithmetic prohibited\n",
7343 				insn->dst_reg);
7344 			return -EACCES;
7345 		}
7346 
7347 		/* check dest operand */
7348 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
7349 		if (err)
7350 			return err;
7351 
7352 	} else if (opcode == BPF_MOV) {
7353 
7354 		if (BPF_SRC(insn->code) == BPF_X) {
7355 			if (insn->imm != 0 || insn->off != 0) {
7356 				verbose(env, "BPF_MOV uses reserved fields\n");
7357 				return -EINVAL;
7358 			}
7359 
7360 			/* check src operand */
7361 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7362 			if (err)
7363 				return err;
7364 		} else {
7365 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7366 				verbose(env, "BPF_MOV uses reserved fields\n");
7367 				return -EINVAL;
7368 			}
7369 		}
7370 
7371 		/* check dest operand, mark as required later */
7372 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7373 		if (err)
7374 			return err;
7375 
7376 		if (BPF_SRC(insn->code) == BPF_X) {
7377 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
7378 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7379 
7380 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7381 				/* case: R1 = R2
7382 				 * copy register state to dest reg
7383 				 */
7384 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7385 					/* Assign src and dst registers the same ID
7386 					 * that will be used by find_equal_scalars()
7387 					 * to propagate min/max range.
7388 					 */
7389 					src_reg->id = ++env->id_gen;
7390 				copy_register_state(dst_reg, src_reg);
7391 				dst_reg->live |= REG_LIVE_WRITTEN;
7392 				dst_reg->subreg_def = DEF_NOT_SUBREG;
7393 			} else {
7394 				/* R1 = (u32) R2 */
7395 				if (is_pointer_value(env, insn->src_reg)) {
7396 					verbose(env,
7397 						"R%d partial copy of pointer\n",
7398 						insn->src_reg);
7399 					return -EACCES;
7400 				} else if (src_reg->type == SCALAR_VALUE) {
7401 					copy_register_state(dst_reg, src_reg);
7402 					/* Make sure ID is cleared otherwise
7403 					 * dst_reg min/max could be incorrectly
7404 					 * propagated into src_reg by find_equal_scalars()
7405 					 */
7406 					dst_reg->id = 0;
7407 					dst_reg->live |= REG_LIVE_WRITTEN;
7408 					dst_reg->subreg_def = env->insn_idx + 1;
7409 				} else {
7410 					mark_reg_unknown(env, regs,
7411 							 insn->dst_reg);
7412 				}
7413 				zext_32_to_64(dst_reg);
7414 				reg_bounds_sync(dst_reg);
7415 			}
7416 		} else {
7417 			/* case: R = imm
7418 			 * remember the value we stored into this reg
7419 			 */
7420 			/* clear any state __mark_reg_known doesn't set */
7421 			mark_reg_unknown(env, regs, insn->dst_reg);
7422 			regs[insn->dst_reg].type = SCALAR_VALUE;
7423 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7424 				__mark_reg_known(regs + insn->dst_reg,
7425 						 insn->imm);
7426 			} else {
7427 				__mark_reg_known(regs + insn->dst_reg,
7428 						 (u32)insn->imm);
7429 			}
7430 		}
7431 
7432 	} else if (opcode > BPF_END) {
7433 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7434 		return -EINVAL;
7435 
7436 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
7437 
7438 		if (BPF_SRC(insn->code) == BPF_X) {
7439 			if (insn->imm != 0 || insn->off != 0) {
7440 				verbose(env, "BPF_ALU uses reserved fields\n");
7441 				return -EINVAL;
7442 			}
7443 			/* check src1 operand */
7444 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7445 			if (err)
7446 				return err;
7447 		} else {
7448 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7449 				verbose(env, "BPF_ALU uses reserved fields\n");
7450 				return -EINVAL;
7451 			}
7452 		}
7453 
7454 		/* check src2 operand */
7455 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7456 		if (err)
7457 			return err;
7458 
7459 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7460 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7461 			verbose(env, "div by zero\n");
7462 			return -EINVAL;
7463 		}
7464 
7465 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7466 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7467 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7468 
7469 			if (insn->imm < 0 || insn->imm >= size) {
7470 				verbose(env, "invalid shift %d\n", insn->imm);
7471 				return -EINVAL;
7472 			}
7473 		}
7474 
7475 		/* check dest operand */
7476 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7477 		if (err)
7478 			return err;
7479 
7480 		return adjust_reg_min_max_vals(env, insn);
7481 	}
7482 
7483 	return 0;
7484 }
7485 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)7486 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7487 				   struct bpf_reg_state *dst_reg,
7488 				   enum bpf_reg_type type,
7489 				   bool range_right_open)
7490 {
7491 	struct bpf_func_state *state;
7492 	struct bpf_reg_state *reg;
7493 	int new_range;
7494 
7495 	if (dst_reg->off < 0 ||
7496 	    (dst_reg->off == 0 && range_right_open))
7497 		/* This doesn't give us any range */
7498 		return;
7499 
7500 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
7501 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7502 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
7503 		 * than pkt_end, but that's because it's also less than pkt.
7504 		 */
7505 		return;
7506 
7507 	new_range = dst_reg->off;
7508 	if (range_right_open)
7509 		new_range++;
7510 
7511 	/* Examples for register markings:
7512 	 *
7513 	 * pkt_data in dst register:
7514 	 *
7515 	 *   r2 = r3;
7516 	 *   r2 += 8;
7517 	 *   if (r2 > pkt_end) goto <handle exception>
7518 	 *   <access okay>
7519 	 *
7520 	 *   r2 = r3;
7521 	 *   r2 += 8;
7522 	 *   if (r2 < pkt_end) goto <access okay>
7523 	 *   <handle exception>
7524 	 *
7525 	 *   Where:
7526 	 *     r2 == dst_reg, pkt_end == src_reg
7527 	 *     r2=pkt(id=n,off=8,r=0)
7528 	 *     r3=pkt(id=n,off=0,r=0)
7529 	 *
7530 	 * pkt_data in src register:
7531 	 *
7532 	 *   r2 = r3;
7533 	 *   r2 += 8;
7534 	 *   if (pkt_end >= r2) goto <access okay>
7535 	 *   <handle exception>
7536 	 *
7537 	 *   r2 = r3;
7538 	 *   r2 += 8;
7539 	 *   if (pkt_end <= r2) goto <handle exception>
7540 	 *   <access okay>
7541 	 *
7542 	 *   Where:
7543 	 *     pkt_end == dst_reg, r2 == src_reg
7544 	 *     r2=pkt(id=n,off=8,r=0)
7545 	 *     r3=pkt(id=n,off=0,r=0)
7546 	 *
7547 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7548 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7549 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
7550 	 * the check.
7551 	 */
7552 
7553 	/* If our ids match, then we must have the same max_value.  And we
7554 	 * don't care about the other reg's fixed offset, since if it's too big
7555 	 * the range won't allow anything.
7556 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7557 	 */
7558 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7559 		if (reg->type == type && reg->id == dst_reg->id)
7560 			/* keep the maximum range already checked */
7561 			reg->range = max(reg->range, new_range);
7562 	}));
7563 }
7564 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)7565 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7566 {
7567 	struct tnum subreg = tnum_subreg(reg->var_off);
7568 	s32 sval = (s32)val;
7569 
7570 	switch (opcode) {
7571 	case BPF_JEQ:
7572 		if (tnum_is_const(subreg))
7573 			return !!tnum_equals_const(subreg, val);
7574 		break;
7575 	case BPF_JNE:
7576 		if (tnum_is_const(subreg))
7577 			return !tnum_equals_const(subreg, val);
7578 		break;
7579 	case BPF_JSET:
7580 		if ((~subreg.mask & subreg.value) & val)
7581 			return 1;
7582 		if (!((subreg.mask | subreg.value) & val))
7583 			return 0;
7584 		break;
7585 	case BPF_JGT:
7586 		if (reg->u32_min_value > val)
7587 			return 1;
7588 		else if (reg->u32_max_value <= val)
7589 			return 0;
7590 		break;
7591 	case BPF_JSGT:
7592 		if (reg->s32_min_value > sval)
7593 			return 1;
7594 		else if (reg->s32_max_value <= sval)
7595 			return 0;
7596 		break;
7597 	case BPF_JLT:
7598 		if (reg->u32_max_value < val)
7599 			return 1;
7600 		else if (reg->u32_min_value >= val)
7601 			return 0;
7602 		break;
7603 	case BPF_JSLT:
7604 		if (reg->s32_max_value < sval)
7605 			return 1;
7606 		else if (reg->s32_min_value >= sval)
7607 			return 0;
7608 		break;
7609 	case BPF_JGE:
7610 		if (reg->u32_min_value >= val)
7611 			return 1;
7612 		else if (reg->u32_max_value < val)
7613 			return 0;
7614 		break;
7615 	case BPF_JSGE:
7616 		if (reg->s32_min_value >= sval)
7617 			return 1;
7618 		else if (reg->s32_max_value < sval)
7619 			return 0;
7620 		break;
7621 	case BPF_JLE:
7622 		if (reg->u32_max_value <= val)
7623 			return 1;
7624 		else if (reg->u32_min_value > val)
7625 			return 0;
7626 		break;
7627 	case BPF_JSLE:
7628 		if (reg->s32_max_value <= sval)
7629 			return 1;
7630 		else if (reg->s32_min_value > sval)
7631 			return 0;
7632 		break;
7633 	}
7634 
7635 	return -1;
7636 }
7637 
7638 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)7639 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7640 {
7641 	s64 sval = (s64)val;
7642 
7643 	switch (opcode) {
7644 	case BPF_JEQ:
7645 		if (tnum_is_const(reg->var_off))
7646 			return !!tnum_equals_const(reg->var_off, val);
7647 		break;
7648 	case BPF_JNE:
7649 		if (tnum_is_const(reg->var_off))
7650 			return !tnum_equals_const(reg->var_off, val);
7651 		break;
7652 	case BPF_JSET:
7653 		if ((~reg->var_off.mask & reg->var_off.value) & val)
7654 			return 1;
7655 		if (!((reg->var_off.mask | reg->var_off.value) & val))
7656 			return 0;
7657 		break;
7658 	case BPF_JGT:
7659 		if (reg->umin_value > val)
7660 			return 1;
7661 		else if (reg->umax_value <= val)
7662 			return 0;
7663 		break;
7664 	case BPF_JSGT:
7665 		if (reg->smin_value > sval)
7666 			return 1;
7667 		else if (reg->smax_value <= sval)
7668 			return 0;
7669 		break;
7670 	case BPF_JLT:
7671 		if (reg->umax_value < val)
7672 			return 1;
7673 		else if (reg->umin_value >= val)
7674 			return 0;
7675 		break;
7676 	case BPF_JSLT:
7677 		if (reg->smax_value < sval)
7678 			return 1;
7679 		else if (reg->smin_value >= sval)
7680 			return 0;
7681 		break;
7682 	case BPF_JGE:
7683 		if (reg->umin_value >= val)
7684 			return 1;
7685 		else if (reg->umax_value < val)
7686 			return 0;
7687 		break;
7688 	case BPF_JSGE:
7689 		if (reg->smin_value >= sval)
7690 			return 1;
7691 		else if (reg->smax_value < sval)
7692 			return 0;
7693 		break;
7694 	case BPF_JLE:
7695 		if (reg->umax_value <= val)
7696 			return 1;
7697 		else if (reg->umin_value > val)
7698 			return 0;
7699 		break;
7700 	case BPF_JSLE:
7701 		if (reg->smax_value <= sval)
7702 			return 1;
7703 		else if (reg->smin_value > sval)
7704 			return 0;
7705 		break;
7706 	}
7707 
7708 	return -1;
7709 }
7710 
7711 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7712  * and return:
7713  *  1 - branch will be taken and "goto target" will be executed
7714  *  0 - branch will not be taken and fall-through to next insn
7715  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7716  *      range [0,10]
7717  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)7718 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7719 			   bool is_jmp32)
7720 {
7721 	if (__is_pointer_value(false, reg)) {
7722 		if (!reg_type_not_null(reg->type))
7723 			return -1;
7724 
7725 		/* If pointer is valid tests against zero will fail so we can
7726 		 * use this to direct branch taken.
7727 		 */
7728 		if (val != 0)
7729 			return -1;
7730 
7731 		switch (opcode) {
7732 		case BPF_JEQ:
7733 			return 0;
7734 		case BPF_JNE:
7735 			return 1;
7736 		default:
7737 			return -1;
7738 		}
7739 	}
7740 
7741 	if (is_jmp32)
7742 		return is_branch32_taken(reg, val, opcode);
7743 	return is_branch64_taken(reg, val, opcode);
7744 }
7745 
flip_opcode(u32 opcode)7746 static int flip_opcode(u32 opcode)
7747 {
7748 	/* How can we transform "a <op> b" into "b <op> a"? */
7749 	static const u8 opcode_flip[16] = {
7750 		/* these stay the same */
7751 		[BPF_JEQ  >> 4] = BPF_JEQ,
7752 		[BPF_JNE  >> 4] = BPF_JNE,
7753 		[BPF_JSET >> 4] = BPF_JSET,
7754 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
7755 		[BPF_JGE  >> 4] = BPF_JLE,
7756 		[BPF_JGT  >> 4] = BPF_JLT,
7757 		[BPF_JLE  >> 4] = BPF_JGE,
7758 		[BPF_JLT  >> 4] = BPF_JGT,
7759 		[BPF_JSGE >> 4] = BPF_JSLE,
7760 		[BPF_JSGT >> 4] = BPF_JSLT,
7761 		[BPF_JSLE >> 4] = BPF_JSGE,
7762 		[BPF_JSLT >> 4] = BPF_JSGT
7763 	};
7764 	return opcode_flip[opcode >> 4];
7765 }
7766 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)7767 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7768 				   struct bpf_reg_state *src_reg,
7769 				   u8 opcode)
7770 {
7771 	struct bpf_reg_state *pkt;
7772 
7773 	if (src_reg->type == PTR_TO_PACKET_END) {
7774 		pkt = dst_reg;
7775 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
7776 		pkt = src_reg;
7777 		opcode = flip_opcode(opcode);
7778 	} else {
7779 		return -1;
7780 	}
7781 
7782 	if (pkt->range >= 0)
7783 		return -1;
7784 
7785 	switch (opcode) {
7786 	case BPF_JLE:
7787 		/* pkt <= pkt_end */
7788 		fallthrough;
7789 	case BPF_JGT:
7790 		/* pkt > pkt_end */
7791 		if (pkt->range == BEYOND_PKT_END)
7792 			/* pkt has at last one extra byte beyond pkt_end */
7793 			return opcode == BPF_JGT;
7794 		break;
7795 	case BPF_JLT:
7796 		/* pkt < pkt_end */
7797 		fallthrough;
7798 	case BPF_JGE:
7799 		/* pkt >= pkt_end */
7800 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7801 			return opcode == BPF_JGE;
7802 		break;
7803 	}
7804 	return -1;
7805 }
7806 
7807 /* Adjusts the register min/max values in the case that the dst_reg is the
7808  * variable register that we are working on, and src_reg is a constant or we're
7809  * simply doing a BPF_K check.
7810  * In JEQ/JNE cases we also adjust the var_off values.
7811  */
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)7812 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7813 			    struct bpf_reg_state *false_reg,
7814 			    u64 val, u32 val32,
7815 			    u8 opcode, bool is_jmp32)
7816 {
7817 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
7818 	struct tnum false_64off = false_reg->var_off;
7819 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
7820 	struct tnum true_64off = true_reg->var_off;
7821 	s64 sval = (s64)val;
7822 	s32 sval32 = (s32)val32;
7823 
7824 	/* If the dst_reg is a pointer, we can't learn anything about its
7825 	 * variable offset from the compare (unless src_reg were a pointer into
7826 	 * the same object, but we don't bother with that.
7827 	 * Since false_reg and true_reg have the same type by construction, we
7828 	 * only need to check one of them for pointerness.
7829 	 */
7830 	if (__is_pointer_value(false, false_reg))
7831 		return;
7832 
7833 	switch (opcode) {
7834 	/* JEQ/JNE comparison doesn't change the register equivalence.
7835 	 *
7836 	 * r1 = r2;
7837 	 * if (r1 == 42) goto label;
7838 	 * ...
7839 	 * label: // here both r1 and r2 are known to be 42.
7840 	 *
7841 	 * Hence when marking register as known preserve it's ID.
7842 	 */
7843 	case BPF_JEQ:
7844 		if (is_jmp32) {
7845 			__mark_reg32_known(true_reg, val32);
7846 			true_32off = tnum_subreg(true_reg->var_off);
7847 		} else {
7848 			___mark_reg_known(true_reg, val);
7849 			true_64off = true_reg->var_off;
7850 		}
7851 		break;
7852 	case BPF_JNE:
7853 		if (is_jmp32) {
7854 			__mark_reg32_known(false_reg, val32);
7855 			false_32off = tnum_subreg(false_reg->var_off);
7856 		} else {
7857 			___mark_reg_known(false_reg, val);
7858 			false_64off = false_reg->var_off;
7859 		}
7860 		break;
7861 	case BPF_JSET:
7862 		if (is_jmp32) {
7863 			false_32off = tnum_and(false_32off, tnum_const(~val32));
7864 			if (is_power_of_2(val32))
7865 				true_32off = tnum_or(true_32off,
7866 						     tnum_const(val32));
7867 		} else {
7868 			false_64off = tnum_and(false_64off, tnum_const(~val));
7869 			if (is_power_of_2(val))
7870 				true_64off = tnum_or(true_64off,
7871 						     tnum_const(val));
7872 		}
7873 		break;
7874 	case BPF_JGE:
7875 	case BPF_JGT:
7876 	{
7877 		if (is_jmp32) {
7878 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7879 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7880 
7881 			false_reg->u32_max_value = min(false_reg->u32_max_value,
7882 						       false_umax);
7883 			true_reg->u32_min_value = max(true_reg->u32_min_value,
7884 						      true_umin);
7885 		} else {
7886 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7887 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7888 
7889 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
7890 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
7891 		}
7892 		break;
7893 	}
7894 	case BPF_JSGE:
7895 	case BPF_JSGT:
7896 	{
7897 		if (is_jmp32) {
7898 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7899 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7900 
7901 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7902 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7903 		} else {
7904 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7905 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7906 
7907 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
7908 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
7909 		}
7910 		break;
7911 	}
7912 	case BPF_JLE:
7913 	case BPF_JLT:
7914 	{
7915 		if (is_jmp32) {
7916 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7917 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7918 
7919 			false_reg->u32_min_value = max(false_reg->u32_min_value,
7920 						       false_umin);
7921 			true_reg->u32_max_value = min(true_reg->u32_max_value,
7922 						      true_umax);
7923 		} else {
7924 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7925 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7926 
7927 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
7928 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
7929 		}
7930 		break;
7931 	}
7932 	case BPF_JSLE:
7933 	case BPF_JSLT:
7934 	{
7935 		if (is_jmp32) {
7936 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7937 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7938 
7939 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7940 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7941 		} else {
7942 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7943 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7944 
7945 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
7946 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
7947 		}
7948 		break;
7949 	}
7950 	default:
7951 		return;
7952 	}
7953 
7954 	if (is_jmp32) {
7955 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7956 					     tnum_subreg(false_32off));
7957 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7958 					    tnum_subreg(true_32off));
7959 		__reg_combine_32_into_64(false_reg);
7960 		__reg_combine_32_into_64(true_reg);
7961 	} else {
7962 		false_reg->var_off = false_64off;
7963 		true_reg->var_off = true_64off;
7964 		__reg_combine_64_into_32(false_reg);
7965 		__reg_combine_64_into_32(true_reg);
7966 	}
7967 }
7968 
7969 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7970  * the variable reg.
7971  */
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)7972 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7973 				struct bpf_reg_state *false_reg,
7974 				u64 val, u32 val32,
7975 				u8 opcode, bool is_jmp32)
7976 {
7977 	opcode = flip_opcode(opcode);
7978 	/* This uses zero as "not present in table"; luckily the zero opcode,
7979 	 * BPF_JA, can't get here.
7980 	 */
7981 	if (opcode)
7982 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7983 }
7984 
7985 /* 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)7986 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7987 				  struct bpf_reg_state *dst_reg)
7988 {
7989 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7990 							dst_reg->umin_value);
7991 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7992 							dst_reg->umax_value);
7993 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7994 							dst_reg->smin_value);
7995 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7996 							dst_reg->smax_value);
7997 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7998 							     dst_reg->var_off);
7999 	reg_bounds_sync(src_reg);
8000 	reg_bounds_sync(dst_reg);
8001 }
8002 
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)8003 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8004 				struct bpf_reg_state *true_dst,
8005 				struct bpf_reg_state *false_src,
8006 				struct bpf_reg_state *false_dst,
8007 				u8 opcode)
8008 {
8009 	switch (opcode) {
8010 	case BPF_JEQ:
8011 		__reg_combine_min_max(true_src, true_dst);
8012 		break;
8013 	case BPF_JNE:
8014 		__reg_combine_min_max(false_src, false_dst);
8015 		break;
8016 	}
8017 }
8018 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)8019 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8020 				 struct bpf_reg_state *reg, u32 id,
8021 				 bool is_null)
8022 {
8023 	if (type_may_be_null(reg->type) && reg->id == id &&
8024 	    !WARN_ON_ONCE(!reg->id)) {
8025 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8026 				 !tnum_equals_const(reg->var_off, 0) ||
8027 				 reg->off)) {
8028 			/* Old offset (both fixed and variable parts) should
8029 			 * have been known-zero, because we don't allow pointer
8030 			 * arithmetic on pointers that might be NULL. If we
8031 			 * see this happening, don't convert the register.
8032 			 */
8033 			return;
8034 		}
8035 		if (is_null) {
8036 			reg->type = SCALAR_VALUE;
8037 		} else if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
8038 			const struct bpf_map *map = reg->map_ptr;
8039 
8040 			if (map->inner_map_meta) {
8041 				reg->type = CONST_PTR_TO_MAP;
8042 				reg->map_ptr = map->inner_map_meta;
8043 			} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
8044 				reg->type = PTR_TO_XDP_SOCK;
8045 			} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
8046 				   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
8047 				reg->type = PTR_TO_SOCKET;
8048 			} else {
8049 				reg->type = PTR_TO_MAP_VALUE;
8050 			}
8051 		} else {
8052 			reg->type &= ~PTR_MAYBE_NULL;
8053 		}
8054 
8055 		if (is_null) {
8056 			/* We don't need id and ref_obj_id from this point
8057 			 * onwards anymore, thus we should better reset it,
8058 			 * so that state pruning has chances to take effect.
8059 			 */
8060 			reg->id = 0;
8061 			reg->ref_obj_id = 0;
8062 		} else if (!reg_may_point_to_spin_lock(reg)) {
8063 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8064 			 * in release_reference().
8065 			 *
8066 			 * reg->id is still used by spin_lock ptr. Other
8067 			 * than spin_lock ptr type, reg->id can be reset.
8068 			 */
8069 			reg->id = 0;
8070 		}
8071 	}
8072 }
8073 
8074 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8075  * be folded together at some point.
8076  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)8077 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8078 				  bool is_null)
8079 {
8080 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8081 	struct bpf_reg_state *regs = state->regs, *reg;
8082 	u32 ref_obj_id = regs[regno].ref_obj_id;
8083 	u32 id = regs[regno].id;
8084 
8085 	if (ref_obj_id && ref_obj_id == id && is_null)
8086 		/* regs[regno] is in the " == NULL" branch.
8087 		 * No one could have freed the reference state before
8088 		 * doing the NULL check.
8089 		 */
8090 		WARN_ON_ONCE(release_reference_state(state, id));
8091 
8092 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8093 		mark_ptr_or_null_reg(state, reg, id, is_null);
8094 	}));
8095 }
8096 
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)8097 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8098 				   struct bpf_reg_state *dst_reg,
8099 				   struct bpf_reg_state *src_reg,
8100 				   struct bpf_verifier_state *this_branch,
8101 				   struct bpf_verifier_state *other_branch)
8102 {
8103 	if (BPF_SRC(insn->code) != BPF_X)
8104 		return false;
8105 
8106 	/* Pointers are always 64-bit. */
8107 	if (BPF_CLASS(insn->code) == BPF_JMP32)
8108 		return false;
8109 
8110 	switch (BPF_OP(insn->code)) {
8111 	case BPF_JGT:
8112 		if ((dst_reg->type == PTR_TO_PACKET &&
8113 		     src_reg->type == PTR_TO_PACKET_END) ||
8114 		    (dst_reg->type == PTR_TO_PACKET_META &&
8115 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8116 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8117 			find_good_pkt_pointers(this_branch, dst_reg,
8118 					       dst_reg->type, false);
8119 			mark_pkt_end(other_branch, insn->dst_reg, true);
8120 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8121 			    src_reg->type == PTR_TO_PACKET) ||
8122 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8123 			    src_reg->type == PTR_TO_PACKET_META)) {
8124 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
8125 			find_good_pkt_pointers(other_branch, src_reg,
8126 					       src_reg->type, true);
8127 			mark_pkt_end(this_branch, insn->src_reg, false);
8128 		} else {
8129 			return false;
8130 		}
8131 		break;
8132 	case BPF_JLT:
8133 		if ((dst_reg->type == PTR_TO_PACKET &&
8134 		     src_reg->type == PTR_TO_PACKET_END) ||
8135 		    (dst_reg->type == PTR_TO_PACKET_META &&
8136 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8137 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8138 			find_good_pkt_pointers(other_branch, dst_reg,
8139 					       dst_reg->type, true);
8140 			mark_pkt_end(this_branch, insn->dst_reg, false);
8141 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8142 			    src_reg->type == PTR_TO_PACKET) ||
8143 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8144 			    src_reg->type == PTR_TO_PACKET_META)) {
8145 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
8146 			find_good_pkt_pointers(this_branch, src_reg,
8147 					       src_reg->type, false);
8148 			mark_pkt_end(other_branch, insn->src_reg, true);
8149 		} else {
8150 			return false;
8151 		}
8152 		break;
8153 	case BPF_JGE:
8154 		if ((dst_reg->type == PTR_TO_PACKET &&
8155 		     src_reg->type == PTR_TO_PACKET_END) ||
8156 		    (dst_reg->type == PTR_TO_PACKET_META &&
8157 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8158 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8159 			find_good_pkt_pointers(this_branch, dst_reg,
8160 					       dst_reg->type, true);
8161 			mark_pkt_end(other_branch, insn->dst_reg, false);
8162 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8163 			    src_reg->type == PTR_TO_PACKET) ||
8164 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8165 			    src_reg->type == PTR_TO_PACKET_META)) {
8166 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8167 			find_good_pkt_pointers(other_branch, src_reg,
8168 					       src_reg->type, false);
8169 			mark_pkt_end(this_branch, insn->src_reg, true);
8170 		} else {
8171 			return false;
8172 		}
8173 		break;
8174 	case BPF_JLE:
8175 		if ((dst_reg->type == PTR_TO_PACKET &&
8176 		     src_reg->type == PTR_TO_PACKET_END) ||
8177 		    (dst_reg->type == PTR_TO_PACKET_META &&
8178 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8179 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8180 			find_good_pkt_pointers(other_branch, dst_reg,
8181 					       dst_reg->type, false);
8182 			mark_pkt_end(this_branch, insn->dst_reg, true);
8183 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8184 			    src_reg->type == PTR_TO_PACKET) ||
8185 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8186 			    src_reg->type == PTR_TO_PACKET_META)) {
8187 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8188 			find_good_pkt_pointers(this_branch, src_reg,
8189 					       src_reg->type, true);
8190 			mark_pkt_end(other_branch, insn->src_reg, false);
8191 		} else {
8192 			return false;
8193 		}
8194 		break;
8195 	default:
8196 		return false;
8197 	}
8198 
8199 	return true;
8200 }
8201 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)8202 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8203 			       struct bpf_reg_state *known_reg)
8204 {
8205 	struct bpf_func_state *state;
8206 	struct bpf_reg_state *reg;
8207 
8208 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8209 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8210 			copy_register_state(reg, known_reg);
8211 	}));
8212 }
8213 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)8214 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8215 			     struct bpf_insn *insn, int *insn_idx)
8216 {
8217 	struct bpf_verifier_state *this_branch = env->cur_state;
8218 	struct bpf_verifier_state *other_branch;
8219 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8220 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8221 	u8 opcode = BPF_OP(insn->code);
8222 	bool is_jmp32;
8223 	int pred = -1;
8224 	int err;
8225 
8226 	/* Only conditional jumps are expected to reach here. */
8227 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8228 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8229 		return -EINVAL;
8230 	}
8231 
8232 	if (BPF_SRC(insn->code) == BPF_X) {
8233 		if (insn->imm != 0) {
8234 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8235 			return -EINVAL;
8236 		}
8237 
8238 		/* check src1 operand */
8239 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8240 		if (err)
8241 			return err;
8242 
8243 		if (is_pointer_value(env, insn->src_reg)) {
8244 			verbose(env, "R%d pointer comparison prohibited\n",
8245 				insn->src_reg);
8246 			return -EACCES;
8247 		}
8248 		src_reg = &regs[insn->src_reg];
8249 	} else {
8250 		if (insn->src_reg != BPF_REG_0) {
8251 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8252 			return -EINVAL;
8253 		}
8254 	}
8255 
8256 	/* check src2 operand */
8257 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8258 	if (err)
8259 		return err;
8260 
8261 	dst_reg = &regs[insn->dst_reg];
8262 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8263 
8264 	if (BPF_SRC(insn->code) == BPF_K) {
8265 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8266 	} else if (src_reg->type == SCALAR_VALUE &&
8267 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8268 		pred = is_branch_taken(dst_reg,
8269 				       tnum_subreg(src_reg->var_off).value,
8270 				       opcode,
8271 				       is_jmp32);
8272 	} else if (src_reg->type == SCALAR_VALUE &&
8273 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8274 		pred = is_branch_taken(dst_reg,
8275 				       src_reg->var_off.value,
8276 				       opcode,
8277 				       is_jmp32);
8278 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8279 		   reg_is_pkt_pointer_any(src_reg) &&
8280 		   !is_jmp32) {
8281 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8282 	}
8283 
8284 	if (pred >= 0) {
8285 		/* If we get here with a dst_reg pointer type it is because
8286 		 * above is_branch_taken() special cased the 0 comparison.
8287 		 */
8288 		if (!__is_pointer_value(false, dst_reg))
8289 			err = mark_chain_precision(env, insn->dst_reg);
8290 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8291 		    !__is_pointer_value(false, src_reg))
8292 			err = mark_chain_precision(env, insn->src_reg);
8293 		if (err)
8294 			return err;
8295 	}
8296 
8297 	if (pred == 1) {
8298 		/* Only follow the goto, ignore fall-through. If needed, push
8299 		 * the fall-through branch for simulation under speculative
8300 		 * execution.
8301 		 */
8302 		if (!env->bypass_spec_v1 &&
8303 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
8304 					       *insn_idx))
8305 			return -EFAULT;
8306 		*insn_idx += insn->off;
8307 		return 0;
8308 	} else if (pred == 0) {
8309 		/* Only follow the fall-through branch, since that's where the
8310 		 * program will go. If needed, push the goto branch for
8311 		 * simulation under speculative execution.
8312 		 */
8313 		if (!env->bypass_spec_v1 &&
8314 		    !sanitize_speculative_path(env, insn,
8315 					       *insn_idx + insn->off + 1,
8316 					       *insn_idx))
8317 			return -EFAULT;
8318 		return 0;
8319 	}
8320 
8321 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8322 				  false);
8323 	if (!other_branch)
8324 		return -EFAULT;
8325 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8326 
8327 	/* detect if we are comparing against a constant value so we can adjust
8328 	 * our min/max values for our dst register.
8329 	 * this is only legit if both are scalars (or pointers to the same
8330 	 * object, I suppose, but we don't support that right now), because
8331 	 * otherwise the different base pointers mean the offsets aren't
8332 	 * comparable.
8333 	 */
8334 	if (BPF_SRC(insn->code) == BPF_X) {
8335 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8336 
8337 		if (dst_reg->type == SCALAR_VALUE &&
8338 		    src_reg->type == SCALAR_VALUE) {
8339 			if (tnum_is_const(src_reg->var_off) ||
8340 			    (is_jmp32 &&
8341 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8342 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8343 						dst_reg,
8344 						src_reg->var_off.value,
8345 						tnum_subreg(src_reg->var_off).value,
8346 						opcode, is_jmp32);
8347 			else if (tnum_is_const(dst_reg->var_off) ||
8348 				 (is_jmp32 &&
8349 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8350 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8351 						    src_reg,
8352 						    dst_reg->var_off.value,
8353 						    tnum_subreg(dst_reg->var_off).value,
8354 						    opcode, is_jmp32);
8355 			else if (!is_jmp32 &&
8356 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8357 				/* Comparing for equality, we can combine knowledge */
8358 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8359 						    &other_branch_regs[insn->dst_reg],
8360 						    src_reg, dst_reg, opcode);
8361 			if (src_reg->id &&
8362 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8363 				find_equal_scalars(this_branch, src_reg);
8364 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8365 			}
8366 
8367 		}
8368 	} else if (dst_reg->type == SCALAR_VALUE) {
8369 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8370 					dst_reg, insn->imm, (u32)insn->imm,
8371 					opcode, is_jmp32);
8372 	}
8373 
8374 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8375 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8376 		find_equal_scalars(this_branch, dst_reg);
8377 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8378 	}
8379 
8380 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8381 	 * NOTE: these optimizations below are related with pointer comparison
8382 	 *       which will never be JMP32.
8383 	 */
8384 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8385 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8386 	    type_may_be_null(dst_reg->type)) {
8387 		/* Mark all identical registers in each branch as either
8388 		 * safe or unknown depending R == 0 or R != 0 conditional.
8389 		 */
8390 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8391 				      opcode == BPF_JNE);
8392 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8393 				      opcode == BPF_JEQ);
8394 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8395 					   this_branch, other_branch) &&
8396 		   is_pointer_value(env, insn->dst_reg)) {
8397 		verbose(env, "R%d pointer comparison prohibited\n",
8398 			insn->dst_reg);
8399 		return -EACCES;
8400 	}
8401 	if (env->log.level & BPF_LOG_LEVEL)
8402 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8403 	return 0;
8404 }
8405 
8406 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)8407 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8408 {
8409 	struct bpf_insn_aux_data *aux = cur_aux(env);
8410 	struct bpf_reg_state *regs = cur_regs(env);
8411 	struct bpf_reg_state *dst_reg;
8412 	struct bpf_map *map;
8413 	int err;
8414 
8415 	if (BPF_SIZE(insn->code) != BPF_DW) {
8416 		verbose(env, "invalid BPF_LD_IMM insn\n");
8417 		return -EINVAL;
8418 	}
8419 	if (insn->off != 0) {
8420 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8421 		return -EINVAL;
8422 	}
8423 
8424 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8425 	if (err)
8426 		return err;
8427 
8428 	dst_reg = &regs[insn->dst_reg];
8429 	if (insn->src_reg == 0) {
8430 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8431 
8432 		dst_reg->type = SCALAR_VALUE;
8433 		__mark_reg_known(&regs[insn->dst_reg], imm);
8434 		return 0;
8435 	}
8436 
8437 	/* All special src_reg cases are listed below. From this point onwards
8438 	 * we either succeed and assign a corresponding dst_reg->type after
8439 	 * zeroing the offset, or fail and reject the program.
8440 	 */
8441 	mark_reg_known_zero(env, regs, insn->dst_reg);
8442 
8443 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8444 		dst_reg->type = aux->btf_var.reg_type;
8445 		switch (base_type(dst_reg->type)) {
8446 		case PTR_TO_MEM:
8447 			dst_reg->mem_size = aux->btf_var.mem_size;
8448 			break;
8449 		case PTR_TO_BTF_ID:
8450 		case PTR_TO_PERCPU_BTF_ID:
8451 			dst_reg->btf_id = aux->btf_var.btf_id;
8452 			break;
8453 		default:
8454 			verbose(env, "bpf verifier is misconfigured\n");
8455 			return -EFAULT;
8456 		}
8457 		return 0;
8458 	}
8459 
8460 	map = env->used_maps[aux->map_index];
8461 	dst_reg->map_ptr = map;
8462 
8463 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8464 		dst_reg->type = PTR_TO_MAP_VALUE;
8465 		dst_reg->off = aux->map_off;
8466 		if (map_value_has_spin_lock(map))
8467 			dst_reg->id = ++env->id_gen;
8468 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8469 		dst_reg->type = CONST_PTR_TO_MAP;
8470 	} else {
8471 		verbose(env, "bpf verifier is misconfigured\n");
8472 		return -EINVAL;
8473 	}
8474 
8475 	return 0;
8476 }
8477 
may_access_skb(enum bpf_prog_type type)8478 static bool may_access_skb(enum bpf_prog_type type)
8479 {
8480 	switch (type) {
8481 	case BPF_PROG_TYPE_SOCKET_FILTER:
8482 	case BPF_PROG_TYPE_SCHED_CLS:
8483 	case BPF_PROG_TYPE_SCHED_ACT:
8484 		return true;
8485 	default:
8486 		return false;
8487 	}
8488 }
8489 
8490 /* verify safety of LD_ABS|LD_IND instructions:
8491  * - they can only appear in the programs where ctx == skb
8492  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8493  *   preserve R6-R9, and store return value into R0
8494  *
8495  * Implicit input:
8496  *   ctx == skb == R6 == CTX
8497  *
8498  * Explicit input:
8499  *   SRC == any register
8500  *   IMM == 32-bit immediate
8501  *
8502  * Output:
8503  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8504  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)8505 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8506 {
8507 	struct bpf_reg_state *regs = cur_regs(env);
8508 	static const int ctx_reg = BPF_REG_6;
8509 	u8 mode = BPF_MODE(insn->code);
8510 	int i, err;
8511 
8512 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8513 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8514 		return -EINVAL;
8515 	}
8516 
8517 	if (!env->ops->gen_ld_abs) {
8518 		verbose(env, "bpf verifier is misconfigured\n");
8519 		return -EINVAL;
8520 	}
8521 
8522 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8523 	    BPF_SIZE(insn->code) == BPF_DW ||
8524 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8525 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8526 		return -EINVAL;
8527 	}
8528 
8529 	/* check whether implicit source operand (register R6) is readable */
8530 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8531 	if (err)
8532 		return err;
8533 
8534 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8535 	 * gen_ld_abs() may terminate the program at runtime, leading to
8536 	 * reference leak.
8537 	 */
8538 	err = check_reference_leak(env);
8539 	if (err) {
8540 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8541 		return err;
8542 	}
8543 
8544 	if (env->cur_state->active_spin_lock) {
8545 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8546 		return -EINVAL;
8547 	}
8548 
8549 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8550 		verbose(env,
8551 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8552 		return -EINVAL;
8553 	}
8554 
8555 	if (mode == BPF_IND) {
8556 		/* check explicit source operand */
8557 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8558 		if (err)
8559 			return err;
8560 	}
8561 
8562 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
8563 	if (err < 0)
8564 		return err;
8565 
8566 	/* reset caller saved regs to unreadable */
8567 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8568 		mark_reg_not_init(env, regs, caller_saved[i]);
8569 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8570 	}
8571 
8572 	/* mark destination R0 register as readable, since it contains
8573 	 * the value fetched from the packet.
8574 	 * Already marked as written above.
8575 	 */
8576 	mark_reg_unknown(env, regs, BPF_REG_0);
8577 	/* ld_abs load up to 32-bit skb data. */
8578 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8579 	return 0;
8580 }
8581 
check_return_code(struct bpf_verifier_env * env)8582 static int check_return_code(struct bpf_verifier_env *env)
8583 {
8584 	struct tnum enforce_attach_type_range = tnum_unknown;
8585 	const struct bpf_prog *prog = env->prog;
8586 	struct bpf_reg_state *reg;
8587 	struct tnum range = tnum_range(0, 1);
8588 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8589 	int err;
8590 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8591 
8592 	/* LSM and struct_ops func-ptr's return type could be "void" */
8593 	if (!is_subprog &&
8594 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8595 	     prog_type == BPF_PROG_TYPE_LSM) &&
8596 	    !prog->aux->attach_func_proto->type)
8597 		return 0;
8598 
8599 	/* eBPF calling convetion is such that R0 is used
8600 	 * to return the value from eBPF program.
8601 	 * Make sure that it's readable at this time
8602 	 * of bpf_exit, which means that program wrote
8603 	 * something into it earlier
8604 	 */
8605 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8606 	if (err)
8607 		return err;
8608 
8609 	if (is_pointer_value(env, BPF_REG_0)) {
8610 		verbose(env, "R0 leaks addr as return value\n");
8611 		return -EACCES;
8612 	}
8613 
8614 	reg = cur_regs(env) + BPF_REG_0;
8615 	if (is_subprog) {
8616 		if (reg->type != SCALAR_VALUE) {
8617 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8618 				reg_type_str(env, reg->type));
8619 			return -EINVAL;
8620 		}
8621 		return 0;
8622 	}
8623 
8624 	switch (prog_type) {
8625 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8626 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8627 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8628 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8629 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8630 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8631 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8632 			range = tnum_range(1, 1);
8633 		break;
8634 	case BPF_PROG_TYPE_CGROUP_SKB:
8635 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8636 			range = tnum_range(0, 3);
8637 			enforce_attach_type_range = tnum_range(2, 3);
8638 		}
8639 		break;
8640 	case BPF_PROG_TYPE_CGROUP_SOCK:
8641 	case BPF_PROG_TYPE_SOCK_OPS:
8642 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8643 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8644 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8645 		break;
8646 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8647 		if (!env->prog->aux->attach_btf_id)
8648 			return 0;
8649 		range = tnum_const(0);
8650 		break;
8651 	case BPF_PROG_TYPE_TRACING:
8652 		switch (env->prog->expected_attach_type) {
8653 		case BPF_TRACE_FENTRY:
8654 		case BPF_TRACE_FEXIT:
8655 			range = tnum_const(0);
8656 			break;
8657 		case BPF_TRACE_RAW_TP:
8658 		case BPF_MODIFY_RETURN:
8659 			return 0;
8660 		case BPF_TRACE_ITER:
8661 			break;
8662 		default:
8663 			return -ENOTSUPP;
8664 		}
8665 		break;
8666 	case BPF_PROG_TYPE_SK_LOOKUP:
8667 		range = tnum_range(SK_DROP, SK_PASS);
8668 		break;
8669 	case BPF_PROG_TYPE_EXT:
8670 		/* freplace program can return anything as its return value
8671 		 * depends on the to-be-replaced kernel func or bpf program.
8672 		 */
8673 	default:
8674 		return 0;
8675 	}
8676 
8677 	if (reg->type != SCALAR_VALUE) {
8678 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8679 			reg_type_str(env, reg->type));
8680 		return -EINVAL;
8681 	}
8682 
8683 	if (!tnum_in(range, reg->var_off)) {
8684 		char tn_buf[48];
8685 
8686 		verbose(env, "At program exit the register R0 ");
8687 		if (!tnum_is_unknown(reg->var_off)) {
8688 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8689 			verbose(env, "has value %s", tn_buf);
8690 		} else {
8691 			verbose(env, "has unknown scalar value");
8692 		}
8693 		tnum_strn(tn_buf, sizeof(tn_buf), range);
8694 		verbose(env, " should have been in %s\n", tn_buf);
8695 		return -EINVAL;
8696 	}
8697 
8698 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8699 	    tnum_in(enforce_attach_type_range, reg->var_off))
8700 		env->prog->enforce_expected_attach_type = 1;
8701 	return 0;
8702 }
8703 
8704 /* non-recursive DFS pseudo code
8705  * 1  procedure DFS-iterative(G,v):
8706  * 2      label v as discovered
8707  * 3      let S be a stack
8708  * 4      S.push(v)
8709  * 5      while S is not empty
8710  * 6            t <- S.pop()
8711  * 7            if t is what we're looking for:
8712  * 8                return t
8713  * 9            for all edges e in G.adjacentEdges(t) do
8714  * 10               if edge e is already labelled
8715  * 11                   continue with the next edge
8716  * 12               w <- G.adjacentVertex(t,e)
8717  * 13               if vertex w is not discovered and not explored
8718  * 14                   label e as tree-edge
8719  * 15                   label w as discovered
8720  * 16                   S.push(w)
8721  * 17                   continue at 5
8722  * 18               else if vertex w is discovered
8723  * 19                   label e as back-edge
8724  * 20               else
8725  * 21                   // vertex w is explored
8726  * 22                   label e as forward- or cross-edge
8727  * 23           label t as explored
8728  * 24           S.pop()
8729  *
8730  * convention:
8731  * 0x10 - discovered
8732  * 0x11 - discovered and fall-through edge labelled
8733  * 0x12 - discovered and fall-through and branch edges labelled
8734  * 0x20 - explored
8735  */
8736 
8737 enum {
8738 	DISCOVERED = 0x10,
8739 	EXPLORED = 0x20,
8740 	FALLTHROUGH = 1,
8741 	BRANCH = 2,
8742 };
8743 
state_htab_size(struct bpf_verifier_env * env)8744 static u32 state_htab_size(struct bpf_verifier_env *env)
8745 {
8746 	return env->prog->len;
8747 }
8748 
explored_state(struct bpf_verifier_env * env,int idx)8749 static struct bpf_verifier_state_list **explored_state(
8750 					struct bpf_verifier_env *env,
8751 					int idx)
8752 {
8753 	struct bpf_verifier_state *cur = env->cur_state;
8754 	struct bpf_func_state *state = cur->frame[cur->curframe];
8755 
8756 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8757 }
8758 
init_explored_state(struct bpf_verifier_env * env,int idx)8759 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8760 {
8761 	env->insn_aux_data[idx].prune_point = true;
8762 }
8763 
8764 /* t, w, e - match pseudo-code above:
8765  * t - index of current instruction
8766  * w - next instruction
8767  * e - edge
8768  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)8769 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8770 		     bool loop_ok)
8771 {
8772 	int *insn_stack = env->cfg.insn_stack;
8773 	int *insn_state = env->cfg.insn_state;
8774 
8775 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8776 		return 0;
8777 
8778 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8779 		return 0;
8780 
8781 	if (w < 0 || w >= env->prog->len) {
8782 		verbose_linfo(env, t, "%d: ", t);
8783 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8784 		return -EINVAL;
8785 	}
8786 
8787 	if (e == BRANCH)
8788 		/* mark branch target for state pruning */
8789 		init_explored_state(env, w);
8790 
8791 	if (insn_state[w] == 0) {
8792 		/* tree-edge */
8793 		insn_state[t] = DISCOVERED | e;
8794 		insn_state[w] = DISCOVERED;
8795 		if (env->cfg.cur_stack >= env->prog->len)
8796 			return -E2BIG;
8797 		insn_stack[env->cfg.cur_stack++] = w;
8798 		return 1;
8799 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8800 		if (loop_ok && env->bpf_capable)
8801 			return 0;
8802 		verbose_linfo(env, t, "%d: ", t);
8803 		verbose_linfo(env, w, "%d: ", w);
8804 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8805 		return -EINVAL;
8806 	} else if (insn_state[w] == EXPLORED) {
8807 		/* forward- or cross-edge */
8808 		insn_state[t] = DISCOVERED | e;
8809 	} else {
8810 		verbose(env, "insn state internal bug\n");
8811 		return -EFAULT;
8812 	}
8813 	return 0;
8814 }
8815 
8816 /* non-recursive depth-first-search to detect loops in BPF program
8817  * loop == back-edge in directed graph
8818  */
check_cfg(struct bpf_verifier_env * env)8819 static int check_cfg(struct bpf_verifier_env *env)
8820 {
8821 	struct bpf_insn *insns = env->prog->insnsi;
8822 	int insn_cnt = env->prog->len;
8823 	int *insn_stack, *insn_state;
8824 	int ret = 0;
8825 	int i, t;
8826 
8827 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8828 	if (!insn_state)
8829 		return -ENOMEM;
8830 
8831 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8832 	if (!insn_stack) {
8833 		kvfree(insn_state);
8834 		return -ENOMEM;
8835 	}
8836 
8837 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8838 	insn_stack[0] = 0; /* 0 is the first instruction */
8839 	env->cfg.cur_stack = 1;
8840 
8841 peek_stack:
8842 	if (env->cfg.cur_stack == 0)
8843 		goto check_state;
8844 	t = insn_stack[env->cfg.cur_stack - 1];
8845 
8846 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8847 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
8848 		u8 opcode = BPF_OP(insns[t].code);
8849 
8850 		if (opcode == BPF_EXIT) {
8851 			goto mark_explored;
8852 		} else if (opcode == BPF_CALL) {
8853 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8854 			if (ret == 1)
8855 				goto peek_stack;
8856 			else if (ret < 0)
8857 				goto err_free;
8858 			if (t + 1 < insn_cnt)
8859 				init_explored_state(env, t + 1);
8860 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8861 				init_explored_state(env, t);
8862 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8863 						env, false);
8864 				if (ret == 1)
8865 					goto peek_stack;
8866 				else if (ret < 0)
8867 					goto err_free;
8868 			}
8869 		} else if (opcode == BPF_JA) {
8870 			if (BPF_SRC(insns[t].code) != BPF_K) {
8871 				ret = -EINVAL;
8872 				goto err_free;
8873 			}
8874 			/* unconditional jump with single edge */
8875 			ret = push_insn(t, t + insns[t].off + 1,
8876 					FALLTHROUGH, env, true);
8877 			if (ret == 1)
8878 				goto peek_stack;
8879 			else if (ret < 0)
8880 				goto err_free;
8881 			/* unconditional jmp is not a good pruning point,
8882 			 * but it's marked, since backtracking needs
8883 			 * to record jmp history in is_state_visited().
8884 			 */
8885 			init_explored_state(env, t + insns[t].off + 1);
8886 			/* tell verifier to check for equivalent states
8887 			 * after every call and jump
8888 			 */
8889 			if (t + 1 < insn_cnt)
8890 				init_explored_state(env, t + 1);
8891 		} else {
8892 			/* conditional jump with two edges */
8893 			init_explored_state(env, t);
8894 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8895 			if (ret == 1)
8896 				goto peek_stack;
8897 			else if (ret < 0)
8898 				goto err_free;
8899 
8900 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8901 			if (ret == 1)
8902 				goto peek_stack;
8903 			else if (ret < 0)
8904 				goto err_free;
8905 		}
8906 	} else {
8907 		/* all other non-branch instructions with single
8908 		 * fall-through edge
8909 		 */
8910 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8911 		if (ret == 1)
8912 			goto peek_stack;
8913 		else if (ret < 0)
8914 			goto err_free;
8915 	}
8916 
8917 mark_explored:
8918 	insn_state[t] = EXPLORED;
8919 	if (env->cfg.cur_stack-- <= 0) {
8920 		verbose(env, "pop stack internal bug\n");
8921 		ret = -EFAULT;
8922 		goto err_free;
8923 	}
8924 	goto peek_stack;
8925 
8926 check_state:
8927 	for (i = 0; i < insn_cnt; i++) {
8928 		if (insn_state[i] != EXPLORED) {
8929 			verbose(env, "unreachable insn %d\n", i);
8930 			ret = -EINVAL;
8931 			goto err_free;
8932 		}
8933 	}
8934 	ret = 0; /* cfg looks good */
8935 
8936 err_free:
8937 	kvfree(insn_state);
8938 	kvfree(insn_stack);
8939 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8940 	return ret;
8941 }
8942 
check_abnormal_return(struct bpf_verifier_env * env)8943 static int check_abnormal_return(struct bpf_verifier_env *env)
8944 {
8945 	int i;
8946 
8947 	for (i = 1; i < env->subprog_cnt; i++) {
8948 		if (env->subprog_info[i].has_ld_abs) {
8949 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8950 			return -EINVAL;
8951 		}
8952 		if (env->subprog_info[i].has_tail_call) {
8953 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8954 			return -EINVAL;
8955 		}
8956 	}
8957 	return 0;
8958 }
8959 
8960 /* The minimum supported BTF func info size */
8961 #define MIN_BPF_FUNCINFO_SIZE	8
8962 #define MAX_FUNCINFO_REC_SIZE	252
8963 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8964 static int check_btf_func(struct bpf_verifier_env *env,
8965 			  const union bpf_attr *attr,
8966 			  union bpf_attr __user *uattr)
8967 {
8968 	const struct btf_type *type, *func_proto, *ret_type;
8969 	u32 i, nfuncs, urec_size, min_size;
8970 	u32 krec_size = sizeof(struct bpf_func_info);
8971 	struct bpf_func_info *krecord;
8972 	struct bpf_func_info_aux *info_aux = NULL;
8973 	struct bpf_prog *prog;
8974 	const struct btf *btf;
8975 	void __user *urecord;
8976 	u32 prev_offset = 0;
8977 	bool scalar_return;
8978 	int ret = -ENOMEM;
8979 
8980 	nfuncs = attr->func_info_cnt;
8981 	if (!nfuncs) {
8982 		if (check_abnormal_return(env))
8983 			return -EINVAL;
8984 		return 0;
8985 	}
8986 
8987 	if (nfuncs != env->subprog_cnt) {
8988 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8989 		return -EINVAL;
8990 	}
8991 
8992 	urec_size = attr->func_info_rec_size;
8993 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8994 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
8995 	    urec_size % sizeof(u32)) {
8996 		verbose(env, "invalid func info rec size %u\n", urec_size);
8997 		return -EINVAL;
8998 	}
8999 
9000 	prog = env->prog;
9001 	btf = prog->aux->btf;
9002 
9003 	urecord = u64_to_user_ptr(attr->func_info);
9004 	min_size = min_t(u32, krec_size, urec_size);
9005 
9006 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9007 	if (!krecord)
9008 		return -ENOMEM;
9009 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9010 	if (!info_aux)
9011 		goto err_free;
9012 
9013 	for (i = 0; i < nfuncs; i++) {
9014 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9015 		if (ret) {
9016 			if (ret == -E2BIG) {
9017 				verbose(env, "nonzero tailing record in func info");
9018 				/* set the size kernel expects so loader can zero
9019 				 * out the rest of the record.
9020 				 */
9021 				if (put_user(min_size, &uattr->func_info_rec_size))
9022 					ret = -EFAULT;
9023 			}
9024 			goto err_free;
9025 		}
9026 
9027 		if (copy_from_user(&krecord[i], urecord, min_size)) {
9028 			ret = -EFAULT;
9029 			goto err_free;
9030 		}
9031 
9032 		/* check insn_off */
9033 		ret = -EINVAL;
9034 		if (i == 0) {
9035 			if (krecord[i].insn_off) {
9036 				verbose(env,
9037 					"nonzero insn_off %u for the first func info record",
9038 					krecord[i].insn_off);
9039 				goto err_free;
9040 			}
9041 		} else if (krecord[i].insn_off <= prev_offset) {
9042 			verbose(env,
9043 				"same or smaller insn offset (%u) than previous func info record (%u)",
9044 				krecord[i].insn_off, prev_offset);
9045 			goto err_free;
9046 		}
9047 
9048 		if (env->subprog_info[i].start != krecord[i].insn_off) {
9049 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9050 			goto err_free;
9051 		}
9052 
9053 		/* check type_id */
9054 		type = btf_type_by_id(btf, krecord[i].type_id);
9055 		if (!type || !btf_type_is_func(type)) {
9056 			verbose(env, "invalid type id %d in func info",
9057 				krecord[i].type_id);
9058 			goto err_free;
9059 		}
9060 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9061 
9062 		func_proto = btf_type_by_id(btf, type->type);
9063 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9064 			/* btf_func_check() already verified it during BTF load */
9065 			goto err_free;
9066 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9067 		scalar_return =
9068 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9069 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9070 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9071 			goto err_free;
9072 		}
9073 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9074 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9075 			goto err_free;
9076 		}
9077 
9078 		prev_offset = krecord[i].insn_off;
9079 		urecord += urec_size;
9080 	}
9081 
9082 	prog->aux->func_info = krecord;
9083 	prog->aux->func_info_cnt = nfuncs;
9084 	prog->aux->func_info_aux = info_aux;
9085 	return 0;
9086 
9087 err_free:
9088 	kvfree(krecord);
9089 	kfree(info_aux);
9090 	return ret;
9091 }
9092 
adjust_btf_func(struct bpf_verifier_env * env)9093 static void adjust_btf_func(struct bpf_verifier_env *env)
9094 {
9095 	struct bpf_prog_aux *aux = env->prog->aux;
9096 	int i;
9097 
9098 	if (!aux->func_info)
9099 		return;
9100 
9101 	for (i = 0; i < env->subprog_cnt; i++)
9102 		aux->func_info[i].insn_off = env->subprog_info[i].start;
9103 }
9104 
9105 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
9106 		sizeof(((struct bpf_line_info *)(0))->line_col))
9107 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
9108 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9109 static int check_btf_line(struct bpf_verifier_env *env,
9110 			  const union bpf_attr *attr,
9111 			  union bpf_attr __user *uattr)
9112 {
9113 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9114 	struct bpf_subprog_info *sub;
9115 	struct bpf_line_info *linfo;
9116 	struct bpf_prog *prog;
9117 	const struct btf *btf;
9118 	void __user *ulinfo;
9119 	int err;
9120 
9121 	nr_linfo = attr->line_info_cnt;
9122 	if (!nr_linfo)
9123 		return 0;
9124 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9125 		return -EINVAL;
9126 
9127 	rec_size = attr->line_info_rec_size;
9128 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9129 	    rec_size > MAX_LINEINFO_REC_SIZE ||
9130 	    rec_size & (sizeof(u32) - 1))
9131 		return -EINVAL;
9132 
9133 	/* Need to zero it in case the userspace may
9134 	 * pass in a smaller bpf_line_info object.
9135 	 */
9136 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9137 			 GFP_KERNEL | __GFP_NOWARN);
9138 	if (!linfo)
9139 		return -ENOMEM;
9140 
9141 	prog = env->prog;
9142 	btf = prog->aux->btf;
9143 
9144 	s = 0;
9145 	sub = env->subprog_info;
9146 	ulinfo = u64_to_user_ptr(attr->line_info);
9147 	expected_size = sizeof(struct bpf_line_info);
9148 	ncopy = min_t(u32, expected_size, rec_size);
9149 	for (i = 0; i < nr_linfo; i++) {
9150 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9151 		if (err) {
9152 			if (err == -E2BIG) {
9153 				verbose(env, "nonzero tailing record in line_info");
9154 				if (put_user(expected_size,
9155 					     &uattr->line_info_rec_size))
9156 					err = -EFAULT;
9157 			}
9158 			goto err_free;
9159 		}
9160 
9161 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9162 			err = -EFAULT;
9163 			goto err_free;
9164 		}
9165 
9166 		/*
9167 		 * Check insn_off to ensure
9168 		 * 1) strictly increasing AND
9169 		 * 2) bounded by prog->len
9170 		 *
9171 		 * The linfo[0].insn_off == 0 check logically falls into
9172 		 * the later "missing bpf_line_info for func..." case
9173 		 * because the first linfo[0].insn_off must be the
9174 		 * first sub also and the first sub must have
9175 		 * subprog_info[0].start == 0.
9176 		 */
9177 		if ((i && linfo[i].insn_off <= prev_offset) ||
9178 		    linfo[i].insn_off >= prog->len) {
9179 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9180 				i, linfo[i].insn_off, prev_offset,
9181 				prog->len);
9182 			err = -EINVAL;
9183 			goto err_free;
9184 		}
9185 
9186 		if (!prog->insnsi[linfo[i].insn_off].code) {
9187 			verbose(env,
9188 				"Invalid insn code at line_info[%u].insn_off\n",
9189 				i);
9190 			err = -EINVAL;
9191 			goto err_free;
9192 		}
9193 
9194 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9195 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9196 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9197 			err = -EINVAL;
9198 			goto err_free;
9199 		}
9200 
9201 		if (s != env->subprog_cnt) {
9202 			if (linfo[i].insn_off == sub[s].start) {
9203 				sub[s].linfo_idx = i;
9204 				s++;
9205 			} else if (sub[s].start < linfo[i].insn_off) {
9206 				verbose(env, "missing bpf_line_info for func#%u\n", s);
9207 				err = -EINVAL;
9208 				goto err_free;
9209 			}
9210 		}
9211 
9212 		prev_offset = linfo[i].insn_off;
9213 		ulinfo += rec_size;
9214 	}
9215 
9216 	if (s != env->subprog_cnt) {
9217 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9218 			env->subprog_cnt - s, s);
9219 		err = -EINVAL;
9220 		goto err_free;
9221 	}
9222 
9223 	prog->aux->linfo = linfo;
9224 	prog->aux->nr_linfo = nr_linfo;
9225 
9226 	return 0;
9227 
9228 err_free:
9229 	kvfree(linfo);
9230 	return err;
9231 }
9232 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9233 static int check_btf_info(struct bpf_verifier_env *env,
9234 			  const union bpf_attr *attr,
9235 			  union bpf_attr __user *uattr)
9236 {
9237 	struct btf *btf;
9238 	int err;
9239 
9240 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9241 		if (check_abnormal_return(env))
9242 			return -EINVAL;
9243 		return 0;
9244 	}
9245 
9246 	btf = btf_get_by_fd(attr->prog_btf_fd);
9247 	if (IS_ERR(btf))
9248 		return PTR_ERR(btf);
9249 	env->prog->aux->btf = btf;
9250 
9251 	err = check_btf_func(env, attr, uattr);
9252 	if (err)
9253 		return err;
9254 
9255 	err = check_btf_line(env, attr, uattr);
9256 	if (err)
9257 		return err;
9258 
9259 	return 0;
9260 }
9261 
9262 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)9263 static bool range_within(struct bpf_reg_state *old,
9264 			 struct bpf_reg_state *cur)
9265 {
9266 	return old->umin_value <= cur->umin_value &&
9267 	       old->umax_value >= cur->umax_value &&
9268 	       old->smin_value <= cur->smin_value &&
9269 	       old->smax_value >= cur->smax_value &&
9270 	       old->u32_min_value <= cur->u32_min_value &&
9271 	       old->u32_max_value >= cur->u32_max_value &&
9272 	       old->s32_min_value <= cur->s32_min_value &&
9273 	       old->s32_max_value >= cur->s32_max_value;
9274 }
9275 
9276 /* If in the old state two registers had the same id, then they need to have
9277  * the same id in the new state as well.  But that id could be different from
9278  * the old state, so we need to track the mapping from old to new ids.
9279  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9280  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9281  * regs with a different old id could still have new id 9, we don't care about
9282  * that.
9283  * So we look through our idmap to see if this old id has been seen before.  If
9284  * so, we require the new id to match; otherwise, we add the id pair to the map.
9285  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)9286 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9287 {
9288 	unsigned int i;
9289 
9290 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9291 		if (!idmap[i].old) {
9292 			/* Reached an empty slot; haven't seen this id before */
9293 			idmap[i].old = old_id;
9294 			idmap[i].cur = cur_id;
9295 			return true;
9296 		}
9297 		if (idmap[i].old == old_id)
9298 			return idmap[i].cur == cur_id;
9299 	}
9300 	/* We ran out of idmap slots, which should be impossible */
9301 	WARN_ON_ONCE(1);
9302 	return false;
9303 }
9304 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)9305 static void clean_func_state(struct bpf_verifier_env *env,
9306 			     struct bpf_func_state *st)
9307 {
9308 	enum bpf_reg_liveness live;
9309 	int i, j;
9310 
9311 	for (i = 0; i < BPF_REG_FP; i++) {
9312 		live = st->regs[i].live;
9313 		/* liveness must not touch this register anymore */
9314 		st->regs[i].live |= REG_LIVE_DONE;
9315 		if (!(live & REG_LIVE_READ))
9316 			/* since the register is unused, clear its state
9317 			 * to make further comparison simpler
9318 			 */
9319 			__mark_reg_not_init(env, &st->regs[i]);
9320 	}
9321 
9322 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9323 		live = st->stack[i].spilled_ptr.live;
9324 		/* liveness must not touch this stack slot anymore */
9325 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9326 		if (!(live & REG_LIVE_READ)) {
9327 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9328 			for (j = 0; j < BPF_REG_SIZE; j++)
9329 				st->stack[i].slot_type[j] = STACK_INVALID;
9330 		}
9331 	}
9332 }
9333 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)9334 static void clean_verifier_state(struct bpf_verifier_env *env,
9335 				 struct bpf_verifier_state *st)
9336 {
9337 	int i;
9338 
9339 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9340 		/* all regs in this state in all frames were already marked */
9341 		return;
9342 
9343 	for (i = 0; i <= st->curframe; i++)
9344 		clean_func_state(env, st->frame[i]);
9345 }
9346 
9347 /* the parentage chains form a tree.
9348  * the verifier states are added to state lists at given insn and
9349  * pushed into state stack for future exploration.
9350  * when the verifier reaches bpf_exit insn some of the verifer states
9351  * stored in the state lists have their final liveness state already,
9352  * but a lot of states will get revised from liveness point of view when
9353  * the verifier explores other branches.
9354  * Example:
9355  * 1: r0 = 1
9356  * 2: if r1 == 100 goto pc+1
9357  * 3: r0 = 2
9358  * 4: exit
9359  * when the verifier reaches exit insn the register r0 in the state list of
9360  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9361  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9362  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9363  *
9364  * Since the verifier pushes the branch states as it sees them while exploring
9365  * the program the condition of walking the branch instruction for the second
9366  * time means that all states below this branch were already explored and
9367  * their final liveness markes are already propagated.
9368  * Hence when the verifier completes the search of state list in is_state_visited()
9369  * we can call this clean_live_states() function to mark all liveness states
9370  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9371  * will not be used.
9372  * This function also clears the registers and stack for states that !READ
9373  * to simplify state merging.
9374  *
9375  * Important note here that walking the same branch instruction in the callee
9376  * doesn't meant that the states are DONE. The verifier has to compare
9377  * the callsites
9378  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)9379 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9380 			      struct bpf_verifier_state *cur)
9381 {
9382 	struct bpf_verifier_state_list *sl;
9383 	int i;
9384 
9385 	sl = *explored_state(env, insn);
9386 	while (sl) {
9387 		if (sl->state.branches)
9388 			goto next;
9389 		if (sl->state.insn_idx != insn ||
9390 		    sl->state.curframe != cur->curframe)
9391 			goto next;
9392 		for (i = 0; i <= cur->curframe; i++)
9393 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9394 				goto next;
9395 		clean_verifier_state(env, &sl->state);
9396 next:
9397 		sl = sl->next;
9398 	}
9399 }
9400 
9401 /* 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)9402 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9403 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9404 {
9405 	bool equal;
9406 
9407 	if (!(rold->live & REG_LIVE_READ))
9408 		/* explored state didn't use this */
9409 		return true;
9410 
9411 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9412 
9413 	if (rold->type == PTR_TO_STACK)
9414 		/* two stack pointers are equal only if they're pointing to
9415 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9416 		 */
9417 		return equal && rold->frameno == rcur->frameno;
9418 
9419 	if (equal)
9420 		return true;
9421 
9422 	if (rold->type == NOT_INIT)
9423 		/* explored state can't have used this */
9424 		return true;
9425 	if (rcur->type == NOT_INIT)
9426 		return false;
9427 	switch (base_type(rold->type)) {
9428 	case SCALAR_VALUE:
9429 		if (env->explore_alu_limits)
9430 			return false;
9431 		if (rcur->type == SCALAR_VALUE) {
9432 			if (!rold->precise)
9433 				return true;
9434 			/* new val must satisfy old val knowledge */
9435 			return range_within(rold, rcur) &&
9436 			       tnum_in(rold->var_off, rcur->var_off);
9437 		} else {
9438 			/* We're trying to use a pointer in place of a scalar.
9439 			 * Even if the scalar was unbounded, this could lead to
9440 			 * pointer leaks because scalars are allowed to leak
9441 			 * while pointers are not. We could make this safe in
9442 			 * special cases if root is calling us, but it's
9443 			 * probably not worth the hassle.
9444 			 */
9445 			return false;
9446 		}
9447 	case PTR_TO_MAP_VALUE:
9448 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9449 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9450 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9451 		 * checked, doing so could have affected others with the same
9452 		 * id, and we can't check for that because we lost the id when
9453 		 * we converted to a PTR_TO_MAP_VALUE.
9454 		 */
9455 		if (type_may_be_null(rold->type)) {
9456 			if (!type_may_be_null(rcur->type))
9457 				return false;
9458 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9459 				return false;
9460 			/* Check our ids match any regs they're supposed to */
9461 			return check_ids(rold->id, rcur->id, idmap);
9462 		}
9463 
9464 		/* If the new min/max/var_off satisfy the old ones and
9465 		 * everything else matches, we are OK.
9466 		 * 'id' is not compared, since it's only used for maps with
9467 		 * bpf_spin_lock inside map element and in such cases if
9468 		 * the rest of the prog is valid for one map element then
9469 		 * it's valid for all map elements regardless of the key
9470 		 * used in bpf_map_lookup()
9471 		 */
9472 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9473 		       range_within(rold, rcur) &&
9474 		       tnum_in(rold->var_off, rcur->var_off);
9475 	case PTR_TO_PACKET_META:
9476 	case PTR_TO_PACKET:
9477 		if (rcur->type != rold->type)
9478 			return false;
9479 		/* We must have at least as much range as the old ptr
9480 		 * did, so that any accesses which were safe before are
9481 		 * still safe.  This is true even if old range < old off,
9482 		 * since someone could have accessed through (ptr - k), or
9483 		 * even done ptr -= k in a register, to get a safe access.
9484 		 */
9485 		if (rold->range > rcur->range)
9486 			return false;
9487 		/* If the offsets don't match, we can't trust our alignment;
9488 		 * nor can we be sure that we won't fall out of range.
9489 		 */
9490 		if (rold->off != rcur->off)
9491 			return false;
9492 		/* id relations must be preserved */
9493 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9494 			return false;
9495 		/* new val must satisfy old val knowledge */
9496 		return range_within(rold, rcur) &&
9497 		       tnum_in(rold->var_off, rcur->var_off);
9498 	case PTR_TO_CTX:
9499 	case CONST_PTR_TO_MAP:
9500 	case PTR_TO_PACKET_END:
9501 	case PTR_TO_FLOW_KEYS:
9502 	case PTR_TO_SOCKET:
9503 	case PTR_TO_SOCK_COMMON:
9504 	case PTR_TO_TCP_SOCK:
9505 	case PTR_TO_XDP_SOCK:
9506 		/* Only valid matches are exact, which memcmp() above
9507 		 * would have accepted
9508 		 */
9509 	default:
9510 		/* Don't know what's going on, just say it's not safe */
9511 		return false;
9512 	}
9513 
9514 	/* Shouldn't get here; if we do, say it's not safe */
9515 	WARN_ON_ONCE(1);
9516 	return false;
9517 }
9518 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)9519 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9520 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9521 {
9522 	int i, spi;
9523 
9524 	/* walk slots of the explored stack and ignore any additional
9525 	 * slots in the current stack, since explored(safe) state
9526 	 * didn't use them
9527 	 */
9528 	for (i = 0; i < old->allocated_stack; i++) {
9529 		spi = i / BPF_REG_SIZE;
9530 
9531 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9532 			i += BPF_REG_SIZE - 1;
9533 			/* explored state didn't use this */
9534 			continue;
9535 		}
9536 
9537 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9538 			continue;
9539 
9540 		/* explored stack has more populated slots than current stack
9541 		 * and these slots were used
9542 		 */
9543 		if (i >= cur->allocated_stack)
9544 			return false;
9545 
9546 		/* if old state was safe with misc data in the stack
9547 		 * it will be safe with zero-initialized stack.
9548 		 * The opposite is not true
9549 		 */
9550 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9551 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9552 			continue;
9553 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9554 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9555 			/* Ex: old explored (safe) state has STACK_SPILL in
9556 			 * this stack slot, but current has STACK_MISC ->
9557 			 * this verifier states are not equivalent,
9558 			 * return false to continue verification of this path
9559 			 */
9560 			return false;
9561 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9562 			continue;
9563 		if (!is_spilled_reg(&old->stack[spi]))
9564 			continue;
9565 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
9566 			     &cur->stack[spi].spilled_ptr, idmap))
9567 			/* when explored and current stack slot are both storing
9568 			 * spilled registers, check that stored pointers types
9569 			 * are the same as well.
9570 			 * Ex: explored safe path could have stored
9571 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9572 			 * but current path has stored:
9573 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9574 			 * such verifier states are not equivalent.
9575 			 * return false to continue verification of this path
9576 			 */
9577 			return false;
9578 	}
9579 	return true;
9580 }
9581 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)9582 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9583 {
9584 	if (old->acquired_refs != cur->acquired_refs)
9585 		return false;
9586 	return !memcmp(old->refs, cur->refs,
9587 		       sizeof(*old->refs) * old->acquired_refs);
9588 }
9589 
9590 /* compare two verifier states
9591  *
9592  * all states stored in state_list are known to be valid, since
9593  * verifier reached 'bpf_exit' instruction through them
9594  *
9595  * this function is called when verifier exploring different branches of
9596  * execution popped from the state stack. If it sees an old state that has
9597  * more strict register state and more strict stack state then this execution
9598  * branch doesn't need to be explored further, since verifier already
9599  * concluded that more strict state leads to valid finish.
9600  *
9601  * Therefore two states are equivalent if register state is more conservative
9602  * and explored stack state is more conservative than the current one.
9603  * Example:
9604  *       explored                   current
9605  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9606  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9607  *
9608  * In other words if current stack state (one being explored) has more
9609  * valid slots than old one that already passed validation, it means
9610  * the verifier can stop exploring and conclude that current state is valid too
9611  *
9612  * Similarly with registers. If explored state has register type as invalid
9613  * whereas register type in current state is meaningful, it means that
9614  * the current state will reach 'bpf_exit' instruction safely
9615  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)9616 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9617 			      struct bpf_func_state *cur)
9618 {
9619 	int i;
9620 
9621 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9622 	for (i = 0; i < MAX_BPF_REG; i++)
9623 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
9624 			     env->idmap_scratch))
9625 			return false;
9626 
9627 	if (!stacksafe(env, old, cur, env->idmap_scratch))
9628 		return false;
9629 
9630 	if (!refsafe(old, cur))
9631 		return false;
9632 
9633 	return true;
9634 }
9635 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9636 static bool states_equal(struct bpf_verifier_env *env,
9637 			 struct bpf_verifier_state *old,
9638 			 struct bpf_verifier_state *cur)
9639 {
9640 	int i;
9641 
9642 	if (old->curframe != cur->curframe)
9643 		return false;
9644 
9645 	/* Verification state from speculative execution simulation
9646 	 * must never prune a non-speculative execution one.
9647 	 */
9648 	if (old->speculative && !cur->speculative)
9649 		return false;
9650 
9651 	if (old->active_spin_lock != cur->active_spin_lock)
9652 		return false;
9653 
9654 	/* for states to be equal callsites have to be the same
9655 	 * and all frame states need to be equivalent
9656 	 */
9657 	for (i = 0; i <= old->curframe; i++) {
9658 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9659 			return false;
9660 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9661 			return false;
9662 	}
9663 	return true;
9664 }
9665 
9666 /* Return 0 if no propagation happened. Return negative error code if error
9667  * happened. Otherwise, return the propagated bit.
9668  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)9669 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9670 				  struct bpf_reg_state *reg,
9671 				  struct bpf_reg_state *parent_reg)
9672 {
9673 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9674 	u8 flag = reg->live & REG_LIVE_READ;
9675 	int err;
9676 
9677 	/* When comes here, read flags of PARENT_REG or REG could be any of
9678 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9679 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9680 	 */
9681 	if (parent_flag == REG_LIVE_READ64 ||
9682 	    /* Or if there is no read flag from REG. */
9683 	    !flag ||
9684 	    /* Or if the read flag from REG is the same as PARENT_REG. */
9685 	    parent_flag == flag)
9686 		return 0;
9687 
9688 	err = mark_reg_read(env, reg, parent_reg, flag);
9689 	if (err)
9690 		return err;
9691 
9692 	return flag;
9693 }
9694 
9695 /* A write screens off any subsequent reads; but write marks come from the
9696  * straight-line code between a state and its parent.  When we arrive at an
9697  * equivalent state (jump target or such) we didn't arrive by the straight-line
9698  * code, so read marks in the state must propagate to the parent regardless
9699  * of the state's write marks. That's what 'parent == state->parent' comparison
9700  * in mark_reg_read() is for.
9701  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)9702 static int propagate_liveness(struct bpf_verifier_env *env,
9703 			      const struct bpf_verifier_state *vstate,
9704 			      struct bpf_verifier_state *vparent)
9705 {
9706 	struct bpf_reg_state *state_reg, *parent_reg;
9707 	struct bpf_func_state *state, *parent;
9708 	int i, frame, err = 0;
9709 
9710 	if (vparent->curframe != vstate->curframe) {
9711 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9712 		     vparent->curframe, vstate->curframe);
9713 		return -EFAULT;
9714 	}
9715 	/* Propagate read liveness of registers... */
9716 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9717 	for (frame = 0; frame <= vstate->curframe; frame++) {
9718 		parent = vparent->frame[frame];
9719 		state = vstate->frame[frame];
9720 		parent_reg = parent->regs;
9721 		state_reg = state->regs;
9722 		/* We don't need to worry about FP liveness, it's read-only */
9723 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9724 			err = propagate_liveness_reg(env, &state_reg[i],
9725 						     &parent_reg[i]);
9726 			if (err < 0)
9727 				return err;
9728 			if (err == REG_LIVE_READ64)
9729 				mark_insn_zext(env, &parent_reg[i]);
9730 		}
9731 
9732 		/* Propagate stack slots. */
9733 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9734 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9735 			parent_reg = &parent->stack[i].spilled_ptr;
9736 			state_reg = &state->stack[i].spilled_ptr;
9737 			err = propagate_liveness_reg(env, state_reg,
9738 						     parent_reg);
9739 			if (err < 0)
9740 				return err;
9741 		}
9742 	}
9743 	return 0;
9744 }
9745 
9746 /* find precise scalars in the previous equivalent state and
9747  * propagate them into the current state
9748  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)9749 static int propagate_precision(struct bpf_verifier_env *env,
9750 			       const struct bpf_verifier_state *old)
9751 {
9752 	struct bpf_reg_state *state_reg;
9753 	struct bpf_func_state *state;
9754 	int i, err = 0, fr;
9755 
9756 	for (fr = old->curframe; fr >= 0; fr--) {
9757 		state = old->frame[fr];
9758 		state_reg = state->regs;
9759 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9760 			if (state_reg->type != SCALAR_VALUE ||
9761 			    !state_reg->precise ||
9762 			    !(state_reg->live & REG_LIVE_READ))
9763 				continue;
9764 			if (env->log.level & BPF_LOG_LEVEL2)
9765 				verbose(env, "frame %d: propagating r%d\n", fr, i);
9766 			err = mark_chain_precision_frame(env, fr, i);
9767 			if (err < 0)
9768 				return err;
9769 		}
9770 
9771 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9772 			if (!is_spilled_reg(&state->stack[i]))
9773 				continue;
9774 			state_reg = &state->stack[i].spilled_ptr;
9775 			if (state_reg->type != SCALAR_VALUE ||
9776 			    !state_reg->precise ||
9777 			    !(state_reg->live & REG_LIVE_READ))
9778 				continue;
9779 			if (env->log.level & BPF_LOG_LEVEL2)
9780 				verbose(env, "frame %d: propagating fp%d\n",
9781 					fr, (-i - 1) * BPF_REG_SIZE);
9782 			err = mark_chain_precision_stack_frame(env, fr, i);
9783 			if (err < 0)
9784 				return err;
9785 		}
9786 	}
9787 	return 0;
9788 }
9789 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9790 static bool states_maybe_looping(struct bpf_verifier_state *old,
9791 				 struct bpf_verifier_state *cur)
9792 {
9793 	struct bpf_func_state *fold, *fcur;
9794 	int i, fr = cur->curframe;
9795 
9796 	if (old->curframe != fr)
9797 		return false;
9798 
9799 	fold = old->frame[fr];
9800 	fcur = cur->frame[fr];
9801 	for (i = 0; i < MAX_BPF_REG; i++)
9802 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9803 			   offsetof(struct bpf_reg_state, parent)))
9804 			return false;
9805 	return true;
9806 }
9807 
9808 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)9809 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9810 {
9811 	struct bpf_verifier_state_list *new_sl;
9812 	struct bpf_verifier_state_list *sl, **pprev;
9813 	struct bpf_verifier_state *cur = env->cur_state, *new;
9814 	int i, j, err, states_cnt = 0;
9815 	bool add_new_state = env->test_state_freq ? true : false;
9816 
9817 	cur->last_insn_idx = env->prev_insn_idx;
9818 	if (!env->insn_aux_data[insn_idx].prune_point)
9819 		/* this 'insn_idx' instruction wasn't marked, so we will not
9820 		 * be doing state search here
9821 		 */
9822 		return 0;
9823 
9824 	/* bpf progs typically have pruning point every 4 instructions
9825 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9826 	 * Do not add new state for future pruning if the verifier hasn't seen
9827 	 * at least 2 jumps and at least 8 instructions.
9828 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9829 	 * In tests that amounts to up to 50% reduction into total verifier
9830 	 * memory consumption and 20% verifier time speedup.
9831 	 */
9832 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9833 	    env->insn_processed - env->prev_insn_processed >= 8)
9834 		add_new_state = true;
9835 
9836 	pprev = explored_state(env, insn_idx);
9837 	sl = *pprev;
9838 
9839 	clean_live_states(env, insn_idx, cur);
9840 
9841 	while (sl) {
9842 		states_cnt++;
9843 		if (sl->state.insn_idx != insn_idx)
9844 			goto next;
9845 		if (sl->state.branches) {
9846 			if (states_maybe_looping(&sl->state, cur) &&
9847 			    states_equal(env, &sl->state, cur)) {
9848 				verbose_linfo(env, insn_idx, "; ");
9849 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9850 				return -EINVAL;
9851 			}
9852 			/* if the verifier is processing a loop, avoid adding new state
9853 			 * too often, since different loop iterations have distinct
9854 			 * states and may not help future pruning.
9855 			 * This threshold shouldn't be too low to make sure that
9856 			 * a loop with large bound will be rejected quickly.
9857 			 * The most abusive loop will be:
9858 			 * r1 += 1
9859 			 * if r1 < 1000000 goto pc-2
9860 			 * 1M insn_procssed limit / 100 == 10k peak states.
9861 			 * This threshold shouldn't be too high either, since states
9862 			 * at the end of the loop are likely to be useful in pruning.
9863 			 */
9864 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9865 			    env->insn_processed - env->prev_insn_processed < 100)
9866 				add_new_state = false;
9867 			goto miss;
9868 		}
9869 		if (states_equal(env, &sl->state, cur)) {
9870 			sl->hit_cnt++;
9871 			/* reached equivalent register/stack state,
9872 			 * prune the search.
9873 			 * Registers read by the continuation are read by us.
9874 			 * If we have any write marks in env->cur_state, they
9875 			 * will prevent corresponding reads in the continuation
9876 			 * from reaching our parent (an explored_state).  Our
9877 			 * own state will get the read marks recorded, but
9878 			 * they'll be immediately forgotten as we're pruning
9879 			 * this state and will pop a new one.
9880 			 */
9881 			err = propagate_liveness(env, &sl->state, cur);
9882 
9883 			/* if previous state reached the exit with precision and
9884 			 * current state is equivalent to it (except precsion marks)
9885 			 * the precision needs to be propagated back in
9886 			 * the current state.
9887 			 */
9888 			err = err ? : push_jmp_history(env, cur);
9889 			err = err ? : propagate_precision(env, &sl->state);
9890 			if (err)
9891 				return err;
9892 			return 1;
9893 		}
9894 miss:
9895 		/* when new state is not going to be added do not increase miss count.
9896 		 * Otherwise several loop iterations will remove the state
9897 		 * recorded earlier. The goal of these heuristics is to have
9898 		 * states from some iterations of the loop (some in the beginning
9899 		 * and some at the end) to help pruning.
9900 		 */
9901 		if (add_new_state)
9902 			sl->miss_cnt++;
9903 		/* heuristic to determine whether this state is beneficial
9904 		 * to keep checking from state equivalence point of view.
9905 		 * Higher numbers increase max_states_per_insn and verification time,
9906 		 * but do not meaningfully decrease insn_processed.
9907 		 */
9908 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9909 			/* the state is unlikely to be useful. Remove it to
9910 			 * speed up verification
9911 			 */
9912 			*pprev = sl->next;
9913 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9914 				u32 br = sl->state.branches;
9915 
9916 				WARN_ONCE(br,
9917 					  "BUG live_done but branches_to_explore %d\n",
9918 					  br);
9919 				free_verifier_state(&sl->state, false);
9920 				kfree(sl);
9921 				env->peak_states--;
9922 			} else {
9923 				/* cannot free this state, since parentage chain may
9924 				 * walk it later. Add it for free_list instead to
9925 				 * be freed at the end of verification
9926 				 */
9927 				sl->next = env->free_list;
9928 				env->free_list = sl;
9929 			}
9930 			sl = *pprev;
9931 			continue;
9932 		}
9933 next:
9934 		pprev = &sl->next;
9935 		sl = *pprev;
9936 	}
9937 
9938 	if (env->max_states_per_insn < states_cnt)
9939 		env->max_states_per_insn = states_cnt;
9940 
9941 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9942 		return push_jmp_history(env, cur);
9943 
9944 	if (!add_new_state)
9945 		return push_jmp_history(env, cur);
9946 
9947 	/* There were no equivalent states, remember the current one.
9948 	 * Technically the current state is not proven to be safe yet,
9949 	 * but it will either reach outer most bpf_exit (which means it's safe)
9950 	 * or it will be rejected. When there are no loops the verifier won't be
9951 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9952 	 * again on the way to bpf_exit.
9953 	 * When looping the sl->state.branches will be > 0 and this state
9954 	 * will not be considered for equivalence until branches == 0.
9955 	 */
9956 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9957 	if (!new_sl)
9958 		return -ENOMEM;
9959 	env->total_states++;
9960 	env->peak_states++;
9961 	env->prev_jmps_processed = env->jmps_processed;
9962 	env->prev_insn_processed = env->insn_processed;
9963 
9964 	/* forget precise markings we inherited, see __mark_chain_precision */
9965 	if (env->bpf_capable)
9966 		mark_all_scalars_imprecise(env, cur);
9967 
9968 	/* add new state to the head of linked list */
9969 	new = &new_sl->state;
9970 	err = copy_verifier_state(new, cur);
9971 	if (err) {
9972 		free_verifier_state(new, false);
9973 		kfree(new_sl);
9974 		return err;
9975 	}
9976 	new->insn_idx = insn_idx;
9977 	WARN_ONCE(new->branches != 1,
9978 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9979 
9980 	cur->parent = new;
9981 	cur->first_insn_idx = insn_idx;
9982 	clear_jmp_history(cur);
9983 	new_sl->next = *explored_state(env, insn_idx);
9984 	*explored_state(env, insn_idx) = new_sl;
9985 	/* connect new state to parentage chain. Current frame needs all
9986 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9987 	 * to the stack implicitly by JITs) so in callers' frames connect just
9988 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9989 	 * the state of the call instruction (with WRITTEN set), and r0 comes
9990 	 * from callee with its full parentage chain, anyway.
9991 	 */
9992 	/* clear write marks in current state: the writes we did are not writes
9993 	 * our child did, so they don't screen off its reads from us.
9994 	 * (There are no read marks in current state, because reads always mark
9995 	 * their parent and current state never has children yet.  Only
9996 	 * explored_states can get read marks.)
9997 	 */
9998 	for (j = 0; j <= cur->curframe; j++) {
9999 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10000 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10001 		for (i = 0; i < BPF_REG_FP; i++)
10002 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10003 	}
10004 
10005 	/* all stack frames are accessible from callee, clear them all */
10006 	for (j = 0; j <= cur->curframe; j++) {
10007 		struct bpf_func_state *frame = cur->frame[j];
10008 		struct bpf_func_state *newframe = new->frame[j];
10009 
10010 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10011 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10012 			frame->stack[i].spilled_ptr.parent =
10013 						&newframe->stack[i].spilled_ptr;
10014 		}
10015 	}
10016 	return 0;
10017 }
10018 
10019 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)10020 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10021 {
10022 	switch (base_type(type)) {
10023 	case PTR_TO_CTX:
10024 	case PTR_TO_SOCKET:
10025 	case PTR_TO_SOCK_COMMON:
10026 	case PTR_TO_TCP_SOCK:
10027 	case PTR_TO_XDP_SOCK:
10028 	case PTR_TO_BTF_ID:
10029 		return false;
10030 	default:
10031 		return true;
10032 	}
10033 }
10034 
10035 /* If an instruction was previously used with particular pointer types, then we
10036  * need to be careful to avoid cases such as the below, where it may be ok
10037  * for one branch accessing the pointer, but not ok for the other branch:
10038  *
10039  * R1 = sock_ptr
10040  * goto X;
10041  * ...
10042  * R1 = some_other_valid_ptr;
10043  * goto X;
10044  * ...
10045  * R2 = *(u32 *)(R1 + 0);
10046  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)10047 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10048 {
10049 	return src != prev && (!reg_type_mismatch_ok(src) ||
10050 			       !reg_type_mismatch_ok(prev));
10051 }
10052 
do_check(struct bpf_verifier_env * env)10053 static int do_check(struct bpf_verifier_env *env)
10054 {
10055 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10056 	struct bpf_verifier_state *state = env->cur_state;
10057 	struct bpf_insn *insns = env->prog->insnsi;
10058 	struct bpf_reg_state *regs;
10059 	int insn_cnt = env->prog->len;
10060 	bool do_print_state = false;
10061 	int prev_insn_idx = -1;
10062 
10063 	for (;;) {
10064 		struct bpf_insn *insn;
10065 		u8 class;
10066 		int err;
10067 
10068 		env->prev_insn_idx = prev_insn_idx;
10069 		if (env->insn_idx >= insn_cnt) {
10070 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
10071 				env->insn_idx, insn_cnt);
10072 			return -EFAULT;
10073 		}
10074 
10075 		insn = &insns[env->insn_idx];
10076 		class = BPF_CLASS(insn->code);
10077 
10078 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10079 			verbose(env,
10080 				"BPF program is too large. Processed %d insn\n",
10081 				env->insn_processed);
10082 			return -E2BIG;
10083 		}
10084 
10085 		err = is_state_visited(env, env->insn_idx);
10086 		if (err < 0)
10087 			return err;
10088 		if (err == 1) {
10089 			/* found equivalent state, can prune the search */
10090 			if (env->log.level & BPF_LOG_LEVEL) {
10091 				if (do_print_state)
10092 					verbose(env, "\nfrom %d to %d%s: safe\n",
10093 						env->prev_insn_idx, env->insn_idx,
10094 						env->cur_state->speculative ?
10095 						" (speculative execution)" : "");
10096 				else
10097 					verbose(env, "%d: safe\n", env->insn_idx);
10098 			}
10099 			goto process_bpf_exit;
10100 		}
10101 
10102 		if (signal_pending(current))
10103 			return -EAGAIN;
10104 
10105 		if (need_resched())
10106 			cond_resched();
10107 
10108 		if (env->log.level & BPF_LOG_LEVEL2 ||
10109 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10110 			if (env->log.level & BPF_LOG_LEVEL2)
10111 				verbose(env, "%d:", env->insn_idx);
10112 			else
10113 				verbose(env, "\nfrom %d to %d%s:",
10114 					env->prev_insn_idx, env->insn_idx,
10115 					env->cur_state->speculative ?
10116 					" (speculative execution)" : "");
10117 			print_verifier_state(env, state->frame[state->curframe]);
10118 			do_print_state = false;
10119 		}
10120 
10121 		if (env->log.level & BPF_LOG_LEVEL) {
10122 			const struct bpf_insn_cbs cbs = {
10123 				.cb_print	= verbose,
10124 				.private_data	= env,
10125 			};
10126 
10127 			verbose_linfo(env, env->insn_idx, "; ");
10128 			verbose(env, "%d: ", env->insn_idx);
10129 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10130 		}
10131 
10132 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
10133 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10134 							   env->prev_insn_idx);
10135 			if (err)
10136 				return err;
10137 		}
10138 
10139 		regs = cur_regs(env);
10140 		sanitize_mark_insn_seen(env);
10141 		prev_insn_idx = env->insn_idx;
10142 
10143 		if (class == BPF_ALU || class == BPF_ALU64) {
10144 			err = check_alu_op(env, insn);
10145 			if (err)
10146 				return err;
10147 
10148 		} else if (class == BPF_LDX) {
10149 			enum bpf_reg_type *prev_src_type, src_reg_type;
10150 
10151 			/* check for reserved fields is already done */
10152 
10153 			/* check src operand */
10154 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10155 			if (err)
10156 				return err;
10157 
10158 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10159 			if (err)
10160 				return err;
10161 
10162 			src_reg_type = regs[insn->src_reg].type;
10163 
10164 			/* check that memory (src_reg + off) is readable,
10165 			 * the state of dst_reg will be updated by this func
10166 			 */
10167 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
10168 					       insn->off, BPF_SIZE(insn->code),
10169 					       BPF_READ, insn->dst_reg, false);
10170 			if (err)
10171 				return err;
10172 
10173 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10174 
10175 			if (*prev_src_type == NOT_INIT) {
10176 				/* saw a valid insn
10177 				 * dst_reg = *(u32 *)(src_reg + off)
10178 				 * save type to validate intersecting paths
10179 				 */
10180 				*prev_src_type = src_reg_type;
10181 
10182 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10183 				/* ABuser program is trying to use the same insn
10184 				 * dst_reg = *(u32*) (src_reg + off)
10185 				 * with different pointer types:
10186 				 * src_reg == ctx in one branch and
10187 				 * src_reg == stack|map in some other branch.
10188 				 * Reject it.
10189 				 */
10190 				verbose(env, "same insn cannot be used with different pointers\n");
10191 				return -EINVAL;
10192 			}
10193 
10194 		} else if (class == BPF_STX) {
10195 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
10196 
10197 			if (BPF_MODE(insn->code) == BPF_XADD) {
10198 				err = check_xadd(env, env->insn_idx, insn);
10199 				if (err)
10200 					return err;
10201 				env->insn_idx++;
10202 				continue;
10203 			}
10204 
10205 			/* check src1 operand */
10206 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10207 			if (err)
10208 				return err;
10209 			/* check src2 operand */
10210 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10211 			if (err)
10212 				return err;
10213 
10214 			dst_reg_type = regs[insn->dst_reg].type;
10215 
10216 			/* check that memory (dst_reg + off) is writeable */
10217 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10218 					       insn->off, BPF_SIZE(insn->code),
10219 					       BPF_WRITE, insn->src_reg, false);
10220 			if (err)
10221 				return err;
10222 
10223 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10224 
10225 			if (*prev_dst_type == NOT_INIT) {
10226 				*prev_dst_type = dst_reg_type;
10227 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10228 				verbose(env, "same insn cannot be used with different pointers\n");
10229 				return -EINVAL;
10230 			}
10231 
10232 		} else if (class == BPF_ST) {
10233 			if (BPF_MODE(insn->code) != BPF_MEM ||
10234 			    insn->src_reg != BPF_REG_0) {
10235 				verbose(env, "BPF_ST uses reserved fields\n");
10236 				return -EINVAL;
10237 			}
10238 			/* check src operand */
10239 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10240 			if (err)
10241 				return err;
10242 
10243 			if (is_ctx_reg(env, insn->dst_reg)) {
10244 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10245 					insn->dst_reg,
10246 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
10247 				return -EACCES;
10248 			}
10249 
10250 			/* check that memory (dst_reg + off) is writeable */
10251 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10252 					       insn->off, BPF_SIZE(insn->code),
10253 					       BPF_WRITE, -1, false);
10254 			if (err)
10255 				return err;
10256 
10257 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10258 			u8 opcode = BPF_OP(insn->code);
10259 
10260 			env->jmps_processed++;
10261 			if (opcode == BPF_CALL) {
10262 				if (BPF_SRC(insn->code) != BPF_K ||
10263 				    insn->off != 0 ||
10264 				    (insn->src_reg != BPF_REG_0 &&
10265 				     insn->src_reg != BPF_PSEUDO_CALL) ||
10266 				    insn->dst_reg != BPF_REG_0 ||
10267 				    class == BPF_JMP32) {
10268 					verbose(env, "BPF_CALL uses reserved fields\n");
10269 					return -EINVAL;
10270 				}
10271 
10272 				if (env->cur_state->active_spin_lock &&
10273 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10274 				     insn->imm != BPF_FUNC_spin_unlock)) {
10275 					verbose(env, "function calls are not allowed while holding a lock\n");
10276 					return -EINVAL;
10277 				}
10278 				if (insn->src_reg == BPF_PSEUDO_CALL)
10279 					err = check_func_call(env, insn, &env->insn_idx);
10280 				else
10281 					err = check_helper_call(env, insn->imm, env->insn_idx);
10282 				if (err)
10283 					return err;
10284 
10285 			} else if (opcode == BPF_JA) {
10286 				if (BPF_SRC(insn->code) != BPF_K ||
10287 				    insn->imm != 0 ||
10288 				    insn->src_reg != BPF_REG_0 ||
10289 				    insn->dst_reg != BPF_REG_0 ||
10290 				    class == BPF_JMP32) {
10291 					verbose(env, "BPF_JA uses reserved fields\n");
10292 					return -EINVAL;
10293 				}
10294 
10295 				env->insn_idx += insn->off + 1;
10296 				continue;
10297 
10298 			} else if (opcode == BPF_EXIT) {
10299 				if (BPF_SRC(insn->code) != BPF_K ||
10300 				    insn->imm != 0 ||
10301 				    insn->src_reg != BPF_REG_0 ||
10302 				    insn->dst_reg != BPF_REG_0 ||
10303 				    class == BPF_JMP32) {
10304 					verbose(env, "BPF_EXIT uses reserved fields\n");
10305 					return -EINVAL;
10306 				}
10307 
10308 				if (env->cur_state->active_spin_lock) {
10309 					verbose(env, "bpf_spin_unlock is missing\n");
10310 					return -EINVAL;
10311 				}
10312 
10313 				if (state->curframe) {
10314 					/* exit from nested function */
10315 					err = prepare_func_exit(env, &env->insn_idx);
10316 					if (err)
10317 						return err;
10318 					do_print_state = true;
10319 					continue;
10320 				}
10321 
10322 				err = check_reference_leak(env);
10323 				if (err)
10324 					return err;
10325 
10326 				err = check_return_code(env);
10327 				if (err)
10328 					return err;
10329 process_bpf_exit:
10330 				update_branch_counts(env, env->cur_state);
10331 				err = pop_stack(env, &prev_insn_idx,
10332 						&env->insn_idx, pop_log);
10333 				if (err < 0) {
10334 					if (err != -ENOENT)
10335 						return err;
10336 					break;
10337 				} else {
10338 					do_print_state = true;
10339 					continue;
10340 				}
10341 			} else {
10342 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10343 				if (err)
10344 					return err;
10345 			}
10346 		} else if (class == BPF_LD) {
10347 			u8 mode = BPF_MODE(insn->code);
10348 
10349 			if (mode == BPF_ABS || mode == BPF_IND) {
10350 				err = check_ld_abs(env, insn);
10351 				if (err)
10352 					return err;
10353 
10354 			} else if (mode == BPF_IMM) {
10355 				err = check_ld_imm(env, insn);
10356 				if (err)
10357 					return err;
10358 
10359 				env->insn_idx++;
10360 				sanitize_mark_insn_seen(env);
10361 			} else {
10362 				verbose(env, "invalid BPF_LD mode\n");
10363 				return -EINVAL;
10364 			}
10365 		} else {
10366 			verbose(env, "unknown insn class %d\n", class);
10367 			return -EINVAL;
10368 		}
10369 
10370 		env->insn_idx++;
10371 	}
10372 
10373 	return 0;
10374 }
10375 
10376 /* 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)10377 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10378 			       struct bpf_insn *insn,
10379 			       struct bpf_insn_aux_data *aux)
10380 {
10381 	const struct btf_var_secinfo *vsi;
10382 	const struct btf_type *datasec;
10383 	const struct btf_type *t;
10384 	const char *sym_name;
10385 	bool percpu = false;
10386 	u32 type, id = insn->imm;
10387 	s32 datasec_id;
10388 	u64 addr;
10389 	int i;
10390 
10391 	if (!btf_vmlinux) {
10392 		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10393 		return -EINVAL;
10394 	}
10395 
10396 	if (insn[1].imm != 0) {
10397 		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10398 		return -EINVAL;
10399 	}
10400 
10401 	t = btf_type_by_id(btf_vmlinux, id);
10402 	if (!t) {
10403 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10404 		return -ENOENT;
10405 	}
10406 
10407 	if (!btf_type_is_var(t)) {
10408 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10409 			id);
10410 		return -EINVAL;
10411 	}
10412 
10413 	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10414 	addr = kallsyms_lookup_name(sym_name);
10415 	if (!addr) {
10416 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10417 			sym_name);
10418 		return -ENOENT;
10419 	}
10420 
10421 	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10422 					   BTF_KIND_DATASEC);
10423 	if (datasec_id > 0) {
10424 		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10425 		for_each_vsi(i, datasec, vsi) {
10426 			if (vsi->type == id) {
10427 				percpu = true;
10428 				break;
10429 			}
10430 		}
10431 	}
10432 
10433 	insn[0].imm = (u32)addr;
10434 	insn[1].imm = addr >> 32;
10435 
10436 	type = t->type;
10437 	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10438 	if (percpu) {
10439 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10440 		aux->btf_var.btf_id = type;
10441 	} else if (!btf_type_is_struct(t)) {
10442 		const struct btf_type *ret;
10443 		const char *tname;
10444 		u32 tsize;
10445 
10446 		/* resolve the type size of ksym. */
10447 		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10448 		if (IS_ERR(ret)) {
10449 			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10450 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10451 				tname, PTR_ERR(ret));
10452 			return -EINVAL;
10453 		}
10454 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
10455 		aux->btf_var.mem_size = tsize;
10456 	} else {
10457 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10458 		aux->btf_var.btf_id = type;
10459 	}
10460 	return 0;
10461 }
10462 
check_map_prealloc(struct bpf_map * map)10463 static int check_map_prealloc(struct bpf_map *map)
10464 {
10465 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10466 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10467 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10468 		!(map->map_flags & BPF_F_NO_PREALLOC);
10469 }
10470 
is_tracing_prog_type(enum bpf_prog_type type)10471 static bool is_tracing_prog_type(enum bpf_prog_type type)
10472 {
10473 	switch (type) {
10474 	case BPF_PROG_TYPE_KPROBE:
10475 	case BPF_PROG_TYPE_TRACEPOINT:
10476 	case BPF_PROG_TYPE_PERF_EVENT:
10477 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10478 		return true;
10479 	default:
10480 		return false;
10481 	}
10482 }
10483 
is_preallocated_map(struct bpf_map * map)10484 static bool is_preallocated_map(struct bpf_map *map)
10485 {
10486 	if (!check_map_prealloc(map))
10487 		return false;
10488 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10489 		return false;
10490 	return true;
10491 }
10492 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)10493 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10494 					struct bpf_map *map,
10495 					struct bpf_prog *prog)
10496 
10497 {
10498 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10499 	/*
10500 	 * Validate that trace type programs use preallocated hash maps.
10501 	 *
10502 	 * For programs attached to PERF events this is mandatory as the
10503 	 * perf NMI can hit any arbitrary code sequence.
10504 	 *
10505 	 * All other trace types using preallocated hash maps are unsafe as
10506 	 * well because tracepoint or kprobes can be inside locked regions
10507 	 * of the memory allocator or at a place where a recursion into the
10508 	 * memory allocator would see inconsistent state.
10509 	 *
10510 	 * On RT enabled kernels run-time allocation of all trace type
10511 	 * programs is strictly prohibited due to lock type constraints. On
10512 	 * !RT kernels it is allowed for backwards compatibility reasons for
10513 	 * now, but warnings are emitted so developers are made aware of
10514 	 * the unsafety and can fix their programs before this is enforced.
10515 	 */
10516 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10517 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10518 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10519 			return -EINVAL;
10520 		}
10521 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10522 			verbose(env, "trace type programs can only use preallocated hash map\n");
10523 			return -EINVAL;
10524 		}
10525 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10526 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10527 	}
10528 
10529 	if ((is_tracing_prog_type(prog_type) ||
10530 	     prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10531 	    map_value_has_spin_lock(map)) {
10532 		verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10533 		return -EINVAL;
10534 	}
10535 
10536 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10537 	    !bpf_offload_prog_map_match(prog, map)) {
10538 		verbose(env, "offload device mismatch between prog and map\n");
10539 		return -EINVAL;
10540 	}
10541 
10542 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10543 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10544 		return -EINVAL;
10545 	}
10546 
10547 	if (prog->aux->sleepable)
10548 		switch (map->map_type) {
10549 		case BPF_MAP_TYPE_HASH:
10550 		case BPF_MAP_TYPE_LRU_HASH:
10551 		case BPF_MAP_TYPE_ARRAY:
10552 			if (!is_preallocated_map(map)) {
10553 				verbose(env,
10554 					"Sleepable programs can only use preallocated hash maps\n");
10555 				return -EINVAL;
10556 			}
10557 			break;
10558 		default:
10559 			verbose(env,
10560 				"Sleepable programs can only use array and hash maps\n");
10561 			return -EINVAL;
10562 		}
10563 
10564 	return 0;
10565 }
10566 
bpf_map_is_cgroup_storage(struct bpf_map * map)10567 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10568 {
10569 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10570 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10571 }
10572 
10573 /* find and rewrite pseudo imm in ld_imm64 instructions:
10574  *
10575  * 1. if it accesses map FD, replace it with actual map pointer.
10576  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10577  *
10578  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10579  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)10580 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10581 {
10582 	struct bpf_insn *insn = env->prog->insnsi;
10583 	int insn_cnt = env->prog->len;
10584 	int i, j, err;
10585 
10586 	err = bpf_prog_calc_tag(env->prog);
10587 	if (err)
10588 		return err;
10589 
10590 	for (i = 0; i < insn_cnt; i++, insn++) {
10591 		if (BPF_CLASS(insn->code) == BPF_LDX &&
10592 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10593 			verbose(env, "BPF_LDX uses reserved fields\n");
10594 			return -EINVAL;
10595 		}
10596 
10597 		if (BPF_CLASS(insn->code) == BPF_STX &&
10598 		    ((BPF_MODE(insn->code) != BPF_MEM &&
10599 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10600 			verbose(env, "BPF_STX uses reserved fields\n");
10601 			return -EINVAL;
10602 		}
10603 
10604 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10605 			struct bpf_insn_aux_data *aux;
10606 			struct bpf_map *map;
10607 			struct fd f;
10608 			u64 addr;
10609 
10610 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
10611 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10612 			    insn[1].off != 0) {
10613 				verbose(env, "invalid bpf_ld_imm64 insn\n");
10614 				return -EINVAL;
10615 			}
10616 
10617 			if (insn[0].src_reg == 0)
10618 				/* valid generic load 64-bit imm */
10619 				goto next_insn;
10620 
10621 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10622 				aux = &env->insn_aux_data[i];
10623 				err = check_pseudo_btf_id(env, insn, aux);
10624 				if (err)
10625 					return err;
10626 				goto next_insn;
10627 			}
10628 
10629 			/* In final convert_pseudo_ld_imm64() step, this is
10630 			 * converted into regular 64-bit imm load insn.
10631 			 */
10632 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10633 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10634 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10635 			     insn[1].imm != 0)) {
10636 				verbose(env,
10637 					"unrecognized bpf_ld_imm64 insn\n");
10638 				return -EINVAL;
10639 			}
10640 
10641 			f = fdget(insn[0].imm);
10642 			map = __bpf_map_get(f);
10643 			if (IS_ERR(map)) {
10644 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
10645 					insn[0].imm);
10646 				return PTR_ERR(map);
10647 			}
10648 
10649 			err = check_map_prog_compatibility(env, map, env->prog);
10650 			if (err) {
10651 				fdput(f);
10652 				return err;
10653 			}
10654 
10655 			aux = &env->insn_aux_data[i];
10656 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10657 				addr = (unsigned long)map;
10658 			} else {
10659 				u32 off = insn[1].imm;
10660 
10661 				if (off >= BPF_MAX_VAR_OFF) {
10662 					verbose(env, "direct value offset of %u is not allowed\n", off);
10663 					fdput(f);
10664 					return -EINVAL;
10665 				}
10666 
10667 				if (!map->ops->map_direct_value_addr) {
10668 					verbose(env, "no direct value access support for this map type\n");
10669 					fdput(f);
10670 					return -EINVAL;
10671 				}
10672 
10673 				err = map->ops->map_direct_value_addr(map, &addr, off);
10674 				if (err) {
10675 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10676 						map->value_size, off);
10677 					fdput(f);
10678 					return err;
10679 				}
10680 
10681 				aux->map_off = off;
10682 				addr += off;
10683 			}
10684 
10685 			insn[0].imm = (u32)addr;
10686 			insn[1].imm = addr >> 32;
10687 
10688 			/* check whether we recorded this map already */
10689 			for (j = 0; j < env->used_map_cnt; j++) {
10690 				if (env->used_maps[j] == map) {
10691 					aux->map_index = j;
10692 					fdput(f);
10693 					goto next_insn;
10694 				}
10695 			}
10696 
10697 			if (env->used_map_cnt >= MAX_USED_MAPS) {
10698 				fdput(f);
10699 				return -E2BIG;
10700 			}
10701 
10702 			/* hold the map. If the program is rejected by verifier,
10703 			 * the map will be released by release_maps() or it
10704 			 * will be used by the valid program until it's unloaded
10705 			 * and all maps are released in free_used_maps()
10706 			 */
10707 			bpf_map_inc(map);
10708 
10709 			aux->map_index = env->used_map_cnt;
10710 			env->used_maps[env->used_map_cnt++] = map;
10711 
10712 			if (bpf_map_is_cgroup_storage(map) &&
10713 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10714 				verbose(env, "only one cgroup storage of each type is allowed\n");
10715 				fdput(f);
10716 				return -EBUSY;
10717 			}
10718 
10719 			fdput(f);
10720 next_insn:
10721 			insn++;
10722 			i++;
10723 			continue;
10724 		}
10725 
10726 		/* Basic sanity check before we invest more work here. */
10727 		if (!bpf_opcode_in_insntable(insn->code)) {
10728 			verbose(env, "unknown opcode %02x\n", insn->code);
10729 			return -EINVAL;
10730 		}
10731 	}
10732 
10733 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10734 	 * 'struct bpf_map *' into a register instead of user map_fd.
10735 	 * These pointers will be used later by verifier to validate map access.
10736 	 */
10737 	return 0;
10738 }
10739 
10740 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)10741 static void release_maps(struct bpf_verifier_env *env)
10742 {
10743 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10744 			     env->used_map_cnt);
10745 }
10746 
10747 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)10748 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10749 {
10750 	struct bpf_insn *insn = env->prog->insnsi;
10751 	int insn_cnt = env->prog->len;
10752 	int i;
10753 
10754 	for (i = 0; i < insn_cnt; i++, insn++)
10755 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10756 			insn->src_reg = 0;
10757 }
10758 
10759 /* single env->prog->insni[off] instruction was replaced with the range
10760  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10761  * [0, off) and [off, end) to new locations, so the patched range stays zero
10762  */
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)10763 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10764 				 struct bpf_insn_aux_data *new_data,
10765 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
10766 {
10767 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10768 	struct bpf_insn *insn = new_prog->insnsi;
10769 	u32 old_seen = old_data[off].seen;
10770 	u32 prog_len;
10771 	int i;
10772 
10773 	/* aux info at OFF always needs adjustment, no matter fast path
10774 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10775 	 * original insn at old prog.
10776 	 */
10777 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10778 
10779 	if (cnt == 1)
10780 		return;
10781 	prog_len = new_prog->len;
10782 
10783 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10784 	memcpy(new_data + off + cnt - 1, old_data + off,
10785 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10786 	for (i = off; i < off + cnt - 1; i++) {
10787 		/* Expand insni[off]'s seen count to the patched range. */
10788 		new_data[i].seen = old_seen;
10789 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10790 	}
10791 	env->insn_aux_data = new_data;
10792 	vfree(old_data);
10793 }
10794 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)10795 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10796 {
10797 	int i;
10798 
10799 	if (len == 1)
10800 		return;
10801 	/* NOTE: fake 'exit' subprog should be updated as well. */
10802 	for (i = 0; i <= env->subprog_cnt; i++) {
10803 		if (env->subprog_info[i].start <= off)
10804 			continue;
10805 		env->subprog_info[i].start += len - 1;
10806 	}
10807 }
10808 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)10809 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10810 {
10811 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10812 	int i, sz = prog->aux->size_poke_tab;
10813 	struct bpf_jit_poke_descriptor *desc;
10814 
10815 	for (i = 0; i < sz; i++) {
10816 		desc = &tab[i];
10817 		if (desc->insn_idx <= off)
10818 			continue;
10819 		desc->insn_idx += len - 1;
10820 	}
10821 }
10822 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)10823 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10824 					    const struct bpf_insn *patch, u32 len)
10825 {
10826 	struct bpf_prog *new_prog;
10827 	struct bpf_insn_aux_data *new_data = NULL;
10828 
10829 	if (len > 1) {
10830 		new_data = vzalloc(array_size(env->prog->len + len - 1,
10831 					      sizeof(struct bpf_insn_aux_data)));
10832 		if (!new_data)
10833 			return NULL;
10834 	}
10835 
10836 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10837 	if (IS_ERR(new_prog)) {
10838 		if (PTR_ERR(new_prog) == -ERANGE)
10839 			verbose(env,
10840 				"insn %d cannot be patched due to 16-bit range\n",
10841 				env->insn_aux_data[off].orig_idx);
10842 		vfree(new_data);
10843 		return NULL;
10844 	}
10845 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
10846 	adjust_subprog_starts(env, off, len);
10847 	adjust_poke_descs(new_prog, off, len);
10848 	return new_prog;
10849 }
10850 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10851 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10852 					      u32 off, u32 cnt)
10853 {
10854 	int i, j;
10855 
10856 	/* find first prog starting at or after off (first to remove) */
10857 	for (i = 0; i < env->subprog_cnt; i++)
10858 		if (env->subprog_info[i].start >= off)
10859 			break;
10860 	/* find first prog starting at or after off + cnt (first to stay) */
10861 	for (j = i; j < env->subprog_cnt; j++)
10862 		if (env->subprog_info[j].start >= off + cnt)
10863 			break;
10864 	/* if j doesn't start exactly at off + cnt, we are just removing
10865 	 * the front of previous prog
10866 	 */
10867 	if (env->subprog_info[j].start != off + cnt)
10868 		j--;
10869 
10870 	if (j > i) {
10871 		struct bpf_prog_aux *aux = env->prog->aux;
10872 		int move;
10873 
10874 		/* move fake 'exit' subprog as well */
10875 		move = env->subprog_cnt + 1 - j;
10876 
10877 		memmove(env->subprog_info + i,
10878 			env->subprog_info + j,
10879 			sizeof(*env->subprog_info) * move);
10880 		env->subprog_cnt -= j - i;
10881 
10882 		/* remove func_info */
10883 		if (aux->func_info) {
10884 			move = aux->func_info_cnt - j;
10885 
10886 			memmove(aux->func_info + i,
10887 				aux->func_info + j,
10888 				sizeof(*aux->func_info) * move);
10889 			aux->func_info_cnt -= j - i;
10890 			/* func_info->insn_off is set after all code rewrites,
10891 			 * in adjust_btf_func() - no need to adjust
10892 			 */
10893 		}
10894 	} else {
10895 		/* convert i from "first prog to remove" to "first to adjust" */
10896 		if (env->subprog_info[i].start == off)
10897 			i++;
10898 	}
10899 
10900 	/* update fake 'exit' subprog as well */
10901 	for (; i <= env->subprog_cnt; i++)
10902 		env->subprog_info[i].start -= cnt;
10903 
10904 	return 0;
10905 }
10906 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10907 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10908 				      u32 cnt)
10909 {
10910 	struct bpf_prog *prog = env->prog;
10911 	u32 i, l_off, l_cnt, nr_linfo;
10912 	struct bpf_line_info *linfo;
10913 
10914 	nr_linfo = prog->aux->nr_linfo;
10915 	if (!nr_linfo)
10916 		return 0;
10917 
10918 	linfo = prog->aux->linfo;
10919 
10920 	/* find first line info to remove, count lines to be removed */
10921 	for (i = 0; i < nr_linfo; i++)
10922 		if (linfo[i].insn_off >= off)
10923 			break;
10924 
10925 	l_off = i;
10926 	l_cnt = 0;
10927 	for (; i < nr_linfo; i++)
10928 		if (linfo[i].insn_off < off + cnt)
10929 			l_cnt++;
10930 		else
10931 			break;
10932 
10933 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10934 	 * last removed linfo.  prog is already modified, so prog->len == off
10935 	 * means no live instructions after (tail of the program was removed).
10936 	 */
10937 	if (prog->len != off && l_cnt &&
10938 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10939 		l_cnt--;
10940 		linfo[--i].insn_off = off + cnt;
10941 	}
10942 
10943 	/* remove the line info which refer to the removed instructions */
10944 	if (l_cnt) {
10945 		memmove(linfo + l_off, linfo + i,
10946 			sizeof(*linfo) * (nr_linfo - i));
10947 
10948 		prog->aux->nr_linfo -= l_cnt;
10949 		nr_linfo = prog->aux->nr_linfo;
10950 	}
10951 
10952 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10953 	for (i = l_off; i < nr_linfo; i++)
10954 		linfo[i].insn_off -= cnt;
10955 
10956 	/* fix up all subprogs (incl. 'exit') which start >= off */
10957 	for (i = 0; i <= env->subprog_cnt; i++)
10958 		if (env->subprog_info[i].linfo_idx > l_off) {
10959 			/* program may have started in the removed region but
10960 			 * may not be fully removed
10961 			 */
10962 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10963 				env->subprog_info[i].linfo_idx -= l_cnt;
10964 			else
10965 				env->subprog_info[i].linfo_idx = l_off;
10966 		}
10967 
10968 	return 0;
10969 }
10970 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)10971 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10972 {
10973 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10974 	unsigned int orig_prog_len = env->prog->len;
10975 	int err;
10976 
10977 	if (bpf_prog_is_dev_bound(env->prog->aux))
10978 		bpf_prog_offload_remove_insns(env, off, cnt);
10979 
10980 	err = bpf_remove_insns(env->prog, off, cnt);
10981 	if (err)
10982 		return err;
10983 
10984 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10985 	if (err)
10986 		return err;
10987 
10988 	err = bpf_adj_linfo_after_remove(env, off, cnt);
10989 	if (err)
10990 		return err;
10991 
10992 	memmove(aux_data + off,	aux_data + off + cnt,
10993 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
10994 
10995 	return 0;
10996 }
10997 
10998 /* The verifier does more data flow analysis than llvm and will not
10999  * explore branches that are dead at run time. Malicious programs can
11000  * have dead code too. Therefore replace all dead at-run-time code
11001  * with 'ja -1'.
11002  *
11003  * Just nops are not optimal, e.g. if they would sit at the end of the
11004  * program and through another bug we would manage to jump there, then
11005  * we'd execute beyond program memory otherwise. Returning exception
11006  * code also wouldn't work since we can have subprogs where the dead
11007  * code could be located.
11008  */
sanitize_dead_code(struct bpf_verifier_env * env)11009 static void sanitize_dead_code(struct bpf_verifier_env *env)
11010 {
11011 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11012 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11013 	struct bpf_insn *insn = env->prog->insnsi;
11014 	const int insn_cnt = env->prog->len;
11015 	int i;
11016 
11017 	for (i = 0; i < insn_cnt; i++) {
11018 		if (aux_data[i].seen)
11019 			continue;
11020 		memcpy(insn + i, &trap, sizeof(trap));
11021 		aux_data[i].zext_dst = false;
11022 	}
11023 }
11024 
insn_is_cond_jump(u8 code)11025 static bool insn_is_cond_jump(u8 code)
11026 {
11027 	u8 op;
11028 
11029 	if (BPF_CLASS(code) == BPF_JMP32)
11030 		return true;
11031 
11032 	if (BPF_CLASS(code) != BPF_JMP)
11033 		return false;
11034 
11035 	op = BPF_OP(code);
11036 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11037 }
11038 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)11039 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11040 {
11041 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11042 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11043 	struct bpf_insn *insn = env->prog->insnsi;
11044 	const int insn_cnt = env->prog->len;
11045 	int i;
11046 
11047 	for (i = 0; i < insn_cnt; i++, insn++) {
11048 		if (!insn_is_cond_jump(insn->code))
11049 			continue;
11050 
11051 		if (!aux_data[i + 1].seen)
11052 			ja.off = insn->off;
11053 		else if (!aux_data[i + 1 + insn->off].seen)
11054 			ja.off = 0;
11055 		else
11056 			continue;
11057 
11058 		if (bpf_prog_is_dev_bound(env->prog->aux))
11059 			bpf_prog_offload_replace_insn(env, i, &ja);
11060 
11061 		memcpy(insn, &ja, sizeof(ja));
11062 	}
11063 }
11064 
opt_remove_dead_code(struct bpf_verifier_env * env)11065 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11066 {
11067 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11068 	int insn_cnt = env->prog->len;
11069 	int i, err;
11070 
11071 	for (i = 0; i < insn_cnt; i++) {
11072 		int j;
11073 
11074 		j = 0;
11075 		while (i + j < insn_cnt && !aux_data[i + j].seen)
11076 			j++;
11077 		if (!j)
11078 			continue;
11079 
11080 		err = verifier_remove_insns(env, i, j);
11081 		if (err)
11082 			return err;
11083 		insn_cnt = env->prog->len;
11084 	}
11085 
11086 	return 0;
11087 }
11088 
opt_remove_nops(struct bpf_verifier_env * env)11089 static int opt_remove_nops(struct bpf_verifier_env *env)
11090 {
11091 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11092 	struct bpf_insn *insn = env->prog->insnsi;
11093 	int insn_cnt = env->prog->len;
11094 	int i, err;
11095 
11096 	for (i = 0; i < insn_cnt; i++) {
11097 		if (memcmp(&insn[i], &ja, sizeof(ja)))
11098 			continue;
11099 
11100 		err = verifier_remove_insns(env, i, 1);
11101 		if (err)
11102 			return err;
11103 		insn_cnt--;
11104 		i--;
11105 	}
11106 
11107 	return 0;
11108 }
11109 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)11110 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11111 					 const union bpf_attr *attr)
11112 {
11113 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11114 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
11115 	int i, patch_len, delta = 0, len = env->prog->len;
11116 	struct bpf_insn *insns = env->prog->insnsi;
11117 	struct bpf_prog *new_prog;
11118 	bool rnd_hi32;
11119 
11120 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11121 	zext_patch[1] = BPF_ZEXT_REG(0);
11122 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11123 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11124 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11125 	for (i = 0; i < len; i++) {
11126 		int adj_idx = i + delta;
11127 		struct bpf_insn insn;
11128 
11129 		insn = insns[adj_idx];
11130 		if (!aux[adj_idx].zext_dst) {
11131 			u8 code, class;
11132 			u32 imm_rnd;
11133 
11134 			if (!rnd_hi32)
11135 				continue;
11136 
11137 			code = insn.code;
11138 			class = BPF_CLASS(code);
11139 			if (insn_no_def(&insn))
11140 				continue;
11141 
11142 			/* NOTE: arg "reg" (the fourth one) is only used for
11143 			 *       BPF_STX which has been ruled out in above
11144 			 *       check, it is safe to pass NULL here.
11145 			 */
11146 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11147 				if (class == BPF_LD &&
11148 				    BPF_MODE(code) == BPF_IMM)
11149 					i++;
11150 				continue;
11151 			}
11152 
11153 			/* ctx load could be transformed into wider load. */
11154 			if (class == BPF_LDX &&
11155 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
11156 				continue;
11157 
11158 			imm_rnd = get_random_int();
11159 			rnd_hi32_patch[0] = insn;
11160 			rnd_hi32_patch[1].imm = imm_rnd;
11161 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11162 			patch = rnd_hi32_patch;
11163 			patch_len = 4;
11164 			goto apply_patch_buffer;
11165 		}
11166 
11167 		if (!bpf_jit_needs_zext())
11168 			continue;
11169 
11170 		zext_patch[0] = insn;
11171 		zext_patch[1].dst_reg = insn.dst_reg;
11172 		zext_patch[1].src_reg = insn.dst_reg;
11173 		patch = zext_patch;
11174 		patch_len = 2;
11175 apply_patch_buffer:
11176 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11177 		if (!new_prog)
11178 			return -ENOMEM;
11179 		env->prog = new_prog;
11180 		insns = new_prog->insnsi;
11181 		aux = env->insn_aux_data;
11182 		delta += patch_len - 1;
11183 	}
11184 
11185 	return 0;
11186 }
11187 
11188 /* convert load instructions that access fields of a context type into a
11189  * sequence of instructions that access fields of the underlying structure:
11190  *     struct __sk_buff    -> struct sk_buff
11191  *     struct bpf_sock_ops -> struct sock
11192  */
convert_ctx_accesses(struct bpf_verifier_env * env)11193 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11194 {
11195 	const struct bpf_verifier_ops *ops = env->ops;
11196 	int i, cnt, size, ctx_field_size, delta = 0;
11197 	const int insn_cnt = env->prog->len;
11198 	struct bpf_insn insn_buf[16], *insn;
11199 	u32 target_size, size_default, off;
11200 	struct bpf_prog *new_prog;
11201 	enum bpf_access_type type;
11202 	bool is_narrower_load;
11203 
11204 	if (ops->gen_prologue || env->seen_direct_write) {
11205 		if (!ops->gen_prologue) {
11206 			verbose(env, "bpf verifier is misconfigured\n");
11207 			return -EINVAL;
11208 		}
11209 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11210 					env->prog);
11211 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11212 			verbose(env, "bpf verifier is misconfigured\n");
11213 			return -EINVAL;
11214 		} else if (cnt) {
11215 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11216 			if (!new_prog)
11217 				return -ENOMEM;
11218 
11219 			env->prog = new_prog;
11220 			delta += cnt - 1;
11221 		}
11222 	}
11223 
11224 	if (bpf_prog_is_dev_bound(env->prog->aux))
11225 		return 0;
11226 
11227 	insn = env->prog->insnsi + delta;
11228 
11229 	for (i = 0; i < insn_cnt; i++, insn++) {
11230 		bpf_convert_ctx_access_t convert_ctx_access;
11231 		bool ctx_access;
11232 
11233 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11234 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11235 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11236 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11237 			type = BPF_READ;
11238 			ctx_access = true;
11239 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11240 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11241 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11242 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11243 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11244 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11245 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11246 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11247 			type = BPF_WRITE;
11248 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11249 		} else {
11250 			continue;
11251 		}
11252 
11253 		if (type == BPF_WRITE &&
11254 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
11255 			struct bpf_insn patch[] = {
11256 				*insn,
11257 				BPF_ST_NOSPEC(),
11258 			};
11259 
11260 			cnt = ARRAY_SIZE(patch);
11261 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11262 			if (!new_prog)
11263 				return -ENOMEM;
11264 
11265 			delta    += cnt - 1;
11266 			env->prog = new_prog;
11267 			insn      = new_prog->insnsi + i + delta;
11268 			continue;
11269 		}
11270 
11271 		if (!ctx_access)
11272 			continue;
11273 
11274 		switch (env->insn_aux_data[i + delta].ptr_type) {
11275 		case PTR_TO_CTX:
11276 			if (!ops->convert_ctx_access)
11277 				continue;
11278 			convert_ctx_access = ops->convert_ctx_access;
11279 			break;
11280 		case PTR_TO_SOCKET:
11281 		case PTR_TO_SOCK_COMMON:
11282 			convert_ctx_access = bpf_sock_convert_ctx_access;
11283 			break;
11284 		case PTR_TO_TCP_SOCK:
11285 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11286 			break;
11287 		case PTR_TO_XDP_SOCK:
11288 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11289 			break;
11290 		case PTR_TO_BTF_ID:
11291 			if (type == BPF_READ) {
11292 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11293 					BPF_SIZE((insn)->code);
11294 				env->prog->aux->num_exentries++;
11295 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11296 				verbose(env, "Writes through BTF pointers are not allowed\n");
11297 				return -EINVAL;
11298 			}
11299 			continue;
11300 		default:
11301 			continue;
11302 		}
11303 
11304 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11305 		size = BPF_LDST_BYTES(insn);
11306 
11307 		/* If the read access is a narrower load of the field,
11308 		 * convert to a 4/8-byte load, to minimum program type specific
11309 		 * convert_ctx_access changes. If conversion is successful,
11310 		 * we will apply proper mask to the result.
11311 		 */
11312 		is_narrower_load = size < ctx_field_size;
11313 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11314 		off = insn->off;
11315 		if (is_narrower_load) {
11316 			u8 size_code;
11317 
11318 			if (type == BPF_WRITE) {
11319 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11320 				return -EINVAL;
11321 			}
11322 
11323 			size_code = BPF_H;
11324 			if (ctx_field_size == 4)
11325 				size_code = BPF_W;
11326 			else if (ctx_field_size == 8)
11327 				size_code = BPF_DW;
11328 
11329 			insn->off = off & ~(size_default - 1);
11330 			insn->code = BPF_LDX | BPF_MEM | size_code;
11331 		}
11332 
11333 		target_size = 0;
11334 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11335 					 &target_size);
11336 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11337 		    (ctx_field_size && !target_size)) {
11338 			verbose(env, "bpf verifier is misconfigured\n");
11339 			return -EINVAL;
11340 		}
11341 
11342 		if (is_narrower_load && size < target_size) {
11343 			u8 shift = bpf_ctx_narrow_access_offset(
11344 				off, size, size_default) * 8;
11345 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11346 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11347 				return -EINVAL;
11348 			}
11349 			if (ctx_field_size <= 4) {
11350 				if (shift)
11351 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11352 									insn->dst_reg,
11353 									shift);
11354 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11355 								(1 << size * 8) - 1);
11356 			} else {
11357 				if (shift)
11358 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11359 									insn->dst_reg,
11360 									shift);
11361 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11362 								(1ULL << size * 8) - 1);
11363 			}
11364 		}
11365 
11366 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11367 		if (!new_prog)
11368 			return -ENOMEM;
11369 
11370 		delta += cnt - 1;
11371 
11372 		/* keep walking new program and skip insns we just inserted */
11373 		env->prog = new_prog;
11374 		insn      = new_prog->insnsi + i + delta;
11375 	}
11376 
11377 	return 0;
11378 }
11379 
jit_subprogs(struct bpf_verifier_env * env)11380 static int jit_subprogs(struct bpf_verifier_env *env)
11381 {
11382 	struct bpf_prog *prog = env->prog, **func, *tmp;
11383 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11384 	struct bpf_map *map_ptr;
11385 	struct bpf_insn *insn;
11386 	void *old_bpf_func;
11387 	int err, num_exentries;
11388 
11389 	if (env->subprog_cnt <= 1)
11390 		return 0;
11391 
11392 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11393 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11394 		    insn->src_reg != BPF_PSEUDO_CALL)
11395 			continue;
11396 		/* Upon error here we cannot fall back to interpreter but
11397 		 * need a hard reject of the program. Thus -EFAULT is
11398 		 * propagated in any case.
11399 		 */
11400 		subprog = find_subprog(env, i + insn->imm + 1);
11401 		if (subprog < 0) {
11402 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11403 				  i + insn->imm + 1);
11404 			return -EFAULT;
11405 		}
11406 		/* temporarily remember subprog id inside insn instead of
11407 		 * aux_data, since next loop will split up all insns into funcs
11408 		 */
11409 		insn->off = subprog;
11410 		/* remember original imm in case JIT fails and fallback
11411 		 * to interpreter will be needed
11412 		 */
11413 		env->insn_aux_data[i].call_imm = insn->imm;
11414 		/* point imm to __bpf_call_base+1 from JITs point of view */
11415 		insn->imm = 1;
11416 	}
11417 
11418 	err = bpf_prog_alloc_jited_linfo(prog);
11419 	if (err)
11420 		goto out_undo_insn;
11421 
11422 	err = -ENOMEM;
11423 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11424 	if (!func)
11425 		goto out_undo_insn;
11426 
11427 	for (i = 0; i < env->subprog_cnt; i++) {
11428 		subprog_start = subprog_end;
11429 		subprog_end = env->subprog_info[i + 1].start;
11430 
11431 		len = subprog_end - subprog_start;
11432 		/* BPF_PROG_RUN doesn't call subprogs directly,
11433 		 * hence main prog stats include the runtime of subprogs.
11434 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11435 		 * func[i]->aux->stats will never be accessed and stays NULL
11436 		 */
11437 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11438 		if (!func[i])
11439 			goto out_free;
11440 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11441 		       len * sizeof(struct bpf_insn));
11442 		func[i]->type = prog->type;
11443 		func[i]->len = len;
11444 		if (bpf_prog_calc_tag(func[i]))
11445 			goto out_free;
11446 		func[i]->is_func = 1;
11447 		func[i]->aux->func_idx = i;
11448 		/* Below members will be freed only at prog->aux */
11449 		func[i]->aux->btf = prog->aux->btf;
11450 		func[i]->aux->func_info = prog->aux->func_info;
11451 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11452 		func[i]->aux->poke_tab = prog->aux->poke_tab;
11453 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11454 
11455 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11456 			struct bpf_jit_poke_descriptor *poke;
11457 
11458 			poke = &prog->aux->poke_tab[j];
11459 			if (poke->insn_idx < subprog_end &&
11460 			    poke->insn_idx >= subprog_start)
11461 				poke->aux = func[i]->aux;
11462 		}
11463 
11464 		func[i]->aux->name[0] = 'F';
11465 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11466 		func[i]->jit_requested = 1;
11467 		func[i]->aux->linfo = prog->aux->linfo;
11468 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11469 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11470 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11471 		num_exentries = 0;
11472 		insn = func[i]->insnsi;
11473 		for (j = 0; j < func[i]->len; j++, insn++) {
11474 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11475 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11476 				num_exentries++;
11477 		}
11478 		func[i]->aux->num_exentries = num_exentries;
11479 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11480 		func[i] = bpf_int_jit_compile(func[i]);
11481 		if (!func[i]->jited) {
11482 			err = -ENOTSUPP;
11483 			goto out_free;
11484 		}
11485 		cond_resched();
11486 	}
11487 
11488 	/* at this point all bpf functions were successfully JITed
11489 	 * now populate all bpf_calls with correct addresses and
11490 	 * run last pass of JIT
11491 	 */
11492 	for (i = 0; i < env->subprog_cnt; i++) {
11493 		insn = func[i]->insnsi;
11494 		for (j = 0; j < func[i]->len; j++, insn++) {
11495 			if (insn->code != (BPF_JMP | BPF_CALL) ||
11496 			    insn->src_reg != BPF_PSEUDO_CALL)
11497 				continue;
11498 			subprog = insn->off;
11499 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11500 				    __bpf_call_base;
11501 		}
11502 
11503 		/* we use the aux data to keep a list of the start addresses
11504 		 * of the JITed images for each function in the program
11505 		 *
11506 		 * for some architectures, such as powerpc64, the imm field
11507 		 * might not be large enough to hold the offset of the start
11508 		 * address of the callee's JITed image from __bpf_call_base
11509 		 *
11510 		 * in such cases, we can lookup the start address of a callee
11511 		 * by using its subprog id, available from the off field of
11512 		 * the call instruction, as an index for this list
11513 		 */
11514 		func[i]->aux->func = func;
11515 		func[i]->aux->func_cnt = env->subprog_cnt;
11516 	}
11517 	for (i = 0; i < env->subprog_cnt; i++) {
11518 		old_bpf_func = func[i]->bpf_func;
11519 		tmp = bpf_int_jit_compile(func[i]);
11520 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11521 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11522 			err = -ENOTSUPP;
11523 			goto out_free;
11524 		}
11525 		cond_resched();
11526 	}
11527 
11528 	/* finally lock prog and jit images for all functions and
11529 	 * populate kallsysm
11530 	 */
11531 	for (i = 0; i < env->subprog_cnt; i++) {
11532 		bpf_prog_lock_ro(func[i]);
11533 		bpf_prog_kallsyms_add(func[i]);
11534 	}
11535 
11536 	/* Last step: make now unused interpreter insns from main
11537 	 * prog consistent for later dump requests, so they can
11538 	 * later look the same as if they were interpreted only.
11539 	 */
11540 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11541 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11542 		    insn->src_reg != BPF_PSEUDO_CALL)
11543 			continue;
11544 		insn->off = env->insn_aux_data[i].call_imm;
11545 		subprog = find_subprog(env, i + insn->off + 1);
11546 		insn->imm = subprog;
11547 	}
11548 
11549 	prog->jited = 1;
11550 	prog->bpf_func = func[0]->bpf_func;
11551 	prog->aux->func = func;
11552 	prog->aux->func_cnt = env->subprog_cnt;
11553 	bpf_prog_free_unused_jited_linfo(prog);
11554 	return 0;
11555 out_free:
11556 	/* We failed JIT'ing, so at this point we need to unregister poke
11557 	 * descriptors from subprogs, so that kernel is not attempting to
11558 	 * patch it anymore as we're freeing the subprog JIT memory.
11559 	 */
11560 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11561 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11562 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11563 	}
11564 	/* At this point we're guaranteed that poke descriptors are not
11565 	 * live anymore. We can just unlink its descriptor table as it's
11566 	 * released with the main prog.
11567 	 */
11568 	for (i = 0; i < env->subprog_cnt; i++) {
11569 		if (!func[i])
11570 			continue;
11571 		func[i]->aux->poke_tab = NULL;
11572 		bpf_jit_free(func[i]);
11573 	}
11574 	kfree(func);
11575 out_undo_insn:
11576 	/* cleanup main prog to be interpreted */
11577 	prog->jit_requested = 0;
11578 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11579 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11580 		    insn->src_reg != BPF_PSEUDO_CALL)
11581 			continue;
11582 		insn->off = 0;
11583 		insn->imm = env->insn_aux_data[i].call_imm;
11584 	}
11585 	bpf_prog_free_jited_linfo(prog);
11586 	return err;
11587 }
11588 
fixup_call_args(struct bpf_verifier_env * env)11589 static int fixup_call_args(struct bpf_verifier_env *env)
11590 {
11591 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11592 	struct bpf_prog *prog = env->prog;
11593 	struct bpf_insn *insn = prog->insnsi;
11594 	int i, depth;
11595 #endif
11596 	int err = 0;
11597 
11598 	if (env->prog->jit_requested &&
11599 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
11600 		err = jit_subprogs(env);
11601 		if (err == 0)
11602 			return 0;
11603 		if (err == -EFAULT)
11604 			return err;
11605 	}
11606 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11607 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11608 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
11609 		 * have to be rejected, since interpreter doesn't support them yet.
11610 		 */
11611 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11612 		return -EINVAL;
11613 	}
11614 	for (i = 0; i < prog->len; i++, insn++) {
11615 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11616 		    insn->src_reg != BPF_PSEUDO_CALL)
11617 			continue;
11618 		depth = get_callee_stack_depth(env, insn, i);
11619 		if (depth < 0)
11620 			return depth;
11621 		bpf_patch_call_args(insn, depth);
11622 	}
11623 	err = 0;
11624 #endif
11625 	return err;
11626 }
11627 
11628 /* fixup insn->imm field of bpf_call instructions
11629  * and inline eligible helpers as explicit sequence of BPF instructions
11630  *
11631  * this function is called after eBPF program passed verification
11632  */
fixup_bpf_calls(struct bpf_verifier_env * env)11633 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11634 {
11635 	struct bpf_prog *prog = env->prog;
11636 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
11637 	struct bpf_insn *insn = prog->insnsi;
11638 	const struct bpf_func_proto *fn;
11639 	const int insn_cnt = prog->len;
11640 	const struct bpf_map_ops *ops;
11641 	struct bpf_insn_aux_data *aux;
11642 	struct bpf_insn insn_buf[16];
11643 	struct bpf_prog *new_prog;
11644 	struct bpf_map *map_ptr;
11645 	int i, ret, cnt, delta = 0;
11646 
11647 	for (i = 0; i < insn_cnt; i++, insn++) {
11648 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11649 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11650 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11651 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11652 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11653 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11654 			struct bpf_insn *patchlet;
11655 			struct bpf_insn chk_and_div[] = {
11656 				/* [R,W]x div 0 -> 0 */
11657 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11658 					     BPF_JNE | BPF_K, insn->src_reg,
11659 					     0, 2, 0),
11660 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11661 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11662 				*insn,
11663 			};
11664 			struct bpf_insn chk_and_mod[] = {
11665 				/* [R,W]x mod 0 -> [R,W]x */
11666 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11667 					     BPF_JEQ | BPF_K, insn->src_reg,
11668 					     0, 1 + (is64 ? 0 : 1), 0),
11669 				*insn,
11670 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11671 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11672 			};
11673 
11674 			patchlet = isdiv ? chk_and_div : chk_and_mod;
11675 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11676 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11677 
11678 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11679 			if (!new_prog)
11680 				return -ENOMEM;
11681 
11682 			delta    += cnt - 1;
11683 			env->prog = prog = new_prog;
11684 			insn      = new_prog->insnsi + i + delta;
11685 			continue;
11686 		}
11687 
11688 		if (BPF_CLASS(insn->code) == BPF_LD &&
11689 		    (BPF_MODE(insn->code) == BPF_ABS ||
11690 		     BPF_MODE(insn->code) == BPF_IND)) {
11691 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
11692 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11693 				verbose(env, "bpf verifier is misconfigured\n");
11694 				return -EINVAL;
11695 			}
11696 
11697 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11698 			if (!new_prog)
11699 				return -ENOMEM;
11700 
11701 			delta    += cnt - 1;
11702 			env->prog = prog = new_prog;
11703 			insn      = new_prog->insnsi + i + delta;
11704 			continue;
11705 		}
11706 
11707 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11708 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11709 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11710 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11711 			struct bpf_insn insn_buf[16];
11712 			struct bpf_insn *patch = &insn_buf[0];
11713 			bool issrc, isneg, isimm;
11714 			u32 off_reg;
11715 
11716 			aux = &env->insn_aux_data[i + delta];
11717 			if (!aux->alu_state ||
11718 			    aux->alu_state == BPF_ALU_NON_POINTER)
11719 				continue;
11720 
11721 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11722 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11723 				BPF_ALU_SANITIZE_SRC;
11724 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11725 
11726 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11727 			if (isimm) {
11728 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11729 			} else {
11730 				if (isneg)
11731 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11732 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11733 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11734 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11735 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11736 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11737 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11738 			}
11739 			if (!issrc)
11740 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11741 			insn->src_reg = BPF_REG_AX;
11742 			if (isneg)
11743 				insn->code = insn->code == code_add ?
11744 					     code_sub : code_add;
11745 			*patch++ = *insn;
11746 			if (issrc && isneg && !isimm)
11747 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11748 			cnt = patch - insn_buf;
11749 
11750 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11751 			if (!new_prog)
11752 				return -ENOMEM;
11753 
11754 			delta    += cnt - 1;
11755 			env->prog = prog = new_prog;
11756 			insn      = new_prog->insnsi + i + delta;
11757 			continue;
11758 		}
11759 
11760 		if (insn->code != (BPF_JMP | BPF_CALL))
11761 			continue;
11762 		if (insn->src_reg == BPF_PSEUDO_CALL)
11763 			continue;
11764 
11765 		if (insn->imm == BPF_FUNC_get_route_realm)
11766 			prog->dst_needed = 1;
11767 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11768 			bpf_user_rnd_init_once();
11769 		if (insn->imm == BPF_FUNC_override_return)
11770 			prog->kprobe_override = 1;
11771 		if (insn->imm == BPF_FUNC_tail_call) {
11772 			/* If we tail call into other programs, we
11773 			 * cannot make any assumptions since they can
11774 			 * be replaced dynamically during runtime in
11775 			 * the program array.
11776 			 */
11777 			prog->cb_access = 1;
11778 			if (!allow_tail_call_in_subprogs(env))
11779 				prog->aux->stack_depth = MAX_BPF_STACK;
11780 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11781 
11782 			/* mark bpf_tail_call as different opcode to avoid
11783 			 * conditional branch in the interpeter for every normal
11784 			 * call and to prevent accidental JITing by JIT compiler
11785 			 * that doesn't support bpf_tail_call yet
11786 			 */
11787 			insn->imm = 0;
11788 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11789 
11790 			aux = &env->insn_aux_data[i + delta];
11791 			if (env->bpf_capable && !expect_blinding &&
11792 			    prog->jit_requested &&
11793 			    !bpf_map_key_poisoned(aux) &&
11794 			    !bpf_map_ptr_poisoned(aux) &&
11795 			    !bpf_map_ptr_unpriv(aux)) {
11796 				struct bpf_jit_poke_descriptor desc = {
11797 					.reason = BPF_POKE_REASON_TAIL_CALL,
11798 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11799 					.tail_call.key = bpf_map_key_immediate(aux),
11800 					.insn_idx = i + delta,
11801 				};
11802 
11803 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11804 				if (ret < 0) {
11805 					verbose(env, "adding tail call poke descriptor failed\n");
11806 					return ret;
11807 				}
11808 
11809 				insn->imm = ret + 1;
11810 				continue;
11811 			}
11812 
11813 			if (!bpf_map_ptr_unpriv(aux))
11814 				continue;
11815 
11816 			/* instead of changing every JIT dealing with tail_call
11817 			 * emit two extra insns:
11818 			 * if (index >= max_entries) goto out;
11819 			 * index &= array->index_mask;
11820 			 * to avoid out-of-bounds cpu speculation
11821 			 */
11822 			if (bpf_map_ptr_poisoned(aux)) {
11823 				verbose(env, "tail_call abusing map_ptr\n");
11824 				return -EINVAL;
11825 			}
11826 
11827 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11828 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11829 						  map_ptr->max_entries, 2);
11830 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11831 						    container_of(map_ptr,
11832 								 struct bpf_array,
11833 								 map)->index_mask);
11834 			insn_buf[2] = *insn;
11835 			cnt = 3;
11836 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11837 			if (!new_prog)
11838 				return -ENOMEM;
11839 
11840 			delta    += cnt - 1;
11841 			env->prog = prog = new_prog;
11842 			insn      = new_prog->insnsi + i + delta;
11843 			continue;
11844 		}
11845 
11846 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11847 		 * and other inlining handlers are currently limited to 64 bit
11848 		 * only.
11849 		 */
11850 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11851 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11852 		     insn->imm == BPF_FUNC_map_update_elem ||
11853 		     insn->imm == BPF_FUNC_map_delete_elem ||
11854 		     insn->imm == BPF_FUNC_map_push_elem   ||
11855 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11856 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11857 			aux = &env->insn_aux_data[i + delta];
11858 			if (bpf_map_ptr_poisoned(aux))
11859 				goto patch_call_imm;
11860 
11861 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11862 			ops = map_ptr->ops;
11863 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11864 			    ops->map_gen_lookup) {
11865 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11866 				if (cnt == -EOPNOTSUPP)
11867 					goto patch_map_ops_generic;
11868 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11869 					verbose(env, "bpf verifier is misconfigured\n");
11870 					return -EINVAL;
11871 				}
11872 
11873 				new_prog = bpf_patch_insn_data(env, i + delta,
11874 							       insn_buf, cnt);
11875 				if (!new_prog)
11876 					return -ENOMEM;
11877 
11878 				delta    += cnt - 1;
11879 				env->prog = prog = new_prog;
11880 				insn      = new_prog->insnsi + i + delta;
11881 				continue;
11882 			}
11883 
11884 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11885 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11886 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11887 				     (int (*)(struct bpf_map *map, void *key))NULL));
11888 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11889 				     (int (*)(struct bpf_map *map, void *key, void *value,
11890 					      u64 flags))NULL));
11891 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11892 				     (int (*)(struct bpf_map *map, void *value,
11893 					      u64 flags))NULL));
11894 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11895 				     (int (*)(struct bpf_map *map, void *value))NULL));
11896 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11897 				     (int (*)(struct bpf_map *map, void *value))NULL));
11898 patch_map_ops_generic:
11899 			switch (insn->imm) {
11900 			case BPF_FUNC_map_lookup_elem:
11901 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11902 					    __bpf_call_base;
11903 				continue;
11904 			case BPF_FUNC_map_update_elem:
11905 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11906 					    __bpf_call_base;
11907 				continue;
11908 			case BPF_FUNC_map_delete_elem:
11909 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11910 					    __bpf_call_base;
11911 				continue;
11912 			case BPF_FUNC_map_push_elem:
11913 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11914 					    __bpf_call_base;
11915 				continue;
11916 			case BPF_FUNC_map_pop_elem:
11917 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11918 					    __bpf_call_base;
11919 				continue;
11920 			case BPF_FUNC_map_peek_elem:
11921 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11922 					    __bpf_call_base;
11923 				continue;
11924 			}
11925 
11926 			goto patch_call_imm;
11927 		}
11928 
11929 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11930 		    insn->imm == BPF_FUNC_jiffies64) {
11931 			struct bpf_insn ld_jiffies_addr[2] = {
11932 				BPF_LD_IMM64(BPF_REG_0,
11933 					     (unsigned long)&jiffies),
11934 			};
11935 
11936 			insn_buf[0] = ld_jiffies_addr[0];
11937 			insn_buf[1] = ld_jiffies_addr[1];
11938 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11939 						  BPF_REG_0, 0);
11940 			cnt = 3;
11941 
11942 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11943 						       cnt);
11944 			if (!new_prog)
11945 				return -ENOMEM;
11946 
11947 			delta    += cnt - 1;
11948 			env->prog = prog = new_prog;
11949 			insn      = new_prog->insnsi + i + delta;
11950 			continue;
11951 		}
11952 
11953 patch_call_imm:
11954 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11955 		/* all functions that have prototype and verifier allowed
11956 		 * programs to call them, must be real in-kernel functions
11957 		 */
11958 		if (!fn->func) {
11959 			verbose(env,
11960 				"kernel subsystem misconfigured func %s#%d\n",
11961 				func_id_name(insn->imm), insn->imm);
11962 			return -EFAULT;
11963 		}
11964 		insn->imm = fn->func - __bpf_call_base;
11965 	}
11966 
11967 	/* Since poke tab is now finalized, publish aux to tracker. */
11968 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11969 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11970 		if (!map_ptr->ops->map_poke_track ||
11971 		    !map_ptr->ops->map_poke_untrack ||
11972 		    !map_ptr->ops->map_poke_run) {
11973 			verbose(env, "bpf verifier is misconfigured\n");
11974 			return -EINVAL;
11975 		}
11976 
11977 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11978 		if (ret < 0) {
11979 			verbose(env, "tracking tail call prog failed\n");
11980 			return ret;
11981 		}
11982 	}
11983 
11984 	return 0;
11985 }
11986 
free_states(struct bpf_verifier_env * env)11987 static void free_states(struct bpf_verifier_env *env)
11988 {
11989 	struct bpf_verifier_state_list *sl, *sln;
11990 	int i;
11991 
11992 	sl = env->free_list;
11993 	while (sl) {
11994 		sln = sl->next;
11995 		free_verifier_state(&sl->state, false);
11996 		kfree(sl);
11997 		sl = sln;
11998 	}
11999 	env->free_list = NULL;
12000 
12001 	if (!env->explored_states)
12002 		return;
12003 
12004 	for (i = 0; i < state_htab_size(env); i++) {
12005 		sl = env->explored_states[i];
12006 
12007 		while (sl) {
12008 			sln = sl->next;
12009 			free_verifier_state(&sl->state, false);
12010 			kfree(sl);
12011 			sl = sln;
12012 		}
12013 		env->explored_states[i] = NULL;
12014 	}
12015 }
12016 
do_check_common(struct bpf_verifier_env * env,int subprog)12017 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12018 {
12019 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12020 	struct bpf_verifier_state *state;
12021 	struct bpf_reg_state *regs;
12022 	int ret, i;
12023 
12024 	env->prev_linfo = NULL;
12025 	env->pass_cnt++;
12026 
12027 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12028 	if (!state)
12029 		return -ENOMEM;
12030 	state->curframe = 0;
12031 	state->speculative = false;
12032 	state->branches = 1;
12033 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12034 	if (!state->frame[0]) {
12035 		kfree(state);
12036 		return -ENOMEM;
12037 	}
12038 	env->cur_state = state;
12039 	init_func_state(env, state->frame[0],
12040 			BPF_MAIN_FUNC /* callsite */,
12041 			0 /* frameno */,
12042 			subprog);
12043 
12044 	state->first_insn_idx = env->subprog_info[subprog].start;
12045 	state->last_insn_idx = -1;
12046 
12047 	regs = state->frame[state->curframe]->regs;
12048 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12049 		ret = btf_prepare_func_args(env, subprog, regs);
12050 		if (ret)
12051 			goto out;
12052 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12053 			if (regs[i].type == PTR_TO_CTX)
12054 				mark_reg_known_zero(env, regs, i);
12055 			else if (regs[i].type == SCALAR_VALUE)
12056 				mark_reg_unknown(env, regs, i);
12057 		}
12058 	} else {
12059 		/* 1st arg to a function */
12060 		regs[BPF_REG_1].type = PTR_TO_CTX;
12061 		mark_reg_known_zero(env, regs, BPF_REG_1);
12062 		ret = btf_check_func_arg_match(env, subprog, regs);
12063 		if (ret == -EFAULT)
12064 			/* unlikely verifier bug. abort.
12065 			 * ret == 0 and ret < 0 are sadly acceptable for
12066 			 * main() function due to backward compatibility.
12067 			 * Like socket filter program may be written as:
12068 			 * int bpf_prog(struct pt_regs *ctx)
12069 			 * and never dereference that ctx in the program.
12070 			 * 'struct pt_regs' is a type mismatch for socket
12071 			 * filter that should be using 'struct __sk_buff'.
12072 			 */
12073 			goto out;
12074 	}
12075 
12076 	ret = do_check(env);
12077 out:
12078 	/* check for NULL is necessary, since cur_state can be freed inside
12079 	 * do_check() under memory pressure.
12080 	 */
12081 	if (env->cur_state) {
12082 		free_verifier_state(env->cur_state, true);
12083 		env->cur_state = NULL;
12084 	}
12085 	while (!pop_stack(env, NULL, NULL, false));
12086 	if (!ret && pop_log)
12087 		bpf_vlog_reset(&env->log, 0);
12088 	free_states(env);
12089 	return ret;
12090 }
12091 
12092 /* Verify all global functions in a BPF program one by one based on their BTF.
12093  * All global functions must pass verification. Otherwise the whole program is rejected.
12094  * Consider:
12095  * int bar(int);
12096  * int foo(int f)
12097  * {
12098  *    return bar(f);
12099  * }
12100  * int bar(int b)
12101  * {
12102  *    ...
12103  * }
12104  * foo() will be verified first for R1=any_scalar_value. During verification it
12105  * will be assumed that bar() already verified successfully and call to bar()
12106  * from foo() will be checked for type match only. Later bar() will be verified
12107  * independently to check that it's safe for R1=any_scalar_value.
12108  */
do_check_subprogs(struct bpf_verifier_env * env)12109 static int do_check_subprogs(struct bpf_verifier_env *env)
12110 {
12111 	struct bpf_prog_aux *aux = env->prog->aux;
12112 	int i, ret;
12113 
12114 	if (!aux->func_info)
12115 		return 0;
12116 
12117 	for (i = 1; i < env->subprog_cnt; i++) {
12118 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12119 			continue;
12120 		env->insn_idx = env->subprog_info[i].start;
12121 		WARN_ON_ONCE(env->insn_idx == 0);
12122 		ret = do_check_common(env, i);
12123 		if (ret) {
12124 			return ret;
12125 		} else if (env->log.level & BPF_LOG_LEVEL) {
12126 			verbose(env,
12127 				"Func#%d is safe for any args that match its prototype\n",
12128 				i);
12129 		}
12130 	}
12131 	return 0;
12132 }
12133 
do_check_main(struct bpf_verifier_env * env)12134 static int do_check_main(struct bpf_verifier_env *env)
12135 {
12136 	int ret;
12137 
12138 	env->insn_idx = 0;
12139 	ret = do_check_common(env, 0);
12140 	if (!ret)
12141 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12142 	return ret;
12143 }
12144 
12145 
print_verification_stats(struct bpf_verifier_env * env)12146 static void print_verification_stats(struct bpf_verifier_env *env)
12147 {
12148 	int i;
12149 
12150 	if (env->log.level & BPF_LOG_STATS) {
12151 		verbose(env, "verification time %lld usec\n",
12152 			div_u64(env->verification_time, 1000));
12153 		verbose(env, "stack depth ");
12154 		for (i = 0; i < env->subprog_cnt; i++) {
12155 			u32 depth = env->subprog_info[i].stack_depth;
12156 
12157 			verbose(env, "%d", depth);
12158 			if (i + 1 < env->subprog_cnt)
12159 				verbose(env, "+");
12160 		}
12161 		verbose(env, "\n");
12162 	}
12163 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12164 		"total_states %d peak_states %d mark_read %d\n",
12165 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12166 		env->max_states_per_insn, env->total_states,
12167 		env->peak_states, env->longest_mark_read_walk);
12168 }
12169 
check_struct_ops_btf_id(struct bpf_verifier_env * env)12170 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12171 {
12172 	const struct btf_type *t, *func_proto;
12173 	const struct bpf_struct_ops *st_ops;
12174 	const struct btf_member *member;
12175 	struct bpf_prog *prog = env->prog;
12176 	u32 btf_id, member_idx;
12177 	const char *mname;
12178 
12179 	if (!prog->gpl_compatible) {
12180 		verbose(env, "struct ops programs must have a GPL compatible license\n");
12181 		return -EINVAL;
12182 	}
12183 
12184 	btf_id = prog->aux->attach_btf_id;
12185 	st_ops = bpf_struct_ops_find(btf_id);
12186 	if (!st_ops) {
12187 		verbose(env, "attach_btf_id %u is not a supported struct\n",
12188 			btf_id);
12189 		return -ENOTSUPP;
12190 	}
12191 
12192 	t = st_ops->type;
12193 	member_idx = prog->expected_attach_type;
12194 	if (member_idx >= btf_type_vlen(t)) {
12195 		verbose(env, "attach to invalid member idx %u of struct %s\n",
12196 			member_idx, st_ops->name);
12197 		return -EINVAL;
12198 	}
12199 
12200 	member = &btf_type_member(t)[member_idx];
12201 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12202 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12203 					       NULL);
12204 	if (!func_proto) {
12205 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12206 			mname, member_idx, st_ops->name);
12207 		return -EINVAL;
12208 	}
12209 
12210 	if (st_ops->check_member) {
12211 		int err = st_ops->check_member(t, member);
12212 
12213 		if (err) {
12214 			verbose(env, "attach to unsupported member %s of struct %s\n",
12215 				mname, st_ops->name);
12216 			return err;
12217 		}
12218 	}
12219 
12220 	prog->aux->attach_func_proto = func_proto;
12221 	prog->aux->attach_func_name = mname;
12222 	env->ops = st_ops->verifier_ops;
12223 
12224 	return 0;
12225 }
12226 #define SECURITY_PREFIX "security_"
12227 
check_attach_modify_return(unsigned long addr,const char * func_name)12228 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12229 {
12230 	if (within_error_injection_list(addr) ||
12231 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12232 		return 0;
12233 
12234 	return -EINVAL;
12235 }
12236 
12237 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12238 BTF_SET_START(btf_sleepable_lsm_hooks)
12239 #ifdef CONFIG_BPF_LSM
BTF_ID(func,bpf_lsm_bprm_committed_creds)12240 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12241 #else
12242 BTF_ID_UNUSED
12243 #endif
12244 BTF_SET_END(btf_sleepable_lsm_hooks)
12245 
12246 static int check_sleepable_lsm_hook(u32 btf_id)
12247 {
12248 	return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12249 }
12250 
12251 /* list of non-sleepable functions that are otherwise on
12252  * ALLOW_ERROR_INJECTION list
12253  */
12254 BTF_SET_START(btf_non_sleepable_error_inject)
12255 /* Three functions below can be called from sleepable and non-sleepable context.
12256  * Assume non-sleepable from bpf safety point of view.
12257  */
BTF_ID(func,__add_to_page_cache_locked)12258 BTF_ID(func, __add_to_page_cache_locked)
12259 BTF_ID(func, should_fail_alloc_page)
12260 BTF_ID(func, should_failslab)
12261 BTF_SET_END(btf_non_sleepable_error_inject)
12262 
12263 static int check_non_sleepable_error_inject(u32 btf_id)
12264 {
12265 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12266 }
12267 
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)12268 int bpf_check_attach_target(struct bpf_verifier_log *log,
12269 			    const struct bpf_prog *prog,
12270 			    const struct bpf_prog *tgt_prog,
12271 			    u32 btf_id,
12272 			    struct bpf_attach_target_info *tgt_info)
12273 {
12274 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12275 	const char prefix[] = "btf_trace_";
12276 	int ret = 0, subprog = -1, i;
12277 	const struct btf_type *t;
12278 	bool conservative = true;
12279 	const char *tname;
12280 	struct btf *btf;
12281 	long addr = 0;
12282 
12283 	if (!btf_id) {
12284 		bpf_log(log, "Tracing programs must provide btf_id\n");
12285 		return -EINVAL;
12286 	}
12287 	btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12288 	if (!btf) {
12289 		bpf_log(log,
12290 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12291 		return -EINVAL;
12292 	}
12293 	t = btf_type_by_id(btf, btf_id);
12294 	if (!t) {
12295 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12296 		return -EINVAL;
12297 	}
12298 	tname = btf_name_by_offset(btf, t->name_off);
12299 	if (!tname) {
12300 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12301 		return -EINVAL;
12302 	}
12303 	if (tgt_prog) {
12304 		struct bpf_prog_aux *aux = tgt_prog->aux;
12305 
12306 		for (i = 0; i < aux->func_info_cnt; i++)
12307 			if (aux->func_info[i].type_id == btf_id) {
12308 				subprog = i;
12309 				break;
12310 			}
12311 		if (subprog == -1) {
12312 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12313 			return -EINVAL;
12314 		}
12315 		conservative = aux->func_info_aux[subprog].unreliable;
12316 		if (prog_extension) {
12317 			if (conservative) {
12318 				bpf_log(log,
12319 					"Cannot replace static functions\n");
12320 				return -EINVAL;
12321 			}
12322 			if (!prog->jit_requested) {
12323 				bpf_log(log,
12324 					"Extension programs should be JITed\n");
12325 				return -EINVAL;
12326 			}
12327 		}
12328 		if (!tgt_prog->jited) {
12329 			bpf_log(log, "Can attach to only JITed progs\n");
12330 			return -EINVAL;
12331 		}
12332 		if (tgt_prog->type == prog->type) {
12333 			/* Cannot fentry/fexit another fentry/fexit program.
12334 			 * Cannot attach program extension to another extension.
12335 			 * It's ok to attach fentry/fexit to extension program.
12336 			 */
12337 			bpf_log(log, "Cannot recursively attach\n");
12338 			return -EINVAL;
12339 		}
12340 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12341 		    prog_extension &&
12342 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12343 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12344 			/* Program extensions can extend all program types
12345 			 * except fentry/fexit. The reason is the following.
12346 			 * The fentry/fexit programs are used for performance
12347 			 * analysis, stats and can be attached to any program
12348 			 * type except themselves. When extension program is
12349 			 * replacing XDP function it is necessary to allow
12350 			 * performance analysis of all functions. Both original
12351 			 * XDP program and its program extension. Hence
12352 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12353 			 * allowed. If extending of fentry/fexit was allowed it
12354 			 * would be possible to create long call chain
12355 			 * fentry->extension->fentry->extension beyond
12356 			 * reasonable stack size. Hence extending fentry is not
12357 			 * allowed.
12358 			 */
12359 			bpf_log(log, "Cannot extend fentry/fexit\n");
12360 			return -EINVAL;
12361 		}
12362 	} else {
12363 		if (prog_extension) {
12364 			bpf_log(log, "Cannot replace kernel functions\n");
12365 			return -EINVAL;
12366 		}
12367 	}
12368 
12369 	switch (prog->expected_attach_type) {
12370 	case BPF_TRACE_RAW_TP:
12371 		if (tgt_prog) {
12372 			bpf_log(log,
12373 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12374 			return -EINVAL;
12375 		}
12376 		if (!btf_type_is_typedef(t)) {
12377 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12378 				btf_id);
12379 			return -EINVAL;
12380 		}
12381 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12382 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12383 				btf_id, tname);
12384 			return -EINVAL;
12385 		}
12386 		tname += sizeof(prefix) - 1;
12387 		t = btf_type_by_id(btf, t->type);
12388 		if (!btf_type_is_ptr(t))
12389 			/* should never happen in valid vmlinux build */
12390 			return -EINVAL;
12391 		t = btf_type_by_id(btf, t->type);
12392 		if (!btf_type_is_func_proto(t))
12393 			/* should never happen in valid vmlinux build */
12394 			return -EINVAL;
12395 
12396 		break;
12397 	case BPF_TRACE_ITER:
12398 		if (!btf_type_is_func(t)) {
12399 			bpf_log(log, "attach_btf_id %u is not a function\n",
12400 				btf_id);
12401 			return -EINVAL;
12402 		}
12403 		t = btf_type_by_id(btf, t->type);
12404 		if (!btf_type_is_func_proto(t))
12405 			return -EINVAL;
12406 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12407 		if (ret)
12408 			return ret;
12409 		break;
12410 	default:
12411 		if (!prog_extension)
12412 			return -EINVAL;
12413 		fallthrough;
12414 	case BPF_MODIFY_RETURN:
12415 	case BPF_LSM_MAC:
12416 	case BPF_TRACE_FENTRY:
12417 	case BPF_TRACE_FEXIT:
12418 		if (!btf_type_is_func(t)) {
12419 			bpf_log(log, "attach_btf_id %u is not a function\n",
12420 				btf_id);
12421 			return -EINVAL;
12422 		}
12423 		if (prog_extension &&
12424 		    btf_check_type_match(log, prog, btf, t))
12425 			return -EINVAL;
12426 		t = btf_type_by_id(btf, t->type);
12427 		if (!btf_type_is_func_proto(t))
12428 			return -EINVAL;
12429 
12430 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12431 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12432 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12433 			return -EINVAL;
12434 
12435 		if (tgt_prog && conservative)
12436 			t = NULL;
12437 
12438 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12439 		if (ret < 0)
12440 			return ret;
12441 
12442 		if (tgt_prog) {
12443 			if (subprog == 0)
12444 				addr = (long) tgt_prog->bpf_func;
12445 			else
12446 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12447 		} else {
12448 			addr = kallsyms_lookup_name(tname);
12449 			if (!addr) {
12450 				bpf_log(log,
12451 					"The address of function %s cannot be found\n",
12452 					tname);
12453 				return -ENOENT;
12454 			}
12455 		}
12456 
12457 		if (prog->aux->sleepable) {
12458 			ret = -EINVAL;
12459 			switch (prog->type) {
12460 			case BPF_PROG_TYPE_TRACING:
12461 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12462 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12463 				 */
12464 				if (!check_non_sleepable_error_inject(btf_id) &&
12465 				    within_error_injection_list(addr))
12466 					ret = 0;
12467 				break;
12468 			case BPF_PROG_TYPE_LSM:
12469 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
12470 				 * Only some of them are sleepable.
12471 				 */
12472 				if (check_sleepable_lsm_hook(btf_id))
12473 					ret = 0;
12474 				break;
12475 			default:
12476 				break;
12477 			}
12478 			if (ret) {
12479 				bpf_log(log, "%s is not sleepable\n", tname);
12480 				return ret;
12481 			}
12482 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12483 			if (tgt_prog) {
12484 				bpf_log(log, "can't modify return codes of BPF programs\n");
12485 				return -EINVAL;
12486 			}
12487 			ret = check_attach_modify_return(addr, tname);
12488 			if (ret) {
12489 				bpf_log(log, "%s() is not modifiable\n", tname);
12490 				return ret;
12491 			}
12492 		}
12493 
12494 		break;
12495 	}
12496 	tgt_info->tgt_addr = addr;
12497 	tgt_info->tgt_name = tname;
12498 	tgt_info->tgt_type = t;
12499 	return 0;
12500 }
12501 
check_attach_btf_id(struct bpf_verifier_env * env)12502 static int check_attach_btf_id(struct bpf_verifier_env *env)
12503 {
12504 	struct bpf_prog *prog = env->prog;
12505 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12506 	struct bpf_attach_target_info tgt_info = {};
12507 	u32 btf_id = prog->aux->attach_btf_id;
12508 	struct bpf_trampoline *tr;
12509 	int ret;
12510 	u64 key;
12511 
12512 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12513 	    prog->type != BPF_PROG_TYPE_LSM) {
12514 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12515 		return -EINVAL;
12516 	}
12517 
12518 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12519 		return check_struct_ops_btf_id(env);
12520 
12521 	if (prog->type != BPF_PROG_TYPE_TRACING &&
12522 	    prog->type != BPF_PROG_TYPE_LSM &&
12523 	    prog->type != BPF_PROG_TYPE_EXT)
12524 		return 0;
12525 
12526 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12527 	if (ret)
12528 		return ret;
12529 
12530 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12531 		/* to make freplace equivalent to their targets, they need to
12532 		 * inherit env->ops and expected_attach_type for the rest of the
12533 		 * verification
12534 		 */
12535 		env->ops = bpf_verifier_ops[tgt_prog->type];
12536 		prog->expected_attach_type = tgt_prog->expected_attach_type;
12537 	}
12538 
12539 	/* store info about the attachment target that will be used later */
12540 	prog->aux->attach_func_proto = tgt_info.tgt_type;
12541 	prog->aux->attach_func_name = tgt_info.tgt_name;
12542 
12543 	if (tgt_prog) {
12544 		prog->aux->saved_dst_prog_type = tgt_prog->type;
12545 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12546 	}
12547 
12548 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12549 		prog->aux->attach_btf_trace = true;
12550 		return 0;
12551 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12552 		if (!bpf_iter_prog_supported(prog))
12553 			return -EINVAL;
12554 		return 0;
12555 	}
12556 
12557 	if (prog->type == BPF_PROG_TYPE_LSM) {
12558 		ret = bpf_lsm_verify_prog(&env->log, prog);
12559 		if (ret < 0)
12560 			return ret;
12561 	}
12562 
12563 	key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12564 	tr = bpf_trampoline_get(key, &tgt_info);
12565 	if (!tr)
12566 		return -ENOMEM;
12567 
12568 	prog->aux->dst_trampoline = tr;
12569 	return 0;
12570 }
12571 
bpf_get_btf_vmlinux(void)12572 struct btf *bpf_get_btf_vmlinux(void)
12573 {
12574 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12575 		mutex_lock(&bpf_verifier_lock);
12576 		if (!btf_vmlinux)
12577 			btf_vmlinux = btf_parse_vmlinux();
12578 		mutex_unlock(&bpf_verifier_lock);
12579 	}
12580 	return btf_vmlinux;
12581 }
12582 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)12583 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12584 	      union bpf_attr __user *uattr)
12585 {
12586 	u64 start_time = ktime_get_ns();
12587 	struct bpf_verifier_env *env;
12588 	struct bpf_verifier_log *log;
12589 	int i, len, ret = -EINVAL;
12590 	bool is_priv;
12591 
12592 	/* no program is valid */
12593 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12594 		return -EINVAL;
12595 
12596 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
12597 	 * allocate/free it every time bpf_check() is called
12598 	 */
12599 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12600 	if (!env)
12601 		return -ENOMEM;
12602 	log = &env->log;
12603 
12604 	len = (*prog)->len;
12605 	env->insn_aux_data =
12606 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12607 	ret = -ENOMEM;
12608 	if (!env->insn_aux_data)
12609 		goto err_free_env;
12610 	for (i = 0; i < len; i++)
12611 		env->insn_aux_data[i].orig_idx = i;
12612 	env->prog = *prog;
12613 	env->ops = bpf_verifier_ops[env->prog->type];
12614 	is_priv = bpf_capable();
12615 
12616 	bpf_get_btf_vmlinux();
12617 
12618 	/* grab the mutex to protect few globals used by verifier */
12619 	if (!is_priv)
12620 		mutex_lock(&bpf_verifier_lock);
12621 
12622 	if (attr->log_level || attr->log_buf || attr->log_size) {
12623 		/* user requested verbose verifier output
12624 		 * and supplied buffer to store the verification trace
12625 		 */
12626 		log->level = attr->log_level;
12627 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12628 		log->len_total = attr->log_size;
12629 
12630 		/* log attributes have to be sane */
12631 		if (!bpf_verifier_log_attr_valid(log)) {
12632 			ret = -EINVAL;
12633 			goto err_unlock;
12634 		}
12635 	}
12636 
12637 	if (IS_ERR(btf_vmlinux)) {
12638 		/* Either gcc or pahole or kernel are broken. */
12639 		verbose(env, "in-kernel BTF is malformed\n");
12640 		ret = PTR_ERR(btf_vmlinux);
12641 		goto skip_full_check;
12642 	}
12643 
12644 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12645 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12646 		env->strict_alignment = true;
12647 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12648 		env->strict_alignment = false;
12649 
12650 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12651 	env->allow_uninit_stack = bpf_allow_uninit_stack();
12652 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12653 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
12654 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
12655 	env->bpf_capable = bpf_capable();
12656 
12657 	if (is_priv)
12658 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12659 
12660 	env->explored_states = kvcalloc(state_htab_size(env),
12661 				       sizeof(struct bpf_verifier_state_list *),
12662 				       GFP_USER);
12663 	ret = -ENOMEM;
12664 	if (!env->explored_states)
12665 		goto skip_full_check;
12666 
12667 	ret = check_subprogs(env);
12668 	if (ret < 0)
12669 		goto skip_full_check;
12670 
12671 	ret = check_btf_info(env, attr, uattr);
12672 	if (ret < 0)
12673 		goto skip_full_check;
12674 
12675 	ret = check_attach_btf_id(env);
12676 	if (ret)
12677 		goto skip_full_check;
12678 
12679 	ret = resolve_pseudo_ldimm64(env);
12680 	if (ret < 0)
12681 		goto skip_full_check;
12682 
12683 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
12684 		ret = bpf_prog_offload_verifier_prep(env->prog);
12685 		if (ret)
12686 			goto skip_full_check;
12687 	}
12688 
12689 	ret = check_cfg(env);
12690 	if (ret < 0)
12691 		goto skip_full_check;
12692 
12693 	ret = do_check_subprogs(env);
12694 	ret = ret ?: do_check_main(env);
12695 
12696 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12697 		ret = bpf_prog_offload_finalize(env);
12698 
12699 skip_full_check:
12700 	kvfree(env->explored_states);
12701 
12702 	if (ret == 0)
12703 		ret = check_max_stack_depth(env);
12704 
12705 	/* instruction rewrites happen after this point */
12706 	if (is_priv) {
12707 		if (ret == 0)
12708 			opt_hard_wire_dead_code_branches(env);
12709 		if (ret == 0)
12710 			ret = opt_remove_dead_code(env);
12711 		if (ret == 0)
12712 			ret = opt_remove_nops(env);
12713 	} else {
12714 		if (ret == 0)
12715 			sanitize_dead_code(env);
12716 	}
12717 
12718 	if (ret == 0)
12719 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12720 		ret = convert_ctx_accesses(env);
12721 
12722 	if (ret == 0)
12723 		ret = fixup_bpf_calls(env);
12724 
12725 	/* do 32-bit optimization after insn patching has done so those patched
12726 	 * insns could be handled correctly.
12727 	 */
12728 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12729 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12730 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12731 								     : false;
12732 	}
12733 
12734 	if (ret == 0)
12735 		ret = fixup_call_args(env);
12736 
12737 	env->verification_time = ktime_get_ns() - start_time;
12738 	print_verification_stats(env);
12739 
12740 	if (log->level && bpf_verifier_log_full(log))
12741 		ret = -ENOSPC;
12742 	if (log->level && !log->ubuf) {
12743 		ret = -EFAULT;
12744 		goto err_release_maps;
12745 	}
12746 
12747 	if (ret == 0 && env->used_map_cnt) {
12748 		/* if program passed verifier, update used_maps in bpf_prog_info */
12749 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12750 							  sizeof(env->used_maps[0]),
12751 							  GFP_KERNEL);
12752 
12753 		if (!env->prog->aux->used_maps) {
12754 			ret = -ENOMEM;
12755 			goto err_release_maps;
12756 		}
12757 
12758 		memcpy(env->prog->aux->used_maps, env->used_maps,
12759 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12760 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12761 
12762 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12763 		 * bpf_ld_imm64 instructions
12764 		 */
12765 		convert_pseudo_ld_imm64(env);
12766 	}
12767 
12768 	if (ret == 0)
12769 		adjust_btf_func(env);
12770 
12771 err_release_maps:
12772 	if (!env->prog->aux->used_maps)
12773 		/* if we didn't copy map pointers into bpf_prog_info, release
12774 		 * them now. Otherwise free_used_maps() will release them.
12775 		 */
12776 		release_maps(env);
12777 
12778 	/* extension progs temporarily inherit the attach_type of their targets
12779 	   for verification purposes, so set it back to zero before returning
12780 	 */
12781 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12782 		env->prog->expected_attach_type = 0;
12783 
12784 	*prog = env->prog;
12785 err_unlock:
12786 	if (!is_priv)
12787 		mutex_unlock(&bpf_verifier_lock);
12788 	vfree(env->insn_aux_data);
12789 err_free_env:
12790 	kfree(env);
12791 	return ret;
12792 }
12793