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