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