• 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 
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)576 static void print_verifier_state(struct bpf_verifier_env *env,
577 				 const struct bpf_func_state *state)
578 {
579 	const struct bpf_reg_state *reg;
580 	enum bpf_reg_type t;
581 	int i;
582 
583 	if (state->frameno)
584 		verbose(env, " frame%d:", state->frameno);
585 	for (i = 0; i < MAX_BPF_REG; i++) {
586 		reg = &state->regs[i];
587 		t = reg->type;
588 		if (t == NOT_INIT)
589 			continue;
590 		verbose(env, " R%d", i);
591 		print_liveness(env, reg->live);
592 		verbose(env, "=%s", reg_type_str(env, t));
593 		if (t == SCALAR_VALUE && reg->precise)
594 			verbose(env, "P");
595 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
596 		    tnum_is_const(reg->var_off)) {
597 			/* reg->off should be 0 for SCALAR_VALUE */
598 			verbose(env, "%lld", reg->var_off.value + reg->off);
599 		} else {
600 			if (base_type(t) == PTR_TO_BTF_ID ||
601 			    base_type(t) == PTR_TO_PERCPU_BTF_ID)
602 				verbose(env, "%s", kernel_type_name(reg->btf_id));
603 			verbose(env, "(id=%d", reg->id);
604 			if (reg_type_may_be_refcounted_or_null(t))
605 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
606 			if (t != SCALAR_VALUE)
607 				verbose(env, ",off=%d", reg->off);
608 			if (type_is_pkt_pointer(t))
609 				verbose(env, ",r=%d", reg->range);
610 			else if (base_type(t) == CONST_PTR_TO_MAP ||
611 				 base_type(t) == PTR_TO_MAP_VALUE)
612 				verbose(env, ",ks=%d,vs=%d",
613 					reg->map_ptr->key_size,
614 					reg->map_ptr->value_size);
615 			if (tnum_is_const(reg->var_off)) {
616 				/* Typically an immediate SCALAR_VALUE, but
617 				 * could be a pointer whose offset is too big
618 				 * for reg->off
619 				 */
620 				verbose(env, ",imm=%llx", reg->var_off.value);
621 			} else {
622 				if (reg->smin_value != reg->umin_value &&
623 				    reg->smin_value != S64_MIN)
624 					verbose(env, ",smin_value=%lld",
625 						(long long)reg->smin_value);
626 				if (reg->smax_value != reg->umax_value &&
627 				    reg->smax_value != S64_MAX)
628 					verbose(env, ",smax_value=%lld",
629 						(long long)reg->smax_value);
630 				if (reg->umin_value != 0)
631 					verbose(env, ",umin_value=%llu",
632 						(unsigned long long)reg->umin_value);
633 				if (reg->umax_value != U64_MAX)
634 					verbose(env, ",umax_value=%llu",
635 						(unsigned long long)reg->umax_value);
636 				if (!tnum_is_unknown(reg->var_off)) {
637 					char tn_buf[48];
638 
639 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
640 					verbose(env, ",var_off=%s", tn_buf);
641 				}
642 				if (reg->s32_min_value != reg->smin_value &&
643 				    reg->s32_min_value != S32_MIN)
644 					verbose(env, ",s32_min_value=%d",
645 						(int)(reg->s32_min_value));
646 				if (reg->s32_max_value != reg->smax_value &&
647 				    reg->s32_max_value != S32_MAX)
648 					verbose(env, ",s32_max_value=%d",
649 						(int)(reg->s32_max_value));
650 				if (reg->u32_min_value != reg->umin_value &&
651 				    reg->u32_min_value != U32_MIN)
652 					verbose(env, ",u32_min_value=%d",
653 						(int)(reg->u32_min_value));
654 				if (reg->u32_max_value != reg->umax_value &&
655 				    reg->u32_max_value != U32_MAX)
656 					verbose(env, ",u32_max_value=%d",
657 						(int)(reg->u32_max_value));
658 			}
659 			verbose(env, ")");
660 		}
661 	}
662 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
663 		char types_buf[BPF_REG_SIZE + 1];
664 		bool valid = false;
665 		int j;
666 
667 		for (j = 0; j < BPF_REG_SIZE; j++) {
668 			if (state->stack[i].slot_type[j] != STACK_INVALID)
669 				valid = true;
670 			types_buf[j] = slot_type_char[
671 					state->stack[i].slot_type[j]];
672 		}
673 		types_buf[BPF_REG_SIZE] = 0;
674 		if (!valid)
675 			continue;
676 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
677 		print_liveness(env, state->stack[i].spilled_ptr.live);
678 		if (is_spilled_reg(&state->stack[i])) {
679 			reg = &state->stack[i].spilled_ptr;
680 			t = reg->type;
681 			verbose(env, "=%s", reg_type_str(env, t));
682 			if (t == SCALAR_VALUE && reg->precise)
683 				verbose(env, "P");
684 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
685 				verbose(env, "%lld", reg->var_off.value + reg->off);
686 		} else {
687 			verbose(env, "=%s", types_buf);
688 		}
689 	}
690 	if (state->acquired_refs && state->refs[0].id) {
691 		verbose(env, " refs=%d", state->refs[0].id);
692 		for (i = 1; i < state->acquired_refs; i++)
693 			if (state->refs[i].id)
694 				verbose(env, ",%d", state->refs[i].id);
695 	}
696 	verbose(env, "\n");
697 }
698 
699 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
700 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
701 			       const struct bpf_func_state *src)	\
702 {									\
703 	if (!src->FIELD)						\
704 		return 0;						\
705 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
706 		/* internal bug, make state invalid to reject the program */ \
707 		memset(dst, 0, sizeof(*dst));				\
708 		return -EFAULT;						\
709 	}								\
710 	memcpy(dst->FIELD, src->FIELD,					\
711 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
712 	return 0;							\
713 }
714 /* copy_reference_state() */
715 COPY_STATE_FN(reference, acquired_refs, refs, 1)
716 /* copy_stack_state() */
COPY_STATE_FN(stack,allocated_stack,stack,BPF_REG_SIZE)717 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
718 #undef COPY_STATE_FN
719 
720 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
721 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
722 				  bool copy_old)			\
723 {									\
724 	u32 old_size = state->COUNT;					\
725 	struct bpf_##NAME##_state *new_##FIELD;				\
726 	int slot = size / SIZE;						\
727 									\
728 	if (size <= old_size || !size) {				\
729 		if (copy_old)						\
730 			return 0;					\
731 		state->COUNT = slot * SIZE;				\
732 		if (!size && old_size) {				\
733 			kfree(state->FIELD);				\
734 			state->FIELD = NULL;				\
735 		}							\
736 		return 0;						\
737 	}								\
738 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
739 				    GFP_KERNEL);			\
740 	if (!new_##FIELD)						\
741 		return -ENOMEM;						\
742 	if (copy_old) {							\
743 		if (state->FIELD)					\
744 			memcpy(new_##FIELD, state->FIELD,		\
745 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
746 		memset(new_##FIELD + old_size / SIZE, 0,		\
747 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
748 	}								\
749 	state->COUNT = slot * SIZE;					\
750 	kfree(state->FIELD);						\
751 	state->FIELD = new_##FIELD;					\
752 	return 0;							\
753 }
754 /* realloc_reference_state() */
755 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
756 /* realloc_stack_state() */
757 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
758 #undef REALLOC_STATE_FN
759 
760 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
761  * make it consume minimal amount of memory. check_stack_write() access from
762  * the program calls into realloc_func_state() to grow the stack size.
763  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
764  * which realloc_stack_state() copies over. It points to previous
765  * bpf_verifier_state which is never reallocated.
766  */
767 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
768 			      int refs_size, bool copy_old)
769 {
770 	int err = realloc_reference_state(state, refs_size, copy_old);
771 	if (err)
772 		return err;
773 	return realloc_stack_state(state, stack_size, copy_old);
774 }
775 
776 /* Acquire a pointer id from the env and update the state->refs to include
777  * this new pointer reference.
778  * On success, returns a valid pointer id to associate with the register
779  * On failure, returns a negative errno.
780  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)781 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
782 {
783 	struct bpf_func_state *state = cur_func(env);
784 	int new_ofs = state->acquired_refs;
785 	int id, err;
786 
787 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
788 	if (err)
789 		return err;
790 	id = ++env->id_gen;
791 	state->refs[new_ofs].id = id;
792 	state->refs[new_ofs].insn_idx = insn_idx;
793 
794 	return id;
795 }
796 
797 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)798 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
799 {
800 	int i, last_idx;
801 
802 	last_idx = state->acquired_refs - 1;
803 	for (i = 0; i < state->acquired_refs; i++) {
804 		if (state->refs[i].id == ptr_id) {
805 			if (last_idx && i != last_idx)
806 				memcpy(&state->refs[i], &state->refs[last_idx],
807 				       sizeof(*state->refs));
808 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
809 			state->acquired_refs--;
810 			return 0;
811 		}
812 	}
813 	return -EINVAL;
814 }
815 
transfer_reference_state(struct bpf_func_state * dst,struct bpf_func_state * src)816 static int transfer_reference_state(struct bpf_func_state *dst,
817 				    struct bpf_func_state *src)
818 {
819 	int err = realloc_reference_state(dst, src->acquired_refs, false);
820 	if (err)
821 		return err;
822 	err = copy_reference_state(dst, src);
823 	if (err)
824 		return err;
825 	return 0;
826 }
827 
free_func_state(struct bpf_func_state * state)828 static void free_func_state(struct bpf_func_state *state)
829 {
830 	if (!state)
831 		return;
832 	kfree(state->refs);
833 	kfree(state->stack);
834 	kfree(state);
835 }
836 
clear_jmp_history(struct bpf_verifier_state * state)837 static void clear_jmp_history(struct bpf_verifier_state *state)
838 {
839 	kfree(state->jmp_history);
840 	state->jmp_history = NULL;
841 	state->jmp_history_cnt = 0;
842 }
843 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)844 static void free_verifier_state(struct bpf_verifier_state *state,
845 				bool free_self)
846 {
847 	int i;
848 
849 	for (i = 0; i <= state->curframe; i++) {
850 		free_func_state(state->frame[i]);
851 		state->frame[i] = NULL;
852 	}
853 	clear_jmp_history(state);
854 	if (free_self)
855 		kfree(state);
856 }
857 
858 /* copy verifier state from src to dst growing dst stack space
859  * when necessary to accommodate larger src stack
860  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)861 static int copy_func_state(struct bpf_func_state *dst,
862 			   const struct bpf_func_state *src)
863 {
864 	int err;
865 
866 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
867 				 false);
868 	if (err)
869 		return err;
870 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
871 	err = copy_reference_state(dst, src);
872 	if (err)
873 		return err;
874 	return copy_stack_state(dst, src);
875 }
876 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)877 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
878 			       const struct bpf_verifier_state *src)
879 {
880 	struct bpf_func_state *dst;
881 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
882 	int i, err;
883 
884 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
885 		kfree(dst_state->jmp_history);
886 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
887 		if (!dst_state->jmp_history)
888 			return -ENOMEM;
889 	}
890 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
891 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
892 
893 	/* if dst has more stack frames then src frame, free them */
894 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
895 		free_func_state(dst_state->frame[i]);
896 		dst_state->frame[i] = NULL;
897 	}
898 	dst_state->speculative = src->speculative;
899 	dst_state->curframe = src->curframe;
900 	dst_state->active_spin_lock = src->active_spin_lock;
901 	dst_state->branches = src->branches;
902 	dst_state->parent = src->parent;
903 	dst_state->first_insn_idx = src->first_insn_idx;
904 	dst_state->last_insn_idx = src->last_insn_idx;
905 	for (i = 0; i <= src->curframe; i++) {
906 		dst = dst_state->frame[i];
907 		if (!dst) {
908 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
909 			if (!dst)
910 				return -ENOMEM;
911 			dst_state->frame[i] = dst;
912 		}
913 		err = copy_func_state(dst, src->frame[i]);
914 		if (err)
915 			return err;
916 	}
917 	return 0;
918 }
919 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)920 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
921 {
922 	while (st) {
923 		u32 br = --st->branches;
924 
925 		/* WARN_ON(br > 1) technically makes sense here,
926 		 * but see comment in push_stack(), hence:
927 		 */
928 		WARN_ONCE((int)br < 0,
929 			  "BUG update_branch_counts:branches_to_explore=%d\n",
930 			  br);
931 		if (br)
932 			break;
933 		st = st->parent;
934 	}
935 }
936 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)937 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
938 		     int *insn_idx, bool pop_log)
939 {
940 	struct bpf_verifier_state *cur = env->cur_state;
941 	struct bpf_verifier_stack_elem *elem, *head = env->head;
942 	int err;
943 
944 	if (env->head == NULL)
945 		return -ENOENT;
946 
947 	if (cur) {
948 		err = copy_verifier_state(cur, &head->st);
949 		if (err)
950 			return err;
951 	}
952 	if (pop_log)
953 		bpf_vlog_reset(&env->log, head->log_pos);
954 	if (insn_idx)
955 		*insn_idx = head->insn_idx;
956 	if (prev_insn_idx)
957 		*prev_insn_idx = head->prev_insn_idx;
958 	elem = head->next;
959 	free_verifier_state(&head->st, false);
960 	kfree(head);
961 	env->head = elem;
962 	env->stack_size--;
963 	return 0;
964 }
965 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)966 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
967 					     int insn_idx, int prev_insn_idx,
968 					     bool speculative)
969 {
970 	struct bpf_verifier_state *cur = env->cur_state;
971 	struct bpf_verifier_stack_elem *elem;
972 	int err;
973 
974 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
975 	if (!elem)
976 		goto err;
977 
978 	elem->insn_idx = insn_idx;
979 	elem->prev_insn_idx = prev_insn_idx;
980 	elem->next = env->head;
981 	elem->log_pos = env->log.len_used;
982 	env->head = elem;
983 	env->stack_size++;
984 	err = copy_verifier_state(&elem->st, cur);
985 	if (err)
986 		goto err;
987 	elem->st.speculative |= speculative;
988 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
989 		verbose(env, "The sequence of %d jumps is too complex.\n",
990 			env->stack_size);
991 		goto err;
992 	}
993 	if (elem->st.parent) {
994 		++elem->st.parent->branches;
995 		/* WARN_ON(branches > 2) technically makes sense here,
996 		 * but
997 		 * 1. speculative states will bump 'branches' for non-branch
998 		 * instructions
999 		 * 2. is_state_visited() heuristics may decide not to create
1000 		 * a new state for a sequence of branches and all such current
1001 		 * and cloned states will be pointing to a single parent state
1002 		 * which might have large 'branches' count.
1003 		 */
1004 	}
1005 	return &elem->st;
1006 err:
1007 	free_verifier_state(env->cur_state, true);
1008 	env->cur_state = NULL;
1009 	/* pop all elements and return */
1010 	while (!pop_stack(env, NULL, NULL, false));
1011 	return NULL;
1012 }
1013 
1014 #define CALLER_SAVED_REGS 6
1015 static const int caller_saved[CALLER_SAVED_REGS] = {
1016 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1017 };
1018 
1019 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1020 				struct bpf_reg_state *reg);
1021 
1022 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1023 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1024 {
1025 	reg->var_off = tnum_const(imm);
1026 	reg->smin_value = (s64)imm;
1027 	reg->smax_value = (s64)imm;
1028 	reg->umin_value = imm;
1029 	reg->umax_value = imm;
1030 
1031 	reg->s32_min_value = (s32)imm;
1032 	reg->s32_max_value = (s32)imm;
1033 	reg->u32_min_value = (u32)imm;
1034 	reg->u32_max_value = (u32)imm;
1035 }
1036 
1037 /* Mark the unknown part of a register (variable offset or scalar value) as
1038  * known to have the value @imm.
1039  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1040 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1041 {
1042 	/* Clear id, off, and union(map_ptr, range) */
1043 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1044 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1045 	___mark_reg_known(reg, imm);
1046 }
1047 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1048 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1049 {
1050 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1051 	reg->s32_min_value = (s32)imm;
1052 	reg->s32_max_value = (s32)imm;
1053 	reg->u32_min_value = (u32)imm;
1054 	reg->u32_max_value = (u32)imm;
1055 }
1056 
1057 /* Mark the 'variable offset' part of a register as zero.  This should be
1058  * used only on registers holding a pointer type.
1059  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1060 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1061 {
1062 	__mark_reg_known(reg, 0);
1063 }
1064 
__mark_reg_const_zero(struct bpf_reg_state * reg)1065 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1066 {
1067 	__mark_reg_known(reg, 0);
1068 	reg->type = SCALAR_VALUE;
1069 }
1070 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1071 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1072 				struct bpf_reg_state *regs, u32 regno)
1073 {
1074 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1075 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1076 		/* Something bad happened, let's kill all regs */
1077 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1078 			__mark_reg_not_init(env, regs + regno);
1079 		return;
1080 	}
1081 	__mark_reg_known_zero(regs + regno);
1082 }
1083 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1084 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1085 {
1086 	return type_is_pkt_pointer(reg->type);
1087 }
1088 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1089 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1090 {
1091 	return reg_is_pkt_pointer(reg) ||
1092 	       reg->type == PTR_TO_PACKET_END;
1093 }
1094 
1095 /* 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)1096 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1097 				    enum bpf_reg_type which)
1098 {
1099 	/* The register can already have a range from prior markings.
1100 	 * This is fine as long as it hasn't been advanced from its
1101 	 * origin.
1102 	 */
1103 	return reg->type == which &&
1104 	       reg->id == 0 &&
1105 	       reg->off == 0 &&
1106 	       tnum_equals_const(reg->var_off, 0);
1107 }
1108 
1109 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1110 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1111 {
1112 	reg->smin_value = S64_MIN;
1113 	reg->smax_value = S64_MAX;
1114 	reg->umin_value = 0;
1115 	reg->umax_value = U64_MAX;
1116 
1117 	reg->s32_min_value = S32_MIN;
1118 	reg->s32_max_value = S32_MAX;
1119 	reg->u32_min_value = 0;
1120 	reg->u32_max_value = U32_MAX;
1121 }
1122 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1123 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1124 {
1125 	reg->smin_value = S64_MIN;
1126 	reg->smax_value = S64_MAX;
1127 	reg->umin_value = 0;
1128 	reg->umax_value = U64_MAX;
1129 }
1130 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1131 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1132 {
1133 	reg->s32_min_value = S32_MIN;
1134 	reg->s32_max_value = S32_MAX;
1135 	reg->u32_min_value = 0;
1136 	reg->u32_max_value = U32_MAX;
1137 }
1138 
__update_reg32_bounds(struct bpf_reg_state * reg)1139 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1140 {
1141 	struct tnum var32_off = tnum_subreg(reg->var_off);
1142 
1143 	/* min signed is max(sign bit) | min(other bits) */
1144 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1145 			var32_off.value | (var32_off.mask & S32_MIN));
1146 	/* max signed is min(sign bit) | max(other bits) */
1147 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1148 			var32_off.value | (var32_off.mask & S32_MAX));
1149 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1150 	reg->u32_max_value = min(reg->u32_max_value,
1151 				 (u32)(var32_off.value | var32_off.mask));
1152 }
1153 
__update_reg64_bounds(struct bpf_reg_state * reg)1154 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1155 {
1156 	/* min signed is max(sign bit) | min(other bits) */
1157 	reg->smin_value = max_t(s64, reg->smin_value,
1158 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1159 	/* max signed is min(sign bit) | max(other bits) */
1160 	reg->smax_value = min_t(s64, reg->smax_value,
1161 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1162 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1163 	reg->umax_value = min(reg->umax_value,
1164 			      reg->var_off.value | reg->var_off.mask);
1165 }
1166 
__update_reg_bounds(struct bpf_reg_state * reg)1167 static void __update_reg_bounds(struct bpf_reg_state *reg)
1168 {
1169 	__update_reg32_bounds(reg);
1170 	__update_reg64_bounds(reg);
1171 }
1172 
1173 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1174 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1175 {
1176 	/* Learn sign from signed bounds.
1177 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1178 	 * are the same, so combine.  This works even in the negative case, e.g.
1179 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1180 	 */
1181 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1182 		reg->s32_min_value = reg->u32_min_value =
1183 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1184 		reg->s32_max_value = reg->u32_max_value =
1185 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1186 		return;
1187 	}
1188 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1189 	 * boundary, so we must be careful.
1190 	 */
1191 	if ((s32)reg->u32_max_value >= 0) {
1192 		/* Positive.  We can't learn anything from the smin, but smax
1193 		 * is positive, hence safe.
1194 		 */
1195 		reg->s32_min_value = reg->u32_min_value;
1196 		reg->s32_max_value = reg->u32_max_value =
1197 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1198 	} else if ((s32)reg->u32_min_value < 0) {
1199 		/* Negative.  We can't learn anything from the smax, but smin
1200 		 * is negative, hence safe.
1201 		 */
1202 		reg->s32_min_value = reg->u32_min_value =
1203 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1204 		reg->s32_max_value = reg->u32_max_value;
1205 	}
1206 }
1207 
__reg64_deduce_bounds(struct bpf_reg_state * reg)1208 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1209 {
1210 	/* Learn sign from signed bounds.
1211 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1212 	 * are the same, so combine.  This works even in the negative case, e.g.
1213 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1214 	 */
1215 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1216 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1217 							  reg->umin_value);
1218 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1219 							  reg->umax_value);
1220 		return;
1221 	}
1222 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1223 	 * boundary, so we must be careful.
1224 	 */
1225 	if ((s64)reg->umax_value >= 0) {
1226 		/* Positive.  We can't learn anything from the smin, but smax
1227 		 * is positive, hence safe.
1228 		 */
1229 		reg->smin_value = reg->umin_value;
1230 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1231 							  reg->umax_value);
1232 	} else if ((s64)reg->umin_value < 0) {
1233 		/* Negative.  We can't learn anything from the smax, but smin
1234 		 * is negative, hence safe.
1235 		 */
1236 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1237 							  reg->umin_value);
1238 		reg->smax_value = reg->umax_value;
1239 	}
1240 }
1241 
__reg_deduce_bounds(struct bpf_reg_state * reg)1242 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1243 {
1244 	__reg32_deduce_bounds(reg);
1245 	__reg64_deduce_bounds(reg);
1246 }
1247 
1248 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1249 static void __reg_bound_offset(struct bpf_reg_state *reg)
1250 {
1251 	struct tnum var64_off = tnum_intersect(reg->var_off,
1252 					       tnum_range(reg->umin_value,
1253 							  reg->umax_value));
1254 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1255 						tnum_range(reg->u32_min_value,
1256 							   reg->u32_max_value));
1257 
1258 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1259 }
1260 
reg_bounds_sync(struct bpf_reg_state * reg)1261 static void reg_bounds_sync(struct bpf_reg_state *reg)
1262 {
1263 	/* We might have learned new bounds from the var_off. */
1264 	__update_reg_bounds(reg);
1265 	/* We might have learned something about the sign bit. */
1266 	__reg_deduce_bounds(reg);
1267 	/* We might have learned some bits from the bounds. */
1268 	__reg_bound_offset(reg);
1269 	/* Intersecting with the old var_off might have improved our bounds
1270 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1271 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1272 	 */
1273 	__update_reg_bounds(reg);
1274 }
1275 
__reg32_bound_s64(s32 a)1276 static bool __reg32_bound_s64(s32 a)
1277 {
1278 	return a >= 0 && a <= S32_MAX;
1279 }
1280 
__reg_assign_32_into_64(struct bpf_reg_state * reg)1281 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1282 {
1283 	reg->umin_value = reg->u32_min_value;
1284 	reg->umax_value = reg->u32_max_value;
1285 
1286 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1287 	 * be positive otherwise set to worse case bounds and refine later
1288 	 * from tnum.
1289 	 */
1290 	if (__reg32_bound_s64(reg->s32_min_value) &&
1291 	    __reg32_bound_s64(reg->s32_max_value)) {
1292 		reg->smin_value = reg->s32_min_value;
1293 		reg->smax_value = reg->s32_max_value;
1294 	} else {
1295 		reg->smin_value = 0;
1296 		reg->smax_value = U32_MAX;
1297 	}
1298 }
1299 
__reg_combine_32_into_64(struct bpf_reg_state * reg)1300 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1301 {
1302 	/* special case when 64-bit register has upper 32-bit register
1303 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1304 	 * allowing us to use 32-bit bounds directly,
1305 	 */
1306 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1307 		__reg_assign_32_into_64(reg);
1308 	} else {
1309 		/* Otherwise the best we can do is push lower 32bit known and
1310 		 * unknown bits into register (var_off set from jmp logic)
1311 		 * then learn as much as possible from the 64-bit tnum
1312 		 * known and unknown bits. The previous smin/smax bounds are
1313 		 * invalid here because of jmp32 compare so mark them unknown
1314 		 * so they do not impact tnum bounds calculation.
1315 		 */
1316 		__mark_reg64_unbounded(reg);
1317 	}
1318 	reg_bounds_sync(reg);
1319 }
1320 
__reg64_bound_s32(s64 a)1321 static bool __reg64_bound_s32(s64 a)
1322 {
1323 	return a >= S32_MIN && a <= S32_MAX;
1324 }
1325 
__reg64_bound_u32(u64 a)1326 static bool __reg64_bound_u32(u64 a)
1327 {
1328 	return a >= U32_MIN && a <= U32_MAX;
1329 }
1330 
__reg_combine_64_into_32(struct bpf_reg_state * reg)1331 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1332 {
1333 	__mark_reg32_unbounded(reg);
1334 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1335 		reg->s32_min_value = (s32)reg->smin_value;
1336 		reg->s32_max_value = (s32)reg->smax_value;
1337 	}
1338 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1339 		reg->u32_min_value = (u32)reg->umin_value;
1340 		reg->u32_max_value = (u32)reg->umax_value;
1341 	}
1342 	reg_bounds_sync(reg);
1343 }
1344 
1345 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1346 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1347 			       struct bpf_reg_state *reg)
1348 {
1349 	/*
1350 	 * Clear type, id, off, and union(map_ptr, range) and
1351 	 * padding between 'type' and union
1352 	 */
1353 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1354 	reg->type = SCALAR_VALUE;
1355 	reg->var_off = tnum_unknown;
1356 	reg->frameno = 0;
1357 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1358 	__mark_reg_unbounded(reg);
1359 }
1360 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1361 static void mark_reg_unknown(struct bpf_verifier_env *env,
1362 			     struct bpf_reg_state *regs, u32 regno)
1363 {
1364 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1365 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1366 		/* Something bad happened, let's kill all regs except FP */
1367 		for (regno = 0; regno < BPF_REG_FP; regno++)
1368 			__mark_reg_not_init(env, regs + regno);
1369 		return;
1370 	}
1371 	__mark_reg_unknown(env, regs + regno);
1372 }
1373 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1374 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1375 				struct bpf_reg_state *reg)
1376 {
1377 	__mark_reg_unknown(env, reg);
1378 	reg->type = NOT_INIT;
1379 }
1380 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1381 static void mark_reg_not_init(struct bpf_verifier_env *env,
1382 			      struct bpf_reg_state *regs, u32 regno)
1383 {
1384 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1385 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1386 		/* Something bad happened, let's kill all regs except FP */
1387 		for (regno = 0; regno < BPF_REG_FP; regno++)
1388 			__mark_reg_not_init(env, regs + regno);
1389 		return;
1390 	}
1391 	__mark_reg_not_init(env, regs + regno);
1392 }
1393 
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)1394 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1395 			    struct bpf_reg_state *regs, u32 regno,
1396 			    enum bpf_reg_type reg_type, u32 btf_id)
1397 {
1398 	if (reg_type == SCALAR_VALUE) {
1399 		mark_reg_unknown(env, regs, regno);
1400 		return;
1401 	}
1402 	mark_reg_known_zero(env, regs, regno);
1403 	regs[regno].type = PTR_TO_BTF_ID;
1404 	regs[regno].btf_id = btf_id;
1405 }
1406 
1407 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1408 static void init_reg_state(struct bpf_verifier_env *env,
1409 			   struct bpf_func_state *state)
1410 {
1411 	struct bpf_reg_state *regs = state->regs;
1412 	int i;
1413 
1414 	for (i = 0; i < MAX_BPF_REG; i++) {
1415 		mark_reg_not_init(env, regs, i);
1416 		regs[i].live = REG_LIVE_NONE;
1417 		regs[i].parent = NULL;
1418 		regs[i].subreg_def = DEF_NOT_SUBREG;
1419 	}
1420 
1421 	/* frame pointer */
1422 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1423 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1424 	regs[BPF_REG_FP].frameno = state->frameno;
1425 }
1426 
1427 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1428 static void init_func_state(struct bpf_verifier_env *env,
1429 			    struct bpf_func_state *state,
1430 			    int callsite, int frameno, int subprogno)
1431 {
1432 	state->callsite = callsite;
1433 	state->frameno = frameno;
1434 	state->subprogno = subprogno;
1435 	init_reg_state(env, state);
1436 }
1437 
1438 enum reg_arg_type {
1439 	SRC_OP,		/* register is used as source operand */
1440 	DST_OP,		/* register is used as destination operand */
1441 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1442 };
1443 
cmp_subprogs(const void * a,const void * b)1444 static int cmp_subprogs(const void *a, const void *b)
1445 {
1446 	return ((struct bpf_subprog_info *)a)->start -
1447 	       ((struct bpf_subprog_info *)b)->start;
1448 }
1449 
find_subprog(struct bpf_verifier_env * env,int off)1450 static int find_subprog(struct bpf_verifier_env *env, int off)
1451 {
1452 	struct bpf_subprog_info *p;
1453 
1454 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1455 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1456 	if (!p)
1457 		return -ENOENT;
1458 	return p - env->subprog_info;
1459 
1460 }
1461 
add_subprog(struct bpf_verifier_env * env,int off)1462 static int add_subprog(struct bpf_verifier_env *env, int off)
1463 {
1464 	int insn_cnt = env->prog->len;
1465 	int ret;
1466 
1467 	if (off >= insn_cnt || off < 0) {
1468 		verbose(env, "call to invalid destination\n");
1469 		return -EINVAL;
1470 	}
1471 	ret = find_subprog(env, off);
1472 	if (ret >= 0)
1473 		return 0;
1474 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1475 		verbose(env, "too many subprograms\n");
1476 		return -E2BIG;
1477 	}
1478 	env->subprog_info[env->subprog_cnt++].start = off;
1479 	sort(env->subprog_info, env->subprog_cnt,
1480 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1481 	return 0;
1482 }
1483 
check_subprogs(struct bpf_verifier_env * env)1484 static int check_subprogs(struct bpf_verifier_env *env)
1485 {
1486 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1487 	struct bpf_subprog_info *subprog = env->subprog_info;
1488 	struct bpf_insn *insn = env->prog->insnsi;
1489 	int insn_cnt = env->prog->len;
1490 
1491 	/* Add entry function. */
1492 	ret = add_subprog(env, 0);
1493 	if (ret < 0)
1494 		return ret;
1495 
1496 	/* determine subprog starts. The end is one before the next starts */
1497 	for (i = 0; i < insn_cnt; i++) {
1498 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1499 			continue;
1500 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1501 			continue;
1502 		if (!env->bpf_capable) {
1503 			verbose(env,
1504 				"function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1505 			return -EPERM;
1506 		}
1507 		ret = add_subprog(env, i + insn[i].imm + 1);
1508 		if (ret < 0)
1509 			return ret;
1510 	}
1511 
1512 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1513 	 * logic. 'subprog_cnt' should not be increased.
1514 	 */
1515 	subprog[env->subprog_cnt].start = insn_cnt;
1516 
1517 	if (env->log.level & BPF_LOG_LEVEL2)
1518 		for (i = 0; i < env->subprog_cnt; i++)
1519 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1520 
1521 	/* now check that all jumps are within the same subprog */
1522 	subprog_start = subprog[cur_subprog].start;
1523 	subprog_end = subprog[cur_subprog + 1].start;
1524 	for (i = 0; i < insn_cnt; i++) {
1525 		u8 code = insn[i].code;
1526 
1527 		if (code == (BPF_JMP | BPF_CALL) &&
1528 		    insn[i].imm == BPF_FUNC_tail_call &&
1529 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1530 			subprog[cur_subprog].has_tail_call = true;
1531 		if (BPF_CLASS(code) == BPF_LD &&
1532 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1533 			subprog[cur_subprog].has_ld_abs = true;
1534 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1535 			goto next;
1536 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1537 			goto next;
1538 		off = i + insn[i].off + 1;
1539 		if (off < subprog_start || off >= subprog_end) {
1540 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1541 			return -EINVAL;
1542 		}
1543 next:
1544 		if (i == subprog_end - 1) {
1545 			/* to avoid fall-through from one subprog into another
1546 			 * the last insn of the subprog should be either exit
1547 			 * or unconditional jump back
1548 			 */
1549 			if (code != (BPF_JMP | BPF_EXIT) &&
1550 			    code != (BPF_JMP | BPF_JA)) {
1551 				verbose(env, "last insn is not an exit or jmp\n");
1552 				return -EINVAL;
1553 			}
1554 			subprog_start = subprog_end;
1555 			cur_subprog++;
1556 			if (cur_subprog < env->subprog_cnt)
1557 				subprog_end = subprog[cur_subprog + 1].start;
1558 		}
1559 	}
1560 	return 0;
1561 }
1562 
1563 /* Parentage chain of this register (or stack slot) should take care of all
1564  * issues like callee-saved registers, stack slot allocation time, etc.
1565  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1566 static int mark_reg_read(struct bpf_verifier_env *env,
1567 			 const struct bpf_reg_state *state,
1568 			 struct bpf_reg_state *parent, u8 flag)
1569 {
1570 	bool writes = parent == state->parent; /* Observe write marks */
1571 	int cnt = 0;
1572 
1573 	while (parent) {
1574 		/* if read wasn't screened by an earlier write ... */
1575 		if (writes && state->live & REG_LIVE_WRITTEN)
1576 			break;
1577 		if (parent->live & REG_LIVE_DONE) {
1578 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1579 				reg_type_str(env, parent->type),
1580 				parent->var_off.value, parent->off);
1581 			return -EFAULT;
1582 		}
1583 		/* The first condition is more likely to be true than the
1584 		 * second, checked it first.
1585 		 */
1586 		if ((parent->live & REG_LIVE_READ) == flag ||
1587 		    parent->live & REG_LIVE_READ64)
1588 			/* The parentage chain never changes and
1589 			 * this parent was already marked as LIVE_READ.
1590 			 * There is no need to keep walking the chain again and
1591 			 * keep re-marking all parents as LIVE_READ.
1592 			 * This case happens when the same register is read
1593 			 * multiple times without writes into it in-between.
1594 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1595 			 * then no need to set the weak REG_LIVE_READ32.
1596 			 */
1597 			break;
1598 		/* ... then we depend on parent's value */
1599 		parent->live |= flag;
1600 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1601 		if (flag == REG_LIVE_READ64)
1602 			parent->live &= ~REG_LIVE_READ32;
1603 		state = parent;
1604 		parent = state->parent;
1605 		writes = true;
1606 		cnt++;
1607 	}
1608 
1609 	if (env->longest_mark_read_walk < cnt)
1610 		env->longest_mark_read_walk = cnt;
1611 	return 0;
1612 }
1613 
1614 /* This function is supposed to be used by the following 32-bit optimization
1615  * code only. It returns TRUE if the source or destination register operates
1616  * on 64-bit, otherwise return FALSE.
1617  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1618 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1619 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1620 {
1621 	u8 code, class, op;
1622 
1623 	code = insn->code;
1624 	class = BPF_CLASS(code);
1625 	op = BPF_OP(code);
1626 	if (class == BPF_JMP) {
1627 		/* BPF_EXIT for "main" will reach here. Return TRUE
1628 		 * conservatively.
1629 		 */
1630 		if (op == BPF_EXIT)
1631 			return true;
1632 		if (op == BPF_CALL) {
1633 			/* BPF to BPF call will reach here because of marking
1634 			 * caller saved clobber with DST_OP_NO_MARK for which we
1635 			 * don't care the register def because they are anyway
1636 			 * marked as NOT_INIT already.
1637 			 */
1638 			if (insn->src_reg == BPF_PSEUDO_CALL)
1639 				return false;
1640 			/* Helper call will reach here because of arg type
1641 			 * check, conservatively return TRUE.
1642 			 */
1643 			if (t == SRC_OP)
1644 				return true;
1645 
1646 			return false;
1647 		}
1648 	}
1649 
1650 	if (class == BPF_ALU64 || class == BPF_JMP ||
1651 	    /* BPF_END always use BPF_ALU class. */
1652 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1653 		return true;
1654 
1655 	if (class == BPF_ALU || class == BPF_JMP32)
1656 		return false;
1657 
1658 	if (class == BPF_LDX) {
1659 		if (t != SRC_OP)
1660 			return BPF_SIZE(code) == BPF_DW;
1661 		/* LDX source must be ptr. */
1662 		return true;
1663 	}
1664 
1665 	if (class == BPF_STX) {
1666 		if (reg->type != SCALAR_VALUE)
1667 			return true;
1668 		return BPF_SIZE(code) == BPF_DW;
1669 	}
1670 
1671 	if (class == BPF_LD) {
1672 		u8 mode = BPF_MODE(code);
1673 
1674 		/* LD_IMM64 */
1675 		if (mode == BPF_IMM)
1676 			return true;
1677 
1678 		/* Both LD_IND and LD_ABS return 32-bit data. */
1679 		if (t != SRC_OP)
1680 			return  false;
1681 
1682 		/* Implicit ctx ptr. */
1683 		if (regno == BPF_REG_6)
1684 			return true;
1685 
1686 		/* Explicit source could be any width. */
1687 		return true;
1688 	}
1689 
1690 	if (class == BPF_ST)
1691 		/* The only source register for BPF_ST is a ptr. */
1692 		return true;
1693 
1694 	/* Conservatively return true at default. */
1695 	return true;
1696 }
1697 
1698 /* Return TRUE if INSN doesn't have explicit value define. */
insn_no_def(struct bpf_insn * insn)1699 static bool insn_no_def(struct bpf_insn *insn)
1700 {
1701 	u8 class = BPF_CLASS(insn->code);
1702 
1703 	return (class == BPF_JMP || class == BPF_JMP32 ||
1704 		class == BPF_STX || class == BPF_ST);
1705 }
1706 
1707 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)1708 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1709 {
1710 	if (insn_no_def(insn))
1711 		return false;
1712 
1713 	return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1714 }
1715 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1716 static void mark_insn_zext(struct bpf_verifier_env *env,
1717 			   struct bpf_reg_state *reg)
1718 {
1719 	s32 def_idx = reg->subreg_def;
1720 
1721 	if (def_idx == DEF_NOT_SUBREG)
1722 		return;
1723 
1724 	env->insn_aux_data[def_idx - 1].zext_dst = true;
1725 	/* The dst will be zero extended, so won't be sub-register anymore. */
1726 	reg->subreg_def = DEF_NOT_SUBREG;
1727 }
1728 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)1729 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1730 			 enum reg_arg_type t)
1731 {
1732 	struct bpf_verifier_state *vstate = env->cur_state;
1733 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1734 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1735 	struct bpf_reg_state *reg, *regs = state->regs;
1736 	bool rw64;
1737 
1738 	if (regno >= MAX_BPF_REG) {
1739 		verbose(env, "R%d is invalid\n", regno);
1740 		return -EINVAL;
1741 	}
1742 
1743 	reg = &regs[regno];
1744 	rw64 = is_reg64(env, insn, regno, reg, t);
1745 	if (t == SRC_OP) {
1746 		/* check whether register used as source operand can be read */
1747 		if (reg->type == NOT_INIT) {
1748 			verbose(env, "R%d !read_ok\n", regno);
1749 			return -EACCES;
1750 		}
1751 		/* We don't need to worry about FP liveness because it's read-only */
1752 		if (regno == BPF_REG_FP)
1753 			return 0;
1754 
1755 		if (rw64)
1756 			mark_insn_zext(env, reg);
1757 
1758 		return mark_reg_read(env, reg, reg->parent,
1759 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1760 	} else {
1761 		/* check whether register used as dest operand can be written to */
1762 		if (regno == BPF_REG_FP) {
1763 			verbose(env, "frame pointer is read only\n");
1764 			return -EACCES;
1765 		}
1766 		reg->live |= REG_LIVE_WRITTEN;
1767 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1768 		if (t == DST_OP)
1769 			mark_reg_unknown(env, regs, regno);
1770 	}
1771 	return 0;
1772 }
1773 
1774 /* 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)1775 static int push_jmp_history(struct bpf_verifier_env *env,
1776 			    struct bpf_verifier_state *cur)
1777 {
1778 	u32 cnt = cur->jmp_history_cnt;
1779 	struct bpf_idx_pair *p;
1780 
1781 	cnt++;
1782 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1783 	if (!p)
1784 		return -ENOMEM;
1785 	p[cnt - 1].idx = env->insn_idx;
1786 	p[cnt - 1].prev_idx = env->prev_insn_idx;
1787 	cur->jmp_history = p;
1788 	cur->jmp_history_cnt = cnt;
1789 	return 0;
1790 }
1791 
1792 /* Backtrack one insn at a time. If idx is not at the top of recorded
1793  * history then previous instruction came from straight line execution.
1794  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)1795 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1796 			     u32 *history)
1797 {
1798 	u32 cnt = *history;
1799 
1800 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
1801 		i = st->jmp_history[cnt - 1].prev_idx;
1802 		(*history)--;
1803 	} else {
1804 		i--;
1805 	}
1806 	return i;
1807 }
1808 
1809 /* For given verifier state backtrack_insn() is called from the last insn to
1810  * the first insn. Its purpose is to compute a bitmask of registers and
1811  * stack slots that needs precision in the parent verifier state.
1812  */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)1813 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1814 			  u32 *reg_mask, u64 *stack_mask)
1815 {
1816 	const struct bpf_insn_cbs cbs = {
1817 		.cb_print	= verbose,
1818 		.private_data	= env,
1819 	};
1820 	struct bpf_insn *insn = env->prog->insnsi + idx;
1821 	u8 class = BPF_CLASS(insn->code);
1822 	u8 opcode = BPF_OP(insn->code);
1823 	u8 mode = BPF_MODE(insn->code);
1824 	u32 dreg = 1u << insn->dst_reg;
1825 	u32 sreg = 1u << insn->src_reg;
1826 	u32 spi;
1827 
1828 	if (insn->code == 0)
1829 		return 0;
1830 	if (env->log.level & BPF_LOG_LEVEL) {
1831 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1832 		verbose(env, "%d: ", idx);
1833 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1834 	}
1835 
1836 	if (class == BPF_ALU || class == BPF_ALU64) {
1837 		if (!(*reg_mask & dreg))
1838 			return 0;
1839 		if (opcode == BPF_MOV) {
1840 			if (BPF_SRC(insn->code) == BPF_X) {
1841 				/* dreg = sreg
1842 				 * dreg needs precision after this insn
1843 				 * sreg needs precision before this insn
1844 				 */
1845 				*reg_mask &= ~dreg;
1846 				*reg_mask |= sreg;
1847 			} else {
1848 				/* dreg = K
1849 				 * dreg needs precision after this insn.
1850 				 * Corresponding register is already marked
1851 				 * as precise=true in this verifier state.
1852 				 * No further markings in parent are necessary
1853 				 */
1854 				*reg_mask &= ~dreg;
1855 			}
1856 		} else {
1857 			if (BPF_SRC(insn->code) == BPF_X) {
1858 				/* dreg += sreg
1859 				 * both dreg and sreg need precision
1860 				 * before this insn
1861 				 */
1862 				*reg_mask |= sreg;
1863 			} /* else dreg += K
1864 			   * dreg still needs precision before this insn
1865 			   */
1866 		}
1867 	} else if (class == BPF_LDX) {
1868 		if (!(*reg_mask & dreg))
1869 			return 0;
1870 		*reg_mask &= ~dreg;
1871 
1872 		/* scalars can only be spilled into stack w/o losing precision.
1873 		 * Load from any other memory can be zero extended.
1874 		 * The desire to keep that precision is already indicated
1875 		 * by 'precise' mark in corresponding register of this state.
1876 		 * No further tracking necessary.
1877 		 */
1878 		if (insn->src_reg != BPF_REG_FP)
1879 			return 0;
1880 		if (BPF_SIZE(insn->code) != BPF_DW)
1881 			return 0;
1882 
1883 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
1884 		 * that [fp - off] slot contains scalar that needs to be
1885 		 * tracked with precision
1886 		 */
1887 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1888 		if (spi >= 64) {
1889 			verbose(env, "BUG spi %d\n", spi);
1890 			WARN_ONCE(1, "verifier backtracking bug");
1891 			return -EFAULT;
1892 		}
1893 		*stack_mask |= 1ull << spi;
1894 	} else if (class == BPF_STX || class == BPF_ST) {
1895 		if (*reg_mask & dreg)
1896 			/* stx & st shouldn't be using _scalar_ dst_reg
1897 			 * to access memory. It means backtracking
1898 			 * encountered a case of pointer subtraction.
1899 			 */
1900 			return -ENOTSUPP;
1901 		/* scalars can only be spilled into stack */
1902 		if (insn->dst_reg != BPF_REG_FP)
1903 			return 0;
1904 		if (BPF_SIZE(insn->code) != BPF_DW)
1905 			return 0;
1906 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1907 		if (spi >= 64) {
1908 			verbose(env, "BUG spi %d\n", spi);
1909 			WARN_ONCE(1, "verifier backtracking bug");
1910 			return -EFAULT;
1911 		}
1912 		if (!(*stack_mask & (1ull << spi)))
1913 			return 0;
1914 		*stack_mask &= ~(1ull << spi);
1915 		if (class == BPF_STX)
1916 			*reg_mask |= sreg;
1917 	} else if (class == BPF_JMP || class == BPF_JMP32) {
1918 		if (opcode == BPF_CALL) {
1919 			if (insn->src_reg == BPF_PSEUDO_CALL)
1920 				return -ENOTSUPP;
1921 			/* regular helper call sets R0 */
1922 			*reg_mask &= ~1;
1923 			if (*reg_mask & 0x3f) {
1924 				/* if backtracing was looking for registers R1-R5
1925 				 * they should have been found already.
1926 				 */
1927 				verbose(env, "BUG regs %x\n", *reg_mask);
1928 				WARN_ONCE(1, "verifier backtracking bug");
1929 				return -EFAULT;
1930 			}
1931 		} else if (opcode == BPF_EXIT) {
1932 			return -ENOTSUPP;
1933 		} else if (BPF_SRC(insn->code) == BPF_X) {
1934 			if (!(*reg_mask & (dreg | sreg)))
1935 				return 0;
1936 			/* dreg <cond> sreg
1937 			 * Both dreg and sreg need precision before
1938 			 * this insn. If only sreg was marked precise
1939 			 * before it would be equally necessary to
1940 			 * propagate it to dreg.
1941 			 */
1942 			*reg_mask |= (sreg | dreg);
1943 			 /* else dreg <cond> K
1944 			  * Only dreg still needs precision before
1945 			  * this insn, so for the K-based conditional
1946 			  * there is nothing new to be marked.
1947 			  */
1948 		}
1949 	} else if (class == BPF_LD) {
1950 		if (!(*reg_mask & dreg))
1951 			return 0;
1952 		*reg_mask &= ~dreg;
1953 		/* It's ld_imm64 or ld_abs or ld_ind.
1954 		 * For ld_imm64 no further tracking of precision
1955 		 * into parent is necessary
1956 		 */
1957 		if (mode == BPF_IND || mode == BPF_ABS)
1958 			/* to be analyzed */
1959 			return -ENOTSUPP;
1960 	}
1961 	return 0;
1962 }
1963 
1964 /* the scalar precision tracking algorithm:
1965  * . at the start all registers have precise=false.
1966  * . scalar ranges are tracked as normal through alu and jmp insns.
1967  * . once precise value of the scalar register is used in:
1968  *   .  ptr + scalar alu
1969  *   . if (scalar cond K|scalar)
1970  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1971  *   backtrack through the verifier states and mark all registers and
1972  *   stack slots with spilled constants that these scalar regisers
1973  *   should be precise.
1974  * . during state pruning two registers (or spilled stack slots)
1975  *   are equivalent if both are not precise.
1976  *
1977  * Note the verifier cannot simply walk register parentage chain,
1978  * since many different registers and stack slots could have been
1979  * used to compute single precise scalar.
1980  *
1981  * The approach of starting with precise=true for all registers and then
1982  * backtrack to mark a register as not precise when the verifier detects
1983  * that program doesn't care about specific value (e.g., when helper
1984  * takes register as ARG_ANYTHING parameter) is not safe.
1985  *
1986  * It's ok to walk single parentage chain of the verifier states.
1987  * It's possible that this backtracking will go all the way till 1st insn.
1988  * All other branches will be explored for needing precision later.
1989  *
1990  * The backtracking needs to deal with cases like:
1991  *   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)
1992  * r9 -= r8
1993  * r5 = r9
1994  * if r5 > 0x79f goto pc+7
1995  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1996  * r5 += 1
1997  * ...
1998  * call bpf_perf_event_output#25
1999  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2000  *
2001  * and this case:
2002  * r6 = 1
2003  * call foo // uses callee's r6 inside to compute r0
2004  * r0 += r6
2005  * if r0 == 0 goto
2006  *
2007  * to track above reg_mask/stack_mask needs to be independent for each frame.
2008  *
2009  * Also if parent's curframe > frame where backtracking started,
2010  * the verifier need to mark registers in both frames, otherwise callees
2011  * may incorrectly prune callers. This is similar to
2012  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2013  *
2014  * For now backtracking falls back into conservative marking.
2015  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2016 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2017 				     struct bpf_verifier_state *st)
2018 {
2019 	struct bpf_func_state *func;
2020 	struct bpf_reg_state *reg;
2021 	int i, j;
2022 
2023 	/* big hammer: mark all scalars precise in this path.
2024 	 * pop_stack may still get !precise scalars.
2025 	 */
2026 	for (; st; st = st->parent)
2027 		for (i = 0; i <= st->curframe; i++) {
2028 			func = st->frame[i];
2029 			for (j = 0; j < BPF_REG_FP; j++) {
2030 				reg = &func->regs[j];
2031 				if (reg->type != SCALAR_VALUE)
2032 					continue;
2033 				reg->precise = true;
2034 			}
2035 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2036 				if (!is_spilled_reg(&func->stack[j]))
2037 					continue;
2038 				reg = &func->stack[j].spilled_ptr;
2039 				if (reg->type != SCALAR_VALUE)
2040 					continue;
2041 				reg->precise = true;
2042 			}
2043 		}
2044 }
2045 
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2046 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2047 				  int spi)
2048 {
2049 	struct bpf_verifier_state *st = env->cur_state;
2050 	int first_idx = st->first_insn_idx;
2051 	int last_idx = env->insn_idx;
2052 	struct bpf_func_state *func;
2053 	struct bpf_reg_state *reg;
2054 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2055 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2056 	bool skip_first = true;
2057 	bool new_marks = false;
2058 	int i, err;
2059 
2060 	if (!env->bpf_capable)
2061 		return 0;
2062 
2063 	func = st->frame[frame];
2064 	if (regno >= 0) {
2065 		reg = &func->regs[regno];
2066 		if (reg->type != SCALAR_VALUE) {
2067 			WARN_ONCE(1, "backtracing misuse");
2068 			return -EFAULT;
2069 		}
2070 		if (!reg->precise)
2071 			new_marks = true;
2072 		else
2073 			reg_mask = 0;
2074 		reg->precise = true;
2075 	}
2076 
2077 	while (spi >= 0) {
2078 		if (!is_spilled_reg(&func->stack[spi])) {
2079 			stack_mask = 0;
2080 			break;
2081 		}
2082 		reg = &func->stack[spi].spilled_ptr;
2083 		if (reg->type != SCALAR_VALUE) {
2084 			stack_mask = 0;
2085 			break;
2086 		}
2087 		if (!reg->precise)
2088 			new_marks = true;
2089 		else
2090 			stack_mask = 0;
2091 		reg->precise = true;
2092 		break;
2093 	}
2094 
2095 	if (!new_marks)
2096 		return 0;
2097 	if (!reg_mask && !stack_mask)
2098 		return 0;
2099 	for (;;) {
2100 		DECLARE_BITMAP(mask, 64);
2101 		u32 history = st->jmp_history_cnt;
2102 
2103 		if (env->log.level & BPF_LOG_LEVEL)
2104 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2105 		for (i = last_idx;;) {
2106 			if (skip_first) {
2107 				err = 0;
2108 				skip_first = false;
2109 			} else {
2110 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2111 			}
2112 			if (err == -ENOTSUPP) {
2113 				mark_all_scalars_precise(env, st);
2114 				return 0;
2115 			} else if (err) {
2116 				return err;
2117 			}
2118 			if (!reg_mask && !stack_mask)
2119 				/* Found assignment(s) into tracked register in this state.
2120 				 * Since this state is already marked, just return.
2121 				 * Nothing to be tracked further in the parent state.
2122 				 */
2123 				return 0;
2124 			if (i == first_idx)
2125 				break;
2126 			i = get_prev_insn_idx(st, i, &history);
2127 			if (i >= env->prog->len) {
2128 				/* This can happen if backtracking reached insn 0
2129 				 * and there are still reg_mask or stack_mask
2130 				 * to backtrack.
2131 				 * It means the backtracking missed the spot where
2132 				 * particular register was initialized with a constant.
2133 				 */
2134 				verbose(env, "BUG backtracking idx %d\n", i);
2135 				WARN_ONCE(1, "verifier backtracking bug");
2136 				return -EFAULT;
2137 			}
2138 		}
2139 		st = st->parent;
2140 		if (!st)
2141 			break;
2142 
2143 		new_marks = false;
2144 		func = st->frame[frame];
2145 		bitmap_from_u64(mask, reg_mask);
2146 		for_each_set_bit(i, mask, 32) {
2147 			reg = &func->regs[i];
2148 			if (reg->type != SCALAR_VALUE) {
2149 				reg_mask &= ~(1u << i);
2150 				continue;
2151 			}
2152 			if (!reg->precise)
2153 				new_marks = true;
2154 			reg->precise = true;
2155 		}
2156 
2157 		bitmap_from_u64(mask, stack_mask);
2158 		for_each_set_bit(i, mask, 64) {
2159 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2160 				/* the sequence of instructions:
2161 				 * 2: (bf) r3 = r10
2162 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2163 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2164 				 * doesn't contain jmps. It's backtracked
2165 				 * as a single block.
2166 				 * During backtracking insn 3 is not recognized as
2167 				 * stack access, so at the end of backtracking
2168 				 * stack slot fp-8 is still marked in stack_mask.
2169 				 * However the parent state may not have accessed
2170 				 * fp-8 and it's "unallocated" stack space.
2171 				 * In such case fallback to conservative.
2172 				 */
2173 				mark_all_scalars_precise(env, st);
2174 				return 0;
2175 			}
2176 
2177 			if (!is_spilled_reg(&func->stack[i])) {
2178 				stack_mask &= ~(1ull << i);
2179 				continue;
2180 			}
2181 			reg = &func->stack[i].spilled_ptr;
2182 			if (reg->type != SCALAR_VALUE) {
2183 				stack_mask &= ~(1ull << i);
2184 				continue;
2185 			}
2186 			if (!reg->precise)
2187 				new_marks = true;
2188 			reg->precise = true;
2189 		}
2190 		if (env->log.level & BPF_LOG_LEVEL) {
2191 			print_verifier_state(env, func);
2192 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2193 				new_marks ? "didn't have" : "already had",
2194 				reg_mask, stack_mask);
2195 		}
2196 
2197 		if (!reg_mask && !stack_mask)
2198 			break;
2199 		if (!new_marks)
2200 			break;
2201 
2202 		last_idx = st->last_insn_idx;
2203 		first_idx = st->first_insn_idx;
2204 	}
2205 	return 0;
2206 }
2207 
mark_chain_precision(struct bpf_verifier_env * env,int regno)2208 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2209 {
2210 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2211 }
2212 
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2213 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2214 {
2215 	return __mark_chain_precision(env, frame, regno, -1);
2216 }
2217 
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2218 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2219 {
2220 	return __mark_chain_precision(env, frame, -1, spi);
2221 }
2222 
is_spillable_regtype(enum bpf_reg_type type)2223 static bool is_spillable_regtype(enum bpf_reg_type type)
2224 {
2225 	switch (base_type(type)) {
2226 	case PTR_TO_MAP_VALUE:
2227 	case PTR_TO_STACK:
2228 	case PTR_TO_CTX:
2229 	case PTR_TO_PACKET:
2230 	case PTR_TO_PACKET_META:
2231 	case PTR_TO_PACKET_END:
2232 	case PTR_TO_FLOW_KEYS:
2233 	case CONST_PTR_TO_MAP:
2234 	case PTR_TO_SOCKET:
2235 	case PTR_TO_SOCK_COMMON:
2236 	case PTR_TO_TCP_SOCK:
2237 	case PTR_TO_XDP_SOCK:
2238 	case PTR_TO_BTF_ID:
2239 	case PTR_TO_BUF:
2240 	case PTR_TO_PERCPU_BTF_ID:
2241 	case PTR_TO_MEM:
2242 		return true;
2243 	default:
2244 		return false;
2245 	}
2246 }
2247 
2248 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2249 static bool register_is_null(struct bpf_reg_state *reg)
2250 {
2251 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2252 }
2253 
register_is_const(struct bpf_reg_state * reg)2254 static bool register_is_const(struct bpf_reg_state *reg)
2255 {
2256 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2257 }
2258 
__is_scalar_unbounded(struct bpf_reg_state * reg)2259 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2260 {
2261 	return tnum_is_unknown(reg->var_off) &&
2262 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2263 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2264 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2265 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2266 }
2267 
register_is_bounded(struct bpf_reg_state * reg)2268 static bool register_is_bounded(struct bpf_reg_state *reg)
2269 {
2270 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2271 }
2272 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)2273 static bool __is_pointer_value(bool allow_ptr_leaks,
2274 			       const struct bpf_reg_state *reg)
2275 {
2276 	if (allow_ptr_leaks)
2277 		return false;
2278 
2279 	return reg->type != SCALAR_VALUE;
2280 }
2281 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg)2282 static void save_register_state(struct bpf_func_state *state,
2283 				int spi, struct bpf_reg_state *reg)
2284 {
2285 	int i;
2286 
2287 	state->stack[spi].spilled_ptr = *reg;
2288 	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2289 
2290 	for (i = 0; i < BPF_REG_SIZE; i++)
2291 		state->stack[spi].slot_type[i] = STACK_SPILL;
2292 }
2293 
2294 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2295  * stack boundary and alignment are checked in check_mem_access()
2296  */
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)2297 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2298 				       /* stack frame we're writing to */
2299 				       struct bpf_func_state *state,
2300 				       int off, int size, int value_regno,
2301 				       int insn_idx)
2302 {
2303 	struct bpf_func_state *cur; /* state of the current function */
2304 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2305 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2306 	struct bpf_reg_state *reg = NULL;
2307 
2308 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2309 				 state->acquired_refs, true);
2310 	if (err)
2311 		return err;
2312 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2313 	 * so it's aligned access and [off, off + size) are within stack limits
2314 	 */
2315 	if (!env->allow_ptr_leaks &&
2316 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2317 	    size != BPF_REG_SIZE) {
2318 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2319 		return -EACCES;
2320 	}
2321 
2322 	cur = env->cur_state->frame[env->cur_state->curframe];
2323 	if (value_regno >= 0)
2324 		reg = &cur->regs[value_regno];
2325 	if (!env->bypass_spec_v4) {
2326 		bool sanitize = reg && is_spillable_regtype(reg->type);
2327 
2328 		for (i = 0; i < size; i++) {
2329 			if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2330 				sanitize = true;
2331 				break;
2332 			}
2333 		}
2334 
2335 		if (sanitize)
2336 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2337 	}
2338 
2339 	if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2340 	    !register_is_null(reg) && env->bpf_capable) {
2341 		if (dst_reg != BPF_REG_FP) {
2342 			/* The backtracking logic can only recognize explicit
2343 			 * stack slot address like [fp - 8]. Other spill of
2344 			 * scalar via different register has to be conervative.
2345 			 * Backtrack from here and mark all registers as precise
2346 			 * that contributed into 'reg' being a constant.
2347 			 */
2348 			err = mark_chain_precision(env, value_regno);
2349 			if (err)
2350 				return err;
2351 		}
2352 		save_register_state(state, spi, reg);
2353 	} else if (reg && is_spillable_regtype(reg->type)) {
2354 		/* register containing pointer is being spilled into stack */
2355 		if (size != BPF_REG_SIZE) {
2356 			verbose_linfo(env, insn_idx, "; ");
2357 			verbose(env, "invalid size of register spill\n");
2358 			return -EACCES;
2359 		}
2360 		if (state != cur && reg->type == PTR_TO_STACK) {
2361 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2362 			return -EINVAL;
2363 		}
2364 		save_register_state(state, spi, reg);
2365 	} else {
2366 		u8 type = STACK_MISC;
2367 
2368 		/* regular write of data into stack destroys any spilled ptr */
2369 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2370 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2371 		if (is_spilled_reg(&state->stack[spi]))
2372 			for (i = 0; i < BPF_REG_SIZE; i++)
2373 				state->stack[spi].slot_type[i] = STACK_MISC;
2374 
2375 		/* only mark the slot as written if all 8 bytes were written
2376 		 * otherwise read propagation may incorrectly stop too soon
2377 		 * when stack slots are partially written.
2378 		 * This heuristic means that read propagation will be
2379 		 * conservative, since it will add reg_live_read marks
2380 		 * to stack slots all the way to first state when programs
2381 		 * writes+reads less than 8 bytes
2382 		 */
2383 		if (size == BPF_REG_SIZE)
2384 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2385 
2386 		/* when we zero initialize stack slots mark them as such */
2387 		if (reg && register_is_null(reg)) {
2388 			/* backtracking doesn't work for STACK_ZERO yet. */
2389 			err = mark_chain_precision(env, value_regno);
2390 			if (err)
2391 				return err;
2392 			type = STACK_ZERO;
2393 		}
2394 
2395 		/* Mark slots affected by this stack write. */
2396 		for (i = 0; i < size; i++)
2397 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2398 				type;
2399 	}
2400 	return 0;
2401 }
2402 
2403 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2404  * known to contain a variable offset.
2405  * This function checks whether the write is permitted and conservatively
2406  * tracks the effects of the write, considering that each stack slot in the
2407  * dynamic range is potentially written to.
2408  *
2409  * 'off' includes 'regno->off'.
2410  * 'value_regno' can be -1, meaning that an unknown value is being written to
2411  * the stack.
2412  *
2413  * Spilled pointers in range are not marked as written because we don't know
2414  * what's going to be actually written. This means that read propagation for
2415  * future reads cannot be terminated by this write.
2416  *
2417  * For privileged programs, uninitialized stack slots are considered
2418  * initialized by this write (even though we don't know exactly what offsets
2419  * are going to be written to). The idea is that we don't want the verifier to
2420  * reject future reads that access slots written to through variable offsets.
2421  */
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)2422 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2423 				     /* func where register points to */
2424 				     struct bpf_func_state *state,
2425 				     int ptr_regno, int off, int size,
2426 				     int value_regno, int insn_idx)
2427 {
2428 	struct bpf_func_state *cur; /* state of the current function */
2429 	int min_off, max_off;
2430 	int i, err;
2431 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2432 	bool writing_zero = false;
2433 	/* set if the fact that we're writing a zero is used to let any
2434 	 * stack slots remain STACK_ZERO
2435 	 */
2436 	bool zero_used = false;
2437 
2438 	cur = env->cur_state->frame[env->cur_state->curframe];
2439 	ptr_reg = &cur->regs[ptr_regno];
2440 	min_off = ptr_reg->smin_value + off;
2441 	max_off = ptr_reg->smax_value + off + size;
2442 	if (value_regno >= 0)
2443 		value_reg = &cur->regs[value_regno];
2444 	if (value_reg && register_is_null(value_reg))
2445 		writing_zero = true;
2446 
2447 	err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2448 				 state->acquired_refs, true);
2449 	if (err)
2450 		return err;
2451 
2452 
2453 	/* Variable offset writes destroy any spilled pointers in range. */
2454 	for (i = min_off; i < max_off; i++) {
2455 		u8 new_type, *stype;
2456 		int slot, spi;
2457 
2458 		slot = -i - 1;
2459 		spi = slot / BPF_REG_SIZE;
2460 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2461 
2462 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
2463 			/* Reject the write if range we may write to has not
2464 			 * been initialized beforehand. If we didn't reject
2465 			 * here, the ptr status would be erased below (even
2466 			 * though not all slots are actually overwritten),
2467 			 * possibly opening the door to leaks.
2468 			 *
2469 			 * We do however catch STACK_INVALID case below, and
2470 			 * only allow reading possibly uninitialized memory
2471 			 * later for CAP_PERFMON, as the write may not happen to
2472 			 * that slot.
2473 			 */
2474 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2475 				insn_idx, i);
2476 			return -EINVAL;
2477 		}
2478 
2479 		/* Erase all spilled pointers. */
2480 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2481 
2482 		/* Update the slot type. */
2483 		new_type = STACK_MISC;
2484 		if (writing_zero && *stype == STACK_ZERO) {
2485 			new_type = STACK_ZERO;
2486 			zero_used = true;
2487 		}
2488 		/* If the slot is STACK_INVALID, we check whether it's OK to
2489 		 * pretend that it will be initialized by this write. The slot
2490 		 * might not actually be written to, and so if we mark it as
2491 		 * initialized future reads might leak uninitialized memory.
2492 		 * For privileged programs, we will accept such reads to slots
2493 		 * that may or may not be written because, if we're reject
2494 		 * them, the error would be too confusing.
2495 		 */
2496 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2497 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2498 					insn_idx, i);
2499 			return -EINVAL;
2500 		}
2501 		*stype = new_type;
2502 	}
2503 	if (zero_used) {
2504 		/* backtracking doesn't work for STACK_ZERO yet. */
2505 		err = mark_chain_precision(env, value_regno);
2506 		if (err)
2507 			return err;
2508 	}
2509 	return 0;
2510 }
2511 
2512 /* When register 'dst_regno' is assigned some values from stack[min_off,
2513  * max_off), we set the register's type according to the types of the
2514  * respective stack slots. If all the stack values are known to be zeros, then
2515  * so is the destination reg. Otherwise, the register is considered to be
2516  * SCALAR. This function does not deal with register filling; the caller must
2517  * ensure that all spilled registers in the stack range have been marked as
2518  * read.
2519  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)2520 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2521 				/* func where src register points to */
2522 				struct bpf_func_state *ptr_state,
2523 				int min_off, int max_off, int dst_regno)
2524 {
2525 	struct bpf_verifier_state *vstate = env->cur_state;
2526 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2527 	int i, slot, spi;
2528 	u8 *stype;
2529 	int zeros = 0;
2530 
2531 	for (i = min_off; i < max_off; i++) {
2532 		slot = -i - 1;
2533 		spi = slot / BPF_REG_SIZE;
2534 		stype = ptr_state->stack[spi].slot_type;
2535 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2536 			break;
2537 		zeros++;
2538 	}
2539 	if (zeros == max_off - min_off) {
2540 		/* any access_size read into register is zero extended,
2541 		 * so the whole register == const_zero
2542 		 */
2543 		__mark_reg_const_zero(&state->regs[dst_regno]);
2544 		/* backtracking doesn't support STACK_ZERO yet,
2545 		 * so mark it precise here, so that later
2546 		 * backtracking can stop here.
2547 		 * Backtracking may not need this if this register
2548 		 * doesn't participate in pointer adjustment.
2549 		 * Forward propagation of precise flag is not
2550 		 * necessary either. This mark is only to stop
2551 		 * backtracking. Any register that contributed
2552 		 * to const 0 was marked precise before spill.
2553 		 */
2554 		state->regs[dst_regno].precise = true;
2555 	} else {
2556 		/* have read misc data from the stack */
2557 		mark_reg_unknown(env, state->regs, dst_regno);
2558 	}
2559 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2560 }
2561 
2562 /* Read the stack at 'off' and put the results into the register indicated by
2563  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2564  * spilled reg.
2565  *
2566  * 'dst_regno' can be -1, meaning that the read value is not going to a
2567  * register.
2568  *
2569  * The access is assumed to be within the current stack bounds.
2570  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)2571 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2572 				      /* func where src register points to */
2573 				      struct bpf_func_state *reg_state,
2574 				      int off, int size, int dst_regno)
2575 {
2576 	struct bpf_verifier_state *vstate = env->cur_state;
2577 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2578 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2579 	struct bpf_reg_state *reg;
2580 	u8 *stype;
2581 
2582 	stype = reg_state->stack[spi].slot_type;
2583 	reg = &reg_state->stack[spi].spilled_ptr;
2584 
2585 	if (is_spilled_reg(&reg_state->stack[spi])) {
2586 		if (size != BPF_REG_SIZE) {
2587 			if (reg->type != SCALAR_VALUE) {
2588 				verbose_linfo(env, env->insn_idx, "; ");
2589 				verbose(env, "invalid size of register fill\n");
2590 				return -EACCES;
2591 			}
2592 			if (dst_regno >= 0) {
2593 				mark_reg_unknown(env, state->regs, dst_regno);
2594 				state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2595 			}
2596 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2597 			return 0;
2598 		}
2599 		for (i = 1; i < BPF_REG_SIZE; i++) {
2600 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2601 				verbose(env, "corrupted spill memory\n");
2602 				return -EACCES;
2603 			}
2604 		}
2605 
2606 		if (dst_regno >= 0) {
2607 			/* restore register state from stack */
2608 			state->regs[dst_regno] = *reg;
2609 			/* mark reg as written since spilled pointer state likely
2610 			 * has its liveness marks cleared by is_state_visited()
2611 			 * which resets stack/reg liveness for state transitions
2612 			 */
2613 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2614 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2615 			/* If dst_regno==-1, the caller is asking us whether
2616 			 * it is acceptable to use this value as a SCALAR_VALUE
2617 			 * (e.g. for XADD).
2618 			 * We must not allow unprivileged callers to do that
2619 			 * with spilled pointers.
2620 			 */
2621 			verbose(env, "leaking pointer from stack off %d\n",
2622 				off);
2623 			return -EACCES;
2624 		}
2625 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2626 	} else {
2627 		u8 type;
2628 
2629 		for (i = 0; i < size; i++) {
2630 			type = stype[(slot - i) % BPF_REG_SIZE];
2631 			if (type == STACK_MISC)
2632 				continue;
2633 			if (type == STACK_ZERO)
2634 				continue;
2635 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2636 				off, i, size);
2637 			return -EACCES;
2638 		}
2639 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2640 		if (dst_regno >= 0)
2641 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2642 	}
2643 	return 0;
2644 }
2645 
2646 enum stack_access_src {
2647 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2648 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
2649 };
2650 
2651 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2652 					 int regno, int off, int access_size,
2653 					 bool zero_size_allowed,
2654 					 enum stack_access_src type,
2655 					 struct bpf_call_arg_meta *meta);
2656 
reg_state(struct bpf_verifier_env * env,int regno)2657 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2658 {
2659 	return cur_regs(env) + regno;
2660 }
2661 
2662 /* Read the stack at 'ptr_regno + off' and put the result into the register
2663  * 'dst_regno'.
2664  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2665  * but not its variable offset.
2666  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2667  *
2668  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2669  * filling registers (i.e. reads of spilled register cannot be detected when
2670  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2671  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2672  * offset; for a fixed offset check_stack_read_fixed_off should be used
2673  * instead.
2674  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2675 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2676 				    int ptr_regno, int off, int size, int dst_regno)
2677 {
2678 	/* The state of the source register. */
2679 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2680 	struct bpf_func_state *ptr_state = func(env, reg);
2681 	int err;
2682 	int min_off, max_off;
2683 
2684 	/* Note that we pass a NULL meta, so raw access will not be permitted.
2685 	 */
2686 	err = check_stack_range_initialized(env, ptr_regno, off, size,
2687 					    false, ACCESS_DIRECT, NULL);
2688 	if (err)
2689 		return err;
2690 
2691 	min_off = reg->smin_value + off;
2692 	max_off = reg->smax_value + off;
2693 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2694 	return 0;
2695 }
2696 
2697 /* check_stack_read dispatches to check_stack_read_fixed_off or
2698  * check_stack_read_var_off.
2699  *
2700  * The caller must ensure that the offset falls within the allocated stack
2701  * bounds.
2702  *
2703  * 'dst_regno' is a register which will receive the value from the stack. It
2704  * can be -1, meaning that the read value is not going to a register.
2705  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2706 static int check_stack_read(struct bpf_verifier_env *env,
2707 			    int ptr_regno, int off, int size,
2708 			    int dst_regno)
2709 {
2710 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2711 	struct bpf_func_state *state = func(env, reg);
2712 	int err;
2713 	/* Some accesses are only permitted with a static offset. */
2714 	bool var_off = !tnum_is_const(reg->var_off);
2715 
2716 	/* The offset is required to be static when reads don't go to a
2717 	 * register, in order to not leak pointers (see
2718 	 * check_stack_read_fixed_off).
2719 	 */
2720 	if (dst_regno < 0 && var_off) {
2721 		char tn_buf[48];
2722 
2723 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2724 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2725 			tn_buf, off, size);
2726 		return -EACCES;
2727 	}
2728 	/* Variable offset is prohibited for unprivileged mode for simplicity
2729 	 * since it requires corresponding support in Spectre masking for stack
2730 	 * ALU. See also retrieve_ptr_limit().
2731 	 */
2732 	if (!env->bypass_spec_v1 && var_off) {
2733 		char tn_buf[48];
2734 
2735 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2736 		verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2737 				ptr_regno, tn_buf);
2738 		return -EACCES;
2739 	}
2740 
2741 	if (!var_off) {
2742 		off += reg->var_off.value;
2743 		err = check_stack_read_fixed_off(env, state, off, size,
2744 						 dst_regno);
2745 	} else {
2746 		/* Variable offset stack reads need more conservative handling
2747 		 * than fixed offset ones. Note that dst_regno >= 0 on this
2748 		 * branch.
2749 		 */
2750 		err = check_stack_read_var_off(env, ptr_regno, off, size,
2751 					       dst_regno);
2752 	}
2753 	return err;
2754 }
2755 
2756 
2757 /* check_stack_write dispatches to check_stack_write_fixed_off or
2758  * check_stack_write_var_off.
2759  *
2760  * 'ptr_regno' is the register used as a pointer into the stack.
2761  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2762  * 'value_regno' is the register whose value we're writing to the stack. It can
2763  * be -1, meaning that we're not writing from a register.
2764  *
2765  * The caller must ensure that the offset falls within the maximum stack size.
2766  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)2767 static int check_stack_write(struct bpf_verifier_env *env,
2768 			     int ptr_regno, int off, int size,
2769 			     int value_regno, int insn_idx)
2770 {
2771 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2772 	struct bpf_func_state *state = func(env, reg);
2773 	int err;
2774 
2775 	if (tnum_is_const(reg->var_off)) {
2776 		off += reg->var_off.value;
2777 		err = check_stack_write_fixed_off(env, state, off, size,
2778 						  value_regno, insn_idx);
2779 	} else {
2780 		/* Variable offset stack reads need more conservative handling
2781 		 * than fixed offset ones.
2782 		 */
2783 		err = check_stack_write_var_off(env, state,
2784 						ptr_regno, off, size,
2785 						value_regno, insn_idx);
2786 	}
2787 	return err;
2788 }
2789 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)2790 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2791 				 int off, int size, enum bpf_access_type type)
2792 {
2793 	struct bpf_reg_state *regs = cur_regs(env);
2794 	struct bpf_map *map = regs[regno].map_ptr;
2795 	u32 cap = bpf_map_flags_to_cap(map);
2796 
2797 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2798 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2799 			map->value_size, off, size);
2800 		return -EACCES;
2801 	}
2802 
2803 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2804 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2805 			map->value_size, off, size);
2806 		return -EACCES;
2807 	}
2808 
2809 	return 0;
2810 }
2811 
2812 /* 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)2813 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2814 			      int off, int size, u32 mem_size,
2815 			      bool zero_size_allowed)
2816 {
2817 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2818 	struct bpf_reg_state *reg;
2819 
2820 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2821 		return 0;
2822 
2823 	reg = &cur_regs(env)[regno];
2824 	switch (reg->type) {
2825 	case PTR_TO_MAP_VALUE:
2826 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2827 			mem_size, off, size);
2828 		break;
2829 	case PTR_TO_PACKET:
2830 	case PTR_TO_PACKET_META:
2831 	case PTR_TO_PACKET_END:
2832 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2833 			off, size, regno, reg->id, off, mem_size);
2834 		break;
2835 	case PTR_TO_MEM:
2836 	default:
2837 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2838 			mem_size, off, size);
2839 	}
2840 
2841 	return -EACCES;
2842 }
2843 
2844 /* 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)2845 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2846 				   int off, int size, u32 mem_size,
2847 				   bool zero_size_allowed)
2848 {
2849 	struct bpf_verifier_state *vstate = env->cur_state;
2850 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2851 	struct bpf_reg_state *reg = &state->regs[regno];
2852 	int err;
2853 
2854 	/* We may have adjusted the register pointing to memory region, so we
2855 	 * need to try adding each of min_value and max_value to off
2856 	 * to make sure our theoretical access will be safe.
2857 	 */
2858 	if (env->log.level & BPF_LOG_LEVEL)
2859 		print_verifier_state(env, state);
2860 
2861 	/* The minimum value is only important with signed
2862 	 * comparisons where we can't assume the floor of a
2863 	 * value is 0.  If we are using signed variables for our
2864 	 * index'es we need to make sure that whatever we use
2865 	 * will have a set floor within our range.
2866 	 */
2867 	if (reg->smin_value < 0 &&
2868 	    (reg->smin_value == S64_MIN ||
2869 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2870 	      reg->smin_value + off < 0)) {
2871 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2872 			regno);
2873 		return -EACCES;
2874 	}
2875 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
2876 				 mem_size, zero_size_allowed);
2877 	if (err) {
2878 		verbose(env, "R%d min value is outside of the allowed memory range\n",
2879 			regno);
2880 		return err;
2881 	}
2882 
2883 	/* If we haven't set a max value then we need to bail since we can't be
2884 	 * sure we won't do bad things.
2885 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
2886 	 */
2887 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2888 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2889 			regno);
2890 		return -EACCES;
2891 	}
2892 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
2893 				 mem_size, zero_size_allowed);
2894 	if (err) {
2895 		verbose(env, "R%d max value is outside of the allowed memory range\n",
2896 			regno);
2897 		return err;
2898 	}
2899 
2900 	return 0;
2901 }
2902 
2903 /* 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)2904 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2905 			    int off, int size, bool zero_size_allowed)
2906 {
2907 	struct bpf_verifier_state *vstate = env->cur_state;
2908 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2909 	struct bpf_reg_state *reg = &state->regs[regno];
2910 	struct bpf_map *map = reg->map_ptr;
2911 	int err;
2912 
2913 	err = check_mem_region_access(env, regno, off, size, map->value_size,
2914 				      zero_size_allowed);
2915 	if (err)
2916 		return err;
2917 
2918 	if (map_value_has_spin_lock(map)) {
2919 		u32 lock = map->spin_lock_off;
2920 
2921 		/* if any part of struct bpf_spin_lock can be touched by
2922 		 * load/store reject this program.
2923 		 * To check that [x1, x2) overlaps with [y1, y2)
2924 		 * it is sufficient to check x1 < y2 && y1 < x2.
2925 		 */
2926 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2927 		     lock < reg->umax_value + off + size) {
2928 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2929 			return -EACCES;
2930 		}
2931 	}
2932 	return err;
2933 }
2934 
2935 #define MAX_PACKET_OFF 0xffff
2936 
resolve_prog_type(struct bpf_prog * prog)2937 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2938 {
2939 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2940 }
2941 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)2942 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2943 				       const struct bpf_call_arg_meta *meta,
2944 				       enum bpf_access_type t)
2945 {
2946 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2947 
2948 	switch (prog_type) {
2949 	/* Program types only with direct read access go here! */
2950 	case BPF_PROG_TYPE_LWT_IN:
2951 	case BPF_PROG_TYPE_LWT_OUT:
2952 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2953 	case BPF_PROG_TYPE_SK_REUSEPORT:
2954 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2955 	case BPF_PROG_TYPE_CGROUP_SKB:
2956 		if (t == BPF_WRITE)
2957 			return false;
2958 		fallthrough;
2959 
2960 	/* Program types with direct read + write access go here! */
2961 	case BPF_PROG_TYPE_SCHED_CLS:
2962 	case BPF_PROG_TYPE_SCHED_ACT:
2963 	case BPF_PROG_TYPE_XDP:
2964 	case BPF_PROG_TYPE_LWT_XMIT:
2965 	case BPF_PROG_TYPE_SK_SKB:
2966 	case BPF_PROG_TYPE_SK_MSG:
2967 		if (meta)
2968 			return meta->pkt_access;
2969 
2970 		env->seen_direct_write = true;
2971 		return true;
2972 
2973 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2974 		if (t == BPF_WRITE)
2975 			env->seen_direct_write = true;
2976 
2977 		return true;
2978 
2979 	default:
2980 		return false;
2981 	}
2982 }
2983 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)2984 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2985 			       int size, bool zero_size_allowed)
2986 {
2987 	struct bpf_reg_state *regs = cur_regs(env);
2988 	struct bpf_reg_state *reg = &regs[regno];
2989 	int err;
2990 
2991 	/* We may have added a variable offset to the packet pointer; but any
2992 	 * reg->range we have comes after that.  We are only checking the fixed
2993 	 * offset.
2994 	 */
2995 
2996 	/* We don't allow negative numbers, because we aren't tracking enough
2997 	 * detail to prove they're safe.
2998 	 */
2999 	if (reg->smin_value < 0) {
3000 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3001 			regno);
3002 		return -EACCES;
3003 	}
3004 
3005 	err = reg->range < 0 ? -EINVAL :
3006 	      __check_mem_access(env, regno, off, size, reg->range,
3007 				 zero_size_allowed);
3008 	if (err) {
3009 		verbose(env, "R%d offset is outside of the packet\n", regno);
3010 		return err;
3011 	}
3012 
3013 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3014 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3015 	 * otherwise find_good_pkt_pointers would have refused to set range info
3016 	 * that __check_mem_access would have rejected this pkt access.
3017 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3018 	 */
3019 	env->prog->aux->max_pkt_offset =
3020 		max_t(u32, env->prog->aux->max_pkt_offset,
3021 		      off + reg->umax_value + size - 1);
3022 
3023 	return err;
3024 }
3025 
3026 /* 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)3027 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3028 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3029 			    u32 *btf_id)
3030 {
3031 	struct bpf_insn_access_aux info = {
3032 		.reg_type = *reg_type,
3033 		.log = &env->log,
3034 	};
3035 
3036 	if (env->ops->is_valid_access &&
3037 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3038 		/* A non zero info.ctx_field_size indicates that this field is a
3039 		 * candidate for later verifier transformation to load the whole
3040 		 * field and then apply a mask when accessed with a narrower
3041 		 * access than actual ctx access size. A zero info.ctx_field_size
3042 		 * will only allow for whole field access and rejects any other
3043 		 * type of narrower access.
3044 		 */
3045 		*reg_type = info.reg_type;
3046 
3047 		if (base_type(*reg_type) == PTR_TO_BTF_ID)
3048 			*btf_id = info.btf_id;
3049 		else
3050 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3051 		/* remember the offset of last byte accessed in ctx */
3052 		if (env->prog->aux->max_ctx_offset < off + size)
3053 			env->prog->aux->max_ctx_offset = off + size;
3054 		return 0;
3055 	}
3056 
3057 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3058 	return -EACCES;
3059 }
3060 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)3061 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3062 				  int size)
3063 {
3064 	if (size < 0 || off < 0 ||
3065 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3066 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3067 			off, size);
3068 		return -EACCES;
3069 	}
3070 	return 0;
3071 }
3072 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)3073 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3074 			     u32 regno, int off, int size,
3075 			     enum bpf_access_type t)
3076 {
3077 	struct bpf_reg_state *regs = cur_regs(env);
3078 	struct bpf_reg_state *reg = &regs[regno];
3079 	struct bpf_insn_access_aux info = {};
3080 	bool valid;
3081 
3082 	if (reg->smin_value < 0) {
3083 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3084 			regno);
3085 		return -EACCES;
3086 	}
3087 
3088 	switch (reg->type) {
3089 	case PTR_TO_SOCK_COMMON:
3090 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3091 		break;
3092 	case PTR_TO_SOCKET:
3093 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3094 		break;
3095 	case PTR_TO_TCP_SOCK:
3096 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3097 		break;
3098 	case PTR_TO_XDP_SOCK:
3099 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3100 		break;
3101 	default:
3102 		valid = false;
3103 	}
3104 
3105 
3106 	if (valid) {
3107 		env->insn_aux_data[insn_idx].ctx_field_size =
3108 			info.ctx_field_size;
3109 		return 0;
3110 	}
3111 
3112 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3113 		regno, reg_type_str(env, reg->type), off, size);
3114 
3115 	return -EACCES;
3116 }
3117 
is_pointer_value(struct bpf_verifier_env * env,int regno)3118 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3119 {
3120 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3121 }
3122 
is_ctx_reg(struct bpf_verifier_env * env,int regno)3123 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3124 {
3125 	const struct bpf_reg_state *reg = reg_state(env, regno);
3126 
3127 	return reg->type == PTR_TO_CTX;
3128 }
3129 
is_sk_reg(struct bpf_verifier_env * env,int regno)3130 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3131 {
3132 	const struct bpf_reg_state *reg = reg_state(env, regno);
3133 
3134 	return type_is_sk_pointer(reg->type);
3135 }
3136 
is_pkt_reg(struct bpf_verifier_env * env,int regno)3137 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3138 {
3139 	const struct bpf_reg_state *reg = reg_state(env, regno);
3140 
3141 	return type_is_pkt_pointer(reg->type);
3142 }
3143 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)3144 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3145 {
3146 	const struct bpf_reg_state *reg = reg_state(env, regno);
3147 
3148 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3149 	return reg->type == PTR_TO_FLOW_KEYS;
3150 }
3151 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)3152 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3153 				   const struct bpf_reg_state *reg,
3154 				   int off, int size, bool strict)
3155 {
3156 	struct tnum reg_off;
3157 	int ip_align;
3158 
3159 	/* Byte size accesses are always allowed. */
3160 	if (!strict || size == 1)
3161 		return 0;
3162 
3163 	/* For platforms that do not have a Kconfig enabling
3164 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3165 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3166 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3167 	 * to this code only in strict mode where we want to emulate
3168 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3169 	 * unconditional IP align value of '2'.
3170 	 */
3171 	ip_align = 2;
3172 
3173 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3174 	if (!tnum_is_aligned(reg_off, size)) {
3175 		char tn_buf[48];
3176 
3177 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3178 		verbose(env,
3179 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3180 			ip_align, tn_buf, reg->off, off, size);
3181 		return -EACCES;
3182 	}
3183 
3184 	return 0;
3185 }
3186 
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)3187 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3188 				       const struct bpf_reg_state *reg,
3189 				       const char *pointer_desc,
3190 				       int off, int size, bool strict)
3191 {
3192 	struct tnum reg_off;
3193 
3194 	/* Byte size accesses are always allowed. */
3195 	if (!strict || size == 1)
3196 		return 0;
3197 
3198 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3199 	if (!tnum_is_aligned(reg_off, size)) {
3200 		char tn_buf[48];
3201 
3202 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3203 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3204 			pointer_desc, tn_buf, reg->off, off, size);
3205 		return -EACCES;
3206 	}
3207 
3208 	return 0;
3209 }
3210 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)3211 static int check_ptr_alignment(struct bpf_verifier_env *env,
3212 			       const struct bpf_reg_state *reg, int off,
3213 			       int size, bool strict_alignment_once)
3214 {
3215 	bool strict = env->strict_alignment || strict_alignment_once;
3216 	const char *pointer_desc = "";
3217 
3218 	switch (reg->type) {
3219 	case PTR_TO_PACKET:
3220 	case PTR_TO_PACKET_META:
3221 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3222 		 * right in front, treat it the very same way.
3223 		 */
3224 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3225 	case PTR_TO_FLOW_KEYS:
3226 		pointer_desc = "flow keys ";
3227 		break;
3228 	case PTR_TO_MAP_VALUE:
3229 		pointer_desc = "value ";
3230 		break;
3231 	case PTR_TO_CTX:
3232 		pointer_desc = "context ";
3233 		break;
3234 	case PTR_TO_STACK:
3235 		pointer_desc = "stack ";
3236 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3237 		 * and check_stack_read_fixed_off() relies on stack accesses being
3238 		 * aligned.
3239 		 */
3240 		strict = true;
3241 		break;
3242 	case PTR_TO_SOCKET:
3243 		pointer_desc = "sock ";
3244 		break;
3245 	case PTR_TO_SOCK_COMMON:
3246 		pointer_desc = "sock_common ";
3247 		break;
3248 	case PTR_TO_TCP_SOCK:
3249 		pointer_desc = "tcp_sock ";
3250 		break;
3251 	case PTR_TO_XDP_SOCK:
3252 		pointer_desc = "xdp_sock ";
3253 		break;
3254 	default:
3255 		break;
3256 	}
3257 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3258 					   strict);
3259 }
3260 
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)3261 static int update_stack_depth(struct bpf_verifier_env *env,
3262 			      const struct bpf_func_state *func,
3263 			      int off)
3264 {
3265 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3266 
3267 	if (stack >= -off)
3268 		return 0;
3269 
3270 	/* update known max for given subprogram */
3271 	env->subprog_info[func->subprogno].stack_depth = -off;
3272 	return 0;
3273 }
3274 
3275 /* starting from main bpf function walk all instructions of the function
3276  * and recursively walk all callees that given function can call.
3277  * Ignore jump and exit insns.
3278  * Since recursion is prevented by check_cfg() this algorithm
3279  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3280  */
check_max_stack_depth(struct bpf_verifier_env * env)3281 static int check_max_stack_depth(struct bpf_verifier_env *env)
3282 {
3283 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3284 	struct bpf_subprog_info *subprog = env->subprog_info;
3285 	struct bpf_insn *insn = env->prog->insnsi;
3286 	bool tail_call_reachable = false;
3287 	int ret_insn[MAX_CALL_FRAMES];
3288 	int ret_prog[MAX_CALL_FRAMES];
3289 	int j;
3290 
3291 process_func:
3292 	/* protect against potential stack overflow that might happen when
3293 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3294 	 * depth for such case down to 256 so that the worst case scenario
3295 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3296 	 * 8k).
3297 	 *
3298 	 * To get the idea what might happen, see an example:
3299 	 * func1 -> sub rsp, 128
3300 	 *  subfunc1 -> sub rsp, 256
3301 	 *  tailcall1 -> add rsp, 256
3302 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3303 	 *   subfunc2 -> sub rsp, 64
3304 	 *   subfunc22 -> sub rsp, 128
3305 	 *   tailcall2 -> add rsp, 128
3306 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3307 	 *
3308 	 * tailcall will unwind the current stack frame but it will not get rid
3309 	 * of caller's stack as shown on the example above.
3310 	 */
3311 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3312 		verbose(env,
3313 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3314 			depth);
3315 		return -EACCES;
3316 	}
3317 	/* round up to 32-bytes, since this is granularity
3318 	 * of interpreter stack size
3319 	 */
3320 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3321 	if (depth > MAX_BPF_STACK) {
3322 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3323 			frame + 1, depth);
3324 		return -EACCES;
3325 	}
3326 continue_func:
3327 	subprog_end = subprog[idx + 1].start;
3328 	for (; i < subprog_end; i++) {
3329 		if (insn[i].code != (BPF_JMP | BPF_CALL))
3330 			continue;
3331 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
3332 			continue;
3333 		/* remember insn and function to return to */
3334 		ret_insn[frame] = i + 1;
3335 		ret_prog[frame] = idx;
3336 
3337 		/* find the callee */
3338 		i = i + insn[i].imm + 1;
3339 		idx = find_subprog(env, i);
3340 		if (idx < 0) {
3341 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3342 				  i);
3343 			return -EFAULT;
3344 		}
3345 
3346 		if (subprog[idx].has_tail_call)
3347 			tail_call_reachable = true;
3348 
3349 		frame++;
3350 		if (frame >= MAX_CALL_FRAMES) {
3351 			verbose(env, "the call stack of %d frames is too deep !\n",
3352 				frame);
3353 			return -E2BIG;
3354 		}
3355 		goto process_func;
3356 	}
3357 	/* if tail call got detected across bpf2bpf calls then mark each of the
3358 	 * currently present subprog frames as tail call reachable subprogs;
3359 	 * this info will be utilized by JIT so that we will be preserving the
3360 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3361 	 */
3362 	if (tail_call_reachable)
3363 		for (j = 0; j < frame; j++)
3364 			subprog[ret_prog[j]].tail_call_reachable = true;
3365 	if (subprog[0].tail_call_reachable)
3366 		env->prog->aux->tail_call_reachable = true;
3367 
3368 	/* end of for() loop means the last insn of the 'subprog'
3369 	 * was reached. Doesn't matter whether it was JA or EXIT
3370 	 */
3371 	if (frame == 0)
3372 		return 0;
3373 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3374 	frame--;
3375 	i = ret_insn[frame];
3376 	idx = ret_prog[frame];
3377 	goto continue_func;
3378 }
3379 
3380 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)3381 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3382 				  const struct bpf_insn *insn, int idx)
3383 {
3384 	int start = idx + insn->imm + 1, subprog;
3385 
3386 	subprog = find_subprog(env, start);
3387 	if (subprog < 0) {
3388 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3389 			  start);
3390 		return -EFAULT;
3391 	}
3392 	return env->subprog_info[subprog].stack_depth;
3393 }
3394 #endif
3395 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)3396 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3397 			       const struct bpf_reg_state *reg, int regno,
3398 			       bool fixed_off_ok)
3399 {
3400 	/* Access to this pointer-typed register or passing it to a helper
3401 	 * is only allowed in its original, unmodified form.
3402 	 */
3403 
3404 	if (!fixed_off_ok && reg->off) {
3405 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3406 			reg_type_str(env, reg->type), regno, reg->off);
3407 		return -EACCES;
3408 	}
3409 
3410 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3411 		char tn_buf[48];
3412 
3413 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3414 		verbose(env, "variable %s access var_off=%s disallowed\n",
3415 			reg_type_str(env, reg->type), tn_buf);
3416 		return -EACCES;
3417 	}
3418 
3419 	return 0;
3420 }
3421 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3422 int check_ptr_off_reg(struct bpf_verifier_env *env,
3423 		      const struct bpf_reg_state *reg, int regno)
3424 {
3425 	return __check_ptr_off_reg(env, reg, regno, false);
3426 }
3427 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)3428 static int __check_buffer_access(struct bpf_verifier_env *env,
3429 				 const char *buf_info,
3430 				 const struct bpf_reg_state *reg,
3431 				 int regno, int off, int size)
3432 {
3433 	if (off < 0) {
3434 		verbose(env,
3435 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3436 			regno, buf_info, off, size);
3437 		return -EACCES;
3438 	}
3439 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3440 		char tn_buf[48];
3441 
3442 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3443 		verbose(env,
3444 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3445 			regno, off, tn_buf);
3446 		return -EACCES;
3447 	}
3448 
3449 	return 0;
3450 }
3451 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)3452 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3453 				  const struct bpf_reg_state *reg,
3454 				  int regno, int off, int size)
3455 {
3456 	int err;
3457 
3458 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3459 	if (err)
3460 		return err;
3461 
3462 	if (off + size > env->prog->aux->max_tp_access)
3463 		env->prog->aux->max_tp_access = off + size;
3464 
3465 	return 0;
3466 }
3467 
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)3468 static int check_buffer_access(struct bpf_verifier_env *env,
3469 			       const struct bpf_reg_state *reg,
3470 			       int regno, int off, int size,
3471 			       bool zero_size_allowed,
3472 			       const char *buf_info,
3473 			       u32 *max_access)
3474 {
3475 	int err;
3476 
3477 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3478 	if (err)
3479 		return err;
3480 
3481 	if (off + size > *max_access)
3482 		*max_access = off + size;
3483 
3484 	return 0;
3485 }
3486 
3487 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)3488 static void zext_32_to_64(struct bpf_reg_state *reg)
3489 {
3490 	reg->var_off = tnum_subreg(reg->var_off);
3491 	__reg_assign_32_into_64(reg);
3492 }
3493 
3494 /* truncate register to smaller size (in bytes)
3495  * must be called with size < BPF_REG_SIZE
3496  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)3497 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3498 {
3499 	u64 mask;
3500 
3501 	/* clear high bits in bit representation */
3502 	reg->var_off = tnum_cast(reg->var_off, size);
3503 
3504 	/* fix arithmetic bounds */
3505 	mask = ((u64)1 << (size * 8)) - 1;
3506 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3507 		reg->umin_value &= mask;
3508 		reg->umax_value &= mask;
3509 	} else {
3510 		reg->umin_value = 0;
3511 		reg->umax_value = mask;
3512 	}
3513 	reg->smin_value = reg->umin_value;
3514 	reg->smax_value = reg->umax_value;
3515 
3516 	/* If size is smaller than 32bit register the 32bit register
3517 	 * values are also truncated so we push 64-bit bounds into
3518 	 * 32-bit bounds. Above were truncated < 32-bits already.
3519 	 */
3520 	if (size >= 4)
3521 		return;
3522 	__reg_combine_64_into_32(reg);
3523 }
3524 
bpf_map_is_rdonly(const struct bpf_map * map)3525 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3526 {
3527 	/* A map is considered read-only if the following condition are true:
3528 	 *
3529 	 * 1) BPF program side cannot change any of the map content. The
3530 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3531 	 *    and was set at map creation time.
3532 	 * 2) The map value(s) have been initialized from user space by a
3533 	 *    loader and then "frozen", such that no new map update/delete
3534 	 *    operations from syscall side are possible for the rest of
3535 	 *    the map's lifetime from that point onwards.
3536 	 * 3) Any parallel/pending map update/delete operations from syscall
3537 	 *    side have been completed. Only after that point, it's safe to
3538 	 *    assume that map value(s) are immutable.
3539 	 */
3540 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
3541 	       READ_ONCE(map->frozen) &&
3542 	       !bpf_map_write_active(map);
3543 }
3544 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)3545 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3546 {
3547 	void *ptr;
3548 	u64 addr;
3549 	int err;
3550 
3551 	err = map->ops->map_direct_value_addr(map, &addr, off);
3552 	if (err)
3553 		return err;
3554 	ptr = (void *)(long)addr + off;
3555 
3556 	switch (size) {
3557 	case sizeof(u8):
3558 		*val = (u64)*(u8 *)ptr;
3559 		break;
3560 	case sizeof(u16):
3561 		*val = (u64)*(u16 *)ptr;
3562 		break;
3563 	case sizeof(u32):
3564 		*val = (u64)*(u32 *)ptr;
3565 		break;
3566 	case sizeof(u64):
3567 		*val = *(u64 *)ptr;
3568 		break;
3569 	default:
3570 		return -EINVAL;
3571 	}
3572 	return 0;
3573 }
3574 
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)3575 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3576 				   struct bpf_reg_state *regs,
3577 				   int regno, int off, int size,
3578 				   enum bpf_access_type atype,
3579 				   int value_regno)
3580 {
3581 	struct bpf_reg_state *reg = regs + regno;
3582 	const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3583 	const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3584 	u32 btf_id;
3585 	int ret;
3586 
3587 	if (off < 0) {
3588 		verbose(env,
3589 			"R%d is ptr_%s invalid negative access: off=%d\n",
3590 			regno, tname, off);
3591 		return -EACCES;
3592 	}
3593 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3594 		char tn_buf[48];
3595 
3596 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3597 		verbose(env,
3598 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3599 			regno, tname, off, tn_buf);
3600 		return -EACCES;
3601 	}
3602 
3603 	if (env->ops->btf_struct_access) {
3604 		ret = env->ops->btf_struct_access(&env->log, t, off, size,
3605 						  atype, &btf_id);
3606 	} else {
3607 		if (atype != BPF_READ) {
3608 			verbose(env, "only read is supported\n");
3609 			return -EACCES;
3610 		}
3611 
3612 		ret = btf_struct_access(&env->log, t, off, size, atype,
3613 					&btf_id);
3614 	}
3615 
3616 	if (ret < 0)
3617 		return ret;
3618 
3619 	if (atype == BPF_READ && value_regno >= 0)
3620 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3621 
3622 	return 0;
3623 }
3624 
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)3625 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3626 				   struct bpf_reg_state *regs,
3627 				   int regno, int off, int size,
3628 				   enum bpf_access_type atype,
3629 				   int value_regno)
3630 {
3631 	struct bpf_reg_state *reg = regs + regno;
3632 	struct bpf_map *map = reg->map_ptr;
3633 	const struct btf_type *t;
3634 	const char *tname;
3635 	u32 btf_id;
3636 	int ret;
3637 
3638 	if (!btf_vmlinux) {
3639 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3640 		return -ENOTSUPP;
3641 	}
3642 
3643 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3644 		verbose(env, "map_ptr access not supported for map type %d\n",
3645 			map->map_type);
3646 		return -ENOTSUPP;
3647 	}
3648 
3649 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3650 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3651 
3652 	if (!env->allow_ptr_to_map_access) {
3653 		verbose(env,
3654 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3655 			tname);
3656 		return -EPERM;
3657 	}
3658 
3659 	if (off < 0) {
3660 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
3661 			regno, tname, off);
3662 		return -EACCES;
3663 	}
3664 
3665 	if (atype != BPF_READ) {
3666 		verbose(env, "only read from %s is supported\n", tname);
3667 		return -EACCES;
3668 	}
3669 
3670 	ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3671 	if (ret < 0)
3672 		return ret;
3673 
3674 	if (value_regno >= 0)
3675 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3676 
3677 	return 0;
3678 }
3679 
3680 /* Check that the stack access at the given offset is within bounds. The
3681  * maximum valid offset is -1.
3682  *
3683  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3684  * -state->allocated_stack for reads.
3685  */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)3686 static int check_stack_slot_within_bounds(int off,
3687 					  struct bpf_func_state *state,
3688 					  enum bpf_access_type t)
3689 {
3690 	int min_valid_off;
3691 
3692 	if (t == BPF_WRITE)
3693 		min_valid_off = -MAX_BPF_STACK;
3694 	else
3695 		min_valid_off = -state->allocated_stack;
3696 
3697 	if (off < min_valid_off || off > -1)
3698 		return -EACCES;
3699 	return 0;
3700 }
3701 
3702 /* Check that the stack access at 'regno + off' falls within the maximum stack
3703  * bounds.
3704  *
3705  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3706  */
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)3707 static int check_stack_access_within_bounds(
3708 		struct bpf_verifier_env *env,
3709 		int regno, int off, int access_size,
3710 		enum stack_access_src src, enum bpf_access_type type)
3711 {
3712 	struct bpf_reg_state *regs = cur_regs(env);
3713 	struct bpf_reg_state *reg = regs + regno;
3714 	struct bpf_func_state *state = func(env, reg);
3715 	int min_off, max_off;
3716 	int err;
3717 	char *err_extra;
3718 
3719 	if (src == ACCESS_HELPER)
3720 		/* We don't know if helpers are reading or writing (or both). */
3721 		err_extra = " indirect access to";
3722 	else if (type == BPF_READ)
3723 		err_extra = " read from";
3724 	else
3725 		err_extra = " write to";
3726 
3727 	if (tnum_is_const(reg->var_off)) {
3728 		min_off = reg->var_off.value + off;
3729 		if (access_size > 0)
3730 			max_off = min_off + access_size - 1;
3731 		else
3732 			max_off = min_off;
3733 	} else {
3734 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3735 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
3736 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3737 				err_extra, regno);
3738 			return -EACCES;
3739 		}
3740 		min_off = reg->smin_value + off;
3741 		if (access_size > 0)
3742 			max_off = reg->smax_value + off + access_size - 1;
3743 		else
3744 			max_off = min_off;
3745 	}
3746 
3747 	err = check_stack_slot_within_bounds(min_off, state, type);
3748 	if (!err)
3749 		err = check_stack_slot_within_bounds(max_off, state, type);
3750 
3751 	if (err) {
3752 		if (tnum_is_const(reg->var_off)) {
3753 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3754 				err_extra, regno, off, access_size);
3755 		} else {
3756 			char tn_buf[48];
3757 
3758 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3759 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3760 				err_extra, regno, tn_buf, access_size);
3761 		}
3762 	}
3763 	return err;
3764 }
3765 
3766 /* check whether memory at (regno + off) is accessible for t = (read | write)
3767  * if t==write, value_regno is a register which value is stored into memory
3768  * if t==read, value_regno is a register which will receive the value from memory
3769  * if t==write && value_regno==-1, some unknown value is stored into memory
3770  * if t==read && value_regno==-1, don't care what we read from memory
3771  */
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)3772 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3773 			    int off, int bpf_size, enum bpf_access_type t,
3774 			    int value_regno, bool strict_alignment_once)
3775 {
3776 	struct bpf_reg_state *regs = cur_regs(env);
3777 	struct bpf_reg_state *reg = regs + regno;
3778 	struct bpf_func_state *state;
3779 	int size, err = 0;
3780 
3781 	size = bpf_size_to_bytes(bpf_size);
3782 	if (size < 0)
3783 		return size;
3784 
3785 	/* alignment checks will add in reg->off themselves */
3786 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3787 	if (err)
3788 		return err;
3789 
3790 	/* for access checks, reg->off is just part of off */
3791 	off += reg->off;
3792 
3793 	if (reg->type == PTR_TO_MAP_VALUE) {
3794 		if (t == BPF_WRITE && value_regno >= 0 &&
3795 		    is_pointer_value(env, value_regno)) {
3796 			verbose(env, "R%d leaks addr into map\n", value_regno);
3797 			return -EACCES;
3798 		}
3799 		err = check_map_access_type(env, regno, off, size, t);
3800 		if (err)
3801 			return err;
3802 		err = check_map_access(env, regno, off, size, false);
3803 		if (!err && t == BPF_READ && value_regno >= 0) {
3804 			struct bpf_map *map = reg->map_ptr;
3805 
3806 			/* if map is read-only, track its contents as scalars */
3807 			if (tnum_is_const(reg->var_off) &&
3808 			    bpf_map_is_rdonly(map) &&
3809 			    map->ops->map_direct_value_addr) {
3810 				int map_off = off + reg->var_off.value;
3811 				u64 val = 0;
3812 
3813 				err = bpf_map_direct_read(map, map_off, size,
3814 							  &val);
3815 				if (err)
3816 					return err;
3817 
3818 				regs[value_regno].type = SCALAR_VALUE;
3819 				__mark_reg_known(&regs[value_regno], val);
3820 			} else {
3821 				mark_reg_unknown(env, regs, value_regno);
3822 			}
3823 		}
3824 	} else if (base_type(reg->type) == PTR_TO_MEM) {
3825 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
3826 
3827 		if (type_may_be_null(reg->type)) {
3828 			verbose(env, "R%d invalid mem access '%s'\n", regno,
3829 				reg_type_str(env, reg->type));
3830 			return -EACCES;
3831 		}
3832 
3833 		if (t == BPF_WRITE && rdonly_mem) {
3834 			verbose(env, "R%d cannot write into %s\n",
3835 				regno, reg_type_str(env, reg->type));
3836 			return -EACCES;
3837 		}
3838 
3839 		if (t == BPF_WRITE && value_regno >= 0 &&
3840 		    is_pointer_value(env, value_regno)) {
3841 			verbose(env, "R%d leaks addr into mem\n", value_regno);
3842 			return -EACCES;
3843 		}
3844 
3845 		err = check_mem_region_access(env, regno, off, size,
3846 					      reg->mem_size, false);
3847 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
3848 			mark_reg_unknown(env, regs, value_regno);
3849 	} else if (reg->type == PTR_TO_CTX) {
3850 		enum bpf_reg_type reg_type = SCALAR_VALUE;
3851 		u32 btf_id = 0;
3852 
3853 		if (t == BPF_WRITE && value_regno >= 0 &&
3854 		    is_pointer_value(env, value_regno)) {
3855 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
3856 			return -EACCES;
3857 		}
3858 
3859 		err = check_ptr_off_reg(env, reg, regno);
3860 		if (err < 0)
3861 			return err;
3862 
3863 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3864 		if (err)
3865 			verbose_linfo(env, insn_idx, "; ");
3866 		if (!err && t == BPF_READ && value_regno >= 0) {
3867 			/* ctx access returns either a scalar, or a
3868 			 * PTR_TO_PACKET[_META,_END]. In the latter
3869 			 * case, we know the offset is zero.
3870 			 */
3871 			if (reg_type == SCALAR_VALUE) {
3872 				mark_reg_unknown(env, regs, value_regno);
3873 			} else {
3874 				mark_reg_known_zero(env, regs,
3875 						    value_regno);
3876 				if (type_may_be_null(reg_type))
3877 					regs[value_regno].id = ++env->id_gen;
3878 				/* A load of ctx field could have different
3879 				 * actual load size with the one encoded in the
3880 				 * insn. When the dst is PTR, it is for sure not
3881 				 * a sub-register.
3882 				 */
3883 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3884 				if (base_type(reg_type) == PTR_TO_BTF_ID)
3885 					regs[value_regno].btf_id = btf_id;
3886 			}
3887 			regs[value_regno].type = reg_type;
3888 		}
3889 
3890 	} else if (reg->type == PTR_TO_STACK) {
3891 		/* Basic bounds checks. */
3892 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3893 		if (err)
3894 			return err;
3895 
3896 		state = func(env, reg);
3897 		err = update_stack_depth(env, state, off);
3898 		if (err)
3899 			return err;
3900 
3901 		if (t == BPF_READ)
3902 			err = check_stack_read(env, regno, off, size,
3903 					       value_regno);
3904 		else
3905 			err = check_stack_write(env, regno, off, size,
3906 						value_regno, insn_idx);
3907 	} else if (reg_is_pkt_pointer(reg)) {
3908 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3909 			verbose(env, "cannot write into packet\n");
3910 			return -EACCES;
3911 		}
3912 		if (t == BPF_WRITE && value_regno >= 0 &&
3913 		    is_pointer_value(env, value_regno)) {
3914 			verbose(env, "R%d leaks addr into packet\n",
3915 				value_regno);
3916 			return -EACCES;
3917 		}
3918 		err = check_packet_access(env, regno, off, size, false);
3919 		if (!err && t == BPF_READ && value_regno >= 0)
3920 			mark_reg_unknown(env, regs, value_regno);
3921 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
3922 		if (t == BPF_WRITE && value_regno >= 0 &&
3923 		    is_pointer_value(env, value_regno)) {
3924 			verbose(env, "R%d leaks addr into flow keys\n",
3925 				value_regno);
3926 			return -EACCES;
3927 		}
3928 
3929 		err = check_flow_keys_access(env, off, size);
3930 		if (!err && t == BPF_READ && value_regno >= 0)
3931 			mark_reg_unknown(env, regs, value_regno);
3932 	} else if (type_is_sk_pointer(reg->type)) {
3933 		if (t == BPF_WRITE) {
3934 			verbose(env, "R%d cannot write into %s\n",
3935 				regno, reg_type_str(env, reg->type));
3936 			return -EACCES;
3937 		}
3938 		err = check_sock_access(env, insn_idx, regno, off, size, t);
3939 		if (!err && value_regno >= 0)
3940 			mark_reg_unknown(env, regs, value_regno);
3941 	} else if (reg->type == PTR_TO_TP_BUFFER) {
3942 		err = check_tp_buffer_access(env, reg, regno, off, size);
3943 		if (!err && t == BPF_READ && value_regno >= 0)
3944 			mark_reg_unknown(env, regs, value_regno);
3945 	} else if (reg->type == PTR_TO_BTF_ID) {
3946 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3947 					      value_regno);
3948 	} else if (reg->type == CONST_PTR_TO_MAP) {
3949 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3950 					      value_regno);
3951 	} else if (base_type(reg->type) == PTR_TO_BUF) {
3952 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
3953 		const char *buf_info;
3954 		u32 *max_access;
3955 
3956 		if (rdonly_mem) {
3957 			if (t == BPF_WRITE) {
3958 				verbose(env, "R%d cannot write into %s\n",
3959 						regno, reg_type_str(env, reg->type));
3960 				return -EACCES;
3961 			}
3962 			buf_info = "rdonly";
3963 			max_access = &env->prog->aux->max_rdonly_access;
3964 		} else {
3965 			buf_info = "rdwr";
3966 			max_access = &env->prog->aux->max_rdwr_access;
3967 		}
3968 
3969 		err = check_buffer_access(env, reg, regno, off, size, false,
3970 					  buf_info, max_access);
3971 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
3972 			mark_reg_unknown(env, regs, value_regno);
3973 	} else {
3974 		verbose(env, "R%d invalid mem access '%s'\n", regno,
3975 			reg_type_str(env, reg->type));
3976 		return -EACCES;
3977 	}
3978 
3979 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3980 	    regs[value_regno].type == SCALAR_VALUE) {
3981 		/* b/h/w load zero-extends, mark upper bits as known 0 */
3982 		coerce_reg_to_size(&regs[value_regno], size);
3983 	}
3984 	return err;
3985 }
3986 
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)3987 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3988 {
3989 	int err;
3990 
3991 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3992 	    insn->imm != 0) {
3993 		verbose(env, "BPF_XADD uses reserved fields\n");
3994 		return -EINVAL;
3995 	}
3996 
3997 	/* check src1 operand */
3998 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
3999 	if (err)
4000 		return err;
4001 
4002 	/* check src2 operand */
4003 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4004 	if (err)
4005 		return err;
4006 
4007 	if (is_pointer_value(env, insn->src_reg)) {
4008 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4009 		return -EACCES;
4010 	}
4011 
4012 	if (is_ctx_reg(env, insn->dst_reg) ||
4013 	    is_pkt_reg(env, insn->dst_reg) ||
4014 	    is_flow_key_reg(env, insn->dst_reg) ||
4015 	    is_sk_reg(env, insn->dst_reg)) {
4016 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
4017 			insn->dst_reg,
4018 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4019 		return -EACCES;
4020 	}
4021 
4022 	/* check whether atomic_add can read the memory */
4023 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4024 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4025 	if (err)
4026 		return err;
4027 
4028 	/* check whether atomic_add can write into the same memory */
4029 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4030 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4031 }
4032 
4033 /* When register 'regno' is used to read the stack (either directly or through
4034  * a helper function) make sure that it's within stack boundary and, depending
4035  * on the access type, that all elements of the stack are initialized.
4036  *
4037  * 'off' includes 'regno->off', but not its dynamic part (if any).
4038  *
4039  * All registers that have been spilled on the stack in the slots within the
4040  * read offsets are marked as read.
4041  */
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)4042 static int check_stack_range_initialized(
4043 		struct bpf_verifier_env *env, int regno, int off,
4044 		int access_size, bool zero_size_allowed,
4045 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4046 {
4047 	struct bpf_reg_state *reg = reg_state(env, regno);
4048 	struct bpf_func_state *state = func(env, reg);
4049 	int err, min_off, max_off, i, j, slot, spi;
4050 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4051 	enum bpf_access_type bounds_check_type;
4052 	/* Some accesses can write anything into the stack, others are
4053 	 * read-only.
4054 	 */
4055 	bool clobber = false;
4056 
4057 	if (access_size == 0 && !zero_size_allowed) {
4058 		verbose(env, "invalid zero-sized read\n");
4059 		return -EACCES;
4060 	}
4061 
4062 	if (type == ACCESS_HELPER) {
4063 		/* The bounds checks for writes are more permissive than for
4064 		 * reads. However, if raw_mode is not set, we'll do extra
4065 		 * checks below.
4066 		 */
4067 		bounds_check_type = BPF_WRITE;
4068 		clobber = true;
4069 	} else {
4070 		bounds_check_type = BPF_READ;
4071 	}
4072 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4073 					       type, bounds_check_type);
4074 	if (err)
4075 		return err;
4076 
4077 
4078 	if (tnum_is_const(reg->var_off)) {
4079 		min_off = max_off = reg->var_off.value + off;
4080 	} else {
4081 		/* Variable offset is prohibited for unprivileged mode for
4082 		 * simplicity since it requires corresponding support in
4083 		 * Spectre masking for stack ALU.
4084 		 * See also retrieve_ptr_limit().
4085 		 */
4086 		if (!env->bypass_spec_v1) {
4087 			char tn_buf[48];
4088 
4089 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4090 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4091 				regno, err_extra, tn_buf);
4092 			return -EACCES;
4093 		}
4094 		/* Only initialized buffer on stack is allowed to be accessed
4095 		 * with variable offset. With uninitialized buffer it's hard to
4096 		 * guarantee that whole memory is marked as initialized on
4097 		 * helper return since specific bounds are unknown what may
4098 		 * cause uninitialized stack leaking.
4099 		 */
4100 		if (meta && meta->raw_mode)
4101 			meta = NULL;
4102 
4103 		min_off = reg->smin_value + off;
4104 		max_off = reg->smax_value + off;
4105 	}
4106 
4107 	if (meta && meta->raw_mode) {
4108 		meta->access_size = access_size;
4109 		meta->regno = regno;
4110 		return 0;
4111 	}
4112 
4113 	for (i = min_off; i < max_off + access_size; i++) {
4114 		u8 *stype;
4115 
4116 		slot = -i - 1;
4117 		spi = slot / BPF_REG_SIZE;
4118 		if (state->allocated_stack <= slot)
4119 			goto err;
4120 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4121 		if (*stype == STACK_MISC)
4122 			goto mark;
4123 		if (*stype == STACK_ZERO) {
4124 			if (clobber) {
4125 				/* helper can write anything into the stack */
4126 				*stype = STACK_MISC;
4127 			}
4128 			goto mark;
4129 		}
4130 
4131 		if (is_spilled_reg(&state->stack[spi]) &&
4132 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4133 			goto mark;
4134 
4135 		if (is_spilled_reg(&state->stack[spi]) &&
4136 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4137 		     env->allow_ptr_leaks)) {
4138 			if (clobber) {
4139 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4140 				for (j = 0; j < BPF_REG_SIZE; j++)
4141 					state->stack[spi].slot_type[j] = STACK_MISC;
4142 			}
4143 			goto mark;
4144 		}
4145 
4146 err:
4147 		if (tnum_is_const(reg->var_off)) {
4148 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4149 				err_extra, regno, min_off, i - min_off, access_size);
4150 		} else {
4151 			char tn_buf[48];
4152 
4153 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4154 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4155 				err_extra, regno, tn_buf, i - min_off, access_size);
4156 		}
4157 		return -EACCES;
4158 mark:
4159 		/* reading any byte out of 8-byte 'spill_slot' will cause
4160 		 * the whole slot to be marked as 'read'
4161 		 */
4162 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4163 			      state->stack[spi].spilled_ptr.parent,
4164 			      REG_LIVE_READ64);
4165 	}
4166 	return update_stack_depth(env, state, min_off);
4167 }
4168 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)4169 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4170 				   int access_size, bool zero_size_allowed,
4171 				   struct bpf_call_arg_meta *meta)
4172 {
4173 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4174 	const char *buf_info;
4175 	u32 *max_access;
4176 
4177 	switch (base_type(reg->type)) {
4178 	case PTR_TO_PACKET:
4179 	case PTR_TO_PACKET_META:
4180 		return check_packet_access(env, regno, reg->off, access_size,
4181 					   zero_size_allowed);
4182 	case PTR_TO_MAP_VALUE:
4183 		if (check_map_access_type(env, regno, reg->off, access_size,
4184 					  meta && meta->raw_mode ? BPF_WRITE :
4185 					  BPF_READ))
4186 			return -EACCES;
4187 		return check_map_access(env, regno, reg->off, access_size,
4188 					zero_size_allowed);
4189 	case PTR_TO_MEM:
4190 		return check_mem_region_access(env, regno, reg->off,
4191 					       access_size, reg->mem_size,
4192 					       zero_size_allowed);
4193 	case PTR_TO_BUF:
4194 		if (type_is_rdonly_mem(reg->type)) {
4195 			if (meta && meta->raw_mode)
4196 				return -EACCES;
4197 
4198 			buf_info = "rdonly";
4199 			max_access = &env->prog->aux->max_rdonly_access;
4200 		} else {
4201 			buf_info = "rdwr";
4202 			max_access = &env->prog->aux->max_rdwr_access;
4203 		}
4204 		return check_buffer_access(env, reg, regno, reg->off,
4205 					   access_size, zero_size_allowed,
4206 					   buf_info, max_access);
4207 	case PTR_TO_STACK:
4208 		return check_stack_range_initialized(
4209 				env,
4210 				regno, reg->off, access_size,
4211 				zero_size_allowed, ACCESS_HELPER, meta);
4212 	default: /* scalar_value or invalid ptr */
4213 		/* Allow zero-byte read from NULL, regardless of pointer type */
4214 		if (zero_size_allowed && access_size == 0 &&
4215 		    register_is_null(reg))
4216 			return 0;
4217 
4218 		verbose(env, "R%d type=%s ", regno,
4219 			reg_type_str(env, reg->type));
4220 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4221 		return -EACCES;
4222 	}
4223 }
4224 
4225 /* Implementation details:
4226  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4227  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4228  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4229  * value_or_null->value transition, since the verifier only cares about
4230  * the range of access to valid map value pointer and doesn't care about actual
4231  * address of the map element.
4232  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4233  * reg->id > 0 after value_or_null->value transition. By doing so
4234  * two bpf_map_lookups will be considered two different pointers that
4235  * point to different bpf_spin_locks.
4236  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4237  * dead-locks.
4238  * Since only one bpf_spin_lock is allowed the checks are simpler than
4239  * reg_is_refcounted() logic. The verifier needs to remember only
4240  * one spin_lock instead of array of acquired_refs.
4241  * cur_state->active_spin_lock remembers which map value element got locked
4242  * and clears it after bpf_spin_unlock.
4243  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)4244 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4245 			     bool is_lock)
4246 {
4247 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4248 	struct bpf_verifier_state *cur = env->cur_state;
4249 	bool is_const = tnum_is_const(reg->var_off);
4250 	struct bpf_map *map = reg->map_ptr;
4251 	u64 val = reg->var_off.value;
4252 
4253 	if (!is_const) {
4254 		verbose(env,
4255 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4256 			regno);
4257 		return -EINVAL;
4258 	}
4259 	if (!map->btf) {
4260 		verbose(env,
4261 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4262 			map->name);
4263 		return -EINVAL;
4264 	}
4265 	if (!map_value_has_spin_lock(map)) {
4266 		if (map->spin_lock_off == -E2BIG)
4267 			verbose(env,
4268 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4269 				map->name);
4270 		else if (map->spin_lock_off == -ENOENT)
4271 			verbose(env,
4272 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4273 				map->name);
4274 		else
4275 			verbose(env,
4276 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4277 				map->name);
4278 		return -EINVAL;
4279 	}
4280 	if (map->spin_lock_off != val + reg->off) {
4281 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4282 			val + reg->off);
4283 		return -EINVAL;
4284 	}
4285 	if (is_lock) {
4286 		if (cur->active_spin_lock) {
4287 			verbose(env,
4288 				"Locking two bpf_spin_locks are not allowed\n");
4289 			return -EINVAL;
4290 		}
4291 		cur->active_spin_lock = reg->id;
4292 	} else {
4293 		if (!cur->active_spin_lock) {
4294 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4295 			return -EINVAL;
4296 		}
4297 		if (cur->active_spin_lock != reg->id) {
4298 			verbose(env, "bpf_spin_unlock of different lock\n");
4299 			return -EINVAL;
4300 		}
4301 		cur->active_spin_lock = 0;
4302 	}
4303 	return 0;
4304 }
4305 
arg_type_is_mem_ptr(enum bpf_arg_type type)4306 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4307 {
4308 	return base_type(type) == ARG_PTR_TO_MEM ||
4309 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
4310 }
4311 
arg_type_is_mem_size(enum bpf_arg_type type)4312 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4313 {
4314 	return type == ARG_CONST_SIZE ||
4315 	       type == ARG_CONST_SIZE_OR_ZERO;
4316 }
4317 
arg_type_is_alloc_size(enum bpf_arg_type type)4318 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4319 {
4320 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4321 }
4322 
arg_type_is_int_ptr(enum bpf_arg_type type)4323 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4324 {
4325 	return type == ARG_PTR_TO_INT ||
4326 	       type == ARG_PTR_TO_LONG;
4327 }
4328 
int_ptr_type_to_size(enum bpf_arg_type type)4329 static int int_ptr_type_to_size(enum bpf_arg_type type)
4330 {
4331 	if (type == ARG_PTR_TO_INT)
4332 		return sizeof(u32);
4333 	else if (type == ARG_PTR_TO_LONG)
4334 		return sizeof(u64);
4335 
4336 	return -EINVAL;
4337 }
4338 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)4339 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4340 				 const struct bpf_call_arg_meta *meta,
4341 				 enum bpf_arg_type *arg_type)
4342 {
4343 	if (!meta->map_ptr) {
4344 		/* kernel subsystem misconfigured verifier */
4345 		verbose(env, "invalid map_ptr to access map->type\n");
4346 		return -EACCES;
4347 	}
4348 
4349 	switch (meta->map_ptr->map_type) {
4350 	case BPF_MAP_TYPE_SOCKMAP:
4351 	case BPF_MAP_TYPE_SOCKHASH:
4352 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4353 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4354 		} else {
4355 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4356 			return -EINVAL;
4357 		}
4358 		break;
4359 
4360 	default:
4361 		break;
4362 	}
4363 	return 0;
4364 }
4365 
4366 struct bpf_reg_types {
4367 	const enum bpf_reg_type types[10];
4368 	u32 *btf_id;
4369 };
4370 
4371 static const struct bpf_reg_types map_key_value_types = {
4372 	.types = {
4373 		PTR_TO_STACK,
4374 		PTR_TO_PACKET,
4375 		PTR_TO_PACKET_META,
4376 		PTR_TO_MAP_VALUE,
4377 	},
4378 };
4379 
4380 static const struct bpf_reg_types sock_types = {
4381 	.types = {
4382 		PTR_TO_SOCK_COMMON,
4383 		PTR_TO_SOCKET,
4384 		PTR_TO_TCP_SOCK,
4385 		PTR_TO_XDP_SOCK,
4386 	},
4387 };
4388 
4389 #ifdef CONFIG_NET
4390 static const struct bpf_reg_types btf_id_sock_common_types = {
4391 	.types = {
4392 		PTR_TO_SOCK_COMMON,
4393 		PTR_TO_SOCKET,
4394 		PTR_TO_TCP_SOCK,
4395 		PTR_TO_XDP_SOCK,
4396 		PTR_TO_BTF_ID,
4397 	},
4398 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4399 };
4400 #endif
4401 
4402 static const struct bpf_reg_types mem_types = {
4403 	.types = {
4404 		PTR_TO_STACK,
4405 		PTR_TO_PACKET,
4406 		PTR_TO_PACKET_META,
4407 		PTR_TO_MAP_VALUE,
4408 		PTR_TO_MEM,
4409 		PTR_TO_MEM | MEM_ALLOC,
4410 		PTR_TO_BUF,
4411 	},
4412 };
4413 
4414 static const struct bpf_reg_types int_ptr_types = {
4415 	.types = {
4416 		PTR_TO_STACK,
4417 		PTR_TO_PACKET,
4418 		PTR_TO_PACKET_META,
4419 		PTR_TO_MAP_VALUE,
4420 	},
4421 };
4422 
4423 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4424 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4425 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4426 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
4427 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4428 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4429 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4430 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4431 
4432 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4433 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4434 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4435 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4436 	[ARG_CONST_SIZE]		= &scalar_types,
4437 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4438 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4439 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4440 	[ARG_PTR_TO_CTX]		= &context_types,
4441 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4442 #ifdef CONFIG_NET
4443 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4444 #endif
4445 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4446 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4447 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4448 	[ARG_PTR_TO_MEM]		= &mem_types,
4449 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4450 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4451 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4452 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4453 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4454 };
4455 
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id)4456 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4457 			  enum bpf_arg_type arg_type,
4458 			  const u32 *arg_btf_id)
4459 {
4460 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4461 	enum bpf_reg_type expected, type = reg->type;
4462 	const struct bpf_reg_types *compatible;
4463 	int i, j;
4464 
4465 	compatible = compatible_reg_types[base_type(arg_type)];
4466 	if (!compatible) {
4467 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4468 		return -EFAULT;
4469 	}
4470 
4471 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
4472 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
4473 	 *
4474 	 * Same for MAYBE_NULL:
4475 	 *
4476 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
4477 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
4478 	 *
4479 	 * Therefore we fold these flags depending on the arg_type before comparison.
4480 	 */
4481 	if (arg_type & MEM_RDONLY)
4482 		type &= ~MEM_RDONLY;
4483 	if (arg_type & PTR_MAYBE_NULL)
4484 		type &= ~PTR_MAYBE_NULL;
4485 
4486 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4487 		expected = compatible->types[i];
4488 		if (expected == NOT_INIT)
4489 			break;
4490 
4491 		if (type == expected)
4492 			goto found;
4493 	}
4494 
4495 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
4496 	for (j = 0; j + 1 < i; j++)
4497 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
4498 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
4499 	return -EACCES;
4500 
4501 found:
4502 	if (reg->type == PTR_TO_BTF_ID) {
4503 		if (!arg_btf_id) {
4504 			if (!compatible->btf_id) {
4505 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4506 				return -EFAULT;
4507 			}
4508 			arg_btf_id = compatible->btf_id;
4509 		}
4510 
4511 		if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4512 					  *arg_btf_id)) {
4513 			verbose(env, "R%d is of type %s but %s is expected\n",
4514 				regno, kernel_type_name(reg->btf_id),
4515 				kernel_type_name(*arg_btf_id));
4516 			return -EACCES;
4517 		}
4518 	}
4519 
4520 	return 0;
4521 }
4522 
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)4523 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4524 			  struct bpf_call_arg_meta *meta,
4525 			  const struct bpf_func_proto *fn)
4526 {
4527 	u32 regno = BPF_REG_1 + arg;
4528 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4529 	enum bpf_arg_type arg_type = fn->arg_type[arg];
4530 	enum bpf_reg_type type = reg->type;
4531 	int err = 0;
4532 
4533 	if (arg_type == ARG_DONTCARE)
4534 		return 0;
4535 
4536 	err = check_reg_arg(env, regno, SRC_OP);
4537 	if (err)
4538 		return err;
4539 
4540 	if (arg_type == ARG_ANYTHING) {
4541 		if (is_pointer_value(env, regno)) {
4542 			verbose(env, "R%d leaks addr into helper function\n",
4543 				regno);
4544 			return -EACCES;
4545 		}
4546 		return 0;
4547 	}
4548 
4549 	if (type_is_pkt_pointer(type) &&
4550 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4551 		verbose(env, "helper access to the packet is not allowed\n");
4552 		return -EACCES;
4553 	}
4554 
4555 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
4556 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4557 		err = resolve_map_arg_type(env, meta, &arg_type);
4558 		if (err)
4559 			return err;
4560 	}
4561 
4562 	if (register_is_null(reg) && type_may_be_null(arg_type))
4563 		/* A NULL register has a SCALAR_VALUE type, so skip
4564 		 * type checking.
4565 		 */
4566 		goto skip_type_check;
4567 
4568 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4569 	if (err)
4570 		return err;
4571 
4572 	switch ((u32)type) {
4573 	case SCALAR_VALUE:
4574 	/* Pointer types where reg offset is explicitly allowed: */
4575 	case PTR_TO_PACKET:
4576 	case PTR_TO_PACKET_META:
4577 	case PTR_TO_MAP_VALUE:
4578 	case PTR_TO_MEM:
4579 	case PTR_TO_MEM | MEM_RDONLY:
4580 	case PTR_TO_MEM | MEM_ALLOC:
4581 	case PTR_TO_BUF:
4582 	case PTR_TO_BUF | MEM_RDONLY:
4583 	case PTR_TO_STACK:
4584 		/* Some of the argument types nevertheless require a
4585 		 * zero register offset.
4586 		 */
4587 		if (arg_type == ARG_PTR_TO_ALLOC_MEM)
4588 			goto force_off_check;
4589 		break;
4590 	/* All the rest must be rejected: */
4591 	default:
4592 force_off_check:
4593 		err = __check_ptr_off_reg(env, reg, regno,
4594 					  type == PTR_TO_BTF_ID);
4595 		if (err < 0)
4596 			return err;
4597 		break;
4598 	}
4599 
4600 skip_type_check:
4601 	if (reg->ref_obj_id) {
4602 		if (meta->ref_obj_id) {
4603 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4604 				regno, reg->ref_obj_id,
4605 				meta->ref_obj_id);
4606 			return -EFAULT;
4607 		}
4608 		meta->ref_obj_id = reg->ref_obj_id;
4609 	}
4610 
4611 	if (arg_type == ARG_CONST_MAP_PTR) {
4612 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4613 		meta->map_ptr = reg->map_ptr;
4614 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4615 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
4616 		 * check that [key, key + map->key_size) are within
4617 		 * stack limits and initialized
4618 		 */
4619 		if (!meta->map_ptr) {
4620 			/* in function declaration map_ptr must come before
4621 			 * map_key, so that it's verified and known before
4622 			 * we have to check map_key here. Otherwise it means
4623 			 * that kernel subsystem misconfigured verifier
4624 			 */
4625 			verbose(env, "invalid map_ptr to access map->key\n");
4626 			return -EACCES;
4627 		}
4628 		err = check_helper_mem_access(env, regno,
4629 					      meta->map_ptr->key_size, false,
4630 					      NULL);
4631 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
4632 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4633 		if (type_may_be_null(arg_type) && register_is_null(reg))
4634 			return 0;
4635 
4636 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
4637 		 * check [value, value + map->value_size) validity
4638 		 */
4639 		if (!meta->map_ptr) {
4640 			/* kernel subsystem misconfigured verifier */
4641 			verbose(env, "invalid map_ptr to access map->value\n");
4642 			return -EACCES;
4643 		}
4644 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4645 		err = check_helper_mem_access(env, regno,
4646 					      meta->map_ptr->value_size, false,
4647 					      meta);
4648 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4649 		if (!reg->btf_id) {
4650 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4651 			return -EACCES;
4652 		}
4653 		meta->ret_btf_id = reg->btf_id;
4654 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4655 		if (meta->func_id == BPF_FUNC_spin_lock) {
4656 			if (process_spin_lock(env, regno, true))
4657 				return -EACCES;
4658 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
4659 			if (process_spin_lock(env, regno, false))
4660 				return -EACCES;
4661 		} else {
4662 			verbose(env, "verifier internal error\n");
4663 			return -EFAULT;
4664 		}
4665 	} else if (arg_type_is_mem_ptr(arg_type)) {
4666 		/* The access to this pointer is only checked when we hit the
4667 		 * next is_mem_size argument below.
4668 		 */
4669 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4670 	} else if (arg_type_is_mem_size(arg_type)) {
4671 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4672 
4673 		/* This is used to refine r0 return value bounds for helpers
4674 		 * that enforce this value as an upper bound on return values.
4675 		 * See do_refine_retval_range() for helpers that can refine
4676 		 * the return value. C type of helper is u32 so we pull register
4677 		 * bound from umax_value however, if negative verifier errors
4678 		 * out. Only upper bounds can be learned because retval is an
4679 		 * int type and negative retvals are allowed.
4680 		 */
4681 		meta->msize_max_value = reg->umax_value;
4682 
4683 		/* The register is SCALAR_VALUE; the access check
4684 		 * happens using its boundaries.
4685 		 */
4686 		if (!tnum_is_const(reg->var_off))
4687 			/* For unprivileged variable accesses, disable raw
4688 			 * mode so that the program is required to
4689 			 * initialize all the memory that the helper could
4690 			 * just partially fill up.
4691 			 */
4692 			meta = NULL;
4693 
4694 		if (reg->smin_value < 0) {
4695 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4696 				regno);
4697 			return -EACCES;
4698 		}
4699 
4700 		if (reg->umin_value == 0) {
4701 			err = check_helper_mem_access(env, regno - 1, 0,
4702 						      zero_size_allowed,
4703 						      meta);
4704 			if (err)
4705 				return err;
4706 		}
4707 
4708 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4709 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4710 				regno);
4711 			return -EACCES;
4712 		}
4713 		err = check_helper_mem_access(env, regno - 1,
4714 					      reg->umax_value,
4715 					      zero_size_allowed, meta);
4716 		if (!err)
4717 			err = mark_chain_precision(env, regno);
4718 	} else if (arg_type_is_alloc_size(arg_type)) {
4719 		if (!tnum_is_const(reg->var_off)) {
4720 			verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4721 				regno);
4722 			return -EACCES;
4723 		}
4724 		meta->mem_size = reg->var_off.value;
4725 	} else if (arg_type_is_int_ptr(arg_type)) {
4726 		int size = int_ptr_type_to_size(arg_type);
4727 
4728 		err = check_helper_mem_access(env, regno, size, false, meta);
4729 		if (err)
4730 			return err;
4731 		err = check_ptr_alignment(env, reg, 0, size, true);
4732 	}
4733 
4734 	return err;
4735 }
4736 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)4737 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4738 {
4739 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
4740 	enum bpf_prog_type type = resolve_prog_type(env->prog);
4741 
4742 	if (func_id != BPF_FUNC_map_update_elem)
4743 		return false;
4744 
4745 	/* It's not possible to get access to a locked struct sock in these
4746 	 * contexts, so updating is safe.
4747 	 */
4748 	switch (type) {
4749 	case BPF_PROG_TYPE_TRACING:
4750 		if (eatype == BPF_TRACE_ITER)
4751 			return true;
4752 		break;
4753 	case BPF_PROG_TYPE_SOCKET_FILTER:
4754 	case BPF_PROG_TYPE_SCHED_CLS:
4755 	case BPF_PROG_TYPE_SCHED_ACT:
4756 	case BPF_PROG_TYPE_XDP:
4757 	case BPF_PROG_TYPE_SK_REUSEPORT:
4758 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4759 	case BPF_PROG_TYPE_SK_LOOKUP:
4760 		return true;
4761 	default:
4762 		break;
4763 	}
4764 
4765 	verbose(env, "cannot update sockmap in this context\n");
4766 	return false;
4767 }
4768 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)4769 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4770 {
4771 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4772 }
4773 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)4774 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4775 					struct bpf_map *map, int func_id)
4776 {
4777 	if (!map)
4778 		return 0;
4779 
4780 	/* We need a two way check, first is from map perspective ... */
4781 	switch (map->map_type) {
4782 	case BPF_MAP_TYPE_PROG_ARRAY:
4783 		if (func_id != BPF_FUNC_tail_call)
4784 			goto error;
4785 		break;
4786 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4787 		if (func_id != BPF_FUNC_perf_event_read &&
4788 		    func_id != BPF_FUNC_perf_event_output &&
4789 		    func_id != BPF_FUNC_skb_output &&
4790 		    func_id != BPF_FUNC_perf_event_read_value &&
4791 		    func_id != BPF_FUNC_xdp_output)
4792 			goto error;
4793 		break;
4794 	case BPF_MAP_TYPE_RINGBUF:
4795 		if (func_id != BPF_FUNC_ringbuf_output &&
4796 		    func_id != BPF_FUNC_ringbuf_reserve &&
4797 		    func_id != BPF_FUNC_ringbuf_query)
4798 			goto error;
4799 		break;
4800 	case BPF_MAP_TYPE_STACK_TRACE:
4801 		if (func_id != BPF_FUNC_get_stackid)
4802 			goto error;
4803 		break;
4804 	case BPF_MAP_TYPE_CGROUP_ARRAY:
4805 		if (func_id != BPF_FUNC_skb_under_cgroup &&
4806 		    func_id != BPF_FUNC_current_task_under_cgroup)
4807 			goto error;
4808 		break;
4809 	case BPF_MAP_TYPE_CGROUP_STORAGE:
4810 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4811 		if (func_id != BPF_FUNC_get_local_storage)
4812 			goto error;
4813 		break;
4814 	case BPF_MAP_TYPE_DEVMAP:
4815 	case BPF_MAP_TYPE_DEVMAP_HASH:
4816 		if (func_id != BPF_FUNC_redirect_map &&
4817 		    func_id != BPF_FUNC_map_lookup_elem)
4818 			goto error;
4819 		break;
4820 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
4821 	 * appear.
4822 	 */
4823 	case BPF_MAP_TYPE_CPUMAP:
4824 		if (func_id != BPF_FUNC_redirect_map)
4825 			goto error;
4826 		break;
4827 	case BPF_MAP_TYPE_XSKMAP:
4828 		if (func_id != BPF_FUNC_redirect_map &&
4829 		    func_id != BPF_FUNC_map_lookup_elem)
4830 			goto error;
4831 		break;
4832 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4833 	case BPF_MAP_TYPE_HASH_OF_MAPS:
4834 		if (func_id != BPF_FUNC_map_lookup_elem)
4835 			goto error;
4836 		break;
4837 	case BPF_MAP_TYPE_SOCKMAP:
4838 		if (func_id != BPF_FUNC_sk_redirect_map &&
4839 		    func_id != BPF_FUNC_sock_map_update &&
4840 		    func_id != BPF_FUNC_map_delete_elem &&
4841 		    func_id != BPF_FUNC_msg_redirect_map &&
4842 		    func_id != BPF_FUNC_sk_select_reuseport &&
4843 		    func_id != BPF_FUNC_map_lookup_elem &&
4844 		    !may_update_sockmap(env, func_id))
4845 			goto error;
4846 		break;
4847 	case BPF_MAP_TYPE_SOCKHASH:
4848 		if (func_id != BPF_FUNC_sk_redirect_hash &&
4849 		    func_id != BPF_FUNC_sock_hash_update &&
4850 		    func_id != BPF_FUNC_map_delete_elem &&
4851 		    func_id != BPF_FUNC_msg_redirect_hash &&
4852 		    func_id != BPF_FUNC_sk_select_reuseport &&
4853 		    func_id != BPF_FUNC_map_lookup_elem &&
4854 		    !may_update_sockmap(env, func_id))
4855 			goto error;
4856 		break;
4857 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4858 		if (func_id != BPF_FUNC_sk_select_reuseport)
4859 			goto error;
4860 		break;
4861 	case BPF_MAP_TYPE_QUEUE:
4862 	case BPF_MAP_TYPE_STACK:
4863 		if (func_id != BPF_FUNC_map_peek_elem &&
4864 		    func_id != BPF_FUNC_map_pop_elem &&
4865 		    func_id != BPF_FUNC_map_push_elem)
4866 			goto error;
4867 		break;
4868 	case BPF_MAP_TYPE_SK_STORAGE:
4869 		if (func_id != BPF_FUNC_sk_storage_get &&
4870 		    func_id != BPF_FUNC_sk_storage_delete)
4871 			goto error;
4872 		break;
4873 	case BPF_MAP_TYPE_INODE_STORAGE:
4874 		if (func_id != BPF_FUNC_inode_storage_get &&
4875 		    func_id != BPF_FUNC_inode_storage_delete)
4876 			goto error;
4877 		break;
4878 	default:
4879 		break;
4880 	}
4881 
4882 	/* ... and second from the function itself. */
4883 	switch (func_id) {
4884 	case BPF_FUNC_tail_call:
4885 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4886 			goto error;
4887 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4888 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4889 			return -EINVAL;
4890 		}
4891 		break;
4892 	case BPF_FUNC_perf_event_read:
4893 	case BPF_FUNC_perf_event_output:
4894 	case BPF_FUNC_perf_event_read_value:
4895 	case BPF_FUNC_skb_output:
4896 	case BPF_FUNC_xdp_output:
4897 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4898 			goto error;
4899 		break;
4900 	case BPF_FUNC_ringbuf_output:
4901 	case BPF_FUNC_ringbuf_reserve:
4902 	case BPF_FUNC_ringbuf_query:
4903 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
4904 			goto error;
4905 		break;
4906 	case BPF_FUNC_get_stackid:
4907 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4908 			goto error;
4909 		break;
4910 	case BPF_FUNC_current_task_under_cgroup:
4911 	case BPF_FUNC_skb_under_cgroup:
4912 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4913 			goto error;
4914 		break;
4915 	case BPF_FUNC_redirect_map:
4916 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4917 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4918 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
4919 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
4920 			goto error;
4921 		break;
4922 	case BPF_FUNC_sk_redirect_map:
4923 	case BPF_FUNC_msg_redirect_map:
4924 	case BPF_FUNC_sock_map_update:
4925 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4926 			goto error;
4927 		break;
4928 	case BPF_FUNC_sk_redirect_hash:
4929 	case BPF_FUNC_msg_redirect_hash:
4930 	case BPF_FUNC_sock_hash_update:
4931 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4932 			goto error;
4933 		break;
4934 	case BPF_FUNC_get_local_storage:
4935 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4936 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4937 			goto error;
4938 		break;
4939 	case BPF_FUNC_sk_select_reuseport:
4940 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4941 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4942 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
4943 			goto error;
4944 		break;
4945 	case BPF_FUNC_map_peek_elem:
4946 	case BPF_FUNC_map_pop_elem:
4947 	case BPF_FUNC_map_push_elem:
4948 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4949 		    map->map_type != BPF_MAP_TYPE_STACK)
4950 			goto error;
4951 		break;
4952 	case BPF_FUNC_sk_storage_get:
4953 	case BPF_FUNC_sk_storage_delete:
4954 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4955 			goto error;
4956 		break;
4957 	case BPF_FUNC_inode_storage_get:
4958 	case BPF_FUNC_inode_storage_delete:
4959 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4960 			goto error;
4961 		break;
4962 	default:
4963 		break;
4964 	}
4965 
4966 	return 0;
4967 error:
4968 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
4969 		map->map_type, func_id_name(func_id), func_id);
4970 	return -EINVAL;
4971 }
4972 
check_raw_mode_ok(const struct bpf_func_proto * fn)4973 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4974 {
4975 	int count = 0;
4976 
4977 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4978 		count++;
4979 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4980 		count++;
4981 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4982 		count++;
4983 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4984 		count++;
4985 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4986 		count++;
4987 
4988 	/* We only support one arg being in raw mode at the moment,
4989 	 * which is sufficient for the helper functions we have
4990 	 * right now.
4991 	 */
4992 	return count <= 1;
4993 }
4994 
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)4995 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4996 				    enum bpf_arg_type arg_next)
4997 {
4998 	return (arg_type_is_mem_ptr(arg_curr) &&
4999 	        !arg_type_is_mem_size(arg_next)) ||
5000 	       (!arg_type_is_mem_ptr(arg_curr) &&
5001 		arg_type_is_mem_size(arg_next));
5002 }
5003 
check_arg_pair_ok(const struct bpf_func_proto * fn)5004 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5005 {
5006 	/* bpf_xxx(..., buf, len) call will access 'len'
5007 	 * bytes from memory 'buf'. Both arg types need
5008 	 * to be paired, so make sure there's no buggy
5009 	 * helper function specification.
5010 	 */
5011 	if (arg_type_is_mem_size(fn->arg1_type) ||
5012 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5013 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5014 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5015 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5016 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5017 		return false;
5018 
5019 	return true;
5020 }
5021 
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5022 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5023 {
5024 	int count = 0;
5025 
5026 	if (arg_type_may_be_refcounted(fn->arg1_type))
5027 		count++;
5028 	if (arg_type_may_be_refcounted(fn->arg2_type))
5029 		count++;
5030 	if (arg_type_may_be_refcounted(fn->arg3_type))
5031 		count++;
5032 	if (arg_type_may_be_refcounted(fn->arg4_type))
5033 		count++;
5034 	if (arg_type_may_be_refcounted(fn->arg5_type))
5035 		count++;
5036 
5037 	/* A reference acquiring function cannot acquire
5038 	 * another refcounted ptr.
5039 	 */
5040 	if (may_be_acquire_function(func_id) && count)
5041 		return false;
5042 
5043 	/* We only support one arg being unreferenced at the moment,
5044 	 * which is sufficient for the helper functions we have right now.
5045 	 */
5046 	return count <= 1;
5047 }
5048 
check_btf_id_ok(const struct bpf_func_proto * fn)5049 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5050 {
5051 	int i;
5052 
5053 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5054 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5055 			return false;
5056 
5057 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5058 			return false;
5059 	}
5060 
5061 	return true;
5062 }
5063 
check_func_proto(const struct bpf_func_proto * fn,int func_id)5064 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5065 {
5066 	return check_raw_mode_ok(fn) &&
5067 	       check_arg_pair_ok(fn) &&
5068 	       check_btf_id_ok(fn) &&
5069 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5070 }
5071 
5072 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5073  * are now invalid, so turn them into unknown SCALAR_VALUE.
5074  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5075 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5076 {
5077 	struct bpf_func_state *state;
5078 	struct bpf_reg_state *reg;
5079 
5080 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5081 		if (reg_is_pkt_pointer_any(reg))
5082 			__mark_reg_unknown(env, reg);
5083 	}));
5084 }
5085 
5086 enum {
5087 	AT_PKT_END = -1,
5088 	BEYOND_PKT_END = -2,
5089 };
5090 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5091 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5092 {
5093 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5094 	struct bpf_reg_state *reg = &state->regs[regn];
5095 
5096 	if (reg->type != PTR_TO_PACKET)
5097 		/* PTR_TO_PACKET_META is not supported yet */
5098 		return;
5099 
5100 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5101 	 * How far beyond pkt_end it goes is unknown.
5102 	 * if (!range_open) it's the case of pkt >= pkt_end
5103 	 * if (range_open) it's the case of pkt > pkt_end
5104 	 * hence this pointer is at least 1 byte bigger than pkt_end
5105 	 */
5106 	if (range_open)
5107 		reg->range = BEYOND_PKT_END;
5108 	else
5109 		reg->range = AT_PKT_END;
5110 }
5111 
5112 /* The pointer with the specified id has released its reference to kernel
5113  * resources. Identify all copies of the same pointer and clear the reference.
5114  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5115 static int release_reference(struct bpf_verifier_env *env,
5116 			     int ref_obj_id)
5117 {
5118 	struct bpf_func_state *state;
5119 	struct bpf_reg_state *reg;
5120 	int err;
5121 
5122 	err = release_reference_state(cur_func(env), ref_obj_id);
5123 	if (err)
5124 		return err;
5125 
5126 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5127 		if (reg->ref_obj_id == ref_obj_id) {
5128 			if (!env->allow_ptr_leaks)
5129 				__mark_reg_not_init(env, reg);
5130 			else
5131 				__mark_reg_unknown(env, reg);
5132 		}
5133 	}));
5134 
5135 	return 0;
5136 }
5137 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5138 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5139 				    struct bpf_reg_state *regs)
5140 {
5141 	int i;
5142 
5143 	/* after the call registers r0 - r5 were scratched */
5144 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5145 		mark_reg_not_init(env, regs, caller_saved[i]);
5146 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5147 	}
5148 }
5149 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)5150 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5151 			   int *insn_idx)
5152 {
5153 	struct bpf_verifier_state *state = env->cur_state;
5154 	struct bpf_func_info_aux *func_info_aux;
5155 	struct bpf_func_state *caller, *callee;
5156 	int i, err, subprog, target_insn;
5157 	bool is_global = false;
5158 
5159 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5160 		verbose(env, "the call stack of %d frames is too deep\n",
5161 			state->curframe + 2);
5162 		return -E2BIG;
5163 	}
5164 
5165 	target_insn = *insn_idx + insn->imm;
5166 	subprog = find_subprog(env, target_insn + 1);
5167 	if (subprog < 0) {
5168 		verbose(env, "verifier bug. No program starts at insn %d\n",
5169 			target_insn + 1);
5170 		return -EFAULT;
5171 	}
5172 
5173 	caller = state->frame[state->curframe];
5174 	if (state->frame[state->curframe + 1]) {
5175 		verbose(env, "verifier bug. Frame %d already allocated\n",
5176 			state->curframe + 1);
5177 		return -EFAULT;
5178 	}
5179 
5180 	func_info_aux = env->prog->aux->func_info_aux;
5181 	if (func_info_aux)
5182 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5183 	err = btf_check_func_arg_match(env, subprog, caller->regs);
5184 	if (err == -EFAULT)
5185 		return err;
5186 	if (is_global) {
5187 		if (err) {
5188 			verbose(env, "Caller passes invalid args into func#%d\n",
5189 				subprog);
5190 			return err;
5191 		} else {
5192 			if (env->log.level & BPF_LOG_LEVEL)
5193 				verbose(env,
5194 					"Func#%d is global and valid. Skipping.\n",
5195 					subprog);
5196 			clear_caller_saved_regs(env, caller->regs);
5197 
5198 			/* All global functions return a 64-bit SCALAR_VALUE */
5199 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5200 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5201 
5202 			/* continue with next insn after call */
5203 			return 0;
5204 		}
5205 	}
5206 
5207 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5208 	if (!callee)
5209 		return -ENOMEM;
5210 	state->frame[state->curframe + 1] = callee;
5211 
5212 	/* callee cannot access r0, r6 - r9 for reading and has to write
5213 	 * into its own stack before reading from it.
5214 	 * callee can read/write into caller's stack
5215 	 */
5216 	init_func_state(env, callee,
5217 			/* remember the callsite, it will be used by bpf_exit */
5218 			*insn_idx /* callsite */,
5219 			state->curframe + 1 /* frameno within this callchain */,
5220 			subprog /* subprog number within this prog */);
5221 
5222 	/* Transfer references to the callee */
5223 	err = transfer_reference_state(callee, caller);
5224 	if (err)
5225 		return err;
5226 
5227 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5228 	 * pointers, which connects us up to the liveness chain
5229 	 */
5230 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5231 		callee->regs[i] = caller->regs[i];
5232 
5233 	clear_caller_saved_regs(env, caller->regs);
5234 
5235 	/* only increment it after check_reg_arg() finished */
5236 	state->curframe++;
5237 
5238 	/* and go analyze first insn of the callee */
5239 	*insn_idx = target_insn;
5240 
5241 	if (env->log.level & BPF_LOG_LEVEL) {
5242 		verbose(env, "caller:\n");
5243 		print_verifier_state(env, caller);
5244 		verbose(env, "callee:\n");
5245 		print_verifier_state(env, callee);
5246 	}
5247 	return 0;
5248 }
5249 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)5250 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5251 {
5252 	struct bpf_verifier_state *state = env->cur_state;
5253 	struct bpf_func_state *caller, *callee;
5254 	struct bpf_reg_state *r0;
5255 	int err;
5256 
5257 	callee = state->frame[state->curframe];
5258 	r0 = &callee->regs[BPF_REG_0];
5259 	if (r0->type == PTR_TO_STACK) {
5260 		/* technically it's ok to return caller's stack pointer
5261 		 * (or caller's caller's pointer) back to the caller,
5262 		 * since these pointers are valid. Only current stack
5263 		 * pointer will be invalid as soon as function exits,
5264 		 * but let's be conservative
5265 		 */
5266 		verbose(env, "cannot return stack pointer to the caller\n");
5267 		return -EINVAL;
5268 	}
5269 
5270 	state->curframe--;
5271 	caller = state->frame[state->curframe];
5272 	/* return to the caller whatever r0 had in the callee */
5273 	caller->regs[BPF_REG_0] = *r0;
5274 
5275 	/* Transfer references to the caller */
5276 	err = transfer_reference_state(caller, callee);
5277 	if (err)
5278 		return err;
5279 
5280 	*insn_idx = callee->callsite + 1;
5281 	if (env->log.level & BPF_LOG_LEVEL) {
5282 		verbose(env, "returning from callee:\n");
5283 		print_verifier_state(env, callee);
5284 		verbose(env, "to caller at %d:\n", *insn_idx);
5285 		print_verifier_state(env, caller);
5286 	}
5287 	/* clear everything in the callee */
5288 	free_func_state(callee);
5289 	state->frame[state->curframe + 1] = NULL;
5290 	return 0;
5291 }
5292 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)5293 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5294 				   int func_id,
5295 				   struct bpf_call_arg_meta *meta)
5296 {
5297 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5298 
5299 	if (ret_type != RET_INTEGER ||
5300 	    (func_id != BPF_FUNC_get_stack &&
5301 	     func_id != BPF_FUNC_probe_read_str &&
5302 	     func_id != BPF_FUNC_probe_read_kernel_str &&
5303 	     func_id != BPF_FUNC_probe_read_user_str))
5304 		return;
5305 
5306 	ret_reg->smax_value = meta->msize_max_value;
5307 	ret_reg->s32_max_value = meta->msize_max_value;
5308 	ret_reg->smin_value = -MAX_ERRNO;
5309 	ret_reg->s32_min_value = -MAX_ERRNO;
5310 	reg_bounds_sync(ret_reg);
5311 }
5312 
5313 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5314 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5315 		int func_id, int insn_idx)
5316 {
5317 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5318 	struct bpf_map *map = meta->map_ptr;
5319 
5320 	if (func_id != BPF_FUNC_tail_call &&
5321 	    func_id != BPF_FUNC_map_lookup_elem &&
5322 	    func_id != BPF_FUNC_map_update_elem &&
5323 	    func_id != BPF_FUNC_map_delete_elem &&
5324 	    func_id != BPF_FUNC_map_push_elem &&
5325 	    func_id != BPF_FUNC_map_pop_elem &&
5326 	    func_id != BPF_FUNC_map_peek_elem)
5327 		return 0;
5328 
5329 	if (map == NULL) {
5330 		verbose(env, "kernel subsystem misconfigured verifier\n");
5331 		return -EINVAL;
5332 	}
5333 
5334 	/* In case of read-only, some additional restrictions
5335 	 * need to be applied in order to prevent altering the
5336 	 * state of the map from program side.
5337 	 */
5338 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5339 	    (func_id == BPF_FUNC_map_delete_elem ||
5340 	     func_id == BPF_FUNC_map_update_elem ||
5341 	     func_id == BPF_FUNC_map_push_elem ||
5342 	     func_id == BPF_FUNC_map_pop_elem)) {
5343 		verbose(env, "write into map forbidden\n");
5344 		return -EACCES;
5345 	}
5346 
5347 	if (!BPF_MAP_PTR(aux->map_ptr_state))
5348 		bpf_map_ptr_store(aux, meta->map_ptr,
5349 				  !meta->map_ptr->bypass_spec_v1);
5350 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5351 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5352 				  !meta->map_ptr->bypass_spec_v1);
5353 	return 0;
5354 }
5355 
5356 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5357 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5358 		int func_id, int insn_idx)
5359 {
5360 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5361 	struct bpf_reg_state *regs = cur_regs(env), *reg;
5362 	struct bpf_map *map = meta->map_ptr;
5363 	u64 val, max;
5364 	int err;
5365 
5366 	if (func_id != BPF_FUNC_tail_call)
5367 		return 0;
5368 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5369 		verbose(env, "kernel subsystem misconfigured verifier\n");
5370 		return -EINVAL;
5371 	}
5372 
5373 	reg = &regs[BPF_REG_3];
5374 	val = reg->var_off.value;
5375 	max = map->max_entries;
5376 
5377 	if (!(register_is_const(reg) && val < max)) {
5378 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5379 		return 0;
5380 	}
5381 
5382 	err = mark_chain_precision(env, BPF_REG_3);
5383 	if (err)
5384 		return err;
5385 	if (bpf_map_key_unseen(aux))
5386 		bpf_map_key_store(aux, val);
5387 	else if (!bpf_map_key_poisoned(aux) &&
5388 		  bpf_map_key_immediate(aux) != val)
5389 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5390 	return 0;
5391 }
5392 
check_reference_leak(struct bpf_verifier_env * env)5393 static int check_reference_leak(struct bpf_verifier_env *env)
5394 {
5395 	struct bpf_func_state *state = cur_func(env);
5396 	int i;
5397 
5398 	for (i = 0; i < state->acquired_refs; i++) {
5399 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5400 			state->refs[i].id, state->refs[i].insn_idx);
5401 	}
5402 	return state->acquired_refs ? -EINVAL : 0;
5403 }
5404 
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)5405 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5406 {
5407 	const struct bpf_func_proto *fn = NULL;
5408 	enum bpf_return_type ret_type;
5409 	enum bpf_type_flag ret_flag;
5410 	struct bpf_reg_state *regs;
5411 	struct bpf_call_arg_meta meta;
5412 	bool changes_data;
5413 	int i, err;
5414 
5415 	/* find function prototype */
5416 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5417 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5418 			func_id);
5419 		return -EINVAL;
5420 	}
5421 
5422 	if (env->ops->get_func_proto)
5423 		fn = env->ops->get_func_proto(func_id, env->prog);
5424 	if (!fn) {
5425 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5426 			func_id);
5427 		return -EINVAL;
5428 	}
5429 
5430 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5431 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5432 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5433 		return -EINVAL;
5434 	}
5435 
5436 	if (fn->allowed && !fn->allowed(env->prog)) {
5437 		verbose(env, "helper call is not allowed in probe\n");
5438 		return -EINVAL;
5439 	}
5440 
5441 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5442 	changes_data = bpf_helper_changes_pkt_data(fn->func);
5443 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5444 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5445 			func_id_name(func_id), func_id);
5446 		return -EINVAL;
5447 	}
5448 
5449 	memset(&meta, 0, sizeof(meta));
5450 	meta.pkt_access = fn->pkt_access;
5451 
5452 	err = check_func_proto(fn, func_id);
5453 	if (err) {
5454 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5455 			func_id_name(func_id), func_id);
5456 		return err;
5457 	}
5458 
5459 	meta.func_id = func_id;
5460 	/* check args */
5461 	for (i = 0; i < 5; i++) {
5462 		err = check_func_arg(env, i, &meta, fn);
5463 		if (err)
5464 			return err;
5465 	}
5466 
5467 	err = record_func_map(env, &meta, func_id, insn_idx);
5468 	if (err)
5469 		return err;
5470 
5471 	err = record_func_key(env, &meta, func_id, insn_idx);
5472 	if (err)
5473 		return err;
5474 
5475 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5476 	 * is inferred from register state.
5477 	 */
5478 	for (i = 0; i < meta.access_size; i++) {
5479 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5480 				       BPF_WRITE, -1, false);
5481 		if (err)
5482 			return err;
5483 	}
5484 
5485 	if (func_id == BPF_FUNC_tail_call) {
5486 		err = check_reference_leak(env);
5487 		if (err) {
5488 			verbose(env, "tail_call would lead to reference leak\n");
5489 			return err;
5490 		}
5491 	} else if (is_release_function(func_id)) {
5492 		err = release_reference(env, meta.ref_obj_id);
5493 		if (err) {
5494 			verbose(env, "func %s#%d reference has not been acquired before\n",
5495 				func_id_name(func_id), func_id);
5496 			return err;
5497 		}
5498 	}
5499 
5500 	regs = cur_regs(env);
5501 
5502 	/* check that flags argument in get_local_storage(map, flags) is 0,
5503 	 * this is required because get_local_storage() can't return an error.
5504 	 */
5505 	if (func_id == BPF_FUNC_get_local_storage &&
5506 	    !register_is_null(&regs[BPF_REG_2])) {
5507 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5508 		return -EINVAL;
5509 	}
5510 
5511 	/* reset caller saved regs */
5512 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5513 		mark_reg_not_init(env, regs, caller_saved[i]);
5514 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5515 	}
5516 
5517 	/* helper call returns 64-bit value. */
5518 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5519 
5520 	/* update return register (already marked as written above) */
5521 	ret_type = fn->ret_type;
5522 	ret_flag = type_flag(fn->ret_type);
5523 	if (ret_type == RET_INTEGER) {
5524 		/* sets type to SCALAR_VALUE */
5525 		mark_reg_unknown(env, regs, BPF_REG_0);
5526 	} else if (ret_type == RET_VOID) {
5527 		regs[BPF_REG_0].type = NOT_INIT;
5528 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
5529 		/* There is no offset yet applied, variable or fixed */
5530 		mark_reg_known_zero(env, regs, BPF_REG_0);
5531 		/* remember map_ptr, so that check_map_access()
5532 		 * can check 'value_size' boundary of memory access
5533 		 * to map element returned from bpf_map_lookup_elem()
5534 		 */
5535 		if (meta.map_ptr == NULL) {
5536 			verbose(env,
5537 				"kernel subsystem misconfigured verifier\n");
5538 			return -EINVAL;
5539 		}
5540 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
5541 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
5542 		if (!type_may_be_null(ret_type) &&
5543 		    map_value_has_spin_lock(meta.map_ptr)) {
5544 			regs[BPF_REG_0].id = ++env->id_gen;
5545 		}
5546 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
5547 		mark_reg_known_zero(env, regs, BPF_REG_0);
5548 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
5549 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
5550 		mark_reg_known_zero(env, regs, BPF_REG_0);
5551 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
5552 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
5553 		mark_reg_known_zero(env, regs, BPF_REG_0);
5554 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
5555 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
5556 		mark_reg_known_zero(env, regs, BPF_REG_0);
5557 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5558 		regs[BPF_REG_0].mem_size = meta.mem_size;
5559 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
5560 		const struct btf_type *t;
5561 
5562 		mark_reg_known_zero(env, regs, BPF_REG_0);
5563 		t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5564 		if (!btf_type_is_struct(t)) {
5565 			u32 tsize;
5566 			const struct btf_type *ret;
5567 			const char *tname;
5568 
5569 			/* resolve the type size of ksym. */
5570 			ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5571 			if (IS_ERR(ret)) {
5572 				tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5573 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
5574 					tname, PTR_ERR(ret));
5575 				return -EINVAL;
5576 			}
5577 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5578 			regs[BPF_REG_0].mem_size = tsize;
5579 		} else {
5580 			/* MEM_RDONLY may be carried from ret_flag, but it
5581 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
5582 			 * it will confuse the check of PTR_TO_BTF_ID in
5583 			 * check_mem_access().
5584 			 */
5585 			ret_flag &= ~MEM_RDONLY;
5586 
5587 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5588 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5589 		}
5590 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
5591 		int ret_btf_id;
5592 
5593 		mark_reg_known_zero(env, regs, BPF_REG_0);
5594 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5595 		ret_btf_id = *fn->ret_btf_id;
5596 		if (ret_btf_id == 0) {
5597 			verbose(env, "invalid return type %u of func %s#%d\n",
5598 				base_type(ret_type), func_id_name(func_id),
5599 				func_id);
5600 			return -EINVAL;
5601 		}
5602 		regs[BPF_REG_0].btf_id = ret_btf_id;
5603 	} else {
5604 		verbose(env, "unknown return type %u of func %s#%d\n",
5605 			base_type(ret_type), func_id_name(func_id), func_id);
5606 		return -EINVAL;
5607 	}
5608 
5609 	if (type_may_be_null(regs[BPF_REG_0].type))
5610 		regs[BPF_REG_0].id = ++env->id_gen;
5611 
5612 	if (is_ptr_cast_function(func_id)) {
5613 		/* For release_reference() */
5614 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5615 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
5616 		int id = acquire_reference_state(env, insn_idx);
5617 
5618 		if (id < 0)
5619 			return id;
5620 		/* For mark_ptr_or_null_reg() */
5621 		regs[BPF_REG_0].id = id;
5622 		/* For release_reference() */
5623 		regs[BPF_REG_0].ref_obj_id = id;
5624 	}
5625 
5626 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5627 
5628 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5629 	if (err)
5630 		return err;
5631 
5632 	if ((func_id == BPF_FUNC_get_stack ||
5633 	     func_id == BPF_FUNC_get_task_stack) &&
5634 	    !env->prog->has_callchain_buf) {
5635 		const char *err_str;
5636 
5637 #ifdef CONFIG_PERF_EVENTS
5638 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
5639 		err_str = "cannot get callchain buffer for func %s#%d\n";
5640 #else
5641 		err = -ENOTSUPP;
5642 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5643 #endif
5644 		if (err) {
5645 			verbose(env, err_str, func_id_name(func_id), func_id);
5646 			return err;
5647 		}
5648 
5649 		env->prog->has_callchain_buf = true;
5650 	}
5651 
5652 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5653 		env->prog->call_get_stack = true;
5654 
5655 	if (changes_data)
5656 		clear_all_pkt_pointers(env);
5657 	return 0;
5658 }
5659 
signed_add_overflows(s64 a,s64 b)5660 static bool signed_add_overflows(s64 a, s64 b)
5661 {
5662 	/* Do the add in u64, where overflow is well-defined */
5663 	s64 res = (s64)((u64)a + (u64)b);
5664 
5665 	if (b < 0)
5666 		return res > a;
5667 	return res < a;
5668 }
5669 
signed_add32_overflows(s32 a,s32 b)5670 static bool signed_add32_overflows(s32 a, s32 b)
5671 {
5672 	/* Do the add in u32, where overflow is well-defined */
5673 	s32 res = (s32)((u32)a + (u32)b);
5674 
5675 	if (b < 0)
5676 		return res > a;
5677 	return res < a;
5678 }
5679 
signed_sub_overflows(s64 a,s64 b)5680 static bool signed_sub_overflows(s64 a, s64 b)
5681 {
5682 	/* Do the sub in u64, where overflow is well-defined */
5683 	s64 res = (s64)((u64)a - (u64)b);
5684 
5685 	if (b < 0)
5686 		return res < a;
5687 	return res > a;
5688 }
5689 
signed_sub32_overflows(s32 a,s32 b)5690 static bool signed_sub32_overflows(s32 a, s32 b)
5691 {
5692 	/* Do the sub in u32, where overflow is well-defined */
5693 	s32 res = (s32)((u32)a - (u32)b);
5694 
5695 	if (b < 0)
5696 		return res < a;
5697 	return res > a;
5698 }
5699 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)5700 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5701 				  const struct bpf_reg_state *reg,
5702 				  enum bpf_reg_type type)
5703 {
5704 	bool known = tnum_is_const(reg->var_off);
5705 	s64 val = reg->var_off.value;
5706 	s64 smin = reg->smin_value;
5707 
5708 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5709 		verbose(env, "math between %s pointer and %lld is not allowed\n",
5710 			reg_type_str(env, type), val);
5711 		return false;
5712 	}
5713 
5714 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5715 		verbose(env, "%s pointer offset %d is not allowed\n",
5716 			reg_type_str(env, type), reg->off);
5717 		return false;
5718 	}
5719 
5720 	if (smin == S64_MIN) {
5721 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5722 			reg_type_str(env, type));
5723 		return false;
5724 	}
5725 
5726 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5727 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
5728 			smin, reg_type_str(env, type));
5729 		return false;
5730 	}
5731 
5732 	return true;
5733 }
5734 
cur_aux(struct bpf_verifier_env * env)5735 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5736 {
5737 	return &env->insn_aux_data[env->insn_idx];
5738 }
5739 
5740 enum {
5741 	REASON_BOUNDS	= -1,
5742 	REASON_TYPE	= -2,
5743 	REASON_PATHS	= -3,
5744 	REASON_LIMIT	= -4,
5745 	REASON_STACK	= -5,
5746 };
5747 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)5748 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5749 			      u32 *alu_limit, bool mask_to_left)
5750 {
5751 	u32 max = 0, ptr_limit = 0;
5752 
5753 	switch (ptr_reg->type) {
5754 	case PTR_TO_STACK:
5755 		/* Offset 0 is out-of-bounds, but acceptable start for the
5756 		 * left direction, see BPF_REG_FP. Also, unknown scalar
5757 		 * offset where we would need to deal with min/max bounds is
5758 		 * currently prohibited for unprivileged.
5759 		 */
5760 		max = MAX_BPF_STACK + mask_to_left;
5761 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5762 		break;
5763 	case PTR_TO_MAP_VALUE:
5764 		max = ptr_reg->map_ptr->value_size;
5765 		ptr_limit = (mask_to_left ?
5766 			     ptr_reg->smin_value :
5767 			     ptr_reg->umax_value) + ptr_reg->off;
5768 		break;
5769 	default:
5770 		return REASON_TYPE;
5771 	}
5772 
5773 	if (ptr_limit >= max)
5774 		return REASON_LIMIT;
5775 	*alu_limit = ptr_limit;
5776 	return 0;
5777 }
5778 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)5779 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5780 				    const struct bpf_insn *insn)
5781 {
5782 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5783 }
5784 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)5785 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5786 				       u32 alu_state, u32 alu_limit)
5787 {
5788 	/* If we arrived here from different branches with different
5789 	 * state or limits to sanitize, then this won't work.
5790 	 */
5791 	if (aux->alu_state &&
5792 	    (aux->alu_state != alu_state ||
5793 	     aux->alu_limit != alu_limit))
5794 		return REASON_PATHS;
5795 
5796 	/* Corresponding fixup done in fixup_bpf_calls(). */
5797 	aux->alu_state = alu_state;
5798 	aux->alu_limit = alu_limit;
5799 	return 0;
5800 }
5801 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)5802 static int sanitize_val_alu(struct bpf_verifier_env *env,
5803 			    struct bpf_insn *insn)
5804 {
5805 	struct bpf_insn_aux_data *aux = cur_aux(env);
5806 
5807 	if (can_skip_alu_sanitation(env, insn))
5808 		return 0;
5809 
5810 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5811 }
5812 
sanitize_needed(u8 opcode)5813 static bool sanitize_needed(u8 opcode)
5814 {
5815 	return opcode == BPF_ADD || opcode == BPF_SUB;
5816 }
5817 
5818 struct bpf_sanitize_info {
5819 	struct bpf_insn_aux_data aux;
5820 	bool mask_to_left;
5821 };
5822 
5823 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)5824 sanitize_speculative_path(struct bpf_verifier_env *env,
5825 			  const struct bpf_insn *insn,
5826 			  u32 next_idx, u32 curr_idx)
5827 {
5828 	struct bpf_verifier_state *branch;
5829 	struct bpf_reg_state *regs;
5830 
5831 	branch = push_stack(env, next_idx, curr_idx, true);
5832 	if (branch && insn) {
5833 		regs = branch->frame[branch->curframe]->regs;
5834 		if (BPF_SRC(insn->code) == BPF_K) {
5835 			mark_reg_unknown(env, regs, insn->dst_reg);
5836 		} else if (BPF_SRC(insn->code) == BPF_X) {
5837 			mark_reg_unknown(env, regs, insn->dst_reg);
5838 			mark_reg_unknown(env, regs, insn->src_reg);
5839 		}
5840 	}
5841 	return branch;
5842 }
5843 
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)5844 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5845 			    struct bpf_insn *insn,
5846 			    const struct bpf_reg_state *ptr_reg,
5847 			    const struct bpf_reg_state *off_reg,
5848 			    struct bpf_reg_state *dst_reg,
5849 			    struct bpf_sanitize_info *info,
5850 			    const bool commit_window)
5851 {
5852 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
5853 	struct bpf_verifier_state *vstate = env->cur_state;
5854 	bool off_is_imm = tnum_is_const(off_reg->var_off);
5855 	bool off_is_neg = off_reg->smin_value < 0;
5856 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
5857 	u8 opcode = BPF_OP(insn->code);
5858 	u32 alu_state, alu_limit;
5859 	struct bpf_reg_state tmp;
5860 	bool ret;
5861 	int err;
5862 
5863 	if (can_skip_alu_sanitation(env, insn))
5864 		return 0;
5865 
5866 	/* We already marked aux for masking from non-speculative
5867 	 * paths, thus we got here in the first place. We only care
5868 	 * to explore bad access from here.
5869 	 */
5870 	if (vstate->speculative)
5871 		goto do_sim;
5872 
5873 	if (!commit_window) {
5874 		if (!tnum_is_const(off_reg->var_off) &&
5875 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
5876 			return REASON_BOUNDS;
5877 
5878 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
5879 				     (opcode == BPF_SUB && !off_is_neg);
5880 	}
5881 
5882 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
5883 	if (err < 0)
5884 		return err;
5885 
5886 	if (commit_window) {
5887 		/* In commit phase we narrow the masking window based on
5888 		 * the observed pointer move after the simulated operation.
5889 		 */
5890 		alu_state = info->aux.alu_state;
5891 		alu_limit = abs(info->aux.alu_limit - alu_limit);
5892 	} else {
5893 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5894 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
5895 		alu_state |= ptr_is_dst_reg ?
5896 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5897 
5898 		/* Limit pruning on unknown scalars to enable deep search for
5899 		 * potential masking differences from other program paths.
5900 		 */
5901 		if (!off_is_imm)
5902 			env->explore_alu_limits = true;
5903 	}
5904 
5905 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
5906 	if (err < 0)
5907 		return err;
5908 do_sim:
5909 	/* If we're in commit phase, we're done here given we already
5910 	 * pushed the truncated dst_reg into the speculative verification
5911 	 * stack.
5912 	 *
5913 	 * Also, when register is a known constant, we rewrite register-based
5914 	 * operation to immediate-based, and thus do not need masking (and as
5915 	 * a consequence, do not need to simulate the zero-truncation either).
5916 	 */
5917 	if (commit_window || off_is_imm)
5918 		return 0;
5919 
5920 	/* Simulate and find potential out-of-bounds access under
5921 	 * speculative execution from truncation as a result of
5922 	 * masking when off was not within expected range. If off
5923 	 * sits in dst, then we temporarily need to move ptr there
5924 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5925 	 * for cases where we use K-based arithmetic in one direction
5926 	 * and truncated reg-based in the other in order to explore
5927 	 * bad access.
5928 	 */
5929 	if (!ptr_is_dst_reg) {
5930 		tmp = *dst_reg;
5931 		*dst_reg = *ptr_reg;
5932 	}
5933 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
5934 					env->insn_idx);
5935 	if (!ptr_is_dst_reg && ret)
5936 		*dst_reg = tmp;
5937 	return !ret ? REASON_STACK : 0;
5938 }
5939 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)5940 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
5941 {
5942 	struct bpf_verifier_state *vstate = env->cur_state;
5943 
5944 	/* If we simulate paths under speculation, we don't update the
5945 	 * insn as 'seen' such that when we verify unreachable paths in
5946 	 * the non-speculative domain, sanitize_dead_code() can still
5947 	 * rewrite/sanitize them.
5948 	 */
5949 	if (!vstate->speculative)
5950 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
5951 }
5952 
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)5953 static int sanitize_err(struct bpf_verifier_env *env,
5954 			const struct bpf_insn *insn, int reason,
5955 			const struct bpf_reg_state *off_reg,
5956 			const struct bpf_reg_state *dst_reg)
5957 {
5958 	static const char *err = "pointer arithmetic with it prohibited for !root";
5959 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
5960 	u32 dst = insn->dst_reg, src = insn->src_reg;
5961 
5962 	switch (reason) {
5963 	case REASON_BOUNDS:
5964 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
5965 			off_reg == dst_reg ? dst : src, err);
5966 		break;
5967 	case REASON_TYPE:
5968 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
5969 			off_reg == dst_reg ? src : dst, err);
5970 		break;
5971 	case REASON_PATHS:
5972 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
5973 			dst, op, err);
5974 		break;
5975 	case REASON_LIMIT:
5976 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
5977 			dst, op, err);
5978 		break;
5979 	case REASON_STACK:
5980 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
5981 			dst, err);
5982 		break;
5983 	default:
5984 		verbose(env, "verifier internal error: unknown reason (%d)\n",
5985 			reason);
5986 		break;
5987 	}
5988 
5989 	return -EACCES;
5990 }
5991 
5992 /* check that stack access falls within stack limits and that 'reg' doesn't
5993  * have a variable offset.
5994  *
5995  * Variable offset is prohibited for unprivileged mode for simplicity since it
5996  * requires corresponding support in Spectre masking for stack ALU.  See also
5997  * retrieve_ptr_limit().
5998  *
5999  *
6000  * 'off' includes 'reg->off'.
6001  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)6002 static int check_stack_access_for_ptr_arithmetic(
6003 				struct bpf_verifier_env *env,
6004 				int regno,
6005 				const struct bpf_reg_state *reg,
6006 				int off)
6007 {
6008 	if (!tnum_is_const(reg->var_off)) {
6009 		char tn_buf[48];
6010 
6011 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6012 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6013 			regno, tn_buf, off);
6014 		return -EACCES;
6015 	}
6016 
6017 	if (off >= 0 || off < -MAX_BPF_STACK) {
6018 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6019 			"prohibited for !root; off=%d\n", regno, off);
6020 		return -EACCES;
6021 	}
6022 
6023 	return 0;
6024 }
6025 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)6026 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6027 				 const struct bpf_insn *insn,
6028 				 const struct bpf_reg_state *dst_reg)
6029 {
6030 	u32 dst = insn->dst_reg;
6031 
6032 	/* For unprivileged we require that resulting offset must be in bounds
6033 	 * in order to be able to sanitize access later on.
6034 	 */
6035 	if (env->bypass_spec_v1)
6036 		return 0;
6037 
6038 	switch (dst_reg->type) {
6039 	case PTR_TO_STACK:
6040 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6041 					dst_reg->off + dst_reg->var_off.value))
6042 			return -EACCES;
6043 		break;
6044 	case PTR_TO_MAP_VALUE:
6045 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6046 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6047 				"prohibited for !root\n", dst);
6048 			return -EACCES;
6049 		}
6050 		break;
6051 	default:
6052 		break;
6053 	}
6054 
6055 	return 0;
6056 }
6057 
6058 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6059  * Caller should also handle BPF_MOV case separately.
6060  * If we return -EACCES, caller may want to try again treating pointer as a
6061  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6062  */
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)6063 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6064 				   struct bpf_insn *insn,
6065 				   const struct bpf_reg_state *ptr_reg,
6066 				   const struct bpf_reg_state *off_reg)
6067 {
6068 	struct bpf_verifier_state *vstate = env->cur_state;
6069 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6070 	struct bpf_reg_state *regs = state->regs, *dst_reg;
6071 	bool known = tnum_is_const(off_reg->var_off);
6072 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6073 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6074 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6075 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6076 	struct bpf_sanitize_info info = {};
6077 	u8 opcode = BPF_OP(insn->code);
6078 	u32 dst = insn->dst_reg;
6079 	int ret;
6080 
6081 	dst_reg = &regs[dst];
6082 
6083 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6084 	    smin_val > smax_val || umin_val > umax_val) {
6085 		/* Taint dst register if offset had invalid bounds derived from
6086 		 * e.g. dead branches.
6087 		 */
6088 		__mark_reg_unknown(env, dst_reg);
6089 		return 0;
6090 	}
6091 
6092 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6093 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6094 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6095 			__mark_reg_unknown(env, dst_reg);
6096 			return 0;
6097 		}
6098 
6099 		verbose(env,
6100 			"R%d 32-bit pointer arithmetic prohibited\n",
6101 			dst);
6102 		return -EACCES;
6103 	}
6104 
6105 	if (ptr_reg->type & PTR_MAYBE_NULL) {
6106 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6107 			dst, reg_type_str(env, ptr_reg->type));
6108 		return -EACCES;
6109 	}
6110 
6111 	switch (base_type(ptr_reg->type)) {
6112 	case CONST_PTR_TO_MAP:
6113 		/* smin_val represents the known value */
6114 		if (known && smin_val == 0 && opcode == BPF_ADD)
6115 			break;
6116 		fallthrough;
6117 	case PTR_TO_PACKET_END:
6118 	case PTR_TO_SOCKET:
6119 	case PTR_TO_SOCK_COMMON:
6120 	case PTR_TO_TCP_SOCK:
6121 	case PTR_TO_XDP_SOCK:
6122 reject:
6123 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6124 			dst, reg_type_str(env, ptr_reg->type));
6125 		return -EACCES;
6126 	default:
6127 		if (type_may_be_null(ptr_reg->type))
6128 			goto reject;
6129 		break;
6130 	}
6131 
6132 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6133 	 * The id may be overwritten later if we create a new variable offset.
6134 	 */
6135 	dst_reg->type = ptr_reg->type;
6136 	dst_reg->id = ptr_reg->id;
6137 
6138 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6139 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6140 		return -EINVAL;
6141 
6142 	/* pointer types do not carry 32-bit bounds at the moment. */
6143 	__mark_reg32_unbounded(dst_reg);
6144 
6145 	if (sanitize_needed(opcode)) {
6146 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6147 				       &info, false);
6148 		if (ret < 0)
6149 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6150 	}
6151 
6152 	switch (opcode) {
6153 	case BPF_ADD:
6154 		/* We can take a fixed offset as long as it doesn't overflow
6155 		 * the s32 'off' field
6156 		 */
6157 		if (known && (ptr_reg->off + smin_val ==
6158 			      (s64)(s32)(ptr_reg->off + smin_val))) {
6159 			/* pointer += K.  Accumulate it into fixed offset */
6160 			dst_reg->smin_value = smin_ptr;
6161 			dst_reg->smax_value = smax_ptr;
6162 			dst_reg->umin_value = umin_ptr;
6163 			dst_reg->umax_value = umax_ptr;
6164 			dst_reg->var_off = ptr_reg->var_off;
6165 			dst_reg->off = ptr_reg->off + smin_val;
6166 			dst_reg->raw = ptr_reg->raw;
6167 			break;
6168 		}
6169 		/* A new variable offset is created.  Note that off_reg->off
6170 		 * == 0, since it's a scalar.
6171 		 * dst_reg gets the pointer type and since some positive
6172 		 * integer value was added to the pointer, give it a new 'id'
6173 		 * if it's a PTR_TO_PACKET.
6174 		 * this creates a new 'base' pointer, off_reg (variable) gets
6175 		 * added into the variable offset, and we copy the fixed offset
6176 		 * from ptr_reg.
6177 		 */
6178 		if (signed_add_overflows(smin_ptr, smin_val) ||
6179 		    signed_add_overflows(smax_ptr, smax_val)) {
6180 			dst_reg->smin_value = S64_MIN;
6181 			dst_reg->smax_value = S64_MAX;
6182 		} else {
6183 			dst_reg->smin_value = smin_ptr + smin_val;
6184 			dst_reg->smax_value = smax_ptr + smax_val;
6185 		}
6186 		if (umin_ptr + umin_val < umin_ptr ||
6187 		    umax_ptr + umax_val < umax_ptr) {
6188 			dst_reg->umin_value = 0;
6189 			dst_reg->umax_value = U64_MAX;
6190 		} else {
6191 			dst_reg->umin_value = umin_ptr + umin_val;
6192 			dst_reg->umax_value = umax_ptr + umax_val;
6193 		}
6194 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6195 		dst_reg->off = ptr_reg->off;
6196 		dst_reg->raw = ptr_reg->raw;
6197 		if (reg_is_pkt_pointer(ptr_reg)) {
6198 			dst_reg->id = ++env->id_gen;
6199 			/* something was added to pkt_ptr, set range to zero */
6200 			dst_reg->raw = 0;
6201 		}
6202 		break;
6203 	case BPF_SUB:
6204 		if (dst_reg == off_reg) {
6205 			/* scalar -= pointer.  Creates an unknown scalar */
6206 			verbose(env, "R%d tried to subtract pointer from scalar\n",
6207 				dst);
6208 			return -EACCES;
6209 		}
6210 		/* We don't allow subtraction from FP, because (according to
6211 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
6212 		 * be able to deal with it.
6213 		 */
6214 		if (ptr_reg->type == PTR_TO_STACK) {
6215 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
6216 				dst);
6217 			return -EACCES;
6218 		}
6219 		if (known && (ptr_reg->off - smin_val ==
6220 			      (s64)(s32)(ptr_reg->off - smin_val))) {
6221 			/* pointer -= K.  Subtract it from fixed offset */
6222 			dst_reg->smin_value = smin_ptr;
6223 			dst_reg->smax_value = smax_ptr;
6224 			dst_reg->umin_value = umin_ptr;
6225 			dst_reg->umax_value = umax_ptr;
6226 			dst_reg->var_off = ptr_reg->var_off;
6227 			dst_reg->id = ptr_reg->id;
6228 			dst_reg->off = ptr_reg->off - smin_val;
6229 			dst_reg->raw = ptr_reg->raw;
6230 			break;
6231 		}
6232 		/* A new variable offset is created.  If the subtrahend is known
6233 		 * nonnegative, then any reg->range we had before is still good.
6234 		 */
6235 		if (signed_sub_overflows(smin_ptr, smax_val) ||
6236 		    signed_sub_overflows(smax_ptr, smin_val)) {
6237 			/* Overflow possible, we know nothing */
6238 			dst_reg->smin_value = S64_MIN;
6239 			dst_reg->smax_value = S64_MAX;
6240 		} else {
6241 			dst_reg->smin_value = smin_ptr - smax_val;
6242 			dst_reg->smax_value = smax_ptr - smin_val;
6243 		}
6244 		if (umin_ptr < umax_val) {
6245 			/* Overflow possible, we know nothing */
6246 			dst_reg->umin_value = 0;
6247 			dst_reg->umax_value = U64_MAX;
6248 		} else {
6249 			/* Cannot overflow (as long as bounds are consistent) */
6250 			dst_reg->umin_value = umin_ptr - umax_val;
6251 			dst_reg->umax_value = umax_ptr - umin_val;
6252 		}
6253 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6254 		dst_reg->off = ptr_reg->off;
6255 		dst_reg->raw = ptr_reg->raw;
6256 		if (reg_is_pkt_pointer(ptr_reg)) {
6257 			dst_reg->id = ++env->id_gen;
6258 			/* something was added to pkt_ptr, set range to zero */
6259 			if (smin_val < 0)
6260 				dst_reg->raw = 0;
6261 		}
6262 		break;
6263 	case BPF_AND:
6264 	case BPF_OR:
6265 	case BPF_XOR:
6266 		/* bitwise ops on pointers are troublesome, prohibit. */
6267 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6268 			dst, bpf_alu_string[opcode >> 4]);
6269 		return -EACCES;
6270 	default:
6271 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
6272 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6273 			dst, bpf_alu_string[opcode >> 4]);
6274 		return -EACCES;
6275 	}
6276 
6277 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6278 		return -EINVAL;
6279 	reg_bounds_sync(dst_reg);
6280 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6281 		return -EACCES;
6282 	if (sanitize_needed(opcode)) {
6283 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6284 				       &info, true);
6285 		if (ret < 0)
6286 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6287 	}
6288 
6289 	return 0;
6290 }
6291 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6292 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6293 				 struct bpf_reg_state *src_reg)
6294 {
6295 	s32 smin_val = src_reg->s32_min_value;
6296 	s32 smax_val = src_reg->s32_max_value;
6297 	u32 umin_val = src_reg->u32_min_value;
6298 	u32 umax_val = src_reg->u32_max_value;
6299 
6300 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6301 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6302 		dst_reg->s32_min_value = S32_MIN;
6303 		dst_reg->s32_max_value = S32_MAX;
6304 	} else {
6305 		dst_reg->s32_min_value += smin_val;
6306 		dst_reg->s32_max_value += smax_val;
6307 	}
6308 	if (dst_reg->u32_min_value + umin_val < umin_val ||
6309 	    dst_reg->u32_max_value + umax_val < umax_val) {
6310 		dst_reg->u32_min_value = 0;
6311 		dst_reg->u32_max_value = U32_MAX;
6312 	} else {
6313 		dst_reg->u32_min_value += umin_val;
6314 		dst_reg->u32_max_value += umax_val;
6315 	}
6316 }
6317 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6318 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6319 			       struct bpf_reg_state *src_reg)
6320 {
6321 	s64 smin_val = src_reg->smin_value;
6322 	s64 smax_val = src_reg->smax_value;
6323 	u64 umin_val = src_reg->umin_value;
6324 	u64 umax_val = src_reg->umax_value;
6325 
6326 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6327 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
6328 		dst_reg->smin_value = S64_MIN;
6329 		dst_reg->smax_value = S64_MAX;
6330 	} else {
6331 		dst_reg->smin_value += smin_val;
6332 		dst_reg->smax_value += smax_val;
6333 	}
6334 	if (dst_reg->umin_value + umin_val < umin_val ||
6335 	    dst_reg->umax_value + umax_val < umax_val) {
6336 		dst_reg->umin_value = 0;
6337 		dst_reg->umax_value = U64_MAX;
6338 	} else {
6339 		dst_reg->umin_value += umin_val;
6340 		dst_reg->umax_value += umax_val;
6341 	}
6342 }
6343 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6344 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6345 				 struct bpf_reg_state *src_reg)
6346 {
6347 	s32 smin_val = src_reg->s32_min_value;
6348 	s32 smax_val = src_reg->s32_max_value;
6349 	u32 umin_val = src_reg->u32_min_value;
6350 	u32 umax_val = src_reg->u32_max_value;
6351 
6352 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6353 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6354 		/* Overflow possible, we know nothing */
6355 		dst_reg->s32_min_value = S32_MIN;
6356 		dst_reg->s32_max_value = S32_MAX;
6357 	} else {
6358 		dst_reg->s32_min_value -= smax_val;
6359 		dst_reg->s32_max_value -= smin_val;
6360 	}
6361 	if (dst_reg->u32_min_value < umax_val) {
6362 		/* Overflow possible, we know nothing */
6363 		dst_reg->u32_min_value = 0;
6364 		dst_reg->u32_max_value = U32_MAX;
6365 	} else {
6366 		/* Cannot overflow (as long as bounds are consistent) */
6367 		dst_reg->u32_min_value -= umax_val;
6368 		dst_reg->u32_max_value -= umin_val;
6369 	}
6370 }
6371 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6372 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6373 			       struct bpf_reg_state *src_reg)
6374 {
6375 	s64 smin_val = src_reg->smin_value;
6376 	s64 smax_val = src_reg->smax_value;
6377 	u64 umin_val = src_reg->umin_value;
6378 	u64 umax_val = src_reg->umax_value;
6379 
6380 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6381 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6382 		/* Overflow possible, we know nothing */
6383 		dst_reg->smin_value = S64_MIN;
6384 		dst_reg->smax_value = S64_MAX;
6385 	} else {
6386 		dst_reg->smin_value -= smax_val;
6387 		dst_reg->smax_value -= smin_val;
6388 	}
6389 	if (dst_reg->umin_value < umax_val) {
6390 		/* Overflow possible, we know nothing */
6391 		dst_reg->umin_value = 0;
6392 		dst_reg->umax_value = U64_MAX;
6393 	} else {
6394 		/* Cannot overflow (as long as bounds are consistent) */
6395 		dst_reg->umin_value -= umax_val;
6396 		dst_reg->umax_value -= umin_val;
6397 	}
6398 }
6399 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6400 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6401 				 struct bpf_reg_state *src_reg)
6402 {
6403 	s32 smin_val = src_reg->s32_min_value;
6404 	u32 umin_val = src_reg->u32_min_value;
6405 	u32 umax_val = src_reg->u32_max_value;
6406 
6407 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6408 		/* Ain't nobody got time to multiply that sign */
6409 		__mark_reg32_unbounded(dst_reg);
6410 		return;
6411 	}
6412 	/* Both values are positive, so we can work with unsigned and
6413 	 * copy the result to signed (unless it exceeds S32_MAX).
6414 	 */
6415 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6416 		/* Potential overflow, we know nothing */
6417 		__mark_reg32_unbounded(dst_reg);
6418 		return;
6419 	}
6420 	dst_reg->u32_min_value *= umin_val;
6421 	dst_reg->u32_max_value *= umax_val;
6422 	if (dst_reg->u32_max_value > S32_MAX) {
6423 		/* Overflow possible, we know nothing */
6424 		dst_reg->s32_min_value = S32_MIN;
6425 		dst_reg->s32_max_value = S32_MAX;
6426 	} else {
6427 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6428 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6429 	}
6430 }
6431 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6432 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6433 			       struct bpf_reg_state *src_reg)
6434 {
6435 	s64 smin_val = src_reg->smin_value;
6436 	u64 umin_val = src_reg->umin_value;
6437 	u64 umax_val = src_reg->umax_value;
6438 
6439 	if (smin_val < 0 || dst_reg->smin_value < 0) {
6440 		/* Ain't nobody got time to multiply that sign */
6441 		__mark_reg64_unbounded(dst_reg);
6442 		return;
6443 	}
6444 	/* Both values are positive, so we can work with unsigned and
6445 	 * copy the result to signed (unless it exceeds S64_MAX).
6446 	 */
6447 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6448 		/* Potential overflow, we know nothing */
6449 		__mark_reg64_unbounded(dst_reg);
6450 		return;
6451 	}
6452 	dst_reg->umin_value *= umin_val;
6453 	dst_reg->umax_value *= umax_val;
6454 	if (dst_reg->umax_value > S64_MAX) {
6455 		/* Overflow possible, we know nothing */
6456 		dst_reg->smin_value = S64_MIN;
6457 		dst_reg->smax_value = S64_MAX;
6458 	} else {
6459 		dst_reg->smin_value = dst_reg->umin_value;
6460 		dst_reg->smax_value = dst_reg->umax_value;
6461 	}
6462 }
6463 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6464 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6465 				 struct bpf_reg_state *src_reg)
6466 {
6467 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6468 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6469 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6470 	s32 smin_val = src_reg->s32_min_value;
6471 	u32 umax_val = src_reg->u32_max_value;
6472 
6473 	if (src_known && dst_known) {
6474 		__mark_reg32_known(dst_reg, var32_off.value);
6475 		return;
6476 	}
6477 
6478 	/* We get our minimum from the var_off, since that's inherently
6479 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6480 	 */
6481 	dst_reg->u32_min_value = var32_off.value;
6482 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6483 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6484 		/* Lose signed bounds when ANDing negative numbers,
6485 		 * ain't nobody got time for that.
6486 		 */
6487 		dst_reg->s32_min_value = S32_MIN;
6488 		dst_reg->s32_max_value = S32_MAX;
6489 	} else {
6490 		/* ANDing two positives gives a positive, so safe to
6491 		 * cast result into s64.
6492 		 */
6493 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6494 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6495 	}
6496 }
6497 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6498 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6499 			       struct bpf_reg_state *src_reg)
6500 {
6501 	bool src_known = tnum_is_const(src_reg->var_off);
6502 	bool dst_known = tnum_is_const(dst_reg->var_off);
6503 	s64 smin_val = src_reg->smin_value;
6504 	u64 umax_val = src_reg->umax_value;
6505 
6506 	if (src_known && dst_known) {
6507 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6508 		return;
6509 	}
6510 
6511 	/* We get our minimum from the var_off, since that's inherently
6512 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6513 	 */
6514 	dst_reg->umin_value = dst_reg->var_off.value;
6515 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6516 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6517 		/* Lose signed bounds when ANDing negative numbers,
6518 		 * ain't nobody got time for that.
6519 		 */
6520 		dst_reg->smin_value = S64_MIN;
6521 		dst_reg->smax_value = S64_MAX;
6522 	} else {
6523 		/* ANDing two positives gives a positive, so safe to
6524 		 * cast result into s64.
6525 		 */
6526 		dst_reg->smin_value = dst_reg->umin_value;
6527 		dst_reg->smax_value = dst_reg->umax_value;
6528 	}
6529 	/* We may learn something more from the var_off */
6530 	__update_reg_bounds(dst_reg);
6531 }
6532 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6533 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6534 				struct bpf_reg_state *src_reg)
6535 {
6536 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6537 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6538 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6539 	s32 smin_val = src_reg->s32_min_value;
6540 	u32 umin_val = src_reg->u32_min_value;
6541 
6542 	if (src_known && dst_known) {
6543 		__mark_reg32_known(dst_reg, var32_off.value);
6544 		return;
6545 	}
6546 
6547 	/* We get our maximum from the var_off, and our minimum is the
6548 	 * maximum of the operands' minima
6549 	 */
6550 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6551 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6552 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6553 		/* Lose signed bounds when ORing negative numbers,
6554 		 * ain't nobody got time for that.
6555 		 */
6556 		dst_reg->s32_min_value = S32_MIN;
6557 		dst_reg->s32_max_value = S32_MAX;
6558 	} else {
6559 		/* ORing two positives gives a positive, so safe to
6560 		 * cast result into s64.
6561 		 */
6562 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6563 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6564 	}
6565 }
6566 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6567 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6568 			      struct bpf_reg_state *src_reg)
6569 {
6570 	bool src_known = tnum_is_const(src_reg->var_off);
6571 	bool dst_known = tnum_is_const(dst_reg->var_off);
6572 	s64 smin_val = src_reg->smin_value;
6573 	u64 umin_val = src_reg->umin_value;
6574 
6575 	if (src_known && dst_known) {
6576 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6577 		return;
6578 	}
6579 
6580 	/* We get our maximum from the var_off, and our minimum is the
6581 	 * maximum of the operands' minima
6582 	 */
6583 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6584 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6585 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6586 		/* Lose signed bounds when ORing negative numbers,
6587 		 * ain't nobody got time for that.
6588 		 */
6589 		dst_reg->smin_value = S64_MIN;
6590 		dst_reg->smax_value = S64_MAX;
6591 	} else {
6592 		/* ORing two positives gives a positive, so safe to
6593 		 * cast result into s64.
6594 		 */
6595 		dst_reg->smin_value = dst_reg->umin_value;
6596 		dst_reg->smax_value = dst_reg->umax_value;
6597 	}
6598 	/* We may learn something more from the var_off */
6599 	__update_reg_bounds(dst_reg);
6600 }
6601 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6602 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6603 				 struct bpf_reg_state *src_reg)
6604 {
6605 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6606 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6607 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6608 	s32 smin_val = src_reg->s32_min_value;
6609 
6610 	if (src_known && dst_known) {
6611 		__mark_reg32_known(dst_reg, var32_off.value);
6612 		return;
6613 	}
6614 
6615 	/* We get both minimum and maximum from the var32_off. */
6616 	dst_reg->u32_min_value = var32_off.value;
6617 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6618 
6619 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6620 		/* XORing two positive sign numbers gives a positive,
6621 		 * so safe to cast u32 result into s32.
6622 		 */
6623 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6624 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6625 	} else {
6626 		dst_reg->s32_min_value = S32_MIN;
6627 		dst_reg->s32_max_value = S32_MAX;
6628 	}
6629 }
6630 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6631 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6632 			       struct bpf_reg_state *src_reg)
6633 {
6634 	bool src_known = tnum_is_const(src_reg->var_off);
6635 	bool dst_known = tnum_is_const(dst_reg->var_off);
6636 	s64 smin_val = src_reg->smin_value;
6637 
6638 	if (src_known && dst_known) {
6639 		/* dst_reg->var_off.value has been updated earlier */
6640 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6641 		return;
6642 	}
6643 
6644 	/* We get both minimum and maximum from the var_off. */
6645 	dst_reg->umin_value = dst_reg->var_off.value;
6646 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6647 
6648 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6649 		/* XORing two positive sign numbers gives a positive,
6650 		 * so safe to cast u64 result into s64.
6651 		 */
6652 		dst_reg->smin_value = dst_reg->umin_value;
6653 		dst_reg->smax_value = dst_reg->umax_value;
6654 	} else {
6655 		dst_reg->smin_value = S64_MIN;
6656 		dst_reg->smax_value = S64_MAX;
6657 	}
6658 
6659 	__update_reg_bounds(dst_reg);
6660 }
6661 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6662 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6663 				   u64 umin_val, u64 umax_val)
6664 {
6665 	/* We lose all sign bit information (except what we can pick
6666 	 * up from var_off)
6667 	 */
6668 	dst_reg->s32_min_value = S32_MIN;
6669 	dst_reg->s32_max_value = S32_MAX;
6670 	/* If we might shift our top bit out, then we know nothing */
6671 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6672 		dst_reg->u32_min_value = 0;
6673 		dst_reg->u32_max_value = U32_MAX;
6674 	} else {
6675 		dst_reg->u32_min_value <<= umin_val;
6676 		dst_reg->u32_max_value <<= umax_val;
6677 	}
6678 }
6679 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6680 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6681 				 struct bpf_reg_state *src_reg)
6682 {
6683 	u32 umax_val = src_reg->u32_max_value;
6684 	u32 umin_val = src_reg->u32_min_value;
6685 	/* u32 alu operation will zext upper bits */
6686 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6687 
6688 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6689 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6690 	/* Not required but being careful mark reg64 bounds as unknown so
6691 	 * that we are forced to pick them up from tnum and zext later and
6692 	 * if some path skips this step we are still safe.
6693 	 */
6694 	__mark_reg64_unbounded(dst_reg);
6695 	__update_reg32_bounds(dst_reg);
6696 }
6697 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6698 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6699 				   u64 umin_val, u64 umax_val)
6700 {
6701 	/* Special case <<32 because it is a common compiler pattern to sign
6702 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6703 	 * positive we know this shift will also be positive so we can track
6704 	 * bounds correctly. Otherwise we lose all sign bit information except
6705 	 * what we can pick up from var_off. Perhaps we can generalize this
6706 	 * later to shifts of any length.
6707 	 */
6708 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6709 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6710 	else
6711 		dst_reg->smax_value = S64_MAX;
6712 
6713 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6714 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6715 	else
6716 		dst_reg->smin_value = S64_MIN;
6717 
6718 	/* If we might shift our top bit out, then we know nothing */
6719 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6720 		dst_reg->umin_value = 0;
6721 		dst_reg->umax_value = U64_MAX;
6722 	} else {
6723 		dst_reg->umin_value <<= umin_val;
6724 		dst_reg->umax_value <<= umax_val;
6725 	}
6726 }
6727 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6728 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6729 			       struct bpf_reg_state *src_reg)
6730 {
6731 	u64 umax_val = src_reg->umax_value;
6732 	u64 umin_val = src_reg->umin_value;
6733 
6734 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
6735 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6736 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6737 
6738 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6739 	/* We may learn something more from the var_off */
6740 	__update_reg_bounds(dst_reg);
6741 }
6742 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6743 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6744 				 struct bpf_reg_state *src_reg)
6745 {
6746 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6747 	u32 umax_val = src_reg->u32_max_value;
6748 	u32 umin_val = src_reg->u32_min_value;
6749 
6750 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6751 	 * be negative, then either:
6752 	 * 1) src_reg might be zero, so the sign bit of the result is
6753 	 *    unknown, so we lose our signed bounds
6754 	 * 2) it's known negative, thus the unsigned bounds capture the
6755 	 *    signed bounds
6756 	 * 3) the signed bounds cross zero, so they tell us nothing
6757 	 *    about the result
6758 	 * If the value in dst_reg is known nonnegative, then again the
6759 	 * unsigned bounts capture the signed bounds.
6760 	 * Thus, in all cases it suffices to blow away our signed bounds
6761 	 * and rely on inferring new ones from the unsigned bounds and
6762 	 * var_off of the result.
6763 	 */
6764 	dst_reg->s32_min_value = S32_MIN;
6765 	dst_reg->s32_max_value = S32_MAX;
6766 
6767 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
6768 	dst_reg->u32_min_value >>= umax_val;
6769 	dst_reg->u32_max_value >>= umin_val;
6770 
6771 	__mark_reg64_unbounded(dst_reg);
6772 	__update_reg32_bounds(dst_reg);
6773 }
6774 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6775 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6776 			       struct bpf_reg_state *src_reg)
6777 {
6778 	u64 umax_val = src_reg->umax_value;
6779 	u64 umin_val = src_reg->umin_value;
6780 
6781 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6782 	 * be negative, then either:
6783 	 * 1) src_reg might be zero, so the sign bit of the result is
6784 	 *    unknown, so we lose our signed bounds
6785 	 * 2) it's known negative, thus the unsigned bounds capture the
6786 	 *    signed bounds
6787 	 * 3) the signed bounds cross zero, so they tell us nothing
6788 	 *    about the result
6789 	 * If the value in dst_reg is known nonnegative, then again the
6790 	 * unsigned bounts capture the signed bounds.
6791 	 * Thus, in all cases it suffices to blow away our signed bounds
6792 	 * and rely on inferring new ones from the unsigned bounds and
6793 	 * var_off of the result.
6794 	 */
6795 	dst_reg->smin_value = S64_MIN;
6796 	dst_reg->smax_value = S64_MAX;
6797 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6798 	dst_reg->umin_value >>= umax_val;
6799 	dst_reg->umax_value >>= umin_val;
6800 
6801 	/* Its not easy to operate on alu32 bounds here because it depends
6802 	 * on bits being shifted in. Take easy way out and mark unbounded
6803 	 * so we can recalculate later from tnum.
6804 	 */
6805 	__mark_reg32_unbounded(dst_reg);
6806 	__update_reg_bounds(dst_reg);
6807 }
6808 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6809 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6810 				  struct bpf_reg_state *src_reg)
6811 {
6812 	u64 umin_val = src_reg->u32_min_value;
6813 
6814 	/* Upon reaching here, src_known is true and
6815 	 * umax_val is equal to umin_val.
6816 	 */
6817 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6818 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6819 
6820 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6821 
6822 	/* blow away the dst_reg umin_value/umax_value and rely on
6823 	 * dst_reg var_off to refine the result.
6824 	 */
6825 	dst_reg->u32_min_value = 0;
6826 	dst_reg->u32_max_value = U32_MAX;
6827 
6828 	__mark_reg64_unbounded(dst_reg);
6829 	__update_reg32_bounds(dst_reg);
6830 }
6831 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6832 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6833 				struct bpf_reg_state *src_reg)
6834 {
6835 	u64 umin_val = src_reg->umin_value;
6836 
6837 	/* Upon reaching here, src_known is true and umax_val is equal
6838 	 * to umin_val.
6839 	 */
6840 	dst_reg->smin_value >>= umin_val;
6841 	dst_reg->smax_value >>= umin_val;
6842 
6843 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6844 
6845 	/* blow away the dst_reg umin_value/umax_value and rely on
6846 	 * dst_reg var_off to refine the result.
6847 	 */
6848 	dst_reg->umin_value = 0;
6849 	dst_reg->umax_value = U64_MAX;
6850 
6851 	/* Its not easy to operate on alu32 bounds here because it depends
6852 	 * on bits being shifted in from upper 32-bits. Take easy way out
6853 	 * and mark unbounded so we can recalculate later from tnum.
6854 	 */
6855 	__mark_reg32_unbounded(dst_reg);
6856 	__update_reg_bounds(dst_reg);
6857 }
6858 
6859 /* WARNING: This function does calculations on 64-bit values, but the actual
6860  * execution may occur on 32-bit values. Therefore, things like bitshifts
6861  * need extra checks in the 32-bit case.
6862  */
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)6863 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6864 				      struct bpf_insn *insn,
6865 				      struct bpf_reg_state *dst_reg,
6866 				      struct bpf_reg_state src_reg)
6867 {
6868 	struct bpf_reg_state *regs = cur_regs(env);
6869 	u8 opcode = BPF_OP(insn->code);
6870 	bool src_known;
6871 	s64 smin_val, smax_val;
6872 	u64 umin_val, umax_val;
6873 	s32 s32_min_val, s32_max_val;
6874 	u32 u32_min_val, u32_max_val;
6875 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6876 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6877 	int ret;
6878 
6879 	smin_val = src_reg.smin_value;
6880 	smax_val = src_reg.smax_value;
6881 	umin_val = src_reg.umin_value;
6882 	umax_val = src_reg.umax_value;
6883 
6884 	s32_min_val = src_reg.s32_min_value;
6885 	s32_max_val = src_reg.s32_max_value;
6886 	u32_min_val = src_reg.u32_min_value;
6887 	u32_max_val = src_reg.u32_max_value;
6888 
6889 	if (alu32) {
6890 		src_known = tnum_subreg_is_const(src_reg.var_off);
6891 		if ((src_known &&
6892 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6893 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6894 			/* Taint dst register if offset had invalid bounds
6895 			 * derived from e.g. dead branches.
6896 			 */
6897 			__mark_reg_unknown(env, dst_reg);
6898 			return 0;
6899 		}
6900 	} else {
6901 		src_known = tnum_is_const(src_reg.var_off);
6902 		if ((src_known &&
6903 		     (smin_val != smax_val || umin_val != umax_val)) ||
6904 		    smin_val > smax_val || umin_val > umax_val) {
6905 			/* Taint dst register if offset had invalid bounds
6906 			 * derived from e.g. dead branches.
6907 			 */
6908 			__mark_reg_unknown(env, dst_reg);
6909 			return 0;
6910 		}
6911 	}
6912 
6913 	if (!src_known &&
6914 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6915 		__mark_reg_unknown(env, dst_reg);
6916 		return 0;
6917 	}
6918 
6919 	if (sanitize_needed(opcode)) {
6920 		ret = sanitize_val_alu(env, insn);
6921 		if (ret < 0)
6922 			return sanitize_err(env, insn, ret, NULL, NULL);
6923 	}
6924 
6925 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6926 	 * There are two classes of instructions: The first class we track both
6927 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
6928 	 * greatest amount of precision when alu operations are mixed with jmp32
6929 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6930 	 * and BPF_OR. This is possible because these ops have fairly easy to
6931 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6932 	 * See alu32 verifier tests for examples. The second class of
6933 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6934 	 * with regards to tracking sign/unsigned bounds because the bits may
6935 	 * cross subreg boundaries in the alu64 case. When this happens we mark
6936 	 * the reg unbounded in the subreg bound space and use the resulting
6937 	 * tnum to calculate an approximation of the sign/unsigned bounds.
6938 	 */
6939 	switch (opcode) {
6940 	case BPF_ADD:
6941 		scalar32_min_max_add(dst_reg, &src_reg);
6942 		scalar_min_max_add(dst_reg, &src_reg);
6943 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6944 		break;
6945 	case BPF_SUB:
6946 		scalar32_min_max_sub(dst_reg, &src_reg);
6947 		scalar_min_max_sub(dst_reg, &src_reg);
6948 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6949 		break;
6950 	case BPF_MUL:
6951 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6952 		scalar32_min_max_mul(dst_reg, &src_reg);
6953 		scalar_min_max_mul(dst_reg, &src_reg);
6954 		break;
6955 	case BPF_AND:
6956 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6957 		scalar32_min_max_and(dst_reg, &src_reg);
6958 		scalar_min_max_and(dst_reg, &src_reg);
6959 		break;
6960 	case BPF_OR:
6961 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6962 		scalar32_min_max_or(dst_reg, &src_reg);
6963 		scalar_min_max_or(dst_reg, &src_reg);
6964 		break;
6965 	case BPF_XOR:
6966 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6967 		scalar32_min_max_xor(dst_reg, &src_reg);
6968 		scalar_min_max_xor(dst_reg, &src_reg);
6969 		break;
6970 	case BPF_LSH:
6971 		if (umax_val >= insn_bitness) {
6972 			/* Shifts greater than 31 or 63 are undefined.
6973 			 * This includes shifts by a negative number.
6974 			 */
6975 			mark_reg_unknown(env, regs, insn->dst_reg);
6976 			break;
6977 		}
6978 		if (alu32)
6979 			scalar32_min_max_lsh(dst_reg, &src_reg);
6980 		else
6981 			scalar_min_max_lsh(dst_reg, &src_reg);
6982 		break;
6983 	case BPF_RSH:
6984 		if (umax_val >= insn_bitness) {
6985 			/* Shifts greater than 31 or 63 are undefined.
6986 			 * This includes shifts by a negative number.
6987 			 */
6988 			mark_reg_unknown(env, regs, insn->dst_reg);
6989 			break;
6990 		}
6991 		if (alu32)
6992 			scalar32_min_max_rsh(dst_reg, &src_reg);
6993 		else
6994 			scalar_min_max_rsh(dst_reg, &src_reg);
6995 		break;
6996 	case BPF_ARSH:
6997 		if (umax_val >= insn_bitness) {
6998 			/* Shifts greater than 31 or 63 are undefined.
6999 			 * This includes shifts by a negative number.
7000 			 */
7001 			mark_reg_unknown(env, regs, insn->dst_reg);
7002 			break;
7003 		}
7004 		if (alu32)
7005 			scalar32_min_max_arsh(dst_reg, &src_reg);
7006 		else
7007 			scalar_min_max_arsh(dst_reg, &src_reg);
7008 		break;
7009 	default:
7010 		mark_reg_unknown(env, regs, insn->dst_reg);
7011 		break;
7012 	}
7013 
7014 	/* ALU32 ops are zero extended into 64bit register */
7015 	if (alu32)
7016 		zext_32_to_64(dst_reg);
7017 	reg_bounds_sync(dst_reg);
7018 	return 0;
7019 }
7020 
7021 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7022  * and var_off.
7023  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)7024 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7025 				   struct bpf_insn *insn)
7026 {
7027 	struct bpf_verifier_state *vstate = env->cur_state;
7028 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7029 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7030 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7031 	u8 opcode = BPF_OP(insn->code);
7032 	int err;
7033 
7034 	dst_reg = &regs[insn->dst_reg];
7035 	src_reg = NULL;
7036 	if (dst_reg->type != SCALAR_VALUE)
7037 		ptr_reg = dst_reg;
7038 	else
7039 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7040 		 * incorrectly propagated into other registers by find_equal_scalars()
7041 		 */
7042 		dst_reg->id = 0;
7043 	if (BPF_SRC(insn->code) == BPF_X) {
7044 		src_reg = &regs[insn->src_reg];
7045 		if (src_reg->type != SCALAR_VALUE) {
7046 			if (dst_reg->type != SCALAR_VALUE) {
7047 				/* Combining two pointers by any ALU op yields
7048 				 * an arbitrary scalar. Disallow all math except
7049 				 * pointer subtraction
7050 				 */
7051 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7052 					mark_reg_unknown(env, regs, insn->dst_reg);
7053 					return 0;
7054 				}
7055 				verbose(env, "R%d pointer %s pointer prohibited\n",
7056 					insn->dst_reg,
7057 					bpf_alu_string[opcode >> 4]);
7058 				return -EACCES;
7059 			} else {
7060 				/* scalar += pointer
7061 				 * This is legal, but we have to reverse our
7062 				 * src/dest handling in computing the range
7063 				 */
7064 				err = mark_chain_precision(env, insn->dst_reg);
7065 				if (err)
7066 					return err;
7067 				return adjust_ptr_min_max_vals(env, insn,
7068 							       src_reg, dst_reg);
7069 			}
7070 		} else if (ptr_reg) {
7071 			/* pointer += scalar */
7072 			err = mark_chain_precision(env, insn->src_reg);
7073 			if (err)
7074 				return err;
7075 			return adjust_ptr_min_max_vals(env, insn,
7076 						       dst_reg, src_reg);
7077 		} else if (dst_reg->precise) {
7078 			/* if dst_reg is precise, src_reg should be precise as well */
7079 			err = mark_chain_precision(env, insn->src_reg);
7080 			if (err)
7081 				return err;
7082 		}
7083 	} else {
7084 		/* Pretend the src is a reg with a known value, since we only
7085 		 * need to be able to read from this state.
7086 		 */
7087 		off_reg.type = SCALAR_VALUE;
7088 		__mark_reg_known(&off_reg, insn->imm);
7089 		src_reg = &off_reg;
7090 		if (ptr_reg) /* pointer += K */
7091 			return adjust_ptr_min_max_vals(env, insn,
7092 						       ptr_reg, src_reg);
7093 	}
7094 
7095 	/* Got here implies adding two SCALAR_VALUEs */
7096 	if (WARN_ON_ONCE(ptr_reg)) {
7097 		print_verifier_state(env, state);
7098 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
7099 		return -EINVAL;
7100 	}
7101 	if (WARN_ON(!src_reg)) {
7102 		print_verifier_state(env, state);
7103 		verbose(env, "verifier internal error: no src_reg\n");
7104 		return -EINVAL;
7105 	}
7106 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7107 }
7108 
7109 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)7110 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7111 {
7112 	struct bpf_reg_state *regs = cur_regs(env);
7113 	u8 opcode = BPF_OP(insn->code);
7114 	int err;
7115 
7116 	if (opcode == BPF_END || opcode == BPF_NEG) {
7117 		if (opcode == BPF_NEG) {
7118 			if (BPF_SRC(insn->code) != 0 ||
7119 			    insn->src_reg != BPF_REG_0 ||
7120 			    insn->off != 0 || insn->imm != 0) {
7121 				verbose(env, "BPF_NEG uses reserved fields\n");
7122 				return -EINVAL;
7123 			}
7124 		} else {
7125 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7126 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7127 			    BPF_CLASS(insn->code) == BPF_ALU64) {
7128 				verbose(env, "BPF_END uses reserved fields\n");
7129 				return -EINVAL;
7130 			}
7131 		}
7132 
7133 		/* check src operand */
7134 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7135 		if (err)
7136 			return err;
7137 
7138 		if (is_pointer_value(env, insn->dst_reg)) {
7139 			verbose(env, "R%d pointer arithmetic prohibited\n",
7140 				insn->dst_reg);
7141 			return -EACCES;
7142 		}
7143 
7144 		/* check dest operand */
7145 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
7146 		if (err)
7147 			return err;
7148 
7149 	} else if (opcode == BPF_MOV) {
7150 
7151 		if (BPF_SRC(insn->code) == BPF_X) {
7152 			if (insn->imm != 0 || insn->off != 0) {
7153 				verbose(env, "BPF_MOV uses reserved fields\n");
7154 				return -EINVAL;
7155 			}
7156 
7157 			/* check src operand */
7158 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7159 			if (err)
7160 				return err;
7161 		} else {
7162 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7163 				verbose(env, "BPF_MOV uses reserved fields\n");
7164 				return -EINVAL;
7165 			}
7166 		}
7167 
7168 		/* check dest operand, mark as required later */
7169 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7170 		if (err)
7171 			return err;
7172 
7173 		if (BPF_SRC(insn->code) == BPF_X) {
7174 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
7175 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7176 
7177 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7178 				/* case: R1 = R2
7179 				 * copy register state to dest reg
7180 				 */
7181 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7182 					/* Assign src and dst registers the same ID
7183 					 * that will be used by find_equal_scalars()
7184 					 * to propagate min/max range.
7185 					 */
7186 					src_reg->id = ++env->id_gen;
7187 				*dst_reg = *src_reg;
7188 				dst_reg->live |= REG_LIVE_WRITTEN;
7189 				dst_reg->subreg_def = DEF_NOT_SUBREG;
7190 			} else {
7191 				/* R1 = (u32) R2 */
7192 				if (is_pointer_value(env, insn->src_reg)) {
7193 					verbose(env,
7194 						"R%d partial copy of pointer\n",
7195 						insn->src_reg);
7196 					return -EACCES;
7197 				} else if (src_reg->type == SCALAR_VALUE) {
7198 					*dst_reg = *src_reg;
7199 					/* Make sure ID is cleared otherwise
7200 					 * dst_reg min/max could be incorrectly
7201 					 * propagated into src_reg by find_equal_scalars()
7202 					 */
7203 					dst_reg->id = 0;
7204 					dst_reg->live |= REG_LIVE_WRITTEN;
7205 					dst_reg->subreg_def = env->insn_idx + 1;
7206 				} else {
7207 					mark_reg_unknown(env, regs,
7208 							 insn->dst_reg);
7209 				}
7210 				zext_32_to_64(dst_reg);
7211 				reg_bounds_sync(dst_reg);
7212 			}
7213 		} else {
7214 			/* case: R = imm
7215 			 * remember the value we stored into this reg
7216 			 */
7217 			/* clear any state __mark_reg_known doesn't set */
7218 			mark_reg_unknown(env, regs, insn->dst_reg);
7219 			regs[insn->dst_reg].type = SCALAR_VALUE;
7220 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7221 				__mark_reg_known(regs + insn->dst_reg,
7222 						 insn->imm);
7223 			} else {
7224 				__mark_reg_known(regs + insn->dst_reg,
7225 						 (u32)insn->imm);
7226 			}
7227 		}
7228 
7229 	} else if (opcode > BPF_END) {
7230 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7231 		return -EINVAL;
7232 
7233 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
7234 
7235 		if (BPF_SRC(insn->code) == BPF_X) {
7236 			if (insn->imm != 0 || insn->off != 0) {
7237 				verbose(env, "BPF_ALU uses reserved fields\n");
7238 				return -EINVAL;
7239 			}
7240 			/* check src1 operand */
7241 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7242 			if (err)
7243 				return err;
7244 		} else {
7245 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7246 				verbose(env, "BPF_ALU uses reserved fields\n");
7247 				return -EINVAL;
7248 			}
7249 		}
7250 
7251 		/* check src2 operand */
7252 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7253 		if (err)
7254 			return err;
7255 
7256 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7257 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7258 			verbose(env, "div by zero\n");
7259 			return -EINVAL;
7260 		}
7261 
7262 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7263 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7264 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7265 
7266 			if (insn->imm < 0 || insn->imm >= size) {
7267 				verbose(env, "invalid shift %d\n", insn->imm);
7268 				return -EINVAL;
7269 			}
7270 		}
7271 
7272 		/* check dest operand */
7273 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7274 		if (err)
7275 			return err;
7276 
7277 		return adjust_reg_min_max_vals(env, insn);
7278 	}
7279 
7280 	return 0;
7281 }
7282 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)7283 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7284 				   struct bpf_reg_state *dst_reg,
7285 				   enum bpf_reg_type type,
7286 				   bool range_right_open)
7287 {
7288 	struct bpf_func_state *state;
7289 	struct bpf_reg_state *reg;
7290 	int new_range;
7291 
7292 	if (dst_reg->off < 0 ||
7293 	    (dst_reg->off == 0 && range_right_open))
7294 		/* This doesn't give us any range */
7295 		return;
7296 
7297 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
7298 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7299 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
7300 		 * than pkt_end, but that's because it's also less than pkt.
7301 		 */
7302 		return;
7303 
7304 	new_range = dst_reg->off;
7305 	if (range_right_open)
7306 		new_range++;
7307 
7308 	/* Examples for register markings:
7309 	 *
7310 	 * pkt_data in dst register:
7311 	 *
7312 	 *   r2 = r3;
7313 	 *   r2 += 8;
7314 	 *   if (r2 > pkt_end) goto <handle exception>
7315 	 *   <access okay>
7316 	 *
7317 	 *   r2 = r3;
7318 	 *   r2 += 8;
7319 	 *   if (r2 < pkt_end) goto <access okay>
7320 	 *   <handle exception>
7321 	 *
7322 	 *   Where:
7323 	 *     r2 == dst_reg, pkt_end == src_reg
7324 	 *     r2=pkt(id=n,off=8,r=0)
7325 	 *     r3=pkt(id=n,off=0,r=0)
7326 	 *
7327 	 * pkt_data in src register:
7328 	 *
7329 	 *   r2 = r3;
7330 	 *   r2 += 8;
7331 	 *   if (pkt_end >= r2) goto <access okay>
7332 	 *   <handle exception>
7333 	 *
7334 	 *   r2 = r3;
7335 	 *   r2 += 8;
7336 	 *   if (pkt_end <= r2) goto <handle exception>
7337 	 *   <access okay>
7338 	 *
7339 	 *   Where:
7340 	 *     pkt_end == dst_reg, r2 == src_reg
7341 	 *     r2=pkt(id=n,off=8,r=0)
7342 	 *     r3=pkt(id=n,off=0,r=0)
7343 	 *
7344 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7345 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7346 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
7347 	 * the check.
7348 	 */
7349 
7350 	/* If our ids match, then we must have the same max_value.  And we
7351 	 * don't care about the other reg's fixed offset, since if it's too big
7352 	 * the range won't allow anything.
7353 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7354 	 */
7355 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7356 		if (reg->type == type && reg->id == dst_reg->id)
7357 			/* keep the maximum range already checked */
7358 			reg->range = max(reg->range, new_range);
7359 	}));
7360 }
7361 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)7362 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7363 {
7364 	struct tnum subreg = tnum_subreg(reg->var_off);
7365 	s32 sval = (s32)val;
7366 
7367 	switch (opcode) {
7368 	case BPF_JEQ:
7369 		if (tnum_is_const(subreg))
7370 			return !!tnum_equals_const(subreg, val);
7371 		break;
7372 	case BPF_JNE:
7373 		if (tnum_is_const(subreg))
7374 			return !tnum_equals_const(subreg, val);
7375 		break;
7376 	case BPF_JSET:
7377 		if ((~subreg.mask & subreg.value) & val)
7378 			return 1;
7379 		if (!((subreg.mask | subreg.value) & val))
7380 			return 0;
7381 		break;
7382 	case BPF_JGT:
7383 		if (reg->u32_min_value > val)
7384 			return 1;
7385 		else if (reg->u32_max_value <= val)
7386 			return 0;
7387 		break;
7388 	case BPF_JSGT:
7389 		if (reg->s32_min_value > sval)
7390 			return 1;
7391 		else if (reg->s32_max_value <= sval)
7392 			return 0;
7393 		break;
7394 	case BPF_JLT:
7395 		if (reg->u32_max_value < val)
7396 			return 1;
7397 		else if (reg->u32_min_value >= val)
7398 			return 0;
7399 		break;
7400 	case BPF_JSLT:
7401 		if (reg->s32_max_value < sval)
7402 			return 1;
7403 		else if (reg->s32_min_value >= sval)
7404 			return 0;
7405 		break;
7406 	case BPF_JGE:
7407 		if (reg->u32_min_value >= val)
7408 			return 1;
7409 		else if (reg->u32_max_value < val)
7410 			return 0;
7411 		break;
7412 	case BPF_JSGE:
7413 		if (reg->s32_min_value >= sval)
7414 			return 1;
7415 		else if (reg->s32_max_value < sval)
7416 			return 0;
7417 		break;
7418 	case BPF_JLE:
7419 		if (reg->u32_max_value <= val)
7420 			return 1;
7421 		else if (reg->u32_min_value > val)
7422 			return 0;
7423 		break;
7424 	case BPF_JSLE:
7425 		if (reg->s32_max_value <= sval)
7426 			return 1;
7427 		else if (reg->s32_min_value > sval)
7428 			return 0;
7429 		break;
7430 	}
7431 
7432 	return -1;
7433 }
7434 
7435 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)7436 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7437 {
7438 	s64 sval = (s64)val;
7439 
7440 	switch (opcode) {
7441 	case BPF_JEQ:
7442 		if (tnum_is_const(reg->var_off))
7443 			return !!tnum_equals_const(reg->var_off, val);
7444 		break;
7445 	case BPF_JNE:
7446 		if (tnum_is_const(reg->var_off))
7447 			return !tnum_equals_const(reg->var_off, val);
7448 		break;
7449 	case BPF_JSET:
7450 		if ((~reg->var_off.mask & reg->var_off.value) & val)
7451 			return 1;
7452 		if (!((reg->var_off.mask | reg->var_off.value) & val))
7453 			return 0;
7454 		break;
7455 	case BPF_JGT:
7456 		if (reg->umin_value > val)
7457 			return 1;
7458 		else if (reg->umax_value <= val)
7459 			return 0;
7460 		break;
7461 	case BPF_JSGT:
7462 		if (reg->smin_value > sval)
7463 			return 1;
7464 		else if (reg->smax_value <= sval)
7465 			return 0;
7466 		break;
7467 	case BPF_JLT:
7468 		if (reg->umax_value < val)
7469 			return 1;
7470 		else if (reg->umin_value >= val)
7471 			return 0;
7472 		break;
7473 	case BPF_JSLT:
7474 		if (reg->smax_value < sval)
7475 			return 1;
7476 		else if (reg->smin_value >= sval)
7477 			return 0;
7478 		break;
7479 	case BPF_JGE:
7480 		if (reg->umin_value >= val)
7481 			return 1;
7482 		else if (reg->umax_value < val)
7483 			return 0;
7484 		break;
7485 	case BPF_JSGE:
7486 		if (reg->smin_value >= sval)
7487 			return 1;
7488 		else if (reg->smax_value < sval)
7489 			return 0;
7490 		break;
7491 	case BPF_JLE:
7492 		if (reg->umax_value <= val)
7493 			return 1;
7494 		else if (reg->umin_value > val)
7495 			return 0;
7496 		break;
7497 	case BPF_JSLE:
7498 		if (reg->smax_value <= sval)
7499 			return 1;
7500 		else if (reg->smin_value > sval)
7501 			return 0;
7502 		break;
7503 	}
7504 
7505 	return -1;
7506 }
7507 
7508 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7509  * and return:
7510  *  1 - branch will be taken and "goto target" will be executed
7511  *  0 - branch will not be taken and fall-through to next insn
7512  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7513  *      range [0,10]
7514  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)7515 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7516 			   bool is_jmp32)
7517 {
7518 	if (__is_pointer_value(false, reg)) {
7519 		if (!reg_type_not_null(reg->type))
7520 			return -1;
7521 
7522 		/* If pointer is valid tests against zero will fail so we can
7523 		 * use this to direct branch taken.
7524 		 */
7525 		if (val != 0)
7526 			return -1;
7527 
7528 		switch (opcode) {
7529 		case BPF_JEQ:
7530 			return 0;
7531 		case BPF_JNE:
7532 			return 1;
7533 		default:
7534 			return -1;
7535 		}
7536 	}
7537 
7538 	if (is_jmp32)
7539 		return is_branch32_taken(reg, val, opcode);
7540 	return is_branch64_taken(reg, val, opcode);
7541 }
7542 
flip_opcode(u32 opcode)7543 static int flip_opcode(u32 opcode)
7544 {
7545 	/* How can we transform "a <op> b" into "b <op> a"? */
7546 	static const u8 opcode_flip[16] = {
7547 		/* these stay the same */
7548 		[BPF_JEQ  >> 4] = BPF_JEQ,
7549 		[BPF_JNE  >> 4] = BPF_JNE,
7550 		[BPF_JSET >> 4] = BPF_JSET,
7551 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
7552 		[BPF_JGE  >> 4] = BPF_JLE,
7553 		[BPF_JGT  >> 4] = BPF_JLT,
7554 		[BPF_JLE  >> 4] = BPF_JGE,
7555 		[BPF_JLT  >> 4] = BPF_JGT,
7556 		[BPF_JSGE >> 4] = BPF_JSLE,
7557 		[BPF_JSGT >> 4] = BPF_JSLT,
7558 		[BPF_JSLE >> 4] = BPF_JSGE,
7559 		[BPF_JSLT >> 4] = BPF_JSGT
7560 	};
7561 	return opcode_flip[opcode >> 4];
7562 }
7563 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)7564 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7565 				   struct bpf_reg_state *src_reg,
7566 				   u8 opcode)
7567 {
7568 	struct bpf_reg_state *pkt;
7569 
7570 	if (src_reg->type == PTR_TO_PACKET_END) {
7571 		pkt = dst_reg;
7572 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
7573 		pkt = src_reg;
7574 		opcode = flip_opcode(opcode);
7575 	} else {
7576 		return -1;
7577 	}
7578 
7579 	if (pkt->range >= 0)
7580 		return -1;
7581 
7582 	switch (opcode) {
7583 	case BPF_JLE:
7584 		/* pkt <= pkt_end */
7585 		fallthrough;
7586 	case BPF_JGT:
7587 		/* pkt > pkt_end */
7588 		if (pkt->range == BEYOND_PKT_END)
7589 			/* pkt has at last one extra byte beyond pkt_end */
7590 			return opcode == BPF_JGT;
7591 		break;
7592 	case BPF_JLT:
7593 		/* pkt < pkt_end */
7594 		fallthrough;
7595 	case BPF_JGE:
7596 		/* pkt >= pkt_end */
7597 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7598 			return opcode == BPF_JGE;
7599 		break;
7600 	}
7601 	return -1;
7602 }
7603 
7604 /* Adjusts the register min/max values in the case that the dst_reg is the
7605  * variable register that we are working on, and src_reg is a constant or we're
7606  * simply doing a BPF_K check.
7607  * In JEQ/JNE cases we also adjust the var_off values.
7608  */
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)7609 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7610 			    struct bpf_reg_state *false_reg,
7611 			    u64 val, u32 val32,
7612 			    u8 opcode, bool is_jmp32)
7613 {
7614 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
7615 	struct tnum false_64off = false_reg->var_off;
7616 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
7617 	struct tnum true_64off = true_reg->var_off;
7618 	s64 sval = (s64)val;
7619 	s32 sval32 = (s32)val32;
7620 
7621 	/* If the dst_reg is a pointer, we can't learn anything about its
7622 	 * variable offset from the compare (unless src_reg were a pointer into
7623 	 * the same object, but we don't bother with that.
7624 	 * Since false_reg and true_reg have the same type by construction, we
7625 	 * only need to check one of them for pointerness.
7626 	 */
7627 	if (__is_pointer_value(false, false_reg))
7628 		return;
7629 
7630 	switch (opcode) {
7631 	/* JEQ/JNE comparison doesn't change the register equivalence.
7632 	 *
7633 	 * r1 = r2;
7634 	 * if (r1 == 42) goto label;
7635 	 * ...
7636 	 * label: // here both r1 and r2 are known to be 42.
7637 	 *
7638 	 * Hence when marking register as known preserve it's ID.
7639 	 */
7640 	case BPF_JEQ:
7641 		if (is_jmp32) {
7642 			__mark_reg32_known(true_reg, val32);
7643 			true_32off = tnum_subreg(true_reg->var_off);
7644 		} else {
7645 			___mark_reg_known(true_reg, val);
7646 			true_64off = true_reg->var_off;
7647 		}
7648 		break;
7649 	case BPF_JNE:
7650 		if (is_jmp32) {
7651 			__mark_reg32_known(false_reg, val32);
7652 			false_32off = tnum_subreg(false_reg->var_off);
7653 		} else {
7654 			___mark_reg_known(false_reg, val);
7655 			false_64off = false_reg->var_off;
7656 		}
7657 		break;
7658 	case BPF_JSET:
7659 		if (is_jmp32) {
7660 			false_32off = tnum_and(false_32off, tnum_const(~val32));
7661 			if (is_power_of_2(val32))
7662 				true_32off = tnum_or(true_32off,
7663 						     tnum_const(val32));
7664 		} else {
7665 			false_64off = tnum_and(false_64off, tnum_const(~val));
7666 			if (is_power_of_2(val))
7667 				true_64off = tnum_or(true_64off,
7668 						     tnum_const(val));
7669 		}
7670 		break;
7671 	case BPF_JGE:
7672 	case BPF_JGT:
7673 	{
7674 		if (is_jmp32) {
7675 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7676 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7677 
7678 			false_reg->u32_max_value = min(false_reg->u32_max_value,
7679 						       false_umax);
7680 			true_reg->u32_min_value = max(true_reg->u32_min_value,
7681 						      true_umin);
7682 		} else {
7683 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7684 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7685 
7686 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
7687 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
7688 		}
7689 		break;
7690 	}
7691 	case BPF_JSGE:
7692 	case BPF_JSGT:
7693 	{
7694 		if (is_jmp32) {
7695 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7696 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7697 
7698 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7699 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7700 		} else {
7701 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7702 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7703 
7704 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
7705 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
7706 		}
7707 		break;
7708 	}
7709 	case BPF_JLE:
7710 	case BPF_JLT:
7711 	{
7712 		if (is_jmp32) {
7713 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7714 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7715 
7716 			false_reg->u32_min_value = max(false_reg->u32_min_value,
7717 						       false_umin);
7718 			true_reg->u32_max_value = min(true_reg->u32_max_value,
7719 						      true_umax);
7720 		} else {
7721 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7722 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7723 
7724 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
7725 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
7726 		}
7727 		break;
7728 	}
7729 	case BPF_JSLE:
7730 	case BPF_JSLT:
7731 	{
7732 		if (is_jmp32) {
7733 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7734 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7735 
7736 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7737 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7738 		} else {
7739 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7740 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7741 
7742 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
7743 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
7744 		}
7745 		break;
7746 	}
7747 	default:
7748 		return;
7749 	}
7750 
7751 	if (is_jmp32) {
7752 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7753 					     tnum_subreg(false_32off));
7754 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7755 					    tnum_subreg(true_32off));
7756 		__reg_combine_32_into_64(false_reg);
7757 		__reg_combine_32_into_64(true_reg);
7758 	} else {
7759 		false_reg->var_off = false_64off;
7760 		true_reg->var_off = true_64off;
7761 		__reg_combine_64_into_32(false_reg);
7762 		__reg_combine_64_into_32(true_reg);
7763 	}
7764 }
7765 
7766 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7767  * the variable reg.
7768  */
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)7769 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7770 				struct bpf_reg_state *false_reg,
7771 				u64 val, u32 val32,
7772 				u8 opcode, bool is_jmp32)
7773 {
7774 	opcode = flip_opcode(opcode);
7775 	/* This uses zero as "not present in table"; luckily the zero opcode,
7776 	 * BPF_JA, can't get here.
7777 	 */
7778 	if (opcode)
7779 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7780 }
7781 
7782 /* 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)7783 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7784 				  struct bpf_reg_state *dst_reg)
7785 {
7786 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7787 							dst_reg->umin_value);
7788 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7789 							dst_reg->umax_value);
7790 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7791 							dst_reg->smin_value);
7792 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7793 							dst_reg->smax_value);
7794 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7795 							     dst_reg->var_off);
7796 	reg_bounds_sync(src_reg);
7797 	reg_bounds_sync(dst_reg);
7798 }
7799 
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)7800 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7801 				struct bpf_reg_state *true_dst,
7802 				struct bpf_reg_state *false_src,
7803 				struct bpf_reg_state *false_dst,
7804 				u8 opcode)
7805 {
7806 	switch (opcode) {
7807 	case BPF_JEQ:
7808 		__reg_combine_min_max(true_src, true_dst);
7809 		break;
7810 	case BPF_JNE:
7811 		__reg_combine_min_max(false_src, false_dst);
7812 		break;
7813 	}
7814 }
7815 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)7816 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7817 				 struct bpf_reg_state *reg, u32 id,
7818 				 bool is_null)
7819 {
7820 	if (type_may_be_null(reg->type) && reg->id == id &&
7821 	    !WARN_ON_ONCE(!reg->id)) {
7822 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7823 				 !tnum_equals_const(reg->var_off, 0) ||
7824 				 reg->off)) {
7825 			/* Old offset (both fixed and variable parts) should
7826 			 * have been known-zero, because we don't allow pointer
7827 			 * arithmetic on pointers that might be NULL. If we
7828 			 * see this happening, don't convert the register.
7829 			 */
7830 			return;
7831 		}
7832 		if (is_null) {
7833 			reg->type = SCALAR_VALUE;
7834 		} else if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
7835 			const struct bpf_map *map = reg->map_ptr;
7836 
7837 			if (map->inner_map_meta) {
7838 				reg->type = CONST_PTR_TO_MAP;
7839 				reg->map_ptr = map->inner_map_meta;
7840 			} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7841 				reg->type = PTR_TO_XDP_SOCK;
7842 			} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7843 				   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7844 				reg->type = PTR_TO_SOCKET;
7845 			} else {
7846 				reg->type = PTR_TO_MAP_VALUE;
7847 			}
7848 		} else {
7849 			reg->type &= ~PTR_MAYBE_NULL;
7850 		}
7851 
7852 		if (is_null) {
7853 			/* We don't need id and ref_obj_id from this point
7854 			 * onwards anymore, thus we should better reset it,
7855 			 * so that state pruning has chances to take effect.
7856 			 */
7857 			reg->id = 0;
7858 			reg->ref_obj_id = 0;
7859 		} else if (!reg_may_point_to_spin_lock(reg)) {
7860 			/* For not-NULL ptr, reg->ref_obj_id will be reset
7861 			 * in release_reference().
7862 			 *
7863 			 * reg->id is still used by spin_lock ptr. Other
7864 			 * than spin_lock ptr type, reg->id can be reset.
7865 			 */
7866 			reg->id = 0;
7867 		}
7868 	}
7869 }
7870 
7871 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7872  * be folded together at some point.
7873  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)7874 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7875 				  bool is_null)
7876 {
7877 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7878 	struct bpf_reg_state *regs = state->regs, *reg;
7879 	u32 ref_obj_id = regs[regno].ref_obj_id;
7880 	u32 id = regs[regno].id;
7881 
7882 	if (ref_obj_id && ref_obj_id == id && is_null)
7883 		/* regs[regno] is in the " == NULL" branch.
7884 		 * No one could have freed the reference state before
7885 		 * doing the NULL check.
7886 		 */
7887 		WARN_ON_ONCE(release_reference_state(state, id));
7888 
7889 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7890 		mark_ptr_or_null_reg(state, reg, id, is_null);
7891 	}));
7892 }
7893 
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)7894 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7895 				   struct bpf_reg_state *dst_reg,
7896 				   struct bpf_reg_state *src_reg,
7897 				   struct bpf_verifier_state *this_branch,
7898 				   struct bpf_verifier_state *other_branch)
7899 {
7900 	if (BPF_SRC(insn->code) != BPF_X)
7901 		return false;
7902 
7903 	/* Pointers are always 64-bit. */
7904 	if (BPF_CLASS(insn->code) == BPF_JMP32)
7905 		return false;
7906 
7907 	switch (BPF_OP(insn->code)) {
7908 	case BPF_JGT:
7909 		if ((dst_reg->type == PTR_TO_PACKET &&
7910 		     src_reg->type == PTR_TO_PACKET_END) ||
7911 		    (dst_reg->type == PTR_TO_PACKET_META &&
7912 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7913 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7914 			find_good_pkt_pointers(this_branch, dst_reg,
7915 					       dst_reg->type, false);
7916 			mark_pkt_end(other_branch, insn->dst_reg, true);
7917 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7918 			    src_reg->type == PTR_TO_PACKET) ||
7919 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7920 			    src_reg->type == PTR_TO_PACKET_META)) {
7921 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
7922 			find_good_pkt_pointers(other_branch, src_reg,
7923 					       src_reg->type, true);
7924 			mark_pkt_end(this_branch, insn->src_reg, false);
7925 		} else {
7926 			return false;
7927 		}
7928 		break;
7929 	case BPF_JLT:
7930 		if ((dst_reg->type == PTR_TO_PACKET &&
7931 		     src_reg->type == PTR_TO_PACKET_END) ||
7932 		    (dst_reg->type == PTR_TO_PACKET_META &&
7933 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7934 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7935 			find_good_pkt_pointers(other_branch, dst_reg,
7936 					       dst_reg->type, true);
7937 			mark_pkt_end(this_branch, insn->dst_reg, false);
7938 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7939 			    src_reg->type == PTR_TO_PACKET) ||
7940 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7941 			    src_reg->type == PTR_TO_PACKET_META)) {
7942 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
7943 			find_good_pkt_pointers(this_branch, src_reg,
7944 					       src_reg->type, false);
7945 			mark_pkt_end(other_branch, insn->src_reg, true);
7946 		} else {
7947 			return false;
7948 		}
7949 		break;
7950 	case BPF_JGE:
7951 		if ((dst_reg->type == PTR_TO_PACKET &&
7952 		     src_reg->type == PTR_TO_PACKET_END) ||
7953 		    (dst_reg->type == PTR_TO_PACKET_META &&
7954 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7955 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7956 			find_good_pkt_pointers(this_branch, dst_reg,
7957 					       dst_reg->type, true);
7958 			mark_pkt_end(other_branch, insn->dst_reg, false);
7959 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7960 			    src_reg->type == PTR_TO_PACKET) ||
7961 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7962 			    src_reg->type == PTR_TO_PACKET_META)) {
7963 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7964 			find_good_pkt_pointers(other_branch, src_reg,
7965 					       src_reg->type, false);
7966 			mark_pkt_end(this_branch, insn->src_reg, true);
7967 		} else {
7968 			return false;
7969 		}
7970 		break;
7971 	case BPF_JLE:
7972 		if ((dst_reg->type == PTR_TO_PACKET &&
7973 		     src_reg->type == PTR_TO_PACKET_END) ||
7974 		    (dst_reg->type == PTR_TO_PACKET_META &&
7975 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7976 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7977 			find_good_pkt_pointers(other_branch, dst_reg,
7978 					       dst_reg->type, false);
7979 			mark_pkt_end(this_branch, insn->dst_reg, true);
7980 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7981 			    src_reg->type == PTR_TO_PACKET) ||
7982 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7983 			    src_reg->type == PTR_TO_PACKET_META)) {
7984 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7985 			find_good_pkt_pointers(this_branch, src_reg,
7986 					       src_reg->type, true);
7987 			mark_pkt_end(other_branch, insn->src_reg, false);
7988 		} else {
7989 			return false;
7990 		}
7991 		break;
7992 	default:
7993 		return false;
7994 	}
7995 
7996 	return true;
7997 }
7998 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)7999 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8000 			       struct bpf_reg_state *known_reg)
8001 {
8002 	struct bpf_func_state *state;
8003 	struct bpf_reg_state *reg;
8004 
8005 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8006 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8007 			*reg = *known_reg;
8008 	}));
8009 }
8010 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)8011 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8012 			     struct bpf_insn *insn, int *insn_idx)
8013 {
8014 	struct bpf_verifier_state *this_branch = env->cur_state;
8015 	struct bpf_verifier_state *other_branch;
8016 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8017 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8018 	u8 opcode = BPF_OP(insn->code);
8019 	bool is_jmp32;
8020 	int pred = -1;
8021 	int err;
8022 
8023 	/* Only conditional jumps are expected to reach here. */
8024 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8025 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8026 		return -EINVAL;
8027 	}
8028 
8029 	if (BPF_SRC(insn->code) == BPF_X) {
8030 		if (insn->imm != 0) {
8031 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8032 			return -EINVAL;
8033 		}
8034 
8035 		/* check src1 operand */
8036 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8037 		if (err)
8038 			return err;
8039 
8040 		if (is_pointer_value(env, insn->src_reg)) {
8041 			verbose(env, "R%d pointer comparison prohibited\n",
8042 				insn->src_reg);
8043 			return -EACCES;
8044 		}
8045 		src_reg = &regs[insn->src_reg];
8046 	} else {
8047 		if (insn->src_reg != BPF_REG_0) {
8048 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8049 			return -EINVAL;
8050 		}
8051 	}
8052 
8053 	/* check src2 operand */
8054 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8055 	if (err)
8056 		return err;
8057 
8058 	dst_reg = &regs[insn->dst_reg];
8059 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8060 
8061 	if (BPF_SRC(insn->code) == BPF_K) {
8062 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8063 	} else if (src_reg->type == SCALAR_VALUE &&
8064 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8065 		pred = is_branch_taken(dst_reg,
8066 				       tnum_subreg(src_reg->var_off).value,
8067 				       opcode,
8068 				       is_jmp32);
8069 	} else if (src_reg->type == SCALAR_VALUE &&
8070 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8071 		pred = is_branch_taken(dst_reg,
8072 				       src_reg->var_off.value,
8073 				       opcode,
8074 				       is_jmp32);
8075 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8076 		   reg_is_pkt_pointer_any(src_reg) &&
8077 		   !is_jmp32) {
8078 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8079 	}
8080 
8081 	if (pred >= 0) {
8082 		/* If we get here with a dst_reg pointer type it is because
8083 		 * above is_branch_taken() special cased the 0 comparison.
8084 		 */
8085 		if (!__is_pointer_value(false, dst_reg))
8086 			err = mark_chain_precision(env, insn->dst_reg);
8087 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8088 		    !__is_pointer_value(false, src_reg))
8089 			err = mark_chain_precision(env, insn->src_reg);
8090 		if (err)
8091 			return err;
8092 	}
8093 
8094 	if (pred == 1) {
8095 		/* Only follow the goto, ignore fall-through. If needed, push
8096 		 * the fall-through branch for simulation under speculative
8097 		 * execution.
8098 		 */
8099 		if (!env->bypass_spec_v1 &&
8100 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
8101 					       *insn_idx))
8102 			return -EFAULT;
8103 		*insn_idx += insn->off;
8104 		return 0;
8105 	} else if (pred == 0) {
8106 		/* Only follow the fall-through branch, since that's where the
8107 		 * program will go. If needed, push the goto branch for
8108 		 * simulation under speculative execution.
8109 		 */
8110 		if (!env->bypass_spec_v1 &&
8111 		    !sanitize_speculative_path(env, insn,
8112 					       *insn_idx + insn->off + 1,
8113 					       *insn_idx))
8114 			return -EFAULT;
8115 		return 0;
8116 	}
8117 
8118 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8119 				  false);
8120 	if (!other_branch)
8121 		return -EFAULT;
8122 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8123 
8124 	/* detect if we are comparing against a constant value so we can adjust
8125 	 * our min/max values for our dst register.
8126 	 * this is only legit if both are scalars (or pointers to the same
8127 	 * object, I suppose, but we don't support that right now), because
8128 	 * otherwise the different base pointers mean the offsets aren't
8129 	 * comparable.
8130 	 */
8131 	if (BPF_SRC(insn->code) == BPF_X) {
8132 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8133 
8134 		if (dst_reg->type == SCALAR_VALUE &&
8135 		    src_reg->type == SCALAR_VALUE) {
8136 			if (tnum_is_const(src_reg->var_off) ||
8137 			    (is_jmp32 &&
8138 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8139 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8140 						dst_reg,
8141 						src_reg->var_off.value,
8142 						tnum_subreg(src_reg->var_off).value,
8143 						opcode, is_jmp32);
8144 			else if (tnum_is_const(dst_reg->var_off) ||
8145 				 (is_jmp32 &&
8146 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8147 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8148 						    src_reg,
8149 						    dst_reg->var_off.value,
8150 						    tnum_subreg(dst_reg->var_off).value,
8151 						    opcode, is_jmp32);
8152 			else if (!is_jmp32 &&
8153 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8154 				/* Comparing for equality, we can combine knowledge */
8155 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8156 						    &other_branch_regs[insn->dst_reg],
8157 						    src_reg, dst_reg, opcode);
8158 			if (src_reg->id &&
8159 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8160 				find_equal_scalars(this_branch, src_reg);
8161 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8162 			}
8163 
8164 		}
8165 	} else if (dst_reg->type == SCALAR_VALUE) {
8166 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8167 					dst_reg, insn->imm, (u32)insn->imm,
8168 					opcode, is_jmp32);
8169 	}
8170 
8171 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8172 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8173 		find_equal_scalars(this_branch, dst_reg);
8174 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8175 	}
8176 
8177 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8178 	 * NOTE: these optimizations below are related with pointer comparison
8179 	 *       which will never be JMP32.
8180 	 */
8181 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8182 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8183 	    type_may_be_null(dst_reg->type)) {
8184 		/* Mark all identical registers in each branch as either
8185 		 * safe or unknown depending R == 0 or R != 0 conditional.
8186 		 */
8187 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8188 				      opcode == BPF_JNE);
8189 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8190 				      opcode == BPF_JEQ);
8191 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8192 					   this_branch, other_branch) &&
8193 		   is_pointer_value(env, insn->dst_reg)) {
8194 		verbose(env, "R%d pointer comparison prohibited\n",
8195 			insn->dst_reg);
8196 		return -EACCES;
8197 	}
8198 	if (env->log.level & BPF_LOG_LEVEL)
8199 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8200 	return 0;
8201 }
8202 
8203 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)8204 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8205 {
8206 	struct bpf_insn_aux_data *aux = cur_aux(env);
8207 	struct bpf_reg_state *regs = cur_regs(env);
8208 	struct bpf_reg_state *dst_reg;
8209 	struct bpf_map *map;
8210 	int err;
8211 
8212 	if (BPF_SIZE(insn->code) != BPF_DW) {
8213 		verbose(env, "invalid BPF_LD_IMM insn\n");
8214 		return -EINVAL;
8215 	}
8216 	if (insn->off != 0) {
8217 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8218 		return -EINVAL;
8219 	}
8220 
8221 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8222 	if (err)
8223 		return err;
8224 
8225 	dst_reg = &regs[insn->dst_reg];
8226 	if (insn->src_reg == 0) {
8227 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8228 
8229 		dst_reg->type = SCALAR_VALUE;
8230 		__mark_reg_known(&regs[insn->dst_reg], imm);
8231 		return 0;
8232 	}
8233 
8234 	/* All special src_reg cases are listed below. From this point onwards
8235 	 * we either succeed and assign a corresponding dst_reg->type after
8236 	 * zeroing the offset, or fail and reject the program.
8237 	 */
8238 	mark_reg_known_zero(env, regs, insn->dst_reg);
8239 
8240 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8241 		dst_reg->type = aux->btf_var.reg_type;
8242 		switch (base_type(dst_reg->type)) {
8243 		case PTR_TO_MEM:
8244 			dst_reg->mem_size = aux->btf_var.mem_size;
8245 			break;
8246 		case PTR_TO_BTF_ID:
8247 		case PTR_TO_PERCPU_BTF_ID:
8248 			dst_reg->btf_id = aux->btf_var.btf_id;
8249 			break;
8250 		default:
8251 			verbose(env, "bpf verifier is misconfigured\n");
8252 			return -EFAULT;
8253 		}
8254 		return 0;
8255 	}
8256 
8257 	map = env->used_maps[aux->map_index];
8258 	dst_reg->map_ptr = map;
8259 
8260 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8261 		dst_reg->type = PTR_TO_MAP_VALUE;
8262 		dst_reg->off = aux->map_off;
8263 		if (map_value_has_spin_lock(map))
8264 			dst_reg->id = ++env->id_gen;
8265 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8266 		dst_reg->type = CONST_PTR_TO_MAP;
8267 	} else {
8268 		verbose(env, "bpf verifier is misconfigured\n");
8269 		return -EINVAL;
8270 	}
8271 
8272 	return 0;
8273 }
8274 
may_access_skb(enum bpf_prog_type type)8275 static bool may_access_skb(enum bpf_prog_type type)
8276 {
8277 	switch (type) {
8278 	case BPF_PROG_TYPE_SOCKET_FILTER:
8279 	case BPF_PROG_TYPE_SCHED_CLS:
8280 	case BPF_PROG_TYPE_SCHED_ACT:
8281 		return true;
8282 	default:
8283 		return false;
8284 	}
8285 }
8286 
8287 /* verify safety of LD_ABS|LD_IND instructions:
8288  * - they can only appear in the programs where ctx == skb
8289  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8290  *   preserve R6-R9, and store return value into R0
8291  *
8292  * Implicit input:
8293  *   ctx == skb == R6 == CTX
8294  *
8295  * Explicit input:
8296  *   SRC == any register
8297  *   IMM == 32-bit immediate
8298  *
8299  * Output:
8300  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8301  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)8302 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8303 {
8304 	struct bpf_reg_state *regs = cur_regs(env);
8305 	static const int ctx_reg = BPF_REG_6;
8306 	u8 mode = BPF_MODE(insn->code);
8307 	int i, err;
8308 
8309 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8310 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8311 		return -EINVAL;
8312 	}
8313 
8314 	if (!env->ops->gen_ld_abs) {
8315 		verbose(env, "bpf verifier is misconfigured\n");
8316 		return -EINVAL;
8317 	}
8318 
8319 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8320 	    BPF_SIZE(insn->code) == BPF_DW ||
8321 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8322 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8323 		return -EINVAL;
8324 	}
8325 
8326 	/* check whether implicit source operand (register R6) is readable */
8327 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8328 	if (err)
8329 		return err;
8330 
8331 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8332 	 * gen_ld_abs() may terminate the program at runtime, leading to
8333 	 * reference leak.
8334 	 */
8335 	err = check_reference_leak(env);
8336 	if (err) {
8337 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8338 		return err;
8339 	}
8340 
8341 	if (env->cur_state->active_spin_lock) {
8342 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8343 		return -EINVAL;
8344 	}
8345 
8346 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8347 		verbose(env,
8348 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8349 		return -EINVAL;
8350 	}
8351 
8352 	if (mode == BPF_IND) {
8353 		/* check explicit source operand */
8354 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8355 		if (err)
8356 			return err;
8357 	}
8358 
8359 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
8360 	if (err < 0)
8361 		return err;
8362 
8363 	/* reset caller saved regs to unreadable */
8364 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8365 		mark_reg_not_init(env, regs, caller_saved[i]);
8366 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8367 	}
8368 
8369 	/* mark destination R0 register as readable, since it contains
8370 	 * the value fetched from the packet.
8371 	 * Already marked as written above.
8372 	 */
8373 	mark_reg_unknown(env, regs, BPF_REG_0);
8374 	/* ld_abs load up to 32-bit skb data. */
8375 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8376 	return 0;
8377 }
8378 
check_return_code(struct bpf_verifier_env * env)8379 static int check_return_code(struct bpf_verifier_env *env)
8380 {
8381 	struct tnum enforce_attach_type_range = tnum_unknown;
8382 	const struct bpf_prog *prog = env->prog;
8383 	struct bpf_reg_state *reg;
8384 	struct tnum range = tnum_range(0, 1);
8385 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8386 	int err;
8387 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8388 
8389 	/* LSM and struct_ops func-ptr's return type could be "void" */
8390 	if (!is_subprog &&
8391 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8392 	     prog_type == BPF_PROG_TYPE_LSM) &&
8393 	    !prog->aux->attach_func_proto->type)
8394 		return 0;
8395 
8396 	/* eBPF calling convetion is such that R0 is used
8397 	 * to return the value from eBPF program.
8398 	 * Make sure that it's readable at this time
8399 	 * of bpf_exit, which means that program wrote
8400 	 * something into it earlier
8401 	 */
8402 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8403 	if (err)
8404 		return err;
8405 
8406 	if (is_pointer_value(env, BPF_REG_0)) {
8407 		verbose(env, "R0 leaks addr as return value\n");
8408 		return -EACCES;
8409 	}
8410 
8411 	reg = cur_regs(env) + BPF_REG_0;
8412 	if (is_subprog) {
8413 		if (reg->type != SCALAR_VALUE) {
8414 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8415 				reg_type_str(env, reg->type));
8416 			return -EINVAL;
8417 		}
8418 		return 0;
8419 	}
8420 
8421 	switch (prog_type) {
8422 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8423 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8424 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8425 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8426 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8427 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8428 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8429 			range = tnum_range(1, 1);
8430 		break;
8431 	case BPF_PROG_TYPE_CGROUP_SKB:
8432 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8433 			range = tnum_range(0, 3);
8434 			enforce_attach_type_range = tnum_range(2, 3);
8435 		}
8436 		break;
8437 	case BPF_PROG_TYPE_CGROUP_SOCK:
8438 	case BPF_PROG_TYPE_SOCK_OPS:
8439 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8440 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8441 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8442 		break;
8443 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8444 		if (!env->prog->aux->attach_btf_id)
8445 			return 0;
8446 		range = tnum_const(0);
8447 		break;
8448 	case BPF_PROG_TYPE_TRACING:
8449 		switch (env->prog->expected_attach_type) {
8450 		case BPF_TRACE_FENTRY:
8451 		case BPF_TRACE_FEXIT:
8452 			range = tnum_const(0);
8453 			break;
8454 		case BPF_TRACE_RAW_TP:
8455 		case BPF_MODIFY_RETURN:
8456 			return 0;
8457 		case BPF_TRACE_ITER:
8458 			break;
8459 		default:
8460 			return -ENOTSUPP;
8461 		}
8462 		break;
8463 	case BPF_PROG_TYPE_SK_LOOKUP:
8464 		range = tnum_range(SK_DROP, SK_PASS);
8465 		break;
8466 	case BPF_PROG_TYPE_EXT:
8467 		/* freplace program can return anything as its return value
8468 		 * depends on the to-be-replaced kernel func or bpf program.
8469 		 */
8470 	default:
8471 		return 0;
8472 	}
8473 
8474 	if (reg->type != SCALAR_VALUE) {
8475 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8476 			reg_type_str(env, reg->type));
8477 		return -EINVAL;
8478 	}
8479 
8480 	if (!tnum_in(range, reg->var_off)) {
8481 		char tn_buf[48];
8482 
8483 		verbose(env, "At program exit the register R0 ");
8484 		if (!tnum_is_unknown(reg->var_off)) {
8485 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8486 			verbose(env, "has value %s", tn_buf);
8487 		} else {
8488 			verbose(env, "has unknown scalar value");
8489 		}
8490 		tnum_strn(tn_buf, sizeof(tn_buf), range);
8491 		verbose(env, " should have been in %s\n", tn_buf);
8492 		return -EINVAL;
8493 	}
8494 
8495 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8496 	    tnum_in(enforce_attach_type_range, reg->var_off))
8497 		env->prog->enforce_expected_attach_type = 1;
8498 	return 0;
8499 }
8500 
8501 /* non-recursive DFS pseudo code
8502  * 1  procedure DFS-iterative(G,v):
8503  * 2      label v as discovered
8504  * 3      let S be a stack
8505  * 4      S.push(v)
8506  * 5      while S is not empty
8507  * 6            t <- S.pop()
8508  * 7            if t is what we're looking for:
8509  * 8                return t
8510  * 9            for all edges e in G.adjacentEdges(t) do
8511  * 10               if edge e is already labelled
8512  * 11                   continue with the next edge
8513  * 12               w <- G.adjacentVertex(t,e)
8514  * 13               if vertex w is not discovered and not explored
8515  * 14                   label e as tree-edge
8516  * 15                   label w as discovered
8517  * 16                   S.push(w)
8518  * 17                   continue at 5
8519  * 18               else if vertex w is discovered
8520  * 19                   label e as back-edge
8521  * 20               else
8522  * 21                   // vertex w is explored
8523  * 22                   label e as forward- or cross-edge
8524  * 23           label t as explored
8525  * 24           S.pop()
8526  *
8527  * convention:
8528  * 0x10 - discovered
8529  * 0x11 - discovered and fall-through edge labelled
8530  * 0x12 - discovered and fall-through and branch edges labelled
8531  * 0x20 - explored
8532  */
8533 
8534 enum {
8535 	DISCOVERED = 0x10,
8536 	EXPLORED = 0x20,
8537 	FALLTHROUGH = 1,
8538 	BRANCH = 2,
8539 };
8540 
state_htab_size(struct bpf_verifier_env * env)8541 static u32 state_htab_size(struct bpf_verifier_env *env)
8542 {
8543 	return env->prog->len;
8544 }
8545 
explored_state(struct bpf_verifier_env * env,int idx)8546 static struct bpf_verifier_state_list **explored_state(
8547 					struct bpf_verifier_env *env,
8548 					int idx)
8549 {
8550 	struct bpf_verifier_state *cur = env->cur_state;
8551 	struct bpf_func_state *state = cur->frame[cur->curframe];
8552 
8553 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8554 }
8555 
init_explored_state(struct bpf_verifier_env * env,int idx)8556 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8557 {
8558 	env->insn_aux_data[idx].prune_point = true;
8559 }
8560 
8561 /* t, w, e - match pseudo-code above:
8562  * t - index of current instruction
8563  * w - next instruction
8564  * e - edge
8565  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)8566 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8567 		     bool loop_ok)
8568 {
8569 	int *insn_stack = env->cfg.insn_stack;
8570 	int *insn_state = env->cfg.insn_state;
8571 
8572 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8573 		return 0;
8574 
8575 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8576 		return 0;
8577 
8578 	if (w < 0 || w >= env->prog->len) {
8579 		verbose_linfo(env, t, "%d: ", t);
8580 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8581 		return -EINVAL;
8582 	}
8583 
8584 	if (e == BRANCH)
8585 		/* mark branch target for state pruning */
8586 		init_explored_state(env, w);
8587 
8588 	if (insn_state[w] == 0) {
8589 		/* tree-edge */
8590 		insn_state[t] = DISCOVERED | e;
8591 		insn_state[w] = DISCOVERED;
8592 		if (env->cfg.cur_stack >= env->prog->len)
8593 			return -E2BIG;
8594 		insn_stack[env->cfg.cur_stack++] = w;
8595 		return 1;
8596 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8597 		if (loop_ok && env->bpf_capable)
8598 			return 0;
8599 		verbose_linfo(env, t, "%d: ", t);
8600 		verbose_linfo(env, w, "%d: ", w);
8601 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8602 		return -EINVAL;
8603 	} else if (insn_state[w] == EXPLORED) {
8604 		/* forward- or cross-edge */
8605 		insn_state[t] = DISCOVERED | e;
8606 	} else {
8607 		verbose(env, "insn state internal bug\n");
8608 		return -EFAULT;
8609 	}
8610 	return 0;
8611 }
8612 
8613 /* non-recursive depth-first-search to detect loops in BPF program
8614  * loop == back-edge in directed graph
8615  */
check_cfg(struct bpf_verifier_env * env)8616 static int check_cfg(struct bpf_verifier_env *env)
8617 {
8618 	struct bpf_insn *insns = env->prog->insnsi;
8619 	int insn_cnt = env->prog->len;
8620 	int *insn_stack, *insn_state;
8621 	int ret = 0;
8622 	int i, t;
8623 
8624 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8625 	if (!insn_state)
8626 		return -ENOMEM;
8627 
8628 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8629 	if (!insn_stack) {
8630 		kvfree(insn_state);
8631 		return -ENOMEM;
8632 	}
8633 
8634 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8635 	insn_stack[0] = 0; /* 0 is the first instruction */
8636 	env->cfg.cur_stack = 1;
8637 
8638 peek_stack:
8639 	if (env->cfg.cur_stack == 0)
8640 		goto check_state;
8641 	t = insn_stack[env->cfg.cur_stack - 1];
8642 
8643 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8644 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
8645 		u8 opcode = BPF_OP(insns[t].code);
8646 
8647 		if (opcode == BPF_EXIT) {
8648 			goto mark_explored;
8649 		} else if (opcode == BPF_CALL) {
8650 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8651 			if (ret == 1)
8652 				goto peek_stack;
8653 			else if (ret < 0)
8654 				goto err_free;
8655 			if (t + 1 < insn_cnt)
8656 				init_explored_state(env, t + 1);
8657 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8658 				init_explored_state(env, t);
8659 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8660 						env, false);
8661 				if (ret == 1)
8662 					goto peek_stack;
8663 				else if (ret < 0)
8664 					goto err_free;
8665 			}
8666 		} else if (opcode == BPF_JA) {
8667 			if (BPF_SRC(insns[t].code) != BPF_K) {
8668 				ret = -EINVAL;
8669 				goto err_free;
8670 			}
8671 			/* unconditional jump with single edge */
8672 			ret = push_insn(t, t + insns[t].off + 1,
8673 					FALLTHROUGH, env, true);
8674 			if (ret == 1)
8675 				goto peek_stack;
8676 			else if (ret < 0)
8677 				goto err_free;
8678 			/* unconditional jmp is not a good pruning point,
8679 			 * but it's marked, since backtracking needs
8680 			 * to record jmp history in is_state_visited().
8681 			 */
8682 			init_explored_state(env, t + insns[t].off + 1);
8683 			/* tell verifier to check for equivalent states
8684 			 * after every call and jump
8685 			 */
8686 			if (t + 1 < insn_cnt)
8687 				init_explored_state(env, t + 1);
8688 		} else {
8689 			/* conditional jump with two edges */
8690 			init_explored_state(env, t);
8691 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8692 			if (ret == 1)
8693 				goto peek_stack;
8694 			else if (ret < 0)
8695 				goto err_free;
8696 
8697 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8698 			if (ret == 1)
8699 				goto peek_stack;
8700 			else if (ret < 0)
8701 				goto err_free;
8702 		}
8703 	} else {
8704 		/* all other non-branch instructions with single
8705 		 * fall-through edge
8706 		 */
8707 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8708 		if (ret == 1)
8709 			goto peek_stack;
8710 		else if (ret < 0)
8711 			goto err_free;
8712 	}
8713 
8714 mark_explored:
8715 	insn_state[t] = EXPLORED;
8716 	if (env->cfg.cur_stack-- <= 0) {
8717 		verbose(env, "pop stack internal bug\n");
8718 		ret = -EFAULT;
8719 		goto err_free;
8720 	}
8721 	goto peek_stack;
8722 
8723 check_state:
8724 	for (i = 0; i < insn_cnt; i++) {
8725 		if (insn_state[i] != EXPLORED) {
8726 			verbose(env, "unreachable insn %d\n", i);
8727 			ret = -EINVAL;
8728 			goto err_free;
8729 		}
8730 	}
8731 	ret = 0; /* cfg looks good */
8732 
8733 err_free:
8734 	kvfree(insn_state);
8735 	kvfree(insn_stack);
8736 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8737 	return ret;
8738 }
8739 
check_abnormal_return(struct bpf_verifier_env * env)8740 static int check_abnormal_return(struct bpf_verifier_env *env)
8741 {
8742 	int i;
8743 
8744 	for (i = 1; i < env->subprog_cnt; i++) {
8745 		if (env->subprog_info[i].has_ld_abs) {
8746 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8747 			return -EINVAL;
8748 		}
8749 		if (env->subprog_info[i].has_tail_call) {
8750 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8751 			return -EINVAL;
8752 		}
8753 	}
8754 	return 0;
8755 }
8756 
8757 /* The minimum supported BTF func info size */
8758 #define MIN_BPF_FUNCINFO_SIZE	8
8759 #define MAX_FUNCINFO_REC_SIZE	252
8760 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8761 static int check_btf_func(struct bpf_verifier_env *env,
8762 			  const union bpf_attr *attr,
8763 			  union bpf_attr __user *uattr)
8764 {
8765 	const struct btf_type *type, *func_proto, *ret_type;
8766 	u32 i, nfuncs, urec_size, min_size;
8767 	u32 krec_size = sizeof(struct bpf_func_info);
8768 	struct bpf_func_info *krecord;
8769 	struct bpf_func_info_aux *info_aux = NULL;
8770 	struct bpf_prog *prog;
8771 	const struct btf *btf;
8772 	void __user *urecord;
8773 	u32 prev_offset = 0;
8774 	bool scalar_return;
8775 	int ret = -ENOMEM;
8776 
8777 	nfuncs = attr->func_info_cnt;
8778 	if (!nfuncs) {
8779 		if (check_abnormal_return(env))
8780 			return -EINVAL;
8781 		return 0;
8782 	}
8783 
8784 	if (nfuncs != env->subprog_cnt) {
8785 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8786 		return -EINVAL;
8787 	}
8788 
8789 	urec_size = attr->func_info_rec_size;
8790 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8791 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
8792 	    urec_size % sizeof(u32)) {
8793 		verbose(env, "invalid func info rec size %u\n", urec_size);
8794 		return -EINVAL;
8795 	}
8796 
8797 	prog = env->prog;
8798 	btf = prog->aux->btf;
8799 
8800 	urecord = u64_to_user_ptr(attr->func_info);
8801 	min_size = min_t(u32, krec_size, urec_size);
8802 
8803 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8804 	if (!krecord)
8805 		return -ENOMEM;
8806 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8807 	if (!info_aux)
8808 		goto err_free;
8809 
8810 	for (i = 0; i < nfuncs; i++) {
8811 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8812 		if (ret) {
8813 			if (ret == -E2BIG) {
8814 				verbose(env, "nonzero tailing record in func info");
8815 				/* set the size kernel expects so loader can zero
8816 				 * out the rest of the record.
8817 				 */
8818 				if (put_user(min_size, &uattr->func_info_rec_size))
8819 					ret = -EFAULT;
8820 			}
8821 			goto err_free;
8822 		}
8823 
8824 		if (copy_from_user(&krecord[i], urecord, min_size)) {
8825 			ret = -EFAULT;
8826 			goto err_free;
8827 		}
8828 
8829 		/* check insn_off */
8830 		ret = -EINVAL;
8831 		if (i == 0) {
8832 			if (krecord[i].insn_off) {
8833 				verbose(env,
8834 					"nonzero insn_off %u for the first func info record",
8835 					krecord[i].insn_off);
8836 				goto err_free;
8837 			}
8838 		} else if (krecord[i].insn_off <= prev_offset) {
8839 			verbose(env,
8840 				"same or smaller insn offset (%u) than previous func info record (%u)",
8841 				krecord[i].insn_off, prev_offset);
8842 			goto err_free;
8843 		}
8844 
8845 		if (env->subprog_info[i].start != krecord[i].insn_off) {
8846 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8847 			goto err_free;
8848 		}
8849 
8850 		/* check type_id */
8851 		type = btf_type_by_id(btf, krecord[i].type_id);
8852 		if (!type || !btf_type_is_func(type)) {
8853 			verbose(env, "invalid type id %d in func info",
8854 				krecord[i].type_id);
8855 			goto err_free;
8856 		}
8857 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8858 
8859 		func_proto = btf_type_by_id(btf, type->type);
8860 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8861 			/* btf_func_check() already verified it during BTF load */
8862 			goto err_free;
8863 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8864 		scalar_return =
8865 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8866 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8867 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8868 			goto err_free;
8869 		}
8870 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8871 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8872 			goto err_free;
8873 		}
8874 
8875 		prev_offset = krecord[i].insn_off;
8876 		urecord += urec_size;
8877 	}
8878 
8879 	prog->aux->func_info = krecord;
8880 	prog->aux->func_info_cnt = nfuncs;
8881 	prog->aux->func_info_aux = info_aux;
8882 	return 0;
8883 
8884 err_free:
8885 	kvfree(krecord);
8886 	kfree(info_aux);
8887 	return ret;
8888 }
8889 
adjust_btf_func(struct bpf_verifier_env * env)8890 static void adjust_btf_func(struct bpf_verifier_env *env)
8891 {
8892 	struct bpf_prog_aux *aux = env->prog->aux;
8893 	int i;
8894 
8895 	if (!aux->func_info)
8896 		return;
8897 
8898 	for (i = 0; i < env->subprog_cnt; i++)
8899 		aux->func_info[i].insn_off = env->subprog_info[i].start;
8900 }
8901 
8902 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
8903 		sizeof(((struct bpf_line_info *)(0))->line_col))
8904 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
8905 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8906 static int check_btf_line(struct bpf_verifier_env *env,
8907 			  const union bpf_attr *attr,
8908 			  union bpf_attr __user *uattr)
8909 {
8910 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8911 	struct bpf_subprog_info *sub;
8912 	struct bpf_line_info *linfo;
8913 	struct bpf_prog *prog;
8914 	const struct btf *btf;
8915 	void __user *ulinfo;
8916 	int err;
8917 
8918 	nr_linfo = attr->line_info_cnt;
8919 	if (!nr_linfo)
8920 		return 0;
8921 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
8922 		return -EINVAL;
8923 
8924 	rec_size = attr->line_info_rec_size;
8925 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8926 	    rec_size > MAX_LINEINFO_REC_SIZE ||
8927 	    rec_size & (sizeof(u32) - 1))
8928 		return -EINVAL;
8929 
8930 	/* Need to zero it in case the userspace may
8931 	 * pass in a smaller bpf_line_info object.
8932 	 */
8933 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8934 			 GFP_KERNEL | __GFP_NOWARN);
8935 	if (!linfo)
8936 		return -ENOMEM;
8937 
8938 	prog = env->prog;
8939 	btf = prog->aux->btf;
8940 
8941 	s = 0;
8942 	sub = env->subprog_info;
8943 	ulinfo = u64_to_user_ptr(attr->line_info);
8944 	expected_size = sizeof(struct bpf_line_info);
8945 	ncopy = min_t(u32, expected_size, rec_size);
8946 	for (i = 0; i < nr_linfo; i++) {
8947 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8948 		if (err) {
8949 			if (err == -E2BIG) {
8950 				verbose(env, "nonzero tailing record in line_info");
8951 				if (put_user(expected_size,
8952 					     &uattr->line_info_rec_size))
8953 					err = -EFAULT;
8954 			}
8955 			goto err_free;
8956 		}
8957 
8958 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8959 			err = -EFAULT;
8960 			goto err_free;
8961 		}
8962 
8963 		/*
8964 		 * Check insn_off to ensure
8965 		 * 1) strictly increasing AND
8966 		 * 2) bounded by prog->len
8967 		 *
8968 		 * The linfo[0].insn_off == 0 check logically falls into
8969 		 * the later "missing bpf_line_info for func..." case
8970 		 * because the first linfo[0].insn_off must be the
8971 		 * first sub also and the first sub must have
8972 		 * subprog_info[0].start == 0.
8973 		 */
8974 		if ((i && linfo[i].insn_off <= prev_offset) ||
8975 		    linfo[i].insn_off >= prog->len) {
8976 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8977 				i, linfo[i].insn_off, prev_offset,
8978 				prog->len);
8979 			err = -EINVAL;
8980 			goto err_free;
8981 		}
8982 
8983 		if (!prog->insnsi[linfo[i].insn_off].code) {
8984 			verbose(env,
8985 				"Invalid insn code at line_info[%u].insn_off\n",
8986 				i);
8987 			err = -EINVAL;
8988 			goto err_free;
8989 		}
8990 
8991 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8992 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
8993 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8994 			err = -EINVAL;
8995 			goto err_free;
8996 		}
8997 
8998 		if (s != env->subprog_cnt) {
8999 			if (linfo[i].insn_off == sub[s].start) {
9000 				sub[s].linfo_idx = i;
9001 				s++;
9002 			} else if (sub[s].start < linfo[i].insn_off) {
9003 				verbose(env, "missing bpf_line_info for func#%u\n", s);
9004 				err = -EINVAL;
9005 				goto err_free;
9006 			}
9007 		}
9008 
9009 		prev_offset = linfo[i].insn_off;
9010 		ulinfo += rec_size;
9011 	}
9012 
9013 	if (s != env->subprog_cnt) {
9014 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9015 			env->subprog_cnt - s, s);
9016 		err = -EINVAL;
9017 		goto err_free;
9018 	}
9019 
9020 	prog->aux->linfo = linfo;
9021 	prog->aux->nr_linfo = nr_linfo;
9022 
9023 	return 0;
9024 
9025 err_free:
9026 	kvfree(linfo);
9027 	return err;
9028 }
9029 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9030 static int check_btf_info(struct bpf_verifier_env *env,
9031 			  const union bpf_attr *attr,
9032 			  union bpf_attr __user *uattr)
9033 {
9034 	struct btf *btf;
9035 	int err;
9036 
9037 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9038 		if (check_abnormal_return(env))
9039 			return -EINVAL;
9040 		return 0;
9041 	}
9042 
9043 	btf = btf_get_by_fd(attr->prog_btf_fd);
9044 	if (IS_ERR(btf))
9045 		return PTR_ERR(btf);
9046 	env->prog->aux->btf = btf;
9047 
9048 	err = check_btf_func(env, attr, uattr);
9049 	if (err)
9050 		return err;
9051 
9052 	err = check_btf_line(env, attr, uattr);
9053 	if (err)
9054 		return err;
9055 
9056 	return 0;
9057 }
9058 
9059 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)9060 static bool range_within(struct bpf_reg_state *old,
9061 			 struct bpf_reg_state *cur)
9062 {
9063 	return old->umin_value <= cur->umin_value &&
9064 	       old->umax_value >= cur->umax_value &&
9065 	       old->smin_value <= cur->smin_value &&
9066 	       old->smax_value >= cur->smax_value &&
9067 	       old->u32_min_value <= cur->u32_min_value &&
9068 	       old->u32_max_value >= cur->u32_max_value &&
9069 	       old->s32_min_value <= cur->s32_min_value &&
9070 	       old->s32_max_value >= cur->s32_max_value;
9071 }
9072 
9073 /* If in the old state two registers had the same id, then they need to have
9074  * the same id in the new state as well.  But that id could be different from
9075  * the old state, so we need to track the mapping from old to new ids.
9076  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9077  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9078  * regs with a different old id could still have new id 9, we don't care about
9079  * that.
9080  * So we look through our idmap to see if this old id has been seen before.  If
9081  * so, we require the new id to match; otherwise, we add the id pair to the map.
9082  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)9083 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9084 {
9085 	unsigned int i;
9086 
9087 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9088 		if (!idmap[i].old) {
9089 			/* Reached an empty slot; haven't seen this id before */
9090 			idmap[i].old = old_id;
9091 			idmap[i].cur = cur_id;
9092 			return true;
9093 		}
9094 		if (idmap[i].old == old_id)
9095 			return idmap[i].cur == cur_id;
9096 	}
9097 	/* We ran out of idmap slots, which should be impossible */
9098 	WARN_ON_ONCE(1);
9099 	return false;
9100 }
9101 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)9102 static void clean_func_state(struct bpf_verifier_env *env,
9103 			     struct bpf_func_state *st)
9104 {
9105 	enum bpf_reg_liveness live;
9106 	int i, j;
9107 
9108 	for (i = 0; i < BPF_REG_FP; i++) {
9109 		live = st->regs[i].live;
9110 		/* liveness must not touch this register anymore */
9111 		st->regs[i].live |= REG_LIVE_DONE;
9112 		if (!(live & REG_LIVE_READ))
9113 			/* since the register is unused, clear its state
9114 			 * to make further comparison simpler
9115 			 */
9116 			__mark_reg_not_init(env, &st->regs[i]);
9117 	}
9118 
9119 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9120 		live = st->stack[i].spilled_ptr.live;
9121 		/* liveness must not touch this stack slot anymore */
9122 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9123 		if (!(live & REG_LIVE_READ)) {
9124 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9125 			for (j = 0; j < BPF_REG_SIZE; j++)
9126 				st->stack[i].slot_type[j] = STACK_INVALID;
9127 		}
9128 	}
9129 }
9130 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)9131 static void clean_verifier_state(struct bpf_verifier_env *env,
9132 				 struct bpf_verifier_state *st)
9133 {
9134 	int i;
9135 
9136 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9137 		/* all regs in this state in all frames were already marked */
9138 		return;
9139 
9140 	for (i = 0; i <= st->curframe; i++)
9141 		clean_func_state(env, st->frame[i]);
9142 }
9143 
9144 /* the parentage chains form a tree.
9145  * the verifier states are added to state lists at given insn and
9146  * pushed into state stack for future exploration.
9147  * when the verifier reaches bpf_exit insn some of the verifer states
9148  * stored in the state lists have their final liveness state already,
9149  * but a lot of states will get revised from liveness point of view when
9150  * the verifier explores other branches.
9151  * Example:
9152  * 1: r0 = 1
9153  * 2: if r1 == 100 goto pc+1
9154  * 3: r0 = 2
9155  * 4: exit
9156  * when the verifier reaches exit insn the register r0 in the state list of
9157  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9158  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9159  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9160  *
9161  * Since the verifier pushes the branch states as it sees them while exploring
9162  * the program the condition of walking the branch instruction for the second
9163  * time means that all states below this branch were already explored and
9164  * their final liveness markes are already propagated.
9165  * Hence when the verifier completes the search of state list in is_state_visited()
9166  * we can call this clean_live_states() function to mark all liveness states
9167  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9168  * will not be used.
9169  * This function also clears the registers and stack for states that !READ
9170  * to simplify state merging.
9171  *
9172  * Important note here that walking the same branch instruction in the callee
9173  * doesn't meant that the states are DONE. The verifier has to compare
9174  * the callsites
9175  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)9176 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9177 			      struct bpf_verifier_state *cur)
9178 {
9179 	struct bpf_verifier_state_list *sl;
9180 	int i;
9181 
9182 	sl = *explored_state(env, insn);
9183 	while (sl) {
9184 		if (sl->state.branches)
9185 			goto next;
9186 		if (sl->state.insn_idx != insn ||
9187 		    sl->state.curframe != cur->curframe)
9188 			goto next;
9189 		for (i = 0; i <= cur->curframe; i++)
9190 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9191 				goto next;
9192 		clean_verifier_state(env, &sl->state);
9193 next:
9194 		sl = sl->next;
9195 	}
9196 }
9197 
9198 /* 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)9199 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9200 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9201 {
9202 	bool equal;
9203 
9204 	if (!(rold->live & REG_LIVE_READ))
9205 		/* explored state didn't use this */
9206 		return true;
9207 
9208 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9209 
9210 	if (rold->type == PTR_TO_STACK)
9211 		/* two stack pointers are equal only if they're pointing to
9212 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9213 		 */
9214 		return equal && rold->frameno == rcur->frameno;
9215 
9216 	if (equal)
9217 		return true;
9218 
9219 	if (rold->type == NOT_INIT)
9220 		/* explored state can't have used this */
9221 		return true;
9222 	if (rcur->type == NOT_INIT)
9223 		return false;
9224 	switch (base_type(rold->type)) {
9225 	case SCALAR_VALUE:
9226 		if (env->explore_alu_limits)
9227 			return false;
9228 		if (rcur->type == SCALAR_VALUE) {
9229 			if (!rold->precise && !rcur->precise)
9230 				return true;
9231 			/* new val must satisfy old val knowledge */
9232 			return range_within(rold, rcur) &&
9233 			       tnum_in(rold->var_off, rcur->var_off);
9234 		} else {
9235 			/* We're trying to use a pointer in place of a scalar.
9236 			 * Even if the scalar was unbounded, this could lead to
9237 			 * pointer leaks because scalars are allowed to leak
9238 			 * while pointers are not. We could make this safe in
9239 			 * special cases if root is calling us, but it's
9240 			 * probably not worth the hassle.
9241 			 */
9242 			return false;
9243 		}
9244 	case PTR_TO_MAP_VALUE:
9245 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9246 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9247 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9248 		 * checked, doing so could have affected others with the same
9249 		 * id, and we can't check for that because we lost the id when
9250 		 * we converted to a PTR_TO_MAP_VALUE.
9251 		 */
9252 		if (type_may_be_null(rold->type)) {
9253 			if (!type_may_be_null(rcur->type))
9254 				return false;
9255 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9256 				return false;
9257 			/* Check our ids match any regs they're supposed to */
9258 			return check_ids(rold->id, rcur->id, idmap);
9259 		}
9260 
9261 		/* If the new min/max/var_off satisfy the old ones and
9262 		 * everything else matches, we are OK.
9263 		 * 'id' is not compared, since it's only used for maps with
9264 		 * bpf_spin_lock inside map element and in such cases if
9265 		 * the rest of the prog is valid for one map element then
9266 		 * it's valid for all map elements regardless of the key
9267 		 * used in bpf_map_lookup()
9268 		 */
9269 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9270 		       range_within(rold, rcur) &&
9271 		       tnum_in(rold->var_off, rcur->var_off);
9272 	case PTR_TO_PACKET_META:
9273 	case PTR_TO_PACKET:
9274 		if (rcur->type != rold->type)
9275 			return false;
9276 		/* We must have at least as much range as the old ptr
9277 		 * did, so that any accesses which were safe before are
9278 		 * still safe.  This is true even if old range < old off,
9279 		 * since someone could have accessed through (ptr - k), or
9280 		 * even done ptr -= k in a register, to get a safe access.
9281 		 */
9282 		if (rold->range > rcur->range)
9283 			return false;
9284 		/* If the offsets don't match, we can't trust our alignment;
9285 		 * nor can we be sure that we won't fall out of range.
9286 		 */
9287 		if (rold->off != rcur->off)
9288 			return false;
9289 		/* id relations must be preserved */
9290 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9291 			return false;
9292 		/* new val must satisfy old val knowledge */
9293 		return range_within(rold, rcur) &&
9294 		       tnum_in(rold->var_off, rcur->var_off);
9295 	case PTR_TO_CTX:
9296 	case CONST_PTR_TO_MAP:
9297 	case PTR_TO_PACKET_END:
9298 	case PTR_TO_FLOW_KEYS:
9299 	case PTR_TO_SOCKET:
9300 	case PTR_TO_SOCK_COMMON:
9301 	case PTR_TO_TCP_SOCK:
9302 	case PTR_TO_XDP_SOCK:
9303 		/* Only valid matches are exact, which memcmp() above
9304 		 * would have accepted
9305 		 */
9306 	default:
9307 		/* Don't know what's going on, just say it's not safe */
9308 		return false;
9309 	}
9310 
9311 	/* Shouldn't get here; if we do, say it's not safe */
9312 	WARN_ON_ONCE(1);
9313 	return false;
9314 }
9315 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)9316 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9317 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9318 {
9319 	int i, spi;
9320 
9321 	/* walk slots of the explored stack and ignore any additional
9322 	 * slots in the current stack, since explored(safe) state
9323 	 * didn't use them
9324 	 */
9325 	for (i = 0; i < old->allocated_stack; i++) {
9326 		spi = i / BPF_REG_SIZE;
9327 
9328 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9329 			i += BPF_REG_SIZE - 1;
9330 			/* explored state didn't use this */
9331 			continue;
9332 		}
9333 
9334 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9335 			continue;
9336 
9337 		/* explored stack has more populated slots than current stack
9338 		 * and these slots were used
9339 		 */
9340 		if (i >= cur->allocated_stack)
9341 			return false;
9342 
9343 		/* if old state was safe with misc data in the stack
9344 		 * it will be safe with zero-initialized stack.
9345 		 * The opposite is not true
9346 		 */
9347 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9348 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9349 			continue;
9350 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9351 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9352 			/* Ex: old explored (safe) state has STACK_SPILL in
9353 			 * this stack slot, but current has STACK_MISC ->
9354 			 * this verifier states are not equivalent,
9355 			 * return false to continue verification of this path
9356 			 */
9357 			return false;
9358 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9359 			continue;
9360 		if (!is_spilled_reg(&old->stack[spi]))
9361 			continue;
9362 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
9363 			     &cur->stack[spi].spilled_ptr, idmap))
9364 			/* when explored and current stack slot are both storing
9365 			 * spilled registers, check that stored pointers types
9366 			 * are the same as well.
9367 			 * Ex: explored safe path could have stored
9368 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9369 			 * but current path has stored:
9370 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9371 			 * such verifier states are not equivalent.
9372 			 * return false to continue verification of this path
9373 			 */
9374 			return false;
9375 	}
9376 	return true;
9377 }
9378 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)9379 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9380 {
9381 	if (old->acquired_refs != cur->acquired_refs)
9382 		return false;
9383 	return !memcmp(old->refs, cur->refs,
9384 		       sizeof(*old->refs) * old->acquired_refs);
9385 }
9386 
9387 /* compare two verifier states
9388  *
9389  * all states stored in state_list are known to be valid, since
9390  * verifier reached 'bpf_exit' instruction through them
9391  *
9392  * this function is called when verifier exploring different branches of
9393  * execution popped from the state stack. If it sees an old state that has
9394  * more strict register state and more strict stack state then this execution
9395  * branch doesn't need to be explored further, since verifier already
9396  * concluded that more strict state leads to valid finish.
9397  *
9398  * Therefore two states are equivalent if register state is more conservative
9399  * and explored stack state is more conservative than the current one.
9400  * Example:
9401  *       explored                   current
9402  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9403  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9404  *
9405  * In other words if current stack state (one being explored) has more
9406  * valid slots than old one that already passed validation, it means
9407  * the verifier can stop exploring and conclude that current state is valid too
9408  *
9409  * Similarly with registers. If explored state has register type as invalid
9410  * whereas register type in current state is meaningful, it means that
9411  * the current state will reach 'bpf_exit' instruction safely
9412  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)9413 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9414 			      struct bpf_func_state *cur)
9415 {
9416 	int i;
9417 
9418 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9419 	for (i = 0; i < MAX_BPF_REG; i++)
9420 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
9421 			     env->idmap_scratch))
9422 			return false;
9423 
9424 	if (!stacksafe(env, old, cur, env->idmap_scratch))
9425 		return false;
9426 
9427 	if (!refsafe(old, cur))
9428 		return false;
9429 
9430 	return true;
9431 }
9432 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9433 static bool states_equal(struct bpf_verifier_env *env,
9434 			 struct bpf_verifier_state *old,
9435 			 struct bpf_verifier_state *cur)
9436 {
9437 	int i;
9438 
9439 	if (old->curframe != cur->curframe)
9440 		return false;
9441 
9442 	/* Verification state from speculative execution simulation
9443 	 * must never prune a non-speculative execution one.
9444 	 */
9445 	if (old->speculative && !cur->speculative)
9446 		return false;
9447 
9448 	if (old->active_spin_lock != cur->active_spin_lock)
9449 		return false;
9450 
9451 	/* for states to be equal callsites have to be the same
9452 	 * and all frame states need to be equivalent
9453 	 */
9454 	for (i = 0; i <= old->curframe; i++) {
9455 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9456 			return false;
9457 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9458 			return false;
9459 	}
9460 	return true;
9461 }
9462 
9463 /* Return 0 if no propagation happened. Return negative error code if error
9464  * happened. Otherwise, return the propagated bit.
9465  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)9466 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9467 				  struct bpf_reg_state *reg,
9468 				  struct bpf_reg_state *parent_reg)
9469 {
9470 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9471 	u8 flag = reg->live & REG_LIVE_READ;
9472 	int err;
9473 
9474 	/* When comes here, read flags of PARENT_REG or REG could be any of
9475 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9476 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9477 	 */
9478 	if (parent_flag == REG_LIVE_READ64 ||
9479 	    /* Or if there is no read flag from REG. */
9480 	    !flag ||
9481 	    /* Or if the read flag from REG is the same as PARENT_REG. */
9482 	    parent_flag == flag)
9483 		return 0;
9484 
9485 	err = mark_reg_read(env, reg, parent_reg, flag);
9486 	if (err)
9487 		return err;
9488 
9489 	return flag;
9490 }
9491 
9492 /* A write screens off any subsequent reads; but write marks come from the
9493  * straight-line code between a state and its parent.  When we arrive at an
9494  * equivalent state (jump target or such) we didn't arrive by the straight-line
9495  * code, so read marks in the state must propagate to the parent regardless
9496  * of the state's write marks. That's what 'parent == state->parent' comparison
9497  * in mark_reg_read() is for.
9498  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)9499 static int propagate_liveness(struct bpf_verifier_env *env,
9500 			      const struct bpf_verifier_state *vstate,
9501 			      struct bpf_verifier_state *vparent)
9502 {
9503 	struct bpf_reg_state *state_reg, *parent_reg;
9504 	struct bpf_func_state *state, *parent;
9505 	int i, frame, err = 0;
9506 
9507 	if (vparent->curframe != vstate->curframe) {
9508 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9509 		     vparent->curframe, vstate->curframe);
9510 		return -EFAULT;
9511 	}
9512 	/* Propagate read liveness of registers... */
9513 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9514 	for (frame = 0; frame <= vstate->curframe; frame++) {
9515 		parent = vparent->frame[frame];
9516 		state = vstate->frame[frame];
9517 		parent_reg = parent->regs;
9518 		state_reg = state->regs;
9519 		/* We don't need to worry about FP liveness, it's read-only */
9520 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9521 			err = propagate_liveness_reg(env, &state_reg[i],
9522 						     &parent_reg[i]);
9523 			if (err < 0)
9524 				return err;
9525 			if (err == REG_LIVE_READ64)
9526 				mark_insn_zext(env, &parent_reg[i]);
9527 		}
9528 
9529 		/* Propagate stack slots. */
9530 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9531 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9532 			parent_reg = &parent->stack[i].spilled_ptr;
9533 			state_reg = &state->stack[i].spilled_ptr;
9534 			err = propagate_liveness_reg(env, state_reg,
9535 						     parent_reg);
9536 			if (err < 0)
9537 				return err;
9538 		}
9539 	}
9540 	return 0;
9541 }
9542 
9543 /* find precise scalars in the previous equivalent state and
9544  * propagate them into the current state
9545  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)9546 static int propagate_precision(struct bpf_verifier_env *env,
9547 			       const struct bpf_verifier_state *old)
9548 {
9549 	struct bpf_reg_state *state_reg;
9550 	struct bpf_func_state *state;
9551 	int i, err = 0, fr;
9552 
9553 	for (fr = old->curframe; fr >= 0; fr--) {
9554 		state = old->frame[fr];
9555 		state_reg = state->regs;
9556 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9557 			if (state_reg->type != SCALAR_VALUE ||
9558 			    !state_reg->precise)
9559 				continue;
9560 			if (env->log.level & BPF_LOG_LEVEL2)
9561 				verbose(env, "frame %d: propagating r%d\n", i, fr);
9562 			err = mark_chain_precision_frame(env, fr, i);
9563 			if (err < 0)
9564 				return err;
9565 		}
9566 
9567 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9568 			if (!is_spilled_reg(&state->stack[i]))
9569 				continue;
9570 			state_reg = &state->stack[i].spilled_ptr;
9571 			if (state_reg->type != SCALAR_VALUE ||
9572 			    !state_reg->precise)
9573 				continue;
9574 			if (env->log.level & BPF_LOG_LEVEL2)
9575 				verbose(env, "frame %d: propagating fp%d\n",
9576 					(-i - 1) * BPF_REG_SIZE, fr);
9577 			err = mark_chain_precision_stack_frame(env, fr, i);
9578 			if (err < 0)
9579 				return err;
9580 		}
9581 	}
9582 	return 0;
9583 }
9584 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9585 static bool states_maybe_looping(struct bpf_verifier_state *old,
9586 				 struct bpf_verifier_state *cur)
9587 {
9588 	struct bpf_func_state *fold, *fcur;
9589 	int i, fr = cur->curframe;
9590 
9591 	if (old->curframe != fr)
9592 		return false;
9593 
9594 	fold = old->frame[fr];
9595 	fcur = cur->frame[fr];
9596 	for (i = 0; i < MAX_BPF_REG; i++)
9597 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9598 			   offsetof(struct bpf_reg_state, parent)))
9599 			return false;
9600 	return true;
9601 }
9602 
9603 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)9604 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9605 {
9606 	struct bpf_verifier_state_list *new_sl;
9607 	struct bpf_verifier_state_list *sl, **pprev;
9608 	struct bpf_verifier_state *cur = env->cur_state, *new;
9609 	int i, j, err, states_cnt = 0;
9610 	bool add_new_state = env->test_state_freq ? true : false;
9611 
9612 	cur->last_insn_idx = env->prev_insn_idx;
9613 	if (!env->insn_aux_data[insn_idx].prune_point)
9614 		/* this 'insn_idx' instruction wasn't marked, so we will not
9615 		 * be doing state search here
9616 		 */
9617 		return 0;
9618 
9619 	/* bpf progs typically have pruning point every 4 instructions
9620 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9621 	 * Do not add new state for future pruning if the verifier hasn't seen
9622 	 * at least 2 jumps and at least 8 instructions.
9623 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9624 	 * In tests that amounts to up to 50% reduction into total verifier
9625 	 * memory consumption and 20% verifier time speedup.
9626 	 */
9627 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9628 	    env->insn_processed - env->prev_insn_processed >= 8)
9629 		add_new_state = true;
9630 
9631 	pprev = explored_state(env, insn_idx);
9632 	sl = *pprev;
9633 
9634 	clean_live_states(env, insn_idx, cur);
9635 
9636 	while (sl) {
9637 		states_cnt++;
9638 		if (sl->state.insn_idx != insn_idx)
9639 			goto next;
9640 		if (sl->state.branches) {
9641 			if (states_maybe_looping(&sl->state, cur) &&
9642 			    states_equal(env, &sl->state, cur)) {
9643 				verbose_linfo(env, insn_idx, "; ");
9644 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9645 				return -EINVAL;
9646 			}
9647 			/* if the verifier is processing a loop, avoid adding new state
9648 			 * too often, since different loop iterations have distinct
9649 			 * states and may not help future pruning.
9650 			 * This threshold shouldn't be too low to make sure that
9651 			 * a loop with large bound will be rejected quickly.
9652 			 * The most abusive loop will be:
9653 			 * r1 += 1
9654 			 * if r1 < 1000000 goto pc-2
9655 			 * 1M insn_procssed limit / 100 == 10k peak states.
9656 			 * This threshold shouldn't be too high either, since states
9657 			 * at the end of the loop are likely to be useful in pruning.
9658 			 */
9659 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9660 			    env->insn_processed - env->prev_insn_processed < 100)
9661 				add_new_state = false;
9662 			goto miss;
9663 		}
9664 		if (states_equal(env, &sl->state, cur)) {
9665 			sl->hit_cnt++;
9666 			/* reached equivalent register/stack state,
9667 			 * prune the search.
9668 			 * Registers read by the continuation are read by us.
9669 			 * If we have any write marks in env->cur_state, they
9670 			 * will prevent corresponding reads in the continuation
9671 			 * from reaching our parent (an explored_state).  Our
9672 			 * own state will get the read marks recorded, but
9673 			 * they'll be immediately forgotten as we're pruning
9674 			 * this state and will pop a new one.
9675 			 */
9676 			err = propagate_liveness(env, &sl->state, cur);
9677 
9678 			/* if previous state reached the exit with precision and
9679 			 * current state is equivalent to it (except precsion marks)
9680 			 * the precision needs to be propagated back in
9681 			 * the current state.
9682 			 */
9683 			err = err ? : push_jmp_history(env, cur);
9684 			err = err ? : propagate_precision(env, &sl->state);
9685 			if (err)
9686 				return err;
9687 			return 1;
9688 		}
9689 miss:
9690 		/* when new state is not going to be added do not increase miss count.
9691 		 * Otherwise several loop iterations will remove the state
9692 		 * recorded earlier. The goal of these heuristics is to have
9693 		 * states from some iterations of the loop (some in the beginning
9694 		 * and some at the end) to help pruning.
9695 		 */
9696 		if (add_new_state)
9697 			sl->miss_cnt++;
9698 		/* heuristic to determine whether this state is beneficial
9699 		 * to keep checking from state equivalence point of view.
9700 		 * Higher numbers increase max_states_per_insn and verification time,
9701 		 * but do not meaningfully decrease insn_processed.
9702 		 */
9703 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9704 			/* the state is unlikely to be useful. Remove it to
9705 			 * speed up verification
9706 			 */
9707 			*pprev = sl->next;
9708 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9709 				u32 br = sl->state.branches;
9710 
9711 				WARN_ONCE(br,
9712 					  "BUG live_done but branches_to_explore %d\n",
9713 					  br);
9714 				free_verifier_state(&sl->state, false);
9715 				kfree(sl);
9716 				env->peak_states--;
9717 			} else {
9718 				/* cannot free this state, since parentage chain may
9719 				 * walk it later. Add it for free_list instead to
9720 				 * be freed at the end of verification
9721 				 */
9722 				sl->next = env->free_list;
9723 				env->free_list = sl;
9724 			}
9725 			sl = *pprev;
9726 			continue;
9727 		}
9728 next:
9729 		pprev = &sl->next;
9730 		sl = *pprev;
9731 	}
9732 
9733 	if (env->max_states_per_insn < states_cnt)
9734 		env->max_states_per_insn = states_cnt;
9735 
9736 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9737 		return push_jmp_history(env, cur);
9738 
9739 	if (!add_new_state)
9740 		return push_jmp_history(env, cur);
9741 
9742 	/* There were no equivalent states, remember the current one.
9743 	 * Technically the current state is not proven to be safe yet,
9744 	 * but it will either reach outer most bpf_exit (which means it's safe)
9745 	 * or it will be rejected. When there are no loops the verifier won't be
9746 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9747 	 * again on the way to bpf_exit.
9748 	 * When looping the sl->state.branches will be > 0 and this state
9749 	 * will not be considered for equivalence until branches == 0.
9750 	 */
9751 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9752 	if (!new_sl)
9753 		return -ENOMEM;
9754 	env->total_states++;
9755 	env->peak_states++;
9756 	env->prev_jmps_processed = env->jmps_processed;
9757 	env->prev_insn_processed = env->insn_processed;
9758 
9759 	/* add new state to the head of linked list */
9760 	new = &new_sl->state;
9761 	err = copy_verifier_state(new, cur);
9762 	if (err) {
9763 		free_verifier_state(new, false);
9764 		kfree(new_sl);
9765 		return err;
9766 	}
9767 	new->insn_idx = insn_idx;
9768 	WARN_ONCE(new->branches != 1,
9769 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9770 
9771 	cur->parent = new;
9772 	cur->first_insn_idx = insn_idx;
9773 	clear_jmp_history(cur);
9774 	new_sl->next = *explored_state(env, insn_idx);
9775 	*explored_state(env, insn_idx) = new_sl;
9776 	/* connect new state to parentage chain. Current frame needs all
9777 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9778 	 * to the stack implicitly by JITs) so in callers' frames connect just
9779 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9780 	 * the state of the call instruction (with WRITTEN set), and r0 comes
9781 	 * from callee with its full parentage chain, anyway.
9782 	 */
9783 	/* clear write marks in current state: the writes we did are not writes
9784 	 * our child did, so they don't screen off its reads from us.
9785 	 * (There are no read marks in current state, because reads always mark
9786 	 * their parent and current state never has children yet.  Only
9787 	 * explored_states can get read marks.)
9788 	 */
9789 	for (j = 0; j <= cur->curframe; j++) {
9790 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9791 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9792 		for (i = 0; i < BPF_REG_FP; i++)
9793 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9794 	}
9795 
9796 	/* all stack frames are accessible from callee, clear them all */
9797 	for (j = 0; j <= cur->curframe; j++) {
9798 		struct bpf_func_state *frame = cur->frame[j];
9799 		struct bpf_func_state *newframe = new->frame[j];
9800 
9801 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9802 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9803 			frame->stack[i].spilled_ptr.parent =
9804 						&newframe->stack[i].spilled_ptr;
9805 		}
9806 	}
9807 	return 0;
9808 }
9809 
9810 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)9811 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9812 {
9813 	switch (base_type(type)) {
9814 	case PTR_TO_CTX:
9815 	case PTR_TO_SOCKET:
9816 	case PTR_TO_SOCK_COMMON:
9817 	case PTR_TO_TCP_SOCK:
9818 	case PTR_TO_XDP_SOCK:
9819 	case PTR_TO_BTF_ID:
9820 		return false;
9821 	default:
9822 		return true;
9823 	}
9824 }
9825 
9826 /* If an instruction was previously used with particular pointer types, then we
9827  * need to be careful to avoid cases such as the below, where it may be ok
9828  * for one branch accessing the pointer, but not ok for the other branch:
9829  *
9830  * R1 = sock_ptr
9831  * goto X;
9832  * ...
9833  * R1 = some_other_valid_ptr;
9834  * goto X;
9835  * ...
9836  * R2 = *(u32 *)(R1 + 0);
9837  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)9838 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9839 {
9840 	return src != prev && (!reg_type_mismatch_ok(src) ||
9841 			       !reg_type_mismatch_ok(prev));
9842 }
9843 
do_check(struct bpf_verifier_env * env)9844 static int do_check(struct bpf_verifier_env *env)
9845 {
9846 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9847 	struct bpf_verifier_state *state = env->cur_state;
9848 	struct bpf_insn *insns = env->prog->insnsi;
9849 	struct bpf_reg_state *regs;
9850 	int insn_cnt = env->prog->len;
9851 	bool do_print_state = false;
9852 	int prev_insn_idx = -1;
9853 
9854 	for (;;) {
9855 		struct bpf_insn *insn;
9856 		u8 class;
9857 		int err;
9858 
9859 		env->prev_insn_idx = prev_insn_idx;
9860 		if (env->insn_idx >= insn_cnt) {
9861 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
9862 				env->insn_idx, insn_cnt);
9863 			return -EFAULT;
9864 		}
9865 
9866 		insn = &insns[env->insn_idx];
9867 		class = BPF_CLASS(insn->code);
9868 
9869 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9870 			verbose(env,
9871 				"BPF program is too large. Processed %d insn\n",
9872 				env->insn_processed);
9873 			return -E2BIG;
9874 		}
9875 
9876 		err = is_state_visited(env, env->insn_idx);
9877 		if (err < 0)
9878 			return err;
9879 		if (err == 1) {
9880 			/* found equivalent state, can prune the search */
9881 			if (env->log.level & BPF_LOG_LEVEL) {
9882 				if (do_print_state)
9883 					verbose(env, "\nfrom %d to %d%s: safe\n",
9884 						env->prev_insn_idx, env->insn_idx,
9885 						env->cur_state->speculative ?
9886 						" (speculative execution)" : "");
9887 				else
9888 					verbose(env, "%d: safe\n", env->insn_idx);
9889 			}
9890 			goto process_bpf_exit;
9891 		}
9892 
9893 		if (signal_pending(current))
9894 			return -EAGAIN;
9895 
9896 		if (need_resched())
9897 			cond_resched();
9898 
9899 		if (env->log.level & BPF_LOG_LEVEL2 ||
9900 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9901 			if (env->log.level & BPF_LOG_LEVEL2)
9902 				verbose(env, "%d:", env->insn_idx);
9903 			else
9904 				verbose(env, "\nfrom %d to %d%s:",
9905 					env->prev_insn_idx, env->insn_idx,
9906 					env->cur_state->speculative ?
9907 					" (speculative execution)" : "");
9908 			print_verifier_state(env, state->frame[state->curframe]);
9909 			do_print_state = false;
9910 		}
9911 
9912 		if (env->log.level & BPF_LOG_LEVEL) {
9913 			const struct bpf_insn_cbs cbs = {
9914 				.cb_print	= verbose,
9915 				.private_data	= env,
9916 			};
9917 
9918 			verbose_linfo(env, env->insn_idx, "; ");
9919 			verbose(env, "%d: ", env->insn_idx);
9920 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9921 		}
9922 
9923 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
9924 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9925 							   env->prev_insn_idx);
9926 			if (err)
9927 				return err;
9928 		}
9929 
9930 		regs = cur_regs(env);
9931 		sanitize_mark_insn_seen(env);
9932 		prev_insn_idx = env->insn_idx;
9933 
9934 		if (class == BPF_ALU || class == BPF_ALU64) {
9935 			err = check_alu_op(env, insn);
9936 			if (err)
9937 				return err;
9938 
9939 		} else if (class == BPF_LDX) {
9940 			enum bpf_reg_type *prev_src_type, src_reg_type;
9941 
9942 			/* check for reserved fields is already done */
9943 
9944 			/* check src operand */
9945 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9946 			if (err)
9947 				return err;
9948 
9949 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9950 			if (err)
9951 				return err;
9952 
9953 			src_reg_type = regs[insn->src_reg].type;
9954 
9955 			/* check that memory (src_reg + off) is readable,
9956 			 * the state of dst_reg will be updated by this func
9957 			 */
9958 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
9959 					       insn->off, BPF_SIZE(insn->code),
9960 					       BPF_READ, insn->dst_reg, false);
9961 			if (err)
9962 				return err;
9963 
9964 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9965 
9966 			if (*prev_src_type == NOT_INIT) {
9967 				/* saw a valid insn
9968 				 * dst_reg = *(u32 *)(src_reg + off)
9969 				 * save type to validate intersecting paths
9970 				 */
9971 				*prev_src_type = src_reg_type;
9972 
9973 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9974 				/* ABuser program is trying to use the same insn
9975 				 * dst_reg = *(u32*) (src_reg + off)
9976 				 * with different pointer types:
9977 				 * src_reg == ctx in one branch and
9978 				 * src_reg == stack|map in some other branch.
9979 				 * Reject it.
9980 				 */
9981 				verbose(env, "same insn cannot be used with different pointers\n");
9982 				return -EINVAL;
9983 			}
9984 
9985 		} else if (class == BPF_STX) {
9986 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
9987 
9988 			if (BPF_MODE(insn->code) == BPF_XADD) {
9989 				err = check_xadd(env, env->insn_idx, insn);
9990 				if (err)
9991 					return err;
9992 				env->insn_idx++;
9993 				continue;
9994 			}
9995 
9996 			/* check src1 operand */
9997 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9998 			if (err)
9999 				return err;
10000 			/* check src2 operand */
10001 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10002 			if (err)
10003 				return err;
10004 
10005 			dst_reg_type = regs[insn->dst_reg].type;
10006 
10007 			/* check that memory (dst_reg + off) is writeable */
10008 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10009 					       insn->off, BPF_SIZE(insn->code),
10010 					       BPF_WRITE, insn->src_reg, false);
10011 			if (err)
10012 				return err;
10013 
10014 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10015 
10016 			if (*prev_dst_type == NOT_INIT) {
10017 				*prev_dst_type = dst_reg_type;
10018 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10019 				verbose(env, "same insn cannot be used with different pointers\n");
10020 				return -EINVAL;
10021 			}
10022 
10023 		} else if (class == BPF_ST) {
10024 			if (BPF_MODE(insn->code) != BPF_MEM ||
10025 			    insn->src_reg != BPF_REG_0) {
10026 				verbose(env, "BPF_ST uses reserved fields\n");
10027 				return -EINVAL;
10028 			}
10029 			/* check src operand */
10030 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10031 			if (err)
10032 				return err;
10033 
10034 			if (is_ctx_reg(env, insn->dst_reg)) {
10035 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10036 					insn->dst_reg,
10037 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
10038 				return -EACCES;
10039 			}
10040 
10041 			/* check that memory (dst_reg + off) is writeable */
10042 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10043 					       insn->off, BPF_SIZE(insn->code),
10044 					       BPF_WRITE, -1, false);
10045 			if (err)
10046 				return err;
10047 
10048 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10049 			u8 opcode = BPF_OP(insn->code);
10050 
10051 			env->jmps_processed++;
10052 			if (opcode == BPF_CALL) {
10053 				if (BPF_SRC(insn->code) != BPF_K ||
10054 				    insn->off != 0 ||
10055 				    (insn->src_reg != BPF_REG_0 &&
10056 				     insn->src_reg != BPF_PSEUDO_CALL) ||
10057 				    insn->dst_reg != BPF_REG_0 ||
10058 				    class == BPF_JMP32) {
10059 					verbose(env, "BPF_CALL uses reserved fields\n");
10060 					return -EINVAL;
10061 				}
10062 
10063 				if (env->cur_state->active_spin_lock &&
10064 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10065 				     insn->imm != BPF_FUNC_spin_unlock)) {
10066 					verbose(env, "function calls are not allowed while holding a lock\n");
10067 					return -EINVAL;
10068 				}
10069 				if (insn->src_reg == BPF_PSEUDO_CALL)
10070 					err = check_func_call(env, insn, &env->insn_idx);
10071 				else
10072 					err = check_helper_call(env, insn->imm, env->insn_idx);
10073 				if (err)
10074 					return err;
10075 
10076 			} else if (opcode == BPF_JA) {
10077 				if (BPF_SRC(insn->code) != BPF_K ||
10078 				    insn->imm != 0 ||
10079 				    insn->src_reg != BPF_REG_0 ||
10080 				    insn->dst_reg != BPF_REG_0 ||
10081 				    class == BPF_JMP32) {
10082 					verbose(env, "BPF_JA uses reserved fields\n");
10083 					return -EINVAL;
10084 				}
10085 
10086 				env->insn_idx += insn->off + 1;
10087 				continue;
10088 
10089 			} else if (opcode == BPF_EXIT) {
10090 				if (BPF_SRC(insn->code) != BPF_K ||
10091 				    insn->imm != 0 ||
10092 				    insn->src_reg != BPF_REG_0 ||
10093 				    insn->dst_reg != BPF_REG_0 ||
10094 				    class == BPF_JMP32) {
10095 					verbose(env, "BPF_EXIT uses reserved fields\n");
10096 					return -EINVAL;
10097 				}
10098 
10099 				if (env->cur_state->active_spin_lock) {
10100 					verbose(env, "bpf_spin_unlock is missing\n");
10101 					return -EINVAL;
10102 				}
10103 
10104 				if (state->curframe) {
10105 					/* exit from nested function */
10106 					err = prepare_func_exit(env, &env->insn_idx);
10107 					if (err)
10108 						return err;
10109 					do_print_state = true;
10110 					continue;
10111 				}
10112 
10113 				err = check_reference_leak(env);
10114 				if (err)
10115 					return err;
10116 
10117 				err = check_return_code(env);
10118 				if (err)
10119 					return err;
10120 process_bpf_exit:
10121 				update_branch_counts(env, env->cur_state);
10122 				err = pop_stack(env, &prev_insn_idx,
10123 						&env->insn_idx, pop_log);
10124 				if (err < 0) {
10125 					if (err != -ENOENT)
10126 						return err;
10127 					break;
10128 				} else {
10129 					do_print_state = true;
10130 					continue;
10131 				}
10132 			} else {
10133 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10134 				if (err)
10135 					return err;
10136 			}
10137 		} else if (class == BPF_LD) {
10138 			u8 mode = BPF_MODE(insn->code);
10139 
10140 			if (mode == BPF_ABS || mode == BPF_IND) {
10141 				err = check_ld_abs(env, insn);
10142 				if (err)
10143 					return err;
10144 
10145 			} else if (mode == BPF_IMM) {
10146 				err = check_ld_imm(env, insn);
10147 				if (err)
10148 					return err;
10149 
10150 				env->insn_idx++;
10151 				sanitize_mark_insn_seen(env);
10152 			} else {
10153 				verbose(env, "invalid BPF_LD mode\n");
10154 				return -EINVAL;
10155 			}
10156 		} else {
10157 			verbose(env, "unknown insn class %d\n", class);
10158 			return -EINVAL;
10159 		}
10160 
10161 		env->insn_idx++;
10162 	}
10163 
10164 	return 0;
10165 }
10166 
10167 /* 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)10168 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10169 			       struct bpf_insn *insn,
10170 			       struct bpf_insn_aux_data *aux)
10171 {
10172 	const struct btf_var_secinfo *vsi;
10173 	const struct btf_type *datasec;
10174 	const struct btf_type *t;
10175 	const char *sym_name;
10176 	bool percpu = false;
10177 	u32 type, id = insn->imm;
10178 	s32 datasec_id;
10179 	u64 addr;
10180 	int i;
10181 
10182 	if (!btf_vmlinux) {
10183 		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10184 		return -EINVAL;
10185 	}
10186 
10187 	if (insn[1].imm != 0) {
10188 		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10189 		return -EINVAL;
10190 	}
10191 
10192 	t = btf_type_by_id(btf_vmlinux, id);
10193 	if (!t) {
10194 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10195 		return -ENOENT;
10196 	}
10197 
10198 	if (!btf_type_is_var(t)) {
10199 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10200 			id);
10201 		return -EINVAL;
10202 	}
10203 
10204 	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10205 	addr = kallsyms_lookup_name(sym_name);
10206 	if (!addr) {
10207 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10208 			sym_name);
10209 		return -ENOENT;
10210 	}
10211 
10212 	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10213 					   BTF_KIND_DATASEC);
10214 	if (datasec_id > 0) {
10215 		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10216 		for_each_vsi(i, datasec, vsi) {
10217 			if (vsi->type == id) {
10218 				percpu = true;
10219 				break;
10220 			}
10221 		}
10222 	}
10223 
10224 	insn[0].imm = (u32)addr;
10225 	insn[1].imm = addr >> 32;
10226 
10227 	type = t->type;
10228 	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10229 	if (percpu) {
10230 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10231 		aux->btf_var.btf_id = type;
10232 	} else if (!btf_type_is_struct(t)) {
10233 		const struct btf_type *ret;
10234 		const char *tname;
10235 		u32 tsize;
10236 
10237 		/* resolve the type size of ksym. */
10238 		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10239 		if (IS_ERR(ret)) {
10240 			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10241 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10242 				tname, PTR_ERR(ret));
10243 			return -EINVAL;
10244 		}
10245 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
10246 		aux->btf_var.mem_size = tsize;
10247 	} else {
10248 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10249 		aux->btf_var.btf_id = type;
10250 	}
10251 	return 0;
10252 }
10253 
check_map_prealloc(struct bpf_map * map)10254 static int check_map_prealloc(struct bpf_map *map)
10255 {
10256 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10257 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10258 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10259 		!(map->map_flags & BPF_F_NO_PREALLOC);
10260 }
10261 
is_tracing_prog_type(enum bpf_prog_type type)10262 static bool is_tracing_prog_type(enum bpf_prog_type type)
10263 {
10264 	switch (type) {
10265 	case BPF_PROG_TYPE_KPROBE:
10266 	case BPF_PROG_TYPE_TRACEPOINT:
10267 	case BPF_PROG_TYPE_PERF_EVENT:
10268 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10269 		return true;
10270 	default:
10271 		return false;
10272 	}
10273 }
10274 
is_preallocated_map(struct bpf_map * map)10275 static bool is_preallocated_map(struct bpf_map *map)
10276 {
10277 	if (!check_map_prealloc(map))
10278 		return false;
10279 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10280 		return false;
10281 	return true;
10282 }
10283 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)10284 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10285 					struct bpf_map *map,
10286 					struct bpf_prog *prog)
10287 
10288 {
10289 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10290 	/*
10291 	 * Validate that trace type programs use preallocated hash maps.
10292 	 *
10293 	 * For programs attached to PERF events this is mandatory as the
10294 	 * perf NMI can hit any arbitrary code sequence.
10295 	 *
10296 	 * All other trace types using preallocated hash maps are unsafe as
10297 	 * well because tracepoint or kprobes can be inside locked regions
10298 	 * of the memory allocator or at a place where a recursion into the
10299 	 * memory allocator would see inconsistent state.
10300 	 *
10301 	 * On RT enabled kernels run-time allocation of all trace type
10302 	 * programs is strictly prohibited due to lock type constraints. On
10303 	 * !RT kernels it is allowed for backwards compatibility reasons for
10304 	 * now, but warnings are emitted so developers are made aware of
10305 	 * the unsafety and can fix their programs before this is enforced.
10306 	 */
10307 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10308 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10309 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10310 			return -EINVAL;
10311 		}
10312 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10313 			verbose(env, "trace type programs can only use preallocated hash map\n");
10314 			return -EINVAL;
10315 		}
10316 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10317 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10318 	}
10319 
10320 	if ((is_tracing_prog_type(prog_type) ||
10321 	     prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10322 	    map_value_has_spin_lock(map)) {
10323 		verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10324 		return -EINVAL;
10325 	}
10326 
10327 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10328 	    !bpf_offload_prog_map_match(prog, map)) {
10329 		verbose(env, "offload device mismatch between prog and map\n");
10330 		return -EINVAL;
10331 	}
10332 
10333 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10334 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10335 		return -EINVAL;
10336 	}
10337 
10338 	if (prog->aux->sleepable)
10339 		switch (map->map_type) {
10340 		case BPF_MAP_TYPE_HASH:
10341 		case BPF_MAP_TYPE_LRU_HASH:
10342 		case BPF_MAP_TYPE_ARRAY:
10343 			if (!is_preallocated_map(map)) {
10344 				verbose(env,
10345 					"Sleepable programs can only use preallocated hash maps\n");
10346 				return -EINVAL;
10347 			}
10348 			break;
10349 		default:
10350 			verbose(env,
10351 				"Sleepable programs can only use array and hash maps\n");
10352 			return -EINVAL;
10353 		}
10354 
10355 	return 0;
10356 }
10357 
bpf_map_is_cgroup_storage(struct bpf_map * map)10358 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10359 {
10360 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10361 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10362 }
10363 
10364 /* find and rewrite pseudo imm in ld_imm64 instructions:
10365  *
10366  * 1. if it accesses map FD, replace it with actual map pointer.
10367  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10368  *
10369  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10370  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)10371 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10372 {
10373 	struct bpf_insn *insn = env->prog->insnsi;
10374 	int insn_cnt = env->prog->len;
10375 	int i, j, err;
10376 
10377 	err = bpf_prog_calc_tag(env->prog);
10378 	if (err)
10379 		return err;
10380 
10381 	for (i = 0; i < insn_cnt; i++, insn++) {
10382 		if (BPF_CLASS(insn->code) == BPF_LDX &&
10383 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10384 			verbose(env, "BPF_LDX uses reserved fields\n");
10385 			return -EINVAL;
10386 		}
10387 
10388 		if (BPF_CLASS(insn->code) == BPF_STX &&
10389 		    ((BPF_MODE(insn->code) != BPF_MEM &&
10390 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10391 			verbose(env, "BPF_STX uses reserved fields\n");
10392 			return -EINVAL;
10393 		}
10394 
10395 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10396 			struct bpf_insn_aux_data *aux;
10397 			struct bpf_map *map;
10398 			struct fd f;
10399 			u64 addr;
10400 
10401 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
10402 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10403 			    insn[1].off != 0) {
10404 				verbose(env, "invalid bpf_ld_imm64 insn\n");
10405 				return -EINVAL;
10406 			}
10407 
10408 			if (insn[0].src_reg == 0)
10409 				/* valid generic load 64-bit imm */
10410 				goto next_insn;
10411 
10412 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10413 				aux = &env->insn_aux_data[i];
10414 				err = check_pseudo_btf_id(env, insn, aux);
10415 				if (err)
10416 					return err;
10417 				goto next_insn;
10418 			}
10419 
10420 			/* In final convert_pseudo_ld_imm64() step, this is
10421 			 * converted into regular 64-bit imm load insn.
10422 			 */
10423 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10424 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10425 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10426 			     insn[1].imm != 0)) {
10427 				verbose(env,
10428 					"unrecognized bpf_ld_imm64 insn\n");
10429 				return -EINVAL;
10430 			}
10431 
10432 			f = fdget(insn[0].imm);
10433 			map = __bpf_map_get(f);
10434 			if (IS_ERR(map)) {
10435 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
10436 					insn[0].imm);
10437 				return PTR_ERR(map);
10438 			}
10439 
10440 			err = check_map_prog_compatibility(env, map, env->prog);
10441 			if (err) {
10442 				fdput(f);
10443 				return err;
10444 			}
10445 
10446 			aux = &env->insn_aux_data[i];
10447 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10448 				addr = (unsigned long)map;
10449 			} else {
10450 				u32 off = insn[1].imm;
10451 
10452 				if (off >= BPF_MAX_VAR_OFF) {
10453 					verbose(env, "direct value offset of %u is not allowed\n", off);
10454 					fdput(f);
10455 					return -EINVAL;
10456 				}
10457 
10458 				if (!map->ops->map_direct_value_addr) {
10459 					verbose(env, "no direct value access support for this map type\n");
10460 					fdput(f);
10461 					return -EINVAL;
10462 				}
10463 
10464 				err = map->ops->map_direct_value_addr(map, &addr, off);
10465 				if (err) {
10466 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10467 						map->value_size, off);
10468 					fdput(f);
10469 					return err;
10470 				}
10471 
10472 				aux->map_off = off;
10473 				addr += off;
10474 			}
10475 
10476 			insn[0].imm = (u32)addr;
10477 			insn[1].imm = addr >> 32;
10478 
10479 			/* check whether we recorded this map already */
10480 			for (j = 0; j < env->used_map_cnt; j++) {
10481 				if (env->used_maps[j] == map) {
10482 					aux->map_index = j;
10483 					fdput(f);
10484 					goto next_insn;
10485 				}
10486 			}
10487 
10488 			if (env->used_map_cnt >= MAX_USED_MAPS) {
10489 				fdput(f);
10490 				return -E2BIG;
10491 			}
10492 
10493 			/* hold the map. If the program is rejected by verifier,
10494 			 * the map will be released by release_maps() or it
10495 			 * will be used by the valid program until it's unloaded
10496 			 * and all maps are released in free_used_maps()
10497 			 */
10498 			bpf_map_inc(map);
10499 
10500 			aux->map_index = env->used_map_cnt;
10501 			env->used_maps[env->used_map_cnt++] = map;
10502 
10503 			if (bpf_map_is_cgroup_storage(map) &&
10504 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10505 				verbose(env, "only one cgroup storage of each type is allowed\n");
10506 				fdput(f);
10507 				return -EBUSY;
10508 			}
10509 
10510 			fdput(f);
10511 next_insn:
10512 			insn++;
10513 			i++;
10514 			continue;
10515 		}
10516 
10517 		/* Basic sanity check before we invest more work here. */
10518 		if (!bpf_opcode_in_insntable(insn->code)) {
10519 			verbose(env, "unknown opcode %02x\n", insn->code);
10520 			return -EINVAL;
10521 		}
10522 	}
10523 
10524 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10525 	 * 'struct bpf_map *' into a register instead of user map_fd.
10526 	 * These pointers will be used later by verifier to validate map access.
10527 	 */
10528 	return 0;
10529 }
10530 
10531 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)10532 static void release_maps(struct bpf_verifier_env *env)
10533 {
10534 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10535 			     env->used_map_cnt);
10536 }
10537 
10538 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)10539 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10540 {
10541 	struct bpf_insn *insn = env->prog->insnsi;
10542 	int insn_cnt = env->prog->len;
10543 	int i;
10544 
10545 	for (i = 0; i < insn_cnt; i++, insn++)
10546 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10547 			insn->src_reg = 0;
10548 }
10549 
10550 /* single env->prog->insni[off] instruction was replaced with the range
10551  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10552  * [0, off) and [off, end) to new locations, so the patched range stays zero
10553  */
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)10554 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10555 				 struct bpf_insn_aux_data *new_data,
10556 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
10557 {
10558 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10559 	struct bpf_insn *insn = new_prog->insnsi;
10560 	u32 old_seen = old_data[off].seen;
10561 	u32 prog_len;
10562 	int i;
10563 
10564 	/* aux info at OFF always needs adjustment, no matter fast path
10565 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10566 	 * original insn at old prog.
10567 	 */
10568 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10569 
10570 	if (cnt == 1)
10571 		return;
10572 	prog_len = new_prog->len;
10573 
10574 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10575 	memcpy(new_data + off + cnt - 1, old_data + off,
10576 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10577 	for (i = off; i < off + cnt - 1; i++) {
10578 		/* Expand insni[off]'s seen count to the patched range. */
10579 		new_data[i].seen = old_seen;
10580 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10581 	}
10582 	env->insn_aux_data = new_data;
10583 	vfree(old_data);
10584 }
10585 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)10586 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10587 {
10588 	int i;
10589 
10590 	if (len == 1)
10591 		return;
10592 	/* NOTE: fake 'exit' subprog should be updated as well. */
10593 	for (i = 0; i <= env->subprog_cnt; i++) {
10594 		if (env->subprog_info[i].start <= off)
10595 			continue;
10596 		env->subprog_info[i].start += len - 1;
10597 	}
10598 }
10599 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)10600 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10601 {
10602 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10603 	int i, sz = prog->aux->size_poke_tab;
10604 	struct bpf_jit_poke_descriptor *desc;
10605 
10606 	for (i = 0; i < sz; i++) {
10607 		desc = &tab[i];
10608 		if (desc->insn_idx <= off)
10609 			continue;
10610 		desc->insn_idx += len - 1;
10611 	}
10612 }
10613 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)10614 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10615 					    const struct bpf_insn *patch, u32 len)
10616 {
10617 	struct bpf_prog *new_prog;
10618 	struct bpf_insn_aux_data *new_data = NULL;
10619 
10620 	if (len > 1) {
10621 		new_data = vzalloc(array_size(env->prog->len + len - 1,
10622 					      sizeof(struct bpf_insn_aux_data)));
10623 		if (!new_data)
10624 			return NULL;
10625 	}
10626 
10627 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10628 	if (IS_ERR(new_prog)) {
10629 		if (PTR_ERR(new_prog) == -ERANGE)
10630 			verbose(env,
10631 				"insn %d cannot be patched due to 16-bit range\n",
10632 				env->insn_aux_data[off].orig_idx);
10633 		vfree(new_data);
10634 		return NULL;
10635 	}
10636 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
10637 	adjust_subprog_starts(env, off, len);
10638 	adjust_poke_descs(new_prog, off, len);
10639 	return new_prog;
10640 }
10641 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10642 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10643 					      u32 off, u32 cnt)
10644 {
10645 	int i, j;
10646 
10647 	/* find first prog starting at or after off (first to remove) */
10648 	for (i = 0; i < env->subprog_cnt; i++)
10649 		if (env->subprog_info[i].start >= off)
10650 			break;
10651 	/* find first prog starting at or after off + cnt (first to stay) */
10652 	for (j = i; j < env->subprog_cnt; j++)
10653 		if (env->subprog_info[j].start >= off + cnt)
10654 			break;
10655 	/* if j doesn't start exactly at off + cnt, we are just removing
10656 	 * the front of previous prog
10657 	 */
10658 	if (env->subprog_info[j].start != off + cnt)
10659 		j--;
10660 
10661 	if (j > i) {
10662 		struct bpf_prog_aux *aux = env->prog->aux;
10663 		int move;
10664 
10665 		/* move fake 'exit' subprog as well */
10666 		move = env->subprog_cnt + 1 - j;
10667 
10668 		memmove(env->subprog_info + i,
10669 			env->subprog_info + j,
10670 			sizeof(*env->subprog_info) * move);
10671 		env->subprog_cnt -= j - i;
10672 
10673 		/* remove func_info */
10674 		if (aux->func_info) {
10675 			move = aux->func_info_cnt - j;
10676 
10677 			memmove(aux->func_info + i,
10678 				aux->func_info + j,
10679 				sizeof(*aux->func_info) * move);
10680 			aux->func_info_cnt -= j - i;
10681 			/* func_info->insn_off is set after all code rewrites,
10682 			 * in adjust_btf_func() - no need to adjust
10683 			 */
10684 		}
10685 	} else {
10686 		/* convert i from "first prog to remove" to "first to adjust" */
10687 		if (env->subprog_info[i].start == off)
10688 			i++;
10689 	}
10690 
10691 	/* update fake 'exit' subprog as well */
10692 	for (; i <= env->subprog_cnt; i++)
10693 		env->subprog_info[i].start -= cnt;
10694 
10695 	return 0;
10696 }
10697 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10698 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10699 				      u32 cnt)
10700 {
10701 	struct bpf_prog *prog = env->prog;
10702 	u32 i, l_off, l_cnt, nr_linfo;
10703 	struct bpf_line_info *linfo;
10704 
10705 	nr_linfo = prog->aux->nr_linfo;
10706 	if (!nr_linfo)
10707 		return 0;
10708 
10709 	linfo = prog->aux->linfo;
10710 
10711 	/* find first line info to remove, count lines to be removed */
10712 	for (i = 0; i < nr_linfo; i++)
10713 		if (linfo[i].insn_off >= off)
10714 			break;
10715 
10716 	l_off = i;
10717 	l_cnt = 0;
10718 	for (; i < nr_linfo; i++)
10719 		if (linfo[i].insn_off < off + cnt)
10720 			l_cnt++;
10721 		else
10722 			break;
10723 
10724 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10725 	 * last removed linfo.  prog is already modified, so prog->len == off
10726 	 * means no live instructions after (tail of the program was removed).
10727 	 */
10728 	if (prog->len != off && l_cnt &&
10729 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10730 		l_cnt--;
10731 		linfo[--i].insn_off = off + cnt;
10732 	}
10733 
10734 	/* remove the line info which refer to the removed instructions */
10735 	if (l_cnt) {
10736 		memmove(linfo + l_off, linfo + i,
10737 			sizeof(*linfo) * (nr_linfo - i));
10738 
10739 		prog->aux->nr_linfo -= l_cnt;
10740 		nr_linfo = prog->aux->nr_linfo;
10741 	}
10742 
10743 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10744 	for (i = l_off; i < nr_linfo; i++)
10745 		linfo[i].insn_off -= cnt;
10746 
10747 	/* fix up all subprogs (incl. 'exit') which start >= off */
10748 	for (i = 0; i <= env->subprog_cnt; i++)
10749 		if (env->subprog_info[i].linfo_idx > l_off) {
10750 			/* program may have started in the removed region but
10751 			 * may not be fully removed
10752 			 */
10753 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10754 				env->subprog_info[i].linfo_idx -= l_cnt;
10755 			else
10756 				env->subprog_info[i].linfo_idx = l_off;
10757 		}
10758 
10759 	return 0;
10760 }
10761 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)10762 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10763 {
10764 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10765 	unsigned int orig_prog_len = env->prog->len;
10766 	int err;
10767 
10768 	if (bpf_prog_is_dev_bound(env->prog->aux))
10769 		bpf_prog_offload_remove_insns(env, off, cnt);
10770 
10771 	err = bpf_remove_insns(env->prog, off, cnt);
10772 	if (err)
10773 		return err;
10774 
10775 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10776 	if (err)
10777 		return err;
10778 
10779 	err = bpf_adj_linfo_after_remove(env, off, cnt);
10780 	if (err)
10781 		return err;
10782 
10783 	memmove(aux_data + off,	aux_data + off + cnt,
10784 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
10785 
10786 	return 0;
10787 }
10788 
10789 /* The verifier does more data flow analysis than llvm and will not
10790  * explore branches that are dead at run time. Malicious programs can
10791  * have dead code too. Therefore replace all dead at-run-time code
10792  * with 'ja -1'.
10793  *
10794  * Just nops are not optimal, e.g. if they would sit at the end of the
10795  * program and through another bug we would manage to jump there, then
10796  * we'd execute beyond program memory otherwise. Returning exception
10797  * code also wouldn't work since we can have subprogs where the dead
10798  * code could be located.
10799  */
sanitize_dead_code(struct bpf_verifier_env * env)10800 static void sanitize_dead_code(struct bpf_verifier_env *env)
10801 {
10802 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10803 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10804 	struct bpf_insn *insn = env->prog->insnsi;
10805 	const int insn_cnt = env->prog->len;
10806 	int i;
10807 
10808 	for (i = 0; i < insn_cnt; i++) {
10809 		if (aux_data[i].seen)
10810 			continue;
10811 		memcpy(insn + i, &trap, sizeof(trap));
10812 		aux_data[i].zext_dst = false;
10813 	}
10814 }
10815 
insn_is_cond_jump(u8 code)10816 static bool insn_is_cond_jump(u8 code)
10817 {
10818 	u8 op;
10819 
10820 	if (BPF_CLASS(code) == BPF_JMP32)
10821 		return true;
10822 
10823 	if (BPF_CLASS(code) != BPF_JMP)
10824 		return false;
10825 
10826 	op = BPF_OP(code);
10827 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10828 }
10829 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)10830 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10831 {
10832 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10833 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10834 	struct bpf_insn *insn = env->prog->insnsi;
10835 	const int insn_cnt = env->prog->len;
10836 	int i;
10837 
10838 	for (i = 0; i < insn_cnt; i++, insn++) {
10839 		if (!insn_is_cond_jump(insn->code))
10840 			continue;
10841 
10842 		if (!aux_data[i + 1].seen)
10843 			ja.off = insn->off;
10844 		else if (!aux_data[i + 1 + insn->off].seen)
10845 			ja.off = 0;
10846 		else
10847 			continue;
10848 
10849 		if (bpf_prog_is_dev_bound(env->prog->aux))
10850 			bpf_prog_offload_replace_insn(env, i, &ja);
10851 
10852 		memcpy(insn, &ja, sizeof(ja));
10853 	}
10854 }
10855 
opt_remove_dead_code(struct bpf_verifier_env * env)10856 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10857 {
10858 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10859 	int insn_cnt = env->prog->len;
10860 	int i, err;
10861 
10862 	for (i = 0; i < insn_cnt; i++) {
10863 		int j;
10864 
10865 		j = 0;
10866 		while (i + j < insn_cnt && !aux_data[i + j].seen)
10867 			j++;
10868 		if (!j)
10869 			continue;
10870 
10871 		err = verifier_remove_insns(env, i, j);
10872 		if (err)
10873 			return err;
10874 		insn_cnt = env->prog->len;
10875 	}
10876 
10877 	return 0;
10878 }
10879 
opt_remove_nops(struct bpf_verifier_env * env)10880 static int opt_remove_nops(struct bpf_verifier_env *env)
10881 {
10882 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10883 	struct bpf_insn *insn = env->prog->insnsi;
10884 	int insn_cnt = env->prog->len;
10885 	int i, err;
10886 
10887 	for (i = 0; i < insn_cnt; i++) {
10888 		if (memcmp(&insn[i], &ja, sizeof(ja)))
10889 			continue;
10890 
10891 		err = verifier_remove_insns(env, i, 1);
10892 		if (err)
10893 			return err;
10894 		insn_cnt--;
10895 		i--;
10896 	}
10897 
10898 	return 0;
10899 }
10900 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)10901 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10902 					 const union bpf_attr *attr)
10903 {
10904 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10905 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
10906 	int i, patch_len, delta = 0, len = env->prog->len;
10907 	struct bpf_insn *insns = env->prog->insnsi;
10908 	struct bpf_prog *new_prog;
10909 	bool rnd_hi32;
10910 
10911 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
10912 	zext_patch[1] = BPF_ZEXT_REG(0);
10913 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10914 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10915 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
10916 	for (i = 0; i < len; i++) {
10917 		int adj_idx = i + delta;
10918 		struct bpf_insn insn;
10919 
10920 		insn = insns[adj_idx];
10921 		if (!aux[adj_idx].zext_dst) {
10922 			u8 code, class;
10923 			u32 imm_rnd;
10924 
10925 			if (!rnd_hi32)
10926 				continue;
10927 
10928 			code = insn.code;
10929 			class = BPF_CLASS(code);
10930 			if (insn_no_def(&insn))
10931 				continue;
10932 
10933 			/* NOTE: arg "reg" (the fourth one) is only used for
10934 			 *       BPF_STX which has been ruled out in above
10935 			 *       check, it is safe to pass NULL here.
10936 			 */
10937 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10938 				if (class == BPF_LD &&
10939 				    BPF_MODE(code) == BPF_IMM)
10940 					i++;
10941 				continue;
10942 			}
10943 
10944 			/* ctx load could be transformed into wider load. */
10945 			if (class == BPF_LDX &&
10946 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
10947 				continue;
10948 
10949 			imm_rnd = get_random_int();
10950 			rnd_hi32_patch[0] = insn;
10951 			rnd_hi32_patch[1].imm = imm_rnd;
10952 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10953 			patch = rnd_hi32_patch;
10954 			patch_len = 4;
10955 			goto apply_patch_buffer;
10956 		}
10957 
10958 		if (!bpf_jit_needs_zext())
10959 			continue;
10960 
10961 		zext_patch[0] = insn;
10962 		zext_patch[1].dst_reg = insn.dst_reg;
10963 		zext_patch[1].src_reg = insn.dst_reg;
10964 		patch = zext_patch;
10965 		patch_len = 2;
10966 apply_patch_buffer:
10967 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
10968 		if (!new_prog)
10969 			return -ENOMEM;
10970 		env->prog = new_prog;
10971 		insns = new_prog->insnsi;
10972 		aux = env->insn_aux_data;
10973 		delta += patch_len - 1;
10974 	}
10975 
10976 	return 0;
10977 }
10978 
10979 /* convert load instructions that access fields of a context type into a
10980  * sequence of instructions that access fields of the underlying structure:
10981  *     struct __sk_buff    -> struct sk_buff
10982  *     struct bpf_sock_ops -> struct sock
10983  */
convert_ctx_accesses(struct bpf_verifier_env * env)10984 static int convert_ctx_accesses(struct bpf_verifier_env *env)
10985 {
10986 	const struct bpf_verifier_ops *ops = env->ops;
10987 	int i, cnt, size, ctx_field_size, delta = 0;
10988 	const int insn_cnt = env->prog->len;
10989 	struct bpf_insn insn_buf[16], *insn;
10990 	u32 target_size, size_default, off;
10991 	struct bpf_prog *new_prog;
10992 	enum bpf_access_type type;
10993 	bool is_narrower_load;
10994 
10995 	if (ops->gen_prologue || env->seen_direct_write) {
10996 		if (!ops->gen_prologue) {
10997 			verbose(env, "bpf verifier is misconfigured\n");
10998 			return -EINVAL;
10999 		}
11000 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11001 					env->prog);
11002 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11003 			verbose(env, "bpf verifier is misconfigured\n");
11004 			return -EINVAL;
11005 		} else if (cnt) {
11006 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11007 			if (!new_prog)
11008 				return -ENOMEM;
11009 
11010 			env->prog = new_prog;
11011 			delta += cnt - 1;
11012 		}
11013 	}
11014 
11015 	if (bpf_prog_is_dev_bound(env->prog->aux))
11016 		return 0;
11017 
11018 	insn = env->prog->insnsi + delta;
11019 
11020 	for (i = 0; i < insn_cnt; i++, insn++) {
11021 		bpf_convert_ctx_access_t convert_ctx_access;
11022 		bool ctx_access;
11023 
11024 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11025 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11026 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11027 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11028 			type = BPF_READ;
11029 			ctx_access = true;
11030 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11031 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11032 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11033 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11034 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11035 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11036 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11037 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11038 			type = BPF_WRITE;
11039 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11040 		} else {
11041 			continue;
11042 		}
11043 
11044 		if (type == BPF_WRITE &&
11045 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
11046 			struct bpf_insn patch[] = {
11047 				*insn,
11048 				BPF_ST_NOSPEC(),
11049 			};
11050 
11051 			cnt = ARRAY_SIZE(patch);
11052 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11053 			if (!new_prog)
11054 				return -ENOMEM;
11055 
11056 			delta    += cnt - 1;
11057 			env->prog = new_prog;
11058 			insn      = new_prog->insnsi + i + delta;
11059 			continue;
11060 		}
11061 
11062 		if (!ctx_access)
11063 			continue;
11064 
11065 		switch (env->insn_aux_data[i + delta].ptr_type) {
11066 		case PTR_TO_CTX:
11067 			if (!ops->convert_ctx_access)
11068 				continue;
11069 			convert_ctx_access = ops->convert_ctx_access;
11070 			break;
11071 		case PTR_TO_SOCKET:
11072 		case PTR_TO_SOCK_COMMON:
11073 			convert_ctx_access = bpf_sock_convert_ctx_access;
11074 			break;
11075 		case PTR_TO_TCP_SOCK:
11076 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11077 			break;
11078 		case PTR_TO_XDP_SOCK:
11079 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11080 			break;
11081 		case PTR_TO_BTF_ID:
11082 			if (type == BPF_READ) {
11083 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11084 					BPF_SIZE((insn)->code);
11085 				env->prog->aux->num_exentries++;
11086 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11087 				verbose(env, "Writes through BTF pointers are not allowed\n");
11088 				return -EINVAL;
11089 			}
11090 			continue;
11091 		default:
11092 			continue;
11093 		}
11094 
11095 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11096 		size = BPF_LDST_BYTES(insn);
11097 
11098 		/* If the read access is a narrower load of the field,
11099 		 * convert to a 4/8-byte load, to minimum program type specific
11100 		 * convert_ctx_access changes. If conversion is successful,
11101 		 * we will apply proper mask to the result.
11102 		 */
11103 		is_narrower_load = size < ctx_field_size;
11104 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11105 		off = insn->off;
11106 		if (is_narrower_load) {
11107 			u8 size_code;
11108 
11109 			if (type == BPF_WRITE) {
11110 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11111 				return -EINVAL;
11112 			}
11113 
11114 			size_code = BPF_H;
11115 			if (ctx_field_size == 4)
11116 				size_code = BPF_W;
11117 			else if (ctx_field_size == 8)
11118 				size_code = BPF_DW;
11119 
11120 			insn->off = off & ~(size_default - 1);
11121 			insn->code = BPF_LDX | BPF_MEM | size_code;
11122 		}
11123 
11124 		target_size = 0;
11125 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11126 					 &target_size);
11127 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11128 		    (ctx_field_size && !target_size)) {
11129 			verbose(env, "bpf verifier is misconfigured\n");
11130 			return -EINVAL;
11131 		}
11132 
11133 		if (is_narrower_load && size < target_size) {
11134 			u8 shift = bpf_ctx_narrow_access_offset(
11135 				off, size, size_default) * 8;
11136 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11137 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11138 				return -EINVAL;
11139 			}
11140 			if (ctx_field_size <= 4) {
11141 				if (shift)
11142 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11143 									insn->dst_reg,
11144 									shift);
11145 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11146 								(1 << size * 8) - 1);
11147 			} else {
11148 				if (shift)
11149 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11150 									insn->dst_reg,
11151 									shift);
11152 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11153 								(1ULL << size * 8) - 1);
11154 			}
11155 		}
11156 
11157 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11158 		if (!new_prog)
11159 			return -ENOMEM;
11160 
11161 		delta += cnt - 1;
11162 
11163 		/* keep walking new program and skip insns we just inserted */
11164 		env->prog = new_prog;
11165 		insn      = new_prog->insnsi + i + delta;
11166 	}
11167 
11168 	return 0;
11169 }
11170 
jit_subprogs(struct bpf_verifier_env * env)11171 static int jit_subprogs(struct bpf_verifier_env *env)
11172 {
11173 	struct bpf_prog *prog = env->prog, **func, *tmp;
11174 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11175 	struct bpf_map *map_ptr;
11176 	struct bpf_insn *insn;
11177 	void *old_bpf_func;
11178 	int err, num_exentries;
11179 
11180 	if (env->subprog_cnt <= 1)
11181 		return 0;
11182 
11183 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11184 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11185 		    insn->src_reg != BPF_PSEUDO_CALL)
11186 			continue;
11187 		/* Upon error here we cannot fall back to interpreter but
11188 		 * need a hard reject of the program. Thus -EFAULT is
11189 		 * propagated in any case.
11190 		 */
11191 		subprog = find_subprog(env, i + insn->imm + 1);
11192 		if (subprog < 0) {
11193 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11194 				  i + insn->imm + 1);
11195 			return -EFAULT;
11196 		}
11197 		/* temporarily remember subprog id inside insn instead of
11198 		 * aux_data, since next loop will split up all insns into funcs
11199 		 */
11200 		insn->off = subprog;
11201 		/* remember original imm in case JIT fails and fallback
11202 		 * to interpreter will be needed
11203 		 */
11204 		env->insn_aux_data[i].call_imm = insn->imm;
11205 		/* point imm to __bpf_call_base+1 from JITs point of view */
11206 		insn->imm = 1;
11207 	}
11208 
11209 	err = bpf_prog_alloc_jited_linfo(prog);
11210 	if (err)
11211 		goto out_undo_insn;
11212 
11213 	err = -ENOMEM;
11214 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11215 	if (!func)
11216 		goto out_undo_insn;
11217 
11218 	for (i = 0; i < env->subprog_cnt; i++) {
11219 		subprog_start = subprog_end;
11220 		subprog_end = env->subprog_info[i + 1].start;
11221 
11222 		len = subprog_end - subprog_start;
11223 		/* BPF_PROG_RUN doesn't call subprogs directly,
11224 		 * hence main prog stats include the runtime of subprogs.
11225 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11226 		 * func[i]->aux->stats will never be accessed and stays NULL
11227 		 */
11228 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11229 		if (!func[i])
11230 			goto out_free;
11231 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11232 		       len * sizeof(struct bpf_insn));
11233 		func[i]->type = prog->type;
11234 		func[i]->len = len;
11235 		if (bpf_prog_calc_tag(func[i]))
11236 			goto out_free;
11237 		func[i]->is_func = 1;
11238 		func[i]->aux->func_idx = i;
11239 		/* Below members will be freed only at prog->aux */
11240 		func[i]->aux->btf = prog->aux->btf;
11241 		func[i]->aux->func_info = prog->aux->func_info;
11242 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11243 		func[i]->aux->poke_tab = prog->aux->poke_tab;
11244 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11245 
11246 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11247 			struct bpf_jit_poke_descriptor *poke;
11248 
11249 			poke = &prog->aux->poke_tab[j];
11250 			if (poke->insn_idx < subprog_end &&
11251 			    poke->insn_idx >= subprog_start)
11252 				poke->aux = func[i]->aux;
11253 		}
11254 
11255 		func[i]->aux->name[0] = 'F';
11256 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11257 		func[i]->jit_requested = 1;
11258 		func[i]->aux->linfo = prog->aux->linfo;
11259 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11260 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11261 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11262 		num_exentries = 0;
11263 		insn = func[i]->insnsi;
11264 		for (j = 0; j < func[i]->len; j++, insn++) {
11265 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11266 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11267 				num_exentries++;
11268 		}
11269 		func[i]->aux->num_exentries = num_exentries;
11270 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11271 		func[i] = bpf_int_jit_compile(func[i]);
11272 		if (!func[i]->jited) {
11273 			err = -ENOTSUPP;
11274 			goto out_free;
11275 		}
11276 		cond_resched();
11277 	}
11278 
11279 	/* at this point all bpf functions were successfully JITed
11280 	 * now populate all bpf_calls with correct addresses and
11281 	 * run last pass of JIT
11282 	 */
11283 	for (i = 0; i < env->subprog_cnt; i++) {
11284 		insn = func[i]->insnsi;
11285 		for (j = 0; j < func[i]->len; j++, insn++) {
11286 			if (insn->code != (BPF_JMP | BPF_CALL) ||
11287 			    insn->src_reg != BPF_PSEUDO_CALL)
11288 				continue;
11289 			subprog = insn->off;
11290 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11291 				    __bpf_call_base;
11292 		}
11293 
11294 		/* we use the aux data to keep a list of the start addresses
11295 		 * of the JITed images for each function in the program
11296 		 *
11297 		 * for some architectures, such as powerpc64, the imm field
11298 		 * might not be large enough to hold the offset of the start
11299 		 * address of the callee's JITed image from __bpf_call_base
11300 		 *
11301 		 * in such cases, we can lookup the start address of a callee
11302 		 * by using its subprog id, available from the off field of
11303 		 * the call instruction, as an index for this list
11304 		 */
11305 		func[i]->aux->func = func;
11306 		func[i]->aux->func_cnt = env->subprog_cnt;
11307 	}
11308 	for (i = 0; i < env->subprog_cnt; i++) {
11309 		old_bpf_func = func[i]->bpf_func;
11310 		tmp = bpf_int_jit_compile(func[i]);
11311 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11312 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11313 			err = -ENOTSUPP;
11314 			goto out_free;
11315 		}
11316 		cond_resched();
11317 	}
11318 
11319 	/* finally lock prog and jit images for all functions and
11320 	 * populate kallsysm
11321 	 */
11322 	for (i = 0; i < env->subprog_cnt; i++) {
11323 		bpf_prog_lock_ro(func[i]);
11324 		bpf_prog_kallsyms_add(func[i]);
11325 	}
11326 
11327 	/* Last step: make now unused interpreter insns from main
11328 	 * prog consistent for later dump requests, so they can
11329 	 * later look the same as if they were interpreted only.
11330 	 */
11331 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11332 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11333 		    insn->src_reg != BPF_PSEUDO_CALL)
11334 			continue;
11335 		insn->off = env->insn_aux_data[i].call_imm;
11336 		subprog = find_subprog(env, i + insn->off + 1);
11337 		insn->imm = subprog;
11338 	}
11339 
11340 	prog->jited = 1;
11341 	prog->bpf_func = func[0]->bpf_func;
11342 	prog->aux->func = func;
11343 	prog->aux->func_cnt = env->subprog_cnt;
11344 	bpf_prog_free_unused_jited_linfo(prog);
11345 	return 0;
11346 out_free:
11347 	/* We failed JIT'ing, so at this point we need to unregister poke
11348 	 * descriptors from subprogs, so that kernel is not attempting to
11349 	 * patch it anymore as we're freeing the subprog JIT memory.
11350 	 */
11351 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11352 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11353 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11354 	}
11355 	/* At this point we're guaranteed that poke descriptors are not
11356 	 * live anymore. We can just unlink its descriptor table as it's
11357 	 * released with the main prog.
11358 	 */
11359 	for (i = 0; i < env->subprog_cnt; i++) {
11360 		if (!func[i])
11361 			continue;
11362 		func[i]->aux->poke_tab = NULL;
11363 		bpf_jit_free(func[i]);
11364 	}
11365 	kfree(func);
11366 out_undo_insn:
11367 	/* cleanup main prog to be interpreted */
11368 	prog->jit_requested = 0;
11369 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11370 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11371 		    insn->src_reg != BPF_PSEUDO_CALL)
11372 			continue;
11373 		insn->off = 0;
11374 		insn->imm = env->insn_aux_data[i].call_imm;
11375 	}
11376 	bpf_prog_free_jited_linfo(prog);
11377 	return err;
11378 }
11379 
fixup_call_args(struct bpf_verifier_env * env)11380 static int fixup_call_args(struct bpf_verifier_env *env)
11381 {
11382 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11383 	struct bpf_prog *prog = env->prog;
11384 	struct bpf_insn *insn = prog->insnsi;
11385 	int i, depth;
11386 #endif
11387 	int err = 0;
11388 
11389 	if (env->prog->jit_requested &&
11390 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
11391 		err = jit_subprogs(env);
11392 		if (err == 0)
11393 			return 0;
11394 		if (err == -EFAULT)
11395 			return err;
11396 	}
11397 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11398 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11399 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
11400 		 * have to be rejected, since interpreter doesn't support them yet.
11401 		 */
11402 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11403 		return -EINVAL;
11404 	}
11405 	for (i = 0; i < prog->len; i++, insn++) {
11406 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11407 		    insn->src_reg != BPF_PSEUDO_CALL)
11408 			continue;
11409 		depth = get_callee_stack_depth(env, insn, i);
11410 		if (depth < 0)
11411 			return depth;
11412 		bpf_patch_call_args(insn, depth);
11413 	}
11414 	err = 0;
11415 #endif
11416 	return err;
11417 }
11418 
11419 /* fixup insn->imm field of bpf_call instructions
11420  * and inline eligible helpers as explicit sequence of BPF instructions
11421  *
11422  * this function is called after eBPF program passed verification
11423  */
fixup_bpf_calls(struct bpf_verifier_env * env)11424 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11425 {
11426 	struct bpf_prog *prog = env->prog;
11427 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
11428 	struct bpf_insn *insn = prog->insnsi;
11429 	const struct bpf_func_proto *fn;
11430 	const int insn_cnt = prog->len;
11431 	const struct bpf_map_ops *ops;
11432 	struct bpf_insn_aux_data *aux;
11433 	struct bpf_insn insn_buf[16];
11434 	struct bpf_prog *new_prog;
11435 	struct bpf_map *map_ptr;
11436 	int i, ret, cnt, delta = 0;
11437 
11438 	for (i = 0; i < insn_cnt; i++, insn++) {
11439 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11440 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11441 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11442 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11443 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11444 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11445 			struct bpf_insn *patchlet;
11446 			struct bpf_insn chk_and_div[] = {
11447 				/* [R,W]x div 0 -> 0 */
11448 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11449 					     BPF_JNE | BPF_K, insn->src_reg,
11450 					     0, 2, 0),
11451 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11452 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11453 				*insn,
11454 			};
11455 			struct bpf_insn chk_and_mod[] = {
11456 				/* [R,W]x mod 0 -> [R,W]x */
11457 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11458 					     BPF_JEQ | BPF_K, insn->src_reg,
11459 					     0, 1 + (is64 ? 0 : 1), 0),
11460 				*insn,
11461 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11462 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11463 			};
11464 
11465 			patchlet = isdiv ? chk_and_div : chk_and_mod;
11466 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11467 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11468 
11469 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11470 			if (!new_prog)
11471 				return -ENOMEM;
11472 
11473 			delta    += cnt - 1;
11474 			env->prog = prog = new_prog;
11475 			insn      = new_prog->insnsi + i + delta;
11476 			continue;
11477 		}
11478 
11479 		if (BPF_CLASS(insn->code) == BPF_LD &&
11480 		    (BPF_MODE(insn->code) == BPF_ABS ||
11481 		     BPF_MODE(insn->code) == BPF_IND)) {
11482 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
11483 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11484 				verbose(env, "bpf verifier is misconfigured\n");
11485 				return -EINVAL;
11486 			}
11487 
11488 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11489 			if (!new_prog)
11490 				return -ENOMEM;
11491 
11492 			delta    += cnt - 1;
11493 			env->prog = prog = new_prog;
11494 			insn      = new_prog->insnsi + i + delta;
11495 			continue;
11496 		}
11497 
11498 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11499 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11500 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11501 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11502 			struct bpf_insn insn_buf[16];
11503 			struct bpf_insn *patch = &insn_buf[0];
11504 			bool issrc, isneg, isimm;
11505 			u32 off_reg;
11506 
11507 			aux = &env->insn_aux_data[i + delta];
11508 			if (!aux->alu_state ||
11509 			    aux->alu_state == BPF_ALU_NON_POINTER)
11510 				continue;
11511 
11512 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11513 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11514 				BPF_ALU_SANITIZE_SRC;
11515 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11516 
11517 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11518 			if (isimm) {
11519 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11520 			} else {
11521 				if (isneg)
11522 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11523 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11524 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11525 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11526 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11527 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11528 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11529 			}
11530 			if (!issrc)
11531 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11532 			insn->src_reg = BPF_REG_AX;
11533 			if (isneg)
11534 				insn->code = insn->code == code_add ?
11535 					     code_sub : code_add;
11536 			*patch++ = *insn;
11537 			if (issrc && isneg && !isimm)
11538 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11539 			cnt = patch - insn_buf;
11540 
11541 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11542 			if (!new_prog)
11543 				return -ENOMEM;
11544 
11545 			delta    += cnt - 1;
11546 			env->prog = prog = new_prog;
11547 			insn      = new_prog->insnsi + i + delta;
11548 			continue;
11549 		}
11550 
11551 		if (insn->code != (BPF_JMP | BPF_CALL))
11552 			continue;
11553 		if (insn->src_reg == BPF_PSEUDO_CALL)
11554 			continue;
11555 
11556 		if (insn->imm == BPF_FUNC_get_route_realm)
11557 			prog->dst_needed = 1;
11558 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11559 			bpf_user_rnd_init_once();
11560 		if (insn->imm == BPF_FUNC_override_return)
11561 			prog->kprobe_override = 1;
11562 		if (insn->imm == BPF_FUNC_tail_call) {
11563 			/* If we tail call into other programs, we
11564 			 * cannot make any assumptions since they can
11565 			 * be replaced dynamically during runtime in
11566 			 * the program array.
11567 			 */
11568 			prog->cb_access = 1;
11569 			if (!allow_tail_call_in_subprogs(env))
11570 				prog->aux->stack_depth = MAX_BPF_STACK;
11571 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11572 
11573 			/* mark bpf_tail_call as different opcode to avoid
11574 			 * conditional branch in the interpeter for every normal
11575 			 * call and to prevent accidental JITing by JIT compiler
11576 			 * that doesn't support bpf_tail_call yet
11577 			 */
11578 			insn->imm = 0;
11579 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11580 
11581 			aux = &env->insn_aux_data[i + delta];
11582 			if (env->bpf_capable && !expect_blinding &&
11583 			    prog->jit_requested &&
11584 			    !bpf_map_key_poisoned(aux) &&
11585 			    !bpf_map_ptr_poisoned(aux) &&
11586 			    !bpf_map_ptr_unpriv(aux)) {
11587 				struct bpf_jit_poke_descriptor desc = {
11588 					.reason = BPF_POKE_REASON_TAIL_CALL,
11589 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11590 					.tail_call.key = bpf_map_key_immediate(aux),
11591 					.insn_idx = i + delta,
11592 				};
11593 
11594 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11595 				if (ret < 0) {
11596 					verbose(env, "adding tail call poke descriptor failed\n");
11597 					return ret;
11598 				}
11599 
11600 				insn->imm = ret + 1;
11601 				continue;
11602 			}
11603 
11604 			if (!bpf_map_ptr_unpriv(aux))
11605 				continue;
11606 
11607 			/* instead of changing every JIT dealing with tail_call
11608 			 * emit two extra insns:
11609 			 * if (index >= max_entries) goto out;
11610 			 * index &= array->index_mask;
11611 			 * to avoid out-of-bounds cpu speculation
11612 			 */
11613 			if (bpf_map_ptr_poisoned(aux)) {
11614 				verbose(env, "tail_call abusing map_ptr\n");
11615 				return -EINVAL;
11616 			}
11617 
11618 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11619 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11620 						  map_ptr->max_entries, 2);
11621 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11622 						    container_of(map_ptr,
11623 								 struct bpf_array,
11624 								 map)->index_mask);
11625 			insn_buf[2] = *insn;
11626 			cnt = 3;
11627 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11628 			if (!new_prog)
11629 				return -ENOMEM;
11630 
11631 			delta    += cnt - 1;
11632 			env->prog = prog = new_prog;
11633 			insn      = new_prog->insnsi + i + delta;
11634 			continue;
11635 		}
11636 
11637 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11638 		 * and other inlining handlers are currently limited to 64 bit
11639 		 * only.
11640 		 */
11641 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11642 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11643 		     insn->imm == BPF_FUNC_map_update_elem ||
11644 		     insn->imm == BPF_FUNC_map_delete_elem ||
11645 		     insn->imm == BPF_FUNC_map_push_elem   ||
11646 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11647 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11648 			aux = &env->insn_aux_data[i + delta];
11649 			if (bpf_map_ptr_poisoned(aux))
11650 				goto patch_call_imm;
11651 
11652 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11653 			ops = map_ptr->ops;
11654 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11655 			    ops->map_gen_lookup) {
11656 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11657 				if (cnt == -EOPNOTSUPP)
11658 					goto patch_map_ops_generic;
11659 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11660 					verbose(env, "bpf verifier is misconfigured\n");
11661 					return -EINVAL;
11662 				}
11663 
11664 				new_prog = bpf_patch_insn_data(env, i + delta,
11665 							       insn_buf, cnt);
11666 				if (!new_prog)
11667 					return -ENOMEM;
11668 
11669 				delta    += cnt - 1;
11670 				env->prog = prog = new_prog;
11671 				insn      = new_prog->insnsi + i + delta;
11672 				continue;
11673 			}
11674 
11675 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11676 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11677 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11678 				     (int (*)(struct bpf_map *map, void *key))NULL));
11679 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11680 				     (int (*)(struct bpf_map *map, void *key, void *value,
11681 					      u64 flags))NULL));
11682 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11683 				     (int (*)(struct bpf_map *map, void *value,
11684 					      u64 flags))NULL));
11685 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11686 				     (int (*)(struct bpf_map *map, void *value))NULL));
11687 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11688 				     (int (*)(struct bpf_map *map, void *value))NULL));
11689 patch_map_ops_generic:
11690 			switch (insn->imm) {
11691 			case BPF_FUNC_map_lookup_elem:
11692 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11693 					    __bpf_call_base;
11694 				continue;
11695 			case BPF_FUNC_map_update_elem:
11696 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11697 					    __bpf_call_base;
11698 				continue;
11699 			case BPF_FUNC_map_delete_elem:
11700 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11701 					    __bpf_call_base;
11702 				continue;
11703 			case BPF_FUNC_map_push_elem:
11704 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11705 					    __bpf_call_base;
11706 				continue;
11707 			case BPF_FUNC_map_pop_elem:
11708 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11709 					    __bpf_call_base;
11710 				continue;
11711 			case BPF_FUNC_map_peek_elem:
11712 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11713 					    __bpf_call_base;
11714 				continue;
11715 			}
11716 
11717 			goto patch_call_imm;
11718 		}
11719 
11720 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11721 		    insn->imm == BPF_FUNC_jiffies64) {
11722 			struct bpf_insn ld_jiffies_addr[2] = {
11723 				BPF_LD_IMM64(BPF_REG_0,
11724 					     (unsigned long)&jiffies),
11725 			};
11726 
11727 			insn_buf[0] = ld_jiffies_addr[0];
11728 			insn_buf[1] = ld_jiffies_addr[1];
11729 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11730 						  BPF_REG_0, 0);
11731 			cnt = 3;
11732 
11733 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11734 						       cnt);
11735 			if (!new_prog)
11736 				return -ENOMEM;
11737 
11738 			delta    += cnt - 1;
11739 			env->prog = prog = new_prog;
11740 			insn      = new_prog->insnsi + i + delta;
11741 			continue;
11742 		}
11743 
11744 patch_call_imm:
11745 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11746 		/* all functions that have prototype and verifier allowed
11747 		 * programs to call them, must be real in-kernel functions
11748 		 */
11749 		if (!fn->func) {
11750 			verbose(env,
11751 				"kernel subsystem misconfigured func %s#%d\n",
11752 				func_id_name(insn->imm), insn->imm);
11753 			return -EFAULT;
11754 		}
11755 		insn->imm = fn->func - __bpf_call_base;
11756 	}
11757 
11758 	/* Since poke tab is now finalized, publish aux to tracker. */
11759 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11760 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11761 		if (!map_ptr->ops->map_poke_track ||
11762 		    !map_ptr->ops->map_poke_untrack ||
11763 		    !map_ptr->ops->map_poke_run) {
11764 			verbose(env, "bpf verifier is misconfigured\n");
11765 			return -EINVAL;
11766 		}
11767 
11768 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11769 		if (ret < 0) {
11770 			verbose(env, "tracking tail call prog failed\n");
11771 			return ret;
11772 		}
11773 	}
11774 
11775 	return 0;
11776 }
11777 
free_states(struct bpf_verifier_env * env)11778 static void free_states(struct bpf_verifier_env *env)
11779 {
11780 	struct bpf_verifier_state_list *sl, *sln;
11781 	int i;
11782 
11783 	sl = env->free_list;
11784 	while (sl) {
11785 		sln = sl->next;
11786 		free_verifier_state(&sl->state, false);
11787 		kfree(sl);
11788 		sl = sln;
11789 	}
11790 	env->free_list = NULL;
11791 
11792 	if (!env->explored_states)
11793 		return;
11794 
11795 	for (i = 0; i < state_htab_size(env); i++) {
11796 		sl = env->explored_states[i];
11797 
11798 		while (sl) {
11799 			sln = sl->next;
11800 			free_verifier_state(&sl->state, false);
11801 			kfree(sl);
11802 			sl = sln;
11803 		}
11804 		env->explored_states[i] = NULL;
11805 	}
11806 }
11807 
do_check_common(struct bpf_verifier_env * env,int subprog)11808 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11809 {
11810 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11811 	struct bpf_verifier_state *state;
11812 	struct bpf_reg_state *regs;
11813 	int ret, i;
11814 
11815 	env->prev_linfo = NULL;
11816 	env->pass_cnt++;
11817 
11818 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11819 	if (!state)
11820 		return -ENOMEM;
11821 	state->curframe = 0;
11822 	state->speculative = false;
11823 	state->branches = 1;
11824 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11825 	if (!state->frame[0]) {
11826 		kfree(state);
11827 		return -ENOMEM;
11828 	}
11829 	env->cur_state = state;
11830 	init_func_state(env, state->frame[0],
11831 			BPF_MAIN_FUNC /* callsite */,
11832 			0 /* frameno */,
11833 			subprog);
11834 
11835 	regs = state->frame[state->curframe]->regs;
11836 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11837 		ret = btf_prepare_func_args(env, subprog, regs);
11838 		if (ret)
11839 			goto out;
11840 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11841 			if (regs[i].type == PTR_TO_CTX)
11842 				mark_reg_known_zero(env, regs, i);
11843 			else if (regs[i].type == SCALAR_VALUE)
11844 				mark_reg_unknown(env, regs, i);
11845 		}
11846 	} else {
11847 		/* 1st arg to a function */
11848 		regs[BPF_REG_1].type = PTR_TO_CTX;
11849 		mark_reg_known_zero(env, regs, BPF_REG_1);
11850 		ret = btf_check_func_arg_match(env, subprog, regs);
11851 		if (ret == -EFAULT)
11852 			/* unlikely verifier bug. abort.
11853 			 * ret == 0 and ret < 0 are sadly acceptable for
11854 			 * main() function due to backward compatibility.
11855 			 * Like socket filter program may be written as:
11856 			 * int bpf_prog(struct pt_regs *ctx)
11857 			 * and never dereference that ctx in the program.
11858 			 * 'struct pt_regs' is a type mismatch for socket
11859 			 * filter that should be using 'struct __sk_buff'.
11860 			 */
11861 			goto out;
11862 	}
11863 
11864 	ret = do_check(env);
11865 out:
11866 	/* check for NULL is necessary, since cur_state can be freed inside
11867 	 * do_check() under memory pressure.
11868 	 */
11869 	if (env->cur_state) {
11870 		free_verifier_state(env->cur_state, true);
11871 		env->cur_state = NULL;
11872 	}
11873 	while (!pop_stack(env, NULL, NULL, false));
11874 	if (!ret && pop_log)
11875 		bpf_vlog_reset(&env->log, 0);
11876 	free_states(env);
11877 	return ret;
11878 }
11879 
11880 /* Verify all global functions in a BPF program one by one based on their BTF.
11881  * All global functions must pass verification. Otherwise the whole program is rejected.
11882  * Consider:
11883  * int bar(int);
11884  * int foo(int f)
11885  * {
11886  *    return bar(f);
11887  * }
11888  * int bar(int b)
11889  * {
11890  *    ...
11891  * }
11892  * foo() will be verified first for R1=any_scalar_value. During verification it
11893  * will be assumed that bar() already verified successfully and call to bar()
11894  * from foo() will be checked for type match only. Later bar() will be verified
11895  * independently to check that it's safe for R1=any_scalar_value.
11896  */
do_check_subprogs(struct bpf_verifier_env * env)11897 static int do_check_subprogs(struct bpf_verifier_env *env)
11898 {
11899 	struct bpf_prog_aux *aux = env->prog->aux;
11900 	int i, ret;
11901 
11902 	if (!aux->func_info)
11903 		return 0;
11904 
11905 	for (i = 1; i < env->subprog_cnt; i++) {
11906 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11907 			continue;
11908 		env->insn_idx = env->subprog_info[i].start;
11909 		WARN_ON_ONCE(env->insn_idx == 0);
11910 		ret = do_check_common(env, i);
11911 		if (ret) {
11912 			return ret;
11913 		} else if (env->log.level & BPF_LOG_LEVEL) {
11914 			verbose(env,
11915 				"Func#%d is safe for any args that match its prototype\n",
11916 				i);
11917 		}
11918 	}
11919 	return 0;
11920 }
11921 
do_check_main(struct bpf_verifier_env * env)11922 static int do_check_main(struct bpf_verifier_env *env)
11923 {
11924 	int ret;
11925 
11926 	env->insn_idx = 0;
11927 	ret = do_check_common(env, 0);
11928 	if (!ret)
11929 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11930 	return ret;
11931 }
11932 
11933 
print_verification_stats(struct bpf_verifier_env * env)11934 static void print_verification_stats(struct bpf_verifier_env *env)
11935 {
11936 	int i;
11937 
11938 	if (env->log.level & BPF_LOG_STATS) {
11939 		verbose(env, "verification time %lld usec\n",
11940 			div_u64(env->verification_time, 1000));
11941 		verbose(env, "stack depth ");
11942 		for (i = 0; i < env->subprog_cnt; i++) {
11943 			u32 depth = env->subprog_info[i].stack_depth;
11944 
11945 			verbose(env, "%d", depth);
11946 			if (i + 1 < env->subprog_cnt)
11947 				verbose(env, "+");
11948 		}
11949 		verbose(env, "\n");
11950 	}
11951 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11952 		"total_states %d peak_states %d mark_read %d\n",
11953 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11954 		env->max_states_per_insn, env->total_states,
11955 		env->peak_states, env->longest_mark_read_walk);
11956 }
11957 
check_struct_ops_btf_id(struct bpf_verifier_env * env)11958 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11959 {
11960 	const struct btf_type *t, *func_proto;
11961 	const struct bpf_struct_ops *st_ops;
11962 	const struct btf_member *member;
11963 	struct bpf_prog *prog = env->prog;
11964 	u32 btf_id, member_idx;
11965 	const char *mname;
11966 
11967 	if (!prog->gpl_compatible) {
11968 		verbose(env, "struct ops programs must have a GPL compatible license\n");
11969 		return -EINVAL;
11970 	}
11971 
11972 	btf_id = prog->aux->attach_btf_id;
11973 	st_ops = bpf_struct_ops_find(btf_id);
11974 	if (!st_ops) {
11975 		verbose(env, "attach_btf_id %u is not a supported struct\n",
11976 			btf_id);
11977 		return -ENOTSUPP;
11978 	}
11979 
11980 	t = st_ops->type;
11981 	member_idx = prog->expected_attach_type;
11982 	if (member_idx >= btf_type_vlen(t)) {
11983 		verbose(env, "attach to invalid member idx %u of struct %s\n",
11984 			member_idx, st_ops->name);
11985 		return -EINVAL;
11986 	}
11987 
11988 	member = &btf_type_member(t)[member_idx];
11989 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
11990 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
11991 					       NULL);
11992 	if (!func_proto) {
11993 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
11994 			mname, member_idx, st_ops->name);
11995 		return -EINVAL;
11996 	}
11997 
11998 	if (st_ops->check_member) {
11999 		int err = st_ops->check_member(t, member);
12000 
12001 		if (err) {
12002 			verbose(env, "attach to unsupported member %s of struct %s\n",
12003 				mname, st_ops->name);
12004 			return err;
12005 		}
12006 	}
12007 
12008 	prog->aux->attach_func_proto = func_proto;
12009 	prog->aux->attach_func_name = mname;
12010 	env->ops = st_ops->verifier_ops;
12011 
12012 	return 0;
12013 }
12014 #define SECURITY_PREFIX "security_"
12015 
check_attach_modify_return(unsigned long addr,const char * func_name)12016 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12017 {
12018 	if (within_error_injection_list(addr) ||
12019 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12020 		return 0;
12021 
12022 	return -EINVAL;
12023 }
12024 
12025 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12026 BTF_SET_START(btf_sleepable_lsm_hooks)
12027 #ifdef CONFIG_BPF_LSM
BTF_ID(func,bpf_lsm_bprm_committed_creds)12028 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12029 #else
12030 BTF_ID_UNUSED
12031 #endif
12032 BTF_SET_END(btf_sleepable_lsm_hooks)
12033 
12034 static int check_sleepable_lsm_hook(u32 btf_id)
12035 {
12036 	return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12037 }
12038 
12039 /* list of non-sleepable functions that are otherwise on
12040  * ALLOW_ERROR_INJECTION list
12041  */
12042 BTF_SET_START(btf_non_sleepable_error_inject)
12043 /* Three functions below can be called from sleepable and non-sleepable context.
12044  * Assume non-sleepable from bpf safety point of view.
12045  */
BTF_ID(func,__add_to_page_cache_locked)12046 BTF_ID(func, __add_to_page_cache_locked)
12047 BTF_ID(func, should_fail_alloc_page)
12048 BTF_ID(func, should_failslab)
12049 BTF_SET_END(btf_non_sleepable_error_inject)
12050 
12051 static int check_non_sleepable_error_inject(u32 btf_id)
12052 {
12053 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12054 }
12055 
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)12056 int bpf_check_attach_target(struct bpf_verifier_log *log,
12057 			    const struct bpf_prog *prog,
12058 			    const struct bpf_prog *tgt_prog,
12059 			    u32 btf_id,
12060 			    struct bpf_attach_target_info *tgt_info)
12061 {
12062 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12063 	const char prefix[] = "btf_trace_";
12064 	int ret = 0, subprog = -1, i;
12065 	const struct btf_type *t;
12066 	bool conservative = true;
12067 	const char *tname;
12068 	struct btf *btf;
12069 	long addr = 0;
12070 
12071 	if (!btf_id) {
12072 		bpf_log(log, "Tracing programs must provide btf_id\n");
12073 		return -EINVAL;
12074 	}
12075 	btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12076 	if (!btf) {
12077 		bpf_log(log,
12078 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12079 		return -EINVAL;
12080 	}
12081 	t = btf_type_by_id(btf, btf_id);
12082 	if (!t) {
12083 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12084 		return -EINVAL;
12085 	}
12086 	tname = btf_name_by_offset(btf, t->name_off);
12087 	if (!tname) {
12088 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12089 		return -EINVAL;
12090 	}
12091 	if (tgt_prog) {
12092 		struct bpf_prog_aux *aux = tgt_prog->aux;
12093 
12094 		for (i = 0; i < aux->func_info_cnt; i++)
12095 			if (aux->func_info[i].type_id == btf_id) {
12096 				subprog = i;
12097 				break;
12098 			}
12099 		if (subprog == -1) {
12100 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12101 			return -EINVAL;
12102 		}
12103 		conservative = aux->func_info_aux[subprog].unreliable;
12104 		if (prog_extension) {
12105 			if (conservative) {
12106 				bpf_log(log,
12107 					"Cannot replace static functions\n");
12108 				return -EINVAL;
12109 			}
12110 			if (!prog->jit_requested) {
12111 				bpf_log(log,
12112 					"Extension programs should be JITed\n");
12113 				return -EINVAL;
12114 			}
12115 		}
12116 		if (!tgt_prog->jited) {
12117 			bpf_log(log, "Can attach to only JITed progs\n");
12118 			return -EINVAL;
12119 		}
12120 		if (tgt_prog->type == prog->type) {
12121 			/* Cannot fentry/fexit another fentry/fexit program.
12122 			 * Cannot attach program extension to another extension.
12123 			 * It's ok to attach fentry/fexit to extension program.
12124 			 */
12125 			bpf_log(log, "Cannot recursively attach\n");
12126 			return -EINVAL;
12127 		}
12128 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12129 		    prog_extension &&
12130 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12131 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12132 			/* Program extensions can extend all program types
12133 			 * except fentry/fexit. The reason is the following.
12134 			 * The fentry/fexit programs are used for performance
12135 			 * analysis, stats and can be attached to any program
12136 			 * type except themselves. When extension program is
12137 			 * replacing XDP function it is necessary to allow
12138 			 * performance analysis of all functions. Both original
12139 			 * XDP program and its program extension. Hence
12140 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12141 			 * allowed. If extending of fentry/fexit was allowed it
12142 			 * would be possible to create long call chain
12143 			 * fentry->extension->fentry->extension beyond
12144 			 * reasonable stack size. Hence extending fentry is not
12145 			 * allowed.
12146 			 */
12147 			bpf_log(log, "Cannot extend fentry/fexit\n");
12148 			return -EINVAL;
12149 		}
12150 	} else {
12151 		if (prog_extension) {
12152 			bpf_log(log, "Cannot replace kernel functions\n");
12153 			return -EINVAL;
12154 		}
12155 	}
12156 
12157 	switch (prog->expected_attach_type) {
12158 	case BPF_TRACE_RAW_TP:
12159 		if (tgt_prog) {
12160 			bpf_log(log,
12161 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12162 			return -EINVAL;
12163 		}
12164 		if (!btf_type_is_typedef(t)) {
12165 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12166 				btf_id);
12167 			return -EINVAL;
12168 		}
12169 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12170 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12171 				btf_id, tname);
12172 			return -EINVAL;
12173 		}
12174 		tname += sizeof(prefix) - 1;
12175 		t = btf_type_by_id(btf, t->type);
12176 		if (!btf_type_is_ptr(t))
12177 			/* should never happen in valid vmlinux build */
12178 			return -EINVAL;
12179 		t = btf_type_by_id(btf, t->type);
12180 		if (!btf_type_is_func_proto(t))
12181 			/* should never happen in valid vmlinux build */
12182 			return -EINVAL;
12183 
12184 		break;
12185 	case BPF_TRACE_ITER:
12186 		if (!btf_type_is_func(t)) {
12187 			bpf_log(log, "attach_btf_id %u is not a function\n",
12188 				btf_id);
12189 			return -EINVAL;
12190 		}
12191 		t = btf_type_by_id(btf, t->type);
12192 		if (!btf_type_is_func_proto(t))
12193 			return -EINVAL;
12194 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12195 		if (ret)
12196 			return ret;
12197 		break;
12198 	default:
12199 		if (!prog_extension)
12200 			return -EINVAL;
12201 		fallthrough;
12202 	case BPF_MODIFY_RETURN:
12203 	case BPF_LSM_MAC:
12204 	case BPF_TRACE_FENTRY:
12205 	case BPF_TRACE_FEXIT:
12206 		if (!btf_type_is_func(t)) {
12207 			bpf_log(log, "attach_btf_id %u is not a function\n",
12208 				btf_id);
12209 			return -EINVAL;
12210 		}
12211 		if (prog_extension &&
12212 		    btf_check_type_match(log, prog, btf, t))
12213 			return -EINVAL;
12214 		t = btf_type_by_id(btf, t->type);
12215 		if (!btf_type_is_func_proto(t))
12216 			return -EINVAL;
12217 
12218 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12219 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12220 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12221 			return -EINVAL;
12222 
12223 		if (tgt_prog && conservative)
12224 			t = NULL;
12225 
12226 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12227 		if (ret < 0)
12228 			return ret;
12229 
12230 		if (tgt_prog) {
12231 			if (subprog == 0)
12232 				addr = (long) tgt_prog->bpf_func;
12233 			else
12234 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12235 		} else {
12236 			addr = kallsyms_lookup_name(tname);
12237 			if (!addr) {
12238 				bpf_log(log,
12239 					"The address of function %s cannot be found\n",
12240 					tname);
12241 				return -ENOENT;
12242 			}
12243 		}
12244 
12245 		if (prog->aux->sleepable) {
12246 			ret = -EINVAL;
12247 			switch (prog->type) {
12248 			case BPF_PROG_TYPE_TRACING:
12249 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12250 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12251 				 */
12252 				if (!check_non_sleepable_error_inject(btf_id) &&
12253 				    within_error_injection_list(addr))
12254 					ret = 0;
12255 				break;
12256 			case BPF_PROG_TYPE_LSM:
12257 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
12258 				 * Only some of them are sleepable.
12259 				 */
12260 				if (check_sleepable_lsm_hook(btf_id))
12261 					ret = 0;
12262 				break;
12263 			default:
12264 				break;
12265 			}
12266 			if (ret) {
12267 				bpf_log(log, "%s is not sleepable\n", tname);
12268 				return ret;
12269 			}
12270 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12271 			if (tgt_prog) {
12272 				bpf_log(log, "can't modify return codes of BPF programs\n");
12273 				return -EINVAL;
12274 			}
12275 			ret = check_attach_modify_return(addr, tname);
12276 			if (ret) {
12277 				bpf_log(log, "%s() is not modifiable\n", tname);
12278 				return ret;
12279 			}
12280 		}
12281 
12282 		break;
12283 	}
12284 	tgt_info->tgt_addr = addr;
12285 	tgt_info->tgt_name = tname;
12286 	tgt_info->tgt_type = t;
12287 	return 0;
12288 }
12289 
check_attach_btf_id(struct bpf_verifier_env * env)12290 static int check_attach_btf_id(struct bpf_verifier_env *env)
12291 {
12292 	struct bpf_prog *prog = env->prog;
12293 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12294 	struct bpf_attach_target_info tgt_info = {};
12295 	u32 btf_id = prog->aux->attach_btf_id;
12296 	struct bpf_trampoline *tr;
12297 	int ret;
12298 	u64 key;
12299 
12300 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12301 	    prog->type != BPF_PROG_TYPE_LSM) {
12302 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12303 		return -EINVAL;
12304 	}
12305 
12306 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12307 		return check_struct_ops_btf_id(env);
12308 
12309 	if (prog->type != BPF_PROG_TYPE_TRACING &&
12310 	    prog->type != BPF_PROG_TYPE_LSM &&
12311 	    prog->type != BPF_PROG_TYPE_EXT)
12312 		return 0;
12313 
12314 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12315 	if (ret)
12316 		return ret;
12317 
12318 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12319 		/* to make freplace equivalent to their targets, they need to
12320 		 * inherit env->ops and expected_attach_type for the rest of the
12321 		 * verification
12322 		 */
12323 		env->ops = bpf_verifier_ops[tgt_prog->type];
12324 		prog->expected_attach_type = tgt_prog->expected_attach_type;
12325 	}
12326 
12327 	/* store info about the attachment target that will be used later */
12328 	prog->aux->attach_func_proto = tgt_info.tgt_type;
12329 	prog->aux->attach_func_name = tgt_info.tgt_name;
12330 
12331 	if (tgt_prog) {
12332 		prog->aux->saved_dst_prog_type = tgt_prog->type;
12333 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12334 	}
12335 
12336 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12337 		prog->aux->attach_btf_trace = true;
12338 		return 0;
12339 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12340 		if (!bpf_iter_prog_supported(prog))
12341 			return -EINVAL;
12342 		return 0;
12343 	}
12344 
12345 	if (prog->type == BPF_PROG_TYPE_LSM) {
12346 		ret = bpf_lsm_verify_prog(&env->log, prog);
12347 		if (ret < 0)
12348 			return ret;
12349 	}
12350 
12351 	key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12352 	tr = bpf_trampoline_get(key, &tgt_info);
12353 	if (!tr)
12354 		return -ENOMEM;
12355 
12356 	prog->aux->dst_trampoline = tr;
12357 	return 0;
12358 }
12359 
bpf_get_btf_vmlinux(void)12360 struct btf *bpf_get_btf_vmlinux(void)
12361 {
12362 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12363 		mutex_lock(&bpf_verifier_lock);
12364 		if (!btf_vmlinux)
12365 			btf_vmlinux = btf_parse_vmlinux();
12366 		mutex_unlock(&bpf_verifier_lock);
12367 	}
12368 	return btf_vmlinux;
12369 }
12370 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)12371 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12372 	      union bpf_attr __user *uattr)
12373 {
12374 	u64 start_time = ktime_get_ns();
12375 	struct bpf_verifier_env *env;
12376 	struct bpf_verifier_log *log;
12377 	int i, len, ret = -EINVAL;
12378 	bool is_priv;
12379 
12380 	/* no program is valid */
12381 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12382 		return -EINVAL;
12383 
12384 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
12385 	 * allocate/free it every time bpf_check() is called
12386 	 */
12387 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12388 	if (!env)
12389 		return -ENOMEM;
12390 	log = &env->log;
12391 
12392 	len = (*prog)->len;
12393 	env->insn_aux_data =
12394 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12395 	ret = -ENOMEM;
12396 	if (!env->insn_aux_data)
12397 		goto err_free_env;
12398 	for (i = 0; i < len; i++)
12399 		env->insn_aux_data[i].orig_idx = i;
12400 	env->prog = *prog;
12401 	env->ops = bpf_verifier_ops[env->prog->type];
12402 	is_priv = bpf_capable();
12403 
12404 	bpf_get_btf_vmlinux();
12405 
12406 	/* grab the mutex to protect few globals used by verifier */
12407 	if (!is_priv)
12408 		mutex_lock(&bpf_verifier_lock);
12409 
12410 	if (attr->log_level || attr->log_buf || attr->log_size) {
12411 		/* user requested verbose verifier output
12412 		 * and supplied buffer to store the verification trace
12413 		 */
12414 		log->level = attr->log_level;
12415 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12416 		log->len_total = attr->log_size;
12417 
12418 		/* log attributes have to be sane */
12419 		if (!bpf_verifier_log_attr_valid(log)) {
12420 			ret = -EINVAL;
12421 			goto err_unlock;
12422 		}
12423 	}
12424 
12425 	if (IS_ERR(btf_vmlinux)) {
12426 		/* Either gcc or pahole or kernel are broken. */
12427 		verbose(env, "in-kernel BTF is malformed\n");
12428 		ret = PTR_ERR(btf_vmlinux);
12429 		goto skip_full_check;
12430 	}
12431 
12432 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12433 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12434 		env->strict_alignment = true;
12435 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12436 		env->strict_alignment = false;
12437 
12438 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12439 	env->allow_uninit_stack = bpf_allow_uninit_stack();
12440 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12441 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
12442 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
12443 	env->bpf_capable = bpf_capable();
12444 
12445 	if (is_priv)
12446 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12447 
12448 	env->explored_states = kvcalloc(state_htab_size(env),
12449 				       sizeof(struct bpf_verifier_state_list *),
12450 				       GFP_USER);
12451 	ret = -ENOMEM;
12452 	if (!env->explored_states)
12453 		goto skip_full_check;
12454 
12455 	ret = check_subprogs(env);
12456 	if (ret < 0)
12457 		goto skip_full_check;
12458 
12459 	ret = check_btf_info(env, attr, uattr);
12460 	if (ret < 0)
12461 		goto skip_full_check;
12462 
12463 	ret = check_attach_btf_id(env);
12464 	if (ret)
12465 		goto skip_full_check;
12466 
12467 	ret = resolve_pseudo_ldimm64(env);
12468 	if (ret < 0)
12469 		goto skip_full_check;
12470 
12471 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
12472 		ret = bpf_prog_offload_verifier_prep(env->prog);
12473 		if (ret)
12474 			goto skip_full_check;
12475 	}
12476 
12477 	ret = check_cfg(env);
12478 	if (ret < 0)
12479 		goto skip_full_check;
12480 
12481 	ret = do_check_subprogs(env);
12482 	ret = ret ?: do_check_main(env);
12483 
12484 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12485 		ret = bpf_prog_offload_finalize(env);
12486 
12487 skip_full_check:
12488 	kvfree(env->explored_states);
12489 
12490 	if (ret == 0)
12491 		ret = check_max_stack_depth(env);
12492 
12493 	/* instruction rewrites happen after this point */
12494 	if (is_priv) {
12495 		if (ret == 0)
12496 			opt_hard_wire_dead_code_branches(env);
12497 		if (ret == 0)
12498 			ret = opt_remove_dead_code(env);
12499 		if (ret == 0)
12500 			ret = opt_remove_nops(env);
12501 	} else {
12502 		if (ret == 0)
12503 			sanitize_dead_code(env);
12504 	}
12505 
12506 	if (ret == 0)
12507 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12508 		ret = convert_ctx_accesses(env);
12509 
12510 	if (ret == 0)
12511 		ret = fixup_bpf_calls(env);
12512 
12513 	/* do 32-bit optimization after insn patching has done so those patched
12514 	 * insns could be handled correctly.
12515 	 */
12516 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12517 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12518 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12519 								     : false;
12520 	}
12521 
12522 	if (ret == 0)
12523 		ret = fixup_call_args(env);
12524 
12525 	env->verification_time = ktime_get_ns() - start_time;
12526 	print_verification_stats(env);
12527 
12528 	if (log->level && bpf_verifier_log_full(log))
12529 		ret = -ENOSPC;
12530 	if (log->level && !log->ubuf) {
12531 		ret = -EFAULT;
12532 		goto err_release_maps;
12533 	}
12534 
12535 	if (ret == 0 && env->used_map_cnt) {
12536 		/* if program passed verifier, update used_maps in bpf_prog_info */
12537 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12538 							  sizeof(env->used_maps[0]),
12539 							  GFP_KERNEL);
12540 
12541 		if (!env->prog->aux->used_maps) {
12542 			ret = -ENOMEM;
12543 			goto err_release_maps;
12544 		}
12545 
12546 		memcpy(env->prog->aux->used_maps, env->used_maps,
12547 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12548 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12549 
12550 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12551 		 * bpf_ld_imm64 instructions
12552 		 */
12553 		convert_pseudo_ld_imm64(env);
12554 	}
12555 
12556 	if (ret == 0)
12557 		adjust_btf_func(env);
12558 
12559 err_release_maps:
12560 	if (!env->prog->aux->used_maps)
12561 		/* if we didn't copy map pointers into bpf_prog_info, release
12562 		 * them now. Otherwise free_used_maps() will release them.
12563 		 */
12564 		release_maps(env);
12565 
12566 	/* extension progs temporarily inherit the attach_type of their targets
12567 	   for verification purposes, so set it back to zero before returning
12568 	 */
12569 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12570 		env->prog->expected_attach_type = 0;
12571 
12572 	*prog = env->prog;
12573 err_unlock:
12574 	if (!is_priv)
12575 		mutex_unlock(&bpf_verifier_lock);
12576 	vfree(env->insn_aux_data);
12577 err_free_env:
12578 	kfree(env);
12579 	return ret;
12580 }
12581