• 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 		err = mark_chain_precision(env, regno);
4925 		if (err)
4926 			return err;
4927 	} else if (arg_type_is_int_ptr(arg_type)) {
4928 		int size = int_ptr_type_to_size(arg_type);
4929 
4930 		err = check_helper_mem_access(env, regno, size, false, meta);
4931 		if (err)
4932 			return err;
4933 		err = check_ptr_alignment(env, reg, 0, size, true);
4934 	}
4935 
4936 	return err;
4937 }
4938 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)4939 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4940 {
4941 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
4942 	enum bpf_prog_type type = resolve_prog_type(env->prog);
4943 
4944 	if (func_id != BPF_FUNC_map_update_elem)
4945 		return false;
4946 
4947 	/* It's not possible to get access to a locked struct sock in these
4948 	 * contexts, so updating is safe.
4949 	 */
4950 	switch (type) {
4951 	case BPF_PROG_TYPE_TRACING:
4952 		if (eatype == BPF_TRACE_ITER)
4953 			return true;
4954 		break;
4955 	case BPF_PROG_TYPE_SOCKET_FILTER:
4956 	case BPF_PROG_TYPE_SCHED_CLS:
4957 	case BPF_PROG_TYPE_SCHED_ACT:
4958 	case BPF_PROG_TYPE_XDP:
4959 	case BPF_PROG_TYPE_SK_REUSEPORT:
4960 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4961 	case BPF_PROG_TYPE_SK_LOOKUP:
4962 		return true;
4963 	default:
4964 		break;
4965 	}
4966 
4967 	verbose(env, "cannot update sockmap in this context\n");
4968 	return false;
4969 }
4970 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)4971 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4972 {
4973 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4974 }
4975 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)4976 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4977 					struct bpf_map *map, int func_id)
4978 {
4979 	if (!map)
4980 		return 0;
4981 
4982 	/* We need a two way check, first is from map perspective ... */
4983 	switch (map->map_type) {
4984 	case BPF_MAP_TYPE_PROG_ARRAY:
4985 		if (func_id != BPF_FUNC_tail_call)
4986 			goto error;
4987 		break;
4988 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4989 		if (func_id != BPF_FUNC_perf_event_read &&
4990 		    func_id != BPF_FUNC_perf_event_output &&
4991 		    func_id != BPF_FUNC_skb_output &&
4992 		    func_id != BPF_FUNC_perf_event_read_value &&
4993 		    func_id != BPF_FUNC_xdp_output)
4994 			goto error;
4995 		break;
4996 	case BPF_MAP_TYPE_RINGBUF:
4997 		if (func_id != BPF_FUNC_ringbuf_output &&
4998 		    func_id != BPF_FUNC_ringbuf_reserve &&
4999 		    func_id != BPF_FUNC_ringbuf_query)
5000 			goto error;
5001 		break;
5002 	case BPF_MAP_TYPE_STACK_TRACE:
5003 		if (func_id != BPF_FUNC_get_stackid)
5004 			goto error;
5005 		break;
5006 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5007 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5008 		    func_id != BPF_FUNC_current_task_under_cgroup)
5009 			goto error;
5010 		break;
5011 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5012 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5013 		if (func_id != BPF_FUNC_get_local_storage)
5014 			goto error;
5015 		break;
5016 	case BPF_MAP_TYPE_DEVMAP:
5017 	case BPF_MAP_TYPE_DEVMAP_HASH:
5018 		if (func_id != BPF_FUNC_redirect_map &&
5019 		    func_id != BPF_FUNC_map_lookup_elem)
5020 			goto error;
5021 		break;
5022 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5023 	 * appear.
5024 	 */
5025 	case BPF_MAP_TYPE_CPUMAP:
5026 		if (func_id != BPF_FUNC_redirect_map)
5027 			goto error;
5028 		break;
5029 	case BPF_MAP_TYPE_XSKMAP:
5030 		if (func_id != BPF_FUNC_redirect_map &&
5031 		    func_id != BPF_FUNC_map_lookup_elem)
5032 			goto error;
5033 		break;
5034 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5035 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5036 		if (func_id != BPF_FUNC_map_lookup_elem)
5037 			goto error;
5038 		break;
5039 	case BPF_MAP_TYPE_SOCKMAP:
5040 		if (func_id != BPF_FUNC_sk_redirect_map &&
5041 		    func_id != BPF_FUNC_sock_map_update &&
5042 		    func_id != BPF_FUNC_map_delete_elem &&
5043 		    func_id != BPF_FUNC_msg_redirect_map &&
5044 		    func_id != BPF_FUNC_sk_select_reuseport &&
5045 		    func_id != BPF_FUNC_map_lookup_elem &&
5046 		    !may_update_sockmap(env, func_id))
5047 			goto error;
5048 		break;
5049 	case BPF_MAP_TYPE_SOCKHASH:
5050 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5051 		    func_id != BPF_FUNC_sock_hash_update &&
5052 		    func_id != BPF_FUNC_map_delete_elem &&
5053 		    func_id != BPF_FUNC_msg_redirect_hash &&
5054 		    func_id != BPF_FUNC_sk_select_reuseport &&
5055 		    func_id != BPF_FUNC_map_lookup_elem &&
5056 		    !may_update_sockmap(env, func_id))
5057 			goto error;
5058 		break;
5059 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5060 		if (func_id != BPF_FUNC_sk_select_reuseport)
5061 			goto error;
5062 		break;
5063 	case BPF_MAP_TYPE_QUEUE:
5064 	case BPF_MAP_TYPE_STACK:
5065 		if (func_id != BPF_FUNC_map_peek_elem &&
5066 		    func_id != BPF_FUNC_map_pop_elem &&
5067 		    func_id != BPF_FUNC_map_push_elem)
5068 			goto error;
5069 		break;
5070 	case BPF_MAP_TYPE_SK_STORAGE:
5071 		if (func_id != BPF_FUNC_sk_storage_get &&
5072 		    func_id != BPF_FUNC_sk_storage_delete)
5073 			goto error;
5074 		break;
5075 	case BPF_MAP_TYPE_INODE_STORAGE:
5076 		if (func_id != BPF_FUNC_inode_storage_get &&
5077 		    func_id != BPF_FUNC_inode_storage_delete)
5078 			goto error;
5079 		break;
5080 	default:
5081 		break;
5082 	}
5083 
5084 	/* ... and second from the function itself. */
5085 	switch (func_id) {
5086 	case BPF_FUNC_tail_call:
5087 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5088 			goto error;
5089 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5090 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5091 			return -EINVAL;
5092 		}
5093 		break;
5094 	case BPF_FUNC_perf_event_read:
5095 	case BPF_FUNC_perf_event_output:
5096 	case BPF_FUNC_perf_event_read_value:
5097 	case BPF_FUNC_skb_output:
5098 	case BPF_FUNC_xdp_output:
5099 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5100 			goto error;
5101 		break;
5102 	case BPF_FUNC_ringbuf_output:
5103 	case BPF_FUNC_ringbuf_reserve:
5104 	case BPF_FUNC_ringbuf_query:
5105 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5106 			goto error;
5107 		break;
5108 	case BPF_FUNC_get_stackid:
5109 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5110 			goto error;
5111 		break;
5112 	case BPF_FUNC_current_task_under_cgroup:
5113 	case BPF_FUNC_skb_under_cgroup:
5114 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5115 			goto error;
5116 		break;
5117 	case BPF_FUNC_redirect_map:
5118 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5119 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5120 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5121 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5122 			goto error;
5123 		break;
5124 	case BPF_FUNC_sk_redirect_map:
5125 	case BPF_FUNC_msg_redirect_map:
5126 	case BPF_FUNC_sock_map_update:
5127 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5128 			goto error;
5129 		break;
5130 	case BPF_FUNC_sk_redirect_hash:
5131 	case BPF_FUNC_msg_redirect_hash:
5132 	case BPF_FUNC_sock_hash_update:
5133 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5134 			goto error;
5135 		break;
5136 	case BPF_FUNC_get_local_storage:
5137 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5138 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5139 			goto error;
5140 		break;
5141 	case BPF_FUNC_sk_select_reuseport:
5142 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5143 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5144 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5145 			goto error;
5146 		break;
5147 	case BPF_FUNC_map_peek_elem:
5148 	case BPF_FUNC_map_pop_elem:
5149 	case BPF_FUNC_map_push_elem:
5150 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5151 		    map->map_type != BPF_MAP_TYPE_STACK)
5152 			goto error;
5153 		break;
5154 	case BPF_FUNC_sk_storage_get:
5155 	case BPF_FUNC_sk_storage_delete:
5156 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5157 			goto error;
5158 		break;
5159 	case BPF_FUNC_inode_storage_get:
5160 	case BPF_FUNC_inode_storage_delete:
5161 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5162 			goto error;
5163 		break;
5164 	default:
5165 		break;
5166 	}
5167 
5168 	return 0;
5169 error:
5170 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5171 		map->map_type, func_id_name(func_id), func_id);
5172 	return -EINVAL;
5173 }
5174 
check_raw_mode_ok(const struct bpf_func_proto * fn)5175 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5176 {
5177 	int count = 0;
5178 
5179 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5180 		count++;
5181 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5182 		count++;
5183 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5184 		count++;
5185 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5186 		count++;
5187 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5188 		count++;
5189 
5190 	/* We only support one arg being in raw mode at the moment,
5191 	 * which is sufficient for the helper functions we have
5192 	 * right now.
5193 	 */
5194 	return count <= 1;
5195 }
5196 
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)5197 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5198 				    enum bpf_arg_type arg_next)
5199 {
5200 	return (arg_type_is_mem_ptr(arg_curr) &&
5201 	        !arg_type_is_mem_size(arg_next)) ||
5202 	       (!arg_type_is_mem_ptr(arg_curr) &&
5203 		arg_type_is_mem_size(arg_next));
5204 }
5205 
check_arg_pair_ok(const struct bpf_func_proto * fn)5206 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5207 {
5208 	/* bpf_xxx(..., buf, len) call will access 'len'
5209 	 * bytes from memory 'buf'. Both arg types need
5210 	 * to be paired, so make sure there's no buggy
5211 	 * helper function specification.
5212 	 */
5213 	if (arg_type_is_mem_size(fn->arg1_type) ||
5214 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5215 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5216 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5217 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5218 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5219 		return false;
5220 
5221 	return true;
5222 }
5223 
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5224 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5225 {
5226 	int count = 0;
5227 
5228 	if (arg_type_may_be_refcounted(fn->arg1_type))
5229 		count++;
5230 	if (arg_type_may_be_refcounted(fn->arg2_type))
5231 		count++;
5232 	if (arg_type_may_be_refcounted(fn->arg3_type))
5233 		count++;
5234 	if (arg_type_may_be_refcounted(fn->arg4_type))
5235 		count++;
5236 	if (arg_type_may_be_refcounted(fn->arg5_type))
5237 		count++;
5238 
5239 	/* A reference acquiring function cannot acquire
5240 	 * another refcounted ptr.
5241 	 */
5242 	if (may_be_acquire_function(func_id) && count)
5243 		return false;
5244 
5245 	/* We only support one arg being unreferenced at the moment,
5246 	 * which is sufficient for the helper functions we have right now.
5247 	 */
5248 	return count <= 1;
5249 }
5250 
check_btf_id_ok(const struct bpf_func_proto * fn)5251 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5252 {
5253 	int i;
5254 
5255 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5256 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5257 			return false;
5258 
5259 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5260 			return false;
5261 	}
5262 
5263 	return true;
5264 }
5265 
check_func_proto(const struct bpf_func_proto * fn,int func_id)5266 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5267 {
5268 	return check_raw_mode_ok(fn) &&
5269 	       check_arg_pair_ok(fn) &&
5270 	       check_btf_id_ok(fn) &&
5271 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5272 }
5273 
5274 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5275  * are now invalid, so turn them into unknown SCALAR_VALUE.
5276  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5277 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5278 {
5279 	struct bpf_func_state *state;
5280 	struct bpf_reg_state *reg;
5281 
5282 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5283 		if (reg_is_pkt_pointer_any(reg))
5284 			__mark_reg_unknown(env, reg);
5285 	}));
5286 }
5287 
5288 enum {
5289 	AT_PKT_END = -1,
5290 	BEYOND_PKT_END = -2,
5291 };
5292 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5293 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5294 {
5295 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5296 	struct bpf_reg_state *reg = &state->regs[regn];
5297 
5298 	if (reg->type != PTR_TO_PACKET)
5299 		/* PTR_TO_PACKET_META is not supported yet */
5300 		return;
5301 
5302 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5303 	 * How far beyond pkt_end it goes is unknown.
5304 	 * if (!range_open) it's the case of pkt >= pkt_end
5305 	 * if (range_open) it's the case of pkt > pkt_end
5306 	 * hence this pointer is at least 1 byte bigger than pkt_end
5307 	 */
5308 	if (range_open)
5309 		reg->range = BEYOND_PKT_END;
5310 	else
5311 		reg->range = AT_PKT_END;
5312 }
5313 
5314 /* The pointer with the specified id has released its reference to kernel
5315  * resources. Identify all copies of the same pointer and clear the reference.
5316  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5317 static int release_reference(struct bpf_verifier_env *env,
5318 			     int ref_obj_id)
5319 {
5320 	struct bpf_func_state *state;
5321 	struct bpf_reg_state *reg;
5322 	int err;
5323 
5324 	err = release_reference_state(cur_func(env), ref_obj_id);
5325 	if (err)
5326 		return err;
5327 
5328 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5329 		if (reg->ref_obj_id == ref_obj_id) {
5330 			if (!env->allow_ptr_leaks)
5331 				__mark_reg_not_init(env, reg);
5332 			else
5333 				__mark_reg_unknown(env, reg);
5334 		}
5335 	}));
5336 
5337 	return 0;
5338 }
5339 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5340 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5341 				    struct bpf_reg_state *regs)
5342 {
5343 	int i;
5344 
5345 	/* after the call registers r0 - r5 were scratched */
5346 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5347 		mark_reg_not_init(env, regs, caller_saved[i]);
5348 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5349 	}
5350 }
5351 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)5352 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5353 			   int *insn_idx)
5354 {
5355 	struct bpf_verifier_state *state = env->cur_state;
5356 	struct bpf_func_info_aux *func_info_aux;
5357 	struct bpf_func_state *caller, *callee;
5358 	int i, err, subprog, target_insn;
5359 	bool is_global = false;
5360 
5361 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5362 		verbose(env, "the call stack of %d frames is too deep\n",
5363 			state->curframe + 2);
5364 		return -E2BIG;
5365 	}
5366 
5367 	target_insn = *insn_idx + insn->imm;
5368 	subprog = find_subprog(env, target_insn + 1);
5369 	if (subprog < 0) {
5370 		verbose(env, "verifier bug. No program starts at insn %d\n",
5371 			target_insn + 1);
5372 		return -EFAULT;
5373 	}
5374 
5375 	caller = state->frame[state->curframe];
5376 	if (state->frame[state->curframe + 1]) {
5377 		verbose(env, "verifier bug. Frame %d already allocated\n",
5378 			state->curframe + 1);
5379 		return -EFAULT;
5380 	}
5381 
5382 	func_info_aux = env->prog->aux->func_info_aux;
5383 	if (func_info_aux)
5384 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5385 	err = btf_check_func_arg_match(env, subprog, caller->regs);
5386 	if (err == -EFAULT)
5387 		return err;
5388 	if (is_global) {
5389 		if (err) {
5390 			verbose(env, "Caller passes invalid args into func#%d\n",
5391 				subprog);
5392 			return err;
5393 		} else {
5394 			if (env->log.level & BPF_LOG_LEVEL)
5395 				verbose(env,
5396 					"Func#%d is global and valid. Skipping.\n",
5397 					subprog);
5398 			clear_caller_saved_regs(env, caller->regs);
5399 
5400 			/* All global functions return a 64-bit SCALAR_VALUE */
5401 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5402 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5403 
5404 			/* continue with next insn after call */
5405 			return 0;
5406 		}
5407 	}
5408 
5409 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5410 	if (!callee)
5411 		return -ENOMEM;
5412 	state->frame[state->curframe + 1] = callee;
5413 
5414 	/* callee cannot access r0, r6 - r9 for reading and has to write
5415 	 * into its own stack before reading from it.
5416 	 * callee can read/write into caller's stack
5417 	 */
5418 	init_func_state(env, callee,
5419 			/* remember the callsite, it will be used by bpf_exit */
5420 			*insn_idx /* callsite */,
5421 			state->curframe + 1 /* frameno within this callchain */,
5422 			subprog /* subprog number within this prog */);
5423 
5424 	/* Transfer references to the callee */
5425 	err = transfer_reference_state(callee, caller);
5426 	if (err)
5427 		goto err_out;
5428 
5429 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5430 	 * pointers, which connects us up to the liveness chain
5431 	 */
5432 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5433 		callee->regs[i] = caller->regs[i];
5434 
5435 	clear_caller_saved_regs(env, caller->regs);
5436 
5437 	/* only increment it after check_reg_arg() finished */
5438 	state->curframe++;
5439 
5440 	/* and go analyze first insn of the callee */
5441 	*insn_idx = target_insn;
5442 
5443 	if (env->log.level & BPF_LOG_LEVEL) {
5444 		verbose(env, "caller:\n");
5445 		print_verifier_state(env, caller);
5446 		verbose(env, "callee:\n");
5447 		print_verifier_state(env, callee);
5448 	}
5449 	return 0;
5450 
5451 err_out:
5452 	free_func_state(callee);
5453 	state->frame[state->curframe + 1] = NULL;
5454 	return err;
5455 }
5456 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)5457 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5458 {
5459 	struct bpf_verifier_state *state = env->cur_state;
5460 	struct bpf_func_state *caller, *callee;
5461 	struct bpf_reg_state *r0;
5462 	int err;
5463 
5464 	callee = state->frame[state->curframe];
5465 	r0 = &callee->regs[BPF_REG_0];
5466 	if (r0->type == PTR_TO_STACK) {
5467 		/* technically it's ok to return caller's stack pointer
5468 		 * (or caller's caller's pointer) back to the caller,
5469 		 * since these pointers are valid. Only current stack
5470 		 * pointer will be invalid as soon as function exits,
5471 		 * but let's be conservative
5472 		 */
5473 		verbose(env, "cannot return stack pointer to the caller\n");
5474 		return -EINVAL;
5475 	}
5476 
5477 	caller = state->frame[state->curframe - 1];
5478 	/* return to the caller whatever r0 had in the callee */
5479 	caller->regs[BPF_REG_0] = *r0;
5480 
5481 	/* Transfer references to the caller */
5482 	err = transfer_reference_state(caller, callee);
5483 	if (err)
5484 		return err;
5485 
5486 	*insn_idx = callee->callsite + 1;
5487 	if (env->log.level & BPF_LOG_LEVEL) {
5488 		verbose(env, "returning from callee:\n");
5489 		print_verifier_state(env, callee);
5490 		verbose(env, "to caller at %d:\n", *insn_idx);
5491 		print_verifier_state(env, caller);
5492 	}
5493 	/* clear everything in the callee */
5494 	free_func_state(callee);
5495 	state->frame[state->curframe--] = NULL;
5496 	return 0;
5497 }
5498 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)5499 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5500 				   int func_id,
5501 				   struct bpf_call_arg_meta *meta)
5502 {
5503 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5504 
5505 	if (ret_type != RET_INTEGER ||
5506 	    (func_id != BPF_FUNC_get_stack &&
5507 	     func_id != BPF_FUNC_probe_read_str &&
5508 	     func_id != BPF_FUNC_probe_read_kernel_str &&
5509 	     func_id != BPF_FUNC_probe_read_user_str))
5510 		return;
5511 
5512 	ret_reg->smax_value = meta->msize_max_value;
5513 	ret_reg->s32_max_value = meta->msize_max_value;
5514 	ret_reg->smin_value = -MAX_ERRNO;
5515 	ret_reg->s32_min_value = -MAX_ERRNO;
5516 	reg_bounds_sync(ret_reg);
5517 }
5518 
5519 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5520 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5521 		int func_id, int insn_idx)
5522 {
5523 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5524 	struct bpf_map *map = meta->map_ptr;
5525 
5526 	if (func_id != BPF_FUNC_tail_call &&
5527 	    func_id != BPF_FUNC_map_lookup_elem &&
5528 	    func_id != BPF_FUNC_map_update_elem &&
5529 	    func_id != BPF_FUNC_map_delete_elem &&
5530 	    func_id != BPF_FUNC_map_push_elem &&
5531 	    func_id != BPF_FUNC_map_pop_elem &&
5532 	    func_id != BPF_FUNC_map_peek_elem)
5533 		return 0;
5534 
5535 	if (map == NULL) {
5536 		verbose(env, "kernel subsystem misconfigured verifier\n");
5537 		return -EINVAL;
5538 	}
5539 
5540 	/* In case of read-only, some additional restrictions
5541 	 * need to be applied in order to prevent altering the
5542 	 * state of the map from program side.
5543 	 */
5544 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5545 	    (func_id == BPF_FUNC_map_delete_elem ||
5546 	     func_id == BPF_FUNC_map_update_elem ||
5547 	     func_id == BPF_FUNC_map_push_elem ||
5548 	     func_id == BPF_FUNC_map_pop_elem)) {
5549 		verbose(env, "write into map forbidden\n");
5550 		return -EACCES;
5551 	}
5552 
5553 	if (!BPF_MAP_PTR(aux->map_ptr_state))
5554 		bpf_map_ptr_store(aux, meta->map_ptr,
5555 				  !meta->map_ptr->bypass_spec_v1);
5556 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5557 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5558 				  !meta->map_ptr->bypass_spec_v1);
5559 	return 0;
5560 }
5561 
5562 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5563 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5564 		int func_id, int insn_idx)
5565 {
5566 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5567 	struct bpf_reg_state *regs = cur_regs(env), *reg;
5568 	struct bpf_map *map = meta->map_ptr;
5569 	u64 val, max;
5570 	int err;
5571 
5572 	if (func_id != BPF_FUNC_tail_call)
5573 		return 0;
5574 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5575 		verbose(env, "kernel subsystem misconfigured verifier\n");
5576 		return -EINVAL;
5577 	}
5578 
5579 	reg = &regs[BPF_REG_3];
5580 	val = reg->var_off.value;
5581 	max = map->max_entries;
5582 
5583 	if (!(register_is_const(reg) && val < max)) {
5584 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5585 		return 0;
5586 	}
5587 
5588 	err = mark_chain_precision(env, BPF_REG_3);
5589 	if (err)
5590 		return err;
5591 	if (bpf_map_key_unseen(aux))
5592 		bpf_map_key_store(aux, val);
5593 	else if (!bpf_map_key_poisoned(aux) &&
5594 		  bpf_map_key_immediate(aux) != val)
5595 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5596 	return 0;
5597 }
5598 
check_reference_leak(struct bpf_verifier_env * env)5599 static int check_reference_leak(struct bpf_verifier_env *env)
5600 {
5601 	struct bpf_func_state *state = cur_func(env);
5602 	int i;
5603 
5604 	for (i = 0; i < state->acquired_refs; i++) {
5605 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5606 			state->refs[i].id, state->refs[i].insn_idx);
5607 	}
5608 	return state->acquired_refs ? -EINVAL : 0;
5609 }
5610 
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)5611 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5612 {
5613 	const struct bpf_func_proto *fn = NULL;
5614 	enum bpf_return_type ret_type;
5615 	enum bpf_type_flag ret_flag;
5616 	struct bpf_reg_state *regs;
5617 	struct bpf_call_arg_meta meta;
5618 	bool changes_data;
5619 	int i, err;
5620 
5621 	/* find function prototype */
5622 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5623 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5624 			func_id);
5625 		return -EINVAL;
5626 	}
5627 
5628 	if (env->ops->get_func_proto)
5629 		fn = env->ops->get_func_proto(func_id, env->prog);
5630 	if (!fn) {
5631 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5632 			func_id);
5633 		return -EINVAL;
5634 	}
5635 
5636 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5637 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5638 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5639 		return -EINVAL;
5640 	}
5641 
5642 	if (fn->allowed && !fn->allowed(env->prog)) {
5643 		verbose(env, "helper call is not allowed in probe\n");
5644 		return -EINVAL;
5645 	}
5646 
5647 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5648 	changes_data = bpf_helper_changes_pkt_data(func_id);
5649 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5650 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5651 			func_id_name(func_id), func_id);
5652 		return -EINVAL;
5653 	}
5654 
5655 	memset(&meta, 0, sizeof(meta));
5656 	meta.pkt_access = fn->pkt_access;
5657 
5658 	err = check_func_proto(fn, func_id);
5659 	if (err) {
5660 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5661 			func_id_name(func_id), func_id);
5662 		return err;
5663 	}
5664 
5665 	meta.func_id = func_id;
5666 	/* check args */
5667 	for (i = 0; i < 5; i++) {
5668 		err = check_func_arg(env, i, &meta, fn);
5669 		if (err)
5670 			return err;
5671 	}
5672 
5673 	err = record_func_map(env, &meta, func_id, insn_idx);
5674 	if (err)
5675 		return err;
5676 
5677 	err = record_func_key(env, &meta, func_id, insn_idx);
5678 	if (err)
5679 		return err;
5680 
5681 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5682 	 * is inferred from register state.
5683 	 */
5684 	for (i = 0; i < meta.access_size; i++) {
5685 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5686 				       BPF_WRITE, -1, false);
5687 		if (err)
5688 			return err;
5689 	}
5690 
5691 	if (func_id == BPF_FUNC_tail_call) {
5692 		err = check_reference_leak(env);
5693 		if (err) {
5694 			verbose(env, "tail_call would lead to reference leak\n");
5695 			return err;
5696 		}
5697 	} else if (is_release_function(func_id)) {
5698 		err = release_reference(env, meta.ref_obj_id);
5699 		if (err) {
5700 			verbose(env, "func %s#%d reference has not been acquired before\n",
5701 				func_id_name(func_id), func_id);
5702 			return err;
5703 		}
5704 	}
5705 
5706 	regs = cur_regs(env);
5707 
5708 	/* check that flags argument in get_local_storage(map, flags) is 0,
5709 	 * this is required because get_local_storage() can't return an error.
5710 	 */
5711 	if (func_id == BPF_FUNC_get_local_storage &&
5712 	    !register_is_null(&regs[BPF_REG_2])) {
5713 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5714 		return -EINVAL;
5715 	}
5716 
5717 	/* reset caller saved regs */
5718 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5719 		mark_reg_not_init(env, regs, caller_saved[i]);
5720 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5721 	}
5722 
5723 	/* helper call returns 64-bit value. */
5724 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5725 
5726 	/* update return register (already marked as written above) */
5727 	ret_type = fn->ret_type;
5728 	ret_flag = type_flag(fn->ret_type);
5729 	if (ret_type == RET_INTEGER) {
5730 		/* sets type to SCALAR_VALUE */
5731 		mark_reg_unknown(env, regs, BPF_REG_0);
5732 	} else if (ret_type == RET_VOID) {
5733 		regs[BPF_REG_0].type = NOT_INIT;
5734 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
5735 		/* There is no offset yet applied, variable or fixed */
5736 		mark_reg_known_zero(env, regs, BPF_REG_0);
5737 		/* remember map_ptr, so that check_map_access()
5738 		 * can check 'value_size' boundary of memory access
5739 		 * to map element returned from bpf_map_lookup_elem()
5740 		 */
5741 		if (meta.map_ptr == NULL) {
5742 			verbose(env,
5743 				"kernel subsystem misconfigured verifier\n");
5744 			return -EINVAL;
5745 		}
5746 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
5747 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
5748 		if (!type_may_be_null(ret_type) &&
5749 		    map_value_has_spin_lock(meta.map_ptr)) {
5750 			regs[BPF_REG_0].id = ++env->id_gen;
5751 		}
5752 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
5753 		mark_reg_known_zero(env, regs, BPF_REG_0);
5754 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
5755 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
5756 		mark_reg_known_zero(env, regs, BPF_REG_0);
5757 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
5758 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
5759 		mark_reg_known_zero(env, regs, BPF_REG_0);
5760 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
5761 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
5762 		mark_reg_known_zero(env, regs, BPF_REG_0);
5763 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5764 		regs[BPF_REG_0].mem_size = meta.mem_size;
5765 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
5766 		const struct btf_type *t;
5767 
5768 		mark_reg_known_zero(env, regs, BPF_REG_0);
5769 		t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5770 		if (!btf_type_is_struct(t)) {
5771 			u32 tsize;
5772 			const struct btf_type *ret;
5773 			const char *tname;
5774 
5775 			/* resolve the type size of ksym. */
5776 			ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5777 			if (IS_ERR(ret)) {
5778 				tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5779 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
5780 					tname, PTR_ERR(ret));
5781 				return -EINVAL;
5782 			}
5783 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5784 			regs[BPF_REG_0].mem_size = tsize;
5785 		} else {
5786 			/* MEM_RDONLY may be carried from ret_flag, but it
5787 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
5788 			 * it will confuse the check of PTR_TO_BTF_ID in
5789 			 * check_mem_access().
5790 			 */
5791 			ret_flag &= ~MEM_RDONLY;
5792 
5793 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5794 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5795 		}
5796 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
5797 		int ret_btf_id;
5798 
5799 		mark_reg_known_zero(env, regs, BPF_REG_0);
5800 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5801 		ret_btf_id = *fn->ret_btf_id;
5802 		if (ret_btf_id == 0) {
5803 			verbose(env, "invalid return type %u of func %s#%d\n",
5804 				base_type(ret_type), func_id_name(func_id),
5805 				func_id);
5806 			return -EINVAL;
5807 		}
5808 		regs[BPF_REG_0].btf_id = ret_btf_id;
5809 	} else {
5810 		verbose(env, "unknown return type %u of func %s#%d\n",
5811 			base_type(ret_type), func_id_name(func_id), func_id);
5812 		return -EINVAL;
5813 	}
5814 
5815 	if (type_may_be_null(regs[BPF_REG_0].type))
5816 		regs[BPF_REG_0].id = ++env->id_gen;
5817 
5818 	if (is_ptr_cast_function(func_id)) {
5819 		/* For release_reference() */
5820 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5821 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
5822 		int id = acquire_reference_state(env, insn_idx);
5823 
5824 		if (id < 0)
5825 			return id;
5826 		/* For mark_ptr_or_null_reg() */
5827 		regs[BPF_REG_0].id = id;
5828 		/* For release_reference() */
5829 		regs[BPF_REG_0].ref_obj_id = id;
5830 	}
5831 
5832 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5833 
5834 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5835 	if (err)
5836 		return err;
5837 
5838 	if ((func_id == BPF_FUNC_get_stack ||
5839 	     func_id == BPF_FUNC_get_task_stack) &&
5840 	    !env->prog->has_callchain_buf) {
5841 		const char *err_str;
5842 
5843 #ifdef CONFIG_PERF_EVENTS
5844 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
5845 		err_str = "cannot get callchain buffer for func %s#%d\n";
5846 #else
5847 		err = -ENOTSUPP;
5848 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5849 #endif
5850 		if (err) {
5851 			verbose(env, err_str, func_id_name(func_id), func_id);
5852 			return err;
5853 		}
5854 
5855 		env->prog->has_callchain_buf = true;
5856 	}
5857 
5858 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5859 		env->prog->call_get_stack = true;
5860 
5861 	if (changes_data)
5862 		clear_all_pkt_pointers(env);
5863 	return 0;
5864 }
5865 
signed_add_overflows(s64 a,s64 b)5866 static bool signed_add_overflows(s64 a, s64 b)
5867 {
5868 	/* Do the add in u64, where overflow is well-defined */
5869 	s64 res = (s64)((u64)a + (u64)b);
5870 
5871 	if (b < 0)
5872 		return res > a;
5873 	return res < a;
5874 }
5875 
signed_add32_overflows(s32 a,s32 b)5876 static bool signed_add32_overflows(s32 a, s32 b)
5877 {
5878 	/* Do the add in u32, where overflow is well-defined */
5879 	s32 res = (s32)((u32)a + (u32)b);
5880 
5881 	if (b < 0)
5882 		return res > a;
5883 	return res < a;
5884 }
5885 
signed_sub_overflows(s64 a,s64 b)5886 static bool signed_sub_overflows(s64 a, s64 b)
5887 {
5888 	/* Do the sub in u64, where overflow is well-defined */
5889 	s64 res = (s64)((u64)a - (u64)b);
5890 
5891 	if (b < 0)
5892 		return res < a;
5893 	return res > a;
5894 }
5895 
signed_sub32_overflows(s32 a,s32 b)5896 static bool signed_sub32_overflows(s32 a, s32 b)
5897 {
5898 	/* Do the sub in u32, where overflow is well-defined */
5899 	s32 res = (s32)((u32)a - (u32)b);
5900 
5901 	if (b < 0)
5902 		return res < a;
5903 	return res > a;
5904 }
5905 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)5906 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5907 				  const struct bpf_reg_state *reg,
5908 				  enum bpf_reg_type type)
5909 {
5910 	bool known = tnum_is_const(reg->var_off);
5911 	s64 val = reg->var_off.value;
5912 	s64 smin = reg->smin_value;
5913 
5914 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5915 		verbose(env, "math between %s pointer and %lld is not allowed\n",
5916 			reg_type_str(env, type), val);
5917 		return false;
5918 	}
5919 
5920 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5921 		verbose(env, "%s pointer offset %d is not allowed\n",
5922 			reg_type_str(env, type), reg->off);
5923 		return false;
5924 	}
5925 
5926 	if (smin == S64_MIN) {
5927 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5928 			reg_type_str(env, type));
5929 		return false;
5930 	}
5931 
5932 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5933 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
5934 			smin, reg_type_str(env, type));
5935 		return false;
5936 	}
5937 
5938 	return true;
5939 }
5940 
cur_aux(struct bpf_verifier_env * env)5941 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5942 {
5943 	return &env->insn_aux_data[env->insn_idx];
5944 }
5945 
5946 enum {
5947 	REASON_BOUNDS	= -1,
5948 	REASON_TYPE	= -2,
5949 	REASON_PATHS	= -3,
5950 	REASON_LIMIT	= -4,
5951 	REASON_STACK	= -5,
5952 };
5953 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)5954 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5955 			      u32 *alu_limit, bool mask_to_left)
5956 {
5957 	u32 max = 0, ptr_limit = 0;
5958 
5959 	switch (ptr_reg->type) {
5960 	case PTR_TO_STACK:
5961 		/* Offset 0 is out-of-bounds, but acceptable start for the
5962 		 * left direction, see BPF_REG_FP. Also, unknown scalar
5963 		 * offset where we would need to deal with min/max bounds is
5964 		 * currently prohibited for unprivileged.
5965 		 */
5966 		max = MAX_BPF_STACK + mask_to_left;
5967 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5968 		break;
5969 	case PTR_TO_MAP_VALUE:
5970 		max = ptr_reg->map_ptr->value_size;
5971 		ptr_limit = (mask_to_left ?
5972 			     ptr_reg->smin_value :
5973 			     ptr_reg->umax_value) + ptr_reg->off;
5974 		break;
5975 	default:
5976 		return REASON_TYPE;
5977 	}
5978 
5979 	if (ptr_limit >= max)
5980 		return REASON_LIMIT;
5981 	*alu_limit = ptr_limit;
5982 	return 0;
5983 }
5984 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)5985 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5986 				    const struct bpf_insn *insn)
5987 {
5988 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5989 }
5990 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)5991 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5992 				       u32 alu_state, u32 alu_limit)
5993 {
5994 	/* If we arrived here from different branches with different
5995 	 * state or limits to sanitize, then this won't work.
5996 	 */
5997 	if (aux->alu_state &&
5998 	    (aux->alu_state != alu_state ||
5999 	     aux->alu_limit != alu_limit))
6000 		return REASON_PATHS;
6001 
6002 	/* Corresponding fixup done in fixup_bpf_calls(). */
6003 	aux->alu_state = alu_state;
6004 	aux->alu_limit = alu_limit;
6005 	return 0;
6006 }
6007 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)6008 static int sanitize_val_alu(struct bpf_verifier_env *env,
6009 			    struct bpf_insn *insn)
6010 {
6011 	struct bpf_insn_aux_data *aux = cur_aux(env);
6012 
6013 	if (can_skip_alu_sanitation(env, insn))
6014 		return 0;
6015 
6016 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6017 }
6018 
sanitize_needed(u8 opcode)6019 static bool sanitize_needed(u8 opcode)
6020 {
6021 	return opcode == BPF_ADD || opcode == BPF_SUB;
6022 }
6023 
6024 struct bpf_sanitize_info {
6025 	struct bpf_insn_aux_data aux;
6026 	bool mask_to_left;
6027 };
6028 
6029 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)6030 sanitize_speculative_path(struct bpf_verifier_env *env,
6031 			  const struct bpf_insn *insn,
6032 			  u32 next_idx, u32 curr_idx)
6033 {
6034 	struct bpf_verifier_state *branch;
6035 	struct bpf_reg_state *regs;
6036 
6037 	branch = push_stack(env, next_idx, curr_idx, true);
6038 	if (branch && insn) {
6039 		regs = branch->frame[branch->curframe]->regs;
6040 		if (BPF_SRC(insn->code) == BPF_K) {
6041 			mark_reg_unknown(env, regs, insn->dst_reg);
6042 		} else if (BPF_SRC(insn->code) == BPF_X) {
6043 			mark_reg_unknown(env, regs, insn->dst_reg);
6044 			mark_reg_unknown(env, regs, insn->src_reg);
6045 		}
6046 	}
6047 	return branch;
6048 }
6049 
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)6050 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6051 			    struct bpf_insn *insn,
6052 			    const struct bpf_reg_state *ptr_reg,
6053 			    const struct bpf_reg_state *off_reg,
6054 			    struct bpf_reg_state *dst_reg,
6055 			    struct bpf_sanitize_info *info,
6056 			    const bool commit_window)
6057 {
6058 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6059 	struct bpf_verifier_state *vstate = env->cur_state;
6060 	bool off_is_imm = tnum_is_const(off_reg->var_off);
6061 	bool off_is_neg = off_reg->smin_value < 0;
6062 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
6063 	u8 opcode = BPF_OP(insn->code);
6064 	u32 alu_state, alu_limit;
6065 	struct bpf_reg_state tmp;
6066 	bool ret;
6067 	int err;
6068 
6069 	if (can_skip_alu_sanitation(env, insn))
6070 		return 0;
6071 
6072 	/* We already marked aux for masking from non-speculative
6073 	 * paths, thus we got here in the first place. We only care
6074 	 * to explore bad access from here.
6075 	 */
6076 	if (vstate->speculative)
6077 		goto do_sim;
6078 
6079 	if (!commit_window) {
6080 		if (!tnum_is_const(off_reg->var_off) &&
6081 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6082 			return REASON_BOUNDS;
6083 
6084 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
6085 				     (opcode == BPF_SUB && !off_is_neg);
6086 	}
6087 
6088 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6089 	if (err < 0)
6090 		return err;
6091 
6092 	if (commit_window) {
6093 		/* In commit phase we narrow the masking window based on
6094 		 * the observed pointer move after the simulated operation.
6095 		 */
6096 		alu_state = info->aux.alu_state;
6097 		alu_limit = abs(info->aux.alu_limit - alu_limit);
6098 	} else {
6099 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6100 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6101 		alu_state |= ptr_is_dst_reg ?
6102 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6103 
6104 		/* Limit pruning on unknown scalars to enable deep search for
6105 		 * potential masking differences from other program paths.
6106 		 */
6107 		if (!off_is_imm)
6108 			env->explore_alu_limits = true;
6109 	}
6110 
6111 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6112 	if (err < 0)
6113 		return err;
6114 do_sim:
6115 	/* If we're in commit phase, we're done here given we already
6116 	 * pushed the truncated dst_reg into the speculative verification
6117 	 * stack.
6118 	 *
6119 	 * Also, when register is a known constant, we rewrite register-based
6120 	 * operation to immediate-based, and thus do not need masking (and as
6121 	 * a consequence, do not need to simulate the zero-truncation either).
6122 	 */
6123 	if (commit_window || off_is_imm)
6124 		return 0;
6125 
6126 	/* Simulate and find potential out-of-bounds access under
6127 	 * speculative execution from truncation as a result of
6128 	 * masking when off was not within expected range. If off
6129 	 * sits in dst, then we temporarily need to move ptr there
6130 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6131 	 * for cases where we use K-based arithmetic in one direction
6132 	 * and truncated reg-based in the other in order to explore
6133 	 * bad access.
6134 	 */
6135 	if (!ptr_is_dst_reg) {
6136 		tmp = *dst_reg;
6137 		copy_register_state(dst_reg, ptr_reg);
6138 	}
6139 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6140 					env->insn_idx);
6141 	if (!ptr_is_dst_reg && ret)
6142 		*dst_reg = tmp;
6143 	return !ret ? REASON_STACK : 0;
6144 }
6145 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)6146 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6147 {
6148 	struct bpf_verifier_state *vstate = env->cur_state;
6149 
6150 	/* If we simulate paths under speculation, we don't update the
6151 	 * insn as 'seen' such that when we verify unreachable paths in
6152 	 * the non-speculative domain, sanitize_dead_code() can still
6153 	 * rewrite/sanitize them.
6154 	 */
6155 	if (!vstate->speculative)
6156 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6157 }
6158 
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)6159 static int sanitize_err(struct bpf_verifier_env *env,
6160 			const struct bpf_insn *insn, int reason,
6161 			const struct bpf_reg_state *off_reg,
6162 			const struct bpf_reg_state *dst_reg)
6163 {
6164 	static const char *err = "pointer arithmetic with it prohibited for !root";
6165 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6166 	u32 dst = insn->dst_reg, src = insn->src_reg;
6167 
6168 	switch (reason) {
6169 	case REASON_BOUNDS:
6170 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6171 			off_reg == dst_reg ? dst : src, err);
6172 		break;
6173 	case REASON_TYPE:
6174 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6175 			off_reg == dst_reg ? src : dst, err);
6176 		break;
6177 	case REASON_PATHS:
6178 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6179 			dst, op, err);
6180 		break;
6181 	case REASON_LIMIT:
6182 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6183 			dst, op, err);
6184 		break;
6185 	case REASON_STACK:
6186 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6187 			dst, err);
6188 		break;
6189 	default:
6190 		verbose(env, "verifier internal error: unknown reason (%d)\n",
6191 			reason);
6192 		break;
6193 	}
6194 
6195 	return -EACCES;
6196 }
6197 
6198 /* check that stack access falls within stack limits and that 'reg' doesn't
6199  * have a variable offset.
6200  *
6201  * Variable offset is prohibited for unprivileged mode for simplicity since it
6202  * requires corresponding support in Spectre masking for stack ALU.  See also
6203  * retrieve_ptr_limit().
6204  *
6205  *
6206  * 'off' includes 'reg->off'.
6207  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)6208 static int check_stack_access_for_ptr_arithmetic(
6209 				struct bpf_verifier_env *env,
6210 				int regno,
6211 				const struct bpf_reg_state *reg,
6212 				int off)
6213 {
6214 	if (!tnum_is_const(reg->var_off)) {
6215 		char tn_buf[48];
6216 
6217 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6218 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6219 			regno, tn_buf, off);
6220 		return -EACCES;
6221 	}
6222 
6223 	if (off >= 0 || off < -MAX_BPF_STACK) {
6224 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6225 			"prohibited for !root; off=%d\n", regno, off);
6226 		return -EACCES;
6227 	}
6228 
6229 	return 0;
6230 }
6231 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)6232 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6233 				 const struct bpf_insn *insn,
6234 				 const struct bpf_reg_state *dst_reg)
6235 {
6236 	u32 dst = insn->dst_reg;
6237 
6238 	/* For unprivileged we require that resulting offset must be in bounds
6239 	 * in order to be able to sanitize access later on.
6240 	 */
6241 	if (env->bypass_spec_v1)
6242 		return 0;
6243 
6244 	switch (dst_reg->type) {
6245 	case PTR_TO_STACK:
6246 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6247 					dst_reg->off + dst_reg->var_off.value))
6248 			return -EACCES;
6249 		break;
6250 	case PTR_TO_MAP_VALUE:
6251 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6252 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6253 				"prohibited for !root\n", dst);
6254 			return -EACCES;
6255 		}
6256 		break;
6257 	default:
6258 		break;
6259 	}
6260 
6261 	return 0;
6262 }
6263 
6264 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6265  * Caller should also handle BPF_MOV case separately.
6266  * If we return -EACCES, caller may want to try again treating pointer as a
6267  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6268  */
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)6269 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6270 				   struct bpf_insn *insn,
6271 				   const struct bpf_reg_state *ptr_reg,
6272 				   const struct bpf_reg_state *off_reg)
6273 {
6274 	struct bpf_verifier_state *vstate = env->cur_state;
6275 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6276 	struct bpf_reg_state *regs = state->regs, *dst_reg;
6277 	bool known = tnum_is_const(off_reg->var_off);
6278 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6279 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6280 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6281 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6282 	struct bpf_sanitize_info info = {};
6283 	u8 opcode = BPF_OP(insn->code);
6284 	u32 dst = insn->dst_reg;
6285 	int ret;
6286 
6287 	dst_reg = &regs[dst];
6288 
6289 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6290 	    smin_val > smax_val || umin_val > umax_val) {
6291 		/* Taint dst register if offset had invalid bounds derived from
6292 		 * e.g. dead branches.
6293 		 */
6294 		__mark_reg_unknown(env, dst_reg);
6295 		return 0;
6296 	}
6297 
6298 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6299 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6300 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6301 			__mark_reg_unknown(env, dst_reg);
6302 			return 0;
6303 		}
6304 
6305 		verbose(env,
6306 			"R%d 32-bit pointer arithmetic prohibited\n",
6307 			dst);
6308 		return -EACCES;
6309 	}
6310 
6311 	if (ptr_reg->type & PTR_MAYBE_NULL) {
6312 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6313 			dst, reg_type_str(env, ptr_reg->type));
6314 		return -EACCES;
6315 	}
6316 
6317 	switch (base_type(ptr_reg->type)) {
6318 	case PTR_TO_FLOW_KEYS:
6319 		if (known)
6320 			break;
6321 		fallthrough;
6322 	case CONST_PTR_TO_MAP:
6323 		/* smin_val represents the known value */
6324 		if (known && smin_val == 0 && opcode == BPF_ADD)
6325 			break;
6326 		fallthrough;
6327 	case PTR_TO_PACKET_END:
6328 	case PTR_TO_SOCKET:
6329 	case PTR_TO_SOCK_COMMON:
6330 	case PTR_TO_TCP_SOCK:
6331 	case PTR_TO_XDP_SOCK:
6332 reject:
6333 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6334 			dst, reg_type_str(env, ptr_reg->type));
6335 		return -EACCES;
6336 	default:
6337 		if (type_may_be_null(ptr_reg->type))
6338 			goto reject;
6339 		break;
6340 	}
6341 
6342 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6343 	 * The id may be overwritten later if we create a new variable offset.
6344 	 */
6345 	dst_reg->type = ptr_reg->type;
6346 	dst_reg->id = ptr_reg->id;
6347 
6348 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6349 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6350 		return -EINVAL;
6351 
6352 	/* pointer types do not carry 32-bit bounds at the moment. */
6353 	__mark_reg32_unbounded(dst_reg);
6354 
6355 	if (sanitize_needed(opcode)) {
6356 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6357 				       &info, false);
6358 		if (ret < 0)
6359 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6360 	}
6361 
6362 	switch (opcode) {
6363 	case BPF_ADD:
6364 		/* We can take a fixed offset as long as it doesn't overflow
6365 		 * the s32 'off' field
6366 		 */
6367 		if (known && (ptr_reg->off + smin_val ==
6368 			      (s64)(s32)(ptr_reg->off + smin_val))) {
6369 			/* pointer += K.  Accumulate it into fixed offset */
6370 			dst_reg->smin_value = smin_ptr;
6371 			dst_reg->smax_value = smax_ptr;
6372 			dst_reg->umin_value = umin_ptr;
6373 			dst_reg->umax_value = umax_ptr;
6374 			dst_reg->var_off = ptr_reg->var_off;
6375 			dst_reg->off = ptr_reg->off + smin_val;
6376 			dst_reg->raw = ptr_reg->raw;
6377 			break;
6378 		}
6379 		/* A new variable offset is created.  Note that off_reg->off
6380 		 * == 0, since it's a scalar.
6381 		 * dst_reg gets the pointer type and since some positive
6382 		 * integer value was added to the pointer, give it a new 'id'
6383 		 * if it's a PTR_TO_PACKET.
6384 		 * this creates a new 'base' pointer, off_reg (variable) gets
6385 		 * added into the variable offset, and we copy the fixed offset
6386 		 * from ptr_reg.
6387 		 */
6388 		if (signed_add_overflows(smin_ptr, smin_val) ||
6389 		    signed_add_overflows(smax_ptr, smax_val)) {
6390 			dst_reg->smin_value = S64_MIN;
6391 			dst_reg->smax_value = S64_MAX;
6392 		} else {
6393 			dst_reg->smin_value = smin_ptr + smin_val;
6394 			dst_reg->smax_value = smax_ptr + smax_val;
6395 		}
6396 		if (umin_ptr + umin_val < umin_ptr ||
6397 		    umax_ptr + umax_val < umax_ptr) {
6398 			dst_reg->umin_value = 0;
6399 			dst_reg->umax_value = U64_MAX;
6400 		} else {
6401 			dst_reg->umin_value = umin_ptr + umin_val;
6402 			dst_reg->umax_value = umax_ptr + umax_val;
6403 		}
6404 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6405 		dst_reg->off = ptr_reg->off;
6406 		dst_reg->raw = ptr_reg->raw;
6407 		if (reg_is_pkt_pointer(ptr_reg)) {
6408 			dst_reg->id = ++env->id_gen;
6409 			/* something was added to pkt_ptr, set range to zero */
6410 			dst_reg->raw = 0;
6411 		}
6412 		break;
6413 	case BPF_SUB:
6414 		if (dst_reg == off_reg) {
6415 			/* scalar -= pointer.  Creates an unknown scalar */
6416 			verbose(env, "R%d tried to subtract pointer from scalar\n",
6417 				dst);
6418 			return -EACCES;
6419 		}
6420 		/* We don't allow subtraction from FP, because (according to
6421 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
6422 		 * be able to deal with it.
6423 		 */
6424 		if (ptr_reg->type == PTR_TO_STACK) {
6425 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
6426 				dst);
6427 			return -EACCES;
6428 		}
6429 		if (known && (ptr_reg->off - smin_val ==
6430 			      (s64)(s32)(ptr_reg->off - smin_val))) {
6431 			/* pointer -= K.  Subtract it from fixed offset */
6432 			dst_reg->smin_value = smin_ptr;
6433 			dst_reg->smax_value = smax_ptr;
6434 			dst_reg->umin_value = umin_ptr;
6435 			dst_reg->umax_value = umax_ptr;
6436 			dst_reg->var_off = ptr_reg->var_off;
6437 			dst_reg->id = ptr_reg->id;
6438 			dst_reg->off = ptr_reg->off - smin_val;
6439 			dst_reg->raw = ptr_reg->raw;
6440 			break;
6441 		}
6442 		/* A new variable offset is created.  If the subtrahend is known
6443 		 * nonnegative, then any reg->range we had before is still good.
6444 		 */
6445 		if (signed_sub_overflows(smin_ptr, smax_val) ||
6446 		    signed_sub_overflows(smax_ptr, smin_val)) {
6447 			/* Overflow possible, we know nothing */
6448 			dst_reg->smin_value = S64_MIN;
6449 			dst_reg->smax_value = S64_MAX;
6450 		} else {
6451 			dst_reg->smin_value = smin_ptr - smax_val;
6452 			dst_reg->smax_value = smax_ptr - smin_val;
6453 		}
6454 		if (umin_ptr < umax_val) {
6455 			/* Overflow possible, we know nothing */
6456 			dst_reg->umin_value = 0;
6457 			dst_reg->umax_value = U64_MAX;
6458 		} else {
6459 			/* Cannot overflow (as long as bounds are consistent) */
6460 			dst_reg->umin_value = umin_ptr - umax_val;
6461 			dst_reg->umax_value = umax_ptr - umin_val;
6462 		}
6463 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6464 		dst_reg->off = ptr_reg->off;
6465 		dst_reg->raw = ptr_reg->raw;
6466 		if (reg_is_pkt_pointer(ptr_reg)) {
6467 			dst_reg->id = ++env->id_gen;
6468 			/* something was added to pkt_ptr, set range to zero */
6469 			if (smin_val < 0)
6470 				dst_reg->raw = 0;
6471 		}
6472 		break;
6473 	case BPF_AND:
6474 	case BPF_OR:
6475 	case BPF_XOR:
6476 		/* bitwise ops on pointers are troublesome, prohibit. */
6477 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6478 			dst, bpf_alu_string[opcode >> 4]);
6479 		return -EACCES;
6480 	default:
6481 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
6482 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6483 			dst, bpf_alu_string[opcode >> 4]);
6484 		return -EACCES;
6485 	}
6486 
6487 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6488 		return -EINVAL;
6489 	reg_bounds_sync(dst_reg);
6490 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6491 		return -EACCES;
6492 	if (sanitize_needed(opcode)) {
6493 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6494 				       &info, true);
6495 		if (ret < 0)
6496 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6497 	}
6498 
6499 	return 0;
6500 }
6501 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6502 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6503 				 struct bpf_reg_state *src_reg)
6504 {
6505 	s32 smin_val = src_reg->s32_min_value;
6506 	s32 smax_val = src_reg->s32_max_value;
6507 	u32 umin_val = src_reg->u32_min_value;
6508 	u32 umax_val = src_reg->u32_max_value;
6509 
6510 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6511 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6512 		dst_reg->s32_min_value = S32_MIN;
6513 		dst_reg->s32_max_value = S32_MAX;
6514 	} else {
6515 		dst_reg->s32_min_value += smin_val;
6516 		dst_reg->s32_max_value += smax_val;
6517 	}
6518 	if (dst_reg->u32_min_value + umin_val < umin_val ||
6519 	    dst_reg->u32_max_value + umax_val < umax_val) {
6520 		dst_reg->u32_min_value = 0;
6521 		dst_reg->u32_max_value = U32_MAX;
6522 	} else {
6523 		dst_reg->u32_min_value += umin_val;
6524 		dst_reg->u32_max_value += umax_val;
6525 	}
6526 }
6527 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6528 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6529 			       struct bpf_reg_state *src_reg)
6530 {
6531 	s64 smin_val = src_reg->smin_value;
6532 	s64 smax_val = src_reg->smax_value;
6533 	u64 umin_val = src_reg->umin_value;
6534 	u64 umax_val = src_reg->umax_value;
6535 
6536 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6537 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
6538 		dst_reg->smin_value = S64_MIN;
6539 		dst_reg->smax_value = S64_MAX;
6540 	} else {
6541 		dst_reg->smin_value += smin_val;
6542 		dst_reg->smax_value += smax_val;
6543 	}
6544 	if (dst_reg->umin_value + umin_val < umin_val ||
6545 	    dst_reg->umax_value + umax_val < umax_val) {
6546 		dst_reg->umin_value = 0;
6547 		dst_reg->umax_value = U64_MAX;
6548 	} else {
6549 		dst_reg->umin_value += umin_val;
6550 		dst_reg->umax_value += umax_val;
6551 	}
6552 }
6553 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6554 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6555 				 struct bpf_reg_state *src_reg)
6556 {
6557 	s32 smin_val = src_reg->s32_min_value;
6558 	s32 smax_val = src_reg->s32_max_value;
6559 	u32 umin_val = src_reg->u32_min_value;
6560 	u32 umax_val = src_reg->u32_max_value;
6561 
6562 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6563 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6564 		/* Overflow possible, we know nothing */
6565 		dst_reg->s32_min_value = S32_MIN;
6566 		dst_reg->s32_max_value = S32_MAX;
6567 	} else {
6568 		dst_reg->s32_min_value -= smax_val;
6569 		dst_reg->s32_max_value -= smin_val;
6570 	}
6571 	if (dst_reg->u32_min_value < umax_val) {
6572 		/* Overflow possible, we know nothing */
6573 		dst_reg->u32_min_value = 0;
6574 		dst_reg->u32_max_value = U32_MAX;
6575 	} else {
6576 		/* Cannot overflow (as long as bounds are consistent) */
6577 		dst_reg->u32_min_value -= umax_val;
6578 		dst_reg->u32_max_value -= umin_val;
6579 	}
6580 }
6581 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6582 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6583 			       struct bpf_reg_state *src_reg)
6584 {
6585 	s64 smin_val = src_reg->smin_value;
6586 	s64 smax_val = src_reg->smax_value;
6587 	u64 umin_val = src_reg->umin_value;
6588 	u64 umax_val = src_reg->umax_value;
6589 
6590 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6591 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6592 		/* Overflow possible, we know nothing */
6593 		dst_reg->smin_value = S64_MIN;
6594 		dst_reg->smax_value = S64_MAX;
6595 	} else {
6596 		dst_reg->smin_value -= smax_val;
6597 		dst_reg->smax_value -= smin_val;
6598 	}
6599 	if (dst_reg->umin_value < umax_val) {
6600 		/* Overflow possible, we know nothing */
6601 		dst_reg->umin_value = 0;
6602 		dst_reg->umax_value = U64_MAX;
6603 	} else {
6604 		/* Cannot overflow (as long as bounds are consistent) */
6605 		dst_reg->umin_value -= umax_val;
6606 		dst_reg->umax_value -= umin_val;
6607 	}
6608 }
6609 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6610 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6611 				 struct bpf_reg_state *src_reg)
6612 {
6613 	s32 smin_val = src_reg->s32_min_value;
6614 	u32 umin_val = src_reg->u32_min_value;
6615 	u32 umax_val = src_reg->u32_max_value;
6616 
6617 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6618 		/* Ain't nobody got time to multiply that sign */
6619 		__mark_reg32_unbounded(dst_reg);
6620 		return;
6621 	}
6622 	/* Both values are positive, so we can work with unsigned and
6623 	 * copy the result to signed (unless it exceeds S32_MAX).
6624 	 */
6625 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6626 		/* Potential overflow, we know nothing */
6627 		__mark_reg32_unbounded(dst_reg);
6628 		return;
6629 	}
6630 	dst_reg->u32_min_value *= umin_val;
6631 	dst_reg->u32_max_value *= umax_val;
6632 	if (dst_reg->u32_max_value > S32_MAX) {
6633 		/* Overflow possible, we know nothing */
6634 		dst_reg->s32_min_value = S32_MIN;
6635 		dst_reg->s32_max_value = S32_MAX;
6636 	} else {
6637 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6638 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6639 	}
6640 }
6641 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6642 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6643 			       struct bpf_reg_state *src_reg)
6644 {
6645 	s64 smin_val = src_reg->smin_value;
6646 	u64 umin_val = src_reg->umin_value;
6647 	u64 umax_val = src_reg->umax_value;
6648 
6649 	if (smin_val < 0 || dst_reg->smin_value < 0) {
6650 		/* Ain't nobody got time to multiply that sign */
6651 		__mark_reg64_unbounded(dst_reg);
6652 		return;
6653 	}
6654 	/* Both values are positive, so we can work with unsigned and
6655 	 * copy the result to signed (unless it exceeds S64_MAX).
6656 	 */
6657 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6658 		/* Potential overflow, we know nothing */
6659 		__mark_reg64_unbounded(dst_reg);
6660 		return;
6661 	}
6662 	dst_reg->umin_value *= umin_val;
6663 	dst_reg->umax_value *= umax_val;
6664 	if (dst_reg->umax_value > S64_MAX) {
6665 		/* Overflow possible, we know nothing */
6666 		dst_reg->smin_value = S64_MIN;
6667 		dst_reg->smax_value = S64_MAX;
6668 	} else {
6669 		dst_reg->smin_value = dst_reg->umin_value;
6670 		dst_reg->smax_value = dst_reg->umax_value;
6671 	}
6672 }
6673 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6674 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6675 				 struct bpf_reg_state *src_reg)
6676 {
6677 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6678 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6679 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6680 	s32 smin_val = src_reg->s32_min_value;
6681 	u32 umax_val = src_reg->u32_max_value;
6682 
6683 	if (src_known && dst_known) {
6684 		__mark_reg32_known(dst_reg, var32_off.value);
6685 		return;
6686 	}
6687 
6688 	/* We get our minimum from the var_off, since that's inherently
6689 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6690 	 */
6691 	dst_reg->u32_min_value = var32_off.value;
6692 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6693 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6694 		/* Lose signed bounds when ANDing negative numbers,
6695 		 * ain't nobody got time for that.
6696 		 */
6697 		dst_reg->s32_min_value = S32_MIN;
6698 		dst_reg->s32_max_value = S32_MAX;
6699 	} else {
6700 		/* ANDing two positives gives a positive, so safe to
6701 		 * cast result into s64.
6702 		 */
6703 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6704 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6705 	}
6706 }
6707 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6708 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6709 			       struct bpf_reg_state *src_reg)
6710 {
6711 	bool src_known = tnum_is_const(src_reg->var_off);
6712 	bool dst_known = tnum_is_const(dst_reg->var_off);
6713 	s64 smin_val = src_reg->smin_value;
6714 	u64 umax_val = src_reg->umax_value;
6715 
6716 	if (src_known && dst_known) {
6717 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6718 		return;
6719 	}
6720 
6721 	/* We get our minimum from the var_off, since that's inherently
6722 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6723 	 */
6724 	dst_reg->umin_value = dst_reg->var_off.value;
6725 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6726 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6727 		/* Lose signed bounds when ANDing negative numbers,
6728 		 * ain't nobody got time for that.
6729 		 */
6730 		dst_reg->smin_value = S64_MIN;
6731 		dst_reg->smax_value = S64_MAX;
6732 	} else {
6733 		/* ANDing two positives gives a positive, so safe to
6734 		 * cast result into s64.
6735 		 */
6736 		dst_reg->smin_value = dst_reg->umin_value;
6737 		dst_reg->smax_value = dst_reg->umax_value;
6738 	}
6739 	/* We may learn something more from the var_off */
6740 	__update_reg_bounds(dst_reg);
6741 }
6742 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6743 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6744 				struct bpf_reg_state *src_reg)
6745 {
6746 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6747 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6748 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6749 	s32 smin_val = src_reg->s32_min_value;
6750 	u32 umin_val = src_reg->u32_min_value;
6751 
6752 	if (src_known && dst_known) {
6753 		__mark_reg32_known(dst_reg, var32_off.value);
6754 		return;
6755 	}
6756 
6757 	/* We get our maximum from the var_off, and our minimum is the
6758 	 * maximum of the operands' minima
6759 	 */
6760 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6761 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6762 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6763 		/* Lose signed bounds when ORing negative numbers,
6764 		 * ain't nobody got time for that.
6765 		 */
6766 		dst_reg->s32_min_value = S32_MIN;
6767 		dst_reg->s32_max_value = S32_MAX;
6768 	} else {
6769 		/* ORing two positives gives a positive, so safe to
6770 		 * cast result into s64.
6771 		 */
6772 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6773 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6774 	}
6775 }
6776 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6777 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6778 			      struct bpf_reg_state *src_reg)
6779 {
6780 	bool src_known = tnum_is_const(src_reg->var_off);
6781 	bool dst_known = tnum_is_const(dst_reg->var_off);
6782 	s64 smin_val = src_reg->smin_value;
6783 	u64 umin_val = src_reg->umin_value;
6784 
6785 	if (src_known && dst_known) {
6786 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6787 		return;
6788 	}
6789 
6790 	/* We get our maximum from the var_off, and our minimum is the
6791 	 * maximum of the operands' minima
6792 	 */
6793 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6794 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6795 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6796 		/* Lose signed bounds when ORing negative numbers,
6797 		 * ain't nobody got time for that.
6798 		 */
6799 		dst_reg->smin_value = S64_MIN;
6800 		dst_reg->smax_value = S64_MAX;
6801 	} else {
6802 		/* ORing two positives gives a positive, so safe to
6803 		 * cast result into s64.
6804 		 */
6805 		dst_reg->smin_value = dst_reg->umin_value;
6806 		dst_reg->smax_value = dst_reg->umax_value;
6807 	}
6808 	/* We may learn something more from the var_off */
6809 	__update_reg_bounds(dst_reg);
6810 }
6811 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6812 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6813 				 struct bpf_reg_state *src_reg)
6814 {
6815 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6816 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6817 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6818 	s32 smin_val = src_reg->s32_min_value;
6819 
6820 	if (src_known && dst_known) {
6821 		__mark_reg32_known(dst_reg, var32_off.value);
6822 		return;
6823 	}
6824 
6825 	/* We get both minimum and maximum from the var32_off. */
6826 	dst_reg->u32_min_value = var32_off.value;
6827 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6828 
6829 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6830 		/* XORing two positive sign numbers gives a positive,
6831 		 * so safe to cast u32 result into s32.
6832 		 */
6833 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6834 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6835 	} else {
6836 		dst_reg->s32_min_value = S32_MIN;
6837 		dst_reg->s32_max_value = S32_MAX;
6838 	}
6839 }
6840 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6841 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6842 			       struct bpf_reg_state *src_reg)
6843 {
6844 	bool src_known = tnum_is_const(src_reg->var_off);
6845 	bool dst_known = tnum_is_const(dst_reg->var_off);
6846 	s64 smin_val = src_reg->smin_value;
6847 
6848 	if (src_known && dst_known) {
6849 		/* dst_reg->var_off.value has been updated earlier */
6850 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6851 		return;
6852 	}
6853 
6854 	/* We get both minimum and maximum from the var_off. */
6855 	dst_reg->umin_value = dst_reg->var_off.value;
6856 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6857 
6858 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6859 		/* XORing two positive sign numbers gives a positive,
6860 		 * so safe to cast u64 result into s64.
6861 		 */
6862 		dst_reg->smin_value = dst_reg->umin_value;
6863 		dst_reg->smax_value = dst_reg->umax_value;
6864 	} else {
6865 		dst_reg->smin_value = S64_MIN;
6866 		dst_reg->smax_value = S64_MAX;
6867 	}
6868 
6869 	__update_reg_bounds(dst_reg);
6870 }
6871 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6872 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6873 				   u64 umin_val, u64 umax_val)
6874 {
6875 	/* We lose all sign bit information (except what we can pick
6876 	 * up from var_off)
6877 	 */
6878 	dst_reg->s32_min_value = S32_MIN;
6879 	dst_reg->s32_max_value = S32_MAX;
6880 	/* If we might shift our top bit out, then we know nothing */
6881 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6882 		dst_reg->u32_min_value = 0;
6883 		dst_reg->u32_max_value = U32_MAX;
6884 	} else {
6885 		dst_reg->u32_min_value <<= umin_val;
6886 		dst_reg->u32_max_value <<= umax_val;
6887 	}
6888 }
6889 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6890 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6891 				 struct bpf_reg_state *src_reg)
6892 {
6893 	u32 umax_val = src_reg->u32_max_value;
6894 	u32 umin_val = src_reg->u32_min_value;
6895 	/* u32 alu operation will zext upper bits */
6896 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6897 
6898 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6899 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6900 	/* Not required but being careful mark reg64 bounds as unknown so
6901 	 * that we are forced to pick them up from tnum and zext later and
6902 	 * if some path skips this step we are still safe.
6903 	 */
6904 	__mark_reg64_unbounded(dst_reg);
6905 	__update_reg32_bounds(dst_reg);
6906 }
6907 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6908 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6909 				   u64 umin_val, u64 umax_val)
6910 {
6911 	/* Special case <<32 because it is a common compiler pattern to sign
6912 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6913 	 * positive we know this shift will also be positive so we can track
6914 	 * bounds correctly. Otherwise we lose all sign bit information except
6915 	 * what we can pick up from var_off. Perhaps we can generalize this
6916 	 * later to shifts of any length.
6917 	 */
6918 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6919 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6920 	else
6921 		dst_reg->smax_value = S64_MAX;
6922 
6923 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6924 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6925 	else
6926 		dst_reg->smin_value = S64_MIN;
6927 
6928 	/* If we might shift our top bit out, then we know nothing */
6929 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6930 		dst_reg->umin_value = 0;
6931 		dst_reg->umax_value = U64_MAX;
6932 	} else {
6933 		dst_reg->umin_value <<= umin_val;
6934 		dst_reg->umax_value <<= umax_val;
6935 	}
6936 }
6937 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6938 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6939 			       struct bpf_reg_state *src_reg)
6940 {
6941 	u64 umax_val = src_reg->umax_value;
6942 	u64 umin_val = src_reg->umin_value;
6943 
6944 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
6945 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6946 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6947 
6948 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6949 	/* We may learn something more from the var_off */
6950 	__update_reg_bounds(dst_reg);
6951 }
6952 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6953 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6954 				 struct bpf_reg_state *src_reg)
6955 {
6956 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6957 	u32 umax_val = src_reg->u32_max_value;
6958 	u32 umin_val = src_reg->u32_min_value;
6959 
6960 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6961 	 * be negative, then either:
6962 	 * 1) src_reg might be zero, so the sign bit of the result is
6963 	 *    unknown, so we lose our signed bounds
6964 	 * 2) it's known negative, thus the unsigned bounds capture the
6965 	 *    signed bounds
6966 	 * 3) the signed bounds cross zero, so they tell us nothing
6967 	 *    about the result
6968 	 * If the value in dst_reg is known nonnegative, then again the
6969 	 * unsigned bounts capture the signed bounds.
6970 	 * Thus, in all cases it suffices to blow away our signed bounds
6971 	 * and rely on inferring new ones from the unsigned bounds and
6972 	 * var_off of the result.
6973 	 */
6974 	dst_reg->s32_min_value = S32_MIN;
6975 	dst_reg->s32_max_value = S32_MAX;
6976 
6977 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
6978 	dst_reg->u32_min_value >>= umax_val;
6979 	dst_reg->u32_max_value >>= umin_val;
6980 
6981 	__mark_reg64_unbounded(dst_reg);
6982 	__update_reg32_bounds(dst_reg);
6983 }
6984 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6985 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6986 			       struct bpf_reg_state *src_reg)
6987 {
6988 	u64 umax_val = src_reg->umax_value;
6989 	u64 umin_val = src_reg->umin_value;
6990 
6991 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6992 	 * be negative, then either:
6993 	 * 1) src_reg might be zero, so the sign bit of the result is
6994 	 *    unknown, so we lose our signed bounds
6995 	 * 2) it's known negative, thus the unsigned bounds capture the
6996 	 *    signed bounds
6997 	 * 3) the signed bounds cross zero, so they tell us nothing
6998 	 *    about the result
6999 	 * If the value in dst_reg is known nonnegative, then again the
7000 	 * unsigned bounts capture the signed bounds.
7001 	 * Thus, in all cases it suffices to blow away our signed bounds
7002 	 * and rely on inferring new ones from the unsigned bounds and
7003 	 * var_off of the result.
7004 	 */
7005 	dst_reg->smin_value = S64_MIN;
7006 	dst_reg->smax_value = S64_MAX;
7007 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7008 	dst_reg->umin_value >>= umax_val;
7009 	dst_reg->umax_value >>= umin_val;
7010 
7011 	/* Its not easy to operate on alu32 bounds here because it depends
7012 	 * on bits being shifted in. Take easy way out and mark unbounded
7013 	 * so we can recalculate later from tnum.
7014 	 */
7015 	__mark_reg32_unbounded(dst_reg);
7016 	__update_reg_bounds(dst_reg);
7017 }
7018 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7019 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7020 				  struct bpf_reg_state *src_reg)
7021 {
7022 	u64 umin_val = src_reg->u32_min_value;
7023 
7024 	/* Upon reaching here, src_known is true and
7025 	 * umax_val is equal to umin_val.
7026 	 */
7027 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7028 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7029 
7030 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7031 
7032 	/* blow away the dst_reg umin_value/umax_value and rely on
7033 	 * dst_reg var_off to refine the result.
7034 	 */
7035 	dst_reg->u32_min_value = 0;
7036 	dst_reg->u32_max_value = U32_MAX;
7037 
7038 	__mark_reg64_unbounded(dst_reg);
7039 	__update_reg32_bounds(dst_reg);
7040 }
7041 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7042 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7043 				struct bpf_reg_state *src_reg)
7044 {
7045 	u64 umin_val = src_reg->umin_value;
7046 
7047 	/* Upon reaching here, src_known is true and umax_val is equal
7048 	 * to umin_val.
7049 	 */
7050 	dst_reg->smin_value >>= umin_val;
7051 	dst_reg->smax_value >>= umin_val;
7052 
7053 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7054 
7055 	/* blow away the dst_reg umin_value/umax_value and rely on
7056 	 * dst_reg var_off to refine the result.
7057 	 */
7058 	dst_reg->umin_value = 0;
7059 	dst_reg->umax_value = U64_MAX;
7060 
7061 	/* Its not easy to operate on alu32 bounds here because it depends
7062 	 * on bits being shifted in from upper 32-bits. Take easy way out
7063 	 * and mark unbounded so we can recalculate later from tnum.
7064 	 */
7065 	__mark_reg32_unbounded(dst_reg);
7066 	__update_reg_bounds(dst_reg);
7067 }
7068 
7069 /* WARNING: This function does calculations on 64-bit values, but the actual
7070  * execution may occur on 32-bit values. Therefore, things like bitshifts
7071  * need extra checks in the 32-bit case.
7072  */
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)7073 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7074 				      struct bpf_insn *insn,
7075 				      struct bpf_reg_state *dst_reg,
7076 				      struct bpf_reg_state src_reg)
7077 {
7078 	struct bpf_reg_state *regs = cur_regs(env);
7079 	u8 opcode = BPF_OP(insn->code);
7080 	bool src_known;
7081 	s64 smin_val, smax_val;
7082 	u64 umin_val, umax_val;
7083 	s32 s32_min_val, s32_max_val;
7084 	u32 u32_min_val, u32_max_val;
7085 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7086 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7087 	int ret;
7088 
7089 	smin_val = src_reg.smin_value;
7090 	smax_val = src_reg.smax_value;
7091 	umin_val = src_reg.umin_value;
7092 	umax_val = src_reg.umax_value;
7093 
7094 	s32_min_val = src_reg.s32_min_value;
7095 	s32_max_val = src_reg.s32_max_value;
7096 	u32_min_val = src_reg.u32_min_value;
7097 	u32_max_val = src_reg.u32_max_value;
7098 
7099 	if (alu32) {
7100 		src_known = tnum_subreg_is_const(src_reg.var_off);
7101 		if ((src_known &&
7102 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7103 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7104 			/* Taint dst register if offset had invalid bounds
7105 			 * derived from e.g. dead branches.
7106 			 */
7107 			__mark_reg_unknown(env, dst_reg);
7108 			return 0;
7109 		}
7110 	} else {
7111 		src_known = tnum_is_const(src_reg.var_off);
7112 		if ((src_known &&
7113 		     (smin_val != smax_val || umin_val != umax_val)) ||
7114 		    smin_val > smax_val || umin_val > umax_val) {
7115 			/* Taint dst register if offset had invalid bounds
7116 			 * derived from e.g. dead branches.
7117 			 */
7118 			__mark_reg_unknown(env, dst_reg);
7119 			return 0;
7120 		}
7121 	}
7122 
7123 	if (!src_known &&
7124 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7125 		__mark_reg_unknown(env, dst_reg);
7126 		return 0;
7127 	}
7128 
7129 	if (sanitize_needed(opcode)) {
7130 		ret = sanitize_val_alu(env, insn);
7131 		if (ret < 0)
7132 			return sanitize_err(env, insn, ret, NULL, NULL);
7133 	}
7134 
7135 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7136 	 * There are two classes of instructions: The first class we track both
7137 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
7138 	 * greatest amount of precision when alu operations are mixed with jmp32
7139 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7140 	 * and BPF_OR. This is possible because these ops have fairly easy to
7141 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7142 	 * See alu32 verifier tests for examples. The second class of
7143 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7144 	 * with regards to tracking sign/unsigned bounds because the bits may
7145 	 * cross subreg boundaries in the alu64 case. When this happens we mark
7146 	 * the reg unbounded in the subreg bound space and use the resulting
7147 	 * tnum to calculate an approximation of the sign/unsigned bounds.
7148 	 */
7149 	switch (opcode) {
7150 	case BPF_ADD:
7151 		scalar32_min_max_add(dst_reg, &src_reg);
7152 		scalar_min_max_add(dst_reg, &src_reg);
7153 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7154 		break;
7155 	case BPF_SUB:
7156 		scalar32_min_max_sub(dst_reg, &src_reg);
7157 		scalar_min_max_sub(dst_reg, &src_reg);
7158 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7159 		break;
7160 	case BPF_MUL:
7161 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7162 		scalar32_min_max_mul(dst_reg, &src_reg);
7163 		scalar_min_max_mul(dst_reg, &src_reg);
7164 		break;
7165 	case BPF_AND:
7166 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7167 		scalar32_min_max_and(dst_reg, &src_reg);
7168 		scalar_min_max_and(dst_reg, &src_reg);
7169 		break;
7170 	case BPF_OR:
7171 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7172 		scalar32_min_max_or(dst_reg, &src_reg);
7173 		scalar_min_max_or(dst_reg, &src_reg);
7174 		break;
7175 	case BPF_XOR:
7176 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7177 		scalar32_min_max_xor(dst_reg, &src_reg);
7178 		scalar_min_max_xor(dst_reg, &src_reg);
7179 		break;
7180 	case BPF_LSH:
7181 		if (umax_val >= insn_bitness) {
7182 			/* Shifts greater than 31 or 63 are undefined.
7183 			 * This includes shifts by a negative number.
7184 			 */
7185 			mark_reg_unknown(env, regs, insn->dst_reg);
7186 			break;
7187 		}
7188 		if (alu32)
7189 			scalar32_min_max_lsh(dst_reg, &src_reg);
7190 		else
7191 			scalar_min_max_lsh(dst_reg, &src_reg);
7192 		break;
7193 	case BPF_RSH:
7194 		if (umax_val >= insn_bitness) {
7195 			/* Shifts greater than 31 or 63 are undefined.
7196 			 * This includes shifts by a negative number.
7197 			 */
7198 			mark_reg_unknown(env, regs, insn->dst_reg);
7199 			break;
7200 		}
7201 		if (alu32)
7202 			scalar32_min_max_rsh(dst_reg, &src_reg);
7203 		else
7204 			scalar_min_max_rsh(dst_reg, &src_reg);
7205 		break;
7206 	case BPF_ARSH:
7207 		if (umax_val >= insn_bitness) {
7208 			/* Shifts greater than 31 or 63 are undefined.
7209 			 * This includes shifts by a negative number.
7210 			 */
7211 			mark_reg_unknown(env, regs, insn->dst_reg);
7212 			break;
7213 		}
7214 		if (alu32)
7215 			scalar32_min_max_arsh(dst_reg, &src_reg);
7216 		else
7217 			scalar_min_max_arsh(dst_reg, &src_reg);
7218 		break;
7219 	default:
7220 		mark_reg_unknown(env, regs, insn->dst_reg);
7221 		break;
7222 	}
7223 
7224 	/* ALU32 ops are zero extended into 64bit register */
7225 	if (alu32)
7226 		zext_32_to_64(dst_reg);
7227 	reg_bounds_sync(dst_reg);
7228 	return 0;
7229 }
7230 
7231 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7232  * and var_off.
7233  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)7234 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7235 				   struct bpf_insn *insn)
7236 {
7237 	struct bpf_verifier_state *vstate = env->cur_state;
7238 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7239 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7240 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7241 	u8 opcode = BPF_OP(insn->code);
7242 	int err;
7243 
7244 	dst_reg = &regs[insn->dst_reg];
7245 	src_reg = NULL;
7246 	if (dst_reg->type != SCALAR_VALUE)
7247 		ptr_reg = dst_reg;
7248 	else
7249 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7250 		 * incorrectly propagated into other registers by find_equal_scalars()
7251 		 */
7252 		dst_reg->id = 0;
7253 	if (BPF_SRC(insn->code) == BPF_X) {
7254 		src_reg = &regs[insn->src_reg];
7255 		if (src_reg->type != SCALAR_VALUE) {
7256 			if (dst_reg->type != SCALAR_VALUE) {
7257 				/* Combining two pointers by any ALU op yields
7258 				 * an arbitrary scalar. Disallow all math except
7259 				 * pointer subtraction
7260 				 */
7261 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7262 					mark_reg_unknown(env, regs, insn->dst_reg);
7263 					return 0;
7264 				}
7265 				verbose(env, "R%d pointer %s pointer prohibited\n",
7266 					insn->dst_reg,
7267 					bpf_alu_string[opcode >> 4]);
7268 				return -EACCES;
7269 			} else {
7270 				/* scalar += pointer
7271 				 * This is legal, but we have to reverse our
7272 				 * src/dest handling in computing the range
7273 				 */
7274 				err = mark_chain_precision(env, insn->dst_reg);
7275 				if (err)
7276 					return err;
7277 				return adjust_ptr_min_max_vals(env, insn,
7278 							       src_reg, dst_reg);
7279 			}
7280 		} else if (ptr_reg) {
7281 			/* pointer += scalar */
7282 			err = mark_chain_precision(env, insn->src_reg);
7283 			if (err)
7284 				return err;
7285 			return adjust_ptr_min_max_vals(env, insn,
7286 						       dst_reg, src_reg);
7287 		} else if (dst_reg->precise) {
7288 			/* if dst_reg is precise, src_reg should be precise as well */
7289 			err = mark_chain_precision(env, insn->src_reg);
7290 			if (err)
7291 				return err;
7292 		}
7293 	} else {
7294 		/* Pretend the src is a reg with a known value, since we only
7295 		 * need to be able to read from this state.
7296 		 */
7297 		off_reg.type = SCALAR_VALUE;
7298 		__mark_reg_known(&off_reg, insn->imm);
7299 		src_reg = &off_reg;
7300 		if (ptr_reg) /* pointer += K */
7301 			return adjust_ptr_min_max_vals(env, insn,
7302 						       ptr_reg, src_reg);
7303 	}
7304 
7305 	/* Got here implies adding two SCALAR_VALUEs */
7306 	if (WARN_ON_ONCE(ptr_reg)) {
7307 		print_verifier_state(env, state);
7308 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
7309 		return -EINVAL;
7310 	}
7311 	if (WARN_ON(!src_reg)) {
7312 		print_verifier_state(env, state);
7313 		verbose(env, "verifier internal error: no src_reg\n");
7314 		return -EINVAL;
7315 	}
7316 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7317 }
7318 
7319 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)7320 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7321 {
7322 	struct bpf_reg_state *regs = cur_regs(env);
7323 	u8 opcode = BPF_OP(insn->code);
7324 	int err;
7325 
7326 	if (opcode == BPF_END || opcode == BPF_NEG) {
7327 		if (opcode == BPF_NEG) {
7328 			if (BPF_SRC(insn->code) != 0 ||
7329 			    insn->src_reg != BPF_REG_0 ||
7330 			    insn->off != 0 || insn->imm != 0) {
7331 				verbose(env, "BPF_NEG uses reserved fields\n");
7332 				return -EINVAL;
7333 			}
7334 		} else {
7335 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7336 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7337 			    BPF_CLASS(insn->code) == BPF_ALU64) {
7338 				verbose(env, "BPF_END uses reserved fields\n");
7339 				return -EINVAL;
7340 			}
7341 		}
7342 
7343 		/* check src operand */
7344 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7345 		if (err)
7346 			return err;
7347 
7348 		if (is_pointer_value(env, insn->dst_reg)) {
7349 			verbose(env, "R%d pointer arithmetic prohibited\n",
7350 				insn->dst_reg);
7351 			return -EACCES;
7352 		}
7353 
7354 		/* check dest operand */
7355 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
7356 		if (err)
7357 			return err;
7358 
7359 	} else if (opcode == BPF_MOV) {
7360 
7361 		if (BPF_SRC(insn->code) == BPF_X) {
7362 			if (insn->imm != 0 || insn->off != 0) {
7363 				verbose(env, "BPF_MOV uses reserved fields\n");
7364 				return -EINVAL;
7365 			}
7366 
7367 			/* check src operand */
7368 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7369 			if (err)
7370 				return err;
7371 		} else {
7372 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7373 				verbose(env, "BPF_MOV uses reserved fields\n");
7374 				return -EINVAL;
7375 			}
7376 		}
7377 
7378 		/* check dest operand, mark as required later */
7379 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7380 		if (err)
7381 			return err;
7382 
7383 		if (BPF_SRC(insn->code) == BPF_X) {
7384 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
7385 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7386 
7387 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7388 				/* case: R1 = R2
7389 				 * copy register state to dest reg
7390 				 */
7391 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7392 					/* Assign src and dst registers the same ID
7393 					 * that will be used by find_equal_scalars()
7394 					 * to propagate min/max range.
7395 					 */
7396 					src_reg->id = ++env->id_gen;
7397 				copy_register_state(dst_reg, src_reg);
7398 				dst_reg->live |= REG_LIVE_WRITTEN;
7399 				dst_reg->subreg_def = DEF_NOT_SUBREG;
7400 			} else {
7401 				/* R1 = (u32) R2 */
7402 				if (is_pointer_value(env, insn->src_reg)) {
7403 					verbose(env,
7404 						"R%d partial copy of pointer\n",
7405 						insn->src_reg);
7406 					return -EACCES;
7407 				} else if (src_reg->type == SCALAR_VALUE) {
7408 					copy_register_state(dst_reg, src_reg);
7409 					/* Make sure ID is cleared otherwise
7410 					 * dst_reg min/max could be incorrectly
7411 					 * propagated into src_reg by find_equal_scalars()
7412 					 */
7413 					dst_reg->id = 0;
7414 					dst_reg->live |= REG_LIVE_WRITTEN;
7415 					dst_reg->subreg_def = env->insn_idx + 1;
7416 				} else {
7417 					mark_reg_unknown(env, regs,
7418 							 insn->dst_reg);
7419 				}
7420 				zext_32_to_64(dst_reg);
7421 				reg_bounds_sync(dst_reg);
7422 			}
7423 		} else {
7424 			/* case: R = imm
7425 			 * remember the value we stored into this reg
7426 			 */
7427 			/* clear any state __mark_reg_known doesn't set */
7428 			mark_reg_unknown(env, regs, insn->dst_reg);
7429 			regs[insn->dst_reg].type = SCALAR_VALUE;
7430 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7431 				__mark_reg_known(regs + insn->dst_reg,
7432 						 insn->imm);
7433 			} else {
7434 				__mark_reg_known(regs + insn->dst_reg,
7435 						 (u32)insn->imm);
7436 			}
7437 		}
7438 
7439 	} else if (opcode > BPF_END) {
7440 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7441 		return -EINVAL;
7442 
7443 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
7444 
7445 		if (BPF_SRC(insn->code) == BPF_X) {
7446 			if (insn->imm != 0 || insn->off != 0) {
7447 				verbose(env, "BPF_ALU uses reserved fields\n");
7448 				return -EINVAL;
7449 			}
7450 			/* check src1 operand */
7451 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7452 			if (err)
7453 				return err;
7454 		} else {
7455 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7456 				verbose(env, "BPF_ALU uses reserved fields\n");
7457 				return -EINVAL;
7458 			}
7459 		}
7460 
7461 		/* check src2 operand */
7462 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7463 		if (err)
7464 			return err;
7465 
7466 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7467 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7468 			verbose(env, "div by zero\n");
7469 			return -EINVAL;
7470 		}
7471 
7472 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7473 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7474 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7475 
7476 			if (insn->imm < 0 || insn->imm >= size) {
7477 				verbose(env, "invalid shift %d\n", insn->imm);
7478 				return -EINVAL;
7479 			}
7480 		}
7481 
7482 		/* check dest operand */
7483 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7484 		if (err)
7485 			return err;
7486 
7487 		return adjust_reg_min_max_vals(env, insn);
7488 	}
7489 
7490 	return 0;
7491 }
7492 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)7493 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7494 				   struct bpf_reg_state *dst_reg,
7495 				   enum bpf_reg_type type,
7496 				   bool range_right_open)
7497 {
7498 	struct bpf_func_state *state;
7499 	struct bpf_reg_state *reg;
7500 	int new_range;
7501 
7502 	if (dst_reg->off < 0 ||
7503 	    (dst_reg->off == 0 && range_right_open))
7504 		/* This doesn't give us any range */
7505 		return;
7506 
7507 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
7508 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7509 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
7510 		 * than pkt_end, but that's because it's also less than pkt.
7511 		 */
7512 		return;
7513 
7514 	new_range = dst_reg->off;
7515 	if (range_right_open)
7516 		new_range++;
7517 
7518 	/* Examples for register markings:
7519 	 *
7520 	 * pkt_data in dst register:
7521 	 *
7522 	 *   r2 = r3;
7523 	 *   r2 += 8;
7524 	 *   if (r2 > pkt_end) goto <handle exception>
7525 	 *   <access okay>
7526 	 *
7527 	 *   r2 = r3;
7528 	 *   r2 += 8;
7529 	 *   if (r2 < pkt_end) goto <access okay>
7530 	 *   <handle exception>
7531 	 *
7532 	 *   Where:
7533 	 *     r2 == dst_reg, pkt_end == src_reg
7534 	 *     r2=pkt(id=n,off=8,r=0)
7535 	 *     r3=pkt(id=n,off=0,r=0)
7536 	 *
7537 	 * pkt_data in src register:
7538 	 *
7539 	 *   r2 = r3;
7540 	 *   r2 += 8;
7541 	 *   if (pkt_end >= r2) goto <access okay>
7542 	 *   <handle exception>
7543 	 *
7544 	 *   r2 = r3;
7545 	 *   r2 += 8;
7546 	 *   if (pkt_end <= r2) goto <handle exception>
7547 	 *   <access okay>
7548 	 *
7549 	 *   Where:
7550 	 *     pkt_end == dst_reg, r2 == src_reg
7551 	 *     r2=pkt(id=n,off=8,r=0)
7552 	 *     r3=pkt(id=n,off=0,r=0)
7553 	 *
7554 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7555 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7556 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
7557 	 * the check.
7558 	 */
7559 
7560 	/* If our ids match, then we must have the same max_value.  And we
7561 	 * don't care about the other reg's fixed offset, since if it's too big
7562 	 * the range won't allow anything.
7563 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7564 	 */
7565 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7566 		if (reg->type == type && reg->id == dst_reg->id)
7567 			/* keep the maximum range already checked */
7568 			reg->range = max(reg->range, new_range);
7569 	}));
7570 }
7571 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)7572 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7573 {
7574 	struct tnum subreg = tnum_subreg(reg->var_off);
7575 	s32 sval = (s32)val;
7576 
7577 	switch (opcode) {
7578 	case BPF_JEQ:
7579 		if (tnum_is_const(subreg))
7580 			return !!tnum_equals_const(subreg, val);
7581 		break;
7582 	case BPF_JNE:
7583 		if (tnum_is_const(subreg))
7584 			return !tnum_equals_const(subreg, val);
7585 		break;
7586 	case BPF_JSET:
7587 		if ((~subreg.mask & subreg.value) & val)
7588 			return 1;
7589 		if (!((subreg.mask | subreg.value) & val))
7590 			return 0;
7591 		break;
7592 	case BPF_JGT:
7593 		if (reg->u32_min_value > val)
7594 			return 1;
7595 		else if (reg->u32_max_value <= val)
7596 			return 0;
7597 		break;
7598 	case BPF_JSGT:
7599 		if (reg->s32_min_value > sval)
7600 			return 1;
7601 		else if (reg->s32_max_value <= sval)
7602 			return 0;
7603 		break;
7604 	case BPF_JLT:
7605 		if (reg->u32_max_value < val)
7606 			return 1;
7607 		else if (reg->u32_min_value >= val)
7608 			return 0;
7609 		break;
7610 	case BPF_JSLT:
7611 		if (reg->s32_max_value < sval)
7612 			return 1;
7613 		else if (reg->s32_min_value >= sval)
7614 			return 0;
7615 		break;
7616 	case BPF_JGE:
7617 		if (reg->u32_min_value >= val)
7618 			return 1;
7619 		else if (reg->u32_max_value < val)
7620 			return 0;
7621 		break;
7622 	case BPF_JSGE:
7623 		if (reg->s32_min_value >= sval)
7624 			return 1;
7625 		else if (reg->s32_max_value < sval)
7626 			return 0;
7627 		break;
7628 	case BPF_JLE:
7629 		if (reg->u32_max_value <= val)
7630 			return 1;
7631 		else if (reg->u32_min_value > val)
7632 			return 0;
7633 		break;
7634 	case BPF_JSLE:
7635 		if (reg->s32_max_value <= sval)
7636 			return 1;
7637 		else if (reg->s32_min_value > sval)
7638 			return 0;
7639 		break;
7640 	}
7641 
7642 	return -1;
7643 }
7644 
7645 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)7646 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7647 {
7648 	s64 sval = (s64)val;
7649 
7650 	switch (opcode) {
7651 	case BPF_JEQ:
7652 		if (tnum_is_const(reg->var_off))
7653 			return !!tnum_equals_const(reg->var_off, val);
7654 		break;
7655 	case BPF_JNE:
7656 		if (tnum_is_const(reg->var_off))
7657 			return !tnum_equals_const(reg->var_off, val);
7658 		break;
7659 	case BPF_JSET:
7660 		if ((~reg->var_off.mask & reg->var_off.value) & val)
7661 			return 1;
7662 		if (!((reg->var_off.mask | reg->var_off.value) & val))
7663 			return 0;
7664 		break;
7665 	case BPF_JGT:
7666 		if (reg->umin_value > val)
7667 			return 1;
7668 		else if (reg->umax_value <= val)
7669 			return 0;
7670 		break;
7671 	case BPF_JSGT:
7672 		if (reg->smin_value > sval)
7673 			return 1;
7674 		else if (reg->smax_value <= sval)
7675 			return 0;
7676 		break;
7677 	case BPF_JLT:
7678 		if (reg->umax_value < val)
7679 			return 1;
7680 		else if (reg->umin_value >= val)
7681 			return 0;
7682 		break;
7683 	case BPF_JSLT:
7684 		if (reg->smax_value < sval)
7685 			return 1;
7686 		else if (reg->smin_value >= sval)
7687 			return 0;
7688 		break;
7689 	case BPF_JGE:
7690 		if (reg->umin_value >= val)
7691 			return 1;
7692 		else if (reg->umax_value < val)
7693 			return 0;
7694 		break;
7695 	case BPF_JSGE:
7696 		if (reg->smin_value >= sval)
7697 			return 1;
7698 		else if (reg->smax_value < sval)
7699 			return 0;
7700 		break;
7701 	case BPF_JLE:
7702 		if (reg->umax_value <= val)
7703 			return 1;
7704 		else if (reg->umin_value > val)
7705 			return 0;
7706 		break;
7707 	case BPF_JSLE:
7708 		if (reg->smax_value <= sval)
7709 			return 1;
7710 		else if (reg->smin_value > sval)
7711 			return 0;
7712 		break;
7713 	}
7714 
7715 	return -1;
7716 }
7717 
7718 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7719  * and return:
7720  *  1 - branch will be taken and "goto target" will be executed
7721  *  0 - branch will not be taken and fall-through to next insn
7722  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7723  *      range [0,10]
7724  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)7725 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7726 			   bool is_jmp32)
7727 {
7728 	if (__is_pointer_value(false, reg)) {
7729 		if (!reg_type_not_null(reg->type))
7730 			return -1;
7731 
7732 		/* If pointer is valid tests against zero will fail so we can
7733 		 * use this to direct branch taken.
7734 		 */
7735 		if (val != 0)
7736 			return -1;
7737 
7738 		switch (opcode) {
7739 		case BPF_JEQ:
7740 			return 0;
7741 		case BPF_JNE:
7742 			return 1;
7743 		default:
7744 			return -1;
7745 		}
7746 	}
7747 
7748 	if (is_jmp32)
7749 		return is_branch32_taken(reg, val, opcode);
7750 	return is_branch64_taken(reg, val, opcode);
7751 }
7752 
flip_opcode(u32 opcode)7753 static int flip_opcode(u32 opcode)
7754 {
7755 	/* How can we transform "a <op> b" into "b <op> a"? */
7756 	static const u8 opcode_flip[16] = {
7757 		/* these stay the same */
7758 		[BPF_JEQ  >> 4] = BPF_JEQ,
7759 		[BPF_JNE  >> 4] = BPF_JNE,
7760 		[BPF_JSET >> 4] = BPF_JSET,
7761 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
7762 		[BPF_JGE  >> 4] = BPF_JLE,
7763 		[BPF_JGT  >> 4] = BPF_JLT,
7764 		[BPF_JLE  >> 4] = BPF_JGE,
7765 		[BPF_JLT  >> 4] = BPF_JGT,
7766 		[BPF_JSGE >> 4] = BPF_JSLE,
7767 		[BPF_JSGT >> 4] = BPF_JSLT,
7768 		[BPF_JSLE >> 4] = BPF_JSGE,
7769 		[BPF_JSLT >> 4] = BPF_JSGT
7770 	};
7771 	return opcode_flip[opcode >> 4];
7772 }
7773 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)7774 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7775 				   struct bpf_reg_state *src_reg,
7776 				   u8 opcode)
7777 {
7778 	struct bpf_reg_state *pkt;
7779 
7780 	if (src_reg->type == PTR_TO_PACKET_END) {
7781 		pkt = dst_reg;
7782 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
7783 		pkt = src_reg;
7784 		opcode = flip_opcode(opcode);
7785 	} else {
7786 		return -1;
7787 	}
7788 
7789 	if (pkt->range >= 0)
7790 		return -1;
7791 
7792 	switch (opcode) {
7793 	case BPF_JLE:
7794 		/* pkt <= pkt_end */
7795 		fallthrough;
7796 	case BPF_JGT:
7797 		/* pkt > pkt_end */
7798 		if (pkt->range == BEYOND_PKT_END)
7799 			/* pkt has at last one extra byte beyond pkt_end */
7800 			return opcode == BPF_JGT;
7801 		break;
7802 	case BPF_JLT:
7803 		/* pkt < pkt_end */
7804 		fallthrough;
7805 	case BPF_JGE:
7806 		/* pkt >= pkt_end */
7807 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7808 			return opcode == BPF_JGE;
7809 		break;
7810 	}
7811 	return -1;
7812 }
7813 
7814 /* Adjusts the register min/max values in the case that the dst_reg is the
7815  * variable register that we are working on, and src_reg is a constant or we're
7816  * simply doing a BPF_K check.
7817  * In JEQ/JNE cases we also adjust the var_off values.
7818  */
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)7819 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7820 			    struct bpf_reg_state *false_reg,
7821 			    u64 val, u32 val32,
7822 			    u8 opcode, bool is_jmp32)
7823 {
7824 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
7825 	struct tnum false_64off = false_reg->var_off;
7826 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
7827 	struct tnum true_64off = true_reg->var_off;
7828 	s64 sval = (s64)val;
7829 	s32 sval32 = (s32)val32;
7830 
7831 	/* If the dst_reg is a pointer, we can't learn anything about its
7832 	 * variable offset from the compare (unless src_reg were a pointer into
7833 	 * the same object, but we don't bother with that.
7834 	 * Since false_reg and true_reg have the same type by construction, we
7835 	 * only need to check one of them for pointerness.
7836 	 */
7837 	if (__is_pointer_value(false, false_reg))
7838 		return;
7839 
7840 	switch (opcode) {
7841 	/* JEQ/JNE comparison doesn't change the register equivalence.
7842 	 *
7843 	 * r1 = r2;
7844 	 * if (r1 == 42) goto label;
7845 	 * ...
7846 	 * label: // here both r1 and r2 are known to be 42.
7847 	 *
7848 	 * Hence when marking register as known preserve it's ID.
7849 	 */
7850 	case BPF_JEQ:
7851 		if (is_jmp32) {
7852 			__mark_reg32_known(true_reg, val32);
7853 			true_32off = tnum_subreg(true_reg->var_off);
7854 		} else {
7855 			___mark_reg_known(true_reg, val);
7856 			true_64off = true_reg->var_off;
7857 		}
7858 		break;
7859 	case BPF_JNE:
7860 		if (is_jmp32) {
7861 			__mark_reg32_known(false_reg, val32);
7862 			false_32off = tnum_subreg(false_reg->var_off);
7863 		} else {
7864 			___mark_reg_known(false_reg, val);
7865 			false_64off = false_reg->var_off;
7866 		}
7867 		break;
7868 	case BPF_JSET:
7869 		if (is_jmp32) {
7870 			false_32off = tnum_and(false_32off, tnum_const(~val32));
7871 			if (is_power_of_2(val32))
7872 				true_32off = tnum_or(true_32off,
7873 						     tnum_const(val32));
7874 		} else {
7875 			false_64off = tnum_and(false_64off, tnum_const(~val));
7876 			if (is_power_of_2(val))
7877 				true_64off = tnum_or(true_64off,
7878 						     tnum_const(val));
7879 		}
7880 		break;
7881 	case BPF_JGE:
7882 	case BPF_JGT:
7883 	{
7884 		if (is_jmp32) {
7885 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7886 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7887 
7888 			false_reg->u32_max_value = min(false_reg->u32_max_value,
7889 						       false_umax);
7890 			true_reg->u32_min_value = max(true_reg->u32_min_value,
7891 						      true_umin);
7892 		} else {
7893 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7894 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7895 
7896 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
7897 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
7898 		}
7899 		break;
7900 	}
7901 	case BPF_JSGE:
7902 	case BPF_JSGT:
7903 	{
7904 		if (is_jmp32) {
7905 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7906 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7907 
7908 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7909 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7910 		} else {
7911 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7912 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7913 
7914 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
7915 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
7916 		}
7917 		break;
7918 	}
7919 	case BPF_JLE:
7920 	case BPF_JLT:
7921 	{
7922 		if (is_jmp32) {
7923 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7924 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7925 
7926 			false_reg->u32_min_value = max(false_reg->u32_min_value,
7927 						       false_umin);
7928 			true_reg->u32_max_value = min(true_reg->u32_max_value,
7929 						      true_umax);
7930 		} else {
7931 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7932 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7933 
7934 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
7935 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
7936 		}
7937 		break;
7938 	}
7939 	case BPF_JSLE:
7940 	case BPF_JSLT:
7941 	{
7942 		if (is_jmp32) {
7943 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7944 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7945 
7946 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7947 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7948 		} else {
7949 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7950 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7951 
7952 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
7953 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
7954 		}
7955 		break;
7956 	}
7957 	default:
7958 		return;
7959 	}
7960 
7961 	if (is_jmp32) {
7962 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7963 					     tnum_subreg(false_32off));
7964 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7965 					    tnum_subreg(true_32off));
7966 		__reg_combine_32_into_64(false_reg);
7967 		__reg_combine_32_into_64(true_reg);
7968 	} else {
7969 		false_reg->var_off = false_64off;
7970 		true_reg->var_off = true_64off;
7971 		__reg_combine_64_into_32(false_reg);
7972 		__reg_combine_64_into_32(true_reg);
7973 	}
7974 }
7975 
7976 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7977  * the variable reg.
7978  */
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)7979 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7980 				struct bpf_reg_state *false_reg,
7981 				u64 val, u32 val32,
7982 				u8 opcode, bool is_jmp32)
7983 {
7984 	opcode = flip_opcode(opcode);
7985 	/* This uses zero as "not present in table"; luckily the zero opcode,
7986 	 * BPF_JA, can't get here.
7987 	 */
7988 	if (opcode)
7989 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7990 }
7991 
7992 /* 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)7993 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7994 				  struct bpf_reg_state *dst_reg)
7995 {
7996 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7997 							dst_reg->umin_value);
7998 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7999 							dst_reg->umax_value);
8000 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8001 							dst_reg->smin_value);
8002 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8003 							dst_reg->smax_value);
8004 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8005 							     dst_reg->var_off);
8006 	reg_bounds_sync(src_reg);
8007 	reg_bounds_sync(dst_reg);
8008 }
8009 
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)8010 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8011 				struct bpf_reg_state *true_dst,
8012 				struct bpf_reg_state *false_src,
8013 				struct bpf_reg_state *false_dst,
8014 				u8 opcode)
8015 {
8016 	switch (opcode) {
8017 	case BPF_JEQ:
8018 		__reg_combine_min_max(true_src, true_dst);
8019 		break;
8020 	case BPF_JNE:
8021 		__reg_combine_min_max(false_src, false_dst);
8022 		break;
8023 	}
8024 }
8025 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)8026 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8027 				 struct bpf_reg_state *reg, u32 id,
8028 				 bool is_null)
8029 {
8030 	if (type_may_be_null(reg->type) && reg->id == id &&
8031 	    !WARN_ON_ONCE(!reg->id)) {
8032 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8033 				 !tnum_equals_const(reg->var_off, 0) ||
8034 				 reg->off)) {
8035 			/* Old offset (both fixed and variable parts) should
8036 			 * have been known-zero, because we don't allow pointer
8037 			 * arithmetic on pointers that might be NULL. If we
8038 			 * see this happening, don't convert the register.
8039 			 */
8040 			return;
8041 		}
8042 		if (is_null) {
8043 			reg->type = SCALAR_VALUE;
8044 		} else if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
8045 			const struct bpf_map *map = reg->map_ptr;
8046 
8047 			if (map->inner_map_meta) {
8048 				reg->type = CONST_PTR_TO_MAP;
8049 				reg->map_ptr = map->inner_map_meta;
8050 			} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
8051 				reg->type = PTR_TO_XDP_SOCK;
8052 			} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
8053 				   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
8054 				reg->type = PTR_TO_SOCKET;
8055 			} else {
8056 				reg->type = PTR_TO_MAP_VALUE;
8057 			}
8058 		} else {
8059 			reg->type &= ~PTR_MAYBE_NULL;
8060 		}
8061 
8062 		if (is_null) {
8063 			/* We don't need id and ref_obj_id from this point
8064 			 * onwards anymore, thus we should better reset it,
8065 			 * so that state pruning has chances to take effect.
8066 			 */
8067 			reg->id = 0;
8068 			reg->ref_obj_id = 0;
8069 		} else if (!reg_may_point_to_spin_lock(reg)) {
8070 			/* For not-NULL ptr, reg->ref_obj_id will be reset
8071 			 * in release_reference().
8072 			 *
8073 			 * reg->id is still used by spin_lock ptr. Other
8074 			 * than spin_lock ptr type, reg->id can be reset.
8075 			 */
8076 			reg->id = 0;
8077 		}
8078 	}
8079 }
8080 
8081 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8082  * be folded together at some point.
8083  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)8084 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8085 				  bool is_null)
8086 {
8087 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8088 	struct bpf_reg_state *regs = state->regs, *reg;
8089 	u32 ref_obj_id = regs[regno].ref_obj_id;
8090 	u32 id = regs[regno].id;
8091 
8092 	if (ref_obj_id && ref_obj_id == id && is_null)
8093 		/* regs[regno] is in the " == NULL" branch.
8094 		 * No one could have freed the reference state before
8095 		 * doing the NULL check.
8096 		 */
8097 		WARN_ON_ONCE(release_reference_state(state, id));
8098 
8099 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8100 		mark_ptr_or_null_reg(state, reg, id, is_null);
8101 	}));
8102 }
8103 
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)8104 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8105 				   struct bpf_reg_state *dst_reg,
8106 				   struct bpf_reg_state *src_reg,
8107 				   struct bpf_verifier_state *this_branch,
8108 				   struct bpf_verifier_state *other_branch)
8109 {
8110 	if (BPF_SRC(insn->code) != BPF_X)
8111 		return false;
8112 
8113 	/* Pointers are always 64-bit. */
8114 	if (BPF_CLASS(insn->code) == BPF_JMP32)
8115 		return false;
8116 
8117 	switch (BPF_OP(insn->code)) {
8118 	case BPF_JGT:
8119 		if ((dst_reg->type == PTR_TO_PACKET &&
8120 		     src_reg->type == PTR_TO_PACKET_END) ||
8121 		    (dst_reg->type == PTR_TO_PACKET_META &&
8122 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8123 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8124 			find_good_pkt_pointers(this_branch, dst_reg,
8125 					       dst_reg->type, false);
8126 			mark_pkt_end(other_branch, insn->dst_reg, true);
8127 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8128 			    src_reg->type == PTR_TO_PACKET) ||
8129 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8130 			    src_reg->type == PTR_TO_PACKET_META)) {
8131 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
8132 			find_good_pkt_pointers(other_branch, src_reg,
8133 					       src_reg->type, true);
8134 			mark_pkt_end(this_branch, insn->src_reg, false);
8135 		} else {
8136 			return false;
8137 		}
8138 		break;
8139 	case BPF_JLT:
8140 		if ((dst_reg->type == PTR_TO_PACKET &&
8141 		     src_reg->type == PTR_TO_PACKET_END) ||
8142 		    (dst_reg->type == PTR_TO_PACKET_META &&
8143 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8144 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8145 			find_good_pkt_pointers(other_branch, dst_reg,
8146 					       dst_reg->type, true);
8147 			mark_pkt_end(this_branch, insn->dst_reg, false);
8148 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8149 			    src_reg->type == PTR_TO_PACKET) ||
8150 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8151 			    src_reg->type == PTR_TO_PACKET_META)) {
8152 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
8153 			find_good_pkt_pointers(this_branch, src_reg,
8154 					       src_reg->type, false);
8155 			mark_pkt_end(other_branch, insn->src_reg, true);
8156 		} else {
8157 			return false;
8158 		}
8159 		break;
8160 	case BPF_JGE:
8161 		if ((dst_reg->type == PTR_TO_PACKET &&
8162 		     src_reg->type == PTR_TO_PACKET_END) ||
8163 		    (dst_reg->type == PTR_TO_PACKET_META &&
8164 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8165 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8166 			find_good_pkt_pointers(this_branch, dst_reg,
8167 					       dst_reg->type, true);
8168 			mark_pkt_end(other_branch, insn->dst_reg, false);
8169 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8170 			    src_reg->type == PTR_TO_PACKET) ||
8171 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8172 			    src_reg->type == PTR_TO_PACKET_META)) {
8173 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8174 			find_good_pkt_pointers(other_branch, src_reg,
8175 					       src_reg->type, false);
8176 			mark_pkt_end(this_branch, insn->src_reg, true);
8177 		} else {
8178 			return false;
8179 		}
8180 		break;
8181 	case BPF_JLE:
8182 		if ((dst_reg->type == PTR_TO_PACKET &&
8183 		     src_reg->type == PTR_TO_PACKET_END) ||
8184 		    (dst_reg->type == PTR_TO_PACKET_META &&
8185 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8186 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8187 			find_good_pkt_pointers(other_branch, dst_reg,
8188 					       dst_reg->type, false);
8189 			mark_pkt_end(this_branch, insn->dst_reg, true);
8190 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8191 			    src_reg->type == PTR_TO_PACKET) ||
8192 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8193 			    src_reg->type == PTR_TO_PACKET_META)) {
8194 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8195 			find_good_pkt_pointers(this_branch, src_reg,
8196 					       src_reg->type, true);
8197 			mark_pkt_end(other_branch, insn->src_reg, false);
8198 		} else {
8199 			return false;
8200 		}
8201 		break;
8202 	default:
8203 		return false;
8204 	}
8205 
8206 	return true;
8207 }
8208 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)8209 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8210 			       struct bpf_reg_state *known_reg)
8211 {
8212 	struct bpf_func_state *state;
8213 	struct bpf_reg_state *reg;
8214 
8215 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8216 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) {
8217 			s32 saved_subreg_def = reg->subreg_def;
8218 
8219 			copy_register_state(reg, known_reg);
8220 			reg->subreg_def = saved_subreg_def;
8221 		}
8222 	}));
8223 }
8224 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)8225 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8226 			     struct bpf_insn *insn, int *insn_idx)
8227 {
8228 	struct bpf_verifier_state *this_branch = env->cur_state;
8229 	struct bpf_verifier_state *other_branch;
8230 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8231 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8232 	u8 opcode = BPF_OP(insn->code);
8233 	bool is_jmp32;
8234 	int pred = -1;
8235 	int err;
8236 
8237 	/* Only conditional jumps are expected to reach here. */
8238 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8239 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8240 		return -EINVAL;
8241 	}
8242 
8243 	if (BPF_SRC(insn->code) == BPF_X) {
8244 		if (insn->imm != 0) {
8245 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8246 			return -EINVAL;
8247 		}
8248 
8249 		/* check src1 operand */
8250 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8251 		if (err)
8252 			return err;
8253 
8254 		if (is_pointer_value(env, insn->src_reg)) {
8255 			verbose(env, "R%d pointer comparison prohibited\n",
8256 				insn->src_reg);
8257 			return -EACCES;
8258 		}
8259 		src_reg = &regs[insn->src_reg];
8260 	} else {
8261 		if (insn->src_reg != BPF_REG_0) {
8262 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8263 			return -EINVAL;
8264 		}
8265 	}
8266 
8267 	/* check src2 operand */
8268 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8269 	if (err)
8270 		return err;
8271 
8272 	dst_reg = &regs[insn->dst_reg];
8273 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8274 
8275 	if (BPF_SRC(insn->code) == BPF_K) {
8276 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8277 	} else if (src_reg->type == SCALAR_VALUE &&
8278 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8279 		pred = is_branch_taken(dst_reg,
8280 				       tnum_subreg(src_reg->var_off).value,
8281 				       opcode,
8282 				       is_jmp32);
8283 	} else if (src_reg->type == SCALAR_VALUE &&
8284 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8285 		pred = is_branch_taken(dst_reg,
8286 				       src_reg->var_off.value,
8287 				       opcode,
8288 				       is_jmp32);
8289 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8290 		   reg_is_pkt_pointer_any(src_reg) &&
8291 		   !is_jmp32) {
8292 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8293 	}
8294 
8295 	if (pred >= 0) {
8296 		/* If we get here with a dst_reg pointer type it is because
8297 		 * above is_branch_taken() special cased the 0 comparison.
8298 		 */
8299 		if (!__is_pointer_value(false, dst_reg))
8300 			err = mark_chain_precision(env, insn->dst_reg);
8301 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8302 		    !__is_pointer_value(false, src_reg))
8303 			err = mark_chain_precision(env, insn->src_reg);
8304 		if (err)
8305 			return err;
8306 	}
8307 
8308 	if (pred == 1) {
8309 		/* Only follow the goto, ignore fall-through. If needed, push
8310 		 * the fall-through branch for simulation under speculative
8311 		 * execution.
8312 		 */
8313 		if (!env->bypass_spec_v1 &&
8314 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
8315 					       *insn_idx))
8316 			return -EFAULT;
8317 		*insn_idx += insn->off;
8318 		return 0;
8319 	} else if (pred == 0) {
8320 		/* Only follow the fall-through branch, since that's where the
8321 		 * program will go. If needed, push the goto branch for
8322 		 * simulation under speculative execution.
8323 		 */
8324 		if (!env->bypass_spec_v1 &&
8325 		    !sanitize_speculative_path(env, insn,
8326 					       *insn_idx + insn->off + 1,
8327 					       *insn_idx))
8328 			return -EFAULT;
8329 		return 0;
8330 	}
8331 
8332 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8333 				  false);
8334 	if (!other_branch)
8335 		return -EFAULT;
8336 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8337 
8338 	/* detect if we are comparing against a constant value so we can adjust
8339 	 * our min/max values for our dst register.
8340 	 * this is only legit if both are scalars (or pointers to the same
8341 	 * object, I suppose, but we don't support that right now), because
8342 	 * otherwise the different base pointers mean the offsets aren't
8343 	 * comparable.
8344 	 */
8345 	if (BPF_SRC(insn->code) == BPF_X) {
8346 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8347 
8348 		if (dst_reg->type == SCALAR_VALUE &&
8349 		    src_reg->type == SCALAR_VALUE) {
8350 			if (tnum_is_const(src_reg->var_off) ||
8351 			    (is_jmp32 &&
8352 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8353 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8354 						dst_reg,
8355 						src_reg->var_off.value,
8356 						tnum_subreg(src_reg->var_off).value,
8357 						opcode, is_jmp32);
8358 			else if (tnum_is_const(dst_reg->var_off) ||
8359 				 (is_jmp32 &&
8360 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8361 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8362 						    src_reg,
8363 						    dst_reg->var_off.value,
8364 						    tnum_subreg(dst_reg->var_off).value,
8365 						    opcode, is_jmp32);
8366 			else if (!is_jmp32 &&
8367 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8368 				/* Comparing for equality, we can combine knowledge */
8369 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8370 						    &other_branch_regs[insn->dst_reg],
8371 						    src_reg, dst_reg, opcode);
8372 			if (src_reg->id &&
8373 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8374 				find_equal_scalars(this_branch, src_reg);
8375 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8376 			}
8377 
8378 		}
8379 	} else if (dst_reg->type == SCALAR_VALUE) {
8380 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8381 					dst_reg, insn->imm, (u32)insn->imm,
8382 					opcode, is_jmp32);
8383 	}
8384 
8385 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8386 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8387 		find_equal_scalars(this_branch, dst_reg);
8388 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8389 	}
8390 
8391 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8392 	 * NOTE: these optimizations below are related with pointer comparison
8393 	 *       which will never be JMP32.
8394 	 */
8395 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8396 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8397 	    type_may_be_null(dst_reg->type)) {
8398 		/* Mark all identical registers in each branch as either
8399 		 * safe or unknown depending R == 0 or R != 0 conditional.
8400 		 */
8401 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8402 				      opcode == BPF_JNE);
8403 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8404 				      opcode == BPF_JEQ);
8405 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8406 					   this_branch, other_branch) &&
8407 		   is_pointer_value(env, insn->dst_reg)) {
8408 		verbose(env, "R%d pointer comparison prohibited\n",
8409 			insn->dst_reg);
8410 		return -EACCES;
8411 	}
8412 	if (env->log.level & BPF_LOG_LEVEL)
8413 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8414 	return 0;
8415 }
8416 
8417 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)8418 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8419 {
8420 	struct bpf_insn_aux_data *aux = cur_aux(env);
8421 	struct bpf_reg_state *regs = cur_regs(env);
8422 	struct bpf_reg_state *dst_reg;
8423 	struct bpf_map *map;
8424 	int err;
8425 
8426 	if (BPF_SIZE(insn->code) != BPF_DW) {
8427 		verbose(env, "invalid BPF_LD_IMM insn\n");
8428 		return -EINVAL;
8429 	}
8430 	if (insn->off != 0) {
8431 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8432 		return -EINVAL;
8433 	}
8434 
8435 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8436 	if (err)
8437 		return err;
8438 
8439 	dst_reg = &regs[insn->dst_reg];
8440 	if (insn->src_reg == 0) {
8441 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8442 
8443 		dst_reg->type = SCALAR_VALUE;
8444 		__mark_reg_known(&regs[insn->dst_reg], imm);
8445 		return 0;
8446 	}
8447 
8448 	/* All special src_reg cases are listed below. From this point onwards
8449 	 * we either succeed and assign a corresponding dst_reg->type after
8450 	 * zeroing the offset, or fail and reject the program.
8451 	 */
8452 	mark_reg_known_zero(env, regs, insn->dst_reg);
8453 
8454 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8455 		dst_reg->type = aux->btf_var.reg_type;
8456 		switch (base_type(dst_reg->type)) {
8457 		case PTR_TO_MEM:
8458 			dst_reg->mem_size = aux->btf_var.mem_size;
8459 			break;
8460 		case PTR_TO_BTF_ID:
8461 		case PTR_TO_PERCPU_BTF_ID:
8462 			dst_reg->btf_id = aux->btf_var.btf_id;
8463 			break;
8464 		default:
8465 			verbose(env, "bpf verifier is misconfigured\n");
8466 			return -EFAULT;
8467 		}
8468 		return 0;
8469 	}
8470 
8471 	map = env->used_maps[aux->map_index];
8472 	dst_reg->map_ptr = map;
8473 
8474 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8475 		dst_reg->type = PTR_TO_MAP_VALUE;
8476 		dst_reg->off = aux->map_off;
8477 		if (map_value_has_spin_lock(map))
8478 			dst_reg->id = ++env->id_gen;
8479 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8480 		dst_reg->type = CONST_PTR_TO_MAP;
8481 	} else {
8482 		verbose(env, "bpf verifier is misconfigured\n");
8483 		return -EINVAL;
8484 	}
8485 
8486 	return 0;
8487 }
8488 
may_access_skb(enum bpf_prog_type type)8489 static bool may_access_skb(enum bpf_prog_type type)
8490 {
8491 	switch (type) {
8492 	case BPF_PROG_TYPE_SOCKET_FILTER:
8493 	case BPF_PROG_TYPE_SCHED_CLS:
8494 	case BPF_PROG_TYPE_SCHED_ACT:
8495 		return true;
8496 	default:
8497 		return false;
8498 	}
8499 }
8500 
8501 /* verify safety of LD_ABS|LD_IND instructions:
8502  * - they can only appear in the programs where ctx == skb
8503  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8504  *   preserve R6-R9, and store return value into R0
8505  *
8506  * Implicit input:
8507  *   ctx == skb == R6 == CTX
8508  *
8509  * Explicit input:
8510  *   SRC == any register
8511  *   IMM == 32-bit immediate
8512  *
8513  * Output:
8514  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8515  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)8516 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8517 {
8518 	struct bpf_reg_state *regs = cur_regs(env);
8519 	static const int ctx_reg = BPF_REG_6;
8520 	u8 mode = BPF_MODE(insn->code);
8521 	int i, err;
8522 
8523 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8524 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8525 		return -EINVAL;
8526 	}
8527 
8528 	if (!env->ops->gen_ld_abs) {
8529 		verbose(env, "bpf verifier is misconfigured\n");
8530 		return -EINVAL;
8531 	}
8532 
8533 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8534 	    BPF_SIZE(insn->code) == BPF_DW ||
8535 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8536 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8537 		return -EINVAL;
8538 	}
8539 
8540 	/* check whether implicit source operand (register R6) is readable */
8541 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8542 	if (err)
8543 		return err;
8544 
8545 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8546 	 * gen_ld_abs() may terminate the program at runtime, leading to
8547 	 * reference leak.
8548 	 */
8549 	err = check_reference_leak(env);
8550 	if (err) {
8551 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8552 		return err;
8553 	}
8554 
8555 	if (env->cur_state->active_spin_lock) {
8556 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8557 		return -EINVAL;
8558 	}
8559 
8560 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8561 		verbose(env,
8562 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8563 		return -EINVAL;
8564 	}
8565 
8566 	if (mode == BPF_IND) {
8567 		/* check explicit source operand */
8568 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8569 		if (err)
8570 			return err;
8571 	}
8572 
8573 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
8574 	if (err < 0)
8575 		return err;
8576 
8577 	/* reset caller saved regs to unreadable */
8578 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8579 		mark_reg_not_init(env, regs, caller_saved[i]);
8580 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8581 	}
8582 
8583 	/* mark destination R0 register as readable, since it contains
8584 	 * the value fetched from the packet.
8585 	 * Already marked as written above.
8586 	 */
8587 	mark_reg_unknown(env, regs, BPF_REG_0);
8588 	/* ld_abs load up to 32-bit skb data. */
8589 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8590 	return 0;
8591 }
8592 
check_return_code(struct bpf_verifier_env * env)8593 static int check_return_code(struct bpf_verifier_env *env)
8594 {
8595 	struct tnum enforce_attach_type_range = tnum_unknown;
8596 	const struct bpf_prog *prog = env->prog;
8597 	struct bpf_reg_state *reg;
8598 	struct tnum range = tnum_range(0, 1);
8599 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8600 	int err;
8601 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8602 
8603 	/* LSM and struct_ops func-ptr's return type could be "void" */
8604 	if (!is_subprog &&
8605 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8606 	     prog_type == BPF_PROG_TYPE_LSM) &&
8607 	    !prog->aux->attach_func_proto->type)
8608 		return 0;
8609 
8610 	/* eBPF calling convetion is such that R0 is used
8611 	 * to return the value from eBPF program.
8612 	 * Make sure that it's readable at this time
8613 	 * of bpf_exit, which means that program wrote
8614 	 * something into it earlier
8615 	 */
8616 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8617 	if (err)
8618 		return err;
8619 
8620 	if (is_pointer_value(env, BPF_REG_0)) {
8621 		verbose(env, "R0 leaks addr as return value\n");
8622 		return -EACCES;
8623 	}
8624 
8625 	reg = cur_regs(env) + BPF_REG_0;
8626 	if (is_subprog) {
8627 		if (reg->type != SCALAR_VALUE) {
8628 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8629 				reg_type_str(env, reg->type));
8630 			return -EINVAL;
8631 		}
8632 		return 0;
8633 	}
8634 
8635 	switch (prog_type) {
8636 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8637 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8638 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8639 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8640 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8641 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8642 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8643 			range = tnum_range(1, 1);
8644 		break;
8645 	case BPF_PROG_TYPE_CGROUP_SKB:
8646 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8647 			range = tnum_range(0, 3);
8648 			enforce_attach_type_range = tnum_range(2, 3);
8649 		}
8650 		break;
8651 	case BPF_PROG_TYPE_CGROUP_SOCK:
8652 	case BPF_PROG_TYPE_SOCK_OPS:
8653 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8654 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8655 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8656 		break;
8657 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8658 		if (!env->prog->aux->attach_btf_id)
8659 			return 0;
8660 		range = tnum_const(0);
8661 		break;
8662 	case BPF_PROG_TYPE_TRACING:
8663 		switch (env->prog->expected_attach_type) {
8664 		case BPF_TRACE_FENTRY:
8665 		case BPF_TRACE_FEXIT:
8666 			range = tnum_const(0);
8667 			break;
8668 		case BPF_TRACE_RAW_TP:
8669 		case BPF_MODIFY_RETURN:
8670 			return 0;
8671 		case BPF_TRACE_ITER:
8672 			break;
8673 		default:
8674 			return -ENOTSUPP;
8675 		}
8676 		break;
8677 	case BPF_PROG_TYPE_SK_LOOKUP:
8678 		range = tnum_range(SK_DROP, SK_PASS);
8679 		break;
8680 	case BPF_PROG_TYPE_EXT:
8681 		/* freplace program can return anything as its return value
8682 		 * depends on the to-be-replaced kernel func or bpf program.
8683 		 */
8684 	default:
8685 		return 0;
8686 	}
8687 
8688 	if (reg->type != SCALAR_VALUE) {
8689 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8690 			reg_type_str(env, reg->type));
8691 		return -EINVAL;
8692 	}
8693 
8694 	if (!tnum_in(range, reg->var_off)) {
8695 		char tn_buf[48];
8696 
8697 		verbose(env, "At program exit the register R0 ");
8698 		if (!tnum_is_unknown(reg->var_off)) {
8699 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8700 			verbose(env, "has value %s", tn_buf);
8701 		} else {
8702 			verbose(env, "has unknown scalar value");
8703 		}
8704 		tnum_strn(tn_buf, sizeof(tn_buf), range);
8705 		verbose(env, " should have been in %s\n", tn_buf);
8706 		return -EINVAL;
8707 	}
8708 
8709 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8710 	    tnum_in(enforce_attach_type_range, reg->var_off))
8711 		env->prog->enforce_expected_attach_type = 1;
8712 	return 0;
8713 }
8714 
8715 /* non-recursive DFS pseudo code
8716  * 1  procedure DFS-iterative(G,v):
8717  * 2      label v as discovered
8718  * 3      let S be a stack
8719  * 4      S.push(v)
8720  * 5      while S is not empty
8721  * 6            t <- S.pop()
8722  * 7            if t is what we're looking for:
8723  * 8                return t
8724  * 9            for all edges e in G.adjacentEdges(t) do
8725  * 10               if edge e is already labelled
8726  * 11                   continue with the next edge
8727  * 12               w <- G.adjacentVertex(t,e)
8728  * 13               if vertex w is not discovered and not explored
8729  * 14                   label e as tree-edge
8730  * 15                   label w as discovered
8731  * 16                   S.push(w)
8732  * 17                   continue at 5
8733  * 18               else if vertex w is discovered
8734  * 19                   label e as back-edge
8735  * 20               else
8736  * 21                   // vertex w is explored
8737  * 22                   label e as forward- or cross-edge
8738  * 23           label t as explored
8739  * 24           S.pop()
8740  *
8741  * convention:
8742  * 0x10 - discovered
8743  * 0x11 - discovered and fall-through edge labelled
8744  * 0x12 - discovered and fall-through and branch edges labelled
8745  * 0x20 - explored
8746  */
8747 
8748 enum {
8749 	DISCOVERED = 0x10,
8750 	EXPLORED = 0x20,
8751 	FALLTHROUGH = 1,
8752 	BRANCH = 2,
8753 };
8754 
state_htab_size(struct bpf_verifier_env * env)8755 static u32 state_htab_size(struct bpf_verifier_env *env)
8756 {
8757 	return env->prog->len;
8758 }
8759 
explored_state(struct bpf_verifier_env * env,int idx)8760 static struct bpf_verifier_state_list **explored_state(
8761 					struct bpf_verifier_env *env,
8762 					int idx)
8763 {
8764 	struct bpf_verifier_state *cur = env->cur_state;
8765 	struct bpf_func_state *state = cur->frame[cur->curframe];
8766 
8767 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8768 }
8769 
init_explored_state(struct bpf_verifier_env * env,int idx)8770 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8771 {
8772 	env->insn_aux_data[idx].prune_point = true;
8773 }
8774 
8775 /* t, w, e - match pseudo-code above:
8776  * t - index of current instruction
8777  * w - next instruction
8778  * e - edge
8779  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)8780 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8781 		     bool loop_ok)
8782 {
8783 	int *insn_stack = env->cfg.insn_stack;
8784 	int *insn_state = env->cfg.insn_state;
8785 
8786 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8787 		return 0;
8788 
8789 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8790 		return 0;
8791 
8792 	if (w < 0 || w >= env->prog->len) {
8793 		verbose_linfo(env, t, "%d: ", t);
8794 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8795 		return -EINVAL;
8796 	}
8797 
8798 	if (e == BRANCH)
8799 		/* mark branch target for state pruning */
8800 		init_explored_state(env, w);
8801 
8802 	if (insn_state[w] == 0) {
8803 		/* tree-edge */
8804 		insn_state[t] = DISCOVERED | e;
8805 		insn_state[w] = DISCOVERED;
8806 		if (env->cfg.cur_stack >= env->prog->len)
8807 			return -E2BIG;
8808 		insn_stack[env->cfg.cur_stack++] = w;
8809 		return 1;
8810 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8811 		if (loop_ok && env->bpf_capable)
8812 			return 0;
8813 		verbose_linfo(env, t, "%d: ", t);
8814 		verbose_linfo(env, w, "%d: ", w);
8815 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8816 		return -EINVAL;
8817 	} else if (insn_state[w] == EXPLORED) {
8818 		/* forward- or cross-edge */
8819 		insn_state[t] = DISCOVERED | e;
8820 	} else {
8821 		verbose(env, "insn state internal bug\n");
8822 		return -EFAULT;
8823 	}
8824 	return 0;
8825 }
8826 
8827 /* non-recursive depth-first-search to detect loops in BPF program
8828  * loop == back-edge in directed graph
8829  */
check_cfg(struct bpf_verifier_env * env)8830 static int check_cfg(struct bpf_verifier_env *env)
8831 {
8832 	struct bpf_insn *insns = env->prog->insnsi;
8833 	int insn_cnt = env->prog->len;
8834 	int *insn_stack, *insn_state;
8835 	int ret = 0;
8836 	int i, t;
8837 
8838 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8839 	if (!insn_state)
8840 		return -ENOMEM;
8841 
8842 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8843 	if (!insn_stack) {
8844 		kvfree(insn_state);
8845 		return -ENOMEM;
8846 	}
8847 
8848 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8849 	insn_stack[0] = 0; /* 0 is the first instruction */
8850 	env->cfg.cur_stack = 1;
8851 
8852 peek_stack:
8853 	if (env->cfg.cur_stack == 0)
8854 		goto check_state;
8855 	t = insn_stack[env->cfg.cur_stack - 1];
8856 
8857 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8858 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
8859 		u8 opcode = BPF_OP(insns[t].code);
8860 
8861 		if (opcode == BPF_EXIT) {
8862 			goto mark_explored;
8863 		} else if (opcode == BPF_CALL) {
8864 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8865 			if (ret == 1)
8866 				goto peek_stack;
8867 			else if (ret < 0)
8868 				goto err_free;
8869 			if (t + 1 < insn_cnt)
8870 				init_explored_state(env, t + 1);
8871 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8872 				init_explored_state(env, t);
8873 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8874 						env, false);
8875 				if (ret == 1)
8876 					goto peek_stack;
8877 				else if (ret < 0)
8878 					goto err_free;
8879 			}
8880 		} else if (opcode == BPF_JA) {
8881 			if (BPF_SRC(insns[t].code) != BPF_K) {
8882 				ret = -EINVAL;
8883 				goto err_free;
8884 			}
8885 			/* unconditional jump with single edge */
8886 			ret = push_insn(t, t + insns[t].off + 1,
8887 					FALLTHROUGH, env, true);
8888 			if (ret == 1)
8889 				goto peek_stack;
8890 			else if (ret < 0)
8891 				goto err_free;
8892 			/* unconditional jmp is not a good pruning point,
8893 			 * but it's marked, since backtracking needs
8894 			 * to record jmp history in is_state_visited().
8895 			 */
8896 			init_explored_state(env, t + insns[t].off + 1);
8897 			/* tell verifier to check for equivalent states
8898 			 * after every call and jump
8899 			 */
8900 			if (t + 1 < insn_cnt)
8901 				init_explored_state(env, t + 1);
8902 		} else {
8903 			/* conditional jump with two edges */
8904 			init_explored_state(env, t);
8905 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8906 			if (ret == 1)
8907 				goto peek_stack;
8908 			else if (ret < 0)
8909 				goto err_free;
8910 
8911 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8912 			if (ret == 1)
8913 				goto peek_stack;
8914 			else if (ret < 0)
8915 				goto err_free;
8916 		}
8917 	} else {
8918 		/* all other non-branch instructions with single
8919 		 * fall-through edge
8920 		 */
8921 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8922 		if (ret == 1)
8923 			goto peek_stack;
8924 		else if (ret < 0)
8925 			goto err_free;
8926 	}
8927 
8928 mark_explored:
8929 	insn_state[t] = EXPLORED;
8930 	if (env->cfg.cur_stack-- <= 0) {
8931 		verbose(env, "pop stack internal bug\n");
8932 		ret = -EFAULT;
8933 		goto err_free;
8934 	}
8935 	goto peek_stack;
8936 
8937 check_state:
8938 	for (i = 0; i < insn_cnt; i++) {
8939 		if (insn_state[i] != EXPLORED) {
8940 			verbose(env, "unreachable insn %d\n", i);
8941 			ret = -EINVAL;
8942 			goto err_free;
8943 		}
8944 	}
8945 	ret = 0; /* cfg looks good */
8946 
8947 err_free:
8948 	kvfree(insn_state);
8949 	kvfree(insn_stack);
8950 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8951 	return ret;
8952 }
8953 
check_abnormal_return(struct bpf_verifier_env * env)8954 static int check_abnormal_return(struct bpf_verifier_env *env)
8955 {
8956 	int i;
8957 
8958 	for (i = 1; i < env->subprog_cnt; i++) {
8959 		if (env->subprog_info[i].has_ld_abs) {
8960 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8961 			return -EINVAL;
8962 		}
8963 		if (env->subprog_info[i].has_tail_call) {
8964 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8965 			return -EINVAL;
8966 		}
8967 	}
8968 	return 0;
8969 }
8970 
8971 /* The minimum supported BTF func info size */
8972 #define MIN_BPF_FUNCINFO_SIZE	8
8973 #define MAX_FUNCINFO_REC_SIZE	252
8974 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8975 static int check_btf_func(struct bpf_verifier_env *env,
8976 			  const union bpf_attr *attr,
8977 			  union bpf_attr __user *uattr)
8978 {
8979 	const struct btf_type *type, *func_proto, *ret_type;
8980 	u32 i, nfuncs, urec_size, min_size;
8981 	u32 krec_size = sizeof(struct bpf_func_info);
8982 	struct bpf_func_info *krecord;
8983 	struct bpf_func_info_aux *info_aux = NULL;
8984 	struct bpf_prog *prog;
8985 	const struct btf *btf;
8986 	void __user *urecord;
8987 	u32 prev_offset = 0;
8988 	bool scalar_return;
8989 	int ret = -ENOMEM;
8990 
8991 	nfuncs = attr->func_info_cnt;
8992 	if (!nfuncs) {
8993 		if (check_abnormal_return(env))
8994 			return -EINVAL;
8995 		return 0;
8996 	}
8997 
8998 	if (nfuncs != env->subprog_cnt) {
8999 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9000 		return -EINVAL;
9001 	}
9002 
9003 	urec_size = attr->func_info_rec_size;
9004 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9005 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
9006 	    urec_size % sizeof(u32)) {
9007 		verbose(env, "invalid func info rec size %u\n", urec_size);
9008 		return -EINVAL;
9009 	}
9010 
9011 	prog = env->prog;
9012 	btf = prog->aux->btf;
9013 
9014 	urecord = u64_to_user_ptr(attr->func_info);
9015 	min_size = min_t(u32, krec_size, urec_size);
9016 
9017 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9018 	if (!krecord)
9019 		return -ENOMEM;
9020 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9021 	if (!info_aux)
9022 		goto err_free;
9023 
9024 	for (i = 0; i < nfuncs; i++) {
9025 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9026 		if (ret) {
9027 			if (ret == -E2BIG) {
9028 				verbose(env, "nonzero tailing record in func info");
9029 				/* set the size kernel expects so loader can zero
9030 				 * out the rest of the record.
9031 				 */
9032 				if (put_user(min_size, &uattr->func_info_rec_size))
9033 					ret = -EFAULT;
9034 			}
9035 			goto err_free;
9036 		}
9037 
9038 		if (copy_from_user(&krecord[i], urecord, min_size)) {
9039 			ret = -EFAULT;
9040 			goto err_free;
9041 		}
9042 
9043 		/* check insn_off */
9044 		ret = -EINVAL;
9045 		if (i == 0) {
9046 			if (krecord[i].insn_off) {
9047 				verbose(env,
9048 					"nonzero insn_off %u for the first func info record",
9049 					krecord[i].insn_off);
9050 				goto err_free;
9051 			}
9052 		} else if (krecord[i].insn_off <= prev_offset) {
9053 			verbose(env,
9054 				"same or smaller insn offset (%u) than previous func info record (%u)",
9055 				krecord[i].insn_off, prev_offset);
9056 			goto err_free;
9057 		}
9058 
9059 		if (env->subprog_info[i].start != krecord[i].insn_off) {
9060 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9061 			goto err_free;
9062 		}
9063 
9064 		/* check type_id */
9065 		type = btf_type_by_id(btf, krecord[i].type_id);
9066 		if (!type || !btf_type_is_func(type)) {
9067 			verbose(env, "invalid type id %d in func info",
9068 				krecord[i].type_id);
9069 			goto err_free;
9070 		}
9071 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9072 
9073 		func_proto = btf_type_by_id(btf, type->type);
9074 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9075 			/* btf_func_check() already verified it during BTF load */
9076 			goto err_free;
9077 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9078 		scalar_return =
9079 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9080 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9081 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9082 			goto err_free;
9083 		}
9084 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9085 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9086 			goto err_free;
9087 		}
9088 
9089 		prev_offset = krecord[i].insn_off;
9090 		urecord += urec_size;
9091 	}
9092 
9093 	prog->aux->func_info = krecord;
9094 	prog->aux->func_info_cnt = nfuncs;
9095 	prog->aux->func_info_aux = info_aux;
9096 	return 0;
9097 
9098 err_free:
9099 	kvfree(krecord);
9100 	kfree(info_aux);
9101 	return ret;
9102 }
9103 
adjust_btf_func(struct bpf_verifier_env * env)9104 static void adjust_btf_func(struct bpf_verifier_env *env)
9105 {
9106 	struct bpf_prog_aux *aux = env->prog->aux;
9107 	int i;
9108 
9109 	if (!aux->func_info)
9110 		return;
9111 
9112 	for (i = 0; i < env->subprog_cnt; i++)
9113 		aux->func_info[i].insn_off = env->subprog_info[i].start;
9114 }
9115 
9116 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
9117 		sizeof(((struct bpf_line_info *)(0))->line_col))
9118 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
9119 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9120 static int check_btf_line(struct bpf_verifier_env *env,
9121 			  const union bpf_attr *attr,
9122 			  union bpf_attr __user *uattr)
9123 {
9124 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9125 	struct bpf_subprog_info *sub;
9126 	struct bpf_line_info *linfo;
9127 	struct bpf_prog *prog;
9128 	const struct btf *btf;
9129 	void __user *ulinfo;
9130 	int err;
9131 
9132 	nr_linfo = attr->line_info_cnt;
9133 	if (!nr_linfo)
9134 		return 0;
9135 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9136 		return -EINVAL;
9137 
9138 	rec_size = attr->line_info_rec_size;
9139 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9140 	    rec_size > MAX_LINEINFO_REC_SIZE ||
9141 	    rec_size & (sizeof(u32) - 1))
9142 		return -EINVAL;
9143 
9144 	/* Need to zero it in case the userspace may
9145 	 * pass in a smaller bpf_line_info object.
9146 	 */
9147 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9148 			 GFP_KERNEL | __GFP_NOWARN);
9149 	if (!linfo)
9150 		return -ENOMEM;
9151 
9152 	prog = env->prog;
9153 	btf = prog->aux->btf;
9154 
9155 	s = 0;
9156 	sub = env->subprog_info;
9157 	ulinfo = u64_to_user_ptr(attr->line_info);
9158 	expected_size = sizeof(struct bpf_line_info);
9159 	ncopy = min_t(u32, expected_size, rec_size);
9160 	for (i = 0; i < nr_linfo; i++) {
9161 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9162 		if (err) {
9163 			if (err == -E2BIG) {
9164 				verbose(env, "nonzero tailing record in line_info");
9165 				if (put_user(expected_size,
9166 					     &uattr->line_info_rec_size))
9167 					err = -EFAULT;
9168 			}
9169 			goto err_free;
9170 		}
9171 
9172 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9173 			err = -EFAULT;
9174 			goto err_free;
9175 		}
9176 
9177 		/*
9178 		 * Check insn_off to ensure
9179 		 * 1) strictly increasing AND
9180 		 * 2) bounded by prog->len
9181 		 *
9182 		 * The linfo[0].insn_off == 0 check logically falls into
9183 		 * the later "missing bpf_line_info for func..." case
9184 		 * because the first linfo[0].insn_off must be the
9185 		 * first sub also and the first sub must have
9186 		 * subprog_info[0].start == 0.
9187 		 */
9188 		if ((i && linfo[i].insn_off <= prev_offset) ||
9189 		    linfo[i].insn_off >= prog->len) {
9190 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9191 				i, linfo[i].insn_off, prev_offset,
9192 				prog->len);
9193 			err = -EINVAL;
9194 			goto err_free;
9195 		}
9196 
9197 		if (!prog->insnsi[linfo[i].insn_off].code) {
9198 			verbose(env,
9199 				"Invalid insn code at line_info[%u].insn_off\n",
9200 				i);
9201 			err = -EINVAL;
9202 			goto err_free;
9203 		}
9204 
9205 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9206 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9207 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9208 			err = -EINVAL;
9209 			goto err_free;
9210 		}
9211 
9212 		if (s != env->subprog_cnt) {
9213 			if (linfo[i].insn_off == sub[s].start) {
9214 				sub[s].linfo_idx = i;
9215 				s++;
9216 			} else if (sub[s].start < linfo[i].insn_off) {
9217 				verbose(env, "missing bpf_line_info for func#%u\n", s);
9218 				err = -EINVAL;
9219 				goto err_free;
9220 			}
9221 		}
9222 
9223 		prev_offset = linfo[i].insn_off;
9224 		ulinfo += rec_size;
9225 	}
9226 
9227 	if (s != env->subprog_cnt) {
9228 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9229 			env->subprog_cnt - s, s);
9230 		err = -EINVAL;
9231 		goto err_free;
9232 	}
9233 
9234 	prog->aux->linfo = linfo;
9235 	prog->aux->nr_linfo = nr_linfo;
9236 
9237 	return 0;
9238 
9239 err_free:
9240 	kvfree(linfo);
9241 	return err;
9242 }
9243 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9244 static int check_btf_info(struct bpf_verifier_env *env,
9245 			  const union bpf_attr *attr,
9246 			  union bpf_attr __user *uattr)
9247 {
9248 	struct btf *btf;
9249 	int err;
9250 
9251 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9252 		if (check_abnormal_return(env))
9253 			return -EINVAL;
9254 		return 0;
9255 	}
9256 
9257 	btf = btf_get_by_fd(attr->prog_btf_fd);
9258 	if (IS_ERR(btf))
9259 		return PTR_ERR(btf);
9260 	env->prog->aux->btf = btf;
9261 
9262 	err = check_btf_func(env, attr, uattr);
9263 	if (err)
9264 		return err;
9265 
9266 	err = check_btf_line(env, attr, uattr);
9267 	if (err)
9268 		return err;
9269 
9270 	return 0;
9271 }
9272 
9273 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)9274 static bool range_within(struct bpf_reg_state *old,
9275 			 struct bpf_reg_state *cur)
9276 {
9277 	return old->umin_value <= cur->umin_value &&
9278 	       old->umax_value >= cur->umax_value &&
9279 	       old->smin_value <= cur->smin_value &&
9280 	       old->smax_value >= cur->smax_value &&
9281 	       old->u32_min_value <= cur->u32_min_value &&
9282 	       old->u32_max_value >= cur->u32_max_value &&
9283 	       old->s32_min_value <= cur->s32_min_value &&
9284 	       old->s32_max_value >= cur->s32_max_value;
9285 }
9286 
9287 /* If in the old state two registers had the same id, then they need to have
9288  * the same id in the new state as well.  But that id could be different from
9289  * the old state, so we need to track the mapping from old to new ids.
9290  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9291  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9292  * regs with a different old id could still have new id 9, we don't care about
9293  * that.
9294  * So we look through our idmap to see if this old id has been seen before.  If
9295  * so, we require the new id to match; otherwise, we add the id pair to the map.
9296  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)9297 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9298 {
9299 	unsigned int i;
9300 
9301 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9302 		if (!idmap[i].old) {
9303 			/* Reached an empty slot; haven't seen this id before */
9304 			idmap[i].old = old_id;
9305 			idmap[i].cur = cur_id;
9306 			return true;
9307 		}
9308 		if (idmap[i].old == old_id)
9309 			return idmap[i].cur == cur_id;
9310 	}
9311 	/* We ran out of idmap slots, which should be impossible */
9312 	WARN_ON_ONCE(1);
9313 	return false;
9314 }
9315 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)9316 static void clean_func_state(struct bpf_verifier_env *env,
9317 			     struct bpf_func_state *st)
9318 {
9319 	enum bpf_reg_liveness live;
9320 	int i, j;
9321 
9322 	for (i = 0; i < BPF_REG_FP; i++) {
9323 		live = st->regs[i].live;
9324 		/* liveness must not touch this register anymore */
9325 		st->regs[i].live |= REG_LIVE_DONE;
9326 		if (!(live & REG_LIVE_READ))
9327 			/* since the register is unused, clear its state
9328 			 * to make further comparison simpler
9329 			 */
9330 			__mark_reg_not_init(env, &st->regs[i]);
9331 	}
9332 
9333 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9334 		live = st->stack[i].spilled_ptr.live;
9335 		/* liveness must not touch this stack slot anymore */
9336 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9337 		if (!(live & REG_LIVE_READ)) {
9338 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9339 			for (j = 0; j < BPF_REG_SIZE; j++)
9340 				st->stack[i].slot_type[j] = STACK_INVALID;
9341 		}
9342 	}
9343 }
9344 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)9345 static void clean_verifier_state(struct bpf_verifier_env *env,
9346 				 struct bpf_verifier_state *st)
9347 {
9348 	int i;
9349 
9350 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9351 		/* all regs in this state in all frames were already marked */
9352 		return;
9353 
9354 	for (i = 0; i <= st->curframe; i++)
9355 		clean_func_state(env, st->frame[i]);
9356 }
9357 
9358 /* the parentage chains form a tree.
9359  * the verifier states are added to state lists at given insn and
9360  * pushed into state stack for future exploration.
9361  * when the verifier reaches bpf_exit insn some of the verifer states
9362  * stored in the state lists have their final liveness state already,
9363  * but a lot of states will get revised from liveness point of view when
9364  * the verifier explores other branches.
9365  * Example:
9366  * 1: r0 = 1
9367  * 2: if r1 == 100 goto pc+1
9368  * 3: r0 = 2
9369  * 4: exit
9370  * when the verifier reaches exit insn the register r0 in the state list of
9371  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9372  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9373  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9374  *
9375  * Since the verifier pushes the branch states as it sees them while exploring
9376  * the program the condition of walking the branch instruction for the second
9377  * time means that all states below this branch were already explored and
9378  * their final liveness markes are already propagated.
9379  * Hence when the verifier completes the search of state list in is_state_visited()
9380  * we can call this clean_live_states() function to mark all liveness states
9381  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9382  * will not be used.
9383  * This function also clears the registers and stack for states that !READ
9384  * to simplify state merging.
9385  *
9386  * Important note here that walking the same branch instruction in the callee
9387  * doesn't meant that the states are DONE. The verifier has to compare
9388  * the callsites
9389  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)9390 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9391 			      struct bpf_verifier_state *cur)
9392 {
9393 	struct bpf_verifier_state_list *sl;
9394 	int i;
9395 
9396 	sl = *explored_state(env, insn);
9397 	while (sl) {
9398 		if (sl->state.branches)
9399 			goto next;
9400 		if (sl->state.insn_idx != insn ||
9401 		    sl->state.curframe != cur->curframe)
9402 			goto next;
9403 		for (i = 0; i <= cur->curframe; i++)
9404 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9405 				goto next;
9406 		clean_verifier_state(env, &sl->state);
9407 next:
9408 		sl = sl->next;
9409 	}
9410 }
9411 
9412 /* 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)9413 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9414 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9415 {
9416 	bool equal;
9417 
9418 	if (!(rold->live & REG_LIVE_READ))
9419 		/* explored state didn't use this */
9420 		return true;
9421 
9422 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9423 
9424 	if (rold->type == PTR_TO_STACK)
9425 		/* two stack pointers are equal only if they're pointing to
9426 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9427 		 */
9428 		return equal && rold->frameno == rcur->frameno;
9429 
9430 	if (equal)
9431 		return true;
9432 
9433 	if (rold->type == NOT_INIT)
9434 		/* explored state can't have used this */
9435 		return true;
9436 	if (rcur->type == NOT_INIT)
9437 		return false;
9438 	switch (base_type(rold->type)) {
9439 	case SCALAR_VALUE:
9440 		if (env->explore_alu_limits)
9441 			return false;
9442 		if (rcur->type == SCALAR_VALUE) {
9443 			if (!rold->precise)
9444 				return true;
9445 			/* new val must satisfy old val knowledge */
9446 			return range_within(rold, rcur) &&
9447 			       tnum_in(rold->var_off, rcur->var_off);
9448 		} else {
9449 			/* We're trying to use a pointer in place of a scalar.
9450 			 * Even if the scalar was unbounded, this could lead to
9451 			 * pointer leaks because scalars are allowed to leak
9452 			 * while pointers are not. We could make this safe in
9453 			 * special cases if root is calling us, but it's
9454 			 * probably not worth the hassle.
9455 			 */
9456 			return false;
9457 		}
9458 	case PTR_TO_MAP_VALUE:
9459 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9460 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9461 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9462 		 * checked, doing so could have affected others with the same
9463 		 * id, and we can't check for that because we lost the id when
9464 		 * we converted to a PTR_TO_MAP_VALUE.
9465 		 */
9466 		if (type_may_be_null(rold->type)) {
9467 			if (!type_may_be_null(rcur->type))
9468 				return false;
9469 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9470 				return false;
9471 			/* Check our ids match any regs they're supposed to */
9472 			return check_ids(rold->id, rcur->id, idmap);
9473 		}
9474 
9475 		/* If the new min/max/var_off satisfy the old ones and
9476 		 * everything else matches, we are OK.
9477 		 * 'id' is not compared, since it's only used for maps with
9478 		 * bpf_spin_lock inside map element and in such cases if
9479 		 * the rest of the prog is valid for one map element then
9480 		 * it's valid for all map elements regardless of the key
9481 		 * used in bpf_map_lookup()
9482 		 */
9483 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9484 		       range_within(rold, rcur) &&
9485 		       tnum_in(rold->var_off, rcur->var_off);
9486 	case PTR_TO_PACKET_META:
9487 	case PTR_TO_PACKET:
9488 		if (rcur->type != rold->type)
9489 			return false;
9490 		/* We must have at least as much range as the old ptr
9491 		 * did, so that any accesses which were safe before are
9492 		 * still safe.  This is true even if old range < old off,
9493 		 * since someone could have accessed through (ptr - k), or
9494 		 * even done ptr -= k in a register, to get a safe access.
9495 		 */
9496 		if (rold->range > rcur->range)
9497 			return false;
9498 		/* If the offsets don't match, we can't trust our alignment;
9499 		 * nor can we be sure that we won't fall out of range.
9500 		 */
9501 		if (rold->off != rcur->off)
9502 			return false;
9503 		/* id relations must be preserved */
9504 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9505 			return false;
9506 		/* new val must satisfy old val knowledge */
9507 		return range_within(rold, rcur) &&
9508 		       tnum_in(rold->var_off, rcur->var_off);
9509 	case PTR_TO_CTX:
9510 	case CONST_PTR_TO_MAP:
9511 	case PTR_TO_PACKET_END:
9512 	case PTR_TO_FLOW_KEYS:
9513 	case PTR_TO_SOCKET:
9514 	case PTR_TO_SOCK_COMMON:
9515 	case PTR_TO_TCP_SOCK:
9516 	case PTR_TO_XDP_SOCK:
9517 		/* Only valid matches are exact, which memcmp() above
9518 		 * would have accepted
9519 		 */
9520 	default:
9521 		/* Don't know what's going on, just say it's not safe */
9522 		return false;
9523 	}
9524 
9525 	/* Shouldn't get here; if we do, say it's not safe */
9526 	WARN_ON_ONCE(1);
9527 	return false;
9528 }
9529 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)9530 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9531 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9532 {
9533 	int i, spi;
9534 
9535 	/* walk slots of the explored stack and ignore any additional
9536 	 * slots in the current stack, since explored(safe) state
9537 	 * didn't use them
9538 	 */
9539 	for (i = 0; i < old->allocated_stack; i++) {
9540 		spi = i / BPF_REG_SIZE;
9541 
9542 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9543 			i += BPF_REG_SIZE - 1;
9544 			/* explored state didn't use this */
9545 			continue;
9546 		}
9547 
9548 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9549 			continue;
9550 
9551 		/* explored stack has more populated slots than current stack
9552 		 * and these slots were used
9553 		 */
9554 		if (i >= cur->allocated_stack)
9555 			return false;
9556 
9557 		/* if old state was safe with misc data in the stack
9558 		 * it will be safe with zero-initialized stack.
9559 		 * The opposite is not true
9560 		 */
9561 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9562 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9563 			continue;
9564 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9565 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9566 			/* Ex: old explored (safe) state has STACK_SPILL in
9567 			 * this stack slot, but current has STACK_MISC ->
9568 			 * this verifier states are not equivalent,
9569 			 * return false to continue verification of this path
9570 			 */
9571 			return false;
9572 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9573 			continue;
9574 		if (!is_spilled_reg(&old->stack[spi]))
9575 			continue;
9576 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
9577 			     &cur->stack[spi].spilled_ptr, idmap))
9578 			/* when explored and current stack slot are both storing
9579 			 * spilled registers, check that stored pointers types
9580 			 * are the same as well.
9581 			 * Ex: explored safe path could have stored
9582 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9583 			 * but current path has stored:
9584 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9585 			 * such verifier states are not equivalent.
9586 			 * return false to continue verification of this path
9587 			 */
9588 			return false;
9589 	}
9590 	return true;
9591 }
9592 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)9593 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9594 {
9595 	if (old->acquired_refs != cur->acquired_refs)
9596 		return false;
9597 	return !memcmp(old->refs, cur->refs,
9598 		       sizeof(*old->refs) * old->acquired_refs);
9599 }
9600 
9601 /* compare two verifier states
9602  *
9603  * all states stored in state_list are known to be valid, since
9604  * verifier reached 'bpf_exit' instruction through them
9605  *
9606  * this function is called when verifier exploring different branches of
9607  * execution popped from the state stack. If it sees an old state that has
9608  * more strict register state and more strict stack state then this execution
9609  * branch doesn't need to be explored further, since verifier already
9610  * concluded that more strict state leads to valid finish.
9611  *
9612  * Therefore two states are equivalent if register state is more conservative
9613  * and explored stack state is more conservative than the current one.
9614  * Example:
9615  *       explored                   current
9616  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9617  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9618  *
9619  * In other words if current stack state (one being explored) has more
9620  * valid slots than old one that already passed validation, it means
9621  * the verifier can stop exploring and conclude that current state is valid too
9622  *
9623  * Similarly with registers. If explored state has register type as invalid
9624  * whereas register type in current state is meaningful, it means that
9625  * the current state will reach 'bpf_exit' instruction safely
9626  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)9627 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9628 			      struct bpf_func_state *cur)
9629 {
9630 	int i;
9631 
9632 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9633 	for (i = 0; i < MAX_BPF_REG; i++)
9634 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
9635 			     env->idmap_scratch))
9636 			return false;
9637 
9638 	if (!stacksafe(env, old, cur, env->idmap_scratch))
9639 		return false;
9640 
9641 	if (!refsafe(old, cur))
9642 		return false;
9643 
9644 	return true;
9645 }
9646 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9647 static bool states_equal(struct bpf_verifier_env *env,
9648 			 struct bpf_verifier_state *old,
9649 			 struct bpf_verifier_state *cur)
9650 {
9651 	int i;
9652 
9653 	if (old->curframe != cur->curframe)
9654 		return false;
9655 
9656 	/* Verification state from speculative execution simulation
9657 	 * must never prune a non-speculative execution one.
9658 	 */
9659 	if (old->speculative && !cur->speculative)
9660 		return false;
9661 
9662 	if (old->active_spin_lock != cur->active_spin_lock)
9663 		return false;
9664 
9665 	/* for states to be equal callsites have to be the same
9666 	 * and all frame states need to be equivalent
9667 	 */
9668 	for (i = 0; i <= old->curframe; i++) {
9669 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9670 			return false;
9671 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9672 			return false;
9673 	}
9674 	return true;
9675 }
9676 
9677 /* Return 0 if no propagation happened. Return negative error code if error
9678  * happened. Otherwise, return the propagated bit.
9679  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)9680 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9681 				  struct bpf_reg_state *reg,
9682 				  struct bpf_reg_state *parent_reg)
9683 {
9684 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9685 	u8 flag = reg->live & REG_LIVE_READ;
9686 	int err;
9687 
9688 	/* When comes here, read flags of PARENT_REG or REG could be any of
9689 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9690 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9691 	 */
9692 	if (parent_flag == REG_LIVE_READ64 ||
9693 	    /* Or if there is no read flag from REG. */
9694 	    !flag ||
9695 	    /* Or if the read flag from REG is the same as PARENT_REG. */
9696 	    parent_flag == flag)
9697 		return 0;
9698 
9699 	err = mark_reg_read(env, reg, parent_reg, flag);
9700 	if (err)
9701 		return err;
9702 
9703 	return flag;
9704 }
9705 
9706 /* A write screens off any subsequent reads; but write marks come from the
9707  * straight-line code between a state and its parent.  When we arrive at an
9708  * equivalent state (jump target or such) we didn't arrive by the straight-line
9709  * code, so read marks in the state must propagate to the parent regardless
9710  * of the state's write marks. That's what 'parent == state->parent' comparison
9711  * in mark_reg_read() is for.
9712  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)9713 static int propagate_liveness(struct bpf_verifier_env *env,
9714 			      const struct bpf_verifier_state *vstate,
9715 			      struct bpf_verifier_state *vparent)
9716 {
9717 	struct bpf_reg_state *state_reg, *parent_reg;
9718 	struct bpf_func_state *state, *parent;
9719 	int i, frame, err = 0;
9720 
9721 	if (vparent->curframe != vstate->curframe) {
9722 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9723 		     vparent->curframe, vstate->curframe);
9724 		return -EFAULT;
9725 	}
9726 	/* Propagate read liveness of registers... */
9727 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9728 	for (frame = 0; frame <= vstate->curframe; frame++) {
9729 		parent = vparent->frame[frame];
9730 		state = vstate->frame[frame];
9731 		parent_reg = parent->regs;
9732 		state_reg = state->regs;
9733 		/* We don't need to worry about FP liveness, it's read-only */
9734 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9735 			err = propagate_liveness_reg(env, &state_reg[i],
9736 						     &parent_reg[i]);
9737 			if (err < 0)
9738 				return err;
9739 			if (err == REG_LIVE_READ64)
9740 				mark_insn_zext(env, &parent_reg[i]);
9741 		}
9742 
9743 		/* Propagate stack slots. */
9744 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9745 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9746 			parent_reg = &parent->stack[i].spilled_ptr;
9747 			state_reg = &state->stack[i].spilled_ptr;
9748 			err = propagate_liveness_reg(env, state_reg,
9749 						     parent_reg);
9750 			if (err < 0)
9751 				return err;
9752 		}
9753 	}
9754 	return 0;
9755 }
9756 
9757 /* find precise scalars in the previous equivalent state and
9758  * propagate them into the current state
9759  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)9760 static int propagate_precision(struct bpf_verifier_env *env,
9761 			       const struct bpf_verifier_state *old)
9762 {
9763 	struct bpf_reg_state *state_reg;
9764 	struct bpf_func_state *state;
9765 	int i, err = 0, fr;
9766 
9767 	for (fr = old->curframe; fr >= 0; fr--) {
9768 		state = old->frame[fr];
9769 		state_reg = state->regs;
9770 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9771 			if (state_reg->type != SCALAR_VALUE ||
9772 			    !state_reg->precise ||
9773 			    !(state_reg->live & REG_LIVE_READ))
9774 				continue;
9775 			if (env->log.level & BPF_LOG_LEVEL2)
9776 				verbose(env, "frame %d: propagating r%d\n", fr, i);
9777 			err = mark_chain_precision_frame(env, fr, i);
9778 			if (err < 0)
9779 				return err;
9780 		}
9781 
9782 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9783 			if (!is_spilled_reg(&state->stack[i]))
9784 				continue;
9785 			state_reg = &state->stack[i].spilled_ptr;
9786 			if (state_reg->type != SCALAR_VALUE ||
9787 			    !state_reg->precise ||
9788 			    !(state_reg->live & REG_LIVE_READ))
9789 				continue;
9790 			if (env->log.level & BPF_LOG_LEVEL2)
9791 				verbose(env, "frame %d: propagating fp%d\n",
9792 					fr, (-i - 1) * BPF_REG_SIZE);
9793 			err = mark_chain_precision_stack_frame(env, fr, i);
9794 			if (err < 0)
9795 				return err;
9796 		}
9797 	}
9798 	return 0;
9799 }
9800 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9801 static bool states_maybe_looping(struct bpf_verifier_state *old,
9802 				 struct bpf_verifier_state *cur)
9803 {
9804 	struct bpf_func_state *fold, *fcur;
9805 	int i, fr = cur->curframe;
9806 
9807 	if (old->curframe != fr)
9808 		return false;
9809 
9810 	fold = old->frame[fr];
9811 	fcur = cur->frame[fr];
9812 	for (i = 0; i < MAX_BPF_REG; i++)
9813 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9814 			   offsetof(struct bpf_reg_state, parent)))
9815 			return false;
9816 	return true;
9817 }
9818 
9819 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)9820 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9821 {
9822 	struct bpf_verifier_state_list *new_sl;
9823 	struct bpf_verifier_state_list *sl, **pprev;
9824 	struct bpf_verifier_state *cur = env->cur_state, *new;
9825 	int i, j, err, states_cnt = 0;
9826 	bool add_new_state = env->test_state_freq ? true : false;
9827 
9828 	cur->last_insn_idx = env->prev_insn_idx;
9829 	if (!env->insn_aux_data[insn_idx].prune_point)
9830 		/* this 'insn_idx' instruction wasn't marked, so we will not
9831 		 * be doing state search here
9832 		 */
9833 		return 0;
9834 
9835 	/* bpf progs typically have pruning point every 4 instructions
9836 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9837 	 * Do not add new state for future pruning if the verifier hasn't seen
9838 	 * at least 2 jumps and at least 8 instructions.
9839 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9840 	 * In tests that amounts to up to 50% reduction into total verifier
9841 	 * memory consumption and 20% verifier time speedup.
9842 	 */
9843 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9844 	    env->insn_processed - env->prev_insn_processed >= 8)
9845 		add_new_state = true;
9846 
9847 	pprev = explored_state(env, insn_idx);
9848 	sl = *pprev;
9849 
9850 	clean_live_states(env, insn_idx, cur);
9851 
9852 	while (sl) {
9853 		states_cnt++;
9854 		if (sl->state.insn_idx != insn_idx)
9855 			goto next;
9856 		if (sl->state.branches) {
9857 			if (states_maybe_looping(&sl->state, cur) &&
9858 			    states_equal(env, &sl->state, cur)) {
9859 				verbose_linfo(env, insn_idx, "; ");
9860 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9861 				return -EINVAL;
9862 			}
9863 			/* if the verifier is processing a loop, avoid adding new state
9864 			 * too often, since different loop iterations have distinct
9865 			 * states and may not help future pruning.
9866 			 * This threshold shouldn't be too low to make sure that
9867 			 * a loop with large bound will be rejected quickly.
9868 			 * The most abusive loop will be:
9869 			 * r1 += 1
9870 			 * if r1 < 1000000 goto pc-2
9871 			 * 1M insn_procssed limit / 100 == 10k peak states.
9872 			 * This threshold shouldn't be too high either, since states
9873 			 * at the end of the loop are likely to be useful in pruning.
9874 			 */
9875 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9876 			    env->insn_processed - env->prev_insn_processed < 100)
9877 				add_new_state = false;
9878 			goto miss;
9879 		}
9880 		if (states_equal(env, &sl->state, cur)) {
9881 			sl->hit_cnt++;
9882 			/* reached equivalent register/stack state,
9883 			 * prune the search.
9884 			 * Registers read by the continuation are read by us.
9885 			 * If we have any write marks in env->cur_state, they
9886 			 * will prevent corresponding reads in the continuation
9887 			 * from reaching our parent (an explored_state).  Our
9888 			 * own state will get the read marks recorded, but
9889 			 * they'll be immediately forgotten as we're pruning
9890 			 * this state and will pop a new one.
9891 			 */
9892 			err = propagate_liveness(env, &sl->state, cur);
9893 
9894 			/* if previous state reached the exit with precision and
9895 			 * current state is equivalent to it (except precsion marks)
9896 			 * the precision needs to be propagated back in
9897 			 * the current state.
9898 			 */
9899 			err = err ? : push_jmp_history(env, cur);
9900 			err = err ? : propagate_precision(env, &sl->state);
9901 			if (err)
9902 				return err;
9903 			return 1;
9904 		}
9905 miss:
9906 		/* when new state is not going to be added do not increase miss count.
9907 		 * Otherwise several loop iterations will remove the state
9908 		 * recorded earlier. The goal of these heuristics is to have
9909 		 * states from some iterations of the loop (some in the beginning
9910 		 * and some at the end) to help pruning.
9911 		 */
9912 		if (add_new_state)
9913 			sl->miss_cnt++;
9914 		/* heuristic to determine whether this state is beneficial
9915 		 * to keep checking from state equivalence point of view.
9916 		 * Higher numbers increase max_states_per_insn and verification time,
9917 		 * but do not meaningfully decrease insn_processed.
9918 		 */
9919 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9920 			/* the state is unlikely to be useful. Remove it to
9921 			 * speed up verification
9922 			 */
9923 			*pprev = sl->next;
9924 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9925 				u32 br = sl->state.branches;
9926 
9927 				WARN_ONCE(br,
9928 					  "BUG live_done but branches_to_explore %d\n",
9929 					  br);
9930 				free_verifier_state(&sl->state, false);
9931 				kfree(sl);
9932 				env->peak_states--;
9933 			} else {
9934 				/* cannot free this state, since parentage chain may
9935 				 * walk it later. Add it for free_list instead to
9936 				 * be freed at the end of verification
9937 				 */
9938 				sl->next = env->free_list;
9939 				env->free_list = sl;
9940 			}
9941 			sl = *pprev;
9942 			continue;
9943 		}
9944 next:
9945 		pprev = &sl->next;
9946 		sl = *pprev;
9947 	}
9948 
9949 	if (env->max_states_per_insn < states_cnt)
9950 		env->max_states_per_insn = states_cnt;
9951 
9952 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9953 		return push_jmp_history(env, cur);
9954 
9955 	if (!add_new_state)
9956 		return push_jmp_history(env, cur);
9957 
9958 	/* There were no equivalent states, remember the current one.
9959 	 * Technically the current state is not proven to be safe yet,
9960 	 * but it will either reach outer most bpf_exit (which means it's safe)
9961 	 * or it will be rejected. When there are no loops the verifier won't be
9962 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9963 	 * again on the way to bpf_exit.
9964 	 * When looping the sl->state.branches will be > 0 and this state
9965 	 * will not be considered for equivalence until branches == 0.
9966 	 */
9967 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9968 	if (!new_sl)
9969 		return -ENOMEM;
9970 	env->total_states++;
9971 	env->peak_states++;
9972 	env->prev_jmps_processed = env->jmps_processed;
9973 	env->prev_insn_processed = env->insn_processed;
9974 
9975 	/* forget precise markings we inherited, see __mark_chain_precision */
9976 	if (env->bpf_capable)
9977 		mark_all_scalars_imprecise(env, cur);
9978 
9979 	/* add new state to the head of linked list */
9980 	new = &new_sl->state;
9981 	err = copy_verifier_state(new, cur);
9982 	if (err) {
9983 		free_verifier_state(new, false);
9984 		kfree(new_sl);
9985 		return err;
9986 	}
9987 	new->insn_idx = insn_idx;
9988 	WARN_ONCE(new->branches != 1,
9989 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9990 
9991 	cur->parent = new;
9992 	cur->first_insn_idx = insn_idx;
9993 	clear_jmp_history(cur);
9994 	new_sl->next = *explored_state(env, insn_idx);
9995 	*explored_state(env, insn_idx) = new_sl;
9996 	/* connect new state to parentage chain. Current frame needs all
9997 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9998 	 * to the stack implicitly by JITs) so in callers' frames connect just
9999 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10000 	 * the state of the call instruction (with WRITTEN set), and r0 comes
10001 	 * from callee with its full parentage chain, anyway.
10002 	 */
10003 	/* clear write marks in current state: the writes we did are not writes
10004 	 * our child did, so they don't screen off its reads from us.
10005 	 * (There are no read marks in current state, because reads always mark
10006 	 * their parent and current state never has children yet.  Only
10007 	 * explored_states can get read marks.)
10008 	 */
10009 	for (j = 0; j <= cur->curframe; j++) {
10010 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10011 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10012 		for (i = 0; i < BPF_REG_FP; i++)
10013 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10014 	}
10015 
10016 	/* all stack frames are accessible from callee, clear them all */
10017 	for (j = 0; j <= cur->curframe; j++) {
10018 		struct bpf_func_state *frame = cur->frame[j];
10019 		struct bpf_func_state *newframe = new->frame[j];
10020 
10021 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10022 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10023 			frame->stack[i].spilled_ptr.parent =
10024 						&newframe->stack[i].spilled_ptr;
10025 		}
10026 	}
10027 	return 0;
10028 }
10029 
10030 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)10031 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10032 {
10033 	switch (base_type(type)) {
10034 	case PTR_TO_CTX:
10035 	case PTR_TO_SOCKET:
10036 	case PTR_TO_SOCK_COMMON:
10037 	case PTR_TO_TCP_SOCK:
10038 	case PTR_TO_XDP_SOCK:
10039 	case PTR_TO_BTF_ID:
10040 		return false;
10041 	default:
10042 		return true;
10043 	}
10044 }
10045 
10046 /* If an instruction was previously used with particular pointer types, then we
10047  * need to be careful to avoid cases such as the below, where it may be ok
10048  * for one branch accessing the pointer, but not ok for the other branch:
10049  *
10050  * R1 = sock_ptr
10051  * goto X;
10052  * ...
10053  * R1 = some_other_valid_ptr;
10054  * goto X;
10055  * ...
10056  * R2 = *(u32 *)(R1 + 0);
10057  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)10058 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10059 {
10060 	return src != prev && (!reg_type_mismatch_ok(src) ||
10061 			       !reg_type_mismatch_ok(prev));
10062 }
10063 
do_check(struct bpf_verifier_env * env)10064 static int do_check(struct bpf_verifier_env *env)
10065 {
10066 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10067 	struct bpf_verifier_state *state = env->cur_state;
10068 	struct bpf_insn *insns = env->prog->insnsi;
10069 	struct bpf_reg_state *regs;
10070 	int insn_cnt = env->prog->len;
10071 	bool do_print_state = false;
10072 	int prev_insn_idx = -1;
10073 
10074 	for (;;) {
10075 		struct bpf_insn *insn;
10076 		u8 class;
10077 		int err;
10078 
10079 		env->prev_insn_idx = prev_insn_idx;
10080 		if (env->insn_idx >= insn_cnt) {
10081 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
10082 				env->insn_idx, insn_cnt);
10083 			return -EFAULT;
10084 		}
10085 
10086 		insn = &insns[env->insn_idx];
10087 		class = BPF_CLASS(insn->code);
10088 
10089 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10090 			verbose(env,
10091 				"BPF program is too large. Processed %d insn\n",
10092 				env->insn_processed);
10093 			return -E2BIG;
10094 		}
10095 
10096 		err = is_state_visited(env, env->insn_idx);
10097 		if (err < 0)
10098 			return err;
10099 		if (err == 1) {
10100 			/* found equivalent state, can prune the search */
10101 			if (env->log.level & BPF_LOG_LEVEL) {
10102 				if (do_print_state)
10103 					verbose(env, "\nfrom %d to %d%s: safe\n",
10104 						env->prev_insn_idx, env->insn_idx,
10105 						env->cur_state->speculative ?
10106 						" (speculative execution)" : "");
10107 				else
10108 					verbose(env, "%d: safe\n", env->insn_idx);
10109 			}
10110 			goto process_bpf_exit;
10111 		}
10112 
10113 		if (signal_pending(current))
10114 			return -EAGAIN;
10115 
10116 		if (need_resched())
10117 			cond_resched();
10118 
10119 		if (env->log.level & BPF_LOG_LEVEL2 ||
10120 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10121 			if (env->log.level & BPF_LOG_LEVEL2)
10122 				verbose(env, "%d:", env->insn_idx);
10123 			else
10124 				verbose(env, "\nfrom %d to %d%s:",
10125 					env->prev_insn_idx, env->insn_idx,
10126 					env->cur_state->speculative ?
10127 					" (speculative execution)" : "");
10128 			print_verifier_state(env, state->frame[state->curframe]);
10129 			do_print_state = false;
10130 		}
10131 
10132 		if (env->log.level & BPF_LOG_LEVEL) {
10133 			const struct bpf_insn_cbs cbs = {
10134 				.cb_print	= verbose,
10135 				.private_data	= env,
10136 			};
10137 
10138 			verbose_linfo(env, env->insn_idx, "; ");
10139 			verbose(env, "%d: ", env->insn_idx);
10140 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10141 		}
10142 
10143 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
10144 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10145 							   env->prev_insn_idx);
10146 			if (err)
10147 				return err;
10148 		}
10149 
10150 		regs = cur_regs(env);
10151 		sanitize_mark_insn_seen(env);
10152 		prev_insn_idx = env->insn_idx;
10153 
10154 		if (class == BPF_ALU || class == BPF_ALU64) {
10155 			err = check_alu_op(env, insn);
10156 			if (err)
10157 				return err;
10158 
10159 		} else if (class == BPF_LDX) {
10160 			enum bpf_reg_type *prev_src_type, src_reg_type;
10161 
10162 			/* check for reserved fields is already done */
10163 
10164 			/* check src operand */
10165 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10166 			if (err)
10167 				return err;
10168 
10169 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10170 			if (err)
10171 				return err;
10172 
10173 			src_reg_type = regs[insn->src_reg].type;
10174 
10175 			/* check that memory (src_reg + off) is readable,
10176 			 * the state of dst_reg will be updated by this func
10177 			 */
10178 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
10179 					       insn->off, BPF_SIZE(insn->code),
10180 					       BPF_READ, insn->dst_reg, false);
10181 			if (err)
10182 				return err;
10183 
10184 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10185 
10186 			if (*prev_src_type == NOT_INIT) {
10187 				/* saw a valid insn
10188 				 * dst_reg = *(u32 *)(src_reg + off)
10189 				 * save type to validate intersecting paths
10190 				 */
10191 				*prev_src_type = src_reg_type;
10192 
10193 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10194 				/* ABuser program is trying to use the same insn
10195 				 * dst_reg = *(u32*) (src_reg + off)
10196 				 * with different pointer types:
10197 				 * src_reg == ctx in one branch and
10198 				 * src_reg == stack|map in some other branch.
10199 				 * Reject it.
10200 				 */
10201 				verbose(env, "same insn cannot be used with different pointers\n");
10202 				return -EINVAL;
10203 			}
10204 
10205 		} else if (class == BPF_STX) {
10206 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
10207 
10208 			if (BPF_MODE(insn->code) == BPF_XADD) {
10209 				err = check_xadd(env, env->insn_idx, insn);
10210 				if (err)
10211 					return err;
10212 				env->insn_idx++;
10213 				continue;
10214 			}
10215 
10216 			/* check src1 operand */
10217 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10218 			if (err)
10219 				return err;
10220 			/* check src2 operand */
10221 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10222 			if (err)
10223 				return err;
10224 
10225 			dst_reg_type = regs[insn->dst_reg].type;
10226 
10227 			/* check that memory (dst_reg + off) is writeable */
10228 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10229 					       insn->off, BPF_SIZE(insn->code),
10230 					       BPF_WRITE, insn->src_reg, false);
10231 			if (err)
10232 				return err;
10233 
10234 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10235 
10236 			if (*prev_dst_type == NOT_INIT) {
10237 				*prev_dst_type = dst_reg_type;
10238 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10239 				verbose(env, "same insn cannot be used with different pointers\n");
10240 				return -EINVAL;
10241 			}
10242 
10243 		} else if (class == BPF_ST) {
10244 			if (BPF_MODE(insn->code) != BPF_MEM ||
10245 			    insn->src_reg != BPF_REG_0) {
10246 				verbose(env, "BPF_ST uses reserved fields\n");
10247 				return -EINVAL;
10248 			}
10249 			/* check src operand */
10250 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10251 			if (err)
10252 				return err;
10253 
10254 			if (is_ctx_reg(env, insn->dst_reg)) {
10255 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10256 					insn->dst_reg,
10257 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
10258 				return -EACCES;
10259 			}
10260 
10261 			/* check that memory (dst_reg + off) is writeable */
10262 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10263 					       insn->off, BPF_SIZE(insn->code),
10264 					       BPF_WRITE, -1, false);
10265 			if (err)
10266 				return err;
10267 
10268 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10269 			u8 opcode = BPF_OP(insn->code);
10270 
10271 			env->jmps_processed++;
10272 			if (opcode == BPF_CALL) {
10273 				if (BPF_SRC(insn->code) != BPF_K ||
10274 				    insn->off != 0 ||
10275 				    (insn->src_reg != BPF_REG_0 &&
10276 				     insn->src_reg != BPF_PSEUDO_CALL) ||
10277 				    insn->dst_reg != BPF_REG_0 ||
10278 				    class == BPF_JMP32) {
10279 					verbose(env, "BPF_CALL uses reserved fields\n");
10280 					return -EINVAL;
10281 				}
10282 
10283 				if (env->cur_state->active_spin_lock &&
10284 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10285 				     insn->imm != BPF_FUNC_spin_unlock)) {
10286 					verbose(env, "function calls are not allowed while holding a lock\n");
10287 					return -EINVAL;
10288 				}
10289 				if (insn->src_reg == BPF_PSEUDO_CALL)
10290 					err = check_func_call(env, insn, &env->insn_idx);
10291 				else
10292 					err = check_helper_call(env, insn->imm, env->insn_idx);
10293 				if (err)
10294 					return err;
10295 
10296 			} else if (opcode == BPF_JA) {
10297 				if (BPF_SRC(insn->code) != BPF_K ||
10298 				    insn->imm != 0 ||
10299 				    insn->src_reg != BPF_REG_0 ||
10300 				    insn->dst_reg != BPF_REG_0 ||
10301 				    class == BPF_JMP32) {
10302 					verbose(env, "BPF_JA uses reserved fields\n");
10303 					return -EINVAL;
10304 				}
10305 
10306 				env->insn_idx += insn->off + 1;
10307 				continue;
10308 
10309 			} else if (opcode == BPF_EXIT) {
10310 				if (BPF_SRC(insn->code) != BPF_K ||
10311 				    insn->imm != 0 ||
10312 				    insn->src_reg != BPF_REG_0 ||
10313 				    insn->dst_reg != BPF_REG_0 ||
10314 				    class == BPF_JMP32) {
10315 					verbose(env, "BPF_EXIT uses reserved fields\n");
10316 					return -EINVAL;
10317 				}
10318 
10319 				if (env->cur_state->active_spin_lock) {
10320 					verbose(env, "bpf_spin_unlock is missing\n");
10321 					return -EINVAL;
10322 				}
10323 
10324 				if (state->curframe) {
10325 					/* exit from nested function */
10326 					err = prepare_func_exit(env, &env->insn_idx);
10327 					if (err)
10328 						return err;
10329 					do_print_state = true;
10330 					continue;
10331 				}
10332 
10333 				err = check_reference_leak(env);
10334 				if (err)
10335 					return err;
10336 
10337 				err = check_return_code(env);
10338 				if (err)
10339 					return err;
10340 process_bpf_exit:
10341 				update_branch_counts(env, env->cur_state);
10342 				err = pop_stack(env, &prev_insn_idx,
10343 						&env->insn_idx, pop_log);
10344 				if (err < 0) {
10345 					if (err != -ENOENT)
10346 						return err;
10347 					break;
10348 				} else {
10349 					do_print_state = true;
10350 					continue;
10351 				}
10352 			} else {
10353 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10354 				if (err)
10355 					return err;
10356 			}
10357 		} else if (class == BPF_LD) {
10358 			u8 mode = BPF_MODE(insn->code);
10359 
10360 			if (mode == BPF_ABS || mode == BPF_IND) {
10361 				err = check_ld_abs(env, insn);
10362 				if (err)
10363 					return err;
10364 
10365 			} else if (mode == BPF_IMM) {
10366 				err = check_ld_imm(env, insn);
10367 				if (err)
10368 					return err;
10369 
10370 				env->insn_idx++;
10371 				sanitize_mark_insn_seen(env);
10372 			} else {
10373 				verbose(env, "invalid BPF_LD mode\n");
10374 				return -EINVAL;
10375 			}
10376 		} else {
10377 			verbose(env, "unknown insn class %d\n", class);
10378 			return -EINVAL;
10379 		}
10380 
10381 		env->insn_idx++;
10382 	}
10383 
10384 	return 0;
10385 }
10386 
10387 /* 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)10388 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10389 			       struct bpf_insn *insn,
10390 			       struct bpf_insn_aux_data *aux)
10391 {
10392 	const struct btf_var_secinfo *vsi;
10393 	const struct btf_type *datasec;
10394 	const struct btf_type *t;
10395 	const char *sym_name;
10396 	bool percpu = false;
10397 	u32 type, id = insn->imm;
10398 	s32 datasec_id;
10399 	u64 addr;
10400 	int i;
10401 
10402 	if (!btf_vmlinux) {
10403 		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10404 		return -EINVAL;
10405 	}
10406 
10407 	if (insn[1].imm != 0) {
10408 		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10409 		return -EINVAL;
10410 	}
10411 
10412 	t = btf_type_by_id(btf_vmlinux, id);
10413 	if (!t) {
10414 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10415 		return -ENOENT;
10416 	}
10417 
10418 	if (!btf_type_is_var(t)) {
10419 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10420 			id);
10421 		return -EINVAL;
10422 	}
10423 
10424 	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10425 	addr = kallsyms_lookup_name(sym_name);
10426 	if (!addr) {
10427 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10428 			sym_name);
10429 		return -ENOENT;
10430 	}
10431 
10432 	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10433 					   BTF_KIND_DATASEC);
10434 	if (datasec_id > 0) {
10435 		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10436 		for_each_vsi(i, datasec, vsi) {
10437 			if (vsi->type == id) {
10438 				percpu = true;
10439 				break;
10440 			}
10441 		}
10442 	}
10443 
10444 	insn[0].imm = (u32)addr;
10445 	insn[1].imm = addr >> 32;
10446 
10447 	type = t->type;
10448 	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10449 	if (percpu) {
10450 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10451 		aux->btf_var.btf_id = type;
10452 	} else if (!btf_type_is_struct(t)) {
10453 		const struct btf_type *ret;
10454 		const char *tname;
10455 		u32 tsize;
10456 
10457 		/* resolve the type size of ksym. */
10458 		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10459 		if (IS_ERR(ret)) {
10460 			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10461 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10462 				tname, PTR_ERR(ret));
10463 			return -EINVAL;
10464 		}
10465 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
10466 		aux->btf_var.mem_size = tsize;
10467 	} else {
10468 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10469 		aux->btf_var.btf_id = type;
10470 	}
10471 	return 0;
10472 }
10473 
check_map_prealloc(struct bpf_map * map)10474 static int check_map_prealloc(struct bpf_map *map)
10475 {
10476 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10477 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10478 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10479 		!(map->map_flags & BPF_F_NO_PREALLOC);
10480 }
10481 
is_tracing_prog_type(enum bpf_prog_type type)10482 static bool is_tracing_prog_type(enum bpf_prog_type type)
10483 {
10484 	switch (type) {
10485 	case BPF_PROG_TYPE_KPROBE:
10486 	case BPF_PROG_TYPE_TRACEPOINT:
10487 	case BPF_PROG_TYPE_PERF_EVENT:
10488 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10489 		return true;
10490 	default:
10491 		return false;
10492 	}
10493 }
10494 
is_preallocated_map(struct bpf_map * map)10495 static bool is_preallocated_map(struct bpf_map *map)
10496 {
10497 	if (!check_map_prealloc(map))
10498 		return false;
10499 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10500 		return false;
10501 	return true;
10502 }
10503 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)10504 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10505 					struct bpf_map *map,
10506 					struct bpf_prog *prog)
10507 
10508 {
10509 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10510 	/*
10511 	 * Validate that trace type programs use preallocated hash maps.
10512 	 *
10513 	 * For programs attached to PERF events this is mandatory as the
10514 	 * perf NMI can hit any arbitrary code sequence.
10515 	 *
10516 	 * All other trace types using preallocated hash maps are unsafe as
10517 	 * well because tracepoint or kprobes can be inside locked regions
10518 	 * of the memory allocator or at a place where a recursion into the
10519 	 * memory allocator would see inconsistent state.
10520 	 *
10521 	 * On RT enabled kernels run-time allocation of all trace type
10522 	 * programs is strictly prohibited due to lock type constraints. On
10523 	 * !RT kernels it is allowed for backwards compatibility reasons for
10524 	 * now, but warnings are emitted so developers are made aware of
10525 	 * the unsafety and can fix their programs before this is enforced.
10526 	 */
10527 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10528 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10529 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10530 			return -EINVAL;
10531 		}
10532 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10533 			verbose(env, "trace type programs can only use preallocated hash map\n");
10534 			return -EINVAL;
10535 		}
10536 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10537 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10538 	}
10539 
10540 	if ((is_tracing_prog_type(prog_type) ||
10541 	     prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10542 	    map_value_has_spin_lock(map)) {
10543 		verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10544 		return -EINVAL;
10545 	}
10546 
10547 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10548 	    !bpf_offload_prog_map_match(prog, map)) {
10549 		verbose(env, "offload device mismatch between prog and map\n");
10550 		return -EINVAL;
10551 	}
10552 
10553 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10554 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10555 		return -EINVAL;
10556 	}
10557 
10558 	if (prog->aux->sleepable)
10559 		switch (map->map_type) {
10560 		case BPF_MAP_TYPE_HASH:
10561 		case BPF_MAP_TYPE_LRU_HASH:
10562 		case BPF_MAP_TYPE_ARRAY:
10563 			if (!is_preallocated_map(map)) {
10564 				verbose(env,
10565 					"Sleepable programs can only use preallocated hash maps\n");
10566 				return -EINVAL;
10567 			}
10568 			break;
10569 		default:
10570 			verbose(env,
10571 				"Sleepable programs can only use array and hash maps\n");
10572 			return -EINVAL;
10573 		}
10574 
10575 	return 0;
10576 }
10577 
bpf_map_is_cgroup_storage(struct bpf_map * map)10578 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10579 {
10580 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10581 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10582 }
10583 
10584 /* find and rewrite pseudo imm in ld_imm64 instructions:
10585  *
10586  * 1. if it accesses map FD, replace it with actual map pointer.
10587  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10588  *
10589  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10590  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)10591 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10592 {
10593 	struct bpf_insn *insn = env->prog->insnsi;
10594 	int insn_cnt = env->prog->len;
10595 	int i, j, err;
10596 
10597 	err = bpf_prog_calc_tag(env->prog);
10598 	if (err)
10599 		return err;
10600 
10601 	for (i = 0; i < insn_cnt; i++, insn++) {
10602 		if (BPF_CLASS(insn->code) == BPF_LDX &&
10603 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10604 			verbose(env, "BPF_LDX uses reserved fields\n");
10605 			return -EINVAL;
10606 		}
10607 
10608 		if (BPF_CLASS(insn->code) == BPF_STX &&
10609 		    ((BPF_MODE(insn->code) != BPF_MEM &&
10610 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10611 			verbose(env, "BPF_STX uses reserved fields\n");
10612 			return -EINVAL;
10613 		}
10614 
10615 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10616 			struct bpf_insn_aux_data *aux;
10617 			struct bpf_map *map;
10618 			struct fd f;
10619 			u64 addr;
10620 
10621 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
10622 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10623 			    insn[1].off != 0) {
10624 				verbose(env, "invalid bpf_ld_imm64 insn\n");
10625 				return -EINVAL;
10626 			}
10627 
10628 			if (insn[0].src_reg == 0)
10629 				/* valid generic load 64-bit imm */
10630 				goto next_insn;
10631 
10632 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10633 				aux = &env->insn_aux_data[i];
10634 				err = check_pseudo_btf_id(env, insn, aux);
10635 				if (err)
10636 					return err;
10637 				goto next_insn;
10638 			}
10639 
10640 			/* In final convert_pseudo_ld_imm64() step, this is
10641 			 * converted into regular 64-bit imm load insn.
10642 			 */
10643 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10644 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10645 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10646 			     insn[1].imm != 0)) {
10647 				verbose(env,
10648 					"unrecognized bpf_ld_imm64 insn\n");
10649 				return -EINVAL;
10650 			}
10651 
10652 			f = fdget(insn[0].imm);
10653 			map = __bpf_map_get(f);
10654 			if (IS_ERR(map)) {
10655 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
10656 					insn[0].imm);
10657 				return PTR_ERR(map);
10658 			}
10659 
10660 			err = check_map_prog_compatibility(env, map, env->prog);
10661 			if (err) {
10662 				fdput(f);
10663 				return err;
10664 			}
10665 
10666 			aux = &env->insn_aux_data[i];
10667 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10668 				addr = (unsigned long)map;
10669 			} else {
10670 				u32 off = insn[1].imm;
10671 
10672 				if (off >= BPF_MAX_VAR_OFF) {
10673 					verbose(env, "direct value offset of %u is not allowed\n", off);
10674 					fdput(f);
10675 					return -EINVAL;
10676 				}
10677 
10678 				if (!map->ops->map_direct_value_addr) {
10679 					verbose(env, "no direct value access support for this map type\n");
10680 					fdput(f);
10681 					return -EINVAL;
10682 				}
10683 
10684 				err = map->ops->map_direct_value_addr(map, &addr, off);
10685 				if (err) {
10686 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10687 						map->value_size, off);
10688 					fdput(f);
10689 					return err;
10690 				}
10691 
10692 				aux->map_off = off;
10693 				addr += off;
10694 			}
10695 
10696 			insn[0].imm = (u32)addr;
10697 			insn[1].imm = addr >> 32;
10698 
10699 			/* check whether we recorded this map already */
10700 			for (j = 0; j < env->used_map_cnt; j++) {
10701 				if (env->used_maps[j] == map) {
10702 					aux->map_index = j;
10703 					fdput(f);
10704 					goto next_insn;
10705 				}
10706 			}
10707 
10708 			if (env->used_map_cnt >= MAX_USED_MAPS) {
10709 				fdput(f);
10710 				return -E2BIG;
10711 			}
10712 
10713 			/* hold the map. If the program is rejected by verifier,
10714 			 * the map will be released by release_maps() or it
10715 			 * will be used by the valid program until it's unloaded
10716 			 * and all maps are released in free_used_maps()
10717 			 */
10718 			bpf_map_inc(map);
10719 
10720 			aux->map_index = env->used_map_cnt;
10721 			env->used_maps[env->used_map_cnt++] = map;
10722 
10723 			if (bpf_map_is_cgroup_storage(map) &&
10724 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10725 				verbose(env, "only one cgroup storage of each type is allowed\n");
10726 				fdput(f);
10727 				return -EBUSY;
10728 			}
10729 
10730 			fdput(f);
10731 next_insn:
10732 			insn++;
10733 			i++;
10734 			continue;
10735 		}
10736 
10737 		/* Basic sanity check before we invest more work here. */
10738 		if (!bpf_opcode_in_insntable(insn->code)) {
10739 			verbose(env, "unknown opcode %02x\n", insn->code);
10740 			return -EINVAL;
10741 		}
10742 	}
10743 
10744 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10745 	 * 'struct bpf_map *' into a register instead of user map_fd.
10746 	 * These pointers will be used later by verifier to validate map access.
10747 	 */
10748 	return 0;
10749 }
10750 
10751 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)10752 static void release_maps(struct bpf_verifier_env *env)
10753 {
10754 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10755 			     env->used_map_cnt);
10756 }
10757 
10758 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)10759 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10760 {
10761 	struct bpf_insn *insn = env->prog->insnsi;
10762 	int insn_cnt = env->prog->len;
10763 	int i;
10764 
10765 	for (i = 0; i < insn_cnt; i++, insn++)
10766 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10767 			insn->src_reg = 0;
10768 }
10769 
10770 /* single env->prog->insni[off] instruction was replaced with the range
10771  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10772  * [0, off) and [off, end) to new locations, so the patched range stays zero
10773  */
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)10774 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10775 				 struct bpf_insn_aux_data *new_data,
10776 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
10777 {
10778 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10779 	struct bpf_insn *insn = new_prog->insnsi;
10780 	u32 old_seen = old_data[off].seen;
10781 	u32 prog_len;
10782 	int i;
10783 
10784 	/* aux info at OFF always needs adjustment, no matter fast path
10785 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10786 	 * original insn at old prog.
10787 	 */
10788 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10789 
10790 	if (cnt == 1)
10791 		return;
10792 	prog_len = new_prog->len;
10793 
10794 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10795 	memcpy(new_data + off + cnt - 1, old_data + off,
10796 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10797 	for (i = off; i < off + cnt - 1; i++) {
10798 		/* Expand insni[off]'s seen count to the patched range. */
10799 		new_data[i].seen = old_seen;
10800 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10801 	}
10802 	env->insn_aux_data = new_data;
10803 	vfree(old_data);
10804 }
10805 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)10806 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10807 {
10808 	int i;
10809 
10810 	if (len == 1)
10811 		return;
10812 	/* NOTE: fake 'exit' subprog should be updated as well. */
10813 	for (i = 0; i <= env->subprog_cnt; i++) {
10814 		if (env->subprog_info[i].start <= off)
10815 			continue;
10816 		env->subprog_info[i].start += len - 1;
10817 	}
10818 }
10819 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)10820 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10821 {
10822 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10823 	int i, sz = prog->aux->size_poke_tab;
10824 	struct bpf_jit_poke_descriptor *desc;
10825 
10826 	for (i = 0; i < sz; i++) {
10827 		desc = &tab[i];
10828 		if (desc->insn_idx <= off)
10829 			continue;
10830 		desc->insn_idx += len - 1;
10831 	}
10832 }
10833 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)10834 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10835 					    const struct bpf_insn *patch, u32 len)
10836 {
10837 	struct bpf_prog *new_prog;
10838 	struct bpf_insn_aux_data *new_data = NULL;
10839 
10840 	if (len > 1) {
10841 		new_data = vzalloc(array_size(env->prog->len + len - 1,
10842 					      sizeof(struct bpf_insn_aux_data)));
10843 		if (!new_data)
10844 			return NULL;
10845 	}
10846 
10847 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10848 	if (IS_ERR(new_prog)) {
10849 		if (PTR_ERR(new_prog) == -ERANGE)
10850 			verbose(env,
10851 				"insn %d cannot be patched due to 16-bit range\n",
10852 				env->insn_aux_data[off].orig_idx);
10853 		vfree(new_data);
10854 		return NULL;
10855 	}
10856 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
10857 	adjust_subprog_starts(env, off, len);
10858 	adjust_poke_descs(new_prog, off, len);
10859 	return new_prog;
10860 }
10861 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10862 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10863 					      u32 off, u32 cnt)
10864 {
10865 	int i, j;
10866 
10867 	/* find first prog starting at or after off (first to remove) */
10868 	for (i = 0; i < env->subprog_cnt; i++)
10869 		if (env->subprog_info[i].start >= off)
10870 			break;
10871 	/* find first prog starting at or after off + cnt (first to stay) */
10872 	for (j = i; j < env->subprog_cnt; j++)
10873 		if (env->subprog_info[j].start >= off + cnt)
10874 			break;
10875 	/* if j doesn't start exactly at off + cnt, we are just removing
10876 	 * the front of previous prog
10877 	 */
10878 	if (env->subprog_info[j].start != off + cnt)
10879 		j--;
10880 
10881 	if (j > i) {
10882 		struct bpf_prog_aux *aux = env->prog->aux;
10883 		int move;
10884 
10885 		/* move fake 'exit' subprog as well */
10886 		move = env->subprog_cnt + 1 - j;
10887 
10888 		memmove(env->subprog_info + i,
10889 			env->subprog_info + j,
10890 			sizeof(*env->subprog_info) * move);
10891 		env->subprog_cnt -= j - i;
10892 
10893 		/* remove func_info */
10894 		if (aux->func_info) {
10895 			move = aux->func_info_cnt - j;
10896 
10897 			memmove(aux->func_info + i,
10898 				aux->func_info + j,
10899 				sizeof(*aux->func_info) * move);
10900 			aux->func_info_cnt -= j - i;
10901 			/* func_info->insn_off is set after all code rewrites,
10902 			 * in adjust_btf_func() - no need to adjust
10903 			 */
10904 		}
10905 	} else {
10906 		/* convert i from "first prog to remove" to "first to adjust" */
10907 		if (env->subprog_info[i].start == off)
10908 			i++;
10909 	}
10910 
10911 	/* update fake 'exit' subprog as well */
10912 	for (; i <= env->subprog_cnt; i++)
10913 		env->subprog_info[i].start -= cnt;
10914 
10915 	return 0;
10916 }
10917 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10918 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10919 				      u32 cnt)
10920 {
10921 	struct bpf_prog *prog = env->prog;
10922 	u32 i, l_off, l_cnt, nr_linfo;
10923 	struct bpf_line_info *linfo;
10924 
10925 	nr_linfo = prog->aux->nr_linfo;
10926 	if (!nr_linfo)
10927 		return 0;
10928 
10929 	linfo = prog->aux->linfo;
10930 
10931 	/* find first line info to remove, count lines to be removed */
10932 	for (i = 0; i < nr_linfo; i++)
10933 		if (linfo[i].insn_off >= off)
10934 			break;
10935 
10936 	l_off = i;
10937 	l_cnt = 0;
10938 	for (; i < nr_linfo; i++)
10939 		if (linfo[i].insn_off < off + cnt)
10940 			l_cnt++;
10941 		else
10942 			break;
10943 
10944 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10945 	 * last removed linfo.  prog is already modified, so prog->len == off
10946 	 * means no live instructions after (tail of the program was removed).
10947 	 */
10948 	if (prog->len != off && l_cnt &&
10949 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10950 		l_cnt--;
10951 		linfo[--i].insn_off = off + cnt;
10952 	}
10953 
10954 	/* remove the line info which refer to the removed instructions */
10955 	if (l_cnt) {
10956 		memmove(linfo + l_off, linfo + i,
10957 			sizeof(*linfo) * (nr_linfo - i));
10958 
10959 		prog->aux->nr_linfo -= l_cnt;
10960 		nr_linfo = prog->aux->nr_linfo;
10961 	}
10962 
10963 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10964 	for (i = l_off; i < nr_linfo; i++)
10965 		linfo[i].insn_off -= cnt;
10966 
10967 	/* fix up all subprogs (incl. 'exit') which start >= off */
10968 	for (i = 0; i <= env->subprog_cnt; i++)
10969 		if (env->subprog_info[i].linfo_idx > l_off) {
10970 			/* program may have started in the removed region but
10971 			 * may not be fully removed
10972 			 */
10973 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10974 				env->subprog_info[i].linfo_idx -= l_cnt;
10975 			else
10976 				env->subprog_info[i].linfo_idx = l_off;
10977 		}
10978 
10979 	return 0;
10980 }
10981 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)10982 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10983 {
10984 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10985 	unsigned int orig_prog_len = env->prog->len;
10986 	int err;
10987 
10988 	if (bpf_prog_is_dev_bound(env->prog->aux))
10989 		bpf_prog_offload_remove_insns(env, off, cnt);
10990 
10991 	err = bpf_remove_insns(env->prog, off, cnt);
10992 	if (err)
10993 		return err;
10994 
10995 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10996 	if (err)
10997 		return err;
10998 
10999 	err = bpf_adj_linfo_after_remove(env, off, cnt);
11000 	if (err)
11001 		return err;
11002 
11003 	memmove(aux_data + off,	aux_data + off + cnt,
11004 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
11005 
11006 	return 0;
11007 }
11008 
11009 /* The verifier does more data flow analysis than llvm and will not
11010  * explore branches that are dead at run time. Malicious programs can
11011  * have dead code too. Therefore replace all dead at-run-time code
11012  * with 'ja -1'.
11013  *
11014  * Just nops are not optimal, e.g. if they would sit at the end of the
11015  * program and through another bug we would manage to jump there, then
11016  * we'd execute beyond program memory otherwise. Returning exception
11017  * code also wouldn't work since we can have subprogs where the dead
11018  * code could be located.
11019  */
sanitize_dead_code(struct bpf_verifier_env * env)11020 static void sanitize_dead_code(struct bpf_verifier_env *env)
11021 {
11022 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11023 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
11024 	struct bpf_insn *insn = env->prog->insnsi;
11025 	const int insn_cnt = env->prog->len;
11026 	int i;
11027 
11028 	for (i = 0; i < insn_cnt; i++) {
11029 		if (aux_data[i].seen)
11030 			continue;
11031 		memcpy(insn + i, &trap, sizeof(trap));
11032 		aux_data[i].zext_dst = false;
11033 	}
11034 }
11035 
insn_is_cond_jump(u8 code)11036 static bool insn_is_cond_jump(u8 code)
11037 {
11038 	u8 op;
11039 
11040 	if (BPF_CLASS(code) == BPF_JMP32)
11041 		return true;
11042 
11043 	if (BPF_CLASS(code) != BPF_JMP)
11044 		return false;
11045 
11046 	op = BPF_OP(code);
11047 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11048 }
11049 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)11050 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11051 {
11052 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11053 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11054 	struct bpf_insn *insn = env->prog->insnsi;
11055 	const int insn_cnt = env->prog->len;
11056 	int i;
11057 
11058 	for (i = 0; i < insn_cnt; i++, insn++) {
11059 		if (!insn_is_cond_jump(insn->code))
11060 			continue;
11061 
11062 		if (!aux_data[i + 1].seen)
11063 			ja.off = insn->off;
11064 		else if (!aux_data[i + 1 + insn->off].seen)
11065 			ja.off = 0;
11066 		else
11067 			continue;
11068 
11069 		if (bpf_prog_is_dev_bound(env->prog->aux))
11070 			bpf_prog_offload_replace_insn(env, i, &ja);
11071 
11072 		memcpy(insn, &ja, sizeof(ja));
11073 	}
11074 }
11075 
opt_remove_dead_code(struct bpf_verifier_env * env)11076 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11077 {
11078 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11079 	int insn_cnt = env->prog->len;
11080 	int i, err;
11081 
11082 	for (i = 0; i < insn_cnt; i++) {
11083 		int j;
11084 
11085 		j = 0;
11086 		while (i + j < insn_cnt && !aux_data[i + j].seen)
11087 			j++;
11088 		if (!j)
11089 			continue;
11090 
11091 		err = verifier_remove_insns(env, i, j);
11092 		if (err)
11093 			return err;
11094 		insn_cnt = env->prog->len;
11095 	}
11096 
11097 	return 0;
11098 }
11099 
opt_remove_nops(struct bpf_verifier_env * env)11100 static int opt_remove_nops(struct bpf_verifier_env *env)
11101 {
11102 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11103 	struct bpf_insn *insn = env->prog->insnsi;
11104 	int insn_cnt = env->prog->len;
11105 	int i, err;
11106 
11107 	for (i = 0; i < insn_cnt; i++) {
11108 		if (memcmp(&insn[i], &ja, sizeof(ja)))
11109 			continue;
11110 
11111 		err = verifier_remove_insns(env, i, 1);
11112 		if (err)
11113 			return err;
11114 		insn_cnt--;
11115 		i--;
11116 	}
11117 
11118 	return 0;
11119 }
11120 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)11121 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11122 					 const union bpf_attr *attr)
11123 {
11124 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11125 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
11126 	int i, patch_len, delta = 0, len = env->prog->len;
11127 	struct bpf_insn *insns = env->prog->insnsi;
11128 	struct bpf_prog *new_prog;
11129 	bool rnd_hi32;
11130 
11131 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11132 	zext_patch[1] = BPF_ZEXT_REG(0);
11133 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11134 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11135 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11136 	for (i = 0; i < len; i++) {
11137 		int adj_idx = i + delta;
11138 		struct bpf_insn insn;
11139 
11140 		insn = insns[adj_idx];
11141 		if (!aux[adj_idx].zext_dst) {
11142 			u8 code, class;
11143 			u32 imm_rnd;
11144 
11145 			if (!rnd_hi32)
11146 				continue;
11147 
11148 			code = insn.code;
11149 			class = BPF_CLASS(code);
11150 			if (insn_no_def(&insn))
11151 				continue;
11152 
11153 			/* NOTE: arg "reg" (the fourth one) is only used for
11154 			 *       BPF_STX which has been ruled out in above
11155 			 *       check, it is safe to pass NULL here.
11156 			 */
11157 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11158 				if (class == BPF_LD &&
11159 				    BPF_MODE(code) == BPF_IMM)
11160 					i++;
11161 				continue;
11162 			}
11163 
11164 			/* ctx load could be transformed into wider load. */
11165 			if (class == BPF_LDX &&
11166 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
11167 				continue;
11168 
11169 			imm_rnd = get_random_int();
11170 			rnd_hi32_patch[0] = insn;
11171 			rnd_hi32_patch[1].imm = imm_rnd;
11172 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11173 			patch = rnd_hi32_patch;
11174 			patch_len = 4;
11175 			goto apply_patch_buffer;
11176 		}
11177 
11178 		if (!bpf_jit_needs_zext())
11179 			continue;
11180 
11181 		zext_patch[0] = insn;
11182 		zext_patch[1].dst_reg = insn.dst_reg;
11183 		zext_patch[1].src_reg = insn.dst_reg;
11184 		patch = zext_patch;
11185 		patch_len = 2;
11186 apply_patch_buffer:
11187 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11188 		if (!new_prog)
11189 			return -ENOMEM;
11190 		env->prog = new_prog;
11191 		insns = new_prog->insnsi;
11192 		aux = env->insn_aux_data;
11193 		delta += patch_len - 1;
11194 	}
11195 
11196 	return 0;
11197 }
11198 
11199 /* convert load instructions that access fields of a context type into a
11200  * sequence of instructions that access fields of the underlying structure:
11201  *     struct __sk_buff    -> struct sk_buff
11202  *     struct bpf_sock_ops -> struct sock
11203  */
convert_ctx_accesses(struct bpf_verifier_env * env)11204 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11205 {
11206 	const struct bpf_verifier_ops *ops = env->ops;
11207 	int i, cnt, size, ctx_field_size, delta = 0;
11208 	const int insn_cnt = env->prog->len;
11209 	struct bpf_insn insn_buf[16], *insn;
11210 	u32 target_size, size_default, off;
11211 	struct bpf_prog *new_prog;
11212 	enum bpf_access_type type;
11213 	bool is_narrower_load;
11214 
11215 	if (ops->gen_prologue || env->seen_direct_write) {
11216 		if (!ops->gen_prologue) {
11217 			verbose(env, "bpf verifier is misconfigured\n");
11218 			return -EINVAL;
11219 		}
11220 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11221 					env->prog);
11222 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11223 			verbose(env, "bpf verifier is misconfigured\n");
11224 			return -EINVAL;
11225 		} else if (cnt) {
11226 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11227 			if (!new_prog)
11228 				return -ENOMEM;
11229 
11230 			env->prog = new_prog;
11231 			delta += cnt - 1;
11232 		}
11233 	}
11234 
11235 	if (bpf_prog_is_dev_bound(env->prog->aux))
11236 		return 0;
11237 
11238 	insn = env->prog->insnsi + delta;
11239 
11240 	for (i = 0; i < insn_cnt; i++, insn++) {
11241 		bpf_convert_ctx_access_t convert_ctx_access;
11242 		bool ctx_access;
11243 
11244 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11245 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11246 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11247 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11248 			type = BPF_READ;
11249 			ctx_access = true;
11250 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11251 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11252 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11253 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11254 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11255 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11256 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11257 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11258 			type = BPF_WRITE;
11259 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11260 		} else {
11261 			continue;
11262 		}
11263 
11264 		if (type == BPF_WRITE &&
11265 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
11266 			struct bpf_insn patch[] = {
11267 				*insn,
11268 				BPF_ST_NOSPEC(),
11269 			};
11270 
11271 			cnt = ARRAY_SIZE(patch);
11272 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11273 			if (!new_prog)
11274 				return -ENOMEM;
11275 
11276 			delta    += cnt - 1;
11277 			env->prog = new_prog;
11278 			insn      = new_prog->insnsi + i + delta;
11279 			continue;
11280 		}
11281 
11282 		if (!ctx_access)
11283 			continue;
11284 
11285 		switch (env->insn_aux_data[i + delta].ptr_type) {
11286 		case PTR_TO_CTX:
11287 			if (!ops->convert_ctx_access)
11288 				continue;
11289 			convert_ctx_access = ops->convert_ctx_access;
11290 			break;
11291 		case PTR_TO_SOCKET:
11292 		case PTR_TO_SOCK_COMMON:
11293 			convert_ctx_access = bpf_sock_convert_ctx_access;
11294 			break;
11295 		case PTR_TO_TCP_SOCK:
11296 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11297 			break;
11298 		case PTR_TO_XDP_SOCK:
11299 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11300 			break;
11301 		case PTR_TO_BTF_ID:
11302 			if (type == BPF_READ) {
11303 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11304 					BPF_SIZE((insn)->code);
11305 				env->prog->aux->num_exentries++;
11306 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11307 				verbose(env, "Writes through BTF pointers are not allowed\n");
11308 				return -EINVAL;
11309 			}
11310 			continue;
11311 		default:
11312 			continue;
11313 		}
11314 
11315 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11316 		size = BPF_LDST_BYTES(insn);
11317 
11318 		/* If the read access is a narrower load of the field,
11319 		 * convert to a 4/8-byte load, to minimum program type specific
11320 		 * convert_ctx_access changes. If conversion is successful,
11321 		 * we will apply proper mask to the result.
11322 		 */
11323 		is_narrower_load = size < ctx_field_size;
11324 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11325 		off = insn->off;
11326 		if (is_narrower_load) {
11327 			u8 size_code;
11328 
11329 			if (type == BPF_WRITE) {
11330 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11331 				return -EINVAL;
11332 			}
11333 
11334 			size_code = BPF_H;
11335 			if (ctx_field_size == 4)
11336 				size_code = BPF_W;
11337 			else if (ctx_field_size == 8)
11338 				size_code = BPF_DW;
11339 
11340 			insn->off = off & ~(size_default - 1);
11341 			insn->code = BPF_LDX | BPF_MEM | size_code;
11342 		}
11343 
11344 		target_size = 0;
11345 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11346 					 &target_size);
11347 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11348 		    (ctx_field_size && !target_size)) {
11349 			verbose(env, "bpf verifier is misconfigured\n");
11350 			return -EINVAL;
11351 		}
11352 
11353 		if (is_narrower_load && size < target_size) {
11354 			u8 shift = bpf_ctx_narrow_access_offset(
11355 				off, size, size_default) * 8;
11356 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11357 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11358 				return -EINVAL;
11359 			}
11360 			if (ctx_field_size <= 4) {
11361 				if (shift)
11362 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11363 									insn->dst_reg,
11364 									shift);
11365 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11366 								(1 << size * 8) - 1);
11367 			} else {
11368 				if (shift)
11369 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11370 									insn->dst_reg,
11371 									shift);
11372 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11373 								(1ULL << size * 8) - 1);
11374 			}
11375 		}
11376 
11377 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11378 		if (!new_prog)
11379 			return -ENOMEM;
11380 
11381 		delta += cnt - 1;
11382 
11383 		/* keep walking new program and skip insns we just inserted */
11384 		env->prog = new_prog;
11385 		insn      = new_prog->insnsi + i + delta;
11386 	}
11387 
11388 	return 0;
11389 }
11390 
jit_subprogs(struct bpf_verifier_env * env)11391 static int jit_subprogs(struct bpf_verifier_env *env)
11392 {
11393 	struct bpf_prog *prog = env->prog, **func, *tmp;
11394 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11395 	struct bpf_map *map_ptr;
11396 	struct bpf_insn *insn;
11397 	void *old_bpf_func;
11398 	int err, num_exentries;
11399 
11400 	if (env->subprog_cnt <= 1)
11401 		return 0;
11402 
11403 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11404 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11405 		    insn->src_reg != BPF_PSEUDO_CALL)
11406 			continue;
11407 		/* Upon error here we cannot fall back to interpreter but
11408 		 * need a hard reject of the program. Thus -EFAULT is
11409 		 * propagated in any case.
11410 		 */
11411 		subprog = find_subprog(env, i + insn->imm + 1);
11412 		if (subprog < 0) {
11413 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11414 				  i + insn->imm + 1);
11415 			return -EFAULT;
11416 		}
11417 		/* temporarily remember subprog id inside insn instead of
11418 		 * aux_data, since next loop will split up all insns into funcs
11419 		 */
11420 		insn->off = subprog;
11421 		/* remember original imm in case JIT fails and fallback
11422 		 * to interpreter will be needed
11423 		 */
11424 		env->insn_aux_data[i].call_imm = insn->imm;
11425 		/* point imm to __bpf_call_base+1 from JITs point of view */
11426 		insn->imm = 1;
11427 	}
11428 
11429 	err = bpf_prog_alloc_jited_linfo(prog);
11430 	if (err)
11431 		goto out_undo_insn;
11432 
11433 	err = -ENOMEM;
11434 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11435 	if (!func)
11436 		goto out_undo_insn;
11437 
11438 	for (i = 0; i < env->subprog_cnt; i++) {
11439 		subprog_start = subprog_end;
11440 		subprog_end = env->subprog_info[i + 1].start;
11441 
11442 		len = subprog_end - subprog_start;
11443 		/* BPF_PROG_RUN doesn't call subprogs directly,
11444 		 * hence main prog stats include the runtime of subprogs.
11445 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11446 		 * func[i]->aux->stats will never be accessed and stays NULL
11447 		 */
11448 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11449 		if (!func[i])
11450 			goto out_free;
11451 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11452 		       len * sizeof(struct bpf_insn));
11453 		func[i]->type = prog->type;
11454 		func[i]->len = len;
11455 		if (bpf_prog_calc_tag(func[i]))
11456 			goto out_free;
11457 		func[i]->is_func = 1;
11458 		func[i]->aux->func_idx = i;
11459 		/* Below members will be freed only at prog->aux */
11460 		func[i]->aux->btf = prog->aux->btf;
11461 		func[i]->aux->func_info = prog->aux->func_info;
11462 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11463 		func[i]->aux->poke_tab = prog->aux->poke_tab;
11464 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11465 
11466 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11467 			struct bpf_jit_poke_descriptor *poke;
11468 
11469 			poke = &prog->aux->poke_tab[j];
11470 			if (poke->insn_idx < subprog_end &&
11471 			    poke->insn_idx >= subprog_start)
11472 				poke->aux = func[i]->aux;
11473 		}
11474 
11475 		func[i]->aux->name[0] = 'F';
11476 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11477 		func[i]->jit_requested = 1;
11478 		func[i]->aux->linfo = prog->aux->linfo;
11479 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11480 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11481 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11482 		num_exentries = 0;
11483 		insn = func[i]->insnsi;
11484 		for (j = 0; j < func[i]->len; j++, insn++) {
11485 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11486 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11487 				num_exentries++;
11488 		}
11489 		func[i]->aux->num_exentries = num_exentries;
11490 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11491 		func[i] = bpf_int_jit_compile(func[i]);
11492 		if (!func[i]->jited) {
11493 			err = -ENOTSUPP;
11494 			goto out_free;
11495 		}
11496 		cond_resched();
11497 	}
11498 
11499 	/* at this point all bpf functions were successfully JITed
11500 	 * now populate all bpf_calls with correct addresses and
11501 	 * run last pass of JIT
11502 	 */
11503 	for (i = 0; i < env->subprog_cnt; i++) {
11504 		insn = func[i]->insnsi;
11505 		for (j = 0; j < func[i]->len; j++, insn++) {
11506 			if (insn->code != (BPF_JMP | BPF_CALL) ||
11507 			    insn->src_reg != BPF_PSEUDO_CALL)
11508 				continue;
11509 			subprog = insn->off;
11510 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11511 				    __bpf_call_base;
11512 		}
11513 
11514 		/* we use the aux data to keep a list of the start addresses
11515 		 * of the JITed images for each function in the program
11516 		 *
11517 		 * for some architectures, such as powerpc64, the imm field
11518 		 * might not be large enough to hold the offset of the start
11519 		 * address of the callee's JITed image from __bpf_call_base
11520 		 *
11521 		 * in such cases, we can lookup the start address of a callee
11522 		 * by using its subprog id, available from the off field of
11523 		 * the call instruction, as an index for this list
11524 		 */
11525 		func[i]->aux->func = func;
11526 		func[i]->aux->func_cnt = env->subprog_cnt;
11527 	}
11528 	for (i = 0; i < env->subprog_cnt; i++) {
11529 		old_bpf_func = func[i]->bpf_func;
11530 		tmp = bpf_int_jit_compile(func[i]);
11531 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11532 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11533 			err = -ENOTSUPP;
11534 			goto out_free;
11535 		}
11536 		cond_resched();
11537 	}
11538 
11539 	/* finally lock prog and jit images for all functions and
11540 	 * populate kallsysm
11541 	 */
11542 	for (i = 1; i < env->subprog_cnt; i++) {
11543 		err = bpf_prog_lock_ro(func[i]);
11544 		if (err)
11545 			goto out_free;
11546 	}
11547 
11548 	for (i = 1; i < env->subprog_cnt; i++)
11549 		bpf_prog_kallsyms_add(func[i]);
11550 
11551 	/* Last step: make now unused interpreter insns from main
11552 	 * prog consistent for later dump requests, so they can
11553 	 * later look the same as if they were interpreted only.
11554 	 */
11555 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11556 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11557 		    insn->src_reg != BPF_PSEUDO_CALL)
11558 			continue;
11559 		insn->off = env->insn_aux_data[i].call_imm;
11560 		subprog = find_subprog(env, i + insn->off + 1);
11561 		insn->imm = subprog;
11562 	}
11563 
11564 	prog->jited = 1;
11565 	prog->bpf_func = func[0]->bpf_func;
11566 	prog->aux->func = func;
11567 	prog->aux->func_cnt = env->subprog_cnt;
11568 	bpf_prog_free_unused_jited_linfo(prog);
11569 	return 0;
11570 out_free:
11571 	/* We failed JIT'ing, so at this point we need to unregister poke
11572 	 * descriptors from subprogs, so that kernel is not attempting to
11573 	 * patch it anymore as we're freeing the subprog JIT memory.
11574 	 */
11575 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11576 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11577 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11578 	}
11579 	/* At this point we're guaranteed that poke descriptors are not
11580 	 * live anymore. We can just unlink its descriptor table as it's
11581 	 * released with the main prog.
11582 	 */
11583 	for (i = 0; i < env->subprog_cnt; i++) {
11584 		if (!func[i])
11585 			continue;
11586 		func[i]->aux->poke_tab = NULL;
11587 		bpf_jit_free(func[i]);
11588 	}
11589 	kfree(func);
11590 out_undo_insn:
11591 	/* cleanup main prog to be interpreted */
11592 	prog->jit_requested = 0;
11593 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11594 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11595 		    insn->src_reg != BPF_PSEUDO_CALL)
11596 			continue;
11597 		insn->off = 0;
11598 		insn->imm = env->insn_aux_data[i].call_imm;
11599 	}
11600 	bpf_prog_free_jited_linfo(prog);
11601 	return err;
11602 }
11603 
fixup_call_args(struct bpf_verifier_env * env)11604 static int fixup_call_args(struct bpf_verifier_env *env)
11605 {
11606 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11607 	struct bpf_prog *prog = env->prog;
11608 	struct bpf_insn *insn = prog->insnsi;
11609 	int i, depth;
11610 #endif
11611 	int err = 0;
11612 
11613 	if (env->prog->jit_requested &&
11614 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
11615 		err = jit_subprogs(env);
11616 		if (err == 0)
11617 			return 0;
11618 		if (err == -EFAULT)
11619 			return err;
11620 	}
11621 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11622 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11623 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
11624 		 * have to be rejected, since interpreter doesn't support them yet.
11625 		 */
11626 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11627 		return -EINVAL;
11628 	}
11629 	for (i = 0; i < prog->len; i++, insn++) {
11630 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11631 		    insn->src_reg != BPF_PSEUDO_CALL)
11632 			continue;
11633 		depth = get_callee_stack_depth(env, insn, i);
11634 		if (depth < 0)
11635 			return depth;
11636 		bpf_patch_call_args(insn, depth);
11637 	}
11638 	err = 0;
11639 #endif
11640 	return err;
11641 }
11642 
11643 /* fixup insn->imm field of bpf_call instructions
11644  * and inline eligible helpers as explicit sequence of BPF instructions
11645  *
11646  * this function is called after eBPF program passed verification
11647  */
fixup_bpf_calls(struct bpf_verifier_env * env)11648 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11649 {
11650 	struct bpf_prog *prog = env->prog;
11651 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
11652 	struct bpf_insn *insn = prog->insnsi;
11653 	const struct bpf_func_proto *fn;
11654 	const int insn_cnt = prog->len;
11655 	const struct bpf_map_ops *ops;
11656 	struct bpf_insn_aux_data *aux;
11657 	struct bpf_insn insn_buf[16];
11658 	struct bpf_prog *new_prog;
11659 	struct bpf_map *map_ptr;
11660 	int i, ret, cnt, delta = 0;
11661 
11662 	for (i = 0; i < insn_cnt; i++, insn++) {
11663 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11664 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11665 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11666 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11667 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11668 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11669 			struct bpf_insn *patchlet;
11670 			struct bpf_insn chk_and_div[] = {
11671 				/* [R,W]x div 0 -> 0 */
11672 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11673 					     BPF_JNE | BPF_K, insn->src_reg,
11674 					     0, 2, 0),
11675 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11676 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11677 				*insn,
11678 			};
11679 			struct bpf_insn chk_and_mod[] = {
11680 				/* [R,W]x mod 0 -> [R,W]x */
11681 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11682 					     BPF_JEQ | BPF_K, insn->src_reg,
11683 					     0, 1 + (is64 ? 0 : 1), 0),
11684 				*insn,
11685 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11686 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11687 			};
11688 
11689 			patchlet = isdiv ? chk_and_div : chk_and_mod;
11690 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11691 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11692 
11693 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11694 			if (!new_prog)
11695 				return -ENOMEM;
11696 
11697 			delta    += cnt - 1;
11698 			env->prog = prog = new_prog;
11699 			insn      = new_prog->insnsi + i + delta;
11700 			continue;
11701 		}
11702 
11703 		if (BPF_CLASS(insn->code) == BPF_LD &&
11704 		    (BPF_MODE(insn->code) == BPF_ABS ||
11705 		     BPF_MODE(insn->code) == BPF_IND)) {
11706 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
11707 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11708 				verbose(env, "bpf verifier is misconfigured\n");
11709 				return -EINVAL;
11710 			}
11711 
11712 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11713 			if (!new_prog)
11714 				return -ENOMEM;
11715 
11716 			delta    += cnt - 1;
11717 			env->prog = prog = new_prog;
11718 			insn      = new_prog->insnsi + i + delta;
11719 			continue;
11720 		}
11721 
11722 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11723 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11724 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11725 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11726 			struct bpf_insn insn_buf[16];
11727 			struct bpf_insn *patch = &insn_buf[0];
11728 			bool issrc, isneg, isimm;
11729 			u32 off_reg;
11730 
11731 			aux = &env->insn_aux_data[i + delta];
11732 			if (!aux->alu_state ||
11733 			    aux->alu_state == BPF_ALU_NON_POINTER)
11734 				continue;
11735 
11736 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11737 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11738 				BPF_ALU_SANITIZE_SRC;
11739 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11740 
11741 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11742 			if (isimm) {
11743 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11744 			} else {
11745 				if (isneg)
11746 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11747 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11748 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11749 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11750 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11751 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11752 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11753 			}
11754 			if (!issrc)
11755 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11756 			insn->src_reg = BPF_REG_AX;
11757 			if (isneg)
11758 				insn->code = insn->code == code_add ?
11759 					     code_sub : code_add;
11760 			*patch++ = *insn;
11761 			if (issrc && isneg && !isimm)
11762 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11763 			cnt = patch - insn_buf;
11764 
11765 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11766 			if (!new_prog)
11767 				return -ENOMEM;
11768 
11769 			delta    += cnt - 1;
11770 			env->prog = prog = new_prog;
11771 			insn      = new_prog->insnsi + i + delta;
11772 			continue;
11773 		}
11774 
11775 		if (insn->code != (BPF_JMP | BPF_CALL))
11776 			continue;
11777 		if (insn->src_reg == BPF_PSEUDO_CALL)
11778 			continue;
11779 
11780 		if (insn->imm == BPF_FUNC_get_route_realm)
11781 			prog->dst_needed = 1;
11782 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11783 			bpf_user_rnd_init_once();
11784 		if (insn->imm == BPF_FUNC_override_return)
11785 			prog->kprobe_override = 1;
11786 		if (insn->imm == BPF_FUNC_tail_call) {
11787 			/* If we tail call into other programs, we
11788 			 * cannot make any assumptions since they can
11789 			 * be replaced dynamically during runtime in
11790 			 * the program array.
11791 			 */
11792 			prog->cb_access = 1;
11793 			if (!allow_tail_call_in_subprogs(env))
11794 				prog->aux->stack_depth = MAX_BPF_STACK;
11795 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11796 
11797 			/* mark bpf_tail_call as different opcode to avoid
11798 			 * conditional branch in the interpeter for every normal
11799 			 * call and to prevent accidental JITing by JIT compiler
11800 			 * that doesn't support bpf_tail_call yet
11801 			 */
11802 			insn->imm = 0;
11803 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11804 
11805 			aux = &env->insn_aux_data[i + delta];
11806 			if (env->bpf_capable && !expect_blinding &&
11807 			    prog->jit_requested &&
11808 			    !bpf_map_key_poisoned(aux) &&
11809 			    !bpf_map_ptr_poisoned(aux) &&
11810 			    !bpf_map_ptr_unpriv(aux)) {
11811 				struct bpf_jit_poke_descriptor desc = {
11812 					.reason = BPF_POKE_REASON_TAIL_CALL,
11813 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11814 					.tail_call.key = bpf_map_key_immediate(aux),
11815 					.insn_idx = i + delta,
11816 				};
11817 
11818 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11819 				if (ret < 0) {
11820 					verbose(env, "adding tail call poke descriptor failed\n");
11821 					return ret;
11822 				}
11823 
11824 				insn->imm = ret + 1;
11825 				continue;
11826 			}
11827 
11828 			if (!bpf_map_ptr_unpriv(aux))
11829 				continue;
11830 
11831 			/* instead of changing every JIT dealing with tail_call
11832 			 * emit two extra insns:
11833 			 * if (index >= max_entries) goto out;
11834 			 * index &= array->index_mask;
11835 			 * to avoid out-of-bounds cpu speculation
11836 			 */
11837 			if (bpf_map_ptr_poisoned(aux)) {
11838 				verbose(env, "tail_call abusing map_ptr\n");
11839 				return -EINVAL;
11840 			}
11841 
11842 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11843 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11844 						  map_ptr->max_entries, 2);
11845 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11846 						    container_of(map_ptr,
11847 								 struct bpf_array,
11848 								 map)->index_mask);
11849 			insn_buf[2] = *insn;
11850 			cnt = 3;
11851 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11852 			if (!new_prog)
11853 				return -ENOMEM;
11854 
11855 			delta    += cnt - 1;
11856 			env->prog = prog = new_prog;
11857 			insn      = new_prog->insnsi + i + delta;
11858 			continue;
11859 		}
11860 
11861 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11862 		 * and other inlining handlers are currently limited to 64 bit
11863 		 * only.
11864 		 */
11865 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11866 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11867 		     insn->imm == BPF_FUNC_map_update_elem ||
11868 		     insn->imm == BPF_FUNC_map_delete_elem ||
11869 		     insn->imm == BPF_FUNC_map_push_elem   ||
11870 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11871 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11872 			aux = &env->insn_aux_data[i + delta];
11873 			if (bpf_map_ptr_poisoned(aux))
11874 				goto patch_call_imm;
11875 
11876 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11877 			ops = map_ptr->ops;
11878 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11879 			    ops->map_gen_lookup) {
11880 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11881 				if (cnt == -EOPNOTSUPP)
11882 					goto patch_map_ops_generic;
11883 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11884 					verbose(env, "bpf verifier is misconfigured\n");
11885 					return -EINVAL;
11886 				}
11887 
11888 				new_prog = bpf_patch_insn_data(env, i + delta,
11889 							       insn_buf, cnt);
11890 				if (!new_prog)
11891 					return -ENOMEM;
11892 
11893 				delta    += cnt - 1;
11894 				env->prog = prog = new_prog;
11895 				insn      = new_prog->insnsi + i + delta;
11896 				continue;
11897 			}
11898 
11899 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11900 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11901 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11902 				     (int (*)(struct bpf_map *map, void *key))NULL));
11903 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11904 				     (int (*)(struct bpf_map *map, void *key, void *value,
11905 					      u64 flags))NULL));
11906 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11907 				     (int (*)(struct bpf_map *map, void *value,
11908 					      u64 flags))NULL));
11909 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11910 				     (int (*)(struct bpf_map *map, void *value))NULL));
11911 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11912 				     (int (*)(struct bpf_map *map, void *value))NULL));
11913 patch_map_ops_generic:
11914 			switch (insn->imm) {
11915 			case BPF_FUNC_map_lookup_elem:
11916 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11917 					    __bpf_call_base;
11918 				continue;
11919 			case BPF_FUNC_map_update_elem:
11920 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11921 					    __bpf_call_base;
11922 				continue;
11923 			case BPF_FUNC_map_delete_elem:
11924 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11925 					    __bpf_call_base;
11926 				continue;
11927 			case BPF_FUNC_map_push_elem:
11928 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11929 					    __bpf_call_base;
11930 				continue;
11931 			case BPF_FUNC_map_pop_elem:
11932 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11933 					    __bpf_call_base;
11934 				continue;
11935 			case BPF_FUNC_map_peek_elem:
11936 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11937 					    __bpf_call_base;
11938 				continue;
11939 			}
11940 
11941 			goto patch_call_imm;
11942 		}
11943 
11944 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11945 		    insn->imm == BPF_FUNC_jiffies64) {
11946 			struct bpf_insn ld_jiffies_addr[2] = {
11947 				BPF_LD_IMM64(BPF_REG_0,
11948 					     (unsigned long)&jiffies),
11949 			};
11950 
11951 			insn_buf[0] = ld_jiffies_addr[0];
11952 			insn_buf[1] = ld_jiffies_addr[1];
11953 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11954 						  BPF_REG_0, 0);
11955 			cnt = 3;
11956 
11957 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11958 						       cnt);
11959 			if (!new_prog)
11960 				return -ENOMEM;
11961 
11962 			delta    += cnt - 1;
11963 			env->prog = prog = new_prog;
11964 			insn      = new_prog->insnsi + i + delta;
11965 			continue;
11966 		}
11967 
11968 patch_call_imm:
11969 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11970 		/* all functions that have prototype and verifier allowed
11971 		 * programs to call them, must be real in-kernel functions
11972 		 */
11973 		if (!fn->func) {
11974 			verbose(env,
11975 				"kernel subsystem misconfigured func %s#%d\n",
11976 				func_id_name(insn->imm), insn->imm);
11977 			return -EFAULT;
11978 		}
11979 		insn->imm = fn->func - __bpf_call_base;
11980 	}
11981 
11982 	/* Since poke tab is now finalized, publish aux to tracker. */
11983 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11984 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11985 		if (!map_ptr->ops->map_poke_track ||
11986 		    !map_ptr->ops->map_poke_untrack ||
11987 		    !map_ptr->ops->map_poke_run) {
11988 			verbose(env, "bpf verifier is misconfigured\n");
11989 			return -EINVAL;
11990 		}
11991 
11992 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11993 		if (ret < 0) {
11994 			verbose(env, "tracking tail call prog failed\n");
11995 			return ret;
11996 		}
11997 	}
11998 
11999 	return 0;
12000 }
12001 
free_states(struct bpf_verifier_env * env)12002 static void free_states(struct bpf_verifier_env *env)
12003 {
12004 	struct bpf_verifier_state_list *sl, *sln;
12005 	int i;
12006 
12007 	sl = env->free_list;
12008 	while (sl) {
12009 		sln = sl->next;
12010 		free_verifier_state(&sl->state, false);
12011 		kfree(sl);
12012 		sl = sln;
12013 	}
12014 	env->free_list = NULL;
12015 
12016 	if (!env->explored_states)
12017 		return;
12018 
12019 	for (i = 0; i < state_htab_size(env); i++) {
12020 		sl = env->explored_states[i];
12021 
12022 		while (sl) {
12023 			sln = sl->next;
12024 			free_verifier_state(&sl->state, false);
12025 			kfree(sl);
12026 			sl = sln;
12027 		}
12028 		env->explored_states[i] = NULL;
12029 	}
12030 }
12031 
do_check_common(struct bpf_verifier_env * env,int subprog)12032 static int do_check_common(struct bpf_verifier_env *env, int subprog)
12033 {
12034 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12035 	struct bpf_verifier_state *state;
12036 	struct bpf_reg_state *regs;
12037 	int ret, i;
12038 
12039 	env->prev_linfo = NULL;
12040 	env->pass_cnt++;
12041 
12042 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12043 	if (!state)
12044 		return -ENOMEM;
12045 	state->curframe = 0;
12046 	state->speculative = false;
12047 	state->branches = 1;
12048 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12049 	if (!state->frame[0]) {
12050 		kfree(state);
12051 		return -ENOMEM;
12052 	}
12053 	env->cur_state = state;
12054 	init_func_state(env, state->frame[0],
12055 			BPF_MAIN_FUNC /* callsite */,
12056 			0 /* frameno */,
12057 			subprog);
12058 
12059 	state->first_insn_idx = env->subprog_info[subprog].start;
12060 	state->last_insn_idx = -1;
12061 
12062 	regs = state->frame[state->curframe]->regs;
12063 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12064 		ret = btf_prepare_func_args(env, subprog, regs);
12065 		if (ret)
12066 			goto out;
12067 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12068 			if (regs[i].type == PTR_TO_CTX)
12069 				mark_reg_known_zero(env, regs, i);
12070 			else if (regs[i].type == SCALAR_VALUE)
12071 				mark_reg_unknown(env, regs, i);
12072 		}
12073 	} else {
12074 		/* 1st arg to a function */
12075 		regs[BPF_REG_1].type = PTR_TO_CTX;
12076 		mark_reg_known_zero(env, regs, BPF_REG_1);
12077 		ret = btf_check_func_arg_match(env, subprog, regs);
12078 		if (ret == -EFAULT)
12079 			/* unlikely verifier bug. abort.
12080 			 * ret == 0 and ret < 0 are sadly acceptable for
12081 			 * main() function due to backward compatibility.
12082 			 * Like socket filter program may be written as:
12083 			 * int bpf_prog(struct pt_regs *ctx)
12084 			 * and never dereference that ctx in the program.
12085 			 * 'struct pt_regs' is a type mismatch for socket
12086 			 * filter that should be using 'struct __sk_buff'.
12087 			 */
12088 			goto out;
12089 	}
12090 
12091 	ret = do_check(env);
12092 out:
12093 	/* check for NULL is necessary, since cur_state can be freed inside
12094 	 * do_check() under memory pressure.
12095 	 */
12096 	if (env->cur_state) {
12097 		free_verifier_state(env->cur_state, true);
12098 		env->cur_state = NULL;
12099 	}
12100 	while (!pop_stack(env, NULL, NULL, false));
12101 	if (!ret && pop_log)
12102 		bpf_vlog_reset(&env->log, 0);
12103 	free_states(env);
12104 	return ret;
12105 }
12106 
12107 /* Verify all global functions in a BPF program one by one based on their BTF.
12108  * All global functions must pass verification. Otherwise the whole program is rejected.
12109  * Consider:
12110  * int bar(int);
12111  * int foo(int f)
12112  * {
12113  *    return bar(f);
12114  * }
12115  * int bar(int b)
12116  * {
12117  *    ...
12118  * }
12119  * foo() will be verified first for R1=any_scalar_value. During verification it
12120  * will be assumed that bar() already verified successfully and call to bar()
12121  * from foo() will be checked for type match only. Later bar() will be verified
12122  * independently to check that it's safe for R1=any_scalar_value.
12123  */
do_check_subprogs(struct bpf_verifier_env * env)12124 static int do_check_subprogs(struct bpf_verifier_env *env)
12125 {
12126 	struct bpf_prog_aux *aux = env->prog->aux;
12127 	int i, ret;
12128 
12129 	if (!aux->func_info)
12130 		return 0;
12131 
12132 	for (i = 1; i < env->subprog_cnt; i++) {
12133 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12134 			continue;
12135 		env->insn_idx = env->subprog_info[i].start;
12136 		WARN_ON_ONCE(env->insn_idx == 0);
12137 		ret = do_check_common(env, i);
12138 		if (ret) {
12139 			return ret;
12140 		} else if (env->log.level & BPF_LOG_LEVEL) {
12141 			verbose(env,
12142 				"Func#%d is safe for any args that match its prototype\n",
12143 				i);
12144 		}
12145 	}
12146 	return 0;
12147 }
12148 
do_check_main(struct bpf_verifier_env * env)12149 static int do_check_main(struct bpf_verifier_env *env)
12150 {
12151 	int ret;
12152 
12153 	env->insn_idx = 0;
12154 	ret = do_check_common(env, 0);
12155 	if (!ret)
12156 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12157 	return ret;
12158 }
12159 
12160 
print_verification_stats(struct bpf_verifier_env * env)12161 static void print_verification_stats(struct bpf_verifier_env *env)
12162 {
12163 	int i;
12164 
12165 	if (env->log.level & BPF_LOG_STATS) {
12166 		verbose(env, "verification time %lld usec\n",
12167 			div_u64(env->verification_time, 1000));
12168 		verbose(env, "stack depth ");
12169 		for (i = 0; i < env->subprog_cnt; i++) {
12170 			u32 depth = env->subprog_info[i].stack_depth;
12171 
12172 			verbose(env, "%d", depth);
12173 			if (i + 1 < env->subprog_cnt)
12174 				verbose(env, "+");
12175 		}
12176 		verbose(env, "\n");
12177 	}
12178 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12179 		"total_states %d peak_states %d mark_read %d\n",
12180 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12181 		env->max_states_per_insn, env->total_states,
12182 		env->peak_states, env->longest_mark_read_walk);
12183 }
12184 
check_struct_ops_btf_id(struct bpf_verifier_env * env)12185 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12186 {
12187 	const struct btf_type *t, *func_proto;
12188 	const struct bpf_struct_ops *st_ops;
12189 	const struct btf_member *member;
12190 	struct bpf_prog *prog = env->prog;
12191 	u32 btf_id, member_idx;
12192 	const char *mname;
12193 
12194 	if (!prog->gpl_compatible) {
12195 		verbose(env, "struct ops programs must have a GPL compatible license\n");
12196 		return -EINVAL;
12197 	}
12198 
12199 	btf_id = prog->aux->attach_btf_id;
12200 	st_ops = bpf_struct_ops_find(btf_id);
12201 	if (!st_ops) {
12202 		verbose(env, "attach_btf_id %u is not a supported struct\n",
12203 			btf_id);
12204 		return -ENOTSUPP;
12205 	}
12206 
12207 	t = st_ops->type;
12208 	member_idx = prog->expected_attach_type;
12209 	if (member_idx >= btf_type_vlen(t)) {
12210 		verbose(env, "attach to invalid member idx %u of struct %s\n",
12211 			member_idx, st_ops->name);
12212 		return -EINVAL;
12213 	}
12214 
12215 	member = &btf_type_member(t)[member_idx];
12216 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12217 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12218 					       NULL);
12219 	if (!func_proto) {
12220 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12221 			mname, member_idx, st_ops->name);
12222 		return -EINVAL;
12223 	}
12224 
12225 	if (st_ops->check_member) {
12226 		int err = st_ops->check_member(t, member);
12227 
12228 		if (err) {
12229 			verbose(env, "attach to unsupported member %s of struct %s\n",
12230 				mname, st_ops->name);
12231 			return err;
12232 		}
12233 	}
12234 
12235 	prog->aux->attach_func_proto = func_proto;
12236 	prog->aux->attach_func_name = mname;
12237 	env->ops = st_ops->verifier_ops;
12238 
12239 	return 0;
12240 }
12241 #define SECURITY_PREFIX "security_"
12242 
check_attach_modify_return(unsigned long addr,const char * func_name)12243 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12244 {
12245 	if (within_error_injection_list(addr) ||
12246 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12247 		return 0;
12248 
12249 	return -EINVAL;
12250 }
12251 
12252 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12253 BTF_SET_START(btf_sleepable_lsm_hooks)
12254 #ifdef CONFIG_BPF_LSM
BTF_ID(func,bpf_lsm_bprm_committed_creds)12255 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12256 #else
12257 BTF_ID_UNUSED
12258 #endif
12259 BTF_SET_END(btf_sleepable_lsm_hooks)
12260 
12261 static int check_sleepable_lsm_hook(u32 btf_id)
12262 {
12263 	return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12264 }
12265 
12266 /* list of non-sleepable functions that are otherwise on
12267  * ALLOW_ERROR_INJECTION list
12268  */
12269 BTF_SET_START(btf_non_sleepable_error_inject)
12270 /* Three functions below can be called from sleepable and non-sleepable context.
12271  * Assume non-sleepable from bpf safety point of view.
12272  */
BTF_ID(func,__add_to_page_cache_locked)12273 BTF_ID(func, __add_to_page_cache_locked)
12274 BTF_ID(func, should_fail_alloc_page)
12275 BTF_ID(func, should_failslab)
12276 BTF_SET_END(btf_non_sleepable_error_inject)
12277 
12278 static int check_non_sleepable_error_inject(u32 btf_id)
12279 {
12280 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12281 }
12282 
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)12283 int bpf_check_attach_target(struct bpf_verifier_log *log,
12284 			    const struct bpf_prog *prog,
12285 			    const struct bpf_prog *tgt_prog,
12286 			    u32 btf_id,
12287 			    struct bpf_attach_target_info *tgt_info)
12288 {
12289 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12290 	const char prefix[] = "btf_trace_";
12291 	int ret = 0, subprog = -1, i;
12292 	const struct btf_type *t;
12293 	bool conservative = true;
12294 	const char *tname;
12295 	struct btf *btf;
12296 	long addr = 0;
12297 
12298 	if (!btf_id) {
12299 		bpf_log(log, "Tracing programs must provide btf_id\n");
12300 		return -EINVAL;
12301 	}
12302 	btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12303 	if (!btf) {
12304 		bpf_log(log,
12305 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12306 		return -EINVAL;
12307 	}
12308 	t = btf_type_by_id(btf, btf_id);
12309 	if (!t) {
12310 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12311 		return -EINVAL;
12312 	}
12313 	tname = btf_name_by_offset(btf, t->name_off);
12314 	if (!tname) {
12315 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12316 		return -EINVAL;
12317 	}
12318 	if (tgt_prog) {
12319 		struct bpf_prog_aux *aux = tgt_prog->aux;
12320 
12321 		for (i = 0; i < aux->func_info_cnt; i++)
12322 			if (aux->func_info[i].type_id == btf_id) {
12323 				subprog = i;
12324 				break;
12325 			}
12326 		if (subprog == -1) {
12327 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12328 			return -EINVAL;
12329 		}
12330 		conservative = aux->func_info_aux[subprog].unreliable;
12331 		if (prog_extension) {
12332 			if (conservative) {
12333 				bpf_log(log,
12334 					"Cannot replace static functions\n");
12335 				return -EINVAL;
12336 			}
12337 			if (!prog->jit_requested) {
12338 				bpf_log(log,
12339 					"Extension programs should be JITed\n");
12340 				return -EINVAL;
12341 			}
12342 		}
12343 		if (!tgt_prog->jited) {
12344 			bpf_log(log, "Can attach to only JITed progs\n");
12345 			return -EINVAL;
12346 		}
12347 		if (tgt_prog->type == prog->type) {
12348 			/* Cannot fentry/fexit another fentry/fexit program.
12349 			 * Cannot attach program extension to another extension.
12350 			 * It's ok to attach fentry/fexit to extension program.
12351 			 */
12352 			bpf_log(log, "Cannot recursively attach\n");
12353 			return -EINVAL;
12354 		}
12355 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12356 		    prog_extension &&
12357 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12358 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12359 			/* Program extensions can extend all program types
12360 			 * except fentry/fexit. The reason is the following.
12361 			 * The fentry/fexit programs are used for performance
12362 			 * analysis, stats and can be attached to any program
12363 			 * type except themselves. When extension program is
12364 			 * replacing XDP function it is necessary to allow
12365 			 * performance analysis of all functions. Both original
12366 			 * XDP program and its program extension. Hence
12367 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12368 			 * allowed. If extending of fentry/fexit was allowed it
12369 			 * would be possible to create long call chain
12370 			 * fentry->extension->fentry->extension beyond
12371 			 * reasonable stack size. Hence extending fentry is not
12372 			 * allowed.
12373 			 */
12374 			bpf_log(log, "Cannot extend fentry/fexit\n");
12375 			return -EINVAL;
12376 		}
12377 	} else {
12378 		if (prog_extension) {
12379 			bpf_log(log, "Cannot replace kernel functions\n");
12380 			return -EINVAL;
12381 		}
12382 	}
12383 
12384 	switch (prog->expected_attach_type) {
12385 	case BPF_TRACE_RAW_TP:
12386 		if (tgt_prog) {
12387 			bpf_log(log,
12388 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12389 			return -EINVAL;
12390 		}
12391 		if (!btf_type_is_typedef(t)) {
12392 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12393 				btf_id);
12394 			return -EINVAL;
12395 		}
12396 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12397 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12398 				btf_id, tname);
12399 			return -EINVAL;
12400 		}
12401 		tname += sizeof(prefix) - 1;
12402 		t = btf_type_by_id(btf, t->type);
12403 		if (!btf_type_is_ptr(t))
12404 			/* should never happen in valid vmlinux build */
12405 			return -EINVAL;
12406 		t = btf_type_by_id(btf, t->type);
12407 		if (!btf_type_is_func_proto(t))
12408 			/* should never happen in valid vmlinux build */
12409 			return -EINVAL;
12410 
12411 		break;
12412 	case BPF_TRACE_ITER:
12413 		if (!btf_type_is_func(t)) {
12414 			bpf_log(log, "attach_btf_id %u is not a function\n",
12415 				btf_id);
12416 			return -EINVAL;
12417 		}
12418 		t = btf_type_by_id(btf, t->type);
12419 		if (!btf_type_is_func_proto(t))
12420 			return -EINVAL;
12421 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12422 		if (ret)
12423 			return ret;
12424 		break;
12425 	default:
12426 		if (!prog_extension)
12427 			return -EINVAL;
12428 		fallthrough;
12429 	case BPF_MODIFY_RETURN:
12430 	case BPF_LSM_MAC:
12431 	case BPF_TRACE_FENTRY:
12432 	case BPF_TRACE_FEXIT:
12433 		if (!btf_type_is_func(t)) {
12434 			bpf_log(log, "attach_btf_id %u is not a function\n",
12435 				btf_id);
12436 			return -EINVAL;
12437 		}
12438 		if (prog_extension &&
12439 		    btf_check_type_match(log, prog, btf, t))
12440 			return -EINVAL;
12441 		t = btf_type_by_id(btf, t->type);
12442 		if (!btf_type_is_func_proto(t))
12443 			return -EINVAL;
12444 
12445 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12446 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12447 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12448 			return -EINVAL;
12449 
12450 		if (tgt_prog && conservative)
12451 			t = NULL;
12452 
12453 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12454 		if (ret < 0)
12455 			return ret;
12456 
12457 		if (tgt_prog) {
12458 			if (subprog == 0)
12459 				addr = (long) tgt_prog->bpf_func;
12460 			else
12461 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12462 		} else {
12463 			addr = kallsyms_lookup_name(tname);
12464 			if (!addr) {
12465 				bpf_log(log,
12466 					"The address of function %s cannot be found\n",
12467 					tname);
12468 				return -ENOENT;
12469 			}
12470 		}
12471 
12472 		if (prog->aux->sleepable) {
12473 			ret = -EINVAL;
12474 			switch (prog->type) {
12475 			case BPF_PROG_TYPE_TRACING:
12476 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12477 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12478 				 */
12479 				if (!check_non_sleepable_error_inject(btf_id) &&
12480 				    within_error_injection_list(addr))
12481 					ret = 0;
12482 				break;
12483 			case BPF_PROG_TYPE_LSM:
12484 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
12485 				 * Only some of them are sleepable.
12486 				 */
12487 				if (check_sleepable_lsm_hook(btf_id))
12488 					ret = 0;
12489 				break;
12490 			default:
12491 				break;
12492 			}
12493 			if (ret) {
12494 				bpf_log(log, "%s is not sleepable\n", tname);
12495 				return ret;
12496 			}
12497 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12498 			if (tgt_prog) {
12499 				bpf_log(log, "can't modify return codes of BPF programs\n");
12500 				return -EINVAL;
12501 			}
12502 			ret = check_attach_modify_return(addr, tname);
12503 			if (ret) {
12504 				bpf_log(log, "%s() is not modifiable\n", tname);
12505 				return ret;
12506 			}
12507 		}
12508 
12509 		break;
12510 	}
12511 	tgt_info->tgt_addr = addr;
12512 	tgt_info->tgt_name = tname;
12513 	tgt_info->tgt_type = t;
12514 	return 0;
12515 }
12516 
check_attach_btf_id(struct bpf_verifier_env * env)12517 static int check_attach_btf_id(struct bpf_verifier_env *env)
12518 {
12519 	struct bpf_prog *prog = env->prog;
12520 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12521 	struct bpf_attach_target_info tgt_info = {};
12522 	u32 btf_id = prog->aux->attach_btf_id;
12523 	struct bpf_trampoline *tr;
12524 	int ret;
12525 	u64 key;
12526 
12527 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12528 	    prog->type != BPF_PROG_TYPE_LSM) {
12529 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12530 		return -EINVAL;
12531 	}
12532 
12533 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12534 		return check_struct_ops_btf_id(env);
12535 
12536 	if (prog->type != BPF_PROG_TYPE_TRACING &&
12537 	    prog->type != BPF_PROG_TYPE_LSM &&
12538 	    prog->type != BPF_PROG_TYPE_EXT)
12539 		return 0;
12540 
12541 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12542 	if (ret)
12543 		return ret;
12544 
12545 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12546 		/* to make freplace equivalent to their targets, they need to
12547 		 * inherit env->ops and expected_attach_type for the rest of the
12548 		 * verification
12549 		 */
12550 		env->ops = bpf_verifier_ops[tgt_prog->type];
12551 		prog->expected_attach_type = tgt_prog->expected_attach_type;
12552 	}
12553 
12554 	/* store info about the attachment target that will be used later */
12555 	prog->aux->attach_func_proto = tgt_info.tgt_type;
12556 	prog->aux->attach_func_name = tgt_info.tgt_name;
12557 
12558 	if (tgt_prog) {
12559 		prog->aux->saved_dst_prog_type = tgt_prog->type;
12560 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12561 	}
12562 
12563 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12564 		prog->aux->attach_btf_trace = true;
12565 		return 0;
12566 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12567 		if (!bpf_iter_prog_supported(prog))
12568 			return -EINVAL;
12569 		return 0;
12570 	}
12571 
12572 	if (prog->type == BPF_PROG_TYPE_LSM) {
12573 		ret = bpf_lsm_verify_prog(&env->log, prog);
12574 		if (ret < 0)
12575 			return ret;
12576 	}
12577 
12578 	key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12579 	tr = bpf_trampoline_get(key, &tgt_info);
12580 	if (!tr)
12581 		return -ENOMEM;
12582 
12583 	prog->aux->dst_trampoline = tr;
12584 	return 0;
12585 }
12586 
bpf_get_btf_vmlinux(void)12587 struct btf *bpf_get_btf_vmlinux(void)
12588 {
12589 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12590 		mutex_lock(&bpf_verifier_lock);
12591 		if (!btf_vmlinux)
12592 			btf_vmlinux = btf_parse_vmlinux();
12593 		mutex_unlock(&bpf_verifier_lock);
12594 	}
12595 	return btf_vmlinux;
12596 }
12597 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)12598 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12599 	      union bpf_attr __user *uattr)
12600 {
12601 	u64 start_time = ktime_get_ns();
12602 	struct bpf_verifier_env *env;
12603 	struct bpf_verifier_log *log;
12604 	int i, len, ret = -EINVAL;
12605 	bool is_priv;
12606 
12607 	/* no program is valid */
12608 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12609 		return -EINVAL;
12610 
12611 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
12612 	 * allocate/free it every time bpf_check() is called
12613 	 */
12614 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12615 	if (!env)
12616 		return -ENOMEM;
12617 	log = &env->log;
12618 
12619 	len = (*prog)->len;
12620 	env->insn_aux_data =
12621 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12622 	ret = -ENOMEM;
12623 	if (!env->insn_aux_data)
12624 		goto err_free_env;
12625 	for (i = 0; i < len; i++)
12626 		env->insn_aux_data[i].orig_idx = i;
12627 	env->prog = *prog;
12628 	env->ops = bpf_verifier_ops[env->prog->type];
12629 	is_priv = bpf_capable();
12630 
12631 	bpf_get_btf_vmlinux();
12632 
12633 	/* grab the mutex to protect few globals used by verifier */
12634 	if (!is_priv)
12635 		mutex_lock(&bpf_verifier_lock);
12636 
12637 	if (attr->log_level || attr->log_buf || attr->log_size) {
12638 		/* user requested verbose verifier output
12639 		 * and supplied buffer to store the verification trace
12640 		 */
12641 		log->level = attr->log_level;
12642 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12643 		log->len_total = attr->log_size;
12644 
12645 		/* log attributes have to be sane */
12646 		if (!bpf_verifier_log_attr_valid(log)) {
12647 			ret = -EINVAL;
12648 			goto err_unlock;
12649 		}
12650 	}
12651 
12652 	if (IS_ERR(btf_vmlinux)) {
12653 		/* Either gcc or pahole or kernel are broken. */
12654 		verbose(env, "in-kernel BTF is malformed\n");
12655 		ret = PTR_ERR(btf_vmlinux);
12656 		goto skip_full_check;
12657 	}
12658 
12659 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12660 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12661 		env->strict_alignment = true;
12662 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12663 		env->strict_alignment = false;
12664 
12665 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12666 	env->allow_uninit_stack = bpf_allow_uninit_stack();
12667 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12668 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
12669 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
12670 	env->bpf_capable = bpf_capable();
12671 
12672 	if (is_priv)
12673 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12674 
12675 	env->explored_states = kvcalloc(state_htab_size(env),
12676 				       sizeof(struct bpf_verifier_state_list *),
12677 				       GFP_USER);
12678 	ret = -ENOMEM;
12679 	if (!env->explored_states)
12680 		goto skip_full_check;
12681 
12682 	ret = check_subprogs(env);
12683 	if (ret < 0)
12684 		goto skip_full_check;
12685 
12686 	ret = check_btf_info(env, attr, uattr);
12687 	if (ret < 0)
12688 		goto skip_full_check;
12689 
12690 	ret = check_attach_btf_id(env);
12691 	if (ret)
12692 		goto skip_full_check;
12693 
12694 	ret = resolve_pseudo_ldimm64(env);
12695 	if (ret < 0)
12696 		goto skip_full_check;
12697 
12698 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
12699 		ret = bpf_prog_offload_verifier_prep(env->prog);
12700 		if (ret)
12701 			goto skip_full_check;
12702 	}
12703 
12704 	ret = check_cfg(env);
12705 	if (ret < 0)
12706 		goto skip_full_check;
12707 
12708 	ret = do_check_subprogs(env);
12709 	ret = ret ?: do_check_main(env);
12710 
12711 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12712 		ret = bpf_prog_offload_finalize(env);
12713 
12714 skip_full_check:
12715 	kvfree(env->explored_states);
12716 
12717 	if (ret == 0)
12718 		ret = check_max_stack_depth(env);
12719 
12720 	/* instruction rewrites happen after this point */
12721 	if (is_priv) {
12722 		if (ret == 0)
12723 			opt_hard_wire_dead_code_branches(env);
12724 		if (ret == 0)
12725 			ret = opt_remove_dead_code(env);
12726 		if (ret == 0)
12727 			ret = opt_remove_nops(env);
12728 	} else {
12729 		if (ret == 0)
12730 			sanitize_dead_code(env);
12731 	}
12732 
12733 	if (ret == 0)
12734 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12735 		ret = convert_ctx_accesses(env);
12736 
12737 	if (ret == 0)
12738 		ret = fixup_bpf_calls(env);
12739 
12740 	/* do 32-bit optimization after insn patching has done so those patched
12741 	 * insns could be handled correctly.
12742 	 */
12743 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12744 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12745 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12746 								     : false;
12747 	}
12748 
12749 	if (ret == 0)
12750 		ret = fixup_call_args(env);
12751 
12752 	env->verification_time = ktime_get_ns() - start_time;
12753 	print_verification_stats(env);
12754 
12755 	if (log->level && bpf_verifier_log_full(log))
12756 		ret = -ENOSPC;
12757 	if (log->level && !log->ubuf) {
12758 		ret = -EFAULT;
12759 		goto err_release_maps;
12760 	}
12761 
12762 	if (ret == 0 && env->used_map_cnt) {
12763 		/* if program passed verifier, update used_maps in bpf_prog_info */
12764 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12765 							  sizeof(env->used_maps[0]),
12766 							  GFP_KERNEL);
12767 
12768 		if (!env->prog->aux->used_maps) {
12769 			ret = -ENOMEM;
12770 			goto err_release_maps;
12771 		}
12772 
12773 		memcpy(env->prog->aux->used_maps, env->used_maps,
12774 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12775 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12776 
12777 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12778 		 * bpf_ld_imm64 instructions
12779 		 */
12780 		convert_pseudo_ld_imm64(env);
12781 	}
12782 
12783 	if (ret == 0)
12784 		adjust_btf_func(env);
12785 
12786 err_release_maps:
12787 	if (!env->prog->aux->used_maps)
12788 		/* if we didn't copy map pointers into bpf_prog_info, release
12789 		 * them now. Otherwise free_used_maps() will release them.
12790 		 */
12791 		release_maps(env);
12792 
12793 	/* extension progs temporarily inherit the attach_type of their targets
12794 	   for verification purposes, so set it back to zero before returning
12795 	 */
12796 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12797 		env->prog->expected_attach_type = 0;
12798 
12799 	*prog = env->prog;
12800 err_unlock:
12801 	if (!is_priv)
12802 		mutex_unlock(&bpf_verifier_lock);
12803 	vfree(env->insn_aux_data);
12804 err_free_env:
12805 	kfree(env);
12806 	return ret;
12807 }
12808