• 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 			s32 saved_subreg_def = reg->subreg_def;
8211 
8212 			copy_register_state(reg, known_reg);
8213 			reg->subreg_def = saved_subreg_def;
8214 		}
8215 	}));
8216 }
8217 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)8218 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8219 			     struct bpf_insn *insn, int *insn_idx)
8220 {
8221 	struct bpf_verifier_state *this_branch = env->cur_state;
8222 	struct bpf_verifier_state *other_branch;
8223 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8224 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8225 	u8 opcode = BPF_OP(insn->code);
8226 	bool is_jmp32;
8227 	int pred = -1;
8228 	int err;
8229 
8230 	/* Only conditional jumps are expected to reach here. */
8231 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8232 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8233 		return -EINVAL;
8234 	}
8235 
8236 	if (BPF_SRC(insn->code) == BPF_X) {
8237 		if (insn->imm != 0) {
8238 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8239 			return -EINVAL;
8240 		}
8241 
8242 		/* check src1 operand */
8243 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8244 		if (err)
8245 			return err;
8246 
8247 		if (is_pointer_value(env, insn->src_reg)) {
8248 			verbose(env, "R%d pointer comparison prohibited\n",
8249 				insn->src_reg);
8250 			return -EACCES;
8251 		}
8252 		src_reg = &regs[insn->src_reg];
8253 	} else {
8254 		if (insn->src_reg != BPF_REG_0) {
8255 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8256 			return -EINVAL;
8257 		}
8258 	}
8259 
8260 	/* check src2 operand */
8261 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8262 	if (err)
8263 		return err;
8264 
8265 	dst_reg = &regs[insn->dst_reg];
8266 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8267 
8268 	if (BPF_SRC(insn->code) == BPF_K) {
8269 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8270 	} else if (src_reg->type == SCALAR_VALUE &&
8271 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8272 		pred = is_branch_taken(dst_reg,
8273 				       tnum_subreg(src_reg->var_off).value,
8274 				       opcode,
8275 				       is_jmp32);
8276 	} else if (src_reg->type == SCALAR_VALUE &&
8277 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8278 		pred = is_branch_taken(dst_reg,
8279 				       src_reg->var_off.value,
8280 				       opcode,
8281 				       is_jmp32);
8282 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8283 		   reg_is_pkt_pointer_any(src_reg) &&
8284 		   !is_jmp32) {
8285 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8286 	}
8287 
8288 	if (pred >= 0) {
8289 		/* If we get here with a dst_reg pointer type it is because
8290 		 * above is_branch_taken() special cased the 0 comparison.
8291 		 */
8292 		if (!__is_pointer_value(false, dst_reg))
8293 			err = mark_chain_precision(env, insn->dst_reg);
8294 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8295 		    !__is_pointer_value(false, src_reg))
8296 			err = mark_chain_precision(env, insn->src_reg);
8297 		if (err)
8298 			return err;
8299 	}
8300 
8301 	if (pred == 1) {
8302 		/* Only follow the goto, ignore fall-through. If needed, push
8303 		 * the fall-through branch for simulation under speculative
8304 		 * execution.
8305 		 */
8306 		if (!env->bypass_spec_v1 &&
8307 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
8308 					       *insn_idx))
8309 			return -EFAULT;
8310 		*insn_idx += insn->off;
8311 		return 0;
8312 	} else if (pred == 0) {
8313 		/* Only follow the fall-through branch, since that's where the
8314 		 * program will go. If needed, push the goto branch for
8315 		 * simulation under speculative execution.
8316 		 */
8317 		if (!env->bypass_spec_v1 &&
8318 		    !sanitize_speculative_path(env, insn,
8319 					       *insn_idx + insn->off + 1,
8320 					       *insn_idx))
8321 			return -EFAULT;
8322 		return 0;
8323 	}
8324 
8325 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8326 				  false);
8327 	if (!other_branch)
8328 		return -EFAULT;
8329 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8330 
8331 	/* detect if we are comparing against a constant value so we can adjust
8332 	 * our min/max values for our dst register.
8333 	 * this is only legit if both are scalars (or pointers to the same
8334 	 * object, I suppose, but we don't support that right now), because
8335 	 * otherwise the different base pointers mean the offsets aren't
8336 	 * comparable.
8337 	 */
8338 	if (BPF_SRC(insn->code) == BPF_X) {
8339 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8340 
8341 		if (dst_reg->type == SCALAR_VALUE &&
8342 		    src_reg->type == SCALAR_VALUE) {
8343 			if (tnum_is_const(src_reg->var_off) ||
8344 			    (is_jmp32 &&
8345 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8346 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8347 						dst_reg,
8348 						src_reg->var_off.value,
8349 						tnum_subreg(src_reg->var_off).value,
8350 						opcode, is_jmp32);
8351 			else if (tnum_is_const(dst_reg->var_off) ||
8352 				 (is_jmp32 &&
8353 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8354 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8355 						    src_reg,
8356 						    dst_reg->var_off.value,
8357 						    tnum_subreg(dst_reg->var_off).value,
8358 						    opcode, is_jmp32);
8359 			else if (!is_jmp32 &&
8360 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8361 				/* Comparing for equality, we can combine knowledge */
8362 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8363 						    &other_branch_regs[insn->dst_reg],
8364 						    src_reg, dst_reg, opcode);
8365 			if (src_reg->id &&
8366 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8367 				find_equal_scalars(this_branch, src_reg);
8368 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8369 			}
8370 
8371 		}
8372 	} else if (dst_reg->type == SCALAR_VALUE) {
8373 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8374 					dst_reg, insn->imm, (u32)insn->imm,
8375 					opcode, is_jmp32);
8376 	}
8377 
8378 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8379 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8380 		find_equal_scalars(this_branch, dst_reg);
8381 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8382 	}
8383 
8384 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8385 	 * NOTE: these optimizations below are related with pointer comparison
8386 	 *       which will never be JMP32.
8387 	 */
8388 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8389 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8390 	    type_may_be_null(dst_reg->type)) {
8391 		/* Mark all identical registers in each branch as either
8392 		 * safe or unknown depending R == 0 or R != 0 conditional.
8393 		 */
8394 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8395 				      opcode == BPF_JNE);
8396 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8397 				      opcode == BPF_JEQ);
8398 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8399 					   this_branch, other_branch) &&
8400 		   is_pointer_value(env, insn->dst_reg)) {
8401 		verbose(env, "R%d pointer comparison prohibited\n",
8402 			insn->dst_reg);
8403 		return -EACCES;
8404 	}
8405 	if (env->log.level & BPF_LOG_LEVEL)
8406 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8407 	return 0;
8408 }
8409 
8410 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)8411 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8412 {
8413 	struct bpf_insn_aux_data *aux = cur_aux(env);
8414 	struct bpf_reg_state *regs = cur_regs(env);
8415 	struct bpf_reg_state *dst_reg;
8416 	struct bpf_map *map;
8417 	int err;
8418 
8419 	if (BPF_SIZE(insn->code) != BPF_DW) {
8420 		verbose(env, "invalid BPF_LD_IMM insn\n");
8421 		return -EINVAL;
8422 	}
8423 	if (insn->off != 0) {
8424 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8425 		return -EINVAL;
8426 	}
8427 
8428 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8429 	if (err)
8430 		return err;
8431 
8432 	dst_reg = &regs[insn->dst_reg];
8433 	if (insn->src_reg == 0) {
8434 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8435 
8436 		dst_reg->type = SCALAR_VALUE;
8437 		__mark_reg_known(&regs[insn->dst_reg], imm);
8438 		return 0;
8439 	}
8440 
8441 	/* All special src_reg cases are listed below. From this point onwards
8442 	 * we either succeed and assign a corresponding dst_reg->type after
8443 	 * zeroing the offset, or fail and reject the program.
8444 	 */
8445 	mark_reg_known_zero(env, regs, insn->dst_reg);
8446 
8447 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8448 		dst_reg->type = aux->btf_var.reg_type;
8449 		switch (base_type(dst_reg->type)) {
8450 		case PTR_TO_MEM:
8451 			dst_reg->mem_size = aux->btf_var.mem_size;
8452 			break;
8453 		case PTR_TO_BTF_ID:
8454 		case PTR_TO_PERCPU_BTF_ID:
8455 			dst_reg->btf_id = aux->btf_var.btf_id;
8456 			break;
8457 		default:
8458 			verbose(env, "bpf verifier is misconfigured\n");
8459 			return -EFAULT;
8460 		}
8461 		return 0;
8462 	}
8463 
8464 	map = env->used_maps[aux->map_index];
8465 	dst_reg->map_ptr = map;
8466 
8467 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8468 		dst_reg->type = PTR_TO_MAP_VALUE;
8469 		dst_reg->off = aux->map_off;
8470 		if (map_value_has_spin_lock(map))
8471 			dst_reg->id = ++env->id_gen;
8472 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8473 		dst_reg->type = CONST_PTR_TO_MAP;
8474 	} else {
8475 		verbose(env, "bpf verifier is misconfigured\n");
8476 		return -EINVAL;
8477 	}
8478 
8479 	return 0;
8480 }
8481 
may_access_skb(enum bpf_prog_type type)8482 static bool may_access_skb(enum bpf_prog_type type)
8483 {
8484 	switch (type) {
8485 	case BPF_PROG_TYPE_SOCKET_FILTER:
8486 	case BPF_PROG_TYPE_SCHED_CLS:
8487 	case BPF_PROG_TYPE_SCHED_ACT:
8488 		return true;
8489 	default:
8490 		return false;
8491 	}
8492 }
8493 
8494 /* verify safety of LD_ABS|LD_IND instructions:
8495  * - they can only appear in the programs where ctx == skb
8496  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8497  *   preserve R6-R9, and store return value into R0
8498  *
8499  * Implicit input:
8500  *   ctx == skb == R6 == CTX
8501  *
8502  * Explicit input:
8503  *   SRC == any register
8504  *   IMM == 32-bit immediate
8505  *
8506  * Output:
8507  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8508  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)8509 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8510 {
8511 	struct bpf_reg_state *regs = cur_regs(env);
8512 	static const int ctx_reg = BPF_REG_6;
8513 	u8 mode = BPF_MODE(insn->code);
8514 	int i, err;
8515 
8516 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8517 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8518 		return -EINVAL;
8519 	}
8520 
8521 	if (!env->ops->gen_ld_abs) {
8522 		verbose(env, "bpf verifier is misconfigured\n");
8523 		return -EINVAL;
8524 	}
8525 
8526 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8527 	    BPF_SIZE(insn->code) == BPF_DW ||
8528 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8529 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8530 		return -EINVAL;
8531 	}
8532 
8533 	/* check whether implicit source operand (register R6) is readable */
8534 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8535 	if (err)
8536 		return err;
8537 
8538 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8539 	 * gen_ld_abs() may terminate the program at runtime, leading to
8540 	 * reference leak.
8541 	 */
8542 	err = check_reference_leak(env);
8543 	if (err) {
8544 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8545 		return err;
8546 	}
8547 
8548 	if (env->cur_state->active_spin_lock) {
8549 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8550 		return -EINVAL;
8551 	}
8552 
8553 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8554 		verbose(env,
8555 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8556 		return -EINVAL;
8557 	}
8558 
8559 	if (mode == BPF_IND) {
8560 		/* check explicit source operand */
8561 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8562 		if (err)
8563 			return err;
8564 	}
8565 
8566 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
8567 	if (err < 0)
8568 		return err;
8569 
8570 	/* reset caller saved regs to unreadable */
8571 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8572 		mark_reg_not_init(env, regs, caller_saved[i]);
8573 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8574 	}
8575 
8576 	/* mark destination R0 register as readable, since it contains
8577 	 * the value fetched from the packet.
8578 	 * Already marked as written above.
8579 	 */
8580 	mark_reg_unknown(env, regs, BPF_REG_0);
8581 	/* ld_abs load up to 32-bit skb data. */
8582 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8583 	return 0;
8584 }
8585 
check_return_code(struct bpf_verifier_env * env)8586 static int check_return_code(struct bpf_verifier_env *env)
8587 {
8588 	struct tnum enforce_attach_type_range = tnum_unknown;
8589 	const struct bpf_prog *prog = env->prog;
8590 	struct bpf_reg_state *reg;
8591 	struct tnum range = tnum_range(0, 1);
8592 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8593 	int err;
8594 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8595 
8596 	/* LSM and struct_ops func-ptr's return type could be "void" */
8597 	if (!is_subprog &&
8598 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8599 	     prog_type == BPF_PROG_TYPE_LSM) &&
8600 	    !prog->aux->attach_func_proto->type)
8601 		return 0;
8602 
8603 	/* eBPF calling convetion is such that R0 is used
8604 	 * to return the value from eBPF program.
8605 	 * Make sure that it's readable at this time
8606 	 * of bpf_exit, which means that program wrote
8607 	 * something into it earlier
8608 	 */
8609 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8610 	if (err)
8611 		return err;
8612 
8613 	if (is_pointer_value(env, BPF_REG_0)) {
8614 		verbose(env, "R0 leaks addr as return value\n");
8615 		return -EACCES;
8616 	}
8617 
8618 	reg = cur_regs(env) + BPF_REG_0;
8619 	if (is_subprog) {
8620 		if (reg->type != SCALAR_VALUE) {
8621 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8622 				reg_type_str(env, reg->type));
8623 			return -EINVAL;
8624 		}
8625 		return 0;
8626 	}
8627 
8628 	switch (prog_type) {
8629 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8630 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8631 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8632 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8633 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8634 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8635 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8636 			range = tnum_range(1, 1);
8637 		break;
8638 	case BPF_PROG_TYPE_CGROUP_SKB:
8639 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8640 			range = tnum_range(0, 3);
8641 			enforce_attach_type_range = tnum_range(2, 3);
8642 		}
8643 		break;
8644 	case BPF_PROG_TYPE_CGROUP_SOCK:
8645 	case BPF_PROG_TYPE_SOCK_OPS:
8646 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8647 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8648 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8649 		break;
8650 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8651 		if (!env->prog->aux->attach_btf_id)
8652 			return 0;
8653 		range = tnum_const(0);
8654 		break;
8655 	case BPF_PROG_TYPE_TRACING:
8656 		switch (env->prog->expected_attach_type) {
8657 		case BPF_TRACE_FENTRY:
8658 		case BPF_TRACE_FEXIT:
8659 			range = tnum_const(0);
8660 			break;
8661 		case BPF_TRACE_RAW_TP:
8662 		case BPF_MODIFY_RETURN:
8663 			return 0;
8664 		case BPF_TRACE_ITER:
8665 			break;
8666 		default:
8667 			return -ENOTSUPP;
8668 		}
8669 		break;
8670 	case BPF_PROG_TYPE_SK_LOOKUP:
8671 		range = tnum_range(SK_DROP, SK_PASS);
8672 		break;
8673 	case BPF_PROG_TYPE_EXT:
8674 		/* freplace program can return anything as its return value
8675 		 * depends on the to-be-replaced kernel func or bpf program.
8676 		 */
8677 	default:
8678 		return 0;
8679 	}
8680 
8681 	if (reg->type != SCALAR_VALUE) {
8682 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8683 			reg_type_str(env, reg->type));
8684 		return -EINVAL;
8685 	}
8686 
8687 	if (!tnum_in(range, reg->var_off)) {
8688 		char tn_buf[48];
8689 
8690 		verbose(env, "At program exit the register R0 ");
8691 		if (!tnum_is_unknown(reg->var_off)) {
8692 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8693 			verbose(env, "has value %s", tn_buf);
8694 		} else {
8695 			verbose(env, "has unknown scalar value");
8696 		}
8697 		tnum_strn(tn_buf, sizeof(tn_buf), range);
8698 		verbose(env, " should have been in %s\n", tn_buf);
8699 		return -EINVAL;
8700 	}
8701 
8702 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8703 	    tnum_in(enforce_attach_type_range, reg->var_off))
8704 		env->prog->enforce_expected_attach_type = 1;
8705 	return 0;
8706 }
8707 
8708 /* non-recursive DFS pseudo code
8709  * 1  procedure DFS-iterative(G,v):
8710  * 2      label v as discovered
8711  * 3      let S be a stack
8712  * 4      S.push(v)
8713  * 5      while S is not empty
8714  * 6            t <- S.pop()
8715  * 7            if t is what we're looking for:
8716  * 8                return t
8717  * 9            for all edges e in G.adjacentEdges(t) do
8718  * 10               if edge e is already labelled
8719  * 11                   continue with the next edge
8720  * 12               w <- G.adjacentVertex(t,e)
8721  * 13               if vertex w is not discovered and not explored
8722  * 14                   label e as tree-edge
8723  * 15                   label w as discovered
8724  * 16                   S.push(w)
8725  * 17                   continue at 5
8726  * 18               else if vertex w is discovered
8727  * 19                   label e as back-edge
8728  * 20               else
8729  * 21                   // vertex w is explored
8730  * 22                   label e as forward- or cross-edge
8731  * 23           label t as explored
8732  * 24           S.pop()
8733  *
8734  * convention:
8735  * 0x10 - discovered
8736  * 0x11 - discovered and fall-through edge labelled
8737  * 0x12 - discovered and fall-through and branch edges labelled
8738  * 0x20 - explored
8739  */
8740 
8741 enum {
8742 	DISCOVERED = 0x10,
8743 	EXPLORED = 0x20,
8744 	FALLTHROUGH = 1,
8745 	BRANCH = 2,
8746 };
8747 
state_htab_size(struct bpf_verifier_env * env)8748 static u32 state_htab_size(struct bpf_verifier_env *env)
8749 {
8750 	return env->prog->len;
8751 }
8752 
explored_state(struct bpf_verifier_env * env,int idx)8753 static struct bpf_verifier_state_list **explored_state(
8754 					struct bpf_verifier_env *env,
8755 					int idx)
8756 {
8757 	struct bpf_verifier_state *cur = env->cur_state;
8758 	struct bpf_func_state *state = cur->frame[cur->curframe];
8759 
8760 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8761 }
8762 
init_explored_state(struct bpf_verifier_env * env,int idx)8763 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8764 {
8765 	env->insn_aux_data[idx].prune_point = true;
8766 }
8767 
8768 /* t, w, e - match pseudo-code above:
8769  * t - index of current instruction
8770  * w - next instruction
8771  * e - edge
8772  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)8773 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8774 		     bool loop_ok)
8775 {
8776 	int *insn_stack = env->cfg.insn_stack;
8777 	int *insn_state = env->cfg.insn_state;
8778 
8779 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8780 		return 0;
8781 
8782 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8783 		return 0;
8784 
8785 	if (w < 0 || w >= env->prog->len) {
8786 		verbose_linfo(env, t, "%d: ", t);
8787 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8788 		return -EINVAL;
8789 	}
8790 
8791 	if (e == BRANCH)
8792 		/* mark branch target for state pruning */
8793 		init_explored_state(env, w);
8794 
8795 	if (insn_state[w] == 0) {
8796 		/* tree-edge */
8797 		insn_state[t] = DISCOVERED | e;
8798 		insn_state[w] = DISCOVERED;
8799 		if (env->cfg.cur_stack >= env->prog->len)
8800 			return -E2BIG;
8801 		insn_stack[env->cfg.cur_stack++] = w;
8802 		return 1;
8803 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8804 		if (loop_ok && env->bpf_capable)
8805 			return 0;
8806 		verbose_linfo(env, t, "%d: ", t);
8807 		verbose_linfo(env, w, "%d: ", w);
8808 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8809 		return -EINVAL;
8810 	} else if (insn_state[w] == EXPLORED) {
8811 		/* forward- or cross-edge */
8812 		insn_state[t] = DISCOVERED | e;
8813 	} else {
8814 		verbose(env, "insn state internal bug\n");
8815 		return -EFAULT;
8816 	}
8817 	return 0;
8818 }
8819 
8820 /* non-recursive depth-first-search to detect loops in BPF program
8821  * loop == back-edge in directed graph
8822  */
check_cfg(struct bpf_verifier_env * env)8823 static int check_cfg(struct bpf_verifier_env *env)
8824 {
8825 	struct bpf_insn *insns = env->prog->insnsi;
8826 	int insn_cnt = env->prog->len;
8827 	int *insn_stack, *insn_state;
8828 	int ret = 0;
8829 	int i, t;
8830 
8831 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8832 	if (!insn_state)
8833 		return -ENOMEM;
8834 
8835 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8836 	if (!insn_stack) {
8837 		kvfree(insn_state);
8838 		return -ENOMEM;
8839 	}
8840 
8841 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8842 	insn_stack[0] = 0; /* 0 is the first instruction */
8843 	env->cfg.cur_stack = 1;
8844 
8845 peek_stack:
8846 	if (env->cfg.cur_stack == 0)
8847 		goto check_state;
8848 	t = insn_stack[env->cfg.cur_stack - 1];
8849 
8850 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8851 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
8852 		u8 opcode = BPF_OP(insns[t].code);
8853 
8854 		if (opcode == BPF_EXIT) {
8855 			goto mark_explored;
8856 		} else if (opcode == BPF_CALL) {
8857 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8858 			if (ret == 1)
8859 				goto peek_stack;
8860 			else if (ret < 0)
8861 				goto err_free;
8862 			if (t + 1 < insn_cnt)
8863 				init_explored_state(env, t + 1);
8864 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8865 				init_explored_state(env, t);
8866 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8867 						env, false);
8868 				if (ret == 1)
8869 					goto peek_stack;
8870 				else if (ret < 0)
8871 					goto err_free;
8872 			}
8873 		} else if (opcode == BPF_JA) {
8874 			if (BPF_SRC(insns[t].code) != BPF_K) {
8875 				ret = -EINVAL;
8876 				goto err_free;
8877 			}
8878 			/* unconditional jump with single edge */
8879 			ret = push_insn(t, t + insns[t].off + 1,
8880 					FALLTHROUGH, env, true);
8881 			if (ret == 1)
8882 				goto peek_stack;
8883 			else if (ret < 0)
8884 				goto err_free;
8885 			/* unconditional jmp is not a good pruning point,
8886 			 * but it's marked, since backtracking needs
8887 			 * to record jmp history in is_state_visited().
8888 			 */
8889 			init_explored_state(env, t + insns[t].off + 1);
8890 			/* tell verifier to check for equivalent states
8891 			 * after every call and jump
8892 			 */
8893 			if (t + 1 < insn_cnt)
8894 				init_explored_state(env, t + 1);
8895 		} else {
8896 			/* conditional jump with two edges */
8897 			init_explored_state(env, t);
8898 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8899 			if (ret == 1)
8900 				goto peek_stack;
8901 			else if (ret < 0)
8902 				goto err_free;
8903 
8904 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8905 			if (ret == 1)
8906 				goto peek_stack;
8907 			else if (ret < 0)
8908 				goto err_free;
8909 		}
8910 	} else {
8911 		/* all other non-branch instructions with single
8912 		 * fall-through edge
8913 		 */
8914 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8915 		if (ret == 1)
8916 			goto peek_stack;
8917 		else if (ret < 0)
8918 			goto err_free;
8919 	}
8920 
8921 mark_explored:
8922 	insn_state[t] = EXPLORED;
8923 	if (env->cfg.cur_stack-- <= 0) {
8924 		verbose(env, "pop stack internal bug\n");
8925 		ret = -EFAULT;
8926 		goto err_free;
8927 	}
8928 	goto peek_stack;
8929 
8930 check_state:
8931 	for (i = 0; i < insn_cnt; i++) {
8932 		if (insn_state[i] != EXPLORED) {
8933 			verbose(env, "unreachable insn %d\n", i);
8934 			ret = -EINVAL;
8935 			goto err_free;
8936 		}
8937 	}
8938 	ret = 0; /* cfg looks good */
8939 
8940 err_free:
8941 	kvfree(insn_state);
8942 	kvfree(insn_stack);
8943 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8944 	return ret;
8945 }
8946 
check_abnormal_return(struct bpf_verifier_env * env)8947 static int check_abnormal_return(struct bpf_verifier_env *env)
8948 {
8949 	int i;
8950 
8951 	for (i = 1; i < env->subprog_cnt; i++) {
8952 		if (env->subprog_info[i].has_ld_abs) {
8953 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8954 			return -EINVAL;
8955 		}
8956 		if (env->subprog_info[i].has_tail_call) {
8957 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8958 			return -EINVAL;
8959 		}
8960 	}
8961 	return 0;
8962 }
8963 
8964 /* The minimum supported BTF func info size */
8965 #define MIN_BPF_FUNCINFO_SIZE	8
8966 #define MAX_FUNCINFO_REC_SIZE	252
8967 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8968 static int check_btf_func(struct bpf_verifier_env *env,
8969 			  const union bpf_attr *attr,
8970 			  union bpf_attr __user *uattr)
8971 {
8972 	const struct btf_type *type, *func_proto, *ret_type;
8973 	u32 i, nfuncs, urec_size, min_size;
8974 	u32 krec_size = sizeof(struct bpf_func_info);
8975 	struct bpf_func_info *krecord;
8976 	struct bpf_func_info_aux *info_aux = NULL;
8977 	struct bpf_prog *prog;
8978 	const struct btf *btf;
8979 	void __user *urecord;
8980 	u32 prev_offset = 0;
8981 	bool scalar_return;
8982 	int ret = -ENOMEM;
8983 
8984 	nfuncs = attr->func_info_cnt;
8985 	if (!nfuncs) {
8986 		if (check_abnormal_return(env))
8987 			return -EINVAL;
8988 		return 0;
8989 	}
8990 
8991 	if (nfuncs != env->subprog_cnt) {
8992 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8993 		return -EINVAL;
8994 	}
8995 
8996 	urec_size = attr->func_info_rec_size;
8997 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8998 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
8999 	    urec_size % sizeof(u32)) {
9000 		verbose(env, "invalid func info rec size %u\n", urec_size);
9001 		return -EINVAL;
9002 	}
9003 
9004 	prog = env->prog;
9005 	btf = prog->aux->btf;
9006 
9007 	urecord = u64_to_user_ptr(attr->func_info);
9008 	min_size = min_t(u32, krec_size, urec_size);
9009 
9010 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9011 	if (!krecord)
9012 		return -ENOMEM;
9013 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9014 	if (!info_aux)
9015 		goto err_free;
9016 
9017 	for (i = 0; i < nfuncs; i++) {
9018 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9019 		if (ret) {
9020 			if (ret == -E2BIG) {
9021 				verbose(env, "nonzero tailing record in func info");
9022 				/* set the size kernel expects so loader can zero
9023 				 * out the rest of the record.
9024 				 */
9025 				if (put_user(min_size, &uattr->func_info_rec_size))
9026 					ret = -EFAULT;
9027 			}
9028 			goto err_free;
9029 		}
9030 
9031 		if (copy_from_user(&krecord[i], urecord, min_size)) {
9032 			ret = -EFAULT;
9033 			goto err_free;
9034 		}
9035 
9036 		/* check insn_off */
9037 		ret = -EINVAL;
9038 		if (i == 0) {
9039 			if (krecord[i].insn_off) {
9040 				verbose(env,
9041 					"nonzero insn_off %u for the first func info record",
9042 					krecord[i].insn_off);
9043 				goto err_free;
9044 			}
9045 		} else if (krecord[i].insn_off <= prev_offset) {
9046 			verbose(env,
9047 				"same or smaller insn offset (%u) than previous func info record (%u)",
9048 				krecord[i].insn_off, prev_offset);
9049 			goto err_free;
9050 		}
9051 
9052 		if (env->subprog_info[i].start != krecord[i].insn_off) {
9053 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9054 			goto err_free;
9055 		}
9056 
9057 		/* check type_id */
9058 		type = btf_type_by_id(btf, krecord[i].type_id);
9059 		if (!type || !btf_type_is_func(type)) {
9060 			verbose(env, "invalid type id %d in func info",
9061 				krecord[i].type_id);
9062 			goto err_free;
9063 		}
9064 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9065 
9066 		func_proto = btf_type_by_id(btf, type->type);
9067 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9068 			/* btf_func_check() already verified it during BTF load */
9069 			goto err_free;
9070 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9071 		scalar_return =
9072 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9073 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9074 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9075 			goto err_free;
9076 		}
9077 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9078 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9079 			goto err_free;
9080 		}
9081 
9082 		prev_offset = krecord[i].insn_off;
9083 		urecord += urec_size;
9084 	}
9085 
9086 	prog->aux->func_info = krecord;
9087 	prog->aux->func_info_cnt = nfuncs;
9088 	prog->aux->func_info_aux = info_aux;
9089 	return 0;
9090 
9091 err_free:
9092 	kvfree(krecord);
9093 	kfree(info_aux);
9094 	return ret;
9095 }
9096 
adjust_btf_func(struct bpf_verifier_env * env)9097 static void adjust_btf_func(struct bpf_verifier_env *env)
9098 {
9099 	struct bpf_prog_aux *aux = env->prog->aux;
9100 	int i;
9101 
9102 	if (!aux->func_info)
9103 		return;
9104 
9105 	for (i = 0; i < env->subprog_cnt; i++)
9106 		aux->func_info[i].insn_off = env->subprog_info[i].start;
9107 }
9108 
9109 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
9110 		sizeof(((struct bpf_line_info *)(0))->line_col))
9111 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
9112 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9113 static int check_btf_line(struct bpf_verifier_env *env,
9114 			  const union bpf_attr *attr,
9115 			  union bpf_attr __user *uattr)
9116 {
9117 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9118 	struct bpf_subprog_info *sub;
9119 	struct bpf_line_info *linfo;
9120 	struct bpf_prog *prog;
9121 	const struct btf *btf;
9122 	void __user *ulinfo;
9123 	int err;
9124 
9125 	nr_linfo = attr->line_info_cnt;
9126 	if (!nr_linfo)
9127 		return 0;
9128 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9129 		return -EINVAL;
9130 
9131 	rec_size = attr->line_info_rec_size;
9132 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9133 	    rec_size > MAX_LINEINFO_REC_SIZE ||
9134 	    rec_size & (sizeof(u32) - 1))
9135 		return -EINVAL;
9136 
9137 	/* Need to zero it in case the userspace may
9138 	 * pass in a smaller bpf_line_info object.
9139 	 */
9140 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9141 			 GFP_KERNEL | __GFP_NOWARN);
9142 	if (!linfo)
9143 		return -ENOMEM;
9144 
9145 	prog = env->prog;
9146 	btf = prog->aux->btf;
9147 
9148 	s = 0;
9149 	sub = env->subprog_info;
9150 	ulinfo = u64_to_user_ptr(attr->line_info);
9151 	expected_size = sizeof(struct bpf_line_info);
9152 	ncopy = min_t(u32, expected_size, rec_size);
9153 	for (i = 0; i < nr_linfo; i++) {
9154 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9155 		if (err) {
9156 			if (err == -E2BIG) {
9157 				verbose(env, "nonzero tailing record in line_info");
9158 				if (put_user(expected_size,
9159 					     &uattr->line_info_rec_size))
9160 					err = -EFAULT;
9161 			}
9162 			goto err_free;
9163 		}
9164 
9165 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9166 			err = -EFAULT;
9167 			goto err_free;
9168 		}
9169 
9170 		/*
9171 		 * Check insn_off to ensure
9172 		 * 1) strictly increasing AND
9173 		 * 2) bounded by prog->len
9174 		 *
9175 		 * The linfo[0].insn_off == 0 check logically falls into
9176 		 * the later "missing bpf_line_info for func..." case
9177 		 * because the first linfo[0].insn_off must be the
9178 		 * first sub also and the first sub must have
9179 		 * subprog_info[0].start == 0.
9180 		 */
9181 		if ((i && linfo[i].insn_off <= prev_offset) ||
9182 		    linfo[i].insn_off >= prog->len) {
9183 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9184 				i, linfo[i].insn_off, prev_offset,
9185 				prog->len);
9186 			err = -EINVAL;
9187 			goto err_free;
9188 		}
9189 
9190 		if (!prog->insnsi[linfo[i].insn_off].code) {
9191 			verbose(env,
9192 				"Invalid insn code at line_info[%u].insn_off\n",
9193 				i);
9194 			err = -EINVAL;
9195 			goto err_free;
9196 		}
9197 
9198 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9199 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9200 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9201 			err = -EINVAL;
9202 			goto err_free;
9203 		}
9204 
9205 		if (s != env->subprog_cnt) {
9206 			if (linfo[i].insn_off == sub[s].start) {
9207 				sub[s].linfo_idx = i;
9208 				s++;
9209 			} else if (sub[s].start < linfo[i].insn_off) {
9210 				verbose(env, "missing bpf_line_info for func#%u\n", s);
9211 				err = -EINVAL;
9212 				goto err_free;
9213 			}
9214 		}
9215 
9216 		prev_offset = linfo[i].insn_off;
9217 		ulinfo += rec_size;
9218 	}
9219 
9220 	if (s != env->subprog_cnt) {
9221 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9222 			env->subprog_cnt - s, s);
9223 		err = -EINVAL;
9224 		goto err_free;
9225 	}
9226 
9227 	prog->aux->linfo = linfo;
9228 	prog->aux->nr_linfo = nr_linfo;
9229 
9230 	return 0;
9231 
9232 err_free:
9233 	kvfree(linfo);
9234 	return err;
9235 }
9236 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9237 static int check_btf_info(struct bpf_verifier_env *env,
9238 			  const union bpf_attr *attr,
9239 			  union bpf_attr __user *uattr)
9240 {
9241 	struct btf *btf;
9242 	int err;
9243 
9244 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9245 		if (check_abnormal_return(env))
9246 			return -EINVAL;
9247 		return 0;
9248 	}
9249 
9250 	btf = btf_get_by_fd(attr->prog_btf_fd);
9251 	if (IS_ERR(btf))
9252 		return PTR_ERR(btf);
9253 	env->prog->aux->btf = btf;
9254 
9255 	err = check_btf_func(env, attr, uattr);
9256 	if (err)
9257 		return err;
9258 
9259 	err = check_btf_line(env, attr, uattr);
9260 	if (err)
9261 		return err;
9262 
9263 	return 0;
9264 }
9265 
9266 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)9267 static bool range_within(struct bpf_reg_state *old,
9268 			 struct bpf_reg_state *cur)
9269 {
9270 	return old->umin_value <= cur->umin_value &&
9271 	       old->umax_value >= cur->umax_value &&
9272 	       old->smin_value <= cur->smin_value &&
9273 	       old->smax_value >= cur->smax_value &&
9274 	       old->u32_min_value <= cur->u32_min_value &&
9275 	       old->u32_max_value >= cur->u32_max_value &&
9276 	       old->s32_min_value <= cur->s32_min_value &&
9277 	       old->s32_max_value >= cur->s32_max_value;
9278 }
9279 
9280 /* If in the old state two registers had the same id, then they need to have
9281  * the same id in the new state as well.  But that id could be different from
9282  * the old state, so we need to track the mapping from old to new ids.
9283  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9284  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9285  * regs with a different old id could still have new id 9, we don't care about
9286  * that.
9287  * So we look through our idmap to see if this old id has been seen before.  If
9288  * so, we require the new id to match; otherwise, we add the id pair to the map.
9289  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)9290 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9291 {
9292 	unsigned int i;
9293 
9294 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9295 		if (!idmap[i].old) {
9296 			/* Reached an empty slot; haven't seen this id before */
9297 			idmap[i].old = old_id;
9298 			idmap[i].cur = cur_id;
9299 			return true;
9300 		}
9301 		if (idmap[i].old == old_id)
9302 			return idmap[i].cur == cur_id;
9303 	}
9304 	/* We ran out of idmap slots, which should be impossible */
9305 	WARN_ON_ONCE(1);
9306 	return false;
9307 }
9308 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)9309 static void clean_func_state(struct bpf_verifier_env *env,
9310 			     struct bpf_func_state *st)
9311 {
9312 	enum bpf_reg_liveness live;
9313 	int i, j;
9314 
9315 	for (i = 0; i < BPF_REG_FP; i++) {
9316 		live = st->regs[i].live;
9317 		/* liveness must not touch this register anymore */
9318 		st->regs[i].live |= REG_LIVE_DONE;
9319 		if (!(live & REG_LIVE_READ))
9320 			/* since the register is unused, clear its state
9321 			 * to make further comparison simpler
9322 			 */
9323 			__mark_reg_not_init(env, &st->regs[i]);
9324 	}
9325 
9326 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9327 		live = st->stack[i].spilled_ptr.live;
9328 		/* liveness must not touch this stack slot anymore */
9329 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9330 		if (!(live & REG_LIVE_READ)) {
9331 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9332 			for (j = 0; j < BPF_REG_SIZE; j++)
9333 				st->stack[i].slot_type[j] = STACK_INVALID;
9334 		}
9335 	}
9336 }
9337 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)9338 static void clean_verifier_state(struct bpf_verifier_env *env,
9339 				 struct bpf_verifier_state *st)
9340 {
9341 	int i;
9342 
9343 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9344 		/* all regs in this state in all frames were already marked */
9345 		return;
9346 
9347 	for (i = 0; i <= st->curframe; i++)
9348 		clean_func_state(env, st->frame[i]);
9349 }
9350 
9351 /* the parentage chains form a tree.
9352  * the verifier states are added to state lists at given insn and
9353  * pushed into state stack for future exploration.
9354  * when the verifier reaches bpf_exit insn some of the verifer states
9355  * stored in the state lists have their final liveness state already,
9356  * but a lot of states will get revised from liveness point of view when
9357  * the verifier explores other branches.
9358  * Example:
9359  * 1: r0 = 1
9360  * 2: if r1 == 100 goto pc+1
9361  * 3: r0 = 2
9362  * 4: exit
9363  * when the verifier reaches exit insn the register r0 in the state list of
9364  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9365  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9366  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9367  *
9368  * Since the verifier pushes the branch states as it sees them while exploring
9369  * the program the condition of walking the branch instruction for the second
9370  * time means that all states below this branch were already explored and
9371  * their final liveness markes are already propagated.
9372  * Hence when the verifier completes the search of state list in is_state_visited()
9373  * we can call this clean_live_states() function to mark all liveness states
9374  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9375  * will not be used.
9376  * This function also clears the registers and stack for states that !READ
9377  * to simplify state merging.
9378  *
9379  * Important note here that walking the same branch instruction in the callee
9380  * doesn't meant that the states are DONE. The verifier has to compare
9381  * the callsites
9382  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)9383 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9384 			      struct bpf_verifier_state *cur)
9385 {
9386 	struct bpf_verifier_state_list *sl;
9387 	int i;
9388 
9389 	sl = *explored_state(env, insn);
9390 	while (sl) {
9391 		if (sl->state.branches)
9392 			goto next;
9393 		if (sl->state.insn_idx != insn ||
9394 		    sl->state.curframe != cur->curframe)
9395 			goto next;
9396 		for (i = 0; i <= cur->curframe; i++)
9397 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9398 				goto next;
9399 		clean_verifier_state(env, &sl->state);
9400 next:
9401 		sl = sl->next;
9402 	}
9403 }
9404 
9405 /* 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)9406 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9407 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9408 {
9409 	bool equal;
9410 
9411 	if (!(rold->live & REG_LIVE_READ))
9412 		/* explored state didn't use this */
9413 		return true;
9414 
9415 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9416 
9417 	if (rold->type == PTR_TO_STACK)
9418 		/* two stack pointers are equal only if they're pointing to
9419 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9420 		 */
9421 		return equal && rold->frameno == rcur->frameno;
9422 
9423 	if (equal)
9424 		return true;
9425 
9426 	if (rold->type == NOT_INIT)
9427 		/* explored state can't have used this */
9428 		return true;
9429 	if (rcur->type == NOT_INIT)
9430 		return false;
9431 	switch (base_type(rold->type)) {
9432 	case SCALAR_VALUE:
9433 		if (env->explore_alu_limits)
9434 			return false;
9435 		if (rcur->type == SCALAR_VALUE) {
9436 			if (!rold->precise)
9437 				return true;
9438 			/* new val must satisfy old val knowledge */
9439 			return range_within(rold, rcur) &&
9440 			       tnum_in(rold->var_off, rcur->var_off);
9441 		} else {
9442 			/* We're trying to use a pointer in place of a scalar.
9443 			 * Even if the scalar was unbounded, this could lead to
9444 			 * pointer leaks because scalars are allowed to leak
9445 			 * while pointers are not. We could make this safe in
9446 			 * special cases if root is calling us, but it's
9447 			 * probably not worth the hassle.
9448 			 */
9449 			return false;
9450 		}
9451 	case PTR_TO_MAP_VALUE:
9452 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9453 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9454 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9455 		 * checked, doing so could have affected others with the same
9456 		 * id, and we can't check for that because we lost the id when
9457 		 * we converted to a PTR_TO_MAP_VALUE.
9458 		 */
9459 		if (type_may_be_null(rold->type)) {
9460 			if (!type_may_be_null(rcur->type))
9461 				return false;
9462 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9463 				return false;
9464 			/* Check our ids match any regs they're supposed to */
9465 			return check_ids(rold->id, rcur->id, idmap);
9466 		}
9467 
9468 		/* If the new min/max/var_off satisfy the old ones and
9469 		 * everything else matches, we are OK.
9470 		 * 'id' is not compared, since it's only used for maps with
9471 		 * bpf_spin_lock inside map element and in such cases if
9472 		 * the rest of the prog is valid for one map element then
9473 		 * it's valid for all map elements regardless of the key
9474 		 * used in bpf_map_lookup()
9475 		 */
9476 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9477 		       range_within(rold, rcur) &&
9478 		       tnum_in(rold->var_off, rcur->var_off);
9479 	case PTR_TO_PACKET_META:
9480 	case PTR_TO_PACKET:
9481 		if (rcur->type != rold->type)
9482 			return false;
9483 		/* We must have at least as much range as the old ptr
9484 		 * did, so that any accesses which were safe before are
9485 		 * still safe.  This is true even if old range < old off,
9486 		 * since someone could have accessed through (ptr - k), or
9487 		 * even done ptr -= k in a register, to get a safe access.
9488 		 */
9489 		if (rold->range > rcur->range)
9490 			return false;
9491 		/* If the offsets don't match, we can't trust our alignment;
9492 		 * nor can we be sure that we won't fall out of range.
9493 		 */
9494 		if (rold->off != rcur->off)
9495 			return false;
9496 		/* id relations must be preserved */
9497 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9498 			return false;
9499 		/* new val must satisfy old val knowledge */
9500 		return range_within(rold, rcur) &&
9501 		       tnum_in(rold->var_off, rcur->var_off);
9502 	case PTR_TO_CTX:
9503 	case CONST_PTR_TO_MAP:
9504 	case PTR_TO_PACKET_END:
9505 	case PTR_TO_FLOW_KEYS:
9506 	case PTR_TO_SOCKET:
9507 	case PTR_TO_SOCK_COMMON:
9508 	case PTR_TO_TCP_SOCK:
9509 	case PTR_TO_XDP_SOCK:
9510 		/* Only valid matches are exact, which memcmp() above
9511 		 * would have accepted
9512 		 */
9513 	default:
9514 		/* Don't know what's going on, just say it's not safe */
9515 		return false;
9516 	}
9517 
9518 	/* Shouldn't get here; if we do, say it's not safe */
9519 	WARN_ON_ONCE(1);
9520 	return false;
9521 }
9522 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)9523 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9524 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9525 {
9526 	int i, spi;
9527 
9528 	/* walk slots of the explored stack and ignore any additional
9529 	 * slots in the current stack, since explored(safe) state
9530 	 * didn't use them
9531 	 */
9532 	for (i = 0; i < old->allocated_stack; i++) {
9533 		spi = i / BPF_REG_SIZE;
9534 
9535 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9536 			i += BPF_REG_SIZE - 1;
9537 			/* explored state didn't use this */
9538 			continue;
9539 		}
9540 
9541 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9542 			continue;
9543 
9544 		/* explored stack has more populated slots than current stack
9545 		 * and these slots were used
9546 		 */
9547 		if (i >= cur->allocated_stack)
9548 			return false;
9549 
9550 		/* if old state was safe with misc data in the stack
9551 		 * it will be safe with zero-initialized stack.
9552 		 * The opposite is not true
9553 		 */
9554 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9555 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9556 			continue;
9557 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9558 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9559 			/* Ex: old explored (safe) state has STACK_SPILL in
9560 			 * this stack slot, but current has STACK_MISC ->
9561 			 * this verifier states are not equivalent,
9562 			 * return false to continue verification of this path
9563 			 */
9564 			return false;
9565 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9566 			continue;
9567 		if (!is_spilled_reg(&old->stack[spi]))
9568 			continue;
9569 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
9570 			     &cur->stack[spi].spilled_ptr, idmap))
9571 			/* when explored and current stack slot are both storing
9572 			 * spilled registers, check that stored pointers types
9573 			 * are the same as well.
9574 			 * Ex: explored safe path could have stored
9575 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9576 			 * but current path has stored:
9577 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9578 			 * such verifier states are not equivalent.
9579 			 * return false to continue verification of this path
9580 			 */
9581 			return false;
9582 	}
9583 	return true;
9584 }
9585 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)9586 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9587 {
9588 	if (old->acquired_refs != cur->acquired_refs)
9589 		return false;
9590 	return !memcmp(old->refs, cur->refs,
9591 		       sizeof(*old->refs) * old->acquired_refs);
9592 }
9593 
9594 /* compare two verifier states
9595  *
9596  * all states stored in state_list are known to be valid, since
9597  * verifier reached 'bpf_exit' instruction through them
9598  *
9599  * this function is called when verifier exploring different branches of
9600  * execution popped from the state stack. If it sees an old state that has
9601  * more strict register state and more strict stack state then this execution
9602  * branch doesn't need to be explored further, since verifier already
9603  * concluded that more strict state leads to valid finish.
9604  *
9605  * Therefore two states are equivalent if register state is more conservative
9606  * and explored stack state is more conservative than the current one.
9607  * Example:
9608  *       explored                   current
9609  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9610  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9611  *
9612  * In other words if current stack state (one being explored) has more
9613  * valid slots than old one that already passed validation, it means
9614  * the verifier can stop exploring and conclude that current state is valid too
9615  *
9616  * Similarly with registers. If explored state has register type as invalid
9617  * whereas register type in current state is meaningful, it means that
9618  * the current state will reach 'bpf_exit' instruction safely
9619  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)9620 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9621 			      struct bpf_func_state *cur)
9622 {
9623 	int i;
9624 
9625 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9626 	for (i = 0; i < MAX_BPF_REG; i++)
9627 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
9628 			     env->idmap_scratch))
9629 			return false;
9630 
9631 	if (!stacksafe(env, old, cur, env->idmap_scratch))
9632 		return false;
9633 
9634 	if (!refsafe(old, cur))
9635 		return false;
9636 
9637 	return true;
9638 }
9639 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9640 static bool states_equal(struct bpf_verifier_env *env,
9641 			 struct bpf_verifier_state *old,
9642 			 struct bpf_verifier_state *cur)
9643 {
9644 	int i;
9645 
9646 	if (old->curframe != cur->curframe)
9647 		return false;
9648 
9649 	/* Verification state from speculative execution simulation
9650 	 * must never prune a non-speculative execution one.
9651 	 */
9652 	if (old->speculative && !cur->speculative)
9653 		return false;
9654 
9655 	if (old->active_spin_lock != cur->active_spin_lock)
9656 		return false;
9657 
9658 	/* for states to be equal callsites have to be the same
9659 	 * and all frame states need to be equivalent
9660 	 */
9661 	for (i = 0; i <= old->curframe; i++) {
9662 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9663 			return false;
9664 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9665 			return false;
9666 	}
9667 	return true;
9668 }
9669 
9670 /* Return 0 if no propagation happened. Return negative error code if error
9671  * happened. Otherwise, return the propagated bit.
9672  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)9673 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9674 				  struct bpf_reg_state *reg,
9675 				  struct bpf_reg_state *parent_reg)
9676 {
9677 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9678 	u8 flag = reg->live & REG_LIVE_READ;
9679 	int err;
9680 
9681 	/* When comes here, read flags of PARENT_REG or REG could be any of
9682 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9683 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9684 	 */
9685 	if (parent_flag == REG_LIVE_READ64 ||
9686 	    /* Or if there is no read flag from REG. */
9687 	    !flag ||
9688 	    /* Or if the read flag from REG is the same as PARENT_REG. */
9689 	    parent_flag == flag)
9690 		return 0;
9691 
9692 	err = mark_reg_read(env, reg, parent_reg, flag);
9693 	if (err)
9694 		return err;
9695 
9696 	return flag;
9697 }
9698 
9699 /* A write screens off any subsequent reads; but write marks come from the
9700  * straight-line code between a state and its parent.  When we arrive at an
9701  * equivalent state (jump target or such) we didn't arrive by the straight-line
9702  * code, so read marks in the state must propagate to the parent regardless
9703  * of the state's write marks. That's what 'parent == state->parent' comparison
9704  * in mark_reg_read() is for.
9705  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)9706 static int propagate_liveness(struct bpf_verifier_env *env,
9707 			      const struct bpf_verifier_state *vstate,
9708 			      struct bpf_verifier_state *vparent)
9709 {
9710 	struct bpf_reg_state *state_reg, *parent_reg;
9711 	struct bpf_func_state *state, *parent;
9712 	int i, frame, err = 0;
9713 
9714 	if (vparent->curframe != vstate->curframe) {
9715 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9716 		     vparent->curframe, vstate->curframe);
9717 		return -EFAULT;
9718 	}
9719 	/* Propagate read liveness of registers... */
9720 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9721 	for (frame = 0; frame <= vstate->curframe; frame++) {
9722 		parent = vparent->frame[frame];
9723 		state = vstate->frame[frame];
9724 		parent_reg = parent->regs;
9725 		state_reg = state->regs;
9726 		/* We don't need to worry about FP liveness, it's read-only */
9727 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9728 			err = propagate_liveness_reg(env, &state_reg[i],
9729 						     &parent_reg[i]);
9730 			if (err < 0)
9731 				return err;
9732 			if (err == REG_LIVE_READ64)
9733 				mark_insn_zext(env, &parent_reg[i]);
9734 		}
9735 
9736 		/* Propagate stack slots. */
9737 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9738 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9739 			parent_reg = &parent->stack[i].spilled_ptr;
9740 			state_reg = &state->stack[i].spilled_ptr;
9741 			err = propagate_liveness_reg(env, state_reg,
9742 						     parent_reg);
9743 			if (err < 0)
9744 				return err;
9745 		}
9746 	}
9747 	return 0;
9748 }
9749 
9750 /* find precise scalars in the previous equivalent state and
9751  * propagate them into the current state
9752  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)9753 static int propagate_precision(struct bpf_verifier_env *env,
9754 			       const struct bpf_verifier_state *old)
9755 {
9756 	struct bpf_reg_state *state_reg;
9757 	struct bpf_func_state *state;
9758 	int i, err = 0, fr;
9759 
9760 	for (fr = old->curframe; fr >= 0; fr--) {
9761 		state = old->frame[fr];
9762 		state_reg = state->regs;
9763 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9764 			if (state_reg->type != SCALAR_VALUE ||
9765 			    !state_reg->precise ||
9766 			    !(state_reg->live & REG_LIVE_READ))
9767 				continue;
9768 			if (env->log.level & BPF_LOG_LEVEL2)
9769 				verbose(env, "frame %d: propagating r%d\n", fr, i);
9770 			err = mark_chain_precision_frame(env, fr, i);
9771 			if (err < 0)
9772 				return err;
9773 		}
9774 
9775 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9776 			if (!is_spilled_reg(&state->stack[i]))
9777 				continue;
9778 			state_reg = &state->stack[i].spilled_ptr;
9779 			if (state_reg->type != SCALAR_VALUE ||
9780 			    !state_reg->precise ||
9781 			    !(state_reg->live & REG_LIVE_READ))
9782 				continue;
9783 			if (env->log.level & BPF_LOG_LEVEL2)
9784 				verbose(env, "frame %d: propagating fp%d\n",
9785 					fr, (-i - 1) * BPF_REG_SIZE);
9786 			err = mark_chain_precision_stack_frame(env, fr, i);
9787 			if (err < 0)
9788 				return err;
9789 		}
9790 	}
9791 	return 0;
9792 }
9793 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9794 static bool states_maybe_looping(struct bpf_verifier_state *old,
9795 				 struct bpf_verifier_state *cur)
9796 {
9797 	struct bpf_func_state *fold, *fcur;
9798 	int i, fr = cur->curframe;
9799 
9800 	if (old->curframe != fr)
9801 		return false;
9802 
9803 	fold = old->frame[fr];
9804 	fcur = cur->frame[fr];
9805 	for (i = 0; i < MAX_BPF_REG; i++)
9806 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9807 			   offsetof(struct bpf_reg_state, parent)))
9808 			return false;
9809 	return true;
9810 }
9811 
9812 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)9813 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9814 {
9815 	struct bpf_verifier_state_list *new_sl;
9816 	struct bpf_verifier_state_list *sl, **pprev;
9817 	struct bpf_verifier_state *cur = env->cur_state, *new;
9818 	int i, j, err, states_cnt = 0;
9819 	bool add_new_state = env->test_state_freq ? true : false;
9820 
9821 	cur->last_insn_idx = env->prev_insn_idx;
9822 	if (!env->insn_aux_data[insn_idx].prune_point)
9823 		/* this 'insn_idx' instruction wasn't marked, so we will not
9824 		 * be doing state search here
9825 		 */
9826 		return 0;
9827 
9828 	/* bpf progs typically have pruning point every 4 instructions
9829 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9830 	 * Do not add new state for future pruning if the verifier hasn't seen
9831 	 * at least 2 jumps and at least 8 instructions.
9832 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9833 	 * In tests that amounts to up to 50% reduction into total verifier
9834 	 * memory consumption and 20% verifier time speedup.
9835 	 */
9836 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9837 	    env->insn_processed - env->prev_insn_processed >= 8)
9838 		add_new_state = true;
9839 
9840 	pprev = explored_state(env, insn_idx);
9841 	sl = *pprev;
9842 
9843 	clean_live_states(env, insn_idx, cur);
9844 
9845 	while (sl) {
9846 		states_cnt++;
9847 		if (sl->state.insn_idx != insn_idx)
9848 			goto next;
9849 		if (sl->state.branches) {
9850 			if (states_maybe_looping(&sl->state, cur) &&
9851 			    states_equal(env, &sl->state, cur)) {
9852 				verbose_linfo(env, insn_idx, "; ");
9853 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9854 				return -EINVAL;
9855 			}
9856 			/* if the verifier is processing a loop, avoid adding new state
9857 			 * too often, since different loop iterations have distinct
9858 			 * states and may not help future pruning.
9859 			 * This threshold shouldn't be too low to make sure that
9860 			 * a loop with large bound will be rejected quickly.
9861 			 * The most abusive loop will be:
9862 			 * r1 += 1
9863 			 * if r1 < 1000000 goto pc-2
9864 			 * 1M insn_procssed limit / 100 == 10k peak states.
9865 			 * This threshold shouldn't be too high either, since states
9866 			 * at the end of the loop are likely to be useful in pruning.
9867 			 */
9868 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9869 			    env->insn_processed - env->prev_insn_processed < 100)
9870 				add_new_state = false;
9871 			goto miss;
9872 		}
9873 		if (states_equal(env, &sl->state, cur)) {
9874 			sl->hit_cnt++;
9875 			/* reached equivalent register/stack state,
9876 			 * prune the search.
9877 			 * Registers read by the continuation are read by us.
9878 			 * If we have any write marks in env->cur_state, they
9879 			 * will prevent corresponding reads in the continuation
9880 			 * from reaching our parent (an explored_state).  Our
9881 			 * own state will get the read marks recorded, but
9882 			 * they'll be immediately forgotten as we're pruning
9883 			 * this state and will pop a new one.
9884 			 */
9885 			err = propagate_liveness(env, &sl->state, cur);
9886 
9887 			/* if previous state reached the exit with precision and
9888 			 * current state is equivalent to it (except precsion marks)
9889 			 * the precision needs to be propagated back in
9890 			 * the current state.
9891 			 */
9892 			err = err ? : push_jmp_history(env, cur);
9893 			err = err ? : propagate_precision(env, &sl->state);
9894 			if (err)
9895 				return err;
9896 			return 1;
9897 		}
9898 miss:
9899 		/* when new state is not going to be added do not increase miss count.
9900 		 * Otherwise several loop iterations will remove the state
9901 		 * recorded earlier. The goal of these heuristics is to have
9902 		 * states from some iterations of the loop (some in the beginning
9903 		 * and some at the end) to help pruning.
9904 		 */
9905 		if (add_new_state)
9906 			sl->miss_cnt++;
9907 		/* heuristic to determine whether this state is beneficial
9908 		 * to keep checking from state equivalence point of view.
9909 		 * Higher numbers increase max_states_per_insn and verification time,
9910 		 * but do not meaningfully decrease insn_processed.
9911 		 */
9912 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9913 			/* the state is unlikely to be useful. Remove it to
9914 			 * speed up verification
9915 			 */
9916 			*pprev = sl->next;
9917 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9918 				u32 br = sl->state.branches;
9919 
9920 				WARN_ONCE(br,
9921 					  "BUG live_done but branches_to_explore %d\n",
9922 					  br);
9923 				free_verifier_state(&sl->state, false);
9924 				kfree(sl);
9925 				env->peak_states--;
9926 			} else {
9927 				/* cannot free this state, since parentage chain may
9928 				 * walk it later. Add it for free_list instead to
9929 				 * be freed at the end of verification
9930 				 */
9931 				sl->next = env->free_list;
9932 				env->free_list = sl;
9933 			}
9934 			sl = *pprev;
9935 			continue;
9936 		}
9937 next:
9938 		pprev = &sl->next;
9939 		sl = *pprev;
9940 	}
9941 
9942 	if (env->max_states_per_insn < states_cnt)
9943 		env->max_states_per_insn = states_cnt;
9944 
9945 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9946 		return push_jmp_history(env, cur);
9947 
9948 	if (!add_new_state)
9949 		return push_jmp_history(env, cur);
9950 
9951 	/* There were no equivalent states, remember the current one.
9952 	 * Technically the current state is not proven to be safe yet,
9953 	 * but it will either reach outer most bpf_exit (which means it's safe)
9954 	 * or it will be rejected. When there are no loops the verifier won't be
9955 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9956 	 * again on the way to bpf_exit.
9957 	 * When looping the sl->state.branches will be > 0 and this state
9958 	 * will not be considered for equivalence until branches == 0.
9959 	 */
9960 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9961 	if (!new_sl)
9962 		return -ENOMEM;
9963 	env->total_states++;
9964 	env->peak_states++;
9965 	env->prev_jmps_processed = env->jmps_processed;
9966 	env->prev_insn_processed = env->insn_processed;
9967 
9968 	/* forget precise markings we inherited, see __mark_chain_precision */
9969 	if (env->bpf_capable)
9970 		mark_all_scalars_imprecise(env, cur);
9971 
9972 	/* add new state to the head of linked list */
9973 	new = &new_sl->state;
9974 	err = copy_verifier_state(new, cur);
9975 	if (err) {
9976 		free_verifier_state(new, false);
9977 		kfree(new_sl);
9978 		return err;
9979 	}
9980 	new->insn_idx = insn_idx;
9981 	WARN_ONCE(new->branches != 1,
9982 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9983 
9984 	cur->parent = new;
9985 	cur->first_insn_idx = insn_idx;
9986 	clear_jmp_history(cur);
9987 	new_sl->next = *explored_state(env, insn_idx);
9988 	*explored_state(env, insn_idx) = new_sl;
9989 	/* connect new state to parentage chain. Current frame needs all
9990 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9991 	 * to the stack implicitly by JITs) so in callers' frames connect just
9992 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9993 	 * the state of the call instruction (with WRITTEN set), and r0 comes
9994 	 * from callee with its full parentage chain, anyway.
9995 	 */
9996 	/* clear write marks in current state: the writes we did are not writes
9997 	 * our child did, so they don't screen off its reads from us.
9998 	 * (There are no read marks in current state, because reads always mark
9999 	 * their parent and current state never has children yet.  Only
10000 	 * explored_states can get read marks.)
10001 	 */
10002 	for (j = 0; j <= cur->curframe; j++) {
10003 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10004 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10005 		for (i = 0; i < BPF_REG_FP; i++)
10006 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10007 	}
10008 
10009 	/* all stack frames are accessible from callee, clear them all */
10010 	for (j = 0; j <= cur->curframe; j++) {
10011 		struct bpf_func_state *frame = cur->frame[j];
10012 		struct bpf_func_state *newframe = new->frame[j];
10013 
10014 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10015 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10016 			frame->stack[i].spilled_ptr.parent =
10017 						&newframe->stack[i].spilled_ptr;
10018 		}
10019 	}
10020 	return 0;
10021 }
10022 
10023 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)10024 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10025 {
10026 	switch (base_type(type)) {
10027 	case PTR_TO_CTX:
10028 	case PTR_TO_SOCKET:
10029 	case PTR_TO_SOCK_COMMON:
10030 	case PTR_TO_TCP_SOCK:
10031 	case PTR_TO_XDP_SOCK:
10032 	case PTR_TO_BTF_ID:
10033 		return false;
10034 	default:
10035 		return true;
10036 	}
10037 }
10038 
10039 /* If an instruction was previously used with particular pointer types, then we
10040  * need to be careful to avoid cases such as the below, where it may be ok
10041  * for one branch accessing the pointer, but not ok for the other branch:
10042  *
10043  * R1 = sock_ptr
10044  * goto X;
10045  * ...
10046  * R1 = some_other_valid_ptr;
10047  * goto X;
10048  * ...
10049  * R2 = *(u32 *)(R1 + 0);
10050  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)10051 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10052 {
10053 	return src != prev && (!reg_type_mismatch_ok(src) ||
10054 			       !reg_type_mismatch_ok(prev));
10055 }
10056 
do_check(struct bpf_verifier_env * env)10057 static int do_check(struct bpf_verifier_env *env)
10058 {
10059 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10060 	struct bpf_verifier_state *state = env->cur_state;
10061 	struct bpf_insn *insns = env->prog->insnsi;
10062 	struct bpf_reg_state *regs;
10063 	int insn_cnt = env->prog->len;
10064 	bool do_print_state = false;
10065 	int prev_insn_idx = -1;
10066 
10067 	for (;;) {
10068 		struct bpf_insn *insn;
10069 		u8 class;
10070 		int err;
10071 
10072 		env->prev_insn_idx = prev_insn_idx;
10073 		if (env->insn_idx >= insn_cnt) {
10074 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
10075 				env->insn_idx, insn_cnt);
10076 			return -EFAULT;
10077 		}
10078 
10079 		insn = &insns[env->insn_idx];
10080 		class = BPF_CLASS(insn->code);
10081 
10082 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10083 			verbose(env,
10084 				"BPF program is too large. Processed %d insn\n",
10085 				env->insn_processed);
10086 			return -E2BIG;
10087 		}
10088 
10089 		err = is_state_visited(env, env->insn_idx);
10090 		if (err < 0)
10091 			return err;
10092 		if (err == 1) {
10093 			/* found equivalent state, can prune the search */
10094 			if (env->log.level & BPF_LOG_LEVEL) {
10095 				if (do_print_state)
10096 					verbose(env, "\nfrom %d to %d%s: safe\n",
10097 						env->prev_insn_idx, env->insn_idx,
10098 						env->cur_state->speculative ?
10099 						" (speculative execution)" : "");
10100 				else
10101 					verbose(env, "%d: safe\n", env->insn_idx);
10102 			}
10103 			goto process_bpf_exit;
10104 		}
10105 
10106 		if (signal_pending(current))
10107 			return -EAGAIN;
10108 
10109 		if (need_resched())
10110 			cond_resched();
10111 
10112 		if (env->log.level & BPF_LOG_LEVEL2 ||
10113 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10114 			if (env->log.level & BPF_LOG_LEVEL2)
10115 				verbose(env, "%d:", env->insn_idx);
10116 			else
10117 				verbose(env, "\nfrom %d to %d%s:",
10118 					env->prev_insn_idx, env->insn_idx,
10119 					env->cur_state->speculative ?
10120 					" (speculative execution)" : "");
10121 			print_verifier_state(env, state->frame[state->curframe]);
10122 			do_print_state = false;
10123 		}
10124 
10125 		if (env->log.level & BPF_LOG_LEVEL) {
10126 			const struct bpf_insn_cbs cbs = {
10127 				.cb_print	= verbose,
10128 				.private_data	= env,
10129 			};
10130 
10131 			verbose_linfo(env, env->insn_idx, "; ");
10132 			verbose(env, "%d: ", env->insn_idx);
10133 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10134 		}
10135 
10136 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
10137 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10138 							   env->prev_insn_idx);
10139 			if (err)
10140 				return err;
10141 		}
10142 
10143 		regs = cur_regs(env);
10144 		sanitize_mark_insn_seen(env);
10145 		prev_insn_idx = env->insn_idx;
10146 
10147 		if (class == BPF_ALU || class == BPF_ALU64) {
10148 			err = check_alu_op(env, insn);
10149 			if (err)
10150 				return err;
10151 
10152 		} else if (class == BPF_LDX) {
10153 			enum bpf_reg_type *prev_src_type, src_reg_type;
10154 
10155 			/* check for reserved fields is already done */
10156 
10157 			/* check src operand */
10158 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10159 			if (err)
10160 				return err;
10161 
10162 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10163 			if (err)
10164 				return err;
10165 
10166 			src_reg_type = regs[insn->src_reg].type;
10167 
10168 			/* check that memory (src_reg + off) is readable,
10169 			 * the state of dst_reg will be updated by this func
10170 			 */
10171 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
10172 					       insn->off, BPF_SIZE(insn->code),
10173 					       BPF_READ, insn->dst_reg, false);
10174 			if (err)
10175 				return err;
10176 
10177 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10178 
10179 			if (*prev_src_type == NOT_INIT) {
10180 				/* saw a valid insn
10181 				 * dst_reg = *(u32 *)(src_reg + off)
10182 				 * save type to validate intersecting paths
10183 				 */
10184 				*prev_src_type = src_reg_type;
10185 
10186 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10187 				/* ABuser program is trying to use the same insn
10188 				 * dst_reg = *(u32*) (src_reg + off)
10189 				 * with different pointer types:
10190 				 * src_reg == ctx in one branch and
10191 				 * src_reg == stack|map in some other branch.
10192 				 * Reject it.
10193 				 */
10194 				verbose(env, "same insn cannot be used with different pointers\n");
10195 				return -EINVAL;
10196 			}
10197 
10198 		} else if (class == BPF_STX) {
10199 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
10200 
10201 			if (BPF_MODE(insn->code) == BPF_XADD) {
10202 				err = check_xadd(env, env->insn_idx, insn);
10203 				if (err)
10204 					return err;
10205 				env->insn_idx++;
10206 				continue;
10207 			}
10208 
10209 			/* check src1 operand */
10210 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10211 			if (err)
10212 				return err;
10213 			/* check src2 operand */
10214 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10215 			if (err)
10216 				return err;
10217 
10218 			dst_reg_type = regs[insn->dst_reg].type;
10219 
10220 			/* check that memory (dst_reg + off) is writeable */
10221 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10222 					       insn->off, BPF_SIZE(insn->code),
10223 					       BPF_WRITE, insn->src_reg, false);
10224 			if (err)
10225 				return err;
10226 
10227 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10228 
10229 			if (*prev_dst_type == NOT_INIT) {
10230 				*prev_dst_type = dst_reg_type;
10231 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10232 				verbose(env, "same insn cannot be used with different pointers\n");
10233 				return -EINVAL;
10234 			}
10235 
10236 		} else if (class == BPF_ST) {
10237 			if (BPF_MODE(insn->code) != BPF_MEM ||
10238 			    insn->src_reg != BPF_REG_0) {
10239 				verbose(env, "BPF_ST uses reserved fields\n");
10240 				return -EINVAL;
10241 			}
10242 			/* check src operand */
10243 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10244 			if (err)
10245 				return err;
10246 
10247 			if (is_ctx_reg(env, insn->dst_reg)) {
10248 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10249 					insn->dst_reg,
10250 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
10251 				return -EACCES;
10252 			}
10253 
10254 			/* check that memory (dst_reg + off) is writeable */
10255 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10256 					       insn->off, BPF_SIZE(insn->code),
10257 					       BPF_WRITE, -1, false);
10258 			if (err)
10259 				return err;
10260 
10261 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10262 			u8 opcode = BPF_OP(insn->code);
10263 
10264 			env->jmps_processed++;
10265 			if (opcode == BPF_CALL) {
10266 				if (BPF_SRC(insn->code) != BPF_K ||
10267 				    insn->off != 0 ||
10268 				    (insn->src_reg != BPF_REG_0 &&
10269 				     insn->src_reg != BPF_PSEUDO_CALL) ||
10270 				    insn->dst_reg != BPF_REG_0 ||
10271 				    class == BPF_JMP32) {
10272 					verbose(env, "BPF_CALL uses reserved fields\n");
10273 					return -EINVAL;
10274 				}
10275 
10276 				if (env->cur_state->active_spin_lock &&
10277 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10278 				     insn->imm != BPF_FUNC_spin_unlock)) {
10279 					verbose(env, "function calls are not allowed while holding a lock\n");
10280 					return -EINVAL;
10281 				}
10282 				if (insn->src_reg == BPF_PSEUDO_CALL)
10283 					err = check_func_call(env, insn, &env->insn_idx);
10284 				else
10285 					err = check_helper_call(env, insn->imm, env->insn_idx);
10286 				if (err)
10287 					return err;
10288 
10289 			} else if (opcode == BPF_JA) {
10290 				if (BPF_SRC(insn->code) != BPF_K ||
10291 				    insn->imm != 0 ||
10292 				    insn->src_reg != BPF_REG_0 ||
10293 				    insn->dst_reg != BPF_REG_0 ||
10294 				    class == BPF_JMP32) {
10295 					verbose(env, "BPF_JA uses reserved fields\n");
10296 					return -EINVAL;
10297 				}
10298 
10299 				env->insn_idx += insn->off + 1;
10300 				continue;
10301 
10302 			} else if (opcode == BPF_EXIT) {
10303 				if (BPF_SRC(insn->code) != BPF_K ||
10304 				    insn->imm != 0 ||
10305 				    insn->src_reg != BPF_REG_0 ||
10306 				    insn->dst_reg != BPF_REG_0 ||
10307 				    class == BPF_JMP32) {
10308 					verbose(env, "BPF_EXIT uses reserved fields\n");
10309 					return -EINVAL;
10310 				}
10311 
10312 				if (env->cur_state->active_spin_lock) {
10313 					verbose(env, "bpf_spin_unlock is missing\n");
10314 					return -EINVAL;
10315 				}
10316 
10317 				if (state->curframe) {
10318 					/* exit from nested function */
10319 					err = prepare_func_exit(env, &env->insn_idx);
10320 					if (err)
10321 						return err;
10322 					do_print_state = true;
10323 					continue;
10324 				}
10325 
10326 				err = check_reference_leak(env);
10327 				if (err)
10328 					return err;
10329 
10330 				err = check_return_code(env);
10331 				if (err)
10332 					return err;
10333 process_bpf_exit:
10334 				update_branch_counts(env, env->cur_state);
10335 				err = pop_stack(env, &prev_insn_idx,
10336 						&env->insn_idx, pop_log);
10337 				if (err < 0) {
10338 					if (err != -ENOENT)
10339 						return err;
10340 					break;
10341 				} else {
10342 					do_print_state = true;
10343 					continue;
10344 				}
10345 			} else {
10346 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10347 				if (err)
10348 					return err;
10349 			}
10350 		} else if (class == BPF_LD) {
10351 			u8 mode = BPF_MODE(insn->code);
10352 
10353 			if (mode == BPF_ABS || mode == BPF_IND) {
10354 				err = check_ld_abs(env, insn);
10355 				if (err)
10356 					return err;
10357 
10358 			} else if (mode == BPF_IMM) {
10359 				err = check_ld_imm(env, insn);
10360 				if (err)
10361 					return err;
10362 
10363 				env->insn_idx++;
10364 				sanitize_mark_insn_seen(env);
10365 			} else {
10366 				verbose(env, "invalid BPF_LD mode\n");
10367 				return -EINVAL;
10368 			}
10369 		} else {
10370 			verbose(env, "unknown insn class %d\n", class);
10371 			return -EINVAL;
10372 		}
10373 
10374 		env->insn_idx++;
10375 	}
10376 
10377 	return 0;
10378 }
10379 
10380 /* 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)10381 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10382 			       struct bpf_insn *insn,
10383 			       struct bpf_insn_aux_data *aux)
10384 {
10385 	const struct btf_var_secinfo *vsi;
10386 	const struct btf_type *datasec;
10387 	const struct btf_type *t;
10388 	const char *sym_name;
10389 	bool percpu = false;
10390 	u32 type, id = insn->imm;
10391 	s32 datasec_id;
10392 	u64 addr;
10393 	int i;
10394 
10395 	if (!btf_vmlinux) {
10396 		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10397 		return -EINVAL;
10398 	}
10399 
10400 	if (insn[1].imm != 0) {
10401 		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10402 		return -EINVAL;
10403 	}
10404 
10405 	t = btf_type_by_id(btf_vmlinux, id);
10406 	if (!t) {
10407 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10408 		return -ENOENT;
10409 	}
10410 
10411 	if (!btf_type_is_var(t)) {
10412 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10413 			id);
10414 		return -EINVAL;
10415 	}
10416 
10417 	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10418 	addr = kallsyms_lookup_name(sym_name);
10419 	if (!addr) {
10420 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10421 			sym_name);
10422 		return -ENOENT;
10423 	}
10424 
10425 	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10426 					   BTF_KIND_DATASEC);
10427 	if (datasec_id > 0) {
10428 		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10429 		for_each_vsi(i, datasec, vsi) {
10430 			if (vsi->type == id) {
10431 				percpu = true;
10432 				break;
10433 			}
10434 		}
10435 	}
10436 
10437 	insn[0].imm = (u32)addr;
10438 	insn[1].imm = addr >> 32;
10439 
10440 	type = t->type;
10441 	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10442 	if (percpu) {
10443 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10444 		aux->btf_var.btf_id = type;
10445 	} else if (!btf_type_is_struct(t)) {
10446 		const struct btf_type *ret;
10447 		const char *tname;
10448 		u32 tsize;
10449 
10450 		/* resolve the type size of ksym. */
10451 		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10452 		if (IS_ERR(ret)) {
10453 			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10454 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10455 				tname, PTR_ERR(ret));
10456 			return -EINVAL;
10457 		}
10458 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
10459 		aux->btf_var.mem_size = tsize;
10460 	} else {
10461 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10462 		aux->btf_var.btf_id = type;
10463 	}
10464 	return 0;
10465 }
10466 
check_map_prealloc(struct bpf_map * map)10467 static int check_map_prealloc(struct bpf_map *map)
10468 {
10469 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10470 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10471 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10472 		!(map->map_flags & BPF_F_NO_PREALLOC);
10473 }
10474 
is_tracing_prog_type(enum bpf_prog_type type)10475 static bool is_tracing_prog_type(enum bpf_prog_type type)
10476 {
10477 	switch (type) {
10478 	case BPF_PROG_TYPE_KPROBE:
10479 	case BPF_PROG_TYPE_TRACEPOINT:
10480 	case BPF_PROG_TYPE_PERF_EVENT:
10481 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10482 		return true;
10483 	default:
10484 		return false;
10485 	}
10486 }
10487 
is_preallocated_map(struct bpf_map * map)10488 static bool is_preallocated_map(struct bpf_map *map)
10489 {
10490 	if (!check_map_prealloc(map))
10491 		return false;
10492 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10493 		return false;
10494 	return true;
10495 }
10496 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)10497 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10498 					struct bpf_map *map,
10499 					struct bpf_prog *prog)
10500 
10501 {
10502 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10503 	/*
10504 	 * Validate that trace type programs use preallocated hash maps.
10505 	 *
10506 	 * For programs attached to PERF events this is mandatory as the
10507 	 * perf NMI can hit any arbitrary code sequence.
10508 	 *
10509 	 * All other trace types using preallocated hash maps are unsafe as
10510 	 * well because tracepoint or kprobes can be inside locked regions
10511 	 * of the memory allocator or at a place where a recursion into the
10512 	 * memory allocator would see inconsistent state.
10513 	 *
10514 	 * On RT enabled kernels run-time allocation of all trace type
10515 	 * programs is strictly prohibited due to lock type constraints. On
10516 	 * !RT kernels it is allowed for backwards compatibility reasons for
10517 	 * now, but warnings are emitted so developers are made aware of
10518 	 * the unsafety and can fix their programs before this is enforced.
10519 	 */
10520 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10521 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10522 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10523 			return -EINVAL;
10524 		}
10525 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10526 			verbose(env, "trace type programs can only use preallocated hash map\n");
10527 			return -EINVAL;
10528 		}
10529 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10530 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10531 	}
10532 
10533 	if ((is_tracing_prog_type(prog_type) ||
10534 	     prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10535 	    map_value_has_spin_lock(map)) {
10536 		verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10537 		return -EINVAL;
10538 	}
10539 
10540 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10541 	    !bpf_offload_prog_map_match(prog, map)) {
10542 		verbose(env, "offload device mismatch between prog and map\n");
10543 		return -EINVAL;
10544 	}
10545 
10546 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10547 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10548 		return -EINVAL;
10549 	}
10550 
10551 	if (prog->aux->sleepable)
10552 		switch (map->map_type) {
10553 		case BPF_MAP_TYPE_HASH:
10554 		case BPF_MAP_TYPE_LRU_HASH:
10555 		case BPF_MAP_TYPE_ARRAY:
10556 			if (!is_preallocated_map(map)) {
10557 				verbose(env,
10558 					"Sleepable programs can only use preallocated hash maps\n");
10559 				return -EINVAL;
10560 			}
10561 			break;
10562 		default:
10563 			verbose(env,
10564 				"Sleepable programs can only use array and hash maps\n");
10565 			return -EINVAL;
10566 		}
10567 
10568 	return 0;
10569 }
10570 
bpf_map_is_cgroup_storage(struct bpf_map * map)10571 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10572 {
10573 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10574 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10575 }
10576 
10577 /* find and rewrite pseudo imm in ld_imm64 instructions:
10578  *
10579  * 1. if it accesses map FD, replace it with actual map pointer.
10580  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10581  *
10582  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10583  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)10584 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10585 {
10586 	struct bpf_insn *insn = env->prog->insnsi;
10587 	int insn_cnt = env->prog->len;
10588 	int i, j, err;
10589 
10590 	err = bpf_prog_calc_tag(env->prog);
10591 	if (err)
10592 		return err;
10593 
10594 	for (i = 0; i < insn_cnt; i++, insn++) {
10595 		if (BPF_CLASS(insn->code) == BPF_LDX &&
10596 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10597 			verbose(env, "BPF_LDX uses reserved fields\n");
10598 			return -EINVAL;
10599 		}
10600 
10601 		if (BPF_CLASS(insn->code) == BPF_STX &&
10602 		    ((BPF_MODE(insn->code) != BPF_MEM &&
10603 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10604 			verbose(env, "BPF_STX uses reserved fields\n");
10605 			return -EINVAL;
10606 		}
10607 
10608 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10609 			struct bpf_insn_aux_data *aux;
10610 			struct bpf_map *map;
10611 			struct fd f;
10612 			u64 addr;
10613 
10614 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
10615 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10616 			    insn[1].off != 0) {
10617 				verbose(env, "invalid bpf_ld_imm64 insn\n");
10618 				return -EINVAL;
10619 			}
10620 
10621 			if (insn[0].src_reg == 0)
10622 				/* valid generic load 64-bit imm */
10623 				goto next_insn;
10624 
10625 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10626 				aux = &env->insn_aux_data[i];
10627 				err = check_pseudo_btf_id(env, insn, aux);
10628 				if (err)
10629 					return err;
10630 				goto next_insn;
10631 			}
10632 
10633 			/* In final convert_pseudo_ld_imm64() step, this is
10634 			 * converted into regular 64-bit imm load insn.
10635 			 */
10636 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10637 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10638 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10639 			     insn[1].imm != 0)) {
10640 				verbose(env,
10641 					"unrecognized bpf_ld_imm64 insn\n");
10642 				return -EINVAL;
10643 			}
10644 
10645 			f = fdget(insn[0].imm);
10646 			map = __bpf_map_get(f);
10647 			if (IS_ERR(map)) {
10648 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
10649 					insn[0].imm);
10650 				return PTR_ERR(map);
10651 			}
10652 
10653 			err = check_map_prog_compatibility(env, map, env->prog);
10654 			if (err) {
10655 				fdput(f);
10656 				return err;
10657 			}
10658 
10659 			aux = &env->insn_aux_data[i];
10660 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10661 				addr = (unsigned long)map;
10662 			} else {
10663 				u32 off = insn[1].imm;
10664 
10665 				if (off >= BPF_MAX_VAR_OFF) {
10666 					verbose(env, "direct value offset of %u is not allowed\n", off);
10667 					fdput(f);
10668 					return -EINVAL;
10669 				}
10670 
10671 				if (!map->ops->map_direct_value_addr) {
10672 					verbose(env, "no direct value access support for this map type\n");
10673 					fdput(f);
10674 					return -EINVAL;
10675 				}
10676 
10677 				err = map->ops->map_direct_value_addr(map, &addr, off);
10678 				if (err) {
10679 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10680 						map->value_size, off);
10681 					fdput(f);
10682 					return err;
10683 				}
10684 
10685 				aux->map_off = off;
10686 				addr += off;
10687 			}
10688 
10689 			insn[0].imm = (u32)addr;
10690 			insn[1].imm = addr >> 32;
10691 
10692 			/* check whether we recorded this map already */
10693 			for (j = 0; j < env->used_map_cnt; j++) {
10694 				if (env->used_maps[j] == map) {
10695 					aux->map_index = j;
10696 					fdput(f);
10697 					goto next_insn;
10698 				}
10699 			}
10700 
10701 			if (env->used_map_cnt >= MAX_USED_MAPS) {
10702 				fdput(f);
10703 				return -E2BIG;
10704 			}
10705 
10706 			/* hold the map. If the program is rejected by verifier,
10707 			 * the map will be released by release_maps() or it
10708 			 * will be used by the valid program until it's unloaded
10709 			 * and all maps are released in free_used_maps()
10710 			 */
10711 			bpf_map_inc(map);
10712 
10713 			aux->map_index = env->used_map_cnt;
10714 			env->used_maps[env->used_map_cnt++] = map;
10715 
10716 			if (bpf_map_is_cgroup_storage(map) &&
10717 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10718 				verbose(env, "only one cgroup storage of each type is allowed\n");
10719 				fdput(f);
10720 				return -EBUSY;
10721 			}
10722 
10723 			fdput(f);
10724 next_insn:
10725 			insn++;
10726 			i++;
10727 			continue;
10728 		}
10729 
10730 		/* Basic sanity check before we invest more work here. */
10731 		if (!bpf_opcode_in_insntable(insn->code)) {
10732 			verbose(env, "unknown opcode %02x\n", insn->code);
10733 			return -EINVAL;
10734 		}
10735 	}
10736 
10737 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10738 	 * 'struct bpf_map *' into a register instead of user map_fd.
10739 	 * These pointers will be used later by verifier to validate map access.
10740 	 */
10741 	return 0;
10742 }
10743 
10744 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)10745 static void release_maps(struct bpf_verifier_env *env)
10746 {
10747 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10748 			     env->used_map_cnt);
10749 }
10750 
10751 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)10752 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10753 {
10754 	struct bpf_insn *insn = env->prog->insnsi;
10755 	int insn_cnt = env->prog->len;
10756 	int i;
10757 
10758 	for (i = 0; i < insn_cnt; i++, insn++)
10759 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10760 			insn->src_reg = 0;
10761 }
10762 
10763 /* single env->prog->insni[off] instruction was replaced with the range
10764  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10765  * [0, off) and [off, end) to new locations, so the patched range stays zero
10766  */
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)10767 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10768 				 struct bpf_insn_aux_data *new_data,
10769 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
10770 {
10771 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10772 	struct bpf_insn *insn = new_prog->insnsi;
10773 	u32 old_seen = old_data[off].seen;
10774 	u32 prog_len;
10775 	int i;
10776 
10777 	/* aux info at OFF always needs adjustment, no matter fast path
10778 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10779 	 * original insn at old prog.
10780 	 */
10781 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10782 
10783 	if (cnt == 1)
10784 		return;
10785 	prog_len = new_prog->len;
10786 
10787 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10788 	memcpy(new_data + off + cnt - 1, old_data + off,
10789 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10790 	for (i = off; i < off + cnt - 1; i++) {
10791 		/* Expand insni[off]'s seen count to the patched range. */
10792 		new_data[i].seen = old_seen;
10793 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10794 	}
10795 	env->insn_aux_data = new_data;
10796 	vfree(old_data);
10797 }
10798 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)10799 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10800 {
10801 	int i;
10802 
10803 	if (len == 1)
10804 		return;
10805 	/* NOTE: fake 'exit' subprog should be updated as well. */
10806 	for (i = 0; i <= env->subprog_cnt; i++) {
10807 		if (env->subprog_info[i].start <= off)
10808 			continue;
10809 		env->subprog_info[i].start += len - 1;
10810 	}
10811 }
10812 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)10813 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10814 {
10815 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10816 	int i, sz = prog->aux->size_poke_tab;
10817 	struct bpf_jit_poke_descriptor *desc;
10818 
10819 	for (i = 0; i < sz; i++) {
10820 		desc = &tab[i];
10821 		if (desc->insn_idx <= off)
10822 			continue;
10823 		desc->insn_idx += len - 1;
10824 	}
10825 }
10826 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)10827 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10828 					    const struct bpf_insn *patch, u32 len)
10829 {
10830 	struct bpf_prog *new_prog;
10831 	struct bpf_insn_aux_data *new_data = NULL;
10832 
10833 	if (len > 1) {
10834 		new_data = vzalloc(array_size(env->prog->len + len - 1,
10835 					      sizeof(struct bpf_insn_aux_data)));
10836 		if (!new_data)
10837 			return NULL;
10838 	}
10839 
10840 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10841 	if (IS_ERR(new_prog)) {
10842 		if (PTR_ERR(new_prog) == -ERANGE)
10843 			verbose(env,
10844 				"insn %d cannot be patched due to 16-bit range\n",
10845 				env->insn_aux_data[off].orig_idx);
10846 		vfree(new_data);
10847 		return NULL;
10848 	}
10849 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
10850 	adjust_subprog_starts(env, off, len);
10851 	adjust_poke_descs(new_prog, off, len);
10852 	return new_prog;
10853 }
10854 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10855 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10856 					      u32 off, u32 cnt)
10857 {
10858 	int i, j;
10859 
10860 	/* find first prog starting at or after off (first to remove) */
10861 	for (i = 0; i < env->subprog_cnt; i++)
10862 		if (env->subprog_info[i].start >= off)
10863 			break;
10864 	/* find first prog starting at or after off + cnt (first to stay) */
10865 	for (j = i; j < env->subprog_cnt; j++)
10866 		if (env->subprog_info[j].start >= off + cnt)
10867 			break;
10868 	/* if j doesn't start exactly at off + cnt, we are just removing
10869 	 * the front of previous prog
10870 	 */
10871 	if (env->subprog_info[j].start != off + cnt)
10872 		j--;
10873 
10874 	if (j > i) {
10875 		struct bpf_prog_aux *aux = env->prog->aux;
10876 		int move;
10877 
10878 		/* move fake 'exit' subprog as well */
10879 		move = env->subprog_cnt + 1 - j;
10880 
10881 		memmove(env->subprog_info + i,
10882 			env->subprog_info + j,
10883 			sizeof(*env->subprog_info) * move);
10884 		env->subprog_cnt -= j - i;
10885 
10886 		/* remove func_info */
10887 		if (aux->func_info) {
10888 			move = aux->func_info_cnt - j;
10889 
10890 			memmove(aux->func_info + i,
10891 				aux->func_info + j,
10892 				sizeof(*aux->func_info) * move);
10893 			aux->func_info_cnt -= j - i;
10894 			/* func_info->insn_off is set after all code rewrites,
10895 			 * in adjust_btf_func() - no need to adjust
10896 			 */
10897 		}
10898 	} else {
10899 		/* convert i from "first prog to remove" to "first to adjust" */
10900 		if (env->subprog_info[i].start == off)
10901 			i++;
10902 	}
10903 
10904 	/* update fake 'exit' subprog as well */
10905 	for (; i <= env->subprog_cnt; i++)
10906 		env->subprog_info[i].start -= cnt;
10907 
10908 	return 0;
10909 }
10910 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10911 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10912 				      u32 cnt)
10913 {
10914 	struct bpf_prog *prog = env->prog;
10915 	u32 i, l_off, l_cnt, nr_linfo;
10916 	struct bpf_line_info *linfo;
10917 
10918 	nr_linfo = prog->aux->nr_linfo;
10919 	if (!nr_linfo)
10920 		return 0;
10921 
10922 	linfo = prog->aux->linfo;
10923 
10924 	/* find first line info to remove, count lines to be removed */
10925 	for (i = 0; i < nr_linfo; i++)
10926 		if (linfo[i].insn_off >= off)
10927 			break;
10928 
10929 	l_off = i;
10930 	l_cnt = 0;
10931 	for (; i < nr_linfo; i++)
10932 		if (linfo[i].insn_off < off + cnt)
10933 			l_cnt++;
10934 		else
10935 			break;
10936 
10937 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10938 	 * last removed linfo.  prog is already modified, so prog->len == off
10939 	 * means no live instructions after (tail of the program was removed).
10940 	 */
10941 	if (prog->len != off && l_cnt &&
10942 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10943 		l_cnt--;
10944 		linfo[--i].insn_off = off + cnt;
10945 	}
10946 
10947 	/* remove the line info which refer to the removed instructions */
10948 	if (l_cnt) {
10949 		memmove(linfo + l_off, linfo + i,
10950 			sizeof(*linfo) * (nr_linfo - i));
10951 
10952 		prog->aux->nr_linfo -= l_cnt;
10953 		nr_linfo = prog->aux->nr_linfo;
10954 	}
10955 
10956 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10957 	for (i = l_off; i < nr_linfo; i++)
10958 		linfo[i].insn_off -= cnt;
10959 
10960 	/* fix up all subprogs (incl. 'exit') which start >= off */
10961 	for (i = 0; i <= env->subprog_cnt; i++)
10962 		if (env->subprog_info[i].linfo_idx > l_off) {
10963 			/* program may have started in the removed region but
10964 			 * may not be fully removed
10965 			 */
10966 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10967 				env->subprog_info[i].linfo_idx -= l_cnt;
10968 			else
10969 				env->subprog_info[i].linfo_idx = l_off;
10970 		}
10971 
10972 	return 0;
10973 }
10974 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)10975 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10976 {
10977 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10978 	unsigned int orig_prog_len = env->prog->len;
10979 	int err;
10980 
10981 	if (bpf_prog_is_dev_bound(env->prog->aux))
10982 		bpf_prog_offload_remove_insns(env, off, cnt);
10983 
10984 	err = bpf_remove_insns(env->prog, off, cnt);
10985 	if (err)
10986 		return err;
10987 
10988 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10989 	if (err)
10990 		return err;
10991 
10992 	err = bpf_adj_linfo_after_remove(env, off, cnt);
10993 	if (err)
10994 		return err;
10995 
10996 	memmove(aux_data + off,	aux_data + off + cnt,
10997 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
10998 
10999 	return 0;
11000 }
11001 
11002 /* The verifier does more data flow analysis than llvm and will not
11003  * explore branches that are dead at run time. Malicious programs can
11004  * have dead code too. Therefore replace all dead at-run-time code
11005  * with 'ja -1'.
11006  *
11007  * Just nops are not optimal, e.g. if they would sit at the end of the
11008  * program and through another bug we would manage to jump there, then
11009  * we'd execute beyond program memory otherwise. Returning exception
11010  * code also wouldn't work since we can have subprogs where the dead
11011  * code could be located.
11012  */
sanitize_dead_code(struct bpf_verifier_env * env)11013 static void sanitize_dead_code(struct bpf_verifier_env *env)
11014 {
11015 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11016 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11017 	struct bpf_insn *insn = env->prog->insnsi;
11018 	const int insn_cnt = env->prog->len;
11019 	int i;
11020 
11021 	for (i = 0; i < insn_cnt; i++) {
11022 		if (aux_data[i].seen)
11023 			continue;
11024 		memcpy(insn + i, &trap, sizeof(trap));
11025 		aux_data[i].zext_dst = false;
11026 	}
11027 }
11028 
insn_is_cond_jump(u8 code)11029 static bool insn_is_cond_jump(u8 code)
11030 {
11031 	u8 op;
11032 
11033 	if (BPF_CLASS(code) == BPF_JMP32)
11034 		return true;
11035 
11036 	if (BPF_CLASS(code) != BPF_JMP)
11037 		return false;
11038 
11039 	op = BPF_OP(code);
11040 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11041 }
11042 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)11043 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11044 {
11045 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11046 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11047 	struct bpf_insn *insn = env->prog->insnsi;
11048 	const int insn_cnt = env->prog->len;
11049 	int i;
11050 
11051 	for (i = 0; i < insn_cnt; i++, insn++) {
11052 		if (!insn_is_cond_jump(insn->code))
11053 			continue;
11054 
11055 		if (!aux_data[i + 1].seen)
11056 			ja.off = insn->off;
11057 		else if (!aux_data[i + 1 + insn->off].seen)
11058 			ja.off = 0;
11059 		else
11060 			continue;
11061 
11062 		if (bpf_prog_is_dev_bound(env->prog->aux))
11063 			bpf_prog_offload_replace_insn(env, i, &ja);
11064 
11065 		memcpy(insn, &ja, sizeof(ja));
11066 	}
11067 }
11068 
opt_remove_dead_code(struct bpf_verifier_env * env)11069 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11070 {
11071 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11072 	int insn_cnt = env->prog->len;
11073 	int i, err;
11074 
11075 	for (i = 0; i < insn_cnt; i++) {
11076 		int j;
11077 
11078 		j = 0;
11079 		while (i + j < insn_cnt && !aux_data[i + j].seen)
11080 			j++;
11081 		if (!j)
11082 			continue;
11083 
11084 		err = verifier_remove_insns(env, i, j);
11085 		if (err)
11086 			return err;
11087 		insn_cnt = env->prog->len;
11088 	}
11089 
11090 	return 0;
11091 }
11092 
opt_remove_nops(struct bpf_verifier_env * env)11093 static int opt_remove_nops(struct bpf_verifier_env *env)
11094 {
11095 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11096 	struct bpf_insn *insn = env->prog->insnsi;
11097 	int insn_cnt = env->prog->len;
11098 	int i, err;
11099 
11100 	for (i = 0; i < insn_cnt; i++) {
11101 		if (memcmp(&insn[i], &ja, sizeof(ja)))
11102 			continue;
11103 
11104 		err = verifier_remove_insns(env, i, 1);
11105 		if (err)
11106 			return err;
11107 		insn_cnt--;
11108 		i--;
11109 	}
11110 
11111 	return 0;
11112 }
11113 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)11114 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11115 					 const union bpf_attr *attr)
11116 {
11117 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11118 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
11119 	int i, patch_len, delta = 0, len = env->prog->len;
11120 	struct bpf_insn *insns = env->prog->insnsi;
11121 	struct bpf_prog *new_prog;
11122 	bool rnd_hi32;
11123 
11124 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11125 	zext_patch[1] = BPF_ZEXT_REG(0);
11126 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11127 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11128 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11129 	for (i = 0; i < len; i++) {
11130 		int adj_idx = i + delta;
11131 		struct bpf_insn insn;
11132 
11133 		insn = insns[adj_idx];
11134 		if (!aux[adj_idx].zext_dst) {
11135 			u8 code, class;
11136 			u32 imm_rnd;
11137 
11138 			if (!rnd_hi32)
11139 				continue;
11140 
11141 			code = insn.code;
11142 			class = BPF_CLASS(code);
11143 			if (insn_no_def(&insn))
11144 				continue;
11145 
11146 			/* NOTE: arg "reg" (the fourth one) is only used for
11147 			 *       BPF_STX which has been ruled out in above
11148 			 *       check, it is safe to pass NULL here.
11149 			 */
11150 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11151 				if (class == BPF_LD &&
11152 				    BPF_MODE(code) == BPF_IMM)
11153 					i++;
11154 				continue;
11155 			}
11156 
11157 			/* ctx load could be transformed into wider load. */
11158 			if (class == BPF_LDX &&
11159 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
11160 				continue;
11161 
11162 			imm_rnd = get_random_int();
11163 			rnd_hi32_patch[0] = insn;
11164 			rnd_hi32_patch[1].imm = imm_rnd;
11165 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11166 			patch = rnd_hi32_patch;
11167 			patch_len = 4;
11168 			goto apply_patch_buffer;
11169 		}
11170 
11171 		if (!bpf_jit_needs_zext())
11172 			continue;
11173 
11174 		zext_patch[0] = insn;
11175 		zext_patch[1].dst_reg = insn.dst_reg;
11176 		zext_patch[1].src_reg = insn.dst_reg;
11177 		patch = zext_patch;
11178 		patch_len = 2;
11179 apply_patch_buffer:
11180 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11181 		if (!new_prog)
11182 			return -ENOMEM;
11183 		env->prog = new_prog;
11184 		insns = new_prog->insnsi;
11185 		aux = env->insn_aux_data;
11186 		delta += patch_len - 1;
11187 	}
11188 
11189 	return 0;
11190 }
11191 
11192 /* convert load instructions that access fields of a context type into a
11193  * sequence of instructions that access fields of the underlying structure:
11194  *     struct __sk_buff    -> struct sk_buff
11195  *     struct bpf_sock_ops -> struct sock
11196  */
convert_ctx_accesses(struct bpf_verifier_env * env)11197 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11198 {
11199 	const struct bpf_verifier_ops *ops = env->ops;
11200 	int i, cnt, size, ctx_field_size, delta = 0;
11201 	const int insn_cnt = env->prog->len;
11202 	struct bpf_insn insn_buf[16], *insn;
11203 	u32 target_size, size_default, off;
11204 	struct bpf_prog *new_prog;
11205 	enum bpf_access_type type;
11206 	bool is_narrower_load;
11207 
11208 	if (ops->gen_prologue || env->seen_direct_write) {
11209 		if (!ops->gen_prologue) {
11210 			verbose(env, "bpf verifier is misconfigured\n");
11211 			return -EINVAL;
11212 		}
11213 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11214 					env->prog);
11215 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11216 			verbose(env, "bpf verifier is misconfigured\n");
11217 			return -EINVAL;
11218 		} else if (cnt) {
11219 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11220 			if (!new_prog)
11221 				return -ENOMEM;
11222 
11223 			env->prog = new_prog;
11224 			delta += cnt - 1;
11225 		}
11226 	}
11227 
11228 	if (bpf_prog_is_dev_bound(env->prog->aux))
11229 		return 0;
11230 
11231 	insn = env->prog->insnsi + delta;
11232 
11233 	for (i = 0; i < insn_cnt; i++, insn++) {
11234 		bpf_convert_ctx_access_t convert_ctx_access;
11235 		bool ctx_access;
11236 
11237 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11238 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11239 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11240 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11241 			type = BPF_READ;
11242 			ctx_access = true;
11243 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11244 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11245 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11246 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11247 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11248 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11249 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11250 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11251 			type = BPF_WRITE;
11252 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11253 		} else {
11254 			continue;
11255 		}
11256 
11257 		if (type == BPF_WRITE &&
11258 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
11259 			struct bpf_insn patch[] = {
11260 				*insn,
11261 				BPF_ST_NOSPEC(),
11262 			};
11263 
11264 			cnt = ARRAY_SIZE(patch);
11265 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11266 			if (!new_prog)
11267 				return -ENOMEM;
11268 
11269 			delta    += cnt - 1;
11270 			env->prog = new_prog;
11271 			insn      = new_prog->insnsi + i + delta;
11272 			continue;
11273 		}
11274 
11275 		if (!ctx_access)
11276 			continue;
11277 
11278 		switch (env->insn_aux_data[i + delta].ptr_type) {
11279 		case PTR_TO_CTX:
11280 			if (!ops->convert_ctx_access)
11281 				continue;
11282 			convert_ctx_access = ops->convert_ctx_access;
11283 			break;
11284 		case PTR_TO_SOCKET:
11285 		case PTR_TO_SOCK_COMMON:
11286 			convert_ctx_access = bpf_sock_convert_ctx_access;
11287 			break;
11288 		case PTR_TO_TCP_SOCK:
11289 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11290 			break;
11291 		case PTR_TO_XDP_SOCK:
11292 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11293 			break;
11294 		case PTR_TO_BTF_ID:
11295 			if (type == BPF_READ) {
11296 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11297 					BPF_SIZE((insn)->code);
11298 				env->prog->aux->num_exentries++;
11299 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11300 				verbose(env, "Writes through BTF pointers are not allowed\n");
11301 				return -EINVAL;
11302 			}
11303 			continue;
11304 		default:
11305 			continue;
11306 		}
11307 
11308 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11309 		size = BPF_LDST_BYTES(insn);
11310 
11311 		/* If the read access is a narrower load of the field,
11312 		 * convert to a 4/8-byte load, to minimum program type specific
11313 		 * convert_ctx_access changes. If conversion is successful,
11314 		 * we will apply proper mask to the result.
11315 		 */
11316 		is_narrower_load = size < ctx_field_size;
11317 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11318 		off = insn->off;
11319 		if (is_narrower_load) {
11320 			u8 size_code;
11321 
11322 			if (type == BPF_WRITE) {
11323 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11324 				return -EINVAL;
11325 			}
11326 
11327 			size_code = BPF_H;
11328 			if (ctx_field_size == 4)
11329 				size_code = BPF_W;
11330 			else if (ctx_field_size == 8)
11331 				size_code = BPF_DW;
11332 
11333 			insn->off = off & ~(size_default - 1);
11334 			insn->code = BPF_LDX | BPF_MEM | size_code;
11335 		}
11336 
11337 		target_size = 0;
11338 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11339 					 &target_size);
11340 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11341 		    (ctx_field_size && !target_size)) {
11342 			verbose(env, "bpf verifier is misconfigured\n");
11343 			return -EINVAL;
11344 		}
11345 
11346 		if (is_narrower_load && size < target_size) {
11347 			u8 shift = bpf_ctx_narrow_access_offset(
11348 				off, size, size_default) * 8;
11349 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11350 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11351 				return -EINVAL;
11352 			}
11353 			if (ctx_field_size <= 4) {
11354 				if (shift)
11355 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11356 									insn->dst_reg,
11357 									shift);
11358 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11359 								(1 << size * 8) - 1);
11360 			} else {
11361 				if (shift)
11362 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11363 									insn->dst_reg,
11364 									shift);
11365 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11366 								(1ULL << size * 8) - 1);
11367 			}
11368 		}
11369 
11370 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11371 		if (!new_prog)
11372 			return -ENOMEM;
11373 
11374 		delta += cnt - 1;
11375 
11376 		/* keep walking new program and skip insns we just inserted */
11377 		env->prog = new_prog;
11378 		insn      = new_prog->insnsi + i + delta;
11379 	}
11380 
11381 	return 0;
11382 }
11383 
jit_subprogs(struct bpf_verifier_env * env)11384 static int jit_subprogs(struct bpf_verifier_env *env)
11385 {
11386 	struct bpf_prog *prog = env->prog, **func, *tmp;
11387 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11388 	struct bpf_map *map_ptr;
11389 	struct bpf_insn *insn;
11390 	void *old_bpf_func;
11391 	int err, num_exentries;
11392 
11393 	if (env->subprog_cnt <= 1)
11394 		return 0;
11395 
11396 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11397 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11398 		    insn->src_reg != BPF_PSEUDO_CALL)
11399 			continue;
11400 		/* Upon error here we cannot fall back to interpreter but
11401 		 * need a hard reject of the program. Thus -EFAULT is
11402 		 * propagated in any case.
11403 		 */
11404 		subprog = find_subprog(env, i + insn->imm + 1);
11405 		if (subprog < 0) {
11406 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11407 				  i + insn->imm + 1);
11408 			return -EFAULT;
11409 		}
11410 		/* temporarily remember subprog id inside insn instead of
11411 		 * aux_data, since next loop will split up all insns into funcs
11412 		 */
11413 		insn->off = subprog;
11414 		/* remember original imm in case JIT fails and fallback
11415 		 * to interpreter will be needed
11416 		 */
11417 		env->insn_aux_data[i].call_imm = insn->imm;
11418 		/* point imm to __bpf_call_base+1 from JITs point of view */
11419 		insn->imm = 1;
11420 	}
11421 
11422 	err = bpf_prog_alloc_jited_linfo(prog);
11423 	if (err)
11424 		goto out_undo_insn;
11425 
11426 	err = -ENOMEM;
11427 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11428 	if (!func)
11429 		goto out_undo_insn;
11430 
11431 	for (i = 0; i < env->subprog_cnt; i++) {
11432 		subprog_start = subprog_end;
11433 		subprog_end = env->subprog_info[i + 1].start;
11434 
11435 		len = subprog_end - subprog_start;
11436 		/* BPF_PROG_RUN doesn't call subprogs directly,
11437 		 * hence main prog stats include the runtime of subprogs.
11438 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11439 		 * func[i]->aux->stats will never be accessed and stays NULL
11440 		 */
11441 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11442 		if (!func[i])
11443 			goto out_free;
11444 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11445 		       len * sizeof(struct bpf_insn));
11446 		func[i]->type = prog->type;
11447 		func[i]->len = len;
11448 		if (bpf_prog_calc_tag(func[i]))
11449 			goto out_free;
11450 		func[i]->is_func = 1;
11451 		func[i]->aux->func_idx = i;
11452 		/* Below members will be freed only at prog->aux */
11453 		func[i]->aux->btf = prog->aux->btf;
11454 		func[i]->aux->func_info = prog->aux->func_info;
11455 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11456 		func[i]->aux->poke_tab = prog->aux->poke_tab;
11457 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11458 
11459 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11460 			struct bpf_jit_poke_descriptor *poke;
11461 
11462 			poke = &prog->aux->poke_tab[j];
11463 			if (poke->insn_idx < subprog_end &&
11464 			    poke->insn_idx >= subprog_start)
11465 				poke->aux = func[i]->aux;
11466 		}
11467 
11468 		func[i]->aux->name[0] = 'F';
11469 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11470 		func[i]->jit_requested = 1;
11471 		func[i]->aux->linfo = prog->aux->linfo;
11472 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11473 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11474 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11475 		num_exentries = 0;
11476 		insn = func[i]->insnsi;
11477 		for (j = 0; j < func[i]->len; j++, insn++) {
11478 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11479 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11480 				num_exentries++;
11481 		}
11482 		func[i]->aux->num_exentries = num_exentries;
11483 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11484 		func[i] = bpf_int_jit_compile(func[i]);
11485 		if (!func[i]->jited) {
11486 			err = -ENOTSUPP;
11487 			goto out_free;
11488 		}
11489 		cond_resched();
11490 	}
11491 
11492 	/* at this point all bpf functions were successfully JITed
11493 	 * now populate all bpf_calls with correct addresses and
11494 	 * run last pass of JIT
11495 	 */
11496 	for (i = 0; i < env->subprog_cnt; i++) {
11497 		insn = func[i]->insnsi;
11498 		for (j = 0; j < func[i]->len; j++, insn++) {
11499 			if (insn->code != (BPF_JMP | BPF_CALL) ||
11500 			    insn->src_reg != BPF_PSEUDO_CALL)
11501 				continue;
11502 			subprog = insn->off;
11503 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11504 				    __bpf_call_base;
11505 		}
11506 
11507 		/* we use the aux data to keep a list of the start addresses
11508 		 * of the JITed images for each function in the program
11509 		 *
11510 		 * for some architectures, such as powerpc64, the imm field
11511 		 * might not be large enough to hold the offset of the start
11512 		 * address of the callee's JITed image from __bpf_call_base
11513 		 *
11514 		 * in such cases, we can lookup the start address of a callee
11515 		 * by using its subprog id, available from the off field of
11516 		 * the call instruction, as an index for this list
11517 		 */
11518 		func[i]->aux->func = func;
11519 		func[i]->aux->func_cnt = env->subprog_cnt;
11520 	}
11521 	for (i = 0; i < env->subprog_cnt; i++) {
11522 		old_bpf_func = func[i]->bpf_func;
11523 		tmp = bpf_int_jit_compile(func[i]);
11524 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11525 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11526 			err = -ENOTSUPP;
11527 			goto out_free;
11528 		}
11529 		cond_resched();
11530 	}
11531 
11532 	/* finally lock prog and jit images for all functions and
11533 	 * populate kallsysm
11534 	 */
11535 	for (i = 0; i < env->subprog_cnt; i++) {
11536 		bpf_prog_lock_ro(func[i]);
11537 		bpf_prog_kallsyms_add(func[i]);
11538 	}
11539 
11540 	/* Last step: make now unused interpreter insns from main
11541 	 * prog consistent for later dump requests, so they can
11542 	 * later look the same as if they were interpreted only.
11543 	 */
11544 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11545 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11546 		    insn->src_reg != BPF_PSEUDO_CALL)
11547 			continue;
11548 		insn->off = env->insn_aux_data[i].call_imm;
11549 		subprog = find_subprog(env, i + insn->off + 1);
11550 		insn->imm = subprog;
11551 	}
11552 
11553 	prog->jited = 1;
11554 	prog->bpf_func = func[0]->bpf_func;
11555 	prog->aux->func = func;
11556 	prog->aux->func_cnt = env->subprog_cnt;
11557 	bpf_prog_free_unused_jited_linfo(prog);
11558 	return 0;
11559 out_free:
11560 	/* We failed JIT'ing, so at this point we need to unregister poke
11561 	 * descriptors from subprogs, so that kernel is not attempting to
11562 	 * patch it anymore as we're freeing the subprog JIT memory.
11563 	 */
11564 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11565 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11566 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11567 	}
11568 	/* At this point we're guaranteed that poke descriptors are not
11569 	 * live anymore. We can just unlink its descriptor table as it's
11570 	 * released with the main prog.
11571 	 */
11572 	for (i = 0; i < env->subprog_cnt; i++) {
11573 		if (!func[i])
11574 			continue;
11575 		func[i]->aux->poke_tab = NULL;
11576 		bpf_jit_free(func[i]);
11577 	}
11578 	kfree(func);
11579 out_undo_insn:
11580 	/* cleanup main prog to be interpreted */
11581 	prog->jit_requested = 0;
11582 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11583 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11584 		    insn->src_reg != BPF_PSEUDO_CALL)
11585 			continue;
11586 		insn->off = 0;
11587 		insn->imm = env->insn_aux_data[i].call_imm;
11588 	}
11589 	bpf_prog_free_jited_linfo(prog);
11590 	return err;
11591 }
11592 
fixup_call_args(struct bpf_verifier_env * env)11593 static int fixup_call_args(struct bpf_verifier_env *env)
11594 {
11595 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11596 	struct bpf_prog *prog = env->prog;
11597 	struct bpf_insn *insn = prog->insnsi;
11598 	int i, depth;
11599 #endif
11600 	int err = 0;
11601 
11602 	if (env->prog->jit_requested &&
11603 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
11604 		err = jit_subprogs(env);
11605 		if (err == 0)
11606 			return 0;
11607 		if (err == -EFAULT)
11608 			return err;
11609 	}
11610 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11611 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11612 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
11613 		 * have to be rejected, since interpreter doesn't support them yet.
11614 		 */
11615 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11616 		return -EINVAL;
11617 	}
11618 	for (i = 0; i < prog->len; i++, insn++) {
11619 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11620 		    insn->src_reg != BPF_PSEUDO_CALL)
11621 			continue;
11622 		depth = get_callee_stack_depth(env, insn, i);
11623 		if (depth < 0)
11624 			return depth;
11625 		bpf_patch_call_args(insn, depth);
11626 	}
11627 	err = 0;
11628 #endif
11629 	return err;
11630 }
11631 
11632 /* fixup insn->imm field of bpf_call instructions
11633  * and inline eligible helpers as explicit sequence of BPF instructions
11634  *
11635  * this function is called after eBPF program passed verification
11636  */
fixup_bpf_calls(struct bpf_verifier_env * env)11637 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11638 {
11639 	struct bpf_prog *prog = env->prog;
11640 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
11641 	struct bpf_insn *insn = prog->insnsi;
11642 	const struct bpf_func_proto *fn;
11643 	const int insn_cnt = prog->len;
11644 	const struct bpf_map_ops *ops;
11645 	struct bpf_insn_aux_data *aux;
11646 	struct bpf_insn insn_buf[16];
11647 	struct bpf_prog *new_prog;
11648 	struct bpf_map *map_ptr;
11649 	int i, ret, cnt, delta = 0;
11650 
11651 	for (i = 0; i < insn_cnt; i++, insn++) {
11652 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11653 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11654 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11655 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11656 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11657 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11658 			struct bpf_insn *patchlet;
11659 			struct bpf_insn chk_and_div[] = {
11660 				/* [R,W]x div 0 -> 0 */
11661 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11662 					     BPF_JNE | BPF_K, insn->src_reg,
11663 					     0, 2, 0),
11664 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11665 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11666 				*insn,
11667 			};
11668 			struct bpf_insn chk_and_mod[] = {
11669 				/* [R,W]x mod 0 -> [R,W]x */
11670 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11671 					     BPF_JEQ | BPF_K, insn->src_reg,
11672 					     0, 1 + (is64 ? 0 : 1), 0),
11673 				*insn,
11674 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11675 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11676 			};
11677 
11678 			patchlet = isdiv ? chk_and_div : chk_and_mod;
11679 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11680 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11681 
11682 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11683 			if (!new_prog)
11684 				return -ENOMEM;
11685 
11686 			delta    += cnt - 1;
11687 			env->prog = prog = new_prog;
11688 			insn      = new_prog->insnsi + i + delta;
11689 			continue;
11690 		}
11691 
11692 		if (BPF_CLASS(insn->code) == BPF_LD &&
11693 		    (BPF_MODE(insn->code) == BPF_ABS ||
11694 		     BPF_MODE(insn->code) == BPF_IND)) {
11695 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
11696 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11697 				verbose(env, "bpf verifier is misconfigured\n");
11698 				return -EINVAL;
11699 			}
11700 
11701 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11702 			if (!new_prog)
11703 				return -ENOMEM;
11704 
11705 			delta    += cnt - 1;
11706 			env->prog = prog = new_prog;
11707 			insn      = new_prog->insnsi + i + delta;
11708 			continue;
11709 		}
11710 
11711 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11712 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11713 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11714 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11715 			struct bpf_insn insn_buf[16];
11716 			struct bpf_insn *patch = &insn_buf[0];
11717 			bool issrc, isneg, isimm;
11718 			u32 off_reg;
11719 
11720 			aux = &env->insn_aux_data[i + delta];
11721 			if (!aux->alu_state ||
11722 			    aux->alu_state == BPF_ALU_NON_POINTER)
11723 				continue;
11724 
11725 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11726 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11727 				BPF_ALU_SANITIZE_SRC;
11728 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11729 
11730 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11731 			if (isimm) {
11732 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11733 			} else {
11734 				if (isneg)
11735 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11736 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11737 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11738 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11739 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11740 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11741 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11742 			}
11743 			if (!issrc)
11744 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11745 			insn->src_reg = BPF_REG_AX;
11746 			if (isneg)
11747 				insn->code = insn->code == code_add ?
11748 					     code_sub : code_add;
11749 			*patch++ = *insn;
11750 			if (issrc && isneg && !isimm)
11751 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11752 			cnt = patch - insn_buf;
11753 
11754 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11755 			if (!new_prog)
11756 				return -ENOMEM;
11757 
11758 			delta    += cnt - 1;
11759 			env->prog = prog = new_prog;
11760 			insn      = new_prog->insnsi + i + delta;
11761 			continue;
11762 		}
11763 
11764 		if (insn->code != (BPF_JMP | BPF_CALL))
11765 			continue;
11766 		if (insn->src_reg == BPF_PSEUDO_CALL)
11767 			continue;
11768 
11769 		if (insn->imm == BPF_FUNC_get_route_realm)
11770 			prog->dst_needed = 1;
11771 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11772 			bpf_user_rnd_init_once();
11773 		if (insn->imm == BPF_FUNC_override_return)
11774 			prog->kprobe_override = 1;
11775 		if (insn->imm == BPF_FUNC_tail_call) {
11776 			/* If we tail call into other programs, we
11777 			 * cannot make any assumptions since they can
11778 			 * be replaced dynamically during runtime in
11779 			 * the program array.
11780 			 */
11781 			prog->cb_access = 1;
11782 			if (!allow_tail_call_in_subprogs(env))
11783 				prog->aux->stack_depth = MAX_BPF_STACK;
11784 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11785 
11786 			/* mark bpf_tail_call as different opcode to avoid
11787 			 * conditional branch in the interpeter for every normal
11788 			 * call and to prevent accidental JITing by JIT compiler
11789 			 * that doesn't support bpf_tail_call yet
11790 			 */
11791 			insn->imm = 0;
11792 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11793 
11794 			aux = &env->insn_aux_data[i + delta];
11795 			if (env->bpf_capable && !expect_blinding &&
11796 			    prog->jit_requested &&
11797 			    !bpf_map_key_poisoned(aux) &&
11798 			    !bpf_map_ptr_poisoned(aux) &&
11799 			    !bpf_map_ptr_unpriv(aux)) {
11800 				struct bpf_jit_poke_descriptor desc = {
11801 					.reason = BPF_POKE_REASON_TAIL_CALL,
11802 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11803 					.tail_call.key = bpf_map_key_immediate(aux),
11804 					.insn_idx = i + delta,
11805 				};
11806 
11807 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11808 				if (ret < 0) {
11809 					verbose(env, "adding tail call poke descriptor failed\n");
11810 					return ret;
11811 				}
11812 
11813 				insn->imm = ret + 1;
11814 				continue;
11815 			}
11816 
11817 			if (!bpf_map_ptr_unpriv(aux))
11818 				continue;
11819 
11820 			/* instead of changing every JIT dealing with tail_call
11821 			 * emit two extra insns:
11822 			 * if (index >= max_entries) goto out;
11823 			 * index &= array->index_mask;
11824 			 * to avoid out-of-bounds cpu speculation
11825 			 */
11826 			if (bpf_map_ptr_poisoned(aux)) {
11827 				verbose(env, "tail_call abusing map_ptr\n");
11828 				return -EINVAL;
11829 			}
11830 
11831 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11832 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11833 						  map_ptr->max_entries, 2);
11834 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11835 						    container_of(map_ptr,
11836 								 struct bpf_array,
11837 								 map)->index_mask);
11838 			insn_buf[2] = *insn;
11839 			cnt = 3;
11840 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11841 			if (!new_prog)
11842 				return -ENOMEM;
11843 
11844 			delta    += cnt - 1;
11845 			env->prog = prog = new_prog;
11846 			insn      = new_prog->insnsi + i + delta;
11847 			continue;
11848 		}
11849 
11850 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11851 		 * and other inlining handlers are currently limited to 64 bit
11852 		 * only.
11853 		 */
11854 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11855 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11856 		     insn->imm == BPF_FUNC_map_update_elem ||
11857 		     insn->imm == BPF_FUNC_map_delete_elem ||
11858 		     insn->imm == BPF_FUNC_map_push_elem   ||
11859 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11860 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11861 			aux = &env->insn_aux_data[i + delta];
11862 			if (bpf_map_ptr_poisoned(aux))
11863 				goto patch_call_imm;
11864 
11865 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11866 			ops = map_ptr->ops;
11867 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11868 			    ops->map_gen_lookup) {
11869 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11870 				if (cnt == -EOPNOTSUPP)
11871 					goto patch_map_ops_generic;
11872 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11873 					verbose(env, "bpf verifier is misconfigured\n");
11874 					return -EINVAL;
11875 				}
11876 
11877 				new_prog = bpf_patch_insn_data(env, i + delta,
11878 							       insn_buf, cnt);
11879 				if (!new_prog)
11880 					return -ENOMEM;
11881 
11882 				delta    += cnt - 1;
11883 				env->prog = prog = new_prog;
11884 				insn      = new_prog->insnsi + i + delta;
11885 				continue;
11886 			}
11887 
11888 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11889 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11890 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11891 				     (int (*)(struct bpf_map *map, void *key))NULL));
11892 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11893 				     (int (*)(struct bpf_map *map, void *key, void *value,
11894 					      u64 flags))NULL));
11895 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11896 				     (int (*)(struct bpf_map *map, void *value,
11897 					      u64 flags))NULL));
11898 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11899 				     (int (*)(struct bpf_map *map, void *value))NULL));
11900 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11901 				     (int (*)(struct bpf_map *map, void *value))NULL));
11902 patch_map_ops_generic:
11903 			switch (insn->imm) {
11904 			case BPF_FUNC_map_lookup_elem:
11905 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11906 					    __bpf_call_base;
11907 				continue;
11908 			case BPF_FUNC_map_update_elem:
11909 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11910 					    __bpf_call_base;
11911 				continue;
11912 			case BPF_FUNC_map_delete_elem:
11913 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11914 					    __bpf_call_base;
11915 				continue;
11916 			case BPF_FUNC_map_push_elem:
11917 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11918 					    __bpf_call_base;
11919 				continue;
11920 			case BPF_FUNC_map_pop_elem:
11921 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11922 					    __bpf_call_base;
11923 				continue;
11924 			case BPF_FUNC_map_peek_elem:
11925 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11926 					    __bpf_call_base;
11927 				continue;
11928 			}
11929 
11930 			goto patch_call_imm;
11931 		}
11932 
11933 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11934 		    insn->imm == BPF_FUNC_jiffies64) {
11935 			struct bpf_insn ld_jiffies_addr[2] = {
11936 				BPF_LD_IMM64(BPF_REG_0,
11937 					     (unsigned long)&jiffies),
11938 			};
11939 
11940 			insn_buf[0] = ld_jiffies_addr[0];
11941 			insn_buf[1] = ld_jiffies_addr[1];
11942 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11943 						  BPF_REG_0, 0);
11944 			cnt = 3;
11945 
11946 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11947 						       cnt);
11948 			if (!new_prog)
11949 				return -ENOMEM;
11950 
11951 			delta    += cnt - 1;
11952 			env->prog = prog = new_prog;
11953 			insn      = new_prog->insnsi + i + delta;
11954 			continue;
11955 		}
11956 
11957 patch_call_imm:
11958 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11959 		/* all functions that have prototype and verifier allowed
11960 		 * programs to call them, must be real in-kernel functions
11961 		 */
11962 		if (!fn->func) {
11963 			verbose(env,
11964 				"kernel subsystem misconfigured func %s#%d\n",
11965 				func_id_name(insn->imm), insn->imm);
11966 			return -EFAULT;
11967 		}
11968 		insn->imm = fn->func - __bpf_call_base;
11969 	}
11970 
11971 	/* Since poke tab is now finalized, publish aux to tracker. */
11972 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11973 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11974 		if (!map_ptr->ops->map_poke_track ||
11975 		    !map_ptr->ops->map_poke_untrack ||
11976 		    !map_ptr->ops->map_poke_run) {
11977 			verbose(env, "bpf verifier is misconfigured\n");
11978 			return -EINVAL;
11979 		}
11980 
11981 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11982 		if (ret < 0) {
11983 			verbose(env, "tracking tail call prog failed\n");
11984 			return ret;
11985 		}
11986 	}
11987 
11988 	return 0;
11989 }
11990 
free_states(struct bpf_verifier_env * env)11991 static void free_states(struct bpf_verifier_env *env)
11992 {
11993 	struct bpf_verifier_state_list *sl, *sln;
11994 	int i;
11995 
11996 	sl = env->free_list;
11997 	while (sl) {
11998 		sln = sl->next;
11999 		free_verifier_state(&sl->state, false);
12000 		kfree(sl);
12001 		sl = sln;
12002 	}
12003 	env->free_list = NULL;
12004 
12005 	if (!env->explored_states)
12006 		return;
12007 
12008 	for (i = 0; i < state_htab_size(env); i++) {
12009 		sl = env->explored_states[i];
12010 
12011 		while (sl) {
12012 			sln = sl->next;
12013 			free_verifier_state(&sl->state, false);
12014 			kfree(sl);
12015 			sl = sln;
12016 		}
12017 		env->explored_states[i] = NULL;
12018 	}
12019 }
12020 
do_check_common(struct bpf_verifier_env * env,int subprog)12021 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12022 {
12023 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12024 	struct bpf_verifier_state *state;
12025 	struct bpf_reg_state *regs;
12026 	int ret, i;
12027 
12028 	env->prev_linfo = NULL;
12029 	env->pass_cnt++;
12030 
12031 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12032 	if (!state)
12033 		return -ENOMEM;
12034 	state->curframe = 0;
12035 	state->speculative = false;
12036 	state->branches = 1;
12037 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12038 	if (!state->frame[0]) {
12039 		kfree(state);
12040 		return -ENOMEM;
12041 	}
12042 	env->cur_state = state;
12043 	init_func_state(env, state->frame[0],
12044 			BPF_MAIN_FUNC /* callsite */,
12045 			0 /* frameno */,
12046 			subprog);
12047 
12048 	state->first_insn_idx = env->subprog_info[subprog].start;
12049 	state->last_insn_idx = -1;
12050 
12051 	regs = state->frame[state->curframe]->regs;
12052 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12053 		ret = btf_prepare_func_args(env, subprog, regs);
12054 		if (ret)
12055 			goto out;
12056 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12057 			if (regs[i].type == PTR_TO_CTX)
12058 				mark_reg_known_zero(env, regs, i);
12059 			else if (regs[i].type == SCALAR_VALUE)
12060 				mark_reg_unknown(env, regs, i);
12061 		}
12062 	} else {
12063 		/* 1st arg to a function */
12064 		regs[BPF_REG_1].type = PTR_TO_CTX;
12065 		mark_reg_known_zero(env, regs, BPF_REG_1);
12066 		ret = btf_check_func_arg_match(env, subprog, regs);
12067 		if (ret == -EFAULT)
12068 			/* unlikely verifier bug. abort.
12069 			 * ret == 0 and ret < 0 are sadly acceptable for
12070 			 * main() function due to backward compatibility.
12071 			 * Like socket filter program may be written as:
12072 			 * int bpf_prog(struct pt_regs *ctx)
12073 			 * and never dereference that ctx in the program.
12074 			 * 'struct pt_regs' is a type mismatch for socket
12075 			 * filter that should be using 'struct __sk_buff'.
12076 			 */
12077 			goto out;
12078 	}
12079 
12080 	ret = do_check(env);
12081 out:
12082 	/* check for NULL is necessary, since cur_state can be freed inside
12083 	 * do_check() under memory pressure.
12084 	 */
12085 	if (env->cur_state) {
12086 		free_verifier_state(env->cur_state, true);
12087 		env->cur_state = NULL;
12088 	}
12089 	while (!pop_stack(env, NULL, NULL, false));
12090 	if (!ret && pop_log)
12091 		bpf_vlog_reset(&env->log, 0);
12092 	free_states(env);
12093 	return ret;
12094 }
12095 
12096 /* Verify all global functions in a BPF program one by one based on their BTF.
12097  * All global functions must pass verification. Otherwise the whole program is rejected.
12098  * Consider:
12099  * int bar(int);
12100  * int foo(int f)
12101  * {
12102  *    return bar(f);
12103  * }
12104  * int bar(int b)
12105  * {
12106  *    ...
12107  * }
12108  * foo() will be verified first for R1=any_scalar_value. During verification it
12109  * will be assumed that bar() already verified successfully and call to bar()
12110  * from foo() will be checked for type match only. Later bar() will be verified
12111  * independently to check that it's safe for R1=any_scalar_value.
12112  */
do_check_subprogs(struct bpf_verifier_env * env)12113 static int do_check_subprogs(struct bpf_verifier_env *env)
12114 {
12115 	struct bpf_prog_aux *aux = env->prog->aux;
12116 	int i, ret;
12117 
12118 	if (!aux->func_info)
12119 		return 0;
12120 
12121 	for (i = 1; i < env->subprog_cnt; i++) {
12122 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12123 			continue;
12124 		env->insn_idx = env->subprog_info[i].start;
12125 		WARN_ON_ONCE(env->insn_idx == 0);
12126 		ret = do_check_common(env, i);
12127 		if (ret) {
12128 			return ret;
12129 		} else if (env->log.level & BPF_LOG_LEVEL) {
12130 			verbose(env,
12131 				"Func#%d is safe for any args that match its prototype\n",
12132 				i);
12133 		}
12134 	}
12135 	return 0;
12136 }
12137 
do_check_main(struct bpf_verifier_env * env)12138 static int do_check_main(struct bpf_verifier_env *env)
12139 {
12140 	int ret;
12141 
12142 	env->insn_idx = 0;
12143 	ret = do_check_common(env, 0);
12144 	if (!ret)
12145 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12146 	return ret;
12147 }
12148 
12149 
print_verification_stats(struct bpf_verifier_env * env)12150 static void print_verification_stats(struct bpf_verifier_env *env)
12151 {
12152 	int i;
12153 
12154 	if (env->log.level & BPF_LOG_STATS) {
12155 		verbose(env, "verification time %lld usec\n",
12156 			div_u64(env->verification_time, 1000));
12157 		verbose(env, "stack depth ");
12158 		for (i = 0; i < env->subprog_cnt; i++) {
12159 			u32 depth = env->subprog_info[i].stack_depth;
12160 
12161 			verbose(env, "%d", depth);
12162 			if (i + 1 < env->subprog_cnt)
12163 				verbose(env, "+");
12164 		}
12165 		verbose(env, "\n");
12166 	}
12167 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12168 		"total_states %d peak_states %d mark_read %d\n",
12169 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12170 		env->max_states_per_insn, env->total_states,
12171 		env->peak_states, env->longest_mark_read_walk);
12172 }
12173 
check_struct_ops_btf_id(struct bpf_verifier_env * env)12174 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12175 {
12176 	const struct btf_type *t, *func_proto;
12177 	const struct bpf_struct_ops *st_ops;
12178 	const struct btf_member *member;
12179 	struct bpf_prog *prog = env->prog;
12180 	u32 btf_id, member_idx;
12181 	const char *mname;
12182 
12183 	if (!prog->gpl_compatible) {
12184 		verbose(env, "struct ops programs must have a GPL compatible license\n");
12185 		return -EINVAL;
12186 	}
12187 
12188 	btf_id = prog->aux->attach_btf_id;
12189 	st_ops = bpf_struct_ops_find(btf_id);
12190 	if (!st_ops) {
12191 		verbose(env, "attach_btf_id %u is not a supported struct\n",
12192 			btf_id);
12193 		return -ENOTSUPP;
12194 	}
12195 
12196 	t = st_ops->type;
12197 	member_idx = prog->expected_attach_type;
12198 	if (member_idx >= btf_type_vlen(t)) {
12199 		verbose(env, "attach to invalid member idx %u of struct %s\n",
12200 			member_idx, st_ops->name);
12201 		return -EINVAL;
12202 	}
12203 
12204 	member = &btf_type_member(t)[member_idx];
12205 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12206 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12207 					       NULL);
12208 	if (!func_proto) {
12209 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12210 			mname, member_idx, st_ops->name);
12211 		return -EINVAL;
12212 	}
12213 
12214 	if (st_ops->check_member) {
12215 		int err = st_ops->check_member(t, member);
12216 
12217 		if (err) {
12218 			verbose(env, "attach to unsupported member %s of struct %s\n",
12219 				mname, st_ops->name);
12220 			return err;
12221 		}
12222 	}
12223 
12224 	prog->aux->attach_func_proto = func_proto;
12225 	prog->aux->attach_func_name = mname;
12226 	env->ops = st_ops->verifier_ops;
12227 
12228 	return 0;
12229 }
12230 #define SECURITY_PREFIX "security_"
12231 
check_attach_modify_return(unsigned long addr,const char * func_name)12232 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12233 {
12234 	if (within_error_injection_list(addr) ||
12235 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12236 		return 0;
12237 
12238 	return -EINVAL;
12239 }
12240 
12241 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12242 BTF_SET_START(btf_sleepable_lsm_hooks)
12243 #ifdef CONFIG_BPF_LSM
BTF_ID(func,bpf_lsm_bprm_committed_creds)12244 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12245 #else
12246 BTF_ID_UNUSED
12247 #endif
12248 BTF_SET_END(btf_sleepable_lsm_hooks)
12249 
12250 static int check_sleepable_lsm_hook(u32 btf_id)
12251 {
12252 	return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12253 }
12254 
12255 /* list of non-sleepable functions that are otherwise on
12256  * ALLOW_ERROR_INJECTION list
12257  */
12258 BTF_SET_START(btf_non_sleepable_error_inject)
12259 /* Three functions below can be called from sleepable and non-sleepable context.
12260  * Assume non-sleepable from bpf safety point of view.
12261  */
BTF_ID(func,__add_to_page_cache_locked)12262 BTF_ID(func, __add_to_page_cache_locked)
12263 BTF_ID(func, should_fail_alloc_page)
12264 BTF_ID(func, should_failslab)
12265 BTF_SET_END(btf_non_sleepable_error_inject)
12266 
12267 static int check_non_sleepable_error_inject(u32 btf_id)
12268 {
12269 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12270 }
12271 
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)12272 int bpf_check_attach_target(struct bpf_verifier_log *log,
12273 			    const struct bpf_prog *prog,
12274 			    const struct bpf_prog *tgt_prog,
12275 			    u32 btf_id,
12276 			    struct bpf_attach_target_info *tgt_info)
12277 {
12278 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12279 	const char prefix[] = "btf_trace_";
12280 	int ret = 0, subprog = -1, i;
12281 	const struct btf_type *t;
12282 	bool conservative = true;
12283 	const char *tname;
12284 	struct btf *btf;
12285 	long addr = 0;
12286 
12287 	if (!btf_id) {
12288 		bpf_log(log, "Tracing programs must provide btf_id\n");
12289 		return -EINVAL;
12290 	}
12291 	btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12292 	if (!btf) {
12293 		bpf_log(log,
12294 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12295 		return -EINVAL;
12296 	}
12297 	t = btf_type_by_id(btf, btf_id);
12298 	if (!t) {
12299 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12300 		return -EINVAL;
12301 	}
12302 	tname = btf_name_by_offset(btf, t->name_off);
12303 	if (!tname) {
12304 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12305 		return -EINVAL;
12306 	}
12307 	if (tgt_prog) {
12308 		struct bpf_prog_aux *aux = tgt_prog->aux;
12309 
12310 		for (i = 0; i < aux->func_info_cnt; i++)
12311 			if (aux->func_info[i].type_id == btf_id) {
12312 				subprog = i;
12313 				break;
12314 			}
12315 		if (subprog == -1) {
12316 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12317 			return -EINVAL;
12318 		}
12319 		conservative = aux->func_info_aux[subprog].unreliable;
12320 		if (prog_extension) {
12321 			if (conservative) {
12322 				bpf_log(log,
12323 					"Cannot replace static functions\n");
12324 				return -EINVAL;
12325 			}
12326 			if (!prog->jit_requested) {
12327 				bpf_log(log,
12328 					"Extension programs should be JITed\n");
12329 				return -EINVAL;
12330 			}
12331 		}
12332 		if (!tgt_prog->jited) {
12333 			bpf_log(log, "Can attach to only JITed progs\n");
12334 			return -EINVAL;
12335 		}
12336 		if (tgt_prog->type == prog->type) {
12337 			/* Cannot fentry/fexit another fentry/fexit program.
12338 			 * Cannot attach program extension to another extension.
12339 			 * It's ok to attach fentry/fexit to extension program.
12340 			 */
12341 			bpf_log(log, "Cannot recursively attach\n");
12342 			return -EINVAL;
12343 		}
12344 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12345 		    prog_extension &&
12346 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12347 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12348 			/* Program extensions can extend all program types
12349 			 * except fentry/fexit. The reason is the following.
12350 			 * The fentry/fexit programs are used for performance
12351 			 * analysis, stats and can be attached to any program
12352 			 * type except themselves. When extension program is
12353 			 * replacing XDP function it is necessary to allow
12354 			 * performance analysis of all functions. Both original
12355 			 * XDP program and its program extension. Hence
12356 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12357 			 * allowed. If extending of fentry/fexit was allowed it
12358 			 * would be possible to create long call chain
12359 			 * fentry->extension->fentry->extension beyond
12360 			 * reasonable stack size. Hence extending fentry is not
12361 			 * allowed.
12362 			 */
12363 			bpf_log(log, "Cannot extend fentry/fexit\n");
12364 			return -EINVAL;
12365 		}
12366 	} else {
12367 		if (prog_extension) {
12368 			bpf_log(log, "Cannot replace kernel functions\n");
12369 			return -EINVAL;
12370 		}
12371 	}
12372 
12373 	switch (prog->expected_attach_type) {
12374 	case BPF_TRACE_RAW_TP:
12375 		if (tgt_prog) {
12376 			bpf_log(log,
12377 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12378 			return -EINVAL;
12379 		}
12380 		if (!btf_type_is_typedef(t)) {
12381 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12382 				btf_id);
12383 			return -EINVAL;
12384 		}
12385 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12386 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12387 				btf_id, tname);
12388 			return -EINVAL;
12389 		}
12390 		tname += sizeof(prefix) - 1;
12391 		t = btf_type_by_id(btf, t->type);
12392 		if (!btf_type_is_ptr(t))
12393 			/* should never happen in valid vmlinux build */
12394 			return -EINVAL;
12395 		t = btf_type_by_id(btf, t->type);
12396 		if (!btf_type_is_func_proto(t))
12397 			/* should never happen in valid vmlinux build */
12398 			return -EINVAL;
12399 
12400 		break;
12401 	case BPF_TRACE_ITER:
12402 		if (!btf_type_is_func(t)) {
12403 			bpf_log(log, "attach_btf_id %u is not a function\n",
12404 				btf_id);
12405 			return -EINVAL;
12406 		}
12407 		t = btf_type_by_id(btf, t->type);
12408 		if (!btf_type_is_func_proto(t))
12409 			return -EINVAL;
12410 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12411 		if (ret)
12412 			return ret;
12413 		break;
12414 	default:
12415 		if (!prog_extension)
12416 			return -EINVAL;
12417 		fallthrough;
12418 	case BPF_MODIFY_RETURN:
12419 	case BPF_LSM_MAC:
12420 	case BPF_TRACE_FENTRY:
12421 	case BPF_TRACE_FEXIT:
12422 		if (!btf_type_is_func(t)) {
12423 			bpf_log(log, "attach_btf_id %u is not a function\n",
12424 				btf_id);
12425 			return -EINVAL;
12426 		}
12427 		if (prog_extension &&
12428 		    btf_check_type_match(log, prog, btf, t))
12429 			return -EINVAL;
12430 		t = btf_type_by_id(btf, t->type);
12431 		if (!btf_type_is_func_proto(t))
12432 			return -EINVAL;
12433 
12434 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12435 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12436 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12437 			return -EINVAL;
12438 
12439 		if (tgt_prog && conservative)
12440 			t = NULL;
12441 
12442 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12443 		if (ret < 0)
12444 			return ret;
12445 
12446 		if (tgt_prog) {
12447 			if (subprog == 0)
12448 				addr = (long) tgt_prog->bpf_func;
12449 			else
12450 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12451 		} else {
12452 			addr = kallsyms_lookup_name(tname);
12453 			if (!addr) {
12454 				bpf_log(log,
12455 					"The address of function %s cannot be found\n",
12456 					tname);
12457 				return -ENOENT;
12458 			}
12459 		}
12460 
12461 		if (prog->aux->sleepable) {
12462 			ret = -EINVAL;
12463 			switch (prog->type) {
12464 			case BPF_PROG_TYPE_TRACING:
12465 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12466 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12467 				 */
12468 				if (!check_non_sleepable_error_inject(btf_id) &&
12469 				    within_error_injection_list(addr))
12470 					ret = 0;
12471 				break;
12472 			case BPF_PROG_TYPE_LSM:
12473 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
12474 				 * Only some of them are sleepable.
12475 				 */
12476 				if (check_sleepable_lsm_hook(btf_id))
12477 					ret = 0;
12478 				break;
12479 			default:
12480 				break;
12481 			}
12482 			if (ret) {
12483 				bpf_log(log, "%s is not sleepable\n", tname);
12484 				return ret;
12485 			}
12486 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12487 			if (tgt_prog) {
12488 				bpf_log(log, "can't modify return codes of BPF programs\n");
12489 				return -EINVAL;
12490 			}
12491 			ret = check_attach_modify_return(addr, tname);
12492 			if (ret) {
12493 				bpf_log(log, "%s() is not modifiable\n", tname);
12494 				return ret;
12495 			}
12496 		}
12497 
12498 		break;
12499 	}
12500 	tgt_info->tgt_addr = addr;
12501 	tgt_info->tgt_name = tname;
12502 	tgt_info->tgt_type = t;
12503 	return 0;
12504 }
12505 
check_attach_btf_id(struct bpf_verifier_env * env)12506 static int check_attach_btf_id(struct bpf_verifier_env *env)
12507 {
12508 	struct bpf_prog *prog = env->prog;
12509 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12510 	struct bpf_attach_target_info tgt_info = {};
12511 	u32 btf_id = prog->aux->attach_btf_id;
12512 	struct bpf_trampoline *tr;
12513 	int ret;
12514 	u64 key;
12515 
12516 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12517 	    prog->type != BPF_PROG_TYPE_LSM) {
12518 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12519 		return -EINVAL;
12520 	}
12521 
12522 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12523 		return check_struct_ops_btf_id(env);
12524 
12525 	if (prog->type != BPF_PROG_TYPE_TRACING &&
12526 	    prog->type != BPF_PROG_TYPE_LSM &&
12527 	    prog->type != BPF_PROG_TYPE_EXT)
12528 		return 0;
12529 
12530 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12531 	if (ret)
12532 		return ret;
12533 
12534 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12535 		/* to make freplace equivalent to their targets, they need to
12536 		 * inherit env->ops and expected_attach_type for the rest of the
12537 		 * verification
12538 		 */
12539 		env->ops = bpf_verifier_ops[tgt_prog->type];
12540 		prog->expected_attach_type = tgt_prog->expected_attach_type;
12541 	}
12542 
12543 	/* store info about the attachment target that will be used later */
12544 	prog->aux->attach_func_proto = tgt_info.tgt_type;
12545 	prog->aux->attach_func_name = tgt_info.tgt_name;
12546 
12547 	if (tgt_prog) {
12548 		prog->aux->saved_dst_prog_type = tgt_prog->type;
12549 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12550 	}
12551 
12552 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12553 		prog->aux->attach_btf_trace = true;
12554 		return 0;
12555 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12556 		if (!bpf_iter_prog_supported(prog))
12557 			return -EINVAL;
12558 		return 0;
12559 	}
12560 
12561 	if (prog->type == BPF_PROG_TYPE_LSM) {
12562 		ret = bpf_lsm_verify_prog(&env->log, prog);
12563 		if (ret < 0)
12564 			return ret;
12565 	}
12566 
12567 	key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12568 	tr = bpf_trampoline_get(key, &tgt_info);
12569 	if (!tr)
12570 		return -ENOMEM;
12571 
12572 	prog->aux->dst_trampoline = tr;
12573 	return 0;
12574 }
12575 
bpf_get_btf_vmlinux(void)12576 struct btf *bpf_get_btf_vmlinux(void)
12577 {
12578 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12579 		mutex_lock(&bpf_verifier_lock);
12580 		if (!btf_vmlinux)
12581 			btf_vmlinux = btf_parse_vmlinux();
12582 		mutex_unlock(&bpf_verifier_lock);
12583 	}
12584 	return btf_vmlinux;
12585 }
12586 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)12587 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12588 	      union bpf_attr __user *uattr)
12589 {
12590 	u64 start_time = ktime_get_ns();
12591 	struct bpf_verifier_env *env;
12592 	struct bpf_verifier_log *log;
12593 	int i, len, ret = -EINVAL;
12594 	bool is_priv;
12595 
12596 	/* no program is valid */
12597 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12598 		return -EINVAL;
12599 
12600 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
12601 	 * allocate/free it every time bpf_check() is called
12602 	 */
12603 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12604 	if (!env)
12605 		return -ENOMEM;
12606 	log = &env->log;
12607 
12608 	len = (*prog)->len;
12609 	env->insn_aux_data =
12610 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12611 	ret = -ENOMEM;
12612 	if (!env->insn_aux_data)
12613 		goto err_free_env;
12614 	for (i = 0; i < len; i++)
12615 		env->insn_aux_data[i].orig_idx = i;
12616 	env->prog = *prog;
12617 	env->ops = bpf_verifier_ops[env->prog->type];
12618 	is_priv = bpf_capable();
12619 
12620 	bpf_get_btf_vmlinux();
12621 
12622 	/* grab the mutex to protect few globals used by verifier */
12623 	if (!is_priv)
12624 		mutex_lock(&bpf_verifier_lock);
12625 
12626 	if (attr->log_level || attr->log_buf || attr->log_size) {
12627 		/* user requested verbose verifier output
12628 		 * and supplied buffer to store the verification trace
12629 		 */
12630 		log->level = attr->log_level;
12631 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12632 		log->len_total = attr->log_size;
12633 
12634 		/* log attributes have to be sane */
12635 		if (!bpf_verifier_log_attr_valid(log)) {
12636 			ret = -EINVAL;
12637 			goto err_unlock;
12638 		}
12639 	}
12640 
12641 	if (IS_ERR(btf_vmlinux)) {
12642 		/* Either gcc or pahole or kernel are broken. */
12643 		verbose(env, "in-kernel BTF is malformed\n");
12644 		ret = PTR_ERR(btf_vmlinux);
12645 		goto skip_full_check;
12646 	}
12647 
12648 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12649 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12650 		env->strict_alignment = true;
12651 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12652 		env->strict_alignment = false;
12653 
12654 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12655 	env->allow_uninit_stack = bpf_allow_uninit_stack();
12656 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12657 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
12658 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
12659 	env->bpf_capable = bpf_capable();
12660 
12661 	if (is_priv)
12662 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12663 
12664 	env->explored_states = kvcalloc(state_htab_size(env),
12665 				       sizeof(struct bpf_verifier_state_list *),
12666 				       GFP_USER);
12667 	ret = -ENOMEM;
12668 	if (!env->explored_states)
12669 		goto skip_full_check;
12670 
12671 	ret = check_subprogs(env);
12672 	if (ret < 0)
12673 		goto skip_full_check;
12674 
12675 	ret = check_btf_info(env, attr, uattr);
12676 	if (ret < 0)
12677 		goto skip_full_check;
12678 
12679 	ret = check_attach_btf_id(env);
12680 	if (ret)
12681 		goto skip_full_check;
12682 
12683 	ret = resolve_pseudo_ldimm64(env);
12684 	if (ret < 0)
12685 		goto skip_full_check;
12686 
12687 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
12688 		ret = bpf_prog_offload_verifier_prep(env->prog);
12689 		if (ret)
12690 			goto skip_full_check;
12691 	}
12692 
12693 	ret = check_cfg(env);
12694 	if (ret < 0)
12695 		goto skip_full_check;
12696 
12697 	ret = do_check_subprogs(env);
12698 	ret = ret ?: do_check_main(env);
12699 
12700 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12701 		ret = bpf_prog_offload_finalize(env);
12702 
12703 skip_full_check:
12704 	kvfree(env->explored_states);
12705 
12706 	if (ret == 0)
12707 		ret = check_max_stack_depth(env);
12708 
12709 	/* instruction rewrites happen after this point */
12710 	if (is_priv) {
12711 		if (ret == 0)
12712 			opt_hard_wire_dead_code_branches(env);
12713 		if (ret == 0)
12714 			ret = opt_remove_dead_code(env);
12715 		if (ret == 0)
12716 			ret = opt_remove_nops(env);
12717 	} else {
12718 		if (ret == 0)
12719 			sanitize_dead_code(env);
12720 	}
12721 
12722 	if (ret == 0)
12723 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12724 		ret = convert_ctx_accesses(env);
12725 
12726 	if (ret == 0)
12727 		ret = fixup_bpf_calls(env);
12728 
12729 	/* do 32-bit optimization after insn patching has done so those patched
12730 	 * insns could be handled correctly.
12731 	 */
12732 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12733 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12734 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12735 								     : false;
12736 	}
12737 
12738 	if (ret == 0)
12739 		ret = fixup_call_args(env);
12740 
12741 	env->verification_time = ktime_get_ns() - start_time;
12742 	print_verification_stats(env);
12743 
12744 	if (log->level && bpf_verifier_log_full(log))
12745 		ret = -ENOSPC;
12746 	if (log->level && !log->ubuf) {
12747 		ret = -EFAULT;
12748 		goto err_release_maps;
12749 	}
12750 
12751 	if (ret == 0 && env->used_map_cnt) {
12752 		/* if program passed verifier, update used_maps in bpf_prog_info */
12753 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12754 							  sizeof(env->used_maps[0]),
12755 							  GFP_KERNEL);
12756 
12757 		if (!env->prog->aux->used_maps) {
12758 			ret = -ENOMEM;
12759 			goto err_release_maps;
12760 		}
12761 
12762 		memcpy(env->prog->aux->used_maps, env->used_maps,
12763 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12764 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12765 
12766 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12767 		 * bpf_ld_imm64 instructions
12768 		 */
12769 		convert_pseudo_ld_imm64(env);
12770 	}
12771 
12772 	if (ret == 0)
12773 		adjust_btf_func(env);
12774 
12775 err_release_maps:
12776 	if (!env->prog->aux->used_maps)
12777 		/* if we didn't copy map pointers into bpf_prog_info, release
12778 		 * them now. Otherwise free_used_maps() will release them.
12779 		 */
12780 		release_maps(env);
12781 
12782 	/* extension progs temporarily inherit the attach_type of their targets
12783 	   for verification purposes, so set it back to zero before returning
12784 	 */
12785 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12786 		env->prog->expected_attach_type = 0;
12787 
12788 	*prog = env->prog;
12789 err_unlock:
12790 	if (!is_priv)
12791 		mutex_unlock(&bpf_verifier_lock);
12792 	vfree(env->insn_aux_data);
12793 err_free_env:
12794 	kfree(env);
12795 	return ret;
12796 }
12797