• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25 
26 #include "disasm.h"
27 
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 	[_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38 
39 /* bpf_check() is a static code analyzer that walks eBPF program
40  * instruction by instruction and updates register/stack state.
41  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42  *
43  * The first pass is depth-first-search to check that the program is a DAG.
44  * It rejects the following programs:
45  * - larger than BPF_MAXINSNS insns
46  * - if loop is present (detected via back-edge)
47  * - unreachable insns exist (shouldn't be a forest. program = one function)
48  * - out of bounds or malformed jumps
49  * The second pass is all possible path descent from the 1st insn.
50  * Since it's analyzing all pathes through the program, the length of the
51  * analysis is limited to 64k insn, which may be hit even if total number of
52  * insn is less then 4K, but there are too many branches that change stack/regs.
53  * Number of 'branches to be analyzed' is limited to 1k
54  *
55  * On entry to each instruction, each register has a type, and the instruction
56  * changes the types of the registers depending on instruction semantics.
57  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58  * copied to R1.
59  *
60  * All registers are 64-bit.
61  * R0 - return register
62  * R1-R5 argument passing registers
63  * R6-R9 callee saved registers
64  * R10 - frame pointer read-only
65  *
66  * At the start of BPF program the register R1 contains a pointer to bpf_context
67  * and has type PTR_TO_CTX.
68  *
69  * Verifier tracks arithmetic operations on pointers in case:
70  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72  * 1st insn copies R10 (which has FRAME_PTR) type into R1
73  * and 2nd arithmetic instruction is pattern matched to recognize
74  * that it wants to construct a pointer to some element within stack.
75  * So after 2nd insn, the register R1 has type PTR_TO_STACK
76  * (and -20 constant is saved for further stack bounds checking).
77  * Meaning that this reg is a pointer to stack plus known immediate constant.
78  *
79  * Most of the time the registers have SCALAR_VALUE type, which
80  * means the register has some value, but it's not a valid pointer.
81  * (like pointer plus pointer becomes SCALAR_VALUE type)
82  *
83  * When verifier sees load or store instructions the type of base register
84  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85  * four pointer types recognized by check_mem_access() function.
86  *
87  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88  * and the range of [ptr, ptr + map's value_size) is accessible.
89  *
90  * registers used to pass values to function calls are checked against
91  * function argument constraints.
92  *
93  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94  * It means that the register type passed to this function must be
95  * PTR_TO_STACK and it will be used inside the function as
96  * 'pointer to map element key'
97  *
98  * For example the argument constraints for bpf_map_lookup_elem():
99  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100  *   .arg1_type = ARG_CONST_MAP_PTR,
101  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
102  *
103  * ret_type says that this function returns 'pointer to map elem value or null'
104  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105  * 2nd argument should be a pointer to stack, which will be used inside
106  * the helper function as a pointer to map element key.
107  *
108  * On the kernel side the helper function looks like:
109  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110  * {
111  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112  *    void *key = (void *) (unsigned long) r2;
113  *    void *value;
114  *
115  *    here kernel can access 'key' and 'map' pointers safely, knowing that
116  *    [key, key + map->key_size) bytes are valid and were initialized on
117  *    the stack of eBPF program.
118  * }
119  *
120  * Corresponding eBPF program may look like:
121  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
122  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
124  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125  * here verifier looks at prototype of map_lookup_elem() and sees:
126  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128  *
129  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131  * and were initialized prior to this call.
132  * If it's ok, then verifier allows this BPF_CALL insn and looks at
133  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135  * returns ether pointer to map value or NULL.
136  *
137  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138  * insn, the register holding that pointer in the true branch changes state to
139  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140  * branch. See check_cond_jmp_op().
141  *
142  * After the call R0 is set to return type of the function and registers R1-R5
143  * are set to NOT_INIT to indicate that they are no longer readable.
144  *
145  * The following reference types represent a potential reference to a kernel
146  * resource which, after first being allocated, must be checked and freed by
147  * the BPF program:
148  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149  *
150  * When the verifier sees a helper call return a reference type, it allocates a
151  * pointer id for the reference and stores it in the current function state.
152  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154  * passes through a NULL-check conditional. For the branch wherein the state is
155  * changed to CONST_IMM, the verifier releases the reference.
156  *
157  * For each helper function that allocates a reference, such as
158  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159  * bpf_sk_release(). When a reference type passes into the release function,
160  * the verifier also releases the reference. If any unchecked or unreleased
161  * reference remains at the end of the program, the verifier rejects it.
162  */
163 
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 	/* verifer state is 'st'
167 	 * before processing instruction 'insn_idx'
168 	 * and after processing instruction 'prev_insn_idx'
169 	 */
170 	struct bpf_verifier_state st;
171 	int insn_idx;
172 	int prev_insn_idx;
173 	struct bpf_verifier_stack_elem *next;
174 	/* length of verifier log at the time this state was pushed on stack */
175 	u32 log_pos;
176 };
177 
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
179 #define BPF_COMPLEXITY_LIMIT_STATES	64
180 
181 #define BPF_MAP_KEY_POISON	(1ULL << 63)
182 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
183 
184 #define BPF_MAP_PTR_UNPRIV	1UL
185 #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
186 					  POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188 
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191 	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193 
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196 	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198 
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 			      const struct bpf_map *map, bool unpriv)
201 {
202 	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 	unpriv |= bpf_map_ptr_unpriv(aux);
204 	aux->map_ptr_state = (unsigned long)map |
205 			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207 
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 	return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212 
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217 
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222 
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225 	bool poisoned = bpf_map_key_poisoned(aux);
226 
227 	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230 
231 struct bpf_call_arg_meta {
232 	struct bpf_map *map_ptr;
233 	bool raw_mode;
234 	bool pkt_access;
235 	int regno;
236 	int access_size;
237 	int mem_size;
238 	u64 msize_max_value;
239 	int ref_obj_id;
240 	int func_id;
241 	u32 btf_id;
242 	u32 ret_btf_id;
243 };
244 
245 struct btf *btf_vmlinux;
246 
247 static DEFINE_MUTEX(bpf_verifier_lock);
248 
249 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)250 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
251 {
252 	const struct bpf_line_info *linfo;
253 	const struct bpf_prog *prog;
254 	u32 i, nr_linfo;
255 
256 	prog = env->prog;
257 	nr_linfo = prog->aux->nr_linfo;
258 
259 	if (!nr_linfo || insn_off >= prog->len)
260 		return NULL;
261 
262 	linfo = prog->aux->linfo;
263 	for (i = 1; i < nr_linfo; i++)
264 		if (insn_off < linfo[i].insn_off)
265 			break;
266 
267 	return &linfo[i - 1];
268 }
269 
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)270 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
271 		       va_list args)
272 {
273 	unsigned int n;
274 
275 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
276 
277 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
278 		  "verifier log line truncated - local buffer too short\n");
279 
280 	n = min(log->len_total - log->len_used - 1, n);
281 	log->kbuf[n] = '\0';
282 
283 	if (log->level == BPF_LOG_KERNEL) {
284 		pr_err("BPF:%s\n", log->kbuf);
285 		return;
286 	}
287 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
288 		log->len_used += n;
289 	else
290 		log->ubuf = NULL;
291 }
292 
bpf_vlog_reset(struct bpf_verifier_log * log,u32 new_pos)293 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
294 {
295 	char zero = 0;
296 
297 	if (!bpf_verifier_log_needed(log))
298 		return;
299 
300 	log->len_used = new_pos;
301 	if (put_user(zero, log->ubuf + new_pos))
302 		log->ubuf = NULL;
303 }
304 
305 /* log_level controls verbosity level of eBPF verifier.
306  * bpf_verifier_log_write() is used to dump the verification trace to the log,
307  * so the user can figure out what's wrong with the program
308  */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)309 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
310 					   const char *fmt, ...)
311 {
312 	va_list args;
313 
314 	if (!bpf_verifier_log_needed(&env->log))
315 		return;
316 
317 	va_start(args, fmt);
318 	bpf_verifier_vlog(&env->log, fmt, args);
319 	va_end(args);
320 }
321 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
322 
verbose(void * private_data,const char * fmt,...)323 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
324 {
325 	struct bpf_verifier_env *env = private_data;
326 	va_list args;
327 
328 	if (!bpf_verifier_log_needed(&env->log))
329 		return;
330 
331 	va_start(args, fmt);
332 	bpf_verifier_vlog(&env->log, fmt, args);
333 	va_end(args);
334 }
335 
bpf_log(struct bpf_verifier_log * log,const char * fmt,...)336 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
337 			    const char *fmt, ...)
338 {
339 	va_list args;
340 
341 	if (!bpf_verifier_log_needed(log))
342 		return;
343 
344 	va_start(args, fmt);
345 	bpf_verifier_vlog(log, fmt, args);
346 	va_end(args);
347 }
348 
ltrim(const char * s)349 static const char *ltrim(const char *s)
350 {
351 	while (isspace(*s))
352 		s++;
353 
354 	return s;
355 }
356 
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)357 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
358 					 u32 insn_off,
359 					 const char *prefix_fmt, ...)
360 {
361 	const struct bpf_line_info *linfo;
362 
363 	if (!bpf_verifier_log_needed(&env->log))
364 		return;
365 
366 	linfo = find_linfo(env, insn_off);
367 	if (!linfo || linfo == env->prev_linfo)
368 		return;
369 
370 	if (prefix_fmt) {
371 		va_list args;
372 
373 		va_start(args, prefix_fmt);
374 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
375 		va_end(args);
376 	}
377 
378 	verbose(env, "%s\n",
379 		ltrim(btf_name_by_offset(env->prog->aux->btf,
380 					 linfo->line_off)));
381 
382 	env->prev_linfo = linfo;
383 }
384 
type_is_pkt_pointer(enum bpf_reg_type type)385 static bool type_is_pkt_pointer(enum bpf_reg_type type)
386 {
387 	return type == PTR_TO_PACKET ||
388 	       type == PTR_TO_PACKET_META;
389 }
390 
type_is_sk_pointer(enum bpf_reg_type type)391 static bool type_is_sk_pointer(enum bpf_reg_type type)
392 {
393 	return type == PTR_TO_SOCKET ||
394 		type == PTR_TO_SOCK_COMMON ||
395 		type == PTR_TO_TCP_SOCK ||
396 		type == PTR_TO_XDP_SOCK;
397 }
398 
reg_type_not_null(enum bpf_reg_type type)399 static bool reg_type_not_null(enum bpf_reg_type type)
400 {
401 	return type == PTR_TO_SOCKET ||
402 		type == PTR_TO_TCP_SOCK ||
403 		type == PTR_TO_MAP_VALUE ||
404 		type == PTR_TO_SOCK_COMMON;
405 }
406 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)407 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
408 {
409 	return reg->type == PTR_TO_MAP_VALUE &&
410 		map_value_has_spin_lock(reg->map_ptr);
411 }
412 
reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)413 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
414 {
415 	return base_type(type) == PTR_TO_SOCKET ||
416 	       base_type(type) == PTR_TO_TCP_SOCK ||
417 	       base_type(type) == PTR_TO_MEM;
418 }
419 
type_is_rdonly_mem(u32 type)420 static bool type_is_rdonly_mem(u32 type)
421 {
422 	return type & MEM_RDONLY;
423 }
424 
arg_type_may_be_refcounted(enum bpf_arg_type type)425 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
426 {
427 	return type == ARG_PTR_TO_SOCK_COMMON;
428 }
429 
type_may_be_null(u32 type)430 static bool type_may_be_null(u32 type)
431 {
432 	return type & PTR_MAYBE_NULL;
433 }
434 
435 /* Determine whether the function releases some resources allocated by another
436  * function call. The first reference type argument will be assumed to be
437  * released by release_reference().
438  */
is_release_function(enum bpf_func_id func_id)439 static bool is_release_function(enum bpf_func_id func_id)
440 {
441 	return func_id == BPF_FUNC_sk_release ||
442 	       func_id == BPF_FUNC_ringbuf_submit ||
443 	       func_id == BPF_FUNC_ringbuf_discard;
444 }
445 
may_be_acquire_function(enum bpf_func_id func_id)446 static bool may_be_acquire_function(enum bpf_func_id func_id)
447 {
448 	return func_id == BPF_FUNC_sk_lookup_tcp ||
449 		func_id == BPF_FUNC_sk_lookup_udp ||
450 		func_id == BPF_FUNC_skc_lookup_tcp ||
451 		func_id == BPF_FUNC_map_lookup_elem ||
452 	        func_id == BPF_FUNC_ringbuf_reserve;
453 }
454 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)455 static bool is_acquire_function(enum bpf_func_id func_id,
456 				const struct bpf_map *map)
457 {
458 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
459 
460 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
461 	    func_id == BPF_FUNC_sk_lookup_udp ||
462 	    func_id == BPF_FUNC_skc_lookup_tcp ||
463 	    func_id == BPF_FUNC_ringbuf_reserve)
464 		return true;
465 
466 	if (func_id == BPF_FUNC_map_lookup_elem &&
467 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
468 	     map_type == BPF_MAP_TYPE_SOCKHASH))
469 		return true;
470 
471 	return false;
472 }
473 
is_ptr_cast_function(enum bpf_func_id func_id)474 static bool is_ptr_cast_function(enum bpf_func_id func_id)
475 {
476 	return func_id == BPF_FUNC_tcp_sock ||
477 		func_id == BPF_FUNC_sk_fullsock ||
478 		func_id == BPF_FUNC_skc_to_tcp_sock ||
479 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
480 		func_id == BPF_FUNC_skc_to_udp6_sock ||
481 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
482 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
483 }
484 
485 /* string representation of 'enum bpf_reg_type'
486  *
487  * Note that reg_type_str() can not appear more than once in a single verbose()
488  * statement.
489  */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)490 static const char *reg_type_str(struct bpf_verifier_env *env,
491 		enum bpf_reg_type type)
492 {
493 	char postfix[16] = {0}, prefix[16] = {0};
494 	static const char * const str[] = {
495 		[NOT_INIT]		= "?",
496 		[SCALAR_VALUE]		= "inv",
497 		[PTR_TO_CTX]		= "ctx",
498 		[CONST_PTR_TO_MAP]	= "map_ptr",
499 		[PTR_TO_MAP_VALUE]	= "map_value",
500 		[PTR_TO_STACK]		= "fp",
501 		[PTR_TO_PACKET]		= "pkt",
502 		[PTR_TO_PACKET_META]	= "pkt_meta",
503 		[PTR_TO_PACKET_END]	= "pkt_end",
504 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
505 		[PTR_TO_SOCKET]		= "sock",
506 		[PTR_TO_SOCK_COMMON]	= "sock_common",
507 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
508 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
509 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
510 		[PTR_TO_BTF_ID]		= "ptr_",
511 		[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
512 		[PTR_TO_MEM]		= "mem",
513 		[PTR_TO_BUF]		= "buf",
514 	};
515 
516 	if (type & PTR_MAYBE_NULL) {
517 		if (base_type(type) == PTR_TO_BTF_ID ||
518 		    base_type(type) == PTR_TO_PERCPU_BTF_ID)
519 			strncpy(postfix, "or_null_", 16);
520 		else
521 			strncpy(postfix, "_or_null", 16);
522 	}
523 
524 	if (type & MEM_RDONLY)
525 		strncpy(prefix, "rdonly_", 16);
526 	if (type & MEM_ALLOC)
527 		strncpy(prefix, "alloc_", 16);
528 
529 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
530 		 prefix, str[base_type(type)], postfix);
531 	return env->type_str_buf;
532 }
533 
534 static char slot_type_char[] = {
535 	[STACK_INVALID]	= '?',
536 	[STACK_SPILL]	= 'r',
537 	[STACK_MISC]	= 'm',
538 	[STACK_ZERO]	= '0',
539 };
540 
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)541 static void print_liveness(struct bpf_verifier_env *env,
542 			   enum bpf_reg_liveness live)
543 {
544 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
545 	    verbose(env, "_");
546 	if (live & REG_LIVE_READ)
547 		verbose(env, "r");
548 	if (live & REG_LIVE_WRITTEN)
549 		verbose(env, "w");
550 	if (live & REG_LIVE_DONE)
551 		verbose(env, "D");
552 }
553 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)554 static struct bpf_func_state *func(struct bpf_verifier_env *env,
555 				   const struct bpf_reg_state *reg)
556 {
557 	struct bpf_verifier_state *cur = env->cur_state;
558 
559 	return cur->frame[reg->frameno];
560 }
561 
kernel_type_name(u32 id)562 const char *kernel_type_name(u32 id)
563 {
564 	return btf_name_by_offset(btf_vmlinux,
565 				  btf_type_by_id(btf_vmlinux, id)->name_off);
566 }
567 
568 /* The reg state of a pointer or a bounded scalar was saved when
569  * it was spilled to the stack.
570  */
is_spilled_reg(const struct bpf_stack_state * stack)571 static bool is_spilled_reg(const struct bpf_stack_state *stack)
572 {
573 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
574 }
575 
scrub_spilled_slot(u8 * stype)576 static void scrub_spilled_slot(u8 *stype)
577 {
578 	if (*stype != STACK_INVALID)
579 		*stype = STACK_MISC;
580 }
581 
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)582 static void print_verifier_state(struct bpf_verifier_env *env,
583 				 const struct bpf_func_state *state)
584 {
585 	const struct bpf_reg_state *reg;
586 	enum bpf_reg_type t;
587 	int i;
588 
589 	if (state->frameno)
590 		verbose(env, " frame%d:", state->frameno);
591 	for (i = 0; i < MAX_BPF_REG; i++) {
592 		reg = &state->regs[i];
593 		t = reg->type;
594 		if (t == NOT_INIT)
595 			continue;
596 		verbose(env, " R%d", i);
597 		print_liveness(env, reg->live);
598 		verbose(env, "=%s", reg_type_str(env, t));
599 		if (t == SCALAR_VALUE && reg->precise)
600 			verbose(env, "P");
601 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
602 		    tnum_is_const(reg->var_off)) {
603 			/* reg->off should be 0 for SCALAR_VALUE */
604 			verbose(env, "%lld", reg->var_off.value + reg->off);
605 		} else {
606 			if (base_type(t) == PTR_TO_BTF_ID ||
607 			    base_type(t) == PTR_TO_PERCPU_BTF_ID)
608 				verbose(env, "%s", kernel_type_name(reg->btf_id));
609 			verbose(env, "(id=%d", reg->id);
610 			if (reg_type_may_be_refcounted_or_null(t))
611 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
612 			if (t != SCALAR_VALUE)
613 				verbose(env, ",off=%d", reg->off);
614 			if (type_is_pkt_pointer(t))
615 				verbose(env, ",r=%d", reg->range);
616 			else if (base_type(t) == CONST_PTR_TO_MAP ||
617 				 base_type(t) == PTR_TO_MAP_VALUE)
618 				verbose(env, ",ks=%d,vs=%d",
619 					reg->map_ptr->key_size,
620 					reg->map_ptr->value_size);
621 			if (tnum_is_const(reg->var_off)) {
622 				/* Typically an immediate SCALAR_VALUE, but
623 				 * could be a pointer whose offset is too big
624 				 * for reg->off
625 				 */
626 				verbose(env, ",imm=%llx", reg->var_off.value);
627 			} else {
628 				if (reg->smin_value != reg->umin_value &&
629 				    reg->smin_value != S64_MIN)
630 					verbose(env, ",smin_value=%lld",
631 						(long long)reg->smin_value);
632 				if (reg->smax_value != reg->umax_value &&
633 				    reg->smax_value != S64_MAX)
634 					verbose(env, ",smax_value=%lld",
635 						(long long)reg->smax_value);
636 				if (reg->umin_value != 0)
637 					verbose(env, ",umin_value=%llu",
638 						(unsigned long long)reg->umin_value);
639 				if (reg->umax_value != U64_MAX)
640 					verbose(env, ",umax_value=%llu",
641 						(unsigned long long)reg->umax_value);
642 				if (!tnum_is_unknown(reg->var_off)) {
643 					char tn_buf[48];
644 
645 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
646 					verbose(env, ",var_off=%s", tn_buf);
647 				}
648 				if (reg->s32_min_value != reg->smin_value &&
649 				    reg->s32_min_value != S32_MIN)
650 					verbose(env, ",s32_min_value=%d",
651 						(int)(reg->s32_min_value));
652 				if (reg->s32_max_value != reg->smax_value &&
653 				    reg->s32_max_value != S32_MAX)
654 					verbose(env, ",s32_max_value=%d",
655 						(int)(reg->s32_max_value));
656 				if (reg->u32_min_value != reg->umin_value &&
657 				    reg->u32_min_value != U32_MIN)
658 					verbose(env, ",u32_min_value=%d",
659 						(int)(reg->u32_min_value));
660 				if (reg->u32_max_value != reg->umax_value &&
661 				    reg->u32_max_value != U32_MAX)
662 					verbose(env, ",u32_max_value=%d",
663 						(int)(reg->u32_max_value));
664 			}
665 			verbose(env, ")");
666 		}
667 	}
668 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
669 		char types_buf[BPF_REG_SIZE + 1];
670 		bool valid = false;
671 		int j;
672 
673 		for (j = 0; j < BPF_REG_SIZE; j++) {
674 			if (state->stack[i].slot_type[j] != STACK_INVALID)
675 				valid = true;
676 			types_buf[j] = slot_type_char[
677 					state->stack[i].slot_type[j]];
678 		}
679 		types_buf[BPF_REG_SIZE] = 0;
680 		if (!valid)
681 			continue;
682 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
683 		print_liveness(env, state->stack[i].spilled_ptr.live);
684 		if (is_spilled_reg(&state->stack[i])) {
685 			reg = &state->stack[i].spilled_ptr;
686 			t = reg->type;
687 			verbose(env, "=%s", reg_type_str(env, t));
688 			if (t == SCALAR_VALUE && reg->precise)
689 				verbose(env, "P");
690 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
691 				verbose(env, "%lld", reg->var_off.value + reg->off);
692 		} else {
693 			verbose(env, "=%s", types_buf);
694 		}
695 	}
696 	if (state->acquired_refs && state->refs[0].id) {
697 		verbose(env, " refs=%d", state->refs[0].id);
698 		for (i = 1; i < state->acquired_refs; i++)
699 			if (state->refs[i].id)
700 				verbose(env, ",%d", state->refs[i].id);
701 	}
702 	verbose(env, "\n");
703 }
704 
705 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)				\
706 static int copy_##NAME##_state(struct bpf_func_state *dst,		\
707 			       const struct bpf_func_state *src)	\
708 {									\
709 	if (!src->FIELD)						\
710 		return 0;						\
711 	if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {			\
712 		/* internal bug, make state invalid to reject the program */ \
713 		memset(dst, 0, sizeof(*dst));				\
714 		return -EFAULT;						\
715 	}								\
716 	memcpy(dst->FIELD, src->FIELD,					\
717 	       sizeof(*src->FIELD) * (src->COUNT / SIZE));		\
718 	return 0;							\
719 }
720 /* copy_reference_state() */
721 COPY_STATE_FN(reference, acquired_refs, refs, 1)
722 /* copy_stack_state() */
COPY_STATE_FN(stack,allocated_stack,stack,BPF_REG_SIZE)723 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
724 #undef COPY_STATE_FN
725 
726 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)			\
727 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
728 				  bool copy_old)			\
729 {									\
730 	u32 old_size = state->COUNT;					\
731 	struct bpf_##NAME##_state *new_##FIELD;				\
732 	int slot = size / SIZE;						\
733 									\
734 	if (size <= old_size || !size) {				\
735 		if (copy_old)						\
736 			return 0;					\
737 		state->COUNT = slot * SIZE;				\
738 		if (!size && old_size) {				\
739 			kfree(state->FIELD);				\
740 			state->FIELD = NULL;				\
741 		}							\
742 		return 0;						\
743 	}								\
744 	new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
745 				    GFP_KERNEL);			\
746 	if (!new_##FIELD)						\
747 		return -ENOMEM;						\
748 	if (copy_old) {							\
749 		if (state->FIELD)					\
750 			memcpy(new_##FIELD, state->FIELD,		\
751 			       sizeof(*new_##FIELD) * (old_size / SIZE)); \
752 		memset(new_##FIELD + old_size / SIZE, 0,		\
753 		       sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
754 	}								\
755 	state->COUNT = slot * SIZE;					\
756 	kfree(state->FIELD);						\
757 	state->FIELD = new_##FIELD;					\
758 	return 0;							\
759 }
760 /* realloc_reference_state() */
761 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
762 /* realloc_stack_state() */
763 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
764 #undef REALLOC_STATE_FN
765 
766 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
767  * make it consume minimal amount of memory. check_stack_write() access from
768  * the program calls into realloc_func_state() to grow the stack size.
769  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
770  * which realloc_stack_state() copies over. It points to previous
771  * bpf_verifier_state which is never reallocated.
772  */
773 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
774 			      int refs_size, bool copy_old)
775 {
776 	int err = realloc_reference_state(state, refs_size, copy_old);
777 	if (err)
778 		return err;
779 	return realloc_stack_state(state, stack_size, copy_old);
780 }
781 
782 /* Acquire a pointer id from the env and update the state->refs to include
783  * this new pointer reference.
784  * On success, returns a valid pointer id to associate with the register
785  * On failure, returns a negative errno.
786  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)787 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
788 {
789 	struct bpf_func_state *state = cur_func(env);
790 	int new_ofs = state->acquired_refs;
791 	int id, err;
792 
793 	err = realloc_reference_state(state, state->acquired_refs + 1, true);
794 	if (err)
795 		return err;
796 	id = ++env->id_gen;
797 	state->refs[new_ofs].id = id;
798 	state->refs[new_ofs].insn_idx = insn_idx;
799 
800 	return id;
801 }
802 
803 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)804 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
805 {
806 	int i, last_idx;
807 
808 	last_idx = state->acquired_refs - 1;
809 	for (i = 0; i < state->acquired_refs; i++) {
810 		if (state->refs[i].id == ptr_id) {
811 			if (last_idx && i != last_idx)
812 				memcpy(&state->refs[i], &state->refs[last_idx],
813 				       sizeof(*state->refs));
814 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
815 			state->acquired_refs--;
816 			return 0;
817 		}
818 	}
819 	return -EINVAL;
820 }
821 
transfer_reference_state(struct bpf_func_state * dst,struct bpf_func_state * src)822 static int transfer_reference_state(struct bpf_func_state *dst,
823 				    struct bpf_func_state *src)
824 {
825 	int err = realloc_reference_state(dst, src->acquired_refs, false);
826 	if (err)
827 		return err;
828 	err = copy_reference_state(dst, src);
829 	if (err)
830 		return err;
831 	return 0;
832 }
833 
free_func_state(struct bpf_func_state * state)834 static void free_func_state(struct bpf_func_state *state)
835 {
836 	if (!state)
837 		return;
838 	kfree(state->refs);
839 	kfree(state->stack);
840 	kfree(state);
841 }
842 
clear_jmp_history(struct bpf_verifier_state * state)843 static void clear_jmp_history(struct bpf_verifier_state *state)
844 {
845 	kfree(state->jmp_history);
846 	state->jmp_history = NULL;
847 	state->jmp_history_cnt = 0;
848 }
849 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)850 static void free_verifier_state(struct bpf_verifier_state *state,
851 				bool free_self)
852 {
853 	int i;
854 
855 	for (i = 0; i <= state->curframe; i++) {
856 		free_func_state(state->frame[i]);
857 		state->frame[i] = NULL;
858 	}
859 	clear_jmp_history(state);
860 	if (free_self)
861 		kfree(state);
862 }
863 
864 /* copy verifier state from src to dst growing dst stack space
865  * when necessary to accommodate larger src stack
866  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)867 static int copy_func_state(struct bpf_func_state *dst,
868 			   const struct bpf_func_state *src)
869 {
870 	int err;
871 
872 	err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
873 				 false);
874 	if (err)
875 		return err;
876 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
877 	err = copy_reference_state(dst, src);
878 	if (err)
879 		return err;
880 	return copy_stack_state(dst, src);
881 }
882 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)883 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
884 			       const struct bpf_verifier_state *src)
885 {
886 	struct bpf_func_state *dst;
887 	u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
888 	int i, err;
889 
890 	if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
891 		kfree(dst_state->jmp_history);
892 		dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
893 		if (!dst_state->jmp_history)
894 			return -ENOMEM;
895 	}
896 	memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
897 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
898 
899 	/* if dst has more stack frames then src frame, free them */
900 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
901 		free_func_state(dst_state->frame[i]);
902 		dst_state->frame[i] = NULL;
903 	}
904 	dst_state->speculative = src->speculative;
905 	dst_state->curframe = src->curframe;
906 	dst_state->active_spin_lock = src->active_spin_lock;
907 	dst_state->branches = src->branches;
908 	dst_state->parent = src->parent;
909 	dst_state->first_insn_idx = src->first_insn_idx;
910 	dst_state->last_insn_idx = src->last_insn_idx;
911 	for (i = 0; i <= src->curframe; i++) {
912 		dst = dst_state->frame[i];
913 		if (!dst) {
914 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
915 			if (!dst)
916 				return -ENOMEM;
917 			dst_state->frame[i] = dst;
918 		}
919 		err = copy_func_state(dst, src->frame[i]);
920 		if (err)
921 			return err;
922 	}
923 	return 0;
924 }
925 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)926 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
927 {
928 	while (st) {
929 		u32 br = --st->branches;
930 
931 		/* WARN_ON(br > 1) technically makes sense here,
932 		 * but see comment in push_stack(), hence:
933 		 */
934 		WARN_ONCE((int)br < 0,
935 			  "BUG update_branch_counts:branches_to_explore=%d\n",
936 			  br);
937 		if (br)
938 			break;
939 		st = st->parent;
940 	}
941 }
942 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)943 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
944 		     int *insn_idx, bool pop_log)
945 {
946 	struct bpf_verifier_state *cur = env->cur_state;
947 	struct bpf_verifier_stack_elem *elem, *head = env->head;
948 	int err;
949 
950 	if (env->head == NULL)
951 		return -ENOENT;
952 
953 	if (cur) {
954 		err = copy_verifier_state(cur, &head->st);
955 		if (err)
956 			return err;
957 	}
958 	if (pop_log)
959 		bpf_vlog_reset(&env->log, head->log_pos);
960 	if (insn_idx)
961 		*insn_idx = head->insn_idx;
962 	if (prev_insn_idx)
963 		*prev_insn_idx = head->prev_insn_idx;
964 	elem = head->next;
965 	free_verifier_state(&head->st, false);
966 	kfree(head);
967 	env->head = elem;
968 	env->stack_size--;
969 	return 0;
970 }
971 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)972 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
973 					     int insn_idx, int prev_insn_idx,
974 					     bool speculative)
975 {
976 	struct bpf_verifier_state *cur = env->cur_state;
977 	struct bpf_verifier_stack_elem *elem;
978 	int err;
979 
980 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
981 	if (!elem)
982 		goto err;
983 
984 	elem->insn_idx = insn_idx;
985 	elem->prev_insn_idx = prev_insn_idx;
986 	elem->next = env->head;
987 	elem->log_pos = env->log.len_used;
988 	env->head = elem;
989 	env->stack_size++;
990 	err = copy_verifier_state(&elem->st, cur);
991 	if (err)
992 		goto err;
993 	elem->st.speculative |= speculative;
994 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
995 		verbose(env, "The sequence of %d jumps is too complex.\n",
996 			env->stack_size);
997 		goto err;
998 	}
999 	if (elem->st.parent) {
1000 		++elem->st.parent->branches;
1001 		/* WARN_ON(branches > 2) technically makes sense here,
1002 		 * but
1003 		 * 1. speculative states will bump 'branches' for non-branch
1004 		 * instructions
1005 		 * 2. is_state_visited() heuristics may decide not to create
1006 		 * a new state for a sequence of branches and all such current
1007 		 * and cloned states will be pointing to a single parent state
1008 		 * which might have large 'branches' count.
1009 		 */
1010 	}
1011 	return &elem->st;
1012 err:
1013 	free_verifier_state(env->cur_state, true);
1014 	env->cur_state = NULL;
1015 	/* pop all elements and return */
1016 	while (!pop_stack(env, NULL, NULL, false));
1017 	return NULL;
1018 }
1019 
1020 #define CALLER_SAVED_REGS 6
1021 static const int caller_saved[CALLER_SAVED_REGS] = {
1022 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1023 };
1024 
1025 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1026 				struct bpf_reg_state *reg);
1027 
1028 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1029 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1030 {
1031 	reg->var_off = tnum_const(imm);
1032 	reg->smin_value = (s64)imm;
1033 	reg->smax_value = (s64)imm;
1034 	reg->umin_value = imm;
1035 	reg->umax_value = imm;
1036 
1037 	reg->s32_min_value = (s32)imm;
1038 	reg->s32_max_value = (s32)imm;
1039 	reg->u32_min_value = (u32)imm;
1040 	reg->u32_max_value = (u32)imm;
1041 }
1042 
1043 /* Mark the unknown part of a register (variable offset or scalar value) as
1044  * known to have the value @imm.
1045  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1046 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1047 {
1048 	/* Clear id, off, and union(map_ptr, range) */
1049 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1050 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1051 	___mark_reg_known(reg, imm);
1052 }
1053 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1054 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1055 {
1056 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1057 	reg->s32_min_value = (s32)imm;
1058 	reg->s32_max_value = (s32)imm;
1059 	reg->u32_min_value = (u32)imm;
1060 	reg->u32_max_value = (u32)imm;
1061 }
1062 
1063 /* Mark the 'variable offset' part of a register as zero.  This should be
1064  * used only on registers holding a pointer type.
1065  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1066 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1067 {
1068 	__mark_reg_known(reg, 0);
1069 }
1070 
__mark_reg_const_zero(struct bpf_reg_state * reg)1071 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1072 {
1073 	__mark_reg_known(reg, 0);
1074 	reg->type = SCALAR_VALUE;
1075 }
1076 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1077 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1078 				struct bpf_reg_state *regs, u32 regno)
1079 {
1080 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1081 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1082 		/* Something bad happened, let's kill all regs */
1083 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1084 			__mark_reg_not_init(env, regs + regno);
1085 		return;
1086 	}
1087 	__mark_reg_known_zero(regs + regno);
1088 }
1089 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1090 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1091 {
1092 	return type_is_pkt_pointer(reg->type);
1093 }
1094 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1095 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1096 {
1097 	return reg_is_pkt_pointer(reg) ||
1098 	       reg->type == PTR_TO_PACKET_END;
1099 }
1100 
1101 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
reg_is_init_pkt_pointer(const struct bpf_reg_state * reg,enum bpf_reg_type which)1102 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1103 				    enum bpf_reg_type which)
1104 {
1105 	/* The register can already have a range from prior markings.
1106 	 * This is fine as long as it hasn't been advanced from its
1107 	 * origin.
1108 	 */
1109 	return reg->type == which &&
1110 	       reg->id == 0 &&
1111 	       reg->off == 0 &&
1112 	       tnum_equals_const(reg->var_off, 0);
1113 }
1114 
1115 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1116 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1117 {
1118 	reg->smin_value = S64_MIN;
1119 	reg->smax_value = S64_MAX;
1120 	reg->umin_value = 0;
1121 	reg->umax_value = U64_MAX;
1122 
1123 	reg->s32_min_value = S32_MIN;
1124 	reg->s32_max_value = S32_MAX;
1125 	reg->u32_min_value = 0;
1126 	reg->u32_max_value = U32_MAX;
1127 }
1128 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1129 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1130 {
1131 	reg->smin_value = S64_MIN;
1132 	reg->smax_value = S64_MAX;
1133 	reg->umin_value = 0;
1134 	reg->umax_value = U64_MAX;
1135 }
1136 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1137 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1138 {
1139 	reg->s32_min_value = S32_MIN;
1140 	reg->s32_max_value = S32_MAX;
1141 	reg->u32_min_value = 0;
1142 	reg->u32_max_value = U32_MAX;
1143 }
1144 
__update_reg32_bounds(struct bpf_reg_state * reg)1145 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1146 {
1147 	struct tnum var32_off = tnum_subreg(reg->var_off);
1148 
1149 	/* min signed is max(sign bit) | min(other bits) */
1150 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1151 			var32_off.value | (var32_off.mask & S32_MIN));
1152 	/* max signed is min(sign bit) | max(other bits) */
1153 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1154 			var32_off.value | (var32_off.mask & S32_MAX));
1155 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1156 	reg->u32_max_value = min(reg->u32_max_value,
1157 				 (u32)(var32_off.value | var32_off.mask));
1158 }
1159 
__update_reg64_bounds(struct bpf_reg_state * reg)1160 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1161 {
1162 	/* min signed is max(sign bit) | min(other bits) */
1163 	reg->smin_value = max_t(s64, reg->smin_value,
1164 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1165 	/* max signed is min(sign bit) | max(other bits) */
1166 	reg->smax_value = min_t(s64, reg->smax_value,
1167 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1168 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1169 	reg->umax_value = min(reg->umax_value,
1170 			      reg->var_off.value | reg->var_off.mask);
1171 }
1172 
__update_reg_bounds(struct bpf_reg_state * reg)1173 static void __update_reg_bounds(struct bpf_reg_state *reg)
1174 {
1175 	__update_reg32_bounds(reg);
1176 	__update_reg64_bounds(reg);
1177 }
1178 
1179 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1180 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1181 {
1182 	/* Learn sign from signed bounds.
1183 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1184 	 * are the same, so combine.  This works even in the negative case, e.g.
1185 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1186 	 */
1187 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1188 		reg->s32_min_value = reg->u32_min_value =
1189 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1190 		reg->s32_max_value = reg->u32_max_value =
1191 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1192 		return;
1193 	}
1194 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1195 	 * boundary, so we must be careful.
1196 	 */
1197 	if ((s32)reg->u32_max_value >= 0) {
1198 		/* Positive.  We can't learn anything from the smin, but smax
1199 		 * is positive, hence safe.
1200 		 */
1201 		reg->s32_min_value = reg->u32_min_value;
1202 		reg->s32_max_value = reg->u32_max_value =
1203 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1204 	} else if ((s32)reg->u32_min_value < 0) {
1205 		/* Negative.  We can't learn anything from the smax, but smin
1206 		 * is negative, hence safe.
1207 		 */
1208 		reg->s32_min_value = reg->u32_min_value =
1209 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1210 		reg->s32_max_value = reg->u32_max_value;
1211 	}
1212 }
1213 
__reg64_deduce_bounds(struct bpf_reg_state * reg)1214 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1215 {
1216 	/* Learn sign from signed bounds.
1217 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1218 	 * are the same, so combine.  This works even in the negative case, e.g.
1219 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1220 	 */
1221 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1222 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1223 							  reg->umin_value);
1224 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1225 							  reg->umax_value);
1226 		return;
1227 	}
1228 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1229 	 * boundary, so we must be careful.
1230 	 */
1231 	if ((s64)reg->umax_value >= 0) {
1232 		/* Positive.  We can't learn anything from the smin, but smax
1233 		 * is positive, hence safe.
1234 		 */
1235 		reg->smin_value = reg->umin_value;
1236 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1237 							  reg->umax_value);
1238 	} else if ((s64)reg->umin_value < 0) {
1239 		/* Negative.  We can't learn anything from the smax, but smin
1240 		 * is negative, hence safe.
1241 		 */
1242 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1243 							  reg->umin_value);
1244 		reg->smax_value = reg->umax_value;
1245 	}
1246 }
1247 
__reg_deduce_bounds(struct bpf_reg_state * reg)1248 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1249 {
1250 	__reg32_deduce_bounds(reg);
1251 	__reg64_deduce_bounds(reg);
1252 }
1253 
1254 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1255 static void __reg_bound_offset(struct bpf_reg_state *reg)
1256 {
1257 	struct tnum var64_off = tnum_intersect(reg->var_off,
1258 					       tnum_range(reg->umin_value,
1259 							  reg->umax_value));
1260 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1261 						tnum_range(reg->u32_min_value,
1262 							   reg->u32_max_value));
1263 
1264 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1265 }
1266 
reg_bounds_sync(struct bpf_reg_state * reg)1267 static void reg_bounds_sync(struct bpf_reg_state *reg)
1268 {
1269 	/* We might have learned new bounds from the var_off. */
1270 	__update_reg_bounds(reg);
1271 	/* We might have learned something about the sign bit. */
1272 	__reg_deduce_bounds(reg);
1273 	/* We might have learned some bits from the bounds. */
1274 	__reg_bound_offset(reg);
1275 	/* Intersecting with the old var_off might have improved our bounds
1276 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1277 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1278 	 */
1279 	__update_reg_bounds(reg);
1280 }
1281 
__reg32_bound_s64(s32 a)1282 static bool __reg32_bound_s64(s32 a)
1283 {
1284 	return a >= 0 && a <= S32_MAX;
1285 }
1286 
__reg_assign_32_into_64(struct bpf_reg_state * reg)1287 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1288 {
1289 	reg->umin_value = reg->u32_min_value;
1290 	reg->umax_value = reg->u32_max_value;
1291 
1292 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1293 	 * be positive otherwise set to worse case bounds and refine later
1294 	 * from tnum.
1295 	 */
1296 	if (__reg32_bound_s64(reg->s32_min_value) &&
1297 	    __reg32_bound_s64(reg->s32_max_value)) {
1298 		reg->smin_value = reg->s32_min_value;
1299 		reg->smax_value = reg->s32_max_value;
1300 	} else {
1301 		reg->smin_value = 0;
1302 		reg->smax_value = U32_MAX;
1303 	}
1304 }
1305 
__reg_combine_32_into_64(struct bpf_reg_state * reg)1306 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1307 {
1308 	/* special case when 64-bit register has upper 32-bit register
1309 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1310 	 * allowing us to use 32-bit bounds directly,
1311 	 */
1312 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1313 		__reg_assign_32_into_64(reg);
1314 	} else {
1315 		/* Otherwise the best we can do is push lower 32bit known and
1316 		 * unknown bits into register (var_off set from jmp logic)
1317 		 * then learn as much as possible from the 64-bit tnum
1318 		 * known and unknown bits. The previous smin/smax bounds are
1319 		 * invalid here because of jmp32 compare so mark them unknown
1320 		 * so they do not impact tnum bounds calculation.
1321 		 */
1322 		__mark_reg64_unbounded(reg);
1323 	}
1324 	reg_bounds_sync(reg);
1325 }
1326 
__reg64_bound_s32(s64 a)1327 static bool __reg64_bound_s32(s64 a)
1328 {
1329 	return a >= S32_MIN && a <= S32_MAX;
1330 }
1331 
__reg64_bound_u32(u64 a)1332 static bool __reg64_bound_u32(u64 a)
1333 {
1334 	return a >= U32_MIN && a <= U32_MAX;
1335 }
1336 
__reg_combine_64_into_32(struct bpf_reg_state * reg)1337 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1338 {
1339 	__mark_reg32_unbounded(reg);
1340 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1341 		reg->s32_min_value = (s32)reg->smin_value;
1342 		reg->s32_max_value = (s32)reg->smax_value;
1343 	}
1344 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1345 		reg->u32_min_value = (u32)reg->umin_value;
1346 		reg->u32_max_value = (u32)reg->umax_value;
1347 	}
1348 	reg_bounds_sync(reg);
1349 }
1350 
1351 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1352 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1353 			       struct bpf_reg_state *reg)
1354 {
1355 	/*
1356 	 * Clear type, id, off, and union(map_ptr, range) and
1357 	 * padding between 'type' and union
1358 	 */
1359 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1360 	reg->type = SCALAR_VALUE;
1361 	reg->var_off = tnum_unknown;
1362 	reg->frameno = 0;
1363 	reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1364 	__mark_reg_unbounded(reg);
1365 }
1366 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1367 static void mark_reg_unknown(struct bpf_verifier_env *env,
1368 			     struct bpf_reg_state *regs, u32 regno)
1369 {
1370 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1371 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1372 		/* Something bad happened, let's kill all regs except FP */
1373 		for (regno = 0; regno < BPF_REG_FP; regno++)
1374 			__mark_reg_not_init(env, regs + regno);
1375 		return;
1376 	}
1377 	__mark_reg_unknown(env, regs + regno);
1378 }
1379 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1380 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1381 				struct bpf_reg_state *reg)
1382 {
1383 	__mark_reg_unknown(env, reg);
1384 	reg->type = NOT_INIT;
1385 }
1386 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1387 static void mark_reg_not_init(struct bpf_verifier_env *env,
1388 			      struct bpf_reg_state *regs, u32 regno)
1389 {
1390 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1391 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1392 		/* Something bad happened, let's kill all regs except FP */
1393 		for (regno = 0; regno < BPF_REG_FP; regno++)
1394 			__mark_reg_not_init(env, regs + regno);
1395 		return;
1396 	}
1397 	__mark_reg_not_init(env, regs + regno);
1398 }
1399 
mark_btf_ld_reg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum bpf_reg_type reg_type,u32 btf_id)1400 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1401 			    struct bpf_reg_state *regs, u32 regno,
1402 			    enum bpf_reg_type reg_type, u32 btf_id)
1403 {
1404 	if (reg_type == SCALAR_VALUE) {
1405 		mark_reg_unknown(env, regs, regno);
1406 		return;
1407 	}
1408 	mark_reg_known_zero(env, regs, regno);
1409 	regs[regno].type = PTR_TO_BTF_ID;
1410 	regs[regno].btf_id = btf_id;
1411 }
1412 
1413 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1414 static void init_reg_state(struct bpf_verifier_env *env,
1415 			   struct bpf_func_state *state)
1416 {
1417 	struct bpf_reg_state *regs = state->regs;
1418 	int i;
1419 
1420 	for (i = 0; i < MAX_BPF_REG; i++) {
1421 		mark_reg_not_init(env, regs, i);
1422 		regs[i].live = REG_LIVE_NONE;
1423 		regs[i].parent = NULL;
1424 		regs[i].subreg_def = DEF_NOT_SUBREG;
1425 	}
1426 
1427 	/* frame pointer */
1428 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1429 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1430 	regs[BPF_REG_FP].frameno = state->frameno;
1431 }
1432 
1433 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1434 static void init_func_state(struct bpf_verifier_env *env,
1435 			    struct bpf_func_state *state,
1436 			    int callsite, int frameno, int subprogno)
1437 {
1438 	state->callsite = callsite;
1439 	state->frameno = frameno;
1440 	state->subprogno = subprogno;
1441 	init_reg_state(env, state);
1442 }
1443 
1444 enum reg_arg_type {
1445 	SRC_OP,		/* register is used as source operand */
1446 	DST_OP,		/* register is used as destination operand */
1447 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1448 };
1449 
cmp_subprogs(const void * a,const void * b)1450 static int cmp_subprogs(const void *a, const void *b)
1451 {
1452 	return ((struct bpf_subprog_info *)a)->start -
1453 	       ((struct bpf_subprog_info *)b)->start;
1454 }
1455 
find_subprog(struct bpf_verifier_env * env,int off)1456 static int find_subprog(struct bpf_verifier_env *env, int off)
1457 {
1458 	struct bpf_subprog_info *p;
1459 
1460 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1461 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1462 	if (!p)
1463 		return -ENOENT;
1464 	return p - env->subprog_info;
1465 
1466 }
1467 
add_subprog(struct bpf_verifier_env * env,int off)1468 static int add_subprog(struct bpf_verifier_env *env, int off)
1469 {
1470 	int insn_cnt = env->prog->len;
1471 	int ret;
1472 
1473 	if (off >= insn_cnt || off < 0) {
1474 		verbose(env, "call to invalid destination\n");
1475 		return -EINVAL;
1476 	}
1477 	ret = find_subprog(env, off);
1478 	if (ret >= 0)
1479 		return 0;
1480 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1481 		verbose(env, "too many subprograms\n");
1482 		return -E2BIG;
1483 	}
1484 	env->subprog_info[env->subprog_cnt++].start = off;
1485 	sort(env->subprog_info, env->subprog_cnt,
1486 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1487 	return 0;
1488 }
1489 
check_subprogs(struct bpf_verifier_env * env)1490 static int check_subprogs(struct bpf_verifier_env *env)
1491 {
1492 	int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1493 	struct bpf_subprog_info *subprog = env->subprog_info;
1494 	struct bpf_insn *insn = env->prog->insnsi;
1495 	int insn_cnt = env->prog->len;
1496 
1497 	/* Add entry function. */
1498 	ret = add_subprog(env, 0);
1499 	if (ret < 0)
1500 		return ret;
1501 
1502 	/* determine subprog starts. The end is one before the next starts */
1503 	for (i = 0; i < insn_cnt; i++) {
1504 		if (insn[i].code != (BPF_JMP | BPF_CALL))
1505 			continue;
1506 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
1507 			continue;
1508 		if (!env->bpf_capable) {
1509 			verbose(env,
1510 				"function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1511 			return -EPERM;
1512 		}
1513 		ret = add_subprog(env, i + insn[i].imm + 1);
1514 		if (ret < 0)
1515 			return ret;
1516 	}
1517 
1518 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1519 	 * logic. 'subprog_cnt' should not be increased.
1520 	 */
1521 	subprog[env->subprog_cnt].start = insn_cnt;
1522 
1523 	if (env->log.level & BPF_LOG_LEVEL2)
1524 		for (i = 0; i < env->subprog_cnt; i++)
1525 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1526 
1527 	/* now check that all jumps are within the same subprog */
1528 	subprog_start = subprog[cur_subprog].start;
1529 	subprog_end = subprog[cur_subprog + 1].start;
1530 	for (i = 0; i < insn_cnt; i++) {
1531 		u8 code = insn[i].code;
1532 
1533 		if (code == (BPF_JMP | BPF_CALL) &&
1534 		    insn[i].imm == BPF_FUNC_tail_call &&
1535 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1536 			subprog[cur_subprog].has_tail_call = true;
1537 		if (BPF_CLASS(code) == BPF_LD &&
1538 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1539 			subprog[cur_subprog].has_ld_abs = true;
1540 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1541 			goto next;
1542 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1543 			goto next;
1544 		off = i + insn[i].off + 1;
1545 		if (off < subprog_start || off >= subprog_end) {
1546 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1547 			return -EINVAL;
1548 		}
1549 next:
1550 		if (i == subprog_end - 1) {
1551 			/* to avoid fall-through from one subprog into another
1552 			 * the last insn of the subprog should be either exit
1553 			 * or unconditional jump back
1554 			 */
1555 			if (code != (BPF_JMP | BPF_EXIT) &&
1556 			    code != (BPF_JMP | BPF_JA)) {
1557 				verbose(env, "last insn is not an exit or jmp\n");
1558 				return -EINVAL;
1559 			}
1560 			subprog_start = subprog_end;
1561 			cur_subprog++;
1562 			if (cur_subprog < env->subprog_cnt)
1563 				subprog_end = subprog[cur_subprog + 1].start;
1564 		}
1565 	}
1566 	return 0;
1567 }
1568 
1569 /* Parentage chain of this register (or stack slot) should take care of all
1570  * issues like callee-saved registers, stack slot allocation time, etc.
1571  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1572 static int mark_reg_read(struct bpf_verifier_env *env,
1573 			 const struct bpf_reg_state *state,
1574 			 struct bpf_reg_state *parent, u8 flag)
1575 {
1576 	bool writes = parent == state->parent; /* Observe write marks */
1577 	int cnt = 0;
1578 
1579 	while (parent) {
1580 		/* if read wasn't screened by an earlier write ... */
1581 		if (writes && state->live & REG_LIVE_WRITTEN)
1582 			break;
1583 		if (parent->live & REG_LIVE_DONE) {
1584 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1585 				reg_type_str(env, parent->type),
1586 				parent->var_off.value, parent->off);
1587 			return -EFAULT;
1588 		}
1589 		/* The first condition is more likely to be true than the
1590 		 * second, checked it first.
1591 		 */
1592 		if ((parent->live & REG_LIVE_READ) == flag ||
1593 		    parent->live & REG_LIVE_READ64)
1594 			/* The parentage chain never changes and
1595 			 * this parent was already marked as LIVE_READ.
1596 			 * There is no need to keep walking the chain again and
1597 			 * keep re-marking all parents as LIVE_READ.
1598 			 * This case happens when the same register is read
1599 			 * multiple times without writes into it in-between.
1600 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1601 			 * then no need to set the weak REG_LIVE_READ32.
1602 			 */
1603 			break;
1604 		/* ... then we depend on parent's value */
1605 		parent->live |= flag;
1606 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1607 		if (flag == REG_LIVE_READ64)
1608 			parent->live &= ~REG_LIVE_READ32;
1609 		state = parent;
1610 		parent = state->parent;
1611 		writes = true;
1612 		cnt++;
1613 	}
1614 
1615 	if (env->longest_mark_read_walk < cnt)
1616 		env->longest_mark_read_walk = cnt;
1617 	return 0;
1618 }
1619 
1620 /* This function is supposed to be used by the following 32-bit optimization
1621  * code only. It returns TRUE if the source or destination register operates
1622  * on 64-bit, otherwise return FALSE.
1623  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1624 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1625 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1626 {
1627 	u8 code, class, op;
1628 
1629 	code = insn->code;
1630 	class = BPF_CLASS(code);
1631 	op = BPF_OP(code);
1632 	if (class == BPF_JMP) {
1633 		/* BPF_EXIT for "main" will reach here. Return TRUE
1634 		 * conservatively.
1635 		 */
1636 		if (op == BPF_EXIT)
1637 			return true;
1638 		if (op == BPF_CALL) {
1639 			/* BPF to BPF call will reach here because of marking
1640 			 * caller saved clobber with DST_OP_NO_MARK for which we
1641 			 * don't care the register def because they are anyway
1642 			 * marked as NOT_INIT already.
1643 			 */
1644 			if (insn->src_reg == BPF_PSEUDO_CALL)
1645 				return false;
1646 			/* Helper call will reach here because of arg type
1647 			 * check, conservatively return TRUE.
1648 			 */
1649 			if (t == SRC_OP)
1650 				return true;
1651 
1652 			return false;
1653 		}
1654 	}
1655 
1656 	if (class == BPF_ALU64 || class == BPF_JMP ||
1657 	    /* BPF_END always use BPF_ALU class. */
1658 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1659 		return true;
1660 
1661 	if (class == BPF_ALU || class == BPF_JMP32)
1662 		return false;
1663 
1664 	if (class == BPF_LDX) {
1665 		if (t != SRC_OP)
1666 			return BPF_SIZE(code) == BPF_DW;
1667 		/* LDX source must be ptr. */
1668 		return true;
1669 	}
1670 
1671 	if (class == BPF_STX) {
1672 		if (reg->type != SCALAR_VALUE)
1673 			return true;
1674 		return BPF_SIZE(code) == BPF_DW;
1675 	}
1676 
1677 	if (class == BPF_LD) {
1678 		u8 mode = BPF_MODE(code);
1679 
1680 		/* LD_IMM64 */
1681 		if (mode == BPF_IMM)
1682 			return true;
1683 
1684 		/* Both LD_IND and LD_ABS return 32-bit data. */
1685 		if (t != SRC_OP)
1686 			return  false;
1687 
1688 		/* Implicit ctx ptr. */
1689 		if (regno == BPF_REG_6)
1690 			return true;
1691 
1692 		/* Explicit source could be any width. */
1693 		return true;
1694 	}
1695 
1696 	if (class == BPF_ST)
1697 		/* The only source register for BPF_ST is a ptr. */
1698 		return true;
1699 
1700 	/* Conservatively return true at default. */
1701 	return true;
1702 }
1703 
1704 /* Return TRUE if INSN doesn't have explicit value define. */
insn_no_def(struct bpf_insn * insn)1705 static bool insn_no_def(struct bpf_insn *insn)
1706 {
1707 	u8 class = BPF_CLASS(insn->code);
1708 
1709 	return (class == BPF_JMP || class == BPF_JMP32 ||
1710 		class == BPF_STX || class == BPF_ST);
1711 }
1712 
1713 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)1714 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1715 {
1716 	if (insn_no_def(insn))
1717 		return false;
1718 
1719 	return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1720 }
1721 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1722 static void mark_insn_zext(struct bpf_verifier_env *env,
1723 			   struct bpf_reg_state *reg)
1724 {
1725 	s32 def_idx = reg->subreg_def;
1726 
1727 	if (def_idx == DEF_NOT_SUBREG)
1728 		return;
1729 
1730 	env->insn_aux_data[def_idx - 1].zext_dst = true;
1731 	/* The dst will be zero extended, so won't be sub-register anymore. */
1732 	reg->subreg_def = DEF_NOT_SUBREG;
1733 }
1734 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)1735 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1736 			 enum reg_arg_type t)
1737 {
1738 	struct bpf_verifier_state *vstate = env->cur_state;
1739 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
1740 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1741 	struct bpf_reg_state *reg, *regs = state->regs;
1742 	bool rw64;
1743 
1744 	if (regno >= MAX_BPF_REG) {
1745 		verbose(env, "R%d is invalid\n", regno);
1746 		return -EINVAL;
1747 	}
1748 
1749 	reg = &regs[regno];
1750 	rw64 = is_reg64(env, insn, regno, reg, t);
1751 	if (t == SRC_OP) {
1752 		/* check whether register used as source operand can be read */
1753 		if (reg->type == NOT_INIT) {
1754 			verbose(env, "R%d !read_ok\n", regno);
1755 			return -EACCES;
1756 		}
1757 		/* We don't need to worry about FP liveness because it's read-only */
1758 		if (regno == BPF_REG_FP)
1759 			return 0;
1760 
1761 		if (rw64)
1762 			mark_insn_zext(env, reg);
1763 
1764 		return mark_reg_read(env, reg, reg->parent,
1765 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1766 	} else {
1767 		/* check whether register used as dest operand can be written to */
1768 		if (regno == BPF_REG_FP) {
1769 			verbose(env, "frame pointer is read only\n");
1770 			return -EACCES;
1771 		}
1772 		reg->live |= REG_LIVE_WRITTEN;
1773 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1774 		if (t == DST_OP)
1775 			mark_reg_unknown(env, regs, regno);
1776 	}
1777 	return 0;
1778 }
1779 
1780 /* for any branch, call, exit record the history of jmps in the given state */
push_jmp_history(struct bpf_verifier_env * env,struct bpf_verifier_state * cur)1781 static int push_jmp_history(struct bpf_verifier_env *env,
1782 			    struct bpf_verifier_state *cur)
1783 {
1784 	u32 cnt = cur->jmp_history_cnt;
1785 	struct bpf_idx_pair *p;
1786 
1787 	cnt++;
1788 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1789 	if (!p)
1790 		return -ENOMEM;
1791 	p[cnt - 1].idx = env->insn_idx;
1792 	p[cnt - 1].prev_idx = env->prev_insn_idx;
1793 	cur->jmp_history = p;
1794 	cur->jmp_history_cnt = cnt;
1795 	return 0;
1796 }
1797 
1798 /* Backtrack one insn at a time. If idx is not at the top of recorded
1799  * history then previous instruction came from straight line execution.
1800  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)1801 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1802 			     u32 *history)
1803 {
1804 	u32 cnt = *history;
1805 
1806 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
1807 		i = st->jmp_history[cnt - 1].prev_idx;
1808 		(*history)--;
1809 	} else {
1810 		i--;
1811 	}
1812 	return i;
1813 }
1814 
1815 /* For given verifier state backtrack_insn() is called from the last insn to
1816  * the first insn. Its purpose is to compute a bitmask of registers and
1817  * stack slots that needs precision in the parent verifier state.
1818  */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)1819 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1820 			  u32 *reg_mask, u64 *stack_mask)
1821 {
1822 	const struct bpf_insn_cbs cbs = {
1823 		.cb_print	= verbose,
1824 		.private_data	= env,
1825 	};
1826 	struct bpf_insn *insn = env->prog->insnsi + idx;
1827 	u8 class = BPF_CLASS(insn->code);
1828 	u8 opcode = BPF_OP(insn->code);
1829 	u8 mode = BPF_MODE(insn->code);
1830 	u32 dreg = 1u << insn->dst_reg;
1831 	u32 sreg = 1u << insn->src_reg;
1832 	u32 spi;
1833 
1834 	if (insn->code == 0)
1835 		return 0;
1836 	if (env->log.level & BPF_LOG_LEVEL) {
1837 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1838 		verbose(env, "%d: ", idx);
1839 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1840 	}
1841 
1842 	if (class == BPF_ALU || class == BPF_ALU64) {
1843 		if (!(*reg_mask & dreg))
1844 			return 0;
1845 		if (opcode == BPF_MOV) {
1846 			if (BPF_SRC(insn->code) == BPF_X) {
1847 				/* dreg = sreg
1848 				 * dreg needs precision after this insn
1849 				 * sreg needs precision before this insn
1850 				 */
1851 				*reg_mask &= ~dreg;
1852 				*reg_mask |= sreg;
1853 			} else {
1854 				/* dreg = K
1855 				 * dreg needs precision after this insn.
1856 				 * Corresponding register is already marked
1857 				 * as precise=true in this verifier state.
1858 				 * No further markings in parent are necessary
1859 				 */
1860 				*reg_mask &= ~dreg;
1861 			}
1862 		} else {
1863 			if (BPF_SRC(insn->code) == BPF_X) {
1864 				/* dreg += sreg
1865 				 * both dreg and sreg need precision
1866 				 * before this insn
1867 				 */
1868 				*reg_mask |= sreg;
1869 			} /* else dreg += K
1870 			   * dreg still needs precision before this insn
1871 			   */
1872 		}
1873 	} else if (class == BPF_LDX) {
1874 		if (!(*reg_mask & dreg))
1875 			return 0;
1876 		*reg_mask &= ~dreg;
1877 
1878 		/* scalars can only be spilled into stack w/o losing precision.
1879 		 * Load from any other memory can be zero extended.
1880 		 * The desire to keep that precision is already indicated
1881 		 * by 'precise' mark in corresponding register of this state.
1882 		 * No further tracking necessary.
1883 		 */
1884 		if (insn->src_reg != BPF_REG_FP)
1885 			return 0;
1886 
1887 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
1888 		 * that [fp - off] slot contains scalar that needs to be
1889 		 * tracked with precision
1890 		 */
1891 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1892 		if (spi >= 64) {
1893 			verbose(env, "BUG spi %d\n", spi);
1894 			WARN_ONCE(1, "verifier backtracking bug");
1895 			return -EFAULT;
1896 		}
1897 		*stack_mask |= 1ull << spi;
1898 	} else if (class == BPF_STX || class == BPF_ST) {
1899 		if (*reg_mask & dreg)
1900 			/* stx & st shouldn't be using _scalar_ dst_reg
1901 			 * to access memory. It means backtracking
1902 			 * encountered a case of pointer subtraction.
1903 			 */
1904 			return -ENOTSUPP;
1905 		/* scalars can only be spilled into stack */
1906 		if (insn->dst_reg != BPF_REG_FP)
1907 			return 0;
1908 		spi = (-insn->off - 1) / BPF_REG_SIZE;
1909 		if (spi >= 64) {
1910 			verbose(env, "BUG spi %d\n", spi);
1911 			WARN_ONCE(1, "verifier backtracking bug");
1912 			return -EFAULT;
1913 		}
1914 		if (!(*stack_mask & (1ull << spi)))
1915 			return 0;
1916 		*stack_mask &= ~(1ull << spi);
1917 		if (class == BPF_STX)
1918 			*reg_mask |= sreg;
1919 	} else if (class == BPF_JMP || class == BPF_JMP32) {
1920 		if (opcode == BPF_CALL) {
1921 			if (insn->src_reg == BPF_PSEUDO_CALL)
1922 				return -ENOTSUPP;
1923 			/* regular helper call sets R0 */
1924 			*reg_mask &= ~1;
1925 			if (*reg_mask & 0x3f) {
1926 				/* if backtracing was looking for registers R1-R5
1927 				 * they should have been found already.
1928 				 */
1929 				verbose(env, "BUG regs %x\n", *reg_mask);
1930 				WARN_ONCE(1, "verifier backtracking bug");
1931 				return -EFAULT;
1932 			}
1933 		} else if (opcode == BPF_EXIT) {
1934 			return -ENOTSUPP;
1935 		} else if (BPF_SRC(insn->code) == BPF_X) {
1936 			if (!(*reg_mask & (dreg | sreg)))
1937 				return 0;
1938 			/* dreg <cond> sreg
1939 			 * Both dreg and sreg need precision before
1940 			 * this insn. If only sreg was marked precise
1941 			 * before it would be equally necessary to
1942 			 * propagate it to dreg.
1943 			 */
1944 			*reg_mask |= (sreg | dreg);
1945 			 /* else dreg <cond> K
1946 			  * Only dreg still needs precision before
1947 			  * this insn, so for the K-based conditional
1948 			  * there is nothing new to be marked.
1949 			  */
1950 		}
1951 	} else if (class == BPF_LD) {
1952 		if (!(*reg_mask & dreg))
1953 			return 0;
1954 		*reg_mask &= ~dreg;
1955 		/* It's ld_imm64 or ld_abs or ld_ind.
1956 		 * For ld_imm64 no further tracking of precision
1957 		 * into parent is necessary
1958 		 */
1959 		if (mode == BPF_IND || mode == BPF_ABS)
1960 			/* to be analyzed */
1961 			return -ENOTSUPP;
1962 	}
1963 	return 0;
1964 }
1965 
1966 /* the scalar precision tracking algorithm:
1967  * . at the start all registers have precise=false.
1968  * . scalar ranges are tracked as normal through alu and jmp insns.
1969  * . once precise value of the scalar register is used in:
1970  *   .  ptr + scalar alu
1971  *   . if (scalar cond K|scalar)
1972  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1973  *   backtrack through the verifier states and mark all registers and
1974  *   stack slots with spilled constants that these scalar regisers
1975  *   should be precise.
1976  * . during state pruning two registers (or spilled stack slots)
1977  *   are equivalent if both are not precise.
1978  *
1979  * Note the verifier cannot simply walk register parentage chain,
1980  * since many different registers and stack slots could have been
1981  * used to compute single precise scalar.
1982  *
1983  * The approach of starting with precise=true for all registers and then
1984  * backtrack to mark a register as not precise when the verifier detects
1985  * that program doesn't care about specific value (e.g., when helper
1986  * takes register as ARG_ANYTHING parameter) is not safe.
1987  *
1988  * It's ok to walk single parentage chain of the verifier states.
1989  * It's possible that this backtracking will go all the way till 1st insn.
1990  * All other branches will be explored for needing precision later.
1991  *
1992  * The backtracking needs to deal with cases like:
1993  *   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)
1994  * r9 -= r8
1995  * r5 = r9
1996  * if r5 > 0x79f goto pc+7
1997  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1998  * r5 += 1
1999  * ...
2000  * call bpf_perf_event_output#25
2001  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2002  *
2003  * and this case:
2004  * r6 = 1
2005  * call foo // uses callee's r6 inside to compute r0
2006  * r0 += r6
2007  * if r0 == 0 goto
2008  *
2009  * to track above reg_mask/stack_mask needs to be independent for each frame.
2010  *
2011  * Also if parent's curframe > frame where backtracking started,
2012  * the verifier need to mark registers in both frames, otherwise callees
2013  * may incorrectly prune callers. This is similar to
2014  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2015  *
2016  * For now backtracking falls back into conservative marking.
2017  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2018 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2019 				     struct bpf_verifier_state *st)
2020 {
2021 	struct bpf_func_state *func;
2022 	struct bpf_reg_state *reg;
2023 	int i, j;
2024 
2025 	/* big hammer: mark all scalars precise in this path.
2026 	 * pop_stack may still get !precise scalars.
2027 	 */
2028 	for (; st; st = st->parent)
2029 		for (i = 0; i <= st->curframe; i++) {
2030 			func = st->frame[i];
2031 			for (j = 0; j < BPF_REG_FP; j++) {
2032 				reg = &func->regs[j];
2033 				if (reg->type != SCALAR_VALUE)
2034 					continue;
2035 				reg->precise = true;
2036 			}
2037 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2038 				if (!is_spilled_reg(&func->stack[j]))
2039 					continue;
2040 				reg = &func->stack[j].spilled_ptr;
2041 				if (reg->type != SCALAR_VALUE)
2042 					continue;
2043 				reg->precise = true;
2044 			}
2045 		}
2046 }
2047 
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2048 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2049 				  int spi)
2050 {
2051 	struct bpf_verifier_state *st = env->cur_state;
2052 	int first_idx = st->first_insn_idx;
2053 	int last_idx = env->insn_idx;
2054 	struct bpf_func_state *func;
2055 	struct bpf_reg_state *reg;
2056 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2057 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2058 	bool skip_first = true;
2059 	bool new_marks = false;
2060 	int i, err;
2061 
2062 	if (!env->bpf_capable)
2063 		return 0;
2064 
2065 	func = st->frame[frame];
2066 	if (regno >= 0) {
2067 		reg = &func->regs[regno];
2068 		if (reg->type != SCALAR_VALUE) {
2069 			WARN_ONCE(1, "backtracing misuse");
2070 			return -EFAULT;
2071 		}
2072 		if (!reg->precise)
2073 			new_marks = true;
2074 		else
2075 			reg_mask = 0;
2076 		reg->precise = true;
2077 	}
2078 
2079 	while (spi >= 0) {
2080 		if (!is_spilled_reg(&func->stack[spi])) {
2081 			stack_mask = 0;
2082 			break;
2083 		}
2084 		reg = &func->stack[spi].spilled_ptr;
2085 		if (reg->type != SCALAR_VALUE) {
2086 			stack_mask = 0;
2087 			break;
2088 		}
2089 		if (!reg->precise)
2090 			new_marks = true;
2091 		else
2092 			stack_mask = 0;
2093 		reg->precise = true;
2094 		break;
2095 	}
2096 
2097 	if (!new_marks)
2098 		return 0;
2099 	if (!reg_mask && !stack_mask)
2100 		return 0;
2101 	for (;;) {
2102 		DECLARE_BITMAP(mask, 64);
2103 		u32 history = st->jmp_history_cnt;
2104 
2105 		if (env->log.level & BPF_LOG_LEVEL)
2106 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2107 		for (i = last_idx;;) {
2108 			if (skip_first) {
2109 				err = 0;
2110 				skip_first = false;
2111 			} else {
2112 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2113 			}
2114 			if (err == -ENOTSUPP) {
2115 				mark_all_scalars_precise(env, st);
2116 				return 0;
2117 			} else if (err) {
2118 				return err;
2119 			}
2120 			if (!reg_mask && !stack_mask)
2121 				/* Found assignment(s) into tracked register in this state.
2122 				 * Since this state is already marked, just return.
2123 				 * Nothing to be tracked further in the parent state.
2124 				 */
2125 				return 0;
2126 			if (i == first_idx)
2127 				break;
2128 			i = get_prev_insn_idx(st, i, &history);
2129 			if (i >= env->prog->len) {
2130 				/* This can happen if backtracking reached insn 0
2131 				 * and there are still reg_mask or stack_mask
2132 				 * to backtrack.
2133 				 * It means the backtracking missed the spot where
2134 				 * particular register was initialized with a constant.
2135 				 */
2136 				verbose(env, "BUG backtracking idx %d\n", i);
2137 				WARN_ONCE(1, "verifier backtracking bug");
2138 				return -EFAULT;
2139 			}
2140 		}
2141 		st = st->parent;
2142 		if (!st)
2143 			break;
2144 
2145 		new_marks = false;
2146 		func = st->frame[frame];
2147 		bitmap_from_u64(mask, reg_mask);
2148 		for_each_set_bit(i, mask, 32) {
2149 			reg = &func->regs[i];
2150 			if (reg->type != SCALAR_VALUE) {
2151 				reg_mask &= ~(1u << i);
2152 				continue;
2153 			}
2154 			if (!reg->precise)
2155 				new_marks = true;
2156 			reg->precise = true;
2157 		}
2158 
2159 		bitmap_from_u64(mask, stack_mask);
2160 		for_each_set_bit(i, mask, 64) {
2161 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2162 				/* the sequence of instructions:
2163 				 * 2: (bf) r3 = r10
2164 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2165 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2166 				 * doesn't contain jmps. It's backtracked
2167 				 * as a single block.
2168 				 * During backtracking insn 3 is not recognized as
2169 				 * stack access, so at the end of backtracking
2170 				 * stack slot fp-8 is still marked in stack_mask.
2171 				 * However the parent state may not have accessed
2172 				 * fp-8 and it's "unallocated" stack space.
2173 				 * In such case fallback to conservative.
2174 				 */
2175 				mark_all_scalars_precise(env, st);
2176 				return 0;
2177 			}
2178 
2179 			if (!is_spilled_reg(&func->stack[i])) {
2180 				stack_mask &= ~(1ull << i);
2181 				continue;
2182 			}
2183 			reg = &func->stack[i].spilled_ptr;
2184 			if (reg->type != SCALAR_VALUE) {
2185 				stack_mask &= ~(1ull << i);
2186 				continue;
2187 			}
2188 			if (!reg->precise)
2189 				new_marks = true;
2190 			reg->precise = true;
2191 		}
2192 		if (env->log.level & BPF_LOG_LEVEL) {
2193 			print_verifier_state(env, func);
2194 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2195 				new_marks ? "didn't have" : "already had",
2196 				reg_mask, stack_mask);
2197 		}
2198 
2199 		if (!reg_mask && !stack_mask)
2200 			break;
2201 		if (!new_marks)
2202 			break;
2203 
2204 		last_idx = st->last_insn_idx;
2205 		first_idx = st->first_insn_idx;
2206 	}
2207 	return 0;
2208 }
2209 
mark_chain_precision(struct bpf_verifier_env * env,int regno)2210 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2211 {
2212 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2213 }
2214 
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2215 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2216 {
2217 	return __mark_chain_precision(env, frame, regno, -1);
2218 }
2219 
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2220 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2221 {
2222 	return __mark_chain_precision(env, frame, -1, spi);
2223 }
2224 
is_spillable_regtype(enum bpf_reg_type type)2225 static bool is_spillable_regtype(enum bpf_reg_type type)
2226 {
2227 	switch (base_type(type)) {
2228 	case PTR_TO_MAP_VALUE:
2229 	case PTR_TO_STACK:
2230 	case PTR_TO_CTX:
2231 	case PTR_TO_PACKET:
2232 	case PTR_TO_PACKET_META:
2233 	case PTR_TO_PACKET_END:
2234 	case PTR_TO_FLOW_KEYS:
2235 	case CONST_PTR_TO_MAP:
2236 	case PTR_TO_SOCKET:
2237 	case PTR_TO_SOCK_COMMON:
2238 	case PTR_TO_TCP_SOCK:
2239 	case PTR_TO_XDP_SOCK:
2240 	case PTR_TO_BTF_ID:
2241 	case PTR_TO_BUF:
2242 	case PTR_TO_PERCPU_BTF_ID:
2243 	case PTR_TO_MEM:
2244 		return true;
2245 	default:
2246 		return false;
2247 	}
2248 }
2249 
2250 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2251 static bool register_is_null(struct bpf_reg_state *reg)
2252 {
2253 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2254 }
2255 
register_is_const(struct bpf_reg_state * reg)2256 static bool register_is_const(struct bpf_reg_state *reg)
2257 {
2258 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2259 }
2260 
__is_scalar_unbounded(struct bpf_reg_state * reg)2261 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2262 {
2263 	return tnum_is_unknown(reg->var_off) &&
2264 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2265 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2266 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2267 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2268 }
2269 
register_is_bounded(struct bpf_reg_state * reg)2270 static bool register_is_bounded(struct bpf_reg_state *reg)
2271 {
2272 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2273 }
2274 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)2275 static bool __is_pointer_value(bool allow_ptr_leaks,
2276 			       const struct bpf_reg_state *reg)
2277 {
2278 	if (allow_ptr_leaks)
2279 		return false;
2280 
2281 	return reg->type != SCALAR_VALUE;
2282 }
2283 
2284 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)2285 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2286 {
2287 	struct bpf_reg_state *parent = dst->parent;
2288 	enum bpf_reg_liveness live = dst->live;
2289 
2290 	*dst = *src;
2291 	dst->parent = parent;
2292 	dst->live = live;
2293 }
2294 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)2295 static void save_register_state(struct bpf_func_state *state,
2296 				int spi, struct bpf_reg_state *reg,
2297 				int size)
2298 {
2299 	int i;
2300 
2301 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
2302 	if (size == BPF_REG_SIZE)
2303 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2304 
2305 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2306 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2307 
2308 	/* size < 8 bytes spill */
2309 	for (; i; i--)
2310 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2311 }
2312 
2313 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2314  * stack boundary and alignment are checked in check_mem_access()
2315  */
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)2316 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2317 				       /* stack frame we're writing to */
2318 				       struct bpf_func_state *state,
2319 				       int off, int size, int value_regno,
2320 				       int insn_idx)
2321 {
2322 	struct bpf_func_state *cur; /* state of the current function */
2323 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2324 	u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2325 	struct bpf_reg_state *reg = NULL;
2326 
2327 	err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2328 				 state->acquired_refs, true);
2329 	if (err)
2330 		return err;
2331 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2332 	 * so it's aligned access and [off, off + size) are within stack limits
2333 	 */
2334 	if (!env->allow_ptr_leaks &&
2335 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
2336 	    size != BPF_REG_SIZE) {
2337 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2338 		return -EACCES;
2339 	}
2340 
2341 	cur = env->cur_state->frame[env->cur_state->curframe];
2342 	if (value_regno >= 0)
2343 		reg = &cur->regs[value_regno];
2344 	if (!env->bypass_spec_v4) {
2345 		bool sanitize = reg && is_spillable_regtype(reg->type);
2346 
2347 		for (i = 0; i < size; i++) {
2348 			u8 type = state->stack[spi].slot_type[i];
2349 
2350 			if (type != STACK_MISC && type != STACK_ZERO) {
2351 				sanitize = true;
2352 				break;
2353 			}
2354 		}
2355 
2356 		if (sanitize)
2357 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2358 	}
2359 
2360 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2361 	    !register_is_null(reg) && env->bpf_capable) {
2362 		if (dst_reg != BPF_REG_FP) {
2363 			/* The backtracking logic can only recognize explicit
2364 			 * stack slot address like [fp - 8]. Other spill of
2365 			 * scalar via different register has to be conervative.
2366 			 * Backtrack from here and mark all registers as precise
2367 			 * that contributed into 'reg' being a constant.
2368 			 */
2369 			err = mark_chain_precision(env, value_regno);
2370 			if (err)
2371 				return err;
2372 		}
2373 		save_register_state(state, spi, reg, size);
2374 	} else if (reg && is_spillable_regtype(reg->type)) {
2375 		/* register containing pointer is being spilled into stack */
2376 		if (size != BPF_REG_SIZE) {
2377 			verbose_linfo(env, insn_idx, "; ");
2378 			verbose(env, "invalid size of register spill\n");
2379 			return -EACCES;
2380 		}
2381 		if (state != cur && reg->type == PTR_TO_STACK) {
2382 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2383 			return -EINVAL;
2384 		}
2385 		save_register_state(state, spi, reg, size);
2386 	} else {
2387 		u8 type = STACK_MISC;
2388 
2389 		/* regular write of data into stack destroys any spilled ptr */
2390 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2391 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2392 		if (is_spilled_reg(&state->stack[spi]))
2393 			for (i = 0; i < BPF_REG_SIZE; i++)
2394 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2395 
2396 		/* only mark the slot as written if all 8 bytes were written
2397 		 * otherwise read propagation may incorrectly stop too soon
2398 		 * when stack slots are partially written.
2399 		 * This heuristic means that read propagation will be
2400 		 * conservative, since it will add reg_live_read marks
2401 		 * to stack slots all the way to first state when programs
2402 		 * writes+reads less than 8 bytes
2403 		 */
2404 		if (size == BPF_REG_SIZE)
2405 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2406 
2407 		/* when we zero initialize stack slots mark them as such */
2408 		if (reg && register_is_null(reg)) {
2409 			/* backtracking doesn't work for STACK_ZERO yet. */
2410 			err = mark_chain_precision(env, value_regno);
2411 			if (err)
2412 				return err;
2413 			type = STACK_ZERO;
2414 		}
2415 
2416 		/* Mark slots affected by this stack write. */
2417 		for (i = 0; i < size; i++)
2418 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2419 				type;
2420 	}
2421 	return 0;
2422 }
2423 
2424 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2425  * known to contain a variable offset.
2426  * This function checks whether the write is permitted and conservatively
2427  * tracks the effects of the write, considering that each stack slot in the
2428  * dynamic range is potentially written to.
2429  *
2430  * 'off' includes 'regno->off'.
2431  * 'value_regno' can be -1, meaning that an unknown value is being written to
2432  * the stack.
2433  *
2434  * Spilled pointers in range are not marked as written because we don't know
2435  * what's going to be actually written. This means that read propagation for
2436  * future reads cannot be terminated by this write.
2437  *
2438  * For privileged programs, uninitialized stack slots are considered
2439  * initialized by this write (even though we don't know exactly what offsets
2440  * are going to be written to). The idea is that we don't want the verifier to
2441  * reject future reads that access slots written to through variable offsets.
2442  */
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)2443 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2444 				     /* func where register points to */
2445 				     struct bpf_func_state *state,
2446 				     int ptr_regno, int off, int size,
2447 				     int value_regno, int insn_idx)
2448 {
2449 	struct bpf_func_state *cur; /* state of the current function */
2450 	int min_off, max_off;
2451 	int i, err;
2452 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2453 	bool writing_zero = false;
2454 	/* set if the fact that we're writing a zero is used to let any
2455 	 * stack slots remain STACK_ZERO
2456 	 */
2457 	bool zero_used = false;
2458 
2459 	cur = env->cur_state->frame[env->cur_state->curframe];
2460 	ptr_reg = &cur->regs[ptr_regno];
2461 	min_off = ptr_reg->smin_value + off;
2462 	max_off = ptr_reg->smax_value + off + size;
2463 	if (value_regno >= 0)
2464 		value_reg = &cur->regs[value_regno];
2465 	if (value_reg && register_is_null(value_reg))
2466 		writing_zero = true;
2467 
2468 	err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2469 				 state->acquired_refs, true);
2470 	if (err)
2471 		return err;
2472 
2473 
2474 	/* Variable offset writes destroy any spilled pointers in range. */
2475 	for (i = min_off; i < max_off; i++) {
2476 		u8 new_type, *stype;
2477 		int slot, spi;
2478 
2479 		slot = -i - 1;
2480 		spi = slot / BPF_REG_SIZE;
2481 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2482 
2483 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
2484 			/* Reject the write if range we may write to has not
2485 			 * been initialized beforehand. If we didn't reject
2486 			 * here, the ptr status would be erased below (even
2487 			 * though not all slots are actually overwritten),
2488 			 * possibly opening the door to leaks.
2489 			 *
2490 			 * We do however catch STACK_INVALID case below, and
2491 			 * only allow reading possibly uninitialized memory
2492 			 * later for CAP_PERFMON, as the write may not happen to
2493 			 * that slot.
2494 			 */
2495 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2496 				insn_idx, i);
2497 			return -EINVAL;
2498 		}
2499 
2500 		/* Erase all spilled pointers. */
2501 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2502 
2503 		/* Update the slot type. */
2504 		new_type = STACK_MISC;
2505 		if (writing_zero && *stype == STACK_ZERO) {
2506 			new_type = STACK_ZERO;
2507 			zero_used = true;
2508 		}
2509 		/* If the slot is STACK_INVALID, we check whether it's OK to
2510 		 * pretend that it will be initialized by this write. The slot
2511 		 * might not actually be written to, and so if we mark it as
2512 		 * initialized future reads might leak uninitialized memory.
2513 		 * For privileged programs, we will accept such reads to slots
2514 		 * that may or may not be written because, if we're reject
2515 		 * them, the error would be too confusing.
2516 		 */
2517 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2518 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2519 					insn_idx, i);
2520 			return -EINVAL;
2521 		}
2522 		*stype = new_type;
2523 	}
2524 	if (zero_used) {
2525 		/* backtracking doesn't work for STACK_ZERO yet. */
2526 		err = mark_chain_precision(env, value_regno);
2527 		if (err)
2528 			return err;
2529 	}
2530 	return 0;
2531 }
2532 
2533 /* When register 'dst_regno' is assigned some values from stack[min_off,
2534  * max_off), we set the register's type according to the types of the
2535  * respective stack slots. If all the stack values are known to be zeros, then
2536  * so is the destination reg. Otherwise, the register is considered to be
2537  * SCALAR. This function does not deal with register filling; the caller must
2538  * ensure that all spilled registers in the stack range have been marked as
2539  * read.
2540  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)2541 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2542 				/* func where src register points to */
2543 				struct bpf_func_state *ptr_state,
2544 				int min_off, int max_off, 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, spi;
2549 	u8 *stype;
2550 	int zeros = 0;
2551 
2552 	for (i = min_off; i < max_off; i++) {
2553 		slot = -i - 1;
2554 		spi = slot / BPF_REG_SIZE;
2555 		stype = ptr_state->stack[spi].slot_type;
2556 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2557 			break;
2558 		zeros++;
2559 	}
2560 	if (zeros == max_off - min_off) {
2561 		/* any access_size read into register is zero extended,
2562 		 * so the whole register == const_zero
2563 		 */
2564 		__mark_reg_const_zero(&state->regs[dst_regno]);
2565 		/* backtracking doesn't support STACK_ZERO yet,
2566 		 * so mark it precise here, so that later
2567 		 * backtracking can stop here.
2568 		 * Backtracking may not need this if this register
2569 		 * doesn't participate in pointer adjustment.
2570 		 * Forward propagation of precise flag is not
2571 		 * necessary either. This mark is only to stop
2572 		 * backtracking. Any register that contributed
2573 		 * to const 0 was marked precise before spill.
2574 		 */
2575 		state->regs[dst_regno].precise = true;
2576 	} else {
2577 		/* have read misc data from the stack */
2578 		mark_reg_unknown(env, state->regs, dst_regno);
2579 	}
2580 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2581 }
2582 
2583 /* Read the stack at 'off' and put the results into the register indicated by
2584  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2585  * spilled reg.
2586  *
2587  * 'dst_regno' can be -1, meaning that the read value is not going to a
2588  * register.
2589  *
2590  * The access is assumed to be within the current stack bounds.
2591  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)2592 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2593 				      /* func where src register points to */
2594 				      struct bpf_func_state *reg_state,
2595 				      int off, int size, int dst_regno)
2596 {
2597 	struct bpf_verifier_state *vstate = env->cur_state;
2598 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2599 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2600 	struct bpf_reg_state *reg;
2601 	u8 *stype, type;
2602 
2603 	stype = reg_state->stack[spi].slot_type;
2604 	reg = &reg_state->stack[spi].spilled_ptr;
2605 
2606 	if (is_spilled_reg(&reg_state->stack[spi])) {
2607 		u8 spill_size = 1;
2608 
2609 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
2610 			spill_size++;
2611 
2612 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
2613 			if (reg->type != SCALAR_VALUE) {
2614 				verbose_linfo(env, env->insn_idx, "; ");
2615 				verbose(env, "invalid size of register fill\n");
2616 				return -EACCES;
2617 			}
2618 
2619 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2620 			if (dst_regno < 0)
2621 				return 0;
2622 
2623 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
2624 				/* The earlier check_reg_arg() has decided the
2625 				 * subreg_def for this insn.  Save it first.
2626 				 */
2627 				s32 subreg_def = state->regs[dst_regno].subreg_def;
2628 
2629 				copy_register_state(&state->regs[dst_regno], reg);
2630 				state->regs[dst_regno].subreg_def = subreg_def;
2631 			} else {
2632 				for (i = 0; i < size; i++) {
2633 					type = stype[(slot - i) % BPF_REG_SIZE];
2634 					if (type == STACK_SPILL)
2635 						continue;
2636 					if (type == STACK_MISC)
2637 						continue;
2638 					verbose(env, "invalid read from stack off %d+%d size %d\n",
2639 						off, i, size);
2640 					return -EACCES;
2641 				}
2642 				mark_reg_unknown(env, state->regs, dst_regno);
2643 			}
2644 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2645 			return 0;
2646 		}
2647 
2648 		if (dst_regno >= 0) {
2649 			/* restore register state from stack */
2650 			copy_register_state(&state->regs[dst_regno], reg);
2651 			/* mark reg as written since spilled pointer state likely
2652 			 * has its liveness marks cleared by is_state_visited()
2653 			 * which resets stack/reg liveness for state transitions
2654 			 */
2655 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2656 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2657 			/* If dst_regno==-1, the caller is asking us whether
2658 			 * it is acceptable to use this value as a SCALAR_VALUE
2659 			 * (e.g. for XADD).
2660 			 * We must not allow unprivileged callers to do that
2661 			 * with spilled pointers.
2662 			 */
2663 			verbose(env, "leaking pointer from stack off %d\n",
2664 				off);
2665 			return -EACCES;
2666 		}
2667 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2668 	} else {
2669 		for (i = 0; i < size; i++) {
2670 			type = stype[(slot - i) % BPF_REG_SIZE];
2671 			if (type == STACK_MISC)
2672 				continue;
2673 			if (type == STACK_ZERO)
2674 				continue;
2675 			verbose(env, "invalid read from stack off %d+%d size %d\n",
2676 				off, i, size);
2677 			return -EACCES;
2678 		}
2679 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2680 		if (dst_regno >= 0)
2681 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2682 	}
2683 	return 0;
2684 }
2685 
2686 enum stack_access_src {
2687 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
2688 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
2689 };
2690 
2691 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2692 					 int regno, int off, int access_size,
2693 					 bool zero_size_allowed,
2694 					 enum stack_access_src type,
2695 					 struct bpf_call_arg_meta *meta);
2696 
reg_state(struct bpf_verifier_env * env,int regno)2697 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2698 {
2699 	return cur_regs(env) + regno;
2700 }
2701 
2702 /* Read the stack at 'ptr_regno + off' and put the result into the register
2703  * 'dst_regno'.
2704  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2705  * but not its variable offset.
2706  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2707  *
2708  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2709  * filling registers (i.e. reads of spilled register cannot be detected when
2710  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2711  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2712  * offset; for a fixed offset check_stack_read_fixed_off should be used
2713  * instead.
2714  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2715 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2716 				    int ptr_regno, int off, int size, int dst_regno)
2717 {
2718 	/* The state of the source register. */
2719 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2720 	struct bpf_func_state *ptr_state = func(env, reg);
2721 	int err;
2722 	int min_off, max_off;
2723 
2724 	/* Note that we pass a NULL meta, so raw access will not be permitted.
2725 	 */
2726 	err = check_stack_range_initialized(env, ptr_regno, off, size,
2727 					    false, ACCESS_DIRECT, NULL);
2728 	if (err)
2729 		return err;
2730 
2731 	min_off = reg->smin_value + off;
2732 	max_off = reg->smax_value + off;
2733 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2734 	return 0;
2735 }
2736 
2737 /* check_stack_read dispatches to check_stack_read_fixed_off or
2738  * check_stack_read_var_off.
2739  *
2740  * The caller must ensure that the offset falls within the allocated stack
2741  * bounds.
2742  *
2743  * 'dst_regno' is a register which will receive the value from the stack. It
2744  * can be -1, meaning that the read value is not going to a register.
2745  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2746 static int check_stack_read(struct bpf_verifier_env *env,
2747 			    int ptr_regno, int off, int size,
2748 			    int dst_regno)
2749 {
2750 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2751 	struct bpf_func_state *state = func(env, reg);
2752 	int err;
2753 	/* Some accesses are only permitted with a static offset. */
2754 	bool var_off = !tnum_is_const(reg->var_off);
2755 
2756 	/* The offset is required to be static when reads don't go to a
2757 	 * register, in order to not leak pointers (see
2758 	 * check_stack_read_fixed_off).
2759 	 */
2760 	if (dst_regno < 0 && var_off) {
2761 		char tn_buf[48];
2762 
2763 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2764 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2765 			tn_buf, off, size);
2766 		return -EACCES;
2767 	}
2768 	/* Variable offset is prohibited for unprivileged mode for simplicity
2769 	 * since it requires corresponding support in Spectre masking for stack
2770 	 * ALU. See also retrieve_ptr_limit(). The check in
2771 	 * check_stack_access_for_ptr_arithmetic() called by
2772 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
2773 	 * with variable offsets, therefore no check is required here. Further,
2774 	 * just checking it here would be insufficient as speculative stack
2775 	 * writes could still lead to unsafe speculative behaviour.
2776 	 */
2777 	if (!var_off) {
2778 		off += reg->var_off.value;
2779 		err = check_stack_read_fixed_off(env, state, off, size,
2780 						 dst_regno);
2781 	} else {
2782 		/* Variable offset stack reads need more conservative handling
2783 		 * than fixed offset ones. Note that dst_regno >= 0 on this
2784 		 * branch.
2785 		 */
2786 		err = check_stack_read_var_off(env, ptr_regno, off, size,
2787 					       dst_regno);
2788 	}
2789 	return err;
2790 }
2791 
2792 
2793 /* check_stack_write dispatches to check_stack_write_fixed_off or
2794  * check_stack_write_var_off.
2795  *
2796  * 'ptr_regno' is the register used as a pointer into the stack.
2797  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2798  * 'value_regno' is the register whose value we're writing to the stack. It can
2799  * be -1, meaning that we're not writing from a register.
2800  *
2801  * The caller must ensure that the offset falls within the maximum stack size.
2802  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)2803 static int check_stack_write(struct bpf_verifier_env *env,
2804 			     int ptr_regno, int off, int size,
2805 			     int value_regno, int insn_idx)
2806 {
2807 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2808 	struct bpf_func_state *state = func(env, reg);
2809 	int err;
2810 
2811 	if (tnum_is_const(reg->var_off)) {
2812 		off += reg->var_off.value;
2813 		err = check_stack_write_fixed_off(env, state, off, size,
2814 						  value_regno, insn_idx);
2815 	} else {
2816 		/* Variable offset stack reads need more conservative handling
2817 		 * than fixed offset ones.
2818 		 */
2819 		err = check_stack_write_var_off(env, state,
2820 						ptr_regno, off, size,
2821 						value_regno, insn_idx);
2822 	}
2823 	return err;
2824 }
2825 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)2826 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2827 				 int off, int size, enum bpf_access_type type)
2828 {
2829 	struct bpf_reg_state *regs = cur_regs(env);
2830 	struct bpf_map *map = regs[regno].map_ptr;
2831 	u32 cap = bpf_map_flags_to_cap(map);
2832 
2833 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2834 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2835 			map->value_size, off, size);
2836 		return -EACCES;
2837 	}
2838 
2839 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2840 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2841 			map->value_size, off, size);
2842 		return -EACCES;
2843 	}
2844 
2845 	return 0;
2846 }
2847 
2848 /* 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)2849 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2850 			      int off, int size, u32 mem_size,
2851 			      bool zero_size_allowed)
2852 {
2853 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2854 	struct bpf_reg_state *reg;
2855 
2856 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2857 		return 0;
2858 
2859 	reg = &cur_regs(env)[regno];
2860 	switch (reg->type) {
2861 	case PTR_TO_MAP_VALUE:
2862 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2863 			mem_size, off, size);
2864 		break;
2865 	case PTR_TO_PACKET:
2866 	case PTR_TO_PACKET_META:
2867 	case PTR_TO_PACKET_END:
2868 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2869 			off, size, regno, reg->id, off, mem_size);
2870 		break;
2871 	case PTR_TO_MEM:
2872 	default:
2873 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2874 			mem_size, off, size);
2875 	}
2876 
2877 	return -EACCES;
2878 }
2879 
2880 /* 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)2881 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2882 				   int off, int size, u32 mem_size,
2883 				   bool zero_size_allowed)
2884 {
2885 	struct bpf_verifier_state *vstate = env->cur_state;
2886 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2887 	struct bpf_reg_state *reg = &state->regs[regno];
2888 	int err;
2889 
2890 	/* We may have adjusted the register pointing to memory region, so we
2891 	 * need to try adding each of min_value and max_value to off
2892 	 * to make sure our theoretical access will be safe.
2893 	 */
2894 	if (env->log.level & BPF_LOG_LEVEL)
2895 		print_verifier_state(env, state);
2896 
2897 	/* The minimum value is only important with signed
2898 	 * comparisons where we can't assume the floor of a
2899 	 * value is 0.  If we are using signed variables for our
2900 	 * index'es we need to make sure that whatever we use
2901 	 * will have a set floor within our range.
2902 	 */
2903 	if (reg->smin_value < 0 &&
2904 	    (reg->smin_value == S64_MIN ||
2905 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2906 	      reg->smin_value + off < 0)) {
2907 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2908 			regno);
2909 		return -EACCES;
2910 	}
2911 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
2912 				 mem_size, zero_size_allowed);
2913 	if (err) {
2914 		verbose(env, "R%d min value is outside of the allowed memory range\n",
2915 			regno);
2916 		return err;
2917 	}
2918 
2919 	/* If we haven't set a max value then we need to bail since we can't be
2920 	 * sure we won't do bad things.
2921 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
2922 	 */
2923 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2924 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2925 			regno);
2926 		return -EACCES;
2927 	}
2928 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
2929 				 mem_size, zero_size_allowed);
2930 	if (err) {
2931 		verbose(env, "R%d max value is outside of the allowed memory range\n",
2932 			regno);
2933 		return err;
2934 	}
2935 
2936 	return 0;
2937 }
2938 
2939 /* 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)2940 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2941 			    int off, int size, bool zero_size_allowed)
2942 {
2943 	struct bpf_verifier_state *vstate = env->cur_state;
2944 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2945 	struct bpf_reg_state *reg = &state->regs[regno];
2946 	struct bpf_map *map = reg->map_ptr;
2947 	int err;
2948 
2949 	err = check_mem_region_access(env, regno, off, size, map->value_size,
2950 				      zero_size_allowed);
2951 	if (err)
2952 		return err;
2953 
2954 	if (map_value_has_spin_lock(map)) {
2955 		u32 lock = map->spin_lock_off;
2956 
2957 		/* if any part of struct bpf_spin_lock can be touched by
2958 		 * load/store reject this program.
2959 		 * To check that [x1, x2) overlaps with [y1, y2)
2960 		 * it is sufficient to check x1 < y2 && y1 < x2.
2961 		 */
2962 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2963 		     lock < reg->umax_value + off + size) {
2964 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2965 			return -EACCES;
2966 		}
2967 	}
2968 	return err;
2969 }
2970 
2971 #define MAX_PACKET_OFF 0xffff
2972 
resolve_prog_type(struct bpf_prog * prog)2973 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2974 {
2975 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2976 }
2977 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)2978 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2979 				       const struct bpf_call_arg_meta *meta,
2980 				       enum bpf_access_type t)
2981 {
2982 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2983 
2984 	switch (prog_type) {
2985 	/* Program types only with direct read access go here! */
2986 	case BPF_PROG_TYPE_LWT_IN:
2987 	case BPF_PROG_TYPE_LWT_OUT:
2988 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2989 	case BPF_PROG_TYPE_SK_REUSEPORT:
2990 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
2991 	case BPF_PROG_TYPE_CGROUP_SKB:
2992 		if (t == BPF_WRITE)
2993 			return false;
2994 		fallthrough;
2995 
2996 	/* Program types with direct read + write access go here! */
2997 	case BPF_PROG_TYPE_SCHED_CLS:
2998 	case BPF_PROG_TYPE_SCHED_ACT:
2999 	case BPF_PROG_TYPE_XDP:
3000 	case BPF_PROG_TYPE_LWT_XMIT:
3001 	case BPF_PROG_TYPE_SK_SKB:
3002 	case BPF_PROG_TYPE_SK_MSG:
3003 		if (meta)
3004 			return meta->pkt_access;
3005 
3006 		env->seen_direct_write = true;
3007 		return true;
3008 
3009 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3010 		if (t == BPF_WRITE)
3011 			env->seen_direct_write = true;
3012 
3013 		return true;
3014 
3015 	default:
3016 		return false;
3017 	}
3018 }
3019 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)3020 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3021 			       int size, bool zero_size_allowed)
3022 {
3023 	struct bpf_reg_state *regs = cur_regs(env);
3024 	struct bpf_reg_state *reg = &regs[regno];
3025 	int err;
3026 
3027 	/* We may have added a variable offset to the packet pointer; but any
3028 	 * reg->range we have comes after that.  We are only checking the fixed
3029 	 * offset.
3030 	 */
3031 
3032 	/* We don't allow negative numbers, because we aren't tracking enough
3033 	 * detail to prove they're safe.
3034 	 */
3035 	if (reg->smin_value < 0) {
3036 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3037 			regno);
3038 		return -EACCES;
3039 	}
3040 
3041 	err = reg->range < 0 ? -EINVAL :
3042 	      __check_mem_access(env, regno, off, size, reg->range,
3043 				 zero_size_allowed);
3044 	if (err) {
3045 		verbose(env, "R%d offset is outside of the packet\n", regno);
3046 		return err;
3047 	}
3048 
3049 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3050 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3051 	 * otherwise find_good_pkt_pointers would have refused to set range info
3052 	 * that __check_mem_access would have rejected this pkt access.
3053 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3054 	 */
3055 	env->prog->aux->max_pkt_offset =
3056 		max_t(u32, env->prog->aux->max_pkt_offset,
3057 		      off + reg->umax_value + size - 1);
3058 
3059 	return err;
3060 }
3061 
3062 /* 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)3063 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3064 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3065 			    u32 *btf_id)
3066 {
3067 	struct bpf_insn_access_aux info = {
3068 		.reg_type = *reg_type,
3069 		.log = &env->log,
3070 	};
3071 
3072 	if (env->ops->is_valid_access &&
3073 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3074 		/* A non zero info.ctx_field_size indicates that this field is a
3075 		 * candidate for later verifier transformation to load the whole
3076 		 * field and then apply a mask when accessed with a narrower
3077 		 * access than actual ctx access size. A zero info.ctx_field_size
3078 		 * will only allow for whole field access and rejects any other
3079 		 * type of narrower access.
3080 		 */
3081 		*reg_type = info.reg_type;
3082 
3083 		if (base_type(*reg_type) == PTR_TO_BTF_ID)
3084 			*btf_id = info.btf_id;
3085 		else
3086 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3087 		/* remember the offset of last byte accessed in ctx */
3088 		if (env->prog->aux->max_ctx_offset < off + size)
3089 			env->prog->aux->max_ctx_offset = off + size;
3090 		return 0;
3091 	}
3092 
3093 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3094 	return -EACCES;
3095 }
3096 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)3097 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3098 				  int size)
3099 {
3100 	if (size < 0 || off < 0 ||
3101 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3102 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3103 			off, size);
3104 		return -EACCES;
3105 	}
3106 	return 0;
3107 }
3108 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)3109 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3110 			     u32 regno, int off, int size,
3111 			     enum bpf_access_type t)
3112 {
3113 	struct bpf_reg_state *regs = cur_regs(env);
3114 	struct bpf_reg_state *reg = &regs[regno];
3115 	struct bpf_insn_access_aux info = {};
3116 	bool valid;
3117 
3118 	if (reg->smin_value < 0) {
3119 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3120 			regno);
3121 		return -EACCES;
3122 	}
3123 
3124 	switch (reg->type) {
3125 	case PTR_TO_SOCK_COMMON:
3126 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3127 		break;
3128 	case PTR_TO_SOCKET:
3129 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3130 		break;
3131 	case PTR_TO_TCP_SOCK:
3132 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3133 		break;
3134 	case PTR_TO_XDP_SOCK:
3135 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3136 		break;
3137 	default:
3138 		valid = false;
3139 	}
3140 
3141 
3142 	if (valid) {
3143 		env->insn_aux_data[insn_idx].ctx_field_size =
3144 			info.ctx_field_size;
3145 		return 0;
3146 	}
3147 
3148 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3149 		regno, reg_type_str(env, reg->type), off, size);
3150 
3151 	return -EACCES;
3152 }
3153 
is_pointer_value(struct bpf_verifier_env * env,int regno)3154 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3155 {
3156 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3157 }
3158 
is_ctx_reg(struct bpf_verifier_env * env,int regno)3159 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3160 {
3161 	const struct bpf_reg_state *reg = reg_state(env, regno);
3162 
3163 	return reg->type == PTR_TO_CTX;
3164 }
3165 
is_sk_reg(struct bpf_verifier_env * env,int regno)3166 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3167 {
3168 	const struct bpf_reg_state *reg = reg_state(env, regno);
3169 
3170 	return type_is_sk_pointer(reg->type);
3171 }
3172 
is_pkt_reg(struct bpf_verifier_env * env,int regno)3173 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3174 {
3175 	const struct bpf_reg_state *reg = reg_state(env, regno);
3176 
3177 	return type_is_pkt_pointer(reg->type);
3178 }
3179 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)3180 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3181 {
3182 	const struct bpf_reg_state *reg = reg_state(env, regno);
3183 
3184 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3185 	return reg->type == PTR_TO_FLOW_KEYS;
3186 }
3187 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)3188 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3189 				   const struct bpf_reg_state *reg,
3190 				   int off, int size, bool strict)
3191 {
3192 	struct tnum reg_off;
3193 	int ip_align;
3194 
3195 	/* Byte size accesses are always allowed. */
3196 	if (!strict || size == 1)
3197 		return 0;
3198 
3199 	/* For platforms that do not have a Kconfig enabling
3200 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3201 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3202 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3203 	 * to this code only in strict mode where we want to emulate
3204 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3205 	 * unconditional IP align value of '2'.
3206 	 */
3207 	ip_align = 2;
3208 
3209 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3210 	if (!tnum_is_aligned(reg_off, size)) {
3211 		char tn_buf[48];
3212 
3213 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3214 		verbose(env,
3215 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3216 			ip_align, tn_buf, reg->off, off, size);
3217 		return -EACCES;
3218 	}
3219 
3220 	return 0;
3221 }
3222 
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)3223 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3224 				       const struct bpf_reg_state *reg,
3225 				       const char *pointer_desc,
3226 				       int off, int size, bool strict)
3227 {
3228 	struct tnum reg_off;
3229 
3230 	/* Byte size accesses are always allowed. */
3231 	if (!strict || size == 1)
3232 		return 0;
3233 
3234 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3235 	if (!tnum_is_aligned(reg_off, size)) {
3236 		char tn_buf[48];
3237 
3238 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3239 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3240 			pointer_desc, tn_buf, reg->off, off, size);
3241 		return -EACCES;
3242 	}
3243 
3244 	return 0;
3245 }
3246 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)3247 static int check_ptr_alignment(struct bpf_verifier_env *env,
3248 			       const struct bpf_reg_state *reg, int off,
3249 			       int size, bool strict_alignment_once)
3250 {
3251 	bool strict = env->strict_alignment || strict_alignment_once;
3252 	const char *pointer_desc = "";
3253 
3254 	switch (reg->type) {
3255 	case PTR_TO_PACKET:
3256 	case PTR_TO_PACKET_META:
3257 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3258 		 * right in front, treat it the very same way.
3259 		 */
3260 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3261 	case PTR_TO_FLOW_KEYS:
3262 		pointer_desc = "flow keys ";
3263 		break;
3264 	case PTR_TO_MAP_VALUE:
3265 		pointer_desc = "value ";
3266 		break;
3267 	case PTR_TO_CTX:
3268 		pointer_desc = "context ";
3269 		break;
3270 	case PTR_TO_STACK:
3271 		pointer_desc = "stack ";
3272 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3273 		 * and check_stack_read_fixed_off() relies on stack accesses being
3274 		 * aligned.
3275 		 */
3276 		strict = true;
3277 		break;
3278 	case PTR_TO_SOCKET:
3279 		pointer_desc = "sock ";
3280 		break;
3281 	case PTR_TO_SOCK_COMMON:
3282 		pointer_desc = "sock_common ";
3283 		break;
3284 	case PTR_TO_TCP_SOCK:
3285 		pointer_desc = "tcp_sock ";
3286 		break;
3287 	case PTR_TO_XDP_SOCK:
3288 		pointer_desc = "xdp_sock ";
3289 		break;
3290 	default:
3291 		break;
3292 	}
3293 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3294 					   strict);
3295 }
3296 
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)3297 static int update_stack_depth(struct bpf_verifier_env *env,
3298 			      const struct bpf_func_state *func,
3299 			      int off)
3300 {
3301 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3302 
3303 	if (stack >= -off)
3304 		return 0;
3305 
3306 	/* update known max for given subprogram */
3307 	env->subprog_info[func->subprogno].stack_depth = -off;
3308 	return 0;
3309 }
3310 
3311 /* starting from main bpf function walk all instructions of the function
3312  * and recursively walk all callees that given function can call.
3313  * Ignore jump and exit insns.
3314  * Since recursion is prevented by check_cfg() this algorithm
3315  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3316  */
check_max_stack_depth(struct bpf_verifier_env * env)3317 static int check_max_stack_depth(struct bpf_verifier_env *env)
3318 {
3319 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3320 	struct bpf_subprog_info *subprog = env->subprog_info;
3321 	struct bpf_insn *insn = env->prog->insnsi;
3322 	bool tail_call_reachable = false;
3323 	int ret_insn[MAX_CALL_FRAMES];
3324 	int ret_prog[MAX_CALL_FRAMES];
3325 	int j;
3326 
3327 process_func:
3328 	/* protect against potential stack overflow that might happen when
3329 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3330 	 * depth for such case down to 256 so that the worst case scenario
3331 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3332 	 * 8k).
3333 	 *
3334 	 * To get the idea what might happen, see an example:
3335 	 * func1 -> sub rsp, 128
3336 	 *  subfunc1 -> sub rsp, 256
3337 	 *  tailcall1 -> add rsp, 256
3338 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3339 	 *   subfunc2 -> sub rsp, 64
3340 	 *   subfunc22 -> sub rsp, 128
3341 	 *   tailcall2 -> add rsp, 128
3342 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3343 	 *
3344 	 * tailcall will unwind the current stack frame but it will not get rid
3345 	 * of caller's stack as shown on the example above.
3346 	 */
3347 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3348 		verbose(env,
3349 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3350 			depth);
3351 		return -EACCES;
3352 	}
3353 	/* round up to 32-bytes, since this is granularity
3354 	 * of interpreter stack size
3355 	 */
3356 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3357 	if (depth > MAX_BPF_STACK) {
3358 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3359 			frame + 1, depth);
3360 		return -EACCES;
3361 	}
3362 continue_func:
3363 	subprog_end = subprog[idx + 1].start;
3364 	for (; i < subprog_end; i++) {
3365 		if (insn[i].code != (BPF_JMP | BPF_CALL))
3366 			continue;
3367 		if (insn[i].src_reg != BPF_PSEUDO_CALL)
3368 			continue;
3369 		/* remember insn and function to return to */
3370 		ret_insn[frame] = i + 1;
3371 		ret_prog[frame] = idx;
3372 
3373 		/* find the callee */
3374 		i = i + insn[i].imm + 1;
3375 		idx = find_subprog(env, i);
3376 		if (idx < 0) {
3377 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3378 				  i);
3379 			return -EFAULT;
3380 		}
3381 
3382 		if (subprog[idx].has_tail_call)
3383 			tail_call_reachable = true;
3384 
3385 		frame++;
3386 		if (frame >= MAX_CALL_FRAMES) {
3387 			verbose(env, "the call stack of %d frames is too deep !\n",
3388 				frame);
3389 			return -E2BIG;
3390 		}
3391 		goto process_func;
3392 	}
3393 	/* if tail call got detected across bpf2bpf calls then mark each of the
3394 	 * currently present subprog frames as tail call reachable subprogs;
3395 	 * this info will be utilized by JIT so that we will be preserving the
3396 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3397 	 */
3398 	if (tail_call_reachable)
3399 		for (j = 0; j < frame; j++)
3400 			subprog[ret_prog[j]].tail_call_reachable = true;
3401 	if (subprog[0].tail_call_reachable)
3402 		env->prog->aux->tail_call_reachable = true;
3403 
3404 	/* end of for() loop means the last insn of the 'subprog'
3405 	 * was reached. Doesn't matter whether it was JA or EXIT
3406 	 */
3407 	if (frame == 0)
3408 		return 0;
3409 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3410 	frame--;
3411 	i = ret_insn[frame];
3412 	idx = ret_prog[frame];
3413 	goto continue_func;
3414 }
3415 
3416 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)3417 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3418 				  const struct bpf_insn *insn, int idx)
3419 {
3420 	int start = idx + insn->imm + 1, subprog;
3421 
3422 	subprog = find_subprog(env, start);
3423 	if (subprog < 0) {
3424 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3425 			  start);
3426 		return -EFAULT;
3427 	}
3428 	return env->subprog_info[subprog].stack_depth;
3429 }
3430 #endif
3431 
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)3432 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3433 			       const struct bpf_reg_state *reg, int regno,
3434 			       bool fixed_off_ok)
3435 {
3436 	/* Access to this pointer-typed register or passing it to a helper
3437 	 * is only allowed in its original, unmodified form.
3438 	 */
3439 
3440 	if (!fixed_off_ok && reg->off) {
3441 		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3442 			reg_type_str(env, reg->type), regno, reg->off);
3443 		return -EACCES;
3444 	}
3445 
3446 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3447 		char tn_buf[48];
3448 
3449 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3450 		verbose(env, "variable %s access var_off=%s disallowed\n",
3451 			reg_type_str(env, reg->type), tn_buf);
3452 		return -EACCES;
3453 	}
3454 
3455 	return 0;
3456 }
3457 
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3458 int check_ptr_off_reg(struct bpf_verifier_env *env,
3459 		      const struct bpf_reg_state *reg, int regno)
3460 {
3461 	return __check_ptr_off_reg(env, reg, regno, false);
3462 }
3463 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)3464 static int __check_buffer_access(struct bpf_verifier_env *env,
3465 				 const char *buf_info,
3466 				 const struct bpf_reg_state *reg,
3467 				 int regno, int off, int size)
3468 {
3469 	if (off < 0) {
3470 		verbose(env,
3471 			"R%d invalid %s buffer access: off=%d, size=%d\n",
3472 			regno, buf_info, off, size);
3473 		return -EACCES;
3474 	}
3475 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3476 		char tn_buf[48];
3477 
3478 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3479 		verbose(env,
3480 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3481 			regno, off, tn_buf);
3482 		return -EACCES;
3483 	}
3484 
3485 	return 0;
3486 }
3487 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)3488 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3489 				  const struct bpf_reg_state *reg,
3490 				  int regno, int off, int size)
3491 {
3492 	int err;
3493 
3494 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3495 	if (err)
3496 		return err;
3497 
3498 	if (off + size > env->prog->aux->max_tp_access)
3499 		env->prog->aux->max_tp_access = off + size;
3500 
3501 	return 0;
3502 }
3503 
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)3504 static int check_buffer_access(struct bpf_verifier_env *env,
3505 			       const struct bpf_reg_state *reg,
3506 			       int regno, int off, int size,
3507 			       bool zero_size_allowed,
3508 			       const char *buf_info,
3509 			       u32 *max_access)
3510 {
3511 	int err;
3512 
3513 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3514 	if (err)
3515 		return err;
3516 
3517 	if (off + size > *max_access)
3518 		*max_access = off + size;
3519 
3520 	return 0;
3521 }
3522 
3523 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)3524 static void zext_32_to_64(struct bpf_reg_state *reg)
3525 {
3526 	reg->var_off = tnum_subreg(reg->var_off);
3527 	__reg_assign_32_into_64(reg);
3528 }
3529 
3530 /* truncate register to smaller size (in bytes)
3531  * must be called with size < BPF_REG_SIZE
3532  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)3533 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3534 {
3535 	u64 mask;
3536 
3537 	/* clear high bits in bit representation */
3538 	reg->var_off = tnum_cast(reg->var_off, size);
3539 
3540 	/* fix arithmetic bounds */
3541 	mask = ((u64)1 << (size * 8)) - 1;
3542 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3543 		reg->umin_value &= mask;
3544 		reg->umax_value &= mask;
3545 	} else {
3546 		reg->umin_value = 0;
3547 		reg->umax_value = mask;
3548 	}
3549 	reg->smin_value = reg->umin_value;
3550 	reg->smax_value = reg->umax_value;
3551 
3552 	/* If size is smaller than 32bit register the 32bit register
3553 	 * values are also truncated so we push 64-bit bounds into
3554 	 * 32-bit bounds. Above were truncated < 32-bits already.
3555 	 */
3556 	if (size >= 4)
3557 		return;
3558 	__reg_combine_64_into_32(reg);
3559 }
3560 
bpf_map_is_rdonly(const struct bpf_map * map)3561 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3562 {
3563 	/* A map is considered read-only if the following condition are true:
3564 	 *
3565 	 * 1) BPF program side cannot change any of the map content. The
3566 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3567 	 *    and was set at map creation time.
3568 	 * 2) The map value(s) have been initialized from user space by a
3569 	 *    loader and then "frozen", such that no new map update/delete
3570 	 *    operations from syscall side are possible for the rest of
3571 	 *    the map's lifetime from that point onwards.
3572 	 * 3) Any parallel/pending map update/delete operations from syscall
3573 	 *    side have been completed. Only after that point, it's safe to
3574 	 *    assume that map value(s) are immutable.
3575 	 */
3576 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
3577 	       READ_ONCE(map->frozen) &&
3578 	       !bpf_map_write_active(map);
3579 }
3580 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)3581 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3582 {
3583 	void *ptr;
3584 	u64 addr;
3585 	int err;
3586 
3587 	err = map->ops->map_direct_value_addr(map, &addr, off);
3588 	if (err)
3589 		return err;
3590 	ptr = (void *)(long)addr + off;
3591 
3592 	switch (size) {
3593 	case sizeof(u8):
3594 		*val = (u64)*(u8 *)ptr;
3595 		break;
3596 	case sizeof(u16):
3597 		*val = (u64)*(u16 *)ptr;
3598 		break;
3599 	case sizeof(u32):
3600 		*val = (u64)*(u32 *)ptr;
3601 		break;
3602 	case sizeof(u64):
3603 		*val = *(u64 *)ptr;
3604 		break;
3605 	default:
3606 		return -EINVAL;
3607 	}
3608 	return 0;
3609 }
3610 
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)3611 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3612 				   struct bpf_reg_state *regs,
3613 				   int regno, int off, int size,
3614 				   enum bpf_access_type atype,
3615 				   int value_regno)
3616 {
3617 	struct bpf_reg_state *reg = regs + regno;
3618 	const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3619 	const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3620 	u32 btf_id;
3621 	int ret;
3622 
3623 	if (off < 0) {
3624 		verbose(env,
3625 			"R%d is ptr_%s invalid negative access: off=%d\n",
3626 			regno, tname, off);
3627 		return -EACCES;
3628 	}
3629 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3630 		char tn_buf[48];
3631 
3632 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3633 		verbose(env,
3634 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3635 			regno, tname, off, tn_buf);
3636 		return -EACCES;
3637 	}
3638 
3639 	if (env->ops->btf_struct_access) {
3640 		ret = env->ops->btf_struct_access(&env->log, t, off, size,
3641 						  atype, &btf_id);
3642 	} else {
3643 		if (atype != BPF_READ) {
3644 			verbose(env, "only read is supported\n");
3645 			return -EACCES;
3646 		}
3647 
3648 		ret = btf_struct_access(&env->log, t, off, size, atype,
3649 					&btf_id);
3650 	}
3651 
3652 	if (ret < 0)
3653 		return ret;
3654 
3655 	if (atype == BPF_READ && value_regno >= 0)
3656 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3657 
3658 	return 0;
3659 }
3660 
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)3661 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3662 				   struct bpf_reg_state *regs,
3663 				   int regno, int off, int size,
3664 				   enum bpf_access_type atype,
3665 				   int value_regno)
3666 {
3667 	struct bpf_reg_state *reg = regs + regno;
3668 	struct bpf_map *map = reg->map_ptr;
3669 	const struct btf_type *t;
3670 	const char *tname;
3671 	u32 btf_id;
3672 	int ret;
3673 
3674 	if (!btf_vmlinux) {
3675 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3676 		return -ENOTSUPP;
3677 	}
3678 
3679 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3680 		verbose(env, "map_ptr access not supported for map type %d\n",
3681 			map->map_type);
3682 		return -ENOTSUPP;
3683 	}
3684 
3685 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3686 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3687 
3688 	if (!env->allow_ptr_to_map_access) {
3689 		verbose(env,
3690 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3691 			tname);
3692 		return -EPERM;
3693 	}
3694 
3695 	if (off < 0) {
3696 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
3697 			regno, tname, off);
3698 		return -EACCES;
3699 	}
3700 
3701 	if (atype != BPF_READ) {
3702 		verbose(env, "only read from %s is supported\n", tname);
3703 		return -EACCES;
3704 	}
3705 
3706 	ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3707 	if (ret < 0)
3708 		return ret;
3709 
3710 	if (value_regno >= 0)
3711 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3712 
3713 	return 0;
3714 }
3715 
3716 /* Check that the stack access at the given offset is within bounds. The
3717  * maximum valid offset is -1.
3718  *
3719  * The minimum valid offset is -MAX_BPF_STACK for writes, and
3720  * -state->allocated_stack for reads.
3721  */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)3722 static int check_stack_slot_within_bounds(int off,
3723 					  struct bpf_func_state *state,
3724 					  enum bpf_access_type t)
3725 {
3726 	int min_valid_off;
3727 
3728 	if (t == BPF_WRITE)
3729 		min_valid_off = -MAX_BPF_STACK;
3730 	else
3731 		min_valid_off = -state->allocated_stack;
3732 
3733 	if (off < min_valid_off || off > -1)
3734 		return -EACCES;
3735 	return 0;
3736 }
3737 
3738 /* Check that the stack access at 'regno + off' falls within the maximum stack
3739  * bounds.
3740  *
3741  * 'off' includes `regno->offset`, but not its dynamic part (if any).
3742  */
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)3743 static int check_stack_access_within_bounds(
3744 		struct bpf_verifier_env *env,
3745 		int regno, int off, int access_size,
3746 		enum stack_access_src src, enum bpf_access_type type)
3747 {
3748 	struct bpf_reg_state *regs = cur_regs(env);
3749 	struct bpf_reg_state *reg = regs + regno;
3750 	struct bpf_func_state *state = func(env, reg);
3751 	int min_off, max_off;
3752 	int err;
3753 	char *err_extra;
3754 
3755 	if (src == ACCESS_HELPER)
3756 		/* We don't know if helpers are reading or writing (or both). */
3757 		err_extra = " indirect access to";
3758 	else if (type == BPF_READ)
3759 		err_extra = " read from";
3760 	else
3761 		err_extra = " write to";
3762 
3763 	if (tnum_is_const(reg->var_off)) {
3764 		min_off = reg->var_off.value + off;
3765 		if (access_size > 0)
3766 			max_off = min_off + access_size - 1;
3767 		else
3768 			max_off = min_off;
3769 	} else {
3770 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3771 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
3772 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3773 				err_extra, regno);
3774 			return -EACCES;
3775 		}
3776 		min_off = reg->smin_value + off;
3777 		if (access_size > 0)
3778 			max_off = reg->smax_value + off + access_size - 1;
3779 		else
3780 			max_off = min_off;
3781 	}
3782 
3783 	err = check_stack_slot_within_bounds(min_off, state, type);
3784 	if (!err)
3785 		err = check_stack_slot_within_bounds(max_off, state, type);
3786 
3787 	if (err) {
3788 		if (tnum_is_const(reg->var_off)) {
3789 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3790 				err_extra, regno, off, access_size);
3791 		} else {
3792 			char tn_buf[48];
3793 
3794 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3795 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3796 				err_extra, regno, tn_buf, access_size);
3797 		}
3798 	}
3799 	return err;
3800 }
3801 
3802 /* check whether memory at (regno + off) is accessible for t = (read | write)
3803  * if t==write, value_regno is a register which value is stored into memory
3804  * if t==read, value_regno is a register which will receive the value from memory
3805  * if t==write && value_regno==-1, some unknown value is stored into memory
3806  * if t==read && value_regno==-1, don't care what we read from memory
3807  */
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)3808 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3809 			    int off, int bpf_size, enum bpf_access_type t,
3810 			    int value_regno, bool strict_alignment_once)
3811 {
3812 	struct bpf_reg_state *regs = cur_regs(env);
3813 	struct bpf_reg_state *reg = regs + regno;
3814 	struct bpf_func_state *state;
3815 	int size, err = 0;
3816 
3817 	size = bpf_size_to_bytes(bpf_size);
3818 	if (size < 0)
3819 		return size;
3820 
3821 	/* alignment checks will add in reg->off themselves */
3822 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3823 	if (err)
3824 		return err;
3825 
3826 	/* for access checks, reg->off is just part of off */
3827 	off += reg->off;
3828 
3829 	if (reg->type == PTR_TO_MAP_VALUE) {
3830 		if (t == BPF_WRITE && value_regno >= 0 &&
3831 		    is_pointer_value(env, value_regno)) {
3832 			verbose(env, "R%d leaks addr into map\n", value_regno);
3833 			return -EACCES;
3834 		}
3835 		err = check_map_access_type(env, regno, off, size, t);
3836 		if (err)
3837 			return err;
3838 		err = check_map_access(env, regno, off, size, false);
3839 		if (!err && t == BPF_READ && value_regno >= 0) {
3840 			struct bpf_map *map = reg->map_ptr;
3841 
3842 			/* if map is read-only, track its contents as scalars */
3843 			if (tnum_is_const(reg->var_off) &&
3844 			    bpf_map_is_rdonly(map) &&
3845 			    map->ops->map_direct_value_addr) {
3846 				int map_off = off + reg->var_off.value;
3847 				u64 val = 0;
3848 
3849 				err = bpf_map_direct_read(map, map_off, size,
3850 							  &val);
3851 				if (err)
3852 					return err;
3853 
3854 				regs[value_regno].type = SCALAR_VALUE;
3855 				__mark_reg_known(&regs[value_regno], val);
3856 			} else {
3857 				mark_reg_unknown(env, regs, value_regno);
3858 			}
3859 		}
3860 	} else if (base_type(reg->type) == PTR_TO_MEM) {
3861 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
3862 
3863 		if (type_may_be_null(reg->type)) {
3864 			verbose(env, "R%d invalid mem access '%s'\n", regno,
3865 				reg_type_str(env, reg->type));
3866 			return -EACCES;
3867 		}
3868 
3869 		if (t == BPF_WRITE && rdonly_mem) {
3870 			verbose(env, "R%d cannot write into %s\n",
3871 				regno, reg_type_str(env, reg->type));
3872 			return -EACCES;
3873 		}
3874 
3875 		if (t == BPF_WRITE && value_regno >= 0 &&
3876 		    is_pointer_value(env, value_regno)) {
3877 			verbose(env, "R%d leaks addr into mem\n", value_regno);
3878 			return -EACCES;
3879 		}
3880 
3881 		err = check_mem_region_access(env, regno, off, size,
3882 					      reg->mem_size, false);
3883 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
3884 			mark_reg_unknown(env, regs, value_regno);
3885 	} else if (reg->type == PTR_TO_CTX) {
3886 		enum bpf_reg_type reg_type = SCALAR_VALUE;
3887 		u32 btf_id = 0;
3888 
3889 		if (t == BPF_WRITE && value_regno >= 0 &&
3890 		    is_pointer_value(env, value_regno)) {
3891 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
3892 			return -EACCES;
3893 		}
3894 
3895 		err = check_ptr_off_reg(env, reg, regno);
3896 		if (err < 0)
3897 			return err;
3898 
3899 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3900 		if (err)
3901 			verbose_linfo(env, insn_idx, "; ");
3902 		if (!err && t == BPF_READ && value_regno >= 0) {
3903 			/* ctx access returns either a scalar, or a
3904 			 * PTR_TO_PACKET[_META,_END]. In the latter
3905 			 * case, we know the offset is zero.
3906 			 */
3907 			if (reg_type == SCALAR_VALUE) {
3908 				mark_reg_unknown(env, regs, value_regno);
3909 			} else {
3910 				mark_reg_known_zero(env, regs,
3911 						    value_regno);
3912 				if (type_may_be_null(reg_type))
3913 					regs[value_regno].id = ++env->id_gen;
3914 				/* A load of ctx field could have different
3915 				 * actual load size with the one encoded in the
3916 				 * insn. When the dst is PTR, it is for sure not
3917 				 * a sub-register.
3918 				 */
3919 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3920 				if (base_type(reg_type) == PTR_TO_BTF_ID)
3921 					regs[value_regno].btf_id = btf_id;
3922 			}
3923 			regs[value_regno].type = reg_type;
3924 		}
3925 
3926 	} else if (reg->type == PTR_TO_STACK) {
3927 		/* Basic bounds checks. */
3928 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3929 		if (err)
3930 			return err;
3931 
3932 		state = func(env, reg);
3933 		err = update_stack_depth(env, state, off);
3934 		if (err)
3935 			return err;
3936 
3937 		if (t == BPF_READ)
3938 			err = check_stack_read(env, regno, off, size,
3939 					       value_regno);
3940 		else
3941 			err = check_stack_write(env, regno, off, size,
3942 						value_regno, insn_idx);
3943 	} else if (reg_is_pkt_pointer(reg)) {
3944 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3945 			verbose(env, "cannot write into packet\n");
3946 			return -EACCES;
3947 		}
3948 		if (t == BPF_WRITE && value_regno >= 0 &&
3949 		    is_pointer_value(env, value_regno)) {
3950 			verbose(env, "R%d leaks addr into packet\n",
3951 				value_regno);
3952 			return -EACCES;
3953 		}
3954 		err = check_packet_access(env, regno, off, size, false);
3955 		if (!err && t == BPF_READ && value_regno >= 0)
3956 			mark_reg_unknown(env, regs, value_regno);
3957 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
3958 		if (t == BPF_WRITE && value_regno >= 0 &&
3959 		    is_pointer_value(env, value_regno)) {
3960 			verbose(env, "R%d leaks addr into flow keys\n",
3961 				value_regno);
3962 			return -EACCES;
3963 		}
3964 
3965 		err = check_flow_keys_access(env, off, size);
3966 		if (!err && t == BPF_READ && value_regno >= 0)
3967 			mark_reg_unknown(env, regs, value_regno);
3968 	} else if (type_is_sk_pointer(reg->type)) {
3969 		if (t == BPF_WRITE) {
3970 			verbose(env, "R%d cannot write into %s\n",
3971 				regno, reg_type_str(env, reg->type));
3972 			return -EACCES;
3973 		}
3974 		err = check_sock_access(env, insn_idx, regno, off, size, t);
3975 		if (!err && value_regno >= 0)
3976 			mark_reg_unknown(env, regs, value_regno);
3977 	} else if (reg->type == PTR_TO_TP_BUFFER) {
3978 		err = check_tp_buffer_access(env, reg, regno, off, size);
3979 		if (!err && t == BPF_READ && value_regno >= 0)
3980 			mark_reg_unknown(env, regs, value_regno);
3981 	} else if (reg->type == PTR_TO_BTF_ID) {
3982 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3983 					      value_regno);
3984 	} else if (reg->type == CONST_PTR_TO_MAP) {
3985 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3986 					      value_regno);
3987 	} else if (base_type(reg->type) == PTR_TO_BUF) {
3988 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
3989 		const char *buf_info;
3990 		u32 *max_access;
3991 
3992 		if (rdonly_mem) {
3993 			if (t == BPF_WRITE) {
3994 				verbose(env, "R%d cannot write into %s\n",
3995 						regno, reg_type_str(env, reg->type));
3996 				return -EACCES;
3997 			}
3998 			buf_info = "rdonly";
3999 			max_access = &env->prog->aux->max_rdonly_access;
4000 		} else {
4001 			buf_info = "rdwr";
4002 			max_access = &env->prog->aux->max_rdwr_access;
4003 		}
4004 
4005 		err = check_buffer_access(env, reg, regno, off, size, false,
4006 					  buf_info, max_access);
4007 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4008 			mark_reg_unknown(env, regs, value_regno);
4009 	} else {
4010 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4011 			reg_type_str(env, reg->type));
4012 		return -EACCES;
4013 	}
4014 
4015 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4016 	    regs[value_regno].type == SCALAR_VALUE) {
4017 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4018 		coerce_reg_to_size(&regs[value_regno], size);
4019 	}
4020 	return err;
4021 }
4022 
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)4023 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4024 {
4025 	int err;
4026 
4027 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
4028 	    insn->imm != 0) {
4029 		verbose(env, "BPF_XADD uses reserved fields\n");
4030 		return -EINVAL;
4031 	}
4032 
4033 	/* check src1 operand */
4034 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4035 	if (err)
4036 		return err;
4037 
4038 	/* check src2 operand */
4039 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4040 	if (err)
4041 		return err;
4042 
4043 	if (is_pointer_value(env, insn->src_reg)) {
4044 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4045 		return -EACCES;
4046 	}
4047 
4048 	if (is_ctx_reg(env, insn->dst_reg) ||
4049 	    is_pkt_reg(env, insn->dst_reg) ||
4050 	    is_flow_key_reg(env, insn->dst_reg) ||
4051 	    is_sk_reg(env, insn->dst_reg)) {
4052 		verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
4053 			insn->dst_reg,
4054 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4055 		return -EACCES;
4056 	}
4057 
4058 	/* check whether atomic_add can read the memory */
4059 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4060 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4061 	if (err)
4062 		return err;
4063 
4064 	/* check whether atomic_add can write into the same memory */
4065 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4066 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4067 }
4068 
4069 /* When register 'regno' is used to read the stack (either directly or through
4070  * a helper function) make sure that it's within stack boundary and, depending
4071  * on the access type, that all elements of the stack are initialized.
4072  *
4073  * 'off' includes 'regno->off', but not its dynamic part (if any).
4074  *
4075  * All registers that have been spilled on the stack in the slots within the
4076  * read offsets are marked as read.
4077  */
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)4078 static int check_stack_range_initialized(
4079 		struct bpf_verifier_env *env, int regno, int off,
4080 		int access_size, bool zero_size_allowed,
4081 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4082 {
4083 	struct bpf_reg_state *reg = reg_state(env, regno);
4084 	struct bpf_func_state *state = func(env, reg);
4085 	int err, min_off, max_off, i, j, slot, spi;
4086 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4087 	enum bpf_access_type bounds_check_type;
4088 	/* Some accesses can write anything into the stack, others are
4089 	 * read-only.
4090 	 */
4091 	bool clobber = false;
4092 
4093 	if (access_size == 0 && !zero_size_allowed) {
4094 		verbose(env, "invalid zero-sized read\n");
4095 		return -EACCES;
4096 	}
4097 
4098 	if (type == ACCESS_HELPER) {
4099 		/* The bounds checks for writes are more permissive than for
4100 		 * reads. However, if raw_mode is not set, we'll do extra
4101 		 * checks below.
4102 		 */
4103 		bounds_check_type = BPF_WRITE;
4104 		clobber = true;
4105 	} else {
4106 		bounds_check_type = BPF_READ;
4107 	}
4108 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4109 					       type, bounds_check_type);
4110 	if (err)
4111 		return err;
4112 
4113 
4114 	if (tnum_is_const(reg->var_off)) {
4115 		min_off = max_off = reg->var_off.value + off;
4116 	} else {
4117 		/* Variable offset is prohibited for unprivileged mode for
4118 		 * simplicity since it requires corresponding support in
4119 		 * Spectre masking for stack ALU.
4120 		 * See also retrieve_ptr_limit().
4121 		 */
4122 		if (!env->bypass_spec_v1) {
4123 			char tn_buf[48];
4124 
4125 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4126 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4127 				regno, err_extra, tn_buf);
4128 			return -EACCES;
4129 		}
4130 		/* Only initialized buffer on stack is allowed to be accessed
4131 		 * with variable offset. With uninitialized buffer it's hard to
4132 		 * guarantee that whole memory is marked as initialized on
4133 		 * helper return since specific bounds are unknown what may
4134 		 * cause uninitialized stack leaking.
4135 		 */
4136 		if (meta && meta->raw_mode)
4137 			meta = NULL;
4138 
4139 		min_off = reg->smin_value + off;
4140 		max_off = reg->smax_value + off;
4141 	}
4142 
4143 	if (meta && meta->raw_mode) {
4144 		meta->access_size = access_size;
4145 		meta->regno = regno;
4146 		return 0;
4147 	}
4148 
4149 	for (i = min_off; i < max_off + access_size; i++) {
4150 		u8 *stype;
4151 
4152 		slot = -i - 1;
4153 		spi = slot / BPF_REG_SIZE;
4154 		if (state->allocated_stack <= slot)
4155 			goto err;
4156 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4157 		if (*stype == STACK_MISC)
4158 			goto mark;
4159 		if (*stype == STACK_ZERO) {
4160 			if (clobber) {
4161 				/* helper can write anything into the stack */
4162 				*stype = STACK_MISC;
4163 			}
4164 			goto mark;
4165 		}
4166 
4167 		if (is_spilled_reg(&state->stack[spi]) &&
4168 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4169 			goto mark;
4170 
4171 		if (is_spilled_reg(&state->stack[spi]) &&
4172 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4173 		     env->allow_ptr_leaks)) {
4174 			if (clobber) {
4175 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4176 				for (j = 0; j < BPF_REG_SIZE; j++)
4177 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4178 			}
4179 			goto mark;
4180 		}
4181 
4182 err:
4183 		if (tnum_is_const(reg->var_off)) {
4184 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4185 				err_extra, regno, min_off, i - min_off, access_size);
4186 		} else {
4187 			char tn_buf[48];
4188 
4189 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4190 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4191 				err_extra, regno, tn_buf, i - min_off, access_size);
4192 		}
4193 		return -EACCES;
4194 mark:
4195 		/* reading any byte out of 8-byte 'spill_slot' will cause
4196 		 * the whole slot to be marked as 'read'
4197 		 */
4198 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4199 			      state->stack[spi].spilled_ptr.parent,
4200 			      REG_LIVE_READ64);
4201 	}
4202 	return update_stack_depth(env, state, min_off);
4203 }
4204 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)4205 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4206 				   int access_size, bool zero_size_allowed,
4207 				   struct bpf_call_arg_meta *meta)
4208 {
4209 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4210 	const char *buf_info;
4211 	u32 *max_access;
4212 
4213 	switch (base_type(reg->type)) {
4214 	case PTR_TO_PACKET:
4215 	case PTR_TO_PACKET_META:
4216 		return check_packet_access(env, regno, reg->off, access_size,
4217 					   zero_size_allowed);
4218 	case PTR_TO_MAP_VALUE:
4219 		if (check_map_access_type(env, regno, reg->off, access_size,
4220 					  meta && meta->raw_mode ? BPF_WRITE :
4221 					  BPF_READ))
4222 			return -EACCES;
4223 		return check_map_access(env, regno, reg->off, access_size,
4224 					zero_size_allowed);
4225 	case PTR_TO_MEM:
4226 		return check_mem_region_access(env, regno, reg->off,
4227 					       access_size, reg->mem_size,
4228 					       zero_size_allowed);
4229 	case PTR_TO_BUF:
4230 		if (type_is_rdonly_mem(reg->type)) {
4231 			if (meta && meta->raw_mode)
4232 				return -EACCES;
4233 
4234 			buf_info = "rdonly";
4235 			max_access = &env->prog->aux->max_rdonly_access;
4236 		} else {
4237 			buf_info = "rdwr";
4238 			max_access = &env->prog->aux->max_rdwr_access;
4239 		}
4240 		return check_buffer_access(env, reg, regno, reg->off,
4241 					   access_size, zero_size_allowed,
4242 					   buf_info, max_access);
4243 	case PTR_TO_STACK:
4244 		return check_stack_range_initialized(
4245 				env,
4246 				regno, reg->off, access_size,
4247 				zero_size_allowed, ACCESS_HELPER, meta);
4248 	default: /* scalar_value or invalid ptr */
4249 		/* Allow zero-byte read from NULL, regardless of pointer type */
4250 		if (zero_size_allowed && access_size == 0 &&
4251 		    register_is_null(reg))
4252 			return 0;
4253 
4254 		verbose(env, "R%d type=%s ", regno,
4255 			reg_type_str(env, reg->type));
4256 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4257 		return -EACCES;
4258 	}
4259 }
4260 
4261 /* Implementation details:
4262  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4263  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4264  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4265  * value_or_null->value transition, since the verifier only cares about
4266  * the range of access to valid map value pointer and doesn't care about actual
4267  * address of the map element.
4268  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4269  * reg->id > 0 after value_or_null->value transition. By doing so
4270  * two bpf_map_lookups will be considered two different pointers that
4271  * point to different bpf_spin_locks.
4272  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4273  * dead-locks.
4274  * Since only one bpf_spin_lock is allowed the checks are simpler than
4275  * reg_is_refcounted() logic. The verifier needs to remember only
4276  * one spin_lock instead of array of acquired_refs.
4277  * cur_state->active_spin_lock remembers which map value element got locked
4278  * and clears it after bpf_spin_unlock.
4279  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)4280 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4281 			     bool is_lock)
4282 {
4283 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4284 	struct bpf_verifier_state *cur = env->cur_state;
4285 	bool is_const = tnum_is_const(reg->var_off);
4286 	struct bpf_map *map = reg->map_ptr;
4287 	u64 val = reg->var_off.value;
4288 
4289 	if (!is_const) {
4290 		verbose(env,
4291 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4292 			regno);
4293 		return -EINVAL;
4294 	}
4295 	if (!map->btf) {
4296 		verbose(env,
4297 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4298 			map->name);
4299 		return -EINVAL;
4300 	}
4301 	if (!map_value_has_spin_lock(map)) {
4302 		if (map->spin_lock_off == -E2BIG)
4303 			verbose(env,
4304 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4305 				map->name);
4306 		else if (map->spin_lock_off == -ENOENT)
4307 			verbose(env,
4308 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4309 				map->name);
4310 		else
4311 			verbose(env,
4312 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4313 				map->name);
4314 		return -EINVAL;
4315 	}
4316 	if (map->spin_lock_off != val + reg->off) {
4317 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4318 			val + reg->off);
4319 		return -EINVAL;
4320 	}
4321 	if (is_lock) {
4322 		if (cur->active_spin_lock) {
4323 			verbose(env,
4324 				"Locking two bpf_spin_locks are not allowed\n");
4325 			return -EINVAL;
4326 		}
4327 		cur->active_spin_lock = reg->id;
4328 	} else {
4329 		if (!cur->active_spin_lock) {
4330 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4331 			return -EINVAL;
4332 		}
4333 		if (cur->active_spin_lock != reg->id) {
4334 			verbose(env, "bpf_spin_unlock of different lock\n");
4335 			return -EINVAL;
4336 		}
4337 		cur->active_spin_lock = 0;
4338 	}
4339 	return 0;
4340 }
4341 
arg_type_is_mem_ptr(enum bpf_arg_type type)4342 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4343 {
4344 	return base_type(type) == ARG_PTR_TO_MEM ||
4345 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
4346 }
4347 
arg_type_is_mem_size(enum bpf_arg_type type)4348 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4349 {
4350 	return type == ARG_CONST_SIZE ||
4351 	       type == ARG_CONST_SIZE_OR_ZERO;
4352 }
4353 
arg_type_is_alloc_size(enum bpf_arg_type type)4354 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4355 {
4356 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4357 }
4358 
arg_type_is_int_ptr(enum bpf_arg_type type)4359 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4360 {
4361 	return type == ARG_PTR_TO_INT ||
4362 	       type == ARG_PTR_TO_LONG;
4363 }
4364 
int_ptr_type_to_size(enum bpf_arg_type type)4365 static int int_ptr_type_to_size(enum bpf_arg_type type)
4366 {
4367 	if (type == ARG_PTR_TO_INT)
4368 		return sizeof(u32);
4369 	else if (type == ARG_PTR_TO_LONG)
4370 		return sizeof(u64);
4371 
4372 	return -EINVAL;
4373 }
4374 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)4375 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4376 				 const struct bpf_call_arg_meta *meta,
4377 				 enum bpf_arg_type *arg_type)
4378 {
4379 	if (!meta->map_ptr) {
4380 		/* kernel subsystem misconfigured verifier */
4381 		verbose(env, "invalid map_ptr to access map->type\n");
4382 		return -EACCES;
4383 	}
4384 
4385 	switch (meta->map_ptr->map_type) {
4386 	case BPF_MAP_TYPE_SOCKMAP:
4387 	case BPF_MAP_TYPE_SOCKHASH:
4388 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4389 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4390 		} else {
4391 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
4392 			return -EINVAL;
4393 		}
4394 		break;
4395 
4396 	default:
4397 		break;
4398 	}
4399 	return 0;
4400 }
4401 
4402 struct bpf_reg_types {
4403 	const enum bpf_reg_type types[10];
4404 	u32 *btf_id;
4405 };
4406 
4407 static const struct bpf_reg_types map_key_value_types = {
4408 	.types = {
4409 		PTR_TO_STACK,
4410 		PTR_TO_PACKET,
4411 		PTR_TO_PACKET_META,
4412 		PTR_TO_MAP_VALUE,
4413 	},
4414 };
4415 
4416 static const struct bpf_reg_types sock_types = {
4417 	.types = {
4418 		PTR_TO_SOCK_COMMON,
4419 		PTR_TO_SOCKET,
4420 		PTR_TO_TCP_SOCK,
4421 		PTR_TO_XDP_SOCK,
4422 	},
4423 };
4424 
4425 #ifdef CONFIG_NET
4426 static const struct bpf_reg_types btf_id_sock_common_types = {
4427 	.types = {
4428 		PTR_TO_SOCK_COMMON,
4429 		PTR_TO_SOCKET,
4430 		PTR_TO_TCP_SOCK,
4431 		PTR_TO_XDP_SOCK,
4432 		PTR_TO_BTF_ID,
4433 	},
4434 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4435 };
4436 #endif
4437 
4438 static const struct bpf_reg_types mem_types = {
4439 	.types = {
4440 		PTR_TO_STACK,
4441 		PTR_TO_PACKET,
4442 		PTR_TO_PACKET_META,
4443 		PTR_TO_MAP_VALUE,
4444 		PTR_TO_MEM,
4445 		PTR_TO_MEM | MEM_ALLOC,
4446 		PTR_TO_BUF,
4447 	},
4448 };
4449 
4450 static const struct bpf_reg_types int_ptr_types = {
4451 	.types = {
4452 		PTR_TO_STACK,
4453 		PTR_TO_PACKET,
4454 		PTR_TO_PACKET_META,
4455 		PTR_TO_MAP_VALUE,
4456 	},
4457 };
4458 
4459 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4460 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4461 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4462 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
4463 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4464 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4465 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4466 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4467 
4468 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4469 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
4470 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
4471 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
4472 	[ARG_CONST_SIZE]		= &scalar_types,
4473 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
4474 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
4475 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
4476 	[ARG_PTR_TO_CTX]		= &context_types,
4477 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
4478 #ifdef CONFIG_NET
4479 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
4480 #endif
4481 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
4482 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
4483 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
4484 	[ARG_PTR_TO_MEM]		= &mem_types,
4485 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
4486 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
4487 	[ARG_PTR_TO_INT]		= &int_ptr_types,
4488 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
4489 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
4490 };
4491 
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id)4492 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4493 			  enum bpf_arg_type arg_type,
4494 			  const u32 *arg_btf_id)
4495 {
4496 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4497 	enum bpf_reg_type expected, type = reg->type;
4498 	const struct bpf_reg_types *compatible;
4499 	int i, j;
4500 
4501 	compatible = compatible_reg_types[base_type(arg_type)];
4502 	if (!compatible) {
4503 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4504 		return -EFAULT;
4505 	}
4506 
4507 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
4508 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
4509 	 *
4510 	 * Same for MAYBE_NULL:
4511 	 *
4512 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
4513 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
4514 	 *
4515 	 * Therefore we fold these flags depending on the arg_type before comparison.
4516 	 */
4517 	if (arg_type & MEM_RDONLY)
4518 		type &= ~MEM_RDONLY;
4519 	if (arg_type & PTR_MAYBE_NULL)
4520 		type &= ~PTR_MAYBE_NULL;
4521 
4522 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4523 		expected = compatible->types[i];
4524 		if (expected == NOT_INIT)
4525 			break;
4526 
4527 		if (type == expected)
4528 			goto found;
4529 	}
4530 
4531 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
4532 	for (j = 0; j + 1 < i; j++)
4533 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
4534 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
4535 	return -EACCES;
4536 
4537 found:
4538 	if (reg->type == PTR_TO_BTF_ID) {
4539 		if (!arg_btf_id) {
4540 			if (!compatible->btf_id) {
4541 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4542 				return -EFAULT;
4543 			}
4544 			arg_btf_id = compatible->btf_id;
4545 		}
4546 
4547 		if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4548 					  *arg_btf_id)) {
4549 			verbose(env, "R%d is of type %s but %s is expected\n",
4550 				regno, kernel_type_name(reg->btf_id),
4551 				kernel_type_name(*arg_btf_id));
4552 			return -EACCES;
4553 		}
4554 	}
4555 
4556 	return 0;
4557 }
4558 
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)4559 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4560 			  struct bpf_call_arg_meta *meta,
4561 			  const struct bpf_func_proto *fn)
4562 {
4563 	u32 regno = BPF_REG_1 + arg;
4564 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4565 	enum bpf_arg_type arg_type = fn->arg_type[arg];
4566 	enum bpf_reg_type type = reg->type;
4567 	int err = 0;
4568 
4569 	if (arg_type == ARG_DONTCARE)
4570 		return 0;
4571 
4572 	err = check_reg_arg(env, regno, SRC_OP);
4573 	if (err)
4574 		return err;
4575 
4576 	if (arg_type == ARG_ANYTHING) {
4577 		if (is_pointer_value(env, regno)) {
4578 			verbose(env, "R%d leaks addr into helper function\n",
4579 				regno);
4580 			return -EACCES;
4581 		}
4582 		return 0;
4583 	}
4584 
4585 	if (type_is_pkt_pointer(type) &&
4586 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4587 		verbose(env, "helper access to the packet is not allowed\n");
4588 		return -EACCES;
4589 	}
4590 
4591 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
4592 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4593 		err = resolve_map_arg_type(env, meta, &arg_type);
4594 		if (err)
4595 			return err;
4596 	}
4597 
4598 	if (register_is_null(reg) && type_may_be_null(arg_type))
4599 		/* A NULL register has a SCALAR_VALUE type, so skip
4600 		 * type checking.
4601 		 */
4602 		goto skip_type_check;
4603 
4604 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4605 	if (err)
4606 		return err;
4607 
4608 	switch ((u32)type) {
4609 	case SCALAR_VALUE:
4610 	/* Pointer types where reg offset is explicitly allowed: */
4611 	case PTR_TO_PACKET:
4612 	case PTR_TO_PACKET_META:
4613 	case PTR_TO_MAP_VALUE:
4614 	case PTR_TO_MEM:
4615 	case PTR_TO_MEM | MEM_RDONLY:
4616 	case PTR_TO_MEM | MEM_ALLOC:
4617 	case PTR_TO_BUF:
4618 	case PTR_TO_BUF | MEM_RDONLY:
4619 	case PTR_TO_STACK:
4620 		/* Some of the argument types nevertheless require a
4621 		 * zero register offset.
4622 		 */
4623 		if (arg_type == ARG_PTR_TO_ALLOC_MEM)
4624 			goto force_off_check;
4625 		break;
4626 	/* All the rest must be rejected: */
4627 	default:
4628 force_off_check:
4629 		err = __check_ptr_off_reg(env, reg, regno,
4630 					  type == PTR_TO_BTF_ID);
4631 		if (err < 0)
4632 			return err;
4633 		break;
4634 	}
4635 
4636 skip_type_check:
4637 	if (reg->ref_obj_id) {
4638 		if (meta->ref_obj_id) {
4639 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4640 				regno, reg->ref_obj_id,
4641 				meta->ref_obj_id);
4642 			return -EFAULT;
4643 		}
4644 		meta->ref_obj_id = reg->ref_obj_id;
4645 	}
4646 
4647 	if (arg_type == ARG_CONST_MAP_PTR) {
4648 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4649 		meta->map_ptr = reg->map_ptr;
4650 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4651 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
4652 		 * check that [key, key + map->key_size) are within
4653 		 * stack limits and initialized
4654 		 */
4655 		if (!meta->map_ptr) {
4656 			/* in function declaration map_ptr must come before
4657 			 * map_key, so that it's verified and known before
4658 			 * we have to check map_key here. Otherwise it means
4659 			 * that kernel subsystem misconfigured verifier
4660 			 */
4661 			verbose(env, "invalid map_ptr to access map->key\n");
4662 			return -EACCES;
4663 		}
4664 		err = check_helper_mem_access(env, regno,
4665 					      meta->map_ptr->key_size, false,
4666 					      NULL);
4667 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
4668 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4669 		if (type_may_be_null(arg_type) && register_is_null(reg))
4670 			return 0;
4671 
4672 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
4673 		 * check [value, value + map->value_size) validity
4674 		 */
4675 		if (!meta->map_ptr) {
4676 			/* kernel subsystem misconfigured verifier */
4677 			verbose(env, "invalid map_ptr to access map->value\n");
4678 			return -EACCES;
4679 		}
4680 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4681 		err = check_helper_mem_access(env, regno,
4682 					      meta->map_ptr->value_size, false,
4683 					      meta);
4684 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4685 		if (!reg->btf_id) {
4686 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4687 			return -EACCES;
4688 		}
4689 		meta->ret_btf_id = reg->btf_id;
4690 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4691 		if (meta->func_id == BPF_FUNC_spin_lock) {
4692 			if (process_spin_lock(env, regno, true))
4693 				return -EACCES;
4694 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
4695 			if (process_spin_lock(env, regno, false))
4696 				return -EACCES;
4697 		} else {
4698 			verbose(env, "verifier internal error\n");
4699 			return -EFAULT;
4700 		}
4701 	} else if (arg_type_is_mem_ptr(arg_type)) {
4702 		/* The access to this pointer is only checked when we hit the
4703 		 * next is_mem_size argument below.
4704 		 */
4705 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4706 	} else if (arg_type_is_mem_size(arg_type)) {
4707 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4708 
4709 		/* This is used to refine r0 return value bounds for helpers
4710 		 * that enforce this value as an upper bound on return values.
4711 		 * See do_refine_retval_range() for helpers that can refine
4712 		 * the return value. C type of helper is u32 so we pull register
4713 		 * bound from umax_value however, if negative verifier errors
4714 		 * out. Only upper bounds can be learned because retval is an
4715 		 * int type and negative retvals are allowed.
4716 		 */
4717 		meta->msize_max_value = reg->umax_value;
4718 
4719 		/* The register is SCALAR_VALUE; the access check
4720 		 * happens using its boundaries.
4721 		 */
4722 		if (!tnum_is_const(reg->var_off))
4723 			/* For unprivileged variable accesses, disable raw
4724 			 * mode so that the program is required to
4725 			 * initialize all the memory that the helper could
4726 			 * just partially fill up.
4727 			 */
4728 			meta = NULL;
4729 
4730 		if (reg->smin_value < 0) {
4731 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4732 				regno);
4733 			return -EACCES;
4734 		}
4735 
4736 		if (reg->umin_value == 0) {
4737 			err = check_helper_mem_access(env, regno - 1, 0,
4738 						      zero_size_allowed,
4739 						      meta);
4740 			if (err)
4741 				return err;
4742 		}
4743 
4744 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4745 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4746 				regno);
4747 			return -EACCES;
4748 		}
4749 		err = check_helper_mem_access(env, regno - 1,
4750 					      reg->umax_value,
4751 					      zero_size_allowed, meta);
4752 		if (!err)
4753 			err = mark_chain_precision(env, regno);
4754 	} else if (arg_type_is_alloc_size(arg_type)) {
4755 		if (!tnum_is_const(reg->var_off)) {
4756 			verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4757 				regno);
4758 			return -EACCES;
4759 		}
4760 		meta->mem_size = reg->var_off.value;
4761 	} else if (arg_type_is_int_ptr(arg_type)) {
4762 		int size = int_ptr_type_to_size(arg_type);
4763 
4764 		err = check_helper_mem_access(env, regno, size, false, meta);
4765 		if (err)
4766 			return err;
4767 		err = check_ptr_alignment(env, reg, 0, size, true);
4768 	}
4769 
4770 	return err;
4771 }
4772 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)4773 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4774 {
4775 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
4776 	enum bpf_prog_type type = resolve_prog_type(env->prog);
4777 
4778 	if (func_id != BPF_FUNC_map_update_elem)
4779 		return false;
4780 
4781 	/* It's not possible to get access to a locked struct sock in these
4782 	 * contexts, so updating is safe.
4783 	 */
4784 	switch (type) {
4785 	case BPF_PROG_TYPE_TRACING:
4786 		if (eatype == BPF_TRACE_ITER)
4787 			return true;
4788 		break;
4789 	case BPF_PROG_TYPE_SOCKET_FILTER:
4790 	case BPF_PROG_TYPE_SCHED_CLS:
4791 	case BPF_PROG_TYPE_SCHED_ACT:
4792 	case BPF_PROG_TYPE_XDP:
4793 	case BPF_PROG_TYPE_SK_REUSEPORT:
4794 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
4795 	case BPF_PROG_TYPE_SK_LOOKUP:
4796 		return true;
4797 	default:
4798 		break;
4799 	}
4800 
4801 	verbose(env, "cannot update sockmap in this context\n");
4802 	return false;
4803 }
4804 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)4805 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4806 {
4807 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4808 }
4809 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)4810 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4811 					struct bpf_map *map, int func_id)
4812 {
4813 	if (!map)
4814 		return 0;
4815 
4816 	/* We need a two way check, first is from map perspective ... */
4817 	switch (map->map_type) {
4818 	case BPF_MAP_TYPE_PROG_ARRAY:
4819 		if (func_id != BPF_FUNC_tail_call)
4820 			goto error;
4821 		break;
4822 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4823 		if (func_id != BPF_FUNC_perf_event_read &&
4824 		    func_id != BPF_FUNC_perf_event_output &&
4825 		    func_id != BPF_FUNC_skb_output &&
4826 		    func_id != BPF_FUNC_perf_event_read_value &&
4827 		    func_id != BPF_FUNC_xdp_output)
4828 			goto error;
4829 		break;
4830 	case BPF_MAP_TYPE_RINGBUF:
4831 		if (func_id != BPF_FUNC_ringbuf_output &&
4832 		    func_id != BPF_FUNC_ringbuf_reserve &&
4833 		    func_id != BPF_FUNC_ringbuf_query)
4834 			goto error;
4835 		break;
4836 	case BPF_MAP_TYPE_STACK_TRACE:
4837 		if (func_id != BPF_FUNC_get_stackid)
4838 			goto error;
4839 		break;
4840 	case BPF_MAP_TYPE_CGROUP_ARRAY:
4841 		if (func_id != BPF_FUNC_skb_under_cgroup &&
4842 		    func_id != BPF_FUNC_current_task_under_cgroup)
4843 			goto error;
4844 		break;
4845 	case BPF_MAP_TYPE_CGROUP_STORAGE:
4846 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4847 		if (func_id != BPF_FUNC_get_local_storage)
4848 			goto error;
4849 		break;
4850 	case BPF_MAP_TYPE_DEVMAP:
4851 	case BPF_MAP_TYPE_DEVMAP_HASH:
4852 		if (func_id != BPF_FUNC_redirect_map &&
4853 		    func_id != BPF_FUNC_map_lookup_elem)
4854 			goto error;
4855 		break;
4856 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
4857 	 * appear.
4858 	 */
4859 	case BPF_MAP_TYPE_CPUMAP:
4860 		if (func_id != BPF_FUNC_redirect_map)
4861 			goto error;
4862 		break;
4863 	case BPF_MAP_TYPE_XSKMAP:
4864 		if (func_id != BPF_FUNC_redirect_map &&
4865 		    func_id != BPF_FUNC_map_lookup_elem)
4866 			goto error;
4867 		break;
4868 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4869 	case BPF_MAP_TYPE_HASH_OF_MAPS:
4870 		if (func_id != BPF_FUNC_map_lookup_elem)
4871 			goto error;
4872 		break;
4873 	case BPF_MAP_TYPE_SOCKMAP:
4874 		if (func_id != BPF_FUNC_sk_redirect_map &&
4875 		    func_id != BPF_FUNC_sock_map_update &&
4876 		    func_id != BPF_FUNC_map_delete_elem &&
4877 		    func_id != BPF_FUNC_msg_redirect_map &&
4878 		    func_id != BPF_FUNC_sk_select_reuseport &&
4879 		    func_id != BPF_FUNC_map_lookup_elem &&
4880 		    !may_update_sockmap(env, func_id))
4881 			goto error;
4882 		break;
4883 	case BPF_MAP_TYPE_SOCKHASH:
4884 		if (func_id != BPF_FUNC_sk_redirect_hash &&
4885 		    func_id != BPF_FUNC_sock_hash_update &&
4886 		    func_id != BPF_FUNC_map_delete_elem &&
4887 		    func_id != BPF_FUNC_msg_redirect_hash &&
4888 		    func_id != BPF_FUNC_sk_select_reuseport &&
4889 		    func_id != BPF_FUNC_map_lookup_elem &&
4890 		    !may_update_sockmap(env, func_id))
4891 			goto error;
4892 		break;
4893 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4894 		if (func_id != BPF_FUNC_sk_select_reuseport)
4895 			goto error;
4896 		break;
4897 	case BPF_MAP_TYPE_QUEUE:
4898 	case BPF_MAP_TYPE_STACK:
4899 		if (func_id != BPF_FUNC_map_peek_elem &&
4900 		    func_id != BPF_FUNC_map_pop_elem &&
4901 		    func_id != BPF_FUNC_map_push_elem)
4902 			goto error;
4903 		break;
4904 	case BPF_MAP_TYPE_SK_STORAGE:
4905 		if (func_id != BPF_FUNC_sk_storage_get &&
4906 		    func_id != BPF_FUNC_sk_storage_delete)
4907 			goto error;
4908 		break;
4909 	case BPF_MAP_TYPE_INODE_STORAGE:
4910 		if (func_id != BPF_FUNC_inode_storage_get &&
4911 		    func_id != BPF_FUNC_inode_storage_delete)
4912 			goto error;
4913 		break;
4914 	default:
4915 		break;
4916 	}
4917 
4918 	/* ... and second from the function itself. */
4919 	switch (func_id) {
4920 	case BPF_FUNC_tail_call:
4921 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4922 			goto error;
4923 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4924 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4925 			return -EINVAL;
4926 		}
4927 		break;
4928 	case BPF_FUNC_perf_event_read:
4929 	case BPF_FUNC_perf_event_output:
4930 	case BPF_FUNC_perf_event_read_value:
4931 	case BPF_FUNC_skb_output:
4932 	case BPF_FUNC_xdp_output:
4933 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4934 			goto error;
4935 		break;
4936 	case BPF_FUNC_ringbuf_output:
4937 	case BPF_FUNC_ringbuf_reserve:
4938 	case BPF_FUNC_ringbuf_query:
4939 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
4940 			goto error;
4941 		break;
4942 	case BPF_FUNC_get_stackid:
4943 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4944 			goto error;
4945 		break;
4946 	case BPF_FUNC_current_task_under_cgroup:
4947 	case BPF_FUNC_skb_under_cgroup:
4948 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4949 			goto error;
4950 		break;
4951 	case BPF_FUNC_redirect_map:
4952 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4953 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4954 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
4955 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
4956 			goto error;
4957 		break;
4958 	case BPF_FUNC_sk_redirect_map:
4959 	case BPF_FUNC_msg_redirect_map:
4960 	case BPF_FUNC_sock_map_update:
4961 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4962 			goto error;
4963 		break;
4964 	case BPF_FUNC_sk_redirect_hash:
4965 	case BPF_FUNC_msg_redirect_hash:
4966 	case BPF_FUNC_sock_hash_update:
4967 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4968 			goto error;
4969 		break;
4970 	case BPF_FUNC_get_local_storage:
4971 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4972 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4973 			goto error;
4974 		break;
4975 	case BPF_FUNC_sk_select_reuseport:
4976 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4977 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4978 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
4979 			goto error;
4980 		break;
4981 	case BPF_FUNC_map_peek_elem:
4982 	case BPF_FUNC_map_pop_elem:
4983 	case BPF_FUNC_map_push_elem:
4984 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4985 		    map->map_type != BPF_MAP_TYPE_STACK)
4986 			goto error;
4987 		break;
4988 	case BPF_FUNC_sk_storage_get:
4989 	case BPF_FUNC_sk_storage_delete:
4990 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4991 			goto error;
4992 		break;
4993 	case BPF_FUNC_inode_storage_get:
4994 	case BPF_FUNC_inode_storage_delete:
4995 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4996 			goto error;
4997 		break;
4998 	default:
4999 		break;
5000 	}
5001 
5002 	return 0;
5003 error:
5004 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5005 		map->map_type, func_id_name(func_id), func_id);
5006 	return -EINVAL;
5007 }
5008 
check_raw_mode_ok(const struct bpf_func_proto * fn)5009 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5010 {
5011 	int count = 0;
5012 
5013 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5014 		count++;
5015 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5016 		count++;
5017 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5018 		count++;
5019 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5020 		count++;
5021 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5022 		count++;
5023 
5024 	/* We only support one arg being in raw mode at the moment,
5025 	 * which is sufficient for the helper functions we have
5026 	 * right now.
5027 	 */
5028 	return count <= 1;
5029 }
5030 
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)5031 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5032 				    enum bpf_arg_type arg_next)
5033 {
5034 	return (arg_type_is_mem_ptr(arg_curr) &&
5035 	        !arg_type_is_mem_size(arg_next)) ||
5036 	       (!arg_type_is_mem_ptr(arg_curr) &&
5037 		arg_type_is_mem_size(arg_next));
5038 }
5039 
check_arg_pair_ok(const struct bpf_func_proto * fn)5040 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5041 {
5042 	/* bpf_xxx(..., buf, len) call will access 'len'
5043 	 * bytes from memory 'buf'. Both arg types need
5044 	 * to be paired, so make sure there's no buggy
5045 	 * helper function specification.
5046 	 */
5047 	if (arg_type_is_mem_size(fn->arg1_type) ||
5048 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5049 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5050 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5051 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5052 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5053 		return false;
5054 
5055 	return true;
5056 }
5057 
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5058 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5059 {
5060 	int count = 0;
5061 
5062 	if (arg_type_may_be_refcounted(fn->arg1_type))
5063 		count++;
5064 	if (arg_type_may_be_refcounted(fn->arg2_type))
5065 		count++;
5066 	if (arg_type_may_be_refcounted(fn->arg3_type))
5067 		count++;
5068 	if (arg_type_may_be_refcounted(fn->arg4_type))
5069 		count++;
5070 	if (arg_type_may_be_refcounted(fn->arg5_type))
5071 		count++;
5072 
5073 	/* A reference acquiring function cannot acquire
5074 	 * another refcounted ptr.
5075 	 */
5076 	if (may_be_acquire_function(func_id) && count)
5077 		return false;
5078 
5079 	/* We only support one arg being unreferenced at the moment,
5080 	 * which is sufficient for the helper functions we have right now.
5081 	 */
5082 	return count <= 1;
5083 }
5084 
check_btf_id_ok(const struct bpf_func_proto * fn)5085 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5086 {
5087 	int i;
5088 
5089 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5090 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5091 			return false;
5092 
5093 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5094 			return false;
5095 	}
5096 
5097 	return true;
5098 }
5099 
check_func_proto(const struct bpf_func_proto * fn,int func_id)5100 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5101 {
5102 	return check_raw_mode_ok(fn) &&
5103 	       check_arg_pair_ok(fn) &&
5104 	       check_btf_id_ok(fn) &&
5105 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5106 }
5107 
5108 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5109  * are now invalid, so turn them into unknown SCALAR_VALUE.
5110  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5111 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5112 {
5113 	struct bpf_func_state *state;
5114 	struct bpf_reg_state *reg;
5115 
5116 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5117 		if (reg_is_pkt_pointer_any(reg))
5118 			__mark_reg_unknown(env, reg);
5119 	}));
5120 }
5121 
5122 enum {
5123 	AT_PKT_END = -1,
5124 	BEYOND_PKT_END = -2,
5125 };
5126 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5127 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5128 {
5129 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5130 	struct bpf_reg_state *reg = &state->regs[regn];
5131 
5132 	if (reg->type != PTR_TO_PACKET)
5133 		/* PTR_TO_PACKET_META is not supported yet */
5134 		return;
5135 
5136 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5137 	 * How far beyond pkt_end it goes is unknown.
5138 	 * if (!range_open) it's the case of pkt >= pkt_end
5139 	 * if (range_open) it's the case of pkt > pkt_end
5140 	 * hence this pointer is at least 1 byte bigger than pkt_end
5141 	 */
5142 	if (range_open)
5143 		reg->range = BEYOND_PKT_END;
5144 	else
5145 		reg->range = AT_PKT_END;
5146 }
5147 
5148 /* The pointer with the specified id has released its reference to kernel
5149  * resources. Identify all copies of the same pointer and clear the reference.
5150  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5151 static int release_reference(struct bpf_verifier_env *env,
5152 			     int ref_obj_id)
5153 {
5154 	struct bpf_func_state *state;
5155 	struct bpf_reg_state *reg;
5156 	int err;
5157 
5158 	err = release_reference_state(cur_func(env), ref_obj_id);
5159 	if (err)
5160 		return err;
5161 
5162 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5163 		if (reg->ref_obj_id == ref_obj_id) {
5164 			if (!env->allow_ptr_leaks)
5165 				__mark_reg_not_init(env, reg);
5166 			else
5167 				__mark_reg_unknown(env, reg);
5168 		}
5169 	}));
5170 
5171 	return 0;
5172 }
5173 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5174 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5175 				    struct bpf_reg_state *regs)
5176 {
5177 	int i;
5178 
5179 	/* after the call registers r0 - r5 were scratched */
5180 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5181 		mark_reg_not_init(env, regs, caller_saved[i]);
5182 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5183 	}
5184 }
5185 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)5186 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5187 			   int *insn_idx)
5188 {
5189 	struct bpf_verifier_state *state = env->cur_state;
5190 	struct bpf_func_info_aux *func_info_aux;
5191 	struct bpf_func_state *caller, *callee;
5192 	int i, err, subprog, target_insn;
5193 	bool is_global = false;
5194 
5195 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5196 		verbose(env, "the call stack of %d frames is too deep\n",
5197 			state->curframe + 2);
5198 		return -E2BIG;
5199 	}
5200 
5201 	target_insn = *insn_idx + insn->imm;
5202 	subprog = find_subprog(env, target_insn + 1);
5203 	if (subprog < 0) {
5204 		verbose(env, "verifier bug. No program starts at insn %d\n",
5205 			target_insn + 1);
5206 		return -EFAULT;
5207 	}
5208 
5209 	caller = state->frame[state->curframe];
5210 	if (state->frame[state->curframe + 1]) {
5211 		verbose(env, "verifier bug. Frame %d already allocated\n",
5212 			state->curframe + 1);
5213 		return -EFAULT;
5214 	}
5215 
5216 	func_info_aux = env->prog->aux->func_info_aux;
5217 	if (func_info_aux)
5218 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5219 	err = btf_check_func_arg_match(env, subprog, caller->regs);
5220 	if (err == -EFAULT)
5221 		return err;
5222 	if (is_global) {
5223 		if (err) {
5224 			verbose(env, "Caller passes invalid args into func#%d\n",
5225 				subprog);
5226 			return err;
5227 		} else {
5228 			if (env->log.level & BPF_LOG_LEVEL)
5229 				verbose(env,
5230 					"Func#%d is global and valid. Skipping.\n",
5231 					subprog);
5232 			clear_caller_saved_regs(env, caller->regs);
5233 
5234 			/* All global functions return a 64-bit SCALAR_VALUE */
5235 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
5236 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5237 
5238 			/* continue with next insn after call */
5239 			return 0;
5240 		}
5241 	}
5242 
5243 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5244 	if (!callee)
5245 		return -ENOMEM;
5246 	state->frame[state->curframe + 1] = callee;
5247 
5248 	/* callee cannot access r0, r6 - r9 for reading and has to write
5249 	 * into its own stack before reading from it.
5250 	 * callee can read/write into caller's stack
5251 	 */
5252 	init_func_state(env, callee,
5253 			/* remember the callsite, it will be used by bpf_exit */
5254 			*insn_idx /* callsite */,
5255 			state->curframe + 1 /* frameno within this callchain */,
5256 			subprog /* subprog number within this prog */);
5257 
5258 	/* Transfer references to the callee */
5259 	err = transfer_reference_state(callee, caller);
5260 	if (err)
5261 		return err;
5262 
5263 	/* copy r1 - r5 args that callee can access.  The copy includes parent
5264 	 * pointers, which connects us up to the liveness chain
5265 	 */
5266 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5267 		callee->regs[i] = caller->regs[i];
5268 
5269 	clear_caller_saved_regs(env, caller->regs);
5270 
5271 	/* only increment it after check_reg_arg() finished */
5272 	state->curframe++;
5273 
5274 	/* and go analyze first insn of the callee */
5275 	*insn_idx = target_insn;
5276 
5277 	if (env->log.level & BPF_LOG_LEVEL) {
5278 		verbose(env, "caller:\n");
5279 		print_verifier_state(env, caller);
5280 		verbose(env, "callee:\n");
5281 		print_verifier_state(env, callee);
5282 	}
5283 	return 0;
5284 }
5285 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)5286 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5287 {
5288 	struct bpf_verifier_state *state = env->cur_state;
5289 	struct bpf_func_state *caller, *callee;
5290 	struct bpf_reg_state *r0;
5291 	int err;
5292 
5293 	callee = state->frame[state->curframe];
5294 	r0 = &callee->regs[BPF_REG_0];
5295 	if (r0->type == PTR_TO_STACK) {
5296 		/* technically it's ok to return caller's stack pointer
5297 		 * (or caller's caller's pointer) back to the caller,
5298 		 * since these pointers are valid. Only current stack
5299 		 * pointer will be invalid as soon as function exits,
5300 		 * but let's be conservative
5301 		 */
5302 		verbose(env, "cannot return stack pointer to the caller\n");
5303 		return -EINVAL;
5304 	}
5305 
5306 	state->curframe--;
5307 	caller = state->frame[state->curframe];
5308 	/* return to the caller whatever r0 had in the callee */
5309 	caller->regs[BPF_REG_0] = *r0;
5310 
5311 	/* Transfer references to the caller */
5312 	err = transfer_reference_state(caller, callee);
5313 	if (err)
5314 		return err;
5315 
5316 	*insn_idx = callee->callsite + 1;
5317 	if (env->log.level & BPF_LOG_LEVEL) {
5318 		verbose(env, "returning from callee:\n");
5319 		print_verifier_state(env, callee);
5320 		verbose(env, "to caller at %d:\n", *insn_idx);
5321 		print_verifier_state(env, caller);
5322 	}
5323 	/* clear everything in the callee */
5324 	free_func_state(callee);
5325 	state->frame[state->curframe + 1] = NULL;
5326 	return 0;
5327 }
5328 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)5329 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5330 				   int func_id,
5331 				   struct bpf_call_arg_meta *meta)
5332 {
5333 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5334 
5335 	if (ret_type != RET_INTEGER ||
5336 	    (func_id != BPF_FUNC_get_stack &&
5337 	     func_id != BPF_FUNC_probe_read_str &&
5338 	     func_id != BPF_FUNC_probe_read_kernel_str &&
5339 	     func_id != BPF_FUNC_probe_read_user_str))
5340 		return;
5341 
5342 	ret_reg->smax_value = meta->msize_max_value;
5343 	ret_reg->s32_max_value = meta->msize_max_value;
5344 	ret_reg->smin_value = -MAX_ERRNO;
5345 	ret_reg->s32_min_value = -MAX_ERRNO;
5346 	reg_bounds_sync(ret_reg);
5347 }
5348 
5349 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5350 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5351 		int func_id, int insn_idx)
5352 {
5353 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5354 	struct bpf_map *map = meta->map_ptr;
5355 
5356 	if (func_id != BPF_FUNC_tail_call &&
5357 	    func_id != BPF_FUNC_map_lookup_elem &&
5358 	    func_id != BPF_FUNC_map_update_elem &&
5359 	    func_id != BPF_FUNC_map_delete_elem &&
5360 	    func_id != BPF_FUNC_map_push_elem &&
5361 	    func_id != BPF_FUNC_map_pop_elem &&
5362 	    func_id != BPF_FUNC_map_peek_elem)
5363 		return 0;
5364 
5365 	if (map == NULL) {
5366 		verbose(env, "kernel subsystem misconfigured verifier\n");
5367 		return -EINVAL;
5368 	}
5369 
5370 	/* In case of read-only, some additional restrictions
5371 	 * need to be applied in order to prevent altering the
5372 	 * state of the map from program side.
5373 	 */
5374 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5375 	    (func_id == BPF_FUNC_map_delete_elem ||
5376 	     func_id == BPF_FUNC_map_update_elem ||
5377 	     func_id == BPF_FUNC_map_push_elem ||
5378 	     func_id == BPF_FUNC_map_pop_elem)) {
5379 		verbose(env, "write into map forbidden\n");
5380 		return -EACCES;
5381 	}
5382 
5383 	if (!BPF_MAP_PTR(aux->map_ptr_state))
5384 		bpf_map_ptr_store(aux, meta->map_ptr,
5385 				  !meta->map_ptr->bypass_spec_v1);
5386 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5387 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5388 				  !meta->map_ptr->bypass_spec_v1);
5389 	return 0;
5390 }
5391 
5392 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5393 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5394 		int func_id, int insn_idx)
5395 {
5396 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5397 	struct bpf_reg_state *regs = cur_regs(env), *reg;
5398 	struct bpf_map *map = meta->map_ptr;
5399 	u64 val, max;
5400 	int err;
5401 
5402 	if (func_id != BPF_FUNC_tail_call)
5403 		return 0;
5404 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5405 		verbose(env, "kernel subsystem misconfigured verifier\n");
5406 		return -EINVAL;
5407 	}
5408 
5409 	reg = &regs[BPF_REG_3];
5410 	val = reg->var_off.value;
5411 	max = map->max_entries;
5412 
5413 	if (!(register_is_const(reg) && val < max)) {
5414 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5415 		return 0;
5416 	}
5417 
5418 	err = mark_chain_precision(env, BPF_REG_3);
5419 	if (err)
5420 		return err;
5421 	if (bpf_map_key_unseen(aux))
5422 		bpf_map_key_store(aux, val);
5423 	else if (!bpf_map_key_poisoned(aux) &&
5424 		  bpf_map_key_immediate(aux) != val)
5425 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5426 	return 0;
5427 }
5428 
check_reference_leak(struct bpf_verifier_env * env)5429 static int check_reference_leak(struct bpf_verifier_env *env)
5430 {
5431 	struct bpf_func_state *state = cur_func(env);
5432 	int i;
5433 
5434 	for (i = 0; i < state->acquired_refs; i++) {
5435 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5436 			state->refs[i].id, state->refs[i].insn_idx);
5437 	}
5438 	return state->acquired_refs ? -EINVAL : 0;
5439 }
5440 
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)5441 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5442 {
5443 	const struct bpf_func_proto *fn = NULL;
5444 	enum bpf_return_type ret_type;
5445 	enum bpf_type_flag ret_flag;
5446 	struct bpf_reg_state *regs;
5447 	struct bpf_call_arg_meta meta;
5448 	bool changes_data;
5449 	int i, err;
5450 
5451 	/* find function prototype */
5452 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5453 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5454 			func_id);
5455 		return -EINVAL;
5456 	}
5457 
5458 	if (env->ops->get_func_proto)
5459 		fn = env->ops->get_func_proto(func_id, env->prog);
5460 	if (!fn) {
5461 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5462 			func_id);
5463 		return -EINVAL;
5464 	}
5465 
5466 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
5467 	if (!env->prog->gpl_compatible && fn->gpl_only) {
5468 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5469 		return -EINVAL;
5470 	}
5471 
5472 	if (fn->allowed && !fn->allowed(env->prog)) {
5473 		verbose(env, "helper call is not allowed in probe\n");
5474 		return -EINVAL;
5475 	}
5476 
5477 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
5478 	changes_data = bpf_helper_changes_pkt_data(fn->func);
5479 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5480 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5481 			func_id_name(func_id), func_id);
5482 		return -EINVAL;
5483 	}
5484 
5485 	memset(&meta, 0, sizeof(meta));
5486 	meta.pkt_access = fn->pkt_access;
5487 
5488 	err = check_func_proto(fn, func_id);
5489 	if (err) {
5490 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5491 			func_id_name(func_id), func_id);
5492 		return err;
5493 	}
5494 
5495 	meta.func_id = func_id;
5496 	/* check args */
5497 	for (i = 0; i < 5; i++) {
5498 		err = check_func_arg(env, i, &meta, fn);
5499 		if (err)
5500 			return err;
5501 	}
5502 
5503 	err = record_func_map(env, &meta, func_id, insn_idx);
5504 	if (err)
5505 		return err;
5506 
5507 	err = record_func_key(env, &meta, func_id, insn_idx);
5508 	if (err)
5509 		return err;
5510 
5511 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
5512 	 * is inferred from register state.
5513 	 */
5514 	for (i = 0; i < meta.access_size; i++) {
5515 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5516 				       BPF_WRITE, -1, false);
5517 		if (err)
5518 			return err;
5519 	}
5520 
5521 	if (func_id == BPF_FUNC_tail_call) {
5522 		err = check_reference_leak(env);
5523 		if (err) {
5524 			verbose(env, "tail_call would lead to reference leak\n");
5525 			return err;
5526 		}
5527 	} else if (is_release_function(func_id)) {
5528 		err = release_reference(env, meta.ref_obj_id);
5529 		if (err) {
5530 			verbose(env, "func %s#%d reference has not been acquired before\n",
5531 				func_id_name(func_id), func_id);
5532 			return err;
5533 		}
5534 	}
5535 
5536 	regs = cur_regs(env);
5537 
5538 	/* check that flags argument in get_local_storage(map, flags) is 0,
5539 	 * this is required because get_local_storage() can't return an error.
5540 	 */
5541 	if (func_id == BPF_FUNC_get_local_storage &&
5542 	    !register_is_null(&regs[BPF_REG_2])) {
5543 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5544 		return -EINVAL;
5545 	}
5546 
5547 	/* reset caller saved regs */
5548 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5549 		mark_reg_not_init(env, regs, caller_saved[i]);
5550 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5551 	}
5552 
5553 	/* helper call returns 64-bit value. */
5554 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5555 
5556 	/* update return register (already marked as written above) */
5557 	ret_type = fn->ret_type;
5558 	ret_flag = type_flag(fn->ret_type);
5559 	if (ret_type == RET_INTEGER) {
5560 		/* sets type to SCALAR_VALUE */
5561 		mark_reg_unknown(env, regs, BPF_REG_0);
5562 	} else if (ret_type == RET_VOID) {
5563 		regs[BPF_REG_0].type = NOT_INIT;
5564 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
5565 		/* There is no offset yet applied, variable or fixed */
5566 		mark_reg_known_zero(env, regs, BPF_REG_0);
5567 		/* remember map_ptr, so that check_map_access()
5568 		 * can check 'value_size' boundary of memory access
5569 		 * to map element returned from bpf_map_lookup_elem()
5570 		 */
5571 		if (meta.map_ptr == NULL) {
5572 			verbose(env,
5573 				"kernel subsystem misconfigured verifier\n");
5574 			return -EINVAL;
5575 		}
5576 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
5577 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
5578 		if (!type_may_be_null(ret_type) &&
5579 		    map_value_has_spin_lock(meta.map_ptr)) {
5580 			regs[BPF_REG_0].id = ++env->id_gen;
5581 		}
5582 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
5583 		mark_reg_known_zero(env, regs, BPF_REG_0);
5584 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
5585 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
5586 		mark_reg_known_zero(env, regs, BPF_REG_0);
5587 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
5588 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
5589 		mark_reg_known_zero(env, regs, BPF_REG_0);
5590 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
5591 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
5592 		mark_reg_known_zero(env, regs, BPF_REG_0);
5593 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5594 		regs[BPF_REG_0].mem_size = meta.mem_size;
5595 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
5596 		const struct btf_type *t;
5597 
5598 		mark_reg_known_zero(env, regs, BPF_REG_0);
5599 		t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5600 		if (!btf_type_is_struct(t)) {
5601 			u32 tsize;
5602 			const struct btf_type *ret;
5603 			const char *tname;
5604 
5605 			/* resolve the type size of ksym. */
5606 			ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5607 			if (IS_ERR(ret)) {
5608 				tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5609 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
5610 					tname, PTR_ERR(ret));
5611 				return -EINVAL;
5612 			}
5613 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
5614 			regs[BPF_REG_0].mem_size = tsize;
5615 		} else {
5616 			/* MEM_RDONLY may be carried from ret_flag, but it
5617 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
5618 			 * it will confuse the check of PTR_TO_BTF_ID in
5619 			 * check_mem_access().
5620 			 */
5621 			ret_flag &= ~MEM_RDONLY;
5622 
5623 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5624 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5625 		}
5626 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
5627 		int ret_btf_id;
5628 
5629 		mark_reg_known_zero(env, regs, BPF_REG_0);
5630 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
5631 		ret_btf_id = *fn->ret_btf_id;
5632 		if (ret_btf_id == 0) {
5633 			verbose(env, "invalid return type %u of func %s#%d\n",
5634 				base_type(ret_type), func_id_name(func_id),
5635 				func_id);
5636 			return -EINVAL;
5637 		}
5638 		regs[BPF_REG_0].btf_id = ret_btf_id;
5639 	} else {
5640 		verbose(env, "unknown return type %u of func %s#%d\n",
5641 			base_type(ret_type), func_id_name(func_id), func_id);
5642 		return -EINVAL;
5643 	}
5644 
5645 	if (type_may_be_null(regs[BPF_REG_0].type))
5646 		regs[BPF_REG_0].id = ++env->id_gen;
5647 
5648 	if (is_ptr_cast_function(func_id)) {
5649 		/* For release_reference() */
5650 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5651 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
5652 		int id = acquire_reference_state(env, insn_idx);
5653 
5654 		if (id < 0)
5655 			return id;
5656 		/* For mark_ptr_or_null_reg() */
5657 		regs[BPF_REG_0].id = id;
5658 		/* For release_reference() */
5659 		regs[BPF_REG_0].ref_obj_id = id;
5660 	}
5661 
5662 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5663 
5664 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5665 	if (err)
5666 		return err;
5667 
5668 	if ((func_id == BPF_FUNC_get_stack ||
5669 	     func_id == BPF_FUNC_get_task_stack) &&
5670 	    !env->prog->has_callchain_buf) {
5671 		const char *err_str;
5672 
5673 #ifdef CONFIG_PERF_EVENTS
5674 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
5675 		err_str = "cannot get callchain buffer for func %s#%d\n";
5676 #else
5677 		err = -ENOTSUPP;
5678 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5679 #endif
5680 		if (err) {
5681 			verbose(env, err_str, func_id_name(func_id), func_id);
5682 			return err;
5683 		}
5684 
5685 		env->prog->has_callchain_buf = true;
5686 	}
5687 
5688 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5689 		env->prog->call_get_stack = true;
5690 
5691 	if (changes_data)
5692 		clear_all_pkt_pointers(env);
5693 	return 0;
5694 }
5695 
signed_add_overflows(s64 a,s64 b)5696 static bool signed_add_overflows(s64 a, s64 b)
5697 {
5698 	/* Do the add in u64, where overflow is well-defined */
5699 	s64 res = (s64)((u64)a + (u64)b);
5700 
5701 	if (b < 0)
5702 		return res > a;
5703 	return res < a;
5704 }
5705 
signed_add32_overflows(s32 a,s32 b)5706 static bool signed_add32_overflows(s32 a, s32 b)
5707 {
5708 	/* Do the add in u32, where overflow is well-defined */
5709 	s32 res = (s32)((u32)a + (u32)b);
5710 
5711 	if (b < 0)
5712 		return res > a;
5713 	return res < a;
5714 }
5715 
signed_sub_overflows(s64 a,s64 b)5716 static bool signed_sub_overflows(s64 a, s64 b)
5717 {
5718 	/* Do the sub in u64, where overflow is well-defined */
5719 	s64 res = (s64)((u64)a - (u64)b);
5720 
5721 	if (b < 0)
5722 		return res < a;
5723 	return res > a;
5724 }
5725 
signed_sub32_overflows(s32 a,s32 b)5726 static bool signed_sub32_overflows(s32 a, s32 b)
5727 {
5728 	/* Do the sub in u32, where overflow is well-defined */
5729 	s32 res = (s32)((u32)a - (u32)b);
5730 
5731 	if (b < 0)
5732 		return res < a;
5733 	return res > a;
5734 }
5735 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)5736 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5737 				  const struct bpf_reg_state *reg,
5738 				  enum bpf_reg_type type)
5739 {
5740 	bool known = tnum_is_const(reg->var_off);
5741 	s64 val = reg->var_off.value;
5742 	s64 smin = reg->smin_value;
5743 
5744 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5745 		verbose(env, "math between %s pointer and %lld is not allowed\n",
5746 			reg_type_str(env, type), val);
5747 		return false;
5748 	}
5749 
5750 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5751 		verbose(env, "%s pointer offset %d is not allowed\n",
5752 			reg_type_str(env, type), reg->off);
5753 		return false;
5754 	}
5755 
5756 	if (smin == S64_MIN) {
5757 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5758 			reg_type_str(env, type));
5759 		return false;
5760 	}
5761 
5762 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5763 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
5764 			smin, reg_type_str(env, type));
5765 		return false;
5766 	}
5767 
5768 	return true;
5769 }
5770 
cur_aux(struct bpf_verifier_env * env)5771 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5772 {
5773 	return &env->insn_aux_data[env->insn_idx];
5774 }
5775 
5776 enum {
5777 	REASON_BOUNDS	= -1,
5778 	REASON_TYPE	= -2,
5779 	REASON_PATHS	= -3,
5780 	REASON_LIMIT	= -4,
5781 	REASON_STACK	= -5,
5782 };
5783 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)5784 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5785 			      u32 *alu_limit, bool mask_to_left)
5786 {
5787 	u32 max = 0, ptr_limit = 0;
5788 
5789 	switch (ptr_reg->type) {
5790 	case PTR_TO_STACK:
5791 		/* Offset 0 is out-of-bounds, but acceptable start for the
5792 		 * left direction, see BPF_REG_FP. Also, unknown scalar
5793 		 * offset where we would need to deal with min/max bounds is
5794 		 * currently prohibited for unprivileged.
5795 		 */
5796 		max = MAX_BPF_STACK + mask_to_left;
5797 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5798 		break;
5799 	case PTR_TO_MAP_VALUE:
5800 		max = ptr_reg->map_ptr->value_size;
5801 		ptr_limit = (mask_to_left ?
5802 			     ptr_reg->smin_value :
5803 			     ptr_reg->umax_value) + ptr_reg->off;
5804 		break;
5805 	default:
5806 		return REASON_TYPE;
5807 	}
5808 
5809 	if (ptr_limit >= max)
5810 		return REASON_LIMIT;
5811 	*alu_limit = ptr_limit;
5812 	return 0;
5813 }
5814 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)5815 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5816 				    const struct bpf_insn *insn)
5817 {
5818 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5819 }
5820 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)5821 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5822 				       u32 alu_state, u32 alu_limit)
5823 {
5824 	/* If we arrived here from different branches with different
5825 	 * state or limits to sanitize, then this won't work.
5826 	 */
5827 	if (aux->alu_state &&
5828 	    (aux->alu_state != alu_state ||
5829 	     aux->alu_limit != alu_limit))
5830 		return REASON_PATHS;
5831 
5832 	/* Corresponding fixup done in fixup_bpf_calls(). */
5833 	aux->alu_state = alu_state;
5834 	aux->alu_limit = alu_limit;
5835 	return 0;
5836 }
5837 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)5838 static int sanitize_val_alu(struct bpf_verifier_env *env,
5839 			    struct bpf_insn *insn)
5840 {
5841 	struct bpf_insn_aux_data *aux = cur_aux(env);
5842 
5843 	if (can_skip_alu_sanitation(env, insn))
5844 		return 0;
5845 
5846 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5847 }
5848 
sanitize_needed(u8 opcode)5849 static bool sanitize_needed(u8 opcode)
5850 {
5851 	return opcode == BPF_ADD || opcode == BPF_SUB;
5852 }
5853 
5854 struct bpf_sanitize_info {
5855 	struct bpf_insn_aux_data aux;
5856 	bool mask_to_left;
5857 };
5858 
5859 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)5860 sanitize_speculative_path(struct bpf_verifier_env *env,
5861 			  const struct bpf_insn *insn,
5862 			  u32 next_idx, u32 curr_idx)
5863 {
5864 	struct bpf_verifier_state *branch;
5865 	struct bpf_reg_state *regs;
5866 
5867 	branch = push_stack(env, next_idx, curr_idx, true);
5868 	if (branch && insn) {
5869 		regs = branch->frame[branch->curframe]->regs;
5870 		if (BPF_SRC(insn->code) == BPF_K) {
5871 			mark_reg_unknown(env, regs, insn->dst_reg);
5872 		} else if (BPF_SRC(insn->code) == BPF_X) {
5873 			mark_reg_unknown(env, regs, insn->dst_reg);
5874 			mark_reg_unknown(env, regs, insn->src_reg);
5875 		}
5876 	}
5877 	return branch;
5878 }
5879 
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)5880 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5881 			    struct bpf_insn *insn,
5882 			    const struct bpf_reg_state *ptr_reg,
5883 			    const struct bpf_reg_state *off_reg,
5884 			    struct bpf_reg_state *dst_reg,
5885 			    struct bpf_sanitize_info *info,
5886 			    const bool commit_window)
5887 {
5888 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
5889 	struct bpf_verifier_state *vstate = env->cur_state;
5890 	bool off_is_imm = tnum_is_const(off_reg->var_off);
5891 	bool off_is_neg = off_reg->smin_value < 0;
5892 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
5893 	u8 opcode = BPF_OP(insn->code);
5894 	u32 alu_state, alu_limit;
5895 	struct bpf_reg_state tmp;
5896 	bool ret;
5897 	int err;
5898 
5899 	if (can_skip_alu_sanitation(env, insn))
5900 		return 0;
5901 
5902 	/* We already marked aux for masking from non-speculative
5903 	 * paths, thus we got here in the first place. We only care
5904 	 * to explore bad access from here.
5905 	 */
5906 	if (vstate->speculative)
5907 		goto do_sim;
5908 
5909 	if (!commit_window) {
5910 		if (!tnum_is_const(off_reg->var_off) &&
5911 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
5912 			return REASON_BOUNDS;
5913 
5914 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
5915 				     (opcode == BPF_SUB && !off_is_neg);
5916 	}
5917 
5918 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
5919 	if (err < 0)
5920 		return err;
5921 
5922 	if (commit_window) {
5923 		/* In commit phase we narrow the masking window based on
5924 		 * the observed pointer move after the simulated operation.
5925 		 */
5926 		alu_state = info->aux.alu_state;
5927 		alu_limit = abs(info->aux.alu_limit - alu_limit);
5928 	} else {
5929 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5930 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
5931 		alu_state |= ptr_is_dst_reg ?
5932 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5933 
5934 		/* Limit pruning on unknown scalars to enable deep search for
5935 		 * potential masking differences from other program paths.
5936 		 */
5937 		if (!off_is_imm)
5938 			env->explore_alu_limits = true;
5939 	}
5940 
5941 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
5942 	if (err < 0)
5943 		return err;
5944 do_sim:
5945 	/* If we're in commit phase, we're done here given we already
5946 	 * pushed the truncated dst_reg into the speculative verification
5947 	 * stack.
5948 	 *
5949 	 * Also, when register is a known constant, we rewrite register-based
5950 	 * operation to immediate-based, and thus do not need masking (and as
5951 	 * a consequence, do not need to simulate the zero-truncation either).
5952 	 */
5953 	if (commit_window || off_is_imm)
5954 		return 0;
5955 
5956 	/* Simulate and find potential out-of-bounds access under
5957 	 * speculative execution from truncation as a result of
5958 	 * masking when off was not within expected range. If off
5959 	 * sits in dst, then we temporarily need to move ptr there
5960 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5961 	 * for cases where we use K-based arithmetic in one direction
5962 	 * and truncated reg-based in the other in order to explore
5963 	 * bad access.
5964 	 */
5965 	if (!ptr_is_dst_reg) {
5966 		tmp = *dst_reg;
5967 		copy_register_state(dst_reg, ptr_reg);
5968 	}
5969 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
5970 					env->insn_idx);
5971 	if (!ptr_is_dst_reg && ret)
5972 		*dst_reg = tmp;
5973 	return !ret ? REASON_STACK : 0;
5974 }
5975 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)5976 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
5977 {
5978 	struct bpf_verifier_state *vstate = env->cur_state;
5979 
5980 	/* If we simulate paths under speculation, we don't update the
5981 	 * insn as 'seen' such that when we verify unreachable paths in
5982 	 * the non-speculative domain, sanitize_dead_code() can still
5983 	 * rewrite/sanitize them.
5984 	 */
5985 	if (!vstate->speculative)
5986 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
5987 }
5988 
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)5989 static int sanitize_err(struct bpf_verifier_env *env,
5990 			const struct bpf_insn *insn, int reason,
5991 			const struct bpf_reg_state *off_reg,
5992 			const struct bpf_reg_state *dst_reg)
5993 {
5994 	static const char *err = "pointer arithmetic with it prohibited for !root";
5995 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
5996 	u32 dst = insn->dst_reg, src = insn->src_reg;
5997 
5998 	switch (reason) {
5999 	case REASON_BOUNDS:
6000 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6001 			off_reg == dst_reg ? dst : src, err);
6002 		break;
6003 	case REASON_TYPE:
6004 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6005 			off_reg == dst_reg ? src : dst, err);
6006 		break;
6007 	case REASON_PATHS:
6008 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6009 			dst, op, err);
6010 		break;
6011 	case REASON_LIMIT:
6012 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6013 			dst, op, err);
6014 		break;
6015 	case REASON_STACK:
6016 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6017 			dst, err);
6018 		break;
6019 	default:
6020 		verbose(env, "verifier internal error: unknown reason (%d)\n",
6021 			reason);
6022 		break;
6023 	}
6024 
6025 	return -EACCES;
6026 }
6027 
6028 /* check that stack access falls within stack limits and that 'reg' doesn't
6029  * have a variable offset.
6030  *
6031  * Variable offset is prohibited for unprivileged mode for simplicity since it
6032  * requires corresponding support in Spectre masking for stack ALU.  See also
6033  * retrieve_ptr_limit().
6034  *
6035  *
6036  * 'off' includes 'reg->off'.
6037  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)6038 static int check_stack_access_for_ptr_arithmetic(
6039 				struct bpf_verifier_env *env,
6040 				int regno,
6041 				const struct bpf_reg_state *reg,
6042 				int off)
6043 {
6044 	if (!tnum_is_const(reg->var_off)) {
6045 		char tn_buf[48];
6046 
6047 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6048 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6049 			regno, tn_buf, off);
6050 		return -EACCES;
6051 	}
6052 
6053 	if (off >= 0 || off < -MAX_BPF_STACK) {
6054 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
6055 			"prohibited for !root; off=%d\n", regno, off);
6056 		return -EACCES;
6057 	}
6058 
6059 	return 0;
6060 }
6061 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)6062 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6063 				 const struct bpf_insn *insn,
6064 				 const struct bpf_reg_state *dst_reg)
6065 {
6066 	u32 dst = insn->dst_reg;
6067 
6068 	/* For unprivileged we require that resulting offset must be in bounds
6069 	 * in order to be able to sanitize access later on.
6070 	 */
6071 	if (env->bypass_spec_v1)
6072 		return 0;
6073 
6074 	switch (dst_reg->type) {
6075 	case PTR_TO_STACK:
6076 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6077 					dst_reg->off + dst_reg->var_off.value))
6078 			return -EACCES;
6079 		break;
6080 	case PTR_TO_MAP_VALUE:
6081 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6082 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6083 				"prohibited for !root\n", dst);
6084 			return -EACCES;
6085 		}
6086 		break;
6087 	default:
6088 		break;
6089 	}
6090 
6091 	return 0;
6092 }
6093 
6094 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6095  * Caller should also handle BPF_MOV case separately.
6096  * If we return -EACCES, caller may want to try again treating pointer as a
6097  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
6098  */
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)6099 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6100 				   struct bpf_insn *insn,
6101 				   const struct bpf_reg_state *ptr_reg,
6102 				   const struct bpf_reg_state *off_reg)
6103 {
6104 	struct bpf_verifier_state *vstate = env->cur_state;
6105 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
6106 	struct bpf_reg_state *regs = state->regs, *dst_reg;
6107 	bool known = tnum_is_const(off_reg->var_off);
6108 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6109 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6110 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6111 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6112 	struct bpf_sanitize_info info = {};
6113 	u8 opcode = BPF_OP(insn->code);
6114 	u32 dst = insn->dst_reg;
6115 	int ret;
6116 
6117 	dst_reg = &regs[dst];
6118 
6119 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6120 	    smin_val > smax_val || umin_val > umax_val) {
6121 		/* Taint dst register if offset had invalid bounds derived from
6122 		 * e.g. dead branches.
6123 		 */
6124 		__mark_reg_unknown(env, dst_reg);
6125 		return 0;
6126 	}
6127 
6128 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
6129 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
6130 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6131 			__mark_reg_unknown(env, dst_reg);
6132 			return 0;
6133 		}
6134 
6135 		verbose(env,
6136 			"R%d 32-bit pointer arithmetic prohibited\n",
6137 			dst);
6138 		return -EACCES;
6139 	}
6140 
6141 	if (ptr_reg->type & PTR_MAYBE_NULL) {
6142 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6143 			dst, reg_type_str(env, ptr_reg->type));
6144 		return -EACCES;
6145 	}
6146 
6147 	switch (base_type(ptr_reg->type)) {
6148 	case PTR_TO_FLOW_KEYS:
6149 		if (known)
6150 			break;
6151 		fallthrough;
6152 	case CONST_PTR_TO_MAP:
6153 		/* smin_val represents the known value */
6154 		if (known && smin_val == 0 && opcode == BPF_ADD)
6155 			break;
6156 		fallthrough;
6157 	case PTR_TO_PACKET_END:
6158 	case PTR_TO_SOCKET:
6159 	case PTR_TO_SOCK_COMMON:
6160 	case PTR_TO_TCP_SOCK:
6161 	case PTR_TO_XDP_SOCK:
6162 reject:
6163 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6164 			dst, reg_type_str(env, ptr_reg->type));
6165 		return -EACCES;
6166 	default:
6167 		if (type_may_be_null(ptr_reg->type))
6168 			goto reject;
6169 		break;
6170 	}
6171 
6172 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6173 	 * The id may be overwritten later if we create a new variable offset.
6174 	 */
6175 	dst_reg->type = ptr_reg->type;
6176 	dst_reg->id = ptr_reg->id;
6177 
6178 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6179 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6180 		return -EINVAL;
6181 
6182 	/* pointer types do not carry 32-bit bounds at the moment. */
6183 	__mark_reg32_unbounded(dst_reg);
6184 
6185 	if (sanitize_needed(opcode)) {
6186 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6187 				       &info, false);
6188 		if (ret < 0)
6189 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6190 	}
6191 
6192 	switch (opcode) {
6193 	case BPF_ADD:
6194 		/* We can take a fixed offset as long as it doesn't overflow
6195 		 * the s32 'off' field
6196 		 */
6197 		if (known && (ptr_reg->off + smin_val ==
6198 			      (s64)(s32)(ptr_reg->off + smin_val))) {
6199 			/* pointer += K.  Accumulate it into fixed offset */
6200 			dst_reg->smin_value = smin_ptr;
6201 			dst_reg->smax_value = smax_ptr;
6202 			dst_reg->umin_value = umin_ptr;
6203 			dst_reg->umax_value = umax_ptr;
6204 			dst_reg->var_off = ptr_reg->var_off;
6205 			dst_reg->off = ptr_reg->off + smin_val;
6206 			dst_reg->raw = ptr_reg->raw;
6207 			break;
6208 		}
6209 		/* A new variable offset is created.  Note that off_reg->off
6210 		 * == 0, since it's a scalar.
6211 		 * dst_reg gets the pointer type and since some positive
6212 		 * integer value was added to the pointer, give it a new 'id'
6213 		 * if it's a PTR_TO_PACKET.
6214 		 * this creates a new 'base' pointer, off_reg (variable) gets
6215 		 * added into the variable offset, and we copy the fixed offset
6216 		 * from ptr_reg.
6217 		 */
6218 		if (signed_add_overflows(smin_ptr, smin_val) ||
6219 		    signed_add_overflows(smax_ptr, smax_val)) {
6220 			dst_reg->smin_value = S64_MIN;
6221 			dst_reg->smax_value = S64_MAX;
6222 		} else {
6223 			dst_reg->smin_value = smin_ptr + smin_val;
6224 			dst_reg->smax_value = smax_ptr + smax_val;
6225 		}
6226 		if (umin_ptr + umin_val < umin_ptr ||
6227 		    umax_ptr + umax_val < umax_ptr) {
6228 			dst_reg->umin_value = 0;
6229 			dst_reg->umax_value = U64_MAX;
6230 		} else {
6231 			dst_reg->umin_value = umin_ptr + umin_val;
6232 			dst_reg->umax_value = umax_ptr + umax_val;
6233 		}
6234 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6235 		dst_reg->off = ptr_reg->off;
6236 		dst_reg->raw = ptr_reg->raw;
6237 		if (reg_is_pkt_pointer(ptr_reg)) {
6238 			dst_reg->id = ++env->id_gen;
6239 			/* something was added to pkt_ptr, set range to zero */
6240 			dst_reg->raw = 0;
6241 		}
6242 		break;
6243 	case BPF_SUB:
6244 		if (dst_reg == off_reg) {
6245 			/* scalar -= pointer.  Creates an unknown scalar */
6246 			verbose(env, "R%d tried to subtract pointer from scalar\n",
6247 				dst);
6248 			return -EACCES;
6249 		}
6250 		/* We don't allow subtraction from FP, because (according to
6251 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
6252 		 * be able to deal with it.
6253 		 */
6254 		if (ptr_reg->type == PTR_TO_STACK) {
6255 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
6256 				dst);
6257 			return -EACCES;
6258 		}
6259 		if (known && (ptr_reg->off - smin_val ==
6260 			      (s64)(s32)(ptr_reg->off - smin_val))) {
6261 			/* pointer -= K.  Subtract it from fixed offset */
6262 			dst_reg->smin_value = smin_ptr;
6263 			dst_reg->smax_value = smax_ptr;
6264 			dst_reg->umin_value = umin_ptr;
6265 			dst_reg->umax_value = umax_ptr;
6266 			dst_reg->var_off = ptr_reg->var_off;
6267 			dst_reg->id = ptr_reg->id;
6268 			dst_reg->off = ptr_reg->off - smin_val;
6269 			dst_reg->raw = ptr_reg->raw;
6270 			break;
6271 		}
6272 		/* A new variable offset is created.  If the subtrahend is known
6273 		 * nonnegative, then any reg->range we had before is still good.
6274 		 */
6275 		if (signed_sub_overflows(smin_ptr, smax_val) ||
6276 		    signed_sub_overflows(smax_ptr, smin_val)) {
6277 			/* Overflow possible, we know nothing */
6278 			dst_reg->smin_value = S64_MIN;
6279 			dst_reg->smax_value = S64_MAX;
6280 		} else {
6281 			dst_reg->smin_value = smin_ptr - smax_val;
6282 			dst_reg->smax_value = smax_ptr - smin_val;
6283 		}
6284 		if (umin_ptr < umax_val) {
6285 			/* Overflow possible, we know nothing */
6286 			dst_reg->umin_value = 0;
6287 			dst_reg->umax_value = U64_MAX;
6288 		} else {
6289 			/* Cannot overflow (as long as bounds are consistent) */
6290 			dst_reg->umin_value = umin_ptr - umax_val;
6291 			dst_reg->umax_value = umax_ptr - umin_val;
6292 		}
6293 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6294 		dst_reg->off = ptr_reg->off;
6295 		dst_reg->raw = ptr_reg->raw;
6296 		if (reg_is_pkt_pointer(ptr_reg)) {
6297 			dst_reg->id = ++env->id_gen;
6298 			/* something was added to pkt_ptr, set range to zero */
6299 			if (smin_val < 0)
6300 				dst_reg->raw = 0;
6301 		}
6302 		break;
6303 	case BPF_AND:
6304 	case BPF_OR:
6305 	case BPF_XOR:
6306 		/* bitwise ops on pointers are troublesome, prohibit. */
6307 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6308 			dst, bpf_alu_string[opcode >> 4]);
6309 		return -EACCES;
6310 	default:
6311 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
6312 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6313 			dst, bpf_alu_string[opcode >> 4]);
6314 		return -EACCES;
6315 	}
6316 
6317 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6318 		return -EINVAL;
6319 	reg_bounds_sync(dst_reg);
6320 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6321 		return -EACCES;
6322 	if (sanitize_needed(opcode)) {
6323 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6324 				       &info, true);
6325 		if (ret < 0)
6326 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
6327 	}
6328 
6329 	return 0;
6330 }
6331 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6332 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6333 				 struct bpf_reg_state *src_reg)
6334 {
6335 	s32 smin_val = src_reg->s32_min_value;
6336 	s32 smax_val = src_reg->s32_max_value;
6337 	u32 umin_val = src_reg->u32_min_value;
6338 	u32 umax_val = src_reg->u32_max_value;
6339 
6340 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6341 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6342 		dst_reg->s32_min_value = S32_MIN;
6343 		dst_reg->s32_max_value = S32_MAX;
6344 	} else {
6345 		dst_reg->s32_min_value += smin_val;
6346 		dst_reg->s32_max_value += smax_val;
6347 	}
6348 	if (dst_reg->u32_min_value + umin_val < umin_val ||
6349 	    dst_reg->u32_max_value + umax_val < umax_val) {
6350 		dst_reg->u32_min_value = 0;
6351 		dst_reg->u32_max_value = U32_MAX;
6352 	} else {
6353 		dst_reg->u32_min_value += umin_val;
6354 		dst_reg->u32_max_value += umax_val;
6355 	}
6356 }
6357 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6358 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6359 			       struct bpf_reg_state *src_reg)
6360 {
6361 	s64 smin_val = src_reg->smin_value;
6362 	s64 smax_val = src_reg->smax_value;
6363 	u64 umin_val = src_reg->umin_value;
6364 	u64 umax_val = src_reg->umax_value;
6365 
6366 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6367 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
6368 		dst_reg->smin_value = S64_MIN;
6369 		dst_reg->smax_value = S64_MAX;
6370 	} else {
6371 		dst_reg->smin_value += smin_val;
6372 		dst_reg->smax_value += smax_val;
6373 	}
6374 	if (dst_reg->umin_value + umin_val < umin_val ||
6375 	    dst_reg->umax_value + umax_val < umax_val) {
6376 		dst_reg->umin_value = 0;
6377 		dst_reg->umax_value = U64_MAX;
6378 	} else {
6379 		dst_reg->umin_value += umin_val;
6380 		dst_reg->umax_value += umax_val;
6381 	}
6382 }
6383 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6384 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6385 				 struct bpf_reg_state *src_reg)
6386 {
6387 	s32 smin_val = src_reg->s32_min_value;
6388 	s32 smax_val = src_reg->s32_max_value;
6389 	u32 umin_val = src_reg->u32_min_value;
6390 	u32 umax_val = src_reg->u32_max_value;
6391 
6392 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6393 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6394 		/* Overflow possible, we know nothing */
6395 		dst_reg->s32_min_value = S32_MIN;
6396 		dst_reg->s32_max_value = S32_MAX;
6397 	} else {
6398 		dst_reg->s32_min_value -= smax_val;
6399 		dst_reg->s32_max_value -= smin_val;
6400 	}
6401 	if (dst_reg->u32_min_value < umax_val) {
6402 		/* Overflow possible, we know nothing */
6403 		dst_reg->u32_min_value = 0;
6404 		dst_reg->u32_max_value = U32_MAX;
6405 	} else {
6406 		/* Cannot overflow (as long as bounds are consistent) */
6407 		dst_reg->u32_min_value -= umax_val;
6408 		dst_reg->u32_max_value -= umin_val;
6409 	}
6410 }
6411 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6412 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6413 			       struct bpf_reg_state *src_reg)
6414 {
6415 	s64 smin_val = src_reg->smin_value;
6416 	s64 smax_val = src_reg->smax_value;
6417 	u64 umin_val = src_reg->umin_value;
6418 	u64 umax_val = src_reg->umax_value;
6419 
6420 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6421 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6422 		/* Overflow possible, we know nothing */
6423 		dst_reg->smin_value = S64_MIN;
6424 		dst_reg->smax_value = S64_MAX;
6425 	} else {
6426 		dst_reg->smin_value -= smax_val;
6427 		dst_reg->smax_value -= smin_val;
6428 	}
6429 	if (dst_reg->umin_value < umax_val) {
6430 		/* Overflow possible, we know nothing */
6431 		dst_reg->umin_value = 0;
6432 		dst_reg->umax_value = U64_MAX;
6433 	} else {
6434 		/* Cannot overflow (as long as bounds are consistent) */
6435 		dst_reg->umin_value -= umax_val;
6436 		dst_reg->umax_value -= umin_val;
6437 	}
6438 }
6439 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6440 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6441 				 struct bpf_reg_state *src_reg)
6442 {
6443 	s32 smin_val = src_reg->s32_min_value;
6444 	u32 umin_val = src_reg->u32_min_value;
6445 	u32 umax_val = src_reg->u32_max_value;
6446 
6447 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6448 		/* Ain't nobody got time to multiply that sign */
6449 		__mark_reg32_unbounded(dst_reg);
6450 		return;
6451 	}
6452 	/* Both values are positive, so we can work with unsigned and
6453 	 * copy the result to signed (unless it exceeds S32_MAX).
6454 	 */
6455 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6456 		/* Potential overflow, we know nothing */
6457 		__mark_reg32_unbounded(dst_reg);
6458 		return;
6459 	}
6460 	dst_reg->u32_min_value *= umin_val;
6461 	dst_reg->u32_max_value *= umax_val;
6462 	if (dst_reg->u32_max_value > S32_MAX) {
6463 		/* Overflow possible, we know nothing */
6464 		dst_reg->s32_min_value = S32_MIN;
6465 		dst_reg->s32_max_value = S32_MAX;
6466 	} else {
6467 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6468 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6469 	}
6470 }
6471 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6472 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6473 			       struct bpf_reg_state *src_reg)
6474 {
6475 	s64 smin_val = src_reg->smin_value;
6476 	u64 umin_val = src_reg->umin_value;
6477 	u64 umax_val = src_reg->umax_value;
6478 
6479 	if (smin_val < 0 || dst_reg->smin_value < 0) {
6480 		/* Ain't nobody got time to multiply that sign */
6481 		__mark_reg64_unbounded(dst_reg);
6482 		return;
6483 	}
6484 	/* Both values are positive, so we can work with unsigned and
6485 	 * copy the result to signed (unless it exceeds S64_MAX).
6486 	 */
6487 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6488 		/* Potential overflow, we know nothing */
6489 		__mark_reg64_unbounded(dst_reg);
6490 		return;
6491 	}
6492 	dst_reg->umin_value *= umin_val;
6493 	dst_reg->umax_value *= umax_val;
6494 	if (dst_reg->umax_value > S64_MAX) {
6495 		/* Overflow possible, we know nothing */
6496 		dst_reg->smin_value = S64_MIN;
6497 		dst_reg->smax_value = S64_MAX;
6498 	} else {
6499 		dst_reg->smin_value = dst_reg->umin_value;
6500 		dst_reg->smax_value = dst_reg->umax_value;
6501 	}
6502 }
6503 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6504 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6505 				 struct bpf_reg_state *src_reg)
6506 {
6507 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6508 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6509 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6510 	s32 smin_val = src_reg->s32_min_value;
6511 	u32 umax_val = src_reg->u32_max_value;
6512 
6513 	if (src_known && dst_known) {
6514 		__mark_reg32_known(dst_reg, var32_off.value);
6515 		return;
6516 	}
6517 
6518 	/* We get our minimum from the var_off, since that's inherently
6519 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6520 	 */
6521 	dst_reg->u32_min_value = var32_off.value;
6522 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6523 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6524 		/* Lose signed bounds when ANDing negative numbers,
6525 		 * ain't nobody got time for that.
6526 		 */
6527 		dst_reg->s32_min_value = S32_MIN;
6528 		dst_reg->s32_max_value = S32_MAX;
6529 	} else {
6530 		/* ANDing two positives gives a positive, so safe to
6531 		 * cast result into s64.
6532 		 */
6533 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6534 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6535 	}
6536 }
6537 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6538 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6539 			       struct bpf_reg_state *src_reg)
6540 {
6541 	bool src_known = tnum_is_const(src_reg->var_off);
6542 	bool dst_known = tnum_is_const(dst_reg->var_off);
6543 	s64 smin_val = src_reg->smin_value;
6544 	u64 umax_val = src_reg->umax_value;
6545 
6546 	if (src_known && dst_known) {
6547 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6548 		return;
6549 	}
6550 
6551 	/* We get our minimum from the var_off, since that's inherently
6552 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
6553 	 */
6554 	dst_reg->umin_value = dst_reg->var_off.value;
6555 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6556 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6557 		/* Lose signed bounds when ANDing negative numbers,
6558 		 * ain't nobody got time for that.
6559 		 */
6560 		dst_reg->smin_value = S64_MIN;
6561 		dst_reg->smax_value = S64_MAX;
6562 	} else {
6563 		/* ANDing two positives gives a positive, so safe to
6564 		 * cast result into s64.
6565 		 */
6566 		dst_reg->smin_value = dst_reg->umin_value;
6567 		dst_reg->smax_value = dst_reg->umax_value;
6568 	}
6569 	/* We may learn something more from the var_off */
6570 	__update_reg_bounds(dst_reg);
6571 }
6572 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6573 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6574 				struct bpf_reg_state *src_reg)
6575 {
6576 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6577 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6578 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6579 	s32 smin_val = src_reg->s32_min_value;
6580 	u32 umin_val = src_reg->u32_min_value;
6581 
6582 	if (src_known && dst_known) {
6583 		__mark_reg32_known(dst_reg, var32_off.value);
6584 		return;
6585 	}
6586 
6587 	/* We get our maximum from the var_off, and our minimum is the
6588 	 * maximum of the operands' minima
6589 	 */
6590 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6591 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6592 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6593 		/* Lose signed bounds when ORing negative numbers,
6594 		 * ain't nobody got time for that.
6595 		 */
6596 		dst_reg->s32_min_value = S32_MIN;
6597 		dst_reg->s32_max_value = S32_MAX;
6598 	} else {
6599 		/* ORing two positives gives a positive, so safe to
6600 		 * cast result into s64.
6601 		 */
6602 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6603 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6604 	}
6605 }
6606 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6607 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6608 			      struct bpf_reg_state *src_reg)
6609 {
6610 	bool src_known = tnum_is_const(src_reg->var_off);
6611 	bool dst_known = tnum_is_const(dst_reg->var_off);
6612 	s64 smin_val = src_reg->smin_value;
6613 	u64 umin_val = src_reg->umin_value;
6614 
6615 	if (src_known && dst_known) {
6616 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6617 		return;
6618 	}
6619 
6620 	/* We get our maximum from the var_off, and our minimum is the
6621 	 * maximum of the operands' minima
6622 	 */
6623 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6624 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6625 	if (dst_reg->smin_value < 0 || smin_val < 0) {
6626 		/* Lose signed bounds when ORing negative numbers,
6627 		 * ain't nobody got time for that.
6628 		 */
6629 		dst_reg->smin_value = S64_MIN;
6630 		dst_reg->smax_value = S64_MAX;
6631 	} else {
6632 		/* ORing two positives gives a positive, so safe to
6633 		 * cast result into s64.
6634 		 */
6635 		dst_reg->smin_value = dst_reg->umin_value;
6636 		dst_reg->smax_value = dst_reg->umax_value;
6637 	}
6638 	/* We may learn something more from the var_off */
6639 	__update_reg_bounds(dst_reg);
6640 }
6641 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6642 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6643 				 struct bpf_reg_state *src_reg)
6644 {
6645 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
6646 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6647 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6648 	s32 smin_val = src_reg->s32_min_value;
6649 
6650 	if (src_known && dst_known) {
6651 		__mark_reg32_known(dst_reg, var32_off.value);
6652 		return;
6653 	}
6654 
6655 	/* We get both minimum and maximum from the var32_off. */
6656 	dst_reg->u32_min_value = var32_off.value;
6657 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6658 
6659 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6660 		/* XORing two positive sign numbers gives a positive,
6661 		 * so safe to cast u32 result into s32.
6662 		 */
6663 		dst_reg->s32_min_value = dst_reg->u32_min_value;
6664 		dst_reg->s32_max_value = dst_reg->u32_max_value;
6665 	} else {
6666 		dst_reg->s32_min_value = S32_MIN;
6667 		dst_reg->s32_max_value = S32_MAX;
6668 	}
6669 }
6670 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6671 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6672 			       struct bpf_reg_state *src_reg)
6673 {
6674 	bool src_known = tnum_is_const(src_reg->var_off);
6675 	bool dst_known = tnum_is_const(dst_reg->var_off);
6676 	s64 smin_val = src_reg->smin_value;
6677 
6678 	if (src_known && dst_known) {
6679 		/* dst_reg->var_off.value has been updated earlier */
6680 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
6681 		return;
6682 	}
6683 
6684 	/* We get both minimum and maximum from the var_off. */
6685 	dst_reg->umin_value = dst_reg->var_off.value;
6686 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6687 
6688 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6689 		/* XORing two positive sign numbers gives a positive,
6690 		 * so safe to cast u64 result into s64.
6691 		 */
6692 		dst_reg->smin_value = dst_reg->umin_value;
6693 		dst_reg->smax_value = dst_reg->umax_value;
6694 	} else {
6695 		dst_reg->smin_value = S64_MIN;
6696 		dst_reg->smax_value = S64_MAX;
6697 	}
6698 
6699 	__update_reg_bounds(dst_reg);
6700 }
6701 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6702 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6703 				   u64 umin_val, u64 umax_val)
6704 {
6705 	/* We lose all sign bit information (except what we can pick
6706 	 * up from var_off)
6707 	 */
6708 	dst_reg->s32_min_value = S32_MIN;
6709 	dst_reg->s32_max_value = S32_MAX;
6710 	/* If we might shift our top bit out, then we know nothing */
6711 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6712 		dst_reg->u32_min_value = 0;
6713 		dst_reg->u32_max_value = U32_MAX;
6714 	} else {
6715 		dst_reg->u32_min_value <<= umin_val;
6716 		dst_reg->u32_max_value <<= umax_val;
6717 	}
6718 }
6719 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6720 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6721 				 struct bpf_reg_state *src_reg)
6722 {
6723 	u32 umax_val = src_reg->u32_max_value;
6724 	u32 umin_val = src_reg->u32_min_value;
6725 	/* u32 alu operation will zext upper bits */
6726 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6727 
6728 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6729 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6730 	/* Not required but being careful mark reg64 bounds as unknown so
6731 	 * that we are forced to pick them up from tnum and zext later and
6732 	 * if some path skips this step we are still safe.
6733 	 */
6734 	__mark_reg64_unbounded(dst_reg);
6735 	__update_reg32_bounds(dst_reg);
6736 }
6737 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6738 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6739 				   u64 umin_val, u64 umax_val)
6740 {
6741 	/* Special case <<32 because it is a common compiler pattern to sign
6742 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6743 	 * positive we know this shift will also be positive so we can track
6744 	 * bounds correctly. Otherwise we lose all sign bit information except
6745 	 * what we can pick up from var_off. Perhaps we can generalize this
6746 	 * later to shifts of any length.
6747 	 */
6748 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6749 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6750 	else
6751 		dst_reg->smax_value = S64_MAX;
6752 
6753 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6754 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6755 	else
6756 		dst_reg->smin_value = S64_MIN;
6757 
6758 	/* If we might shift our top bit out, then we know nothing */
6759 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6760 		dst_reg->umin_value = 0;
6761 		dst_reg->umax_value = U64_MAX;
6762 	} else {
6763 		dst_reg->umin_value <<= umin_val;
6764 		dst_reg->umax_value <<= umax_val;
6765 	}
6766 }
6767 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6768 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6769 			       struct bpf_reg_state *src_reg)
6770 {
6771 	u64 umax_val = src_reg->umax_value;
6772 	u64 umin_val = src_reg->umin_value;
6773 
6774 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
6775 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6776 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6777 
6778 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6779 	/* We may learn something more from the var_off */
6780 	__update_reg_bounds(dst_reg);
6781 }
6782 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6783 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6784 				 struct bpf_reg_state *src_reg)
6785 {
6786 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
6787 	u32 umax_val = src_reg->u32_max_value;
6788 	u32 umin_val = src_reg->u32_min_value;
6789 
6790 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6791 	 * be negative, then either:
6792 	 * 1) src_reg might be zero, so the sign bit of the result is
6793 	 *    unknown, so we lose our signed bounds
6794 	 * 2) it's known negative, thus the unsigned bounds capture the
6795 	 *    signed bounds
6796 	 * 3) the signed bounds cross zero, so they tell us nothing
6797 	 *    about the result
6798 	 * If the value in dst_reg is known nonnegative, then again the
6799 	 * unsigned bounts capture the signed bounds.
6800 	 * Thus, in all cases it suffices to blow away our signed bounds
6801 	 * and rely on inferring new ones from the unsigned bounds and
6802 	 * var_off of the result.
6803 	 */
6804 	dst_reg->s32_min_value = S32_MIN;
6805 	dst_reg->s32_max_value = S32_MAX;
6806 
6807 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
6808 	dst_reg->u32_min_value >>= umax_val;
6809 	dst_reg->u32_max_value >>= umin_val;
6810 
6811 	__mark_reg64_unbounded(dst_reg);
6812 	__update_reg32_bounds(dst_reg);
6813 }
6814 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6815 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6816 			       struct bpf_reg_state *src_reg)
6817 {
6818 	u64 umax_val = src_reg->umax_value;
6819 	u64 umin_val = src_reg->umin_value;
6820 
6821 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
6822 	 * be negative, then either:
6823 	 * 1) src_reg might be zero, so the sign bit of the result is
6824 	 *    unknown, so we lose our signed bounds
6825 	 * 2) it's known negative, thus the unsigned bounds capture the
6826 	 *    signed bounds
6827 	 * 3) the signed bounds cross zero, so they tell us nothing
6828 	 *    about the result
6829 	 * If the value in dst_reg is known nonnegative, then again the
6830 	 * unsigned bounts capture the signed bounds.
6831 	 * Thus, in all cases it suffices to blow away our signed bounds
6832 	 * and rely on inferring new ones from the unsigned bounds and
6833 	 * var_off of the result.
6834 	 */
6835 	dst_reg->smin_value = S64_MIN;
6836 	dst_reg->smax_value = S64_MAX;
6837 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6838 	dst_reg->umin_value >>= umax_val;
6839 	dst_reg->umax_value >>= umin_val;
6840 
6841 	/* Its not easy to operate on alu32 bounds here because it depends
6842 	 * on bits being shifted in. Take easy way out and mark unbounded
6843 	 * so we can recalculate later from tnum.
6844 	 */
6845 	__mark_reg32_unbounded(dst_reg);
6846 	__update_reg_bounds(dst_reg);
6847 }
6848 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6849 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6850 				  struct bpf_reg_state *src_reg)
6851 {
6852 	u64 umin_val = src_reg->u32_min_value;
6853 
6854 	/* Upon reaching here, src_known is true and
6855 	 * umax_val is equal to umin_val.
6856 	 */
6857 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6858 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6859 
6860 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6861 
6862 	/* blow away the dst_reg umin_value/umax_value and rely on
6863 	 * dst_reg var_off to refine the result.
6864 	 */
6865 	dst_reg->u32_min_value = 0;
6866 	dst_reg->u32_max_value = U32_MAX;
6867 
6868 	__mark_reg64_unbounded(dst_reg);
6869 	__update_reg32_bounds(dst_reg);
6870 }
6871 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6872 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6873 				struct bpf_reg_state *src_reg)
6874 {
6875 	u64 umin_val = src_reg->umin_value;
6876 
6877 	/* Upon reaching here, src_known is true and umax_val is equal
6878 	 * to umin_val.
6879 	 */
6880 	dst_reg->smin_value >>= umin_val;
6881 	dst_reg->smax_value >>= umin_val;
6882 
6883 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6884 
6885 	/* blow away the dst_reg umin_value/umax_value and rely on
6886 	 * dst_reg var_off to refine the result.
6887 	 */
6888 	dst_reg->umin_value = 0;
6889 	dst_reg->umax_value = U64_MAX;
6890 
6891 	/* Its not easy to operate on alu32 bounds here because it depends
6892 	 * on bits being shifted in from upper 32-bits. Take easy way out
6893 	 * and mark unbounded so we can recalculate later from tnum.
6894 	 */
6895 	__mark_reg32_unbounded(dst_reg);
6896 	__update_reg_bounds(dst_reg);
6897 }
6898 
6899 /* WARNING: This function does calculations on 64-bit values, but the actual
6900  * execution may occur on 32-bit values. Therefore, things like bitshifts
6901  * need extra checks in the 32-bit case.
6902  */
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)6903 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6904 				      struct bpf_insn *insn,
6905 				      struct bpf_reg_state *dst_reg,
6906 				      struct bpf_reg_state src_reg)
6907 {
6908 	struct bpf_reg_state *regs = cur_regs(env);
6909 	u8 opcode = BPF_OP(insn->code);
6910 	bool src_known;
6911 	s64 smin_val, smax_val;
6912 	u64 umin_val, umax_val;
6913 	s32 s32_min_val, s32_max_val;
6914 	u32 u32_min_val, u32_max_val;
6915 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6916 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6917 	int ret;
6918 
6919 	smin_val = src_reg.smin_value;
6920 	smax_val = src_reg.smax_value;
6921 	umin_val = src_reg.umin_value;
6922 	umax_val = src_reg.umax_value;
6923 
6924 	s32_min_val = src_reg.s32_min_value;
6925 	s32_max_val = src_reg.s32_max_value;
6926 	u32_min_val = src_reg.u32_min_value;
6927 	u32_max_val = src_reg.u32_max_value;
6928 
6929 	if (alu32) {
6930 		src_known = tnum_subreg_is_const(src_reg.var_off);
6931 		if ((src_known &&
6932 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6933 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6934 			/* Taint dst register if offset had invalid bounds
6935 			 * derived from e.g. dead branches.
6936 			 */
6937 			__mark_reg_unknown(env, dst_reg);
6938 			return 0;
6939 		}
6940 	} else {
6941 		src_known = tnum_is_const(src_reg.var_off);
6942 		if ((src_known &&
6943 		     (smin_val != smax_val || umin_val != umax_val)) ||
6944 		    smin_val > smax_val || umin_val > umax_val) {
6945 			/* Taint dst register if offset had invalid bounds
6946 			 * derived from e.g. dead branches.
6947 			 */
6948 			__mark_reg_unknown(env, dst_reg);
6949 			return 0;
6950 		}
6951 	}
6952 
6953 	if (!src_known &&
6954 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6955 		__mark_reg_unknown(env, dst_reg);
6956 		return 0;
6957 	}
6958 
6959 	if (sanitize_needed(opcode)) {
6960 		ret = sanitize_val_alu(env, insn);
6961 		if (ret < 0)
6962 			return sanitize_err(env, insn, ret, NULL, NULL);
6963 	}
6964 
6965 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6966 	 * There are two classes of instructions: The first class we track both
6967 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
6968 	 * greatest amount of precision when alu operations are mixed with jmp32
6969 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6970 	 * and BPF_OR. This is possible because these ops have fairly easy to
6971 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6972 	 * See alu32 verifier tests for examples. The second class of
6973 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6974 	 * with regards to tracking sign/unsigned bounds because the bits may
6975 	 * cross subreg boundaries in the alu64 case. When this happens we mark
6976 	 * the reg unbounded in the subreg bound space and use the resulting
6977 	 * tnum to calculate an approximation of the sign/unsigned bounds.
6978 	 */
6979 	switch (opcode) {
6980 	case BPF_ADD:
6981 		scalar32_min_max_add(dst_reg, &src_reg);
6982 		scalar_min_max_add(dst_reg, &src_reg);
6983 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6984 		break;
6985 	case BPF_SUB:
6986 		scalar32_min_max_sub(dst_reg, &src_reg);
6987 		scalar_min_max_sub(dst_reg, &src_reg);
6988 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6989 		break;
6990 	case BPF_MUL:
6991 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6992 		scalar32_min_max_mul(dst_reg, &src_reg);
6993 		scalar_min_max_mul(dst_reg, &src_reg);
6994 		break;
6995 	case BPF_AND:
6996 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6997 		scalar32_min_max_and(dst_reg, &src_reg);
6998 		scalar_min_max_and(dst_reg, &src_reg);
6999 		break;
7000 	case BPF_OR:
7001 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7002 		scalar32_min_max_or(dst_reg, &src_reg);
7003 		scalar_min_max_or(dst_reg, &src_reg);
7004 		break;
7005 	case BPF_XOR:
7006 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7007 		scalar32_min_max_xor(dst_reg, &src_reg);
7008 		scalar_min_max_xor(dst_reg, &src_reg);
7009 		break;
7010 	case BPF_LSH:
7011 		if (umax_val >= insn_bitness) {
7012 			/* Shifts greater than 31 or 63 are undefined.
7013 			 * This includes shifts by a negative number.
7014 			 */
7015 			mark_reg_unknown(env, regs, insn->dst_reg);
7016 			break;
7017 		}
7018 		if (alu32)
7019 			scalar32_min_max_lsh(dst_reg, &src_reg);
7020 		else
7021 			scalar_min_max_lsh(dst_reg, &src_reg);
7022 		break;
7023 	case BPF_RSH:
7024 		if (umax_val >= insn_bitness) {
7025 			/* Shifts greater than 31 or 63 are undefined.
7026 			 * This includes shifts by a negative number.
7027 			 */
7028 			mark_reg_unknown(env, regs, insn->dst_reg);
7029 			break;
7030 		}
7031 		if (alu32)
7032 			scalar32_min_max_rsh(dst_reg, &src_reg);
7033 		else
7034 			scalar_min_max_rsh(dst_reg, &src_reg);
7035 		break;
7036 	case BPF_ARSH:
7037 		if (umax_val >= insn_bitness) {
7038 			/* Shifts greater than 31 or 63 are undefined.
7039 			 * This includes shifts by a negative number.
7040 			 */
7041 			mark_reg_unknown(env, regs, insn->dst_reg);
7042 			break;
7043 		}
7044 		if (alu32)
7045 			scalar32_min_max_arsh(dst_reg, &src_reg);
7046 		else
7047 			scalar_min_max_arsh(dst_reg, &src_reg);
7048 		break;
7049 	default:
7050 		mark_reg_unknown(env, regs, insn->dst_reg);
7051 		break;
7052 	}
7053 
7054 	/* ALU32 ops are zero extended into 64bit register */
7055 	if (alu32)
7056 		zext_32_to_64(dst_reg);
7057 	reg_bounds_sync(dst_reg);
7058 	return 0;
7059 }
7060 
7061 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7062  * and var_off.
7063  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)7064 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7065 				   struct bpf_insn *insn)
7066 {
7067 	struct bpf_verifier_state *vstate = env->cur_state;
7068 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7069 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7070 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7071 	u8 opcode = BPF_OP(insn->code);
7072 	int err;
7073 
7074 	dst_reg = &regs[insn->dst_reg];
7075 	src_reg = NULL;
7076 	if (dst_reg->type != SCALAR_VALUE)
7077 		ptr_reg = dst_reg;
7078 	else
7079 		/* Make sure ID is cleared otherwise dst_reg min/max could be
7080 		 * incorrectly propagated into other registers by find_equal_scalars()
7081 		 */
7082 		dst_reg->id = 0;
7083 	if (BPF_SRC(insn->code) == BPF_X) {
7084 		src_reg = &regs[insn->src_reg];
7085 		if (src_reg->type != SCALAR_VALUE) {
7086 			if (dst_reg->type != SCALAR_VALUE) {
7087 				/* Combining two pointers by any ALU op yields
7088 				 * an arbitrary scalar. Disallow all math except
7089 				 * pointer subtraction
7090 				 */
7091 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7092 					mark_reg_unknown(env, regs, insn->dst_reg);
7093 					return 0;
7094 				}
7095 				verbose(env, "R%d pointer %s pointer prohibited\n",
7096 					insn->dst_reg,
7097 					bpf_alu_string[opcode >> 4]);
7098 				return -EACCES;
7099 			} else {
7100 				/* scalar += pointer
7101 				 * This is legal, but we have to reverse our
7102 				 * src/dest handling in computing the range
7103 				 */
7104 				err = mark_chain_precision(env, insn->dst_reg);
7105 				if (err)
7106 					return err;
7107 				return adjust_ptr_min_max_vals(env, insn,
7108 							       src_reg, dst_reg);
7109 			}
7110 		} else if (ptr_reg) {
7111 			/* pointer += scalar */
7112 			err = mark_chain_precision(env, insn->src_reg);
7113 			if (err)
7114 				return err;
7115 			return adjust_ptr_min_max_vals(env, insn,
7116 						       dst_reg, src_reg);
7117 		} else if (dst_reg->precise) {
7118 			/* if dst_reg is precise, src_reg should be precise as well */
7119 			err = mark_chain_precision(env, insn->src_reg);
7120 			if (err)
7121 				return err;
7122 		}
7123 	} else {
7124 		/* Pretend the src is a reg with a known value, since we only
7125 		 * need to be able to read from this state.
7126 		 */
7127 		off_reg.type = SCALAR_VALUE;
7128 		__mark_reg_known(&off_reg, insn->imm);
7129 		src_reg = &off_reg;
7130 		if (ptr_reg) /* pointer += K */
7131 			return adjust_ptr_min_max_vals(env, insn,
7132 						       ptr_reg, src_reg);
7133 	}
7134 
7135 	/* Got here implies adding two SCALAR_VALUEs */
7136 	if (WARN_ON_ONCE(ptr_reg)) {
7137 		print_verifier_state(env, state);
7138 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
7139 		return -EINVAL;
7140 	}
7141 	if (WARN_ON(!src_reg)) {
7142 		print_verifier_state(env, state);
7143 		verbose(env, "verifier internal error: no src_reg\n");
7144 		return -EINVAL;
7145 	}
7146 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7147 }
7148 
7149 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)7150 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7151 {
7152 	struct bpf_reg_state *regs = cur_regs(env);
7153 	u8 opcode = BPF_OP(insn->code);
7154 	int err;
7155 
7156 	if (opcode == BPF_END || opcode == BPF_NEG) {
7157 		if (opcode == BPF_NEG) {
7158 			if (BPF_SRC(insn->code) != 0 ||
7159 			    insn->src_reg != BPF_REG_0 ||
7160 			    insn->off != 0 || insn->imm != 0) {
7161 				verbose(env, "BPF_NEG uses reserved fields\n");
7162 				return -EINVAL;
7163 			}
7164 		} else {
7165 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7166 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7167 			    BPF_CLASS(insn->code) == BPF_ALU64) {
7168 				verbose(env, "BPF_END uses reserved fields\n");
7169 				return -EINVAL;
7170 			}
7171 		}
7172 
7173 		/* check src operand */
7174 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7175 		if (err)
7176 			return err;
7177 
7178 		if (is_pointer_value(env, insn->dst_reg)) {
7179 			verbose(env, "R%d pointer arithmetic prohibited\n",
7180 				insn->dst_reg);
7181 			return -EACCES;
7182 		}
7183 
7184 		/* check dest operand */
7185 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
7186 		if (err)
7187 			return err;
7188 
7189 	} else if (opcode == BPF_MOV) {
7190 
7191 		if (BPF_SRC(insn->code) == BPF_X) {
7192 			if (insn->imm != 0 || insn->off != 0) {
7193 				verbose(env, "BPF_MOV uses reserved fields\n");
7194 				return -EINVAL;
7195 			}
7196 
7197 			/* check src operand */
7198 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7199 			if (err)
7200 				return err;
7201 		} else {
7202 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7203 				verbose(env, "BPF_MOV uses reserved fields\n");
7204 				return -EINVAL;
7205 			}
7206 		}
7207 
7208 		/* check dest operand, mark as required later */
7209 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7210 		if (err)
7211 			return err;
7212 
7213 		if (BPF_SRC(insn->code) == BPF_X) {
7214 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
7215 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7216 
7217 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7218 				/* case: R1 = R2
7219 				 * copy register state to dest reg
7220 				 */
7221 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7222 					/* Assign src and dst registers the same ID
7223 					 * that will be used by find_equal_scalars()
7224 					 * to propagate min/max range.
7225 					 */
7226 					src_reg->id = ++env->id_gen;
7227 				copy_register_state(dst_reg, src_reg);
7228 				dst_reg->live |= REG_LIVE_WRITTEN;
7229 				dst_reg->subreg_def = DEF_NOT_SUBREG;
7230 			} else {
7231 				/* R1 = (u32) R2 */
7232 				if (is_pointer_value(env, insn->src_reg)) {
7233 					verbose(env,
7234 						"R%d partial copy of pointer\n",
7235 						insn->src_reg);
7236 					return -EACCES;
7237 				} else if (src_reg->type == SCALAR_VALUE) {
7238 					copy_register_state(dst_reg, src_reg);
7239 					/* Make sure ID is cleared otherwise
7240 					 * dst_reg min/max could be incorrectly
7241 					 * propagated into src_reg by find_equal_scalars()
7242 					 */
7243 					dst_reg->id = 0;
7244 					dst_reg->live |= REG_LIVE_WRITTEN;
7245 					dst_reg->subreg_def = env->insn_idx + 1;
7246 				} else {
7247 					mark_reg_unknown(env, regs,
7248 							 insn->dst_reg);
7249 				}
7250 				zext_32_to_64(dst_reg);
7251 				reg_bounds_sync(dst_reg);
7252 			}
7253 		} else {
7254 			/* case: R = imm
7255 			 * remember the value we stored into this reg
7256 			 */
7257 			/* clear any state __mark_reg_known doesn't set */
7258 			mark_reg_unknown(env, regs, insn->dst_reg);
7259 			regs[insn->dst_reg].type = SCALAR_VALUE;
7260 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
7261 				__mark_reg_known(regs + insn->dst_reg,
7262 						 insn->imm);
7263 			} else {
7264 				__mark_reg_known(regs + insn->dst_reg,
7265 						 (u32)insn->imm);
7266 			}
7267 		}
7268 
7269 	} else if (opcode > BPF_END) {
7270 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7271 		return -EINVAL;
7272 
7273 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
7274 
7275 		if (BPF_SRC(insn->code) == BPF_X) {
7276 			if (insn->imm != 0 || insn->off != 0) {
7277 				verbose(env, "BPF_ALU uses reserved fields\n");
7278 				return -EINVAL;
7279 			}
7280 			/* check src1 operand */
7281 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
7282 			if (err)
7283 				return err;
7284 		} else {
7285 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7286 				verbose(env, "BPF_ALU uses reserved fields\n");
7287 				return -EINVAL;
7288 			}
7289 		}
7290 
7291 		/* check src2 operand */
7292 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7293 		if (err)
7294 			return err;
7295 
7296 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7297 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7298 			verbose(env, "div by zero\n");
7299 			return -EINVAL;
7300 		}
7301 
7302 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7303 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7304 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7305 
7306 			if (insn->imm < 0 || insn->imm >= size) {
7307 				verbose(env, "invalid shift %d\n", insn->imm);
7308 				return -EINVAL;
7309 			}
7310 		}
7311 
7312 		/* check dest operand */
7313 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7314 		if (err)
7315 			return err;
7316 
7317 		return adjust_reg_min_max_vals(env, insn);
7318 	}
7319 
7320 	return 0;
7321 }
7322 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)7323 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7324 				   struct bpf_reg_state *dst_reg,
7325 				   enum bpf_reg_type type,
7326 				   bool range_right_open)
7327 {
7328 	struct bpf_func_state *state;
7329 	struct bpf_reg_state *reg;
7330 	int new_range;
7331 
7332 	if (dst_reg->off < 0 ||
7333 	    (dst_reg->off == 0 && range_right_open))
7334 		/* This doesn't give us any range */
7335 		return;
7336 
7337 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
7338 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7339 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
7340 		 * than pkt_end, but that's because it's also less than pkt.
7341 		 */
7342 		return;
7343 
7344 	new_range = dst_reg->off;
7345 	if (range_right_open)
7346 		new_range++;
7347 
7348 	/* Examples for register markings:
7349 	 *
7350 	 * pkt_data in dst register:
7351 	 *
7352 	 *   r2 = r3;
7353 	 *   r2 += 8;
7354 	 *   if (r2 > pkt_end) goto <handle exception>
7355 	 *   <access okay>
7356 	 *
7357 	 *   r2 = r3;
7358 	 *   r2 += 8;
7359 	 *   if (r2 < pkt_end) goto <access okay>
7360 	 *   <handle exception>
7361 	 *
7362 	 *   Where:
7363 	 *     r2 == dst_reg, pkt_end == src_reg
7364 	 *     r2=pkt(id=n,off=8,r=0)
7365 	 *     r3=pkt(id=n,off=0,r=0)
7366 	 *
7367 	 * pkt_data in src register:
7368 	 *
7369 	 *   r2 = r3;
7370 	 *   r2 += 8;
7371 	 *   if (pkt_end >= r2) goto <access okay>
7372 	 *   <handle exception>
7373 	 *
7374 	 *   r2 = r3;
7375 	 *   r2 += 8;
7376 	 *   if (pkt_end <= r2) goto <handle exception>
7377 	 *   <access okay>
7378 	 *
7379 	 *   Where:
7380 	 *     pkt_end == dst_reg, r2 == src_reg
7381 	 *     r2=pkt(id=n,off=8,r=0)
7382 	 *     r3=pkt(id=n,off=0,r=0)
7383 	 *
7384 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7385 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7386 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
7387 	 * the check.
7388 	 */
7389 
7390 	/* If our ids match, then we must have the same max_value.  And we
7391 	 * don't care about the other reg's fixed offset, since if it's too big
7392 	 * the range won't allow anything.
7393 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7394 	 */
7395 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7396 		if (reg->type == type && reg->id == dst_reg->id)
7397 			/* keep the maximum range already checked */
7398 			reg->range = max(reg->range, new_range);
7399 	}));
7400 }
7401 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)7402 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7403 {
7404 	struct tnum subreg = tnum_subreg(reg->var_off);
7405 	s32 sval = (s32)val;
7406 
7407 	switch (opcode) {
7408 	case BPF_JEQ:
7409 		if (tnum_is_const(subreg))
7410 			return !!tnum_equals_const(subreg, val);
7411 		break;
7412 	case BPF_JNE:
7413 		if (tnum_is_const(subreg))
7414 			return !tnum_equals_const(subreg, val);
7415 		break;
7416 	case BPF_JSET:
7417 		if ((~subreg.mask & subreg.value) & val)
7418 			return 1;
7419 		if (!((subreg.mask | subreg.value) & val))
7420 			return 0;
7421 		break;
7422 	case BPF_JGT:
7423 		if (reg->u32_min_value > val)
7424 			return 1;
7425 		else if (reg->u32_max_value <= val)
7426 			return 0;
7427 		break;
7428 	case BPF_JSGT:
7429 		if (reg->s32_min_value > sval)
7430 			return 1;
7431 		else if (reg->s32_max_value <= sval)
7432 			return 0;
7433 		break;
7434 	case BPF_JLT:
7435 		if (reg->u32_max_value < val)
7436 			return 1;
7437 		else if (reg->u32_min_value >= val)
7438 			return 0;
7439 		break;
7440 	case BPF_JSLT:
7441 		if (reg->s32_max_value < sval)
7442 			return 1;
7443 		else if (reg->s32_min_value >= sval)
7444 			return 0;
7445 		break;
7446 	case BPF_JGE:
7447 		if (reg->u32_min_value >= val)
7448 			return 1;
7449 		else if (reg->u32_max_value < val)
7450 			return 0;
7451 		break;
7452 	case BPF_JSGE:
7453 		if (reg->s32_min_value >= sval)
7454 			return 1;
7455 		else if (reg->s32_max_value < sval)
7456 			return 0;
7457 		break;
7458 	case BPF_JLE:
7459 		if (reg->u32_max_value <= val)
7460 			return 1;
7461 		else if (reg->u32_min_value > val)
7462 			return 0;
7463 		break;
7464 	case BPF_JSLE:
7465 		if (reg->s32_max_value <= sval)
7466 			return 1;
7467 		else if (reg->s32_min_value > sval)
7468 			return 0;
7469 		break;
7470 	}
7471 
7472 	return -1;
7473 }
7474 
7475 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)7476 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7477 {
7478 	s64 sval = (s64)val;
7479 
7480 	switch (opcode) {
7481 	case BPF_JEQ:
7482 		if (tnum_is_const(reg->var_off))
7483 			return !!tnum_equals_const(reg->var_off, val);
7484 		break;
7485 	case BPF_JNE:
7486 		if (tnum_is_const(reg->var_off))
7487 			return !tnum_equals_const(reg->var_off, val);
7488 		break;
7489 	case BPF_JSET:
7490 		if ((~reg->var_off.mask & reg->var_off.value) & val)
7491 			return 1;
7492 		if (!((reg->var_off.mask | reg->var_off.value) & val))
7493 			return 0;
7494 		break;
7495 	case BPF_JGT:
7496 		if (reg->umin_value > val)
7497 			return 1;
7498 		else if (reg->umax_value <= val)
7499 			return 0;
7500 		break;
7501 	case BPF_JSGT:
7502 		if (reg->smin_value > sval)
7503 			return 1;
7504 		else if (reg->smax_value <= sval)
7505 			return 0;
7506 		break;
7507 	case BPF_JLT:
7508 		if (reg->umax_value < val)
7509 			return 1;
7510 		else if (reg->umin_value >= val)
7511 			return 0;
7512 		break;
7513 	case BPF_JSLT:
7514 		if (reg->smax_value < sval)
7515 			return 1;
7516 		else if (reg->smin_value >= sval)
7517 			return 0;
7518 		break;
7519 	case BPF_JGE:
7520 		if (reg->umin_value >= val)
7521 			return 1;
7522 		else if (reg->umax_value < val)
7523 			return 0;
7524 		break;
7525 	case BPF_JSGE:
7526 		if (reg->smin_value >= sval)
7527 			return 1;
7528 		else if (reg->smax_value < sval)
7529 			return 0;
7530 		break;
7531 	case BPF_JLE:
7532 		if (reg->umax_value <= val)
7533 			return 1;
7534 		else if (reg->umin_value > val)
7535 			return 0;
7536 		break;
7537 	case BPF_JSLE:
7538 		if (reg->smax_value <= sval)
7539 			return 1;
7540 		else if (reg->smin_value > sval)
7541 			return 0;
7542 		break;
7543 	}
7544 
7545 	return -1;
7546 }
7547 
7548 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7549  * and return:
7550  *  1 - branch will be taken and "goto target" will be executed
7551  *  0 - branch will not be taken and fall-through to next insn
7552  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7553  *      range [0,10]
7554  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)7555 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7556 			   bool is_jmp32)
7557 {
7558 	if (__is_pointer_value(false, reg)) {
7559 		if (!reg_type_not_null(reg->type))
7560 			return -1;
7561 
7562 		/* If pointer is valid tests against zero will fail so we can
7563 		 * use this to direct branch taken.
7564 		 */
7565 		if (val != 0)
7566 			return -1;
7567 
7568 		switch (opcode) {
7569 		case BPF_JEQ:
7570 			return 0;
7571 		case BPF_JNE:
7572 			return 1;
7573 		default:
7574 			return -1;
7575 		}
7576 	}
7577 
7578 	if (is_jmp32)
7579 		return is_branch32_taken(reg, val, opcode);
7580 	return is_branch64_taken(reg, val, opcode);
7581 }
7582 
flip_opcode(u32 opcode)7583 static int flip_opcode(u32 opcode)
7584 {
7585 	/* How can we transform "a <op> b" into "b <op> a"? */
7586 	static const u8 opcode_flip[16] = {
7587 		/* these stay the same */
7588 		[BPF_JEQ  >> 4] = BPF_JEQ,
7589 		[BPF_JNE  >> 4] = BPF_JNE,
7590 		[BPF_JSET >> 4] = BPF_JSET,
7591 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
7592 		[BPF_JGE  >> 4] = BPF_JLE,
7593 		[BPF_JGT  >> 4] = BPF_JLT,
7594 		[BPF_JLE  >> 4] = BPF_JGE,
7595 		[BPF_JLT  >> 4] = BPF_JGT,
7596 		[BPF_JSGE >> 4] = BPF_JSLE,
7597 		[BPF_JSGT >> 4] = BPF_JSLT,
7598 		[BPF_JSLE >> 4] = BPF_JSGE,
7599 		[BPF_JSLT >> 4] = BPF_JSGT
7600 	};
7601 	return opcode_flip[opcode >> 4];
7602 }
7603 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)7604 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7605 				   struct bpf_reg_state *src_reg,
7606 				   u8 opcode)
7607 {
7608 	struct bpf_reg_state *pkt;
7609 
7610 	if (src_reg->type == PTR_TO_PACKET_END) {
7611 		pkt = dst_reg;
7612 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
7613 		pkt = src_reg;
7614 		opcode = flip_opcode(opcode);
7615 	} else {
7616 		return -1;
7617 	}
7618 
7619 	if (pkt->range >= 0)
7620 		return -1;
7621 
7622 	switch (opcode) {
7623 	case BPF_JLE:
7624 		/* pkt <= pkt_end */
7625 		fallthrough;
7626 	case BPF_JGT:
7627 		/* pkt > pkt_end */
7628 		if (pkt->range == BEYOND_PKT_END)
7629 			/* pkt has at last one extra byte beyond pkt_end */
7630 			return opcode == BPF_JGT;
7631 		break;
7632 	case BPF_JLT:
7633 		/* pkt < pkt_end */
7634 		fallthrough;
7635 	case BPF_JGE:
7636 		/* pkt >= pkt_end */
7637 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7638 			return opcode == BPF_JGE;
7639 		break;
7640 	}
7641 	return -1;
7642 }
7643 
7644 /* Adjusts the register min/max values in the case that the dst_reg is the
7645  * variable register that we are working on, and src_reg is a constant or we're
7646  * simply doing a BPF_K check.
7647  * In JEQ/JNE cases we also adjust the var_off values.
7648  */
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)7649 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7650 			    struct bpf_reg_state *false_reg,
7651 			    u64 val, u32 val32,
7652 			    u8 opcode, bool is_jmp32)
7653 {
7654 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
7655 	struct tnum false_64off = false_reg->var_off;
7656 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
7657 	struct tnum true_64off = true_reg->var_off;
7658 	s64 sval = (s64)val;
7659 	s32 sval32 = (s32)val32;
7660 
7661 	/* If the dst_reg is a pointer, we can't learn anything about its
7662 	 * variable offset from the compare (unless src_reg were a pointer into
7663 	 * the same object, but we don't bother with that.
7664 	 * Since false_reg and true_reg have the same type by construction, we
7665 	 * only need to check one of them for pointerness.
7666 	 */
7667 	if (__is_pointer_value(false, false_reg))
7668 		return;
7669 
7670 	switch (opcode) {
7671 	/* JEQ/JNE comparison doesn't change the register equivalence.
7672 	 *
7673 	 * r1 = r2;
7674 	 * if (r1 == 42) goto label;
7675 	 * ...
7676 	 * label: // here both r1 and r2 are known to be 42.
7677 	 *
7678 	 * Hence when marking register as known preserve it's ID.
7679 	 */
7680 	case BPF_JEQ:
7681 		if (is_jmp32) {
7682 			__mark_reg32_known(true_reg, val32);
7683 			true_32off = tnum_subreg(true_reg->var_off);
7684 		} else {
7685 			___mark_reg_known(true_reg, val);
7686 			true_64off = true_reg->var_off;
7687 		}
7688 		break;
7689 	case BPF_JNE:
7690 		if (is_jmp32) {
7691 			__mark_reg32_known(false_reg, val32);
7692 			false_32off = tnum_subreg(false_reg->var_off);
7693 		} else {
7694 			___mark_reg_known(false_reg, val);
7695 			false_64off = false_reg->var_off;
7696 		}
7697 		break;
7698 	case BPF_JSET:
7699 		if (is_jmp32) {
7700 			false_32off = tnum_and(false_32off, tnum_const(~val32));
7701 			if (is_power_of_2(val32))
7702 				true_32off = tnum_or(true_32off,
7703 						     tnum_const(val32));
7704 		} else {
7705 			false_64off = tnum_and(false_64off, tnum_const(~val));
7706 			if (is_power_of_2(val))
7707 				true_64off = tnum_or(true_64off,
7708 						     tnum_const(val));
7709 		}
7710 		break;
7711 	case BPF_JGE:
7712 	case BPF_JGT:
7713 	{
7714 		if (is_jmp32) {
7715 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
7716 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7717 
7718 			false_reg->u32_max_value = min(false_reg->u32_max_value,
7719 						       false_umax);
7720 			true_reg->u32_min_value = max(true_reg->u32_min_value,
7721 						      true_umin);
7722 		} else {
7723 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
7724 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7725 
7726 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
7727 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
7728 		}
7729 		break;
7730 	}
7731 	case BPF_JSGE:
7732 	case BPF_JSGT:
7733 	{
7734 		if (is_jmp32) {
7735 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
7736 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7737 
7738 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7739 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7740 		} else {
7741 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
7742 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7743 
7744 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
7745 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
7746 		}
7747 		break;
7748 	}
7749 	case BPF_JLE:
7750 	case BPF_JLT:
7751 	{
7752 		if (is_jmp32) {
7753 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
7754 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7755 
7756 			false_reg->u32_min_value = max(false_reg->u32_min_value,
7757 						       false_umin);
7758 			true_reg->u32_max_value = min(true_reg->u32_max_value,
7759 						      true_umax);
7760 		} else {
7761 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
7762 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7763 
7764 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
7765 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
7766 		}
7767 		break;
7768 	}
7769 	case BPF_JSLE:
7770 	case BPF_JSLT:
7771 	{
7772 		if (is_jmp32) {
7773 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
7774 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7775 
7776 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7777 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7778 		} else {
7779 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
7780 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7781 
7782 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
7783 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
7784 		}
7785 		break;
7786 	}
7787 	default:
7788 		return;
7789 	}
7790 
7791 	if (is_jmp32) {
7792 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7793 					     tnum_subreg(false_32off));
7794 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7795 					    tnum_subreg(true_32off));
7796 		__reg_combine_32_into_64(false_reg);
7797 		__reg_combine_32_into_64(true_reg);
7798 	} else {
7799 		false_reg->var_off = false_64off;
7800 		true_reg->var_off = true_64off;
7801 		__reg_combine_64_into_32(false_reg);
7802 		__reg_combine_64_into_32(true_reg);
7803 	}
7804 }
7805 
7806 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7807  * the variable reg.
7808  */
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)7809 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7810 				struct bpf_reg_state *false_reg,
7811 				u64 val, u32 val32,
7812 				u8 opcode, bool is_jmp32)
7813 {
7814 	opcode = flip_opcode(opcode);
7815 	/* This uses zero as "not present in table"; luckily the zero opcode,
7816 	 * BPF_JA, can't get here.
7817 	 */
7818 	if (opcode)
7819 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7820 }
7821 
7822 /* 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)7823 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7824 				  struct bpf_reg_state *dst_reg)
7825 {
7826 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7827 							dst_reg->umin_value);
7828 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7829 							dst_reg->umax_value);
7830 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7831 							dst_reg->smin_value);
7832 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7833 							dst_reg->smax_value);
7834 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7835 							     dst_reg->var_off);
7836 	reg_bounds_sync(src_reg);
7837 	reg_bounds_sync(dst_reg);
7838 }
7839 
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)7840 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7841 				struct bpf_reg_state *true_dst,
7842 				struct bpf_reg_state *false_src,
7843 				struct bpf_reg_state *false_dst,
7844 				u8 opcode)
7845 {
7846 	switch (opcode) {
7847 	case BPF_JEQ:
7848 		__reg_combine_min_max(true_src, true_dst);
7849 		break;
7850 	case BPF_JNE:
7851 		__reg_combine_min_max(false_src, false_dst);
7852 		break;
7853 	}
7854 }
7855 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)7856 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7857 				 struct bpf_reg_state *reg, u32 id,
7858 				 bool is_null)
7859 {
7860 	if (type_may_be_null(reg->type) && reg->id == id &&
7861 	    !WARN_ON_ONCE(!reg->id)) {
7862 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7863 				 !tnum_equals_const(reg->var_off, 0) ||
7864 				 reg->off)) {
7865 			/* Old offset (both fixed and variable parts) should
7866 			 * have been known-zero, because we don't allow pointer
7867 			 * arithmetic on pointers that might be NULL. If we
7868 			 * see this happening, don't convert the register.
7869 			 */
7870 			return;
7871 		}
7872 		if (is_null) {
7873 			reg->type = SCALAR_VALUE;
7874 		} else if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
7875 			const struct bpf_map *map = reg->map_ptr;
7876 
7877 			if (map->inner_map_meta) {
7878 				reg->type = CONST_PTR_TO_MAP;
7879 				reg->map_ptr = map->inner_map_meta;
7880 			} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7881 				reg->type = PTR_TO_XDP_SOCK;
7882 			} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7883 				   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7884 				reg->type = PTR_TO_SOCKET;
7885 			} else {
7886 				reg->type = PTR_TO_MAP_VALUE;
7887 			}
7888 		} else {
7889 			reg->type &= ~PTR_MAYBE_NULL;
7890 		}
7891 
7892 		if (is_null) {
7893 			/* We don't need id and ref_obj_id from this point
7894 			 * onwards anymore, thus we should better reset it,
7895 			 * so that state pruning has chances to take effect.
7896 			 */
7897 			reg->id = 0;
7898 			reg->ref_obj_id = 0;
7899 		} else if (!reg_may_point_to_spin_lock(reg)) {
7900 			/* For not-NULL ptr, reg->ref_obj_id will be reset
7901 			 * in release_reference().
7902 			 *
7903 			 * reg->id is still used by spin_lock ptr. Other
7904 			 * than spin_lock ptr type, reg->id can be reset.
7905 			 */
7906 			reg->id = 0;
7907 		}
7908 	}
7909 }
7910 
7911 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7912  * be folded together at some point.
7913  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)7914 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7915 				  bool is_null)
7916 {
7917 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7918 	struct bpf_reg_state *regs = state->regs, *reg;
7919 	u32 ref_obj_id = regs[regno].ref_obj_id;
7920 	u32 id = regs[regno].id;
7921 
7922 	if (ref_obj_id && ref_obj_id == id && is_null)
7923 		/* regs[regno] is in the " == NULL" branch.
7924 		 * No one could have freed the reference state before
7925 		 * doing the NULL check.
7926 		 */
7927 		WARN_ON_ONCE(release_reference_state(state, id));
7928 
7929 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7930 		mark_ptr_or_null_reg(state, reg, id, is_null);
7931 	}));
7932 }
7933 
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)7934 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7935 				   struct bpf_reg_state *dst_reg,
7936 				   struct bpf_reg_state *src_reg,
7937 				   struct bpf_verifier_state *this_branch,
7938 				   struct bpf_verifier_state *other_branch)
7939 {
7940 	if (BPF_SRC(insn->code) != BPF_X)
7941 		return false;
7942 
7943 	/* Pointers are always 64-bit. */
7944 	if (BPF_CLASS(insn->code) == BPF_JMP32)
7945 		return false;
7946 
7947 	switch (BPF_OP(insn->code)) {
7948 	case BPF_JGT:
7949 		if ((dst_reg->type == PTR_TO_PACKET &&
7950 		     src_reg->type == PTR_TO_PACKET_END) ||
7951 		    (dst_reg->type == PTR_TO_PACKET_META &&
7952 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7953 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7954 			find_good_pkt_pointers(this_branch, dst_reg,
7955 					       dst_reg->type, false);
7956 			mark_pkt_end(other_branch, insn->dst_reg, true);
7957 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7958 			    src_reg->type == PTR_TO_PACKET) ||
7959 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7960 			    src_reg->type == PTR_TO_PACKET_META)) {
7961 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
7962 			find_good_pkt_pointers(other_branch, src_reg,
7963 					       src_reg->type, true);
7964 			mark_pkt_end(this_branch, insn->src_reg, false);
7965 		} else {
7966 			return false;
7967 		}
7968 		break;
7969 	case BPF_JLT:
7970 		if ((dst_reg->type == PTR_TO_PACKET &&
7971 		     src_reg->type == PTR_TO_PACKET_END) ||
7972 		    (dst_reg->type == PTR_TO_PACKET_META &&
7973 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7974 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7975 			find_good_pkt_pointers(other_branch, dst_reg,
7976 					       dst_reg->type, true);
7977 			mark_pkt_end(this_branch, insn->dst_reg, false);
7978 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
7979 			    src_reg->type == PTR_TO_PACKET) ||
7980 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7981 			    src_reg->type == PTR_TO_PACKET_META)) {
7982 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
7983 			find_good_pkt_pointers(this_branch, src_reg,
7984 					       src_reg->type, false);
7985 			mark_pkt_end(other_branch, insn->src_reg, true);
7986 		} else {
7987 			return false;
7988 		}
7989 		break;
7990 	case BPF_JGE:
7991 		if ((dst_reg->type == PTR_TO_PACKET &&
7992 		     src_reg->type == PTR_TO_PACKET_END) ||
7993 		    (dst_reg->type == PTR_TO_PACKET_META &&
7994 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7995 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7996 			find_good_pkt_pointers(this_branch, dst_reg,
7997 					       dst_reg->type, true);
7998 			mark_pkt_end(other_branch, insn->dst_reg, false);
7999 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8000 			    src_reg->type == PTR_TO_PACKET) ||
8001 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8002 			    src_reg->type == PTR_TO_PACKET_META)) {
8003 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8004 			find_good_pkt_pointers(other_branch, src_reg,
8005 					       src_reg->type, false);
8006 			mark_pkt_end(this_branch, insn->src_reg, true);
8007 		} else {
8008 			return false;
8009 		}
8010 		break;
8011 	case BPF_JLE:
8012 		if ((dst_reg->type == PTR_TO_PACKET &&
8013 		     src_reg->type == PTR_TO_PACKET_END) ||
8014 		    (dst_reg->type == PTR_TO_PACKET_META &&
8015 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8016 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8017 			find_good_pkt_pointers(other_branch, dst_reg,
8018 					       dst_reg->type, false);
8019 			mark_pkt_end(this_branch, insn->dst_reg, true);
8020 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
8021 			    src_reg->type == PTR_TO_PACKET) ||
8022 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8023 			    src_reg->type == PTR_TO_PACKET_META)) {
8024 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8025 			find_good_pkt_pointers(this_branch, src_reg,
8026 					       src_reg->type, true);
8027 			mark_pkt_end(other_branch, insn->src_reg, false);
8028 		} else {
8029 			return false;
8030 		}
8031 		break;
8032 	default:
8033 		return false;
8034 	}
8035 
8036 	return true;
8037 }
8038 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)8039 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8040 			       struct bpf_reg_state *known_reg)
8041 {
8042 	struct bpf_func_state *state;
8043 	struct bpf_reg_state *reg;
8044 
8045 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8046 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8047 			copy_register_state(reg, known_reg);
8048 	}));
8049 }
8050 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)8051 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8052 			     struct bpf_insn *insn, int *insn_idx)
8053 {
8054 	struct bpf_verifier_state *this_branch = env->cur_state;
8055 	struct bpf_verifier_state *other_branch;
8056 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8057 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8058 	u8 opcode = BPF_OP(insn->code);
8059 	bool is_jmp32;
8060 	int pred = -1;
8061 	int err;
8062 
8063 	/* Only conditional jumps are expected to reach here. */
8064 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
8065 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8066 		return -EINVAL;
8067 	}
8068 
8069 	if (BPF_SRC(insn->code) == BPF_X) {
8070 		if (insn->imm != 0) {
8071 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8072 			return -EINVAL;
8073 		}
8074 
8075 		/* check src1 operand */
8076 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8077 		if (err)
8078 			return err;
8079 
8080 		if (is_pointer_value(env, insn->src_reg)) {
8081 			verbose(env, "R%d pointer comparison prohibited\n",
8082 				insn->src_reg);
8083 			return -EACCES;
8084 		}
8085 		src_reg = &regs[insn->src_reg];
8086 	} else {
8087 		if (insn->src_reg != BPF_REG_0) {
8088 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8089 			return -EINVAL;
8090 		}
8091 	}
8092 
8093 	/* check src2 operand */
8094 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8095 	if (err)
8096 		return err;
8097 
8098 	dst_reg = &regs[insn->dst_reg];
8099 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8100 
8101 	if (BPF_SRC(insn->code) == BPF_K) {
8102 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8103 	} else if (src_reg->type == SCALAR_VALUE &&
8104 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8105 		pred = is_branch_taken(dst_reg,
8106 				       tnum_subreg(src_reg->var_off).value,
8107 				       opcode,
8108 				       is_jmp32);
8109 	} else if (src_reg->type == SCALAR_VALUE &&
8110 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8111 		pred = is_branch_taken(dst_reg,
8112 				       src_reg->var_off.value,
8113 				       opcode,
8114 				       is_jmp32);
8115 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
8116 		   reg_is_pkt_pointer_any(src_reg) &&
8117 		   !is_jmp32) {
8118 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8119 	}
8120 
8121 	if (pred >= 0) {
8122 		/* If we get here with a dst_reg pointer type it is because
8123 		 * above is_branch_taken() special cased the 0 comparison.
8124 		 */
8125 		if (!__is_pointer_value(false, dst_reg))
8126 			err = mark_chain_precision(env, insn->dst_reg);
8127 		if (BPF_SRC(insn->code) == BPF_X && !err &&
8128 		    !__is_pointer_value(false, src_reg))
8129 			err = mark_chain_precision(env, insn->src_reg);
8130 		if (err)
8131 			return err;
8132 	}
8133 
8134 	if (pred == 1) {
8135 		/* Only follow the goto, ignore fall-through. If needed, push
8136 		 * the fall-through branch for simulation under speculative
8137 		 * execution.
8138 		 */
8139 		if (!env->bypass_spec_v1 &&
8140 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
8141 					       *insn_idx))
8142 			return -EFAULT;
8143 		*insn_idx += insn->off;
8144 		return 0;
8145 	} else if (pred == 0) {
8146 		/* Only follow the fall-through branch, since that's where the
8147 		 * program will go. If needed, push the goto branch for
8148 		 * simulation under speculative execution.
8149 		 */
8150 		if (!env->bypass_spec_v1 &&
8151 		    !sanitize_speculative_path(env, insn,
8152 					       *insn_idx + insn->off + 1,
8153 					       *insn_idx))
8154 			return -EFAULT;
8155 		return 0;
8156 	}
8157 
8158 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8159 				  false);
8160 	if (!other_branch)
8161 		return -EFAULT;
8162 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8163 
8164 	/* detect if we are comparing against a constant value so we can adjust
8165 	 * our min/max values for our dst register.
8166 	 * this is only legit if both are scalars (or pointers to the same
8167 	 * object, I suppose, but we don't support that right now), because
8168 	 * otherwise the different base pointers mean the offsets aren't
8169 	 * comparable.
8170 	 */
8171 	if (BPF_SRC(insn->code) == BPF_X) {
8172 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8173 
8174 		if (dst_reg->type == SCALAR_VALUE &&
8175 		    src_reg->type == SCALAR_VALUE) {
8176 			if (tnum_is_const(src_reg->var_off) ||
8177 			    (is_jmp32 &&
8178 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
8179 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
8180 						dst_reg,
8181 						src_reg->var_off.value,
8182 						tnum_subreg(src_reg->var_off).value,
8183 						opcode, is_jmp32);
8184 			else if (tnum_is_const(dst_reg->var_off) ||
8185 				 (is_jmp32 &&
8186 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
8187 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8188 						    src_reg,
8189 						    dst_reg->var_off.value,
8190 						    tnum_subreg(dst_reg->var_off).value,
8191 						    opcode, is_jmp32);
8192 			else if (!is_jmp32 &&
8193 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
8194 				/* Comparing for equality, we can combine knowledge */
8195 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
8196 						    &other_branch_regs[insn->dst_reg],
8197 						    src_reg, dst_reg, opcode);
8198 			if (src_reg->id &&
8199 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8200 				find_equal_scalars(this_branch, src_reg);
8201 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8202 			}
8203 
8204 		}
8205 	} else if (dst_reg->type == SCALAR_VALUE) {
8206 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
8207 					dst_reg, insn->imm, (u32)insn->imm,
8208 					opcode, is_jmp32);
8209 	}
8210 
8211 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8212 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8213 		find_equal_scalars(this_branch, dst_reg);
8214 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8215 	}
8216 
8217 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8218 	 * NOTE: these optimizations below are related with pointer comparison
8219 	 *       which will never be JMP32.
8220 	 */
8221 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8222 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8223 	    type_may_be_null(dst_reg->type)) {
8224 		/* Mark all identical registers in each branch as either
8225 		 * safe or unknown depending R == 0 or R != 0 conditional.
8226 		 */
8227 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8228 				      opcode == BPF_JNE);
8229 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8230 				      opcode == BPF_JEQ);
8231 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8232 					   this_branch, other_branch) &&
8233 		   is_pointer_value(env, insn->dst_reg)) {
8234 		verbose(env, "R%d pointer comparison prohibited\n",
8235 			insn->dst_reg);
8236 		return -EACCES;
8237 	}
8238 	if (env->log.level & BPF_LOG_LEVEL)
8239 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8240 	return 0;
8241 }
8242 
8243 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)8244 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8245 {
8246 	struct bpf_insn_aux_data *aux = cur_aux(env);
8247 	struct bpf_reg_state *regs = cur_regs(env);
8248 	struct bpf_reg_state *dst_reg;
8249 	struct bpf_map *map;
8250 	int err;
8251 
8252 	if (BPF_SIZE(insn->code) != BPF_DW) {
8253 		verbose(env, "invalid BPF_LD_IMM insn\n");
8254 		return -EINVAL;
8255 	}
8256 	if (insn->off != 0) {
8257 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8258 		return -EINVAL;
8259 	}
8260 
8261 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
8262 	if (err)
8263 		return err;
8264 
8265 	dst_reg = &regs[insn->dst_reg];
8266 	if (insn->src_reg == 0) {
8267 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8268 
8269 		dst_reg->type = SCALAR_VALUE;
8270 		__mark_reg_known(&regs[insn->dst_reg], imm);
8271 		return 0;
8272 	}
8273 
8274 	/* All special src_reg cases are listed below. From this point onwards
8275 	 * we either succeed and assign a corresponding dst_reg->type after
8276 	 * zeroing the offset, or fail and reject the program.
8277 	 */
8278 	mark_reg_known_zero(env, regs, insn->dst_reg);
8279 
8280 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8281 		dst_reg->type = aux->btf_var.reg_type;
8282 		switch (base_type(dst_reg->type)) {
8283 		case PTR_TO_MEM:
8284 			dst_reg->mem_size = aux->btf_var.mem_size;
8285 			break;
8286 		case PTR_TO_BTF_ID:
8287 		case PTR_TO_PERCPU_BTF_ID:
8288 			dst_reg->btf_id = aux->btf_var.btf_id;
8289 			break;
8290 		default:
8291 			verbose(env, "bpf verifier is misconfigured\n");
8292 			return -EFAULT;
8293 		}
8294 		return 0;
8295 	}
8296 
8297 	map = env->used_maps[aux->map_index];
8298 	dst_reg->map_ptr = map;
8299 
8300 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8301 		dst_reg->type = PTR_TO_MAP_VALUE;
8302 		dst_reg->off = aux->map_off;
8303 		if (map_value_has_spin_lock(map))
8304 			dst_reg->id = ++env->id_gen;
8305 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8306 		dst_reg->type = CONST_PTR_TO_MAP;
8307 	} else {
8308 		verbose(env, "bpf verifier is misconfigured\n");
8309 		return -EINVAL;
8310 	}
8311 
8312 	return 0;
8313 }
8314 
may_access_skb(enum bpf_prog_type type)8315 static bool may_access_skb(enum bpf_prog_type type)
8316 {
8317 	switch (type) {
8318 	case BPF_PROG_TYPE_SOCKET_FILTER:
8319 	case BPF_PROG_TYPE_SCHED_CLS:
8320 	case BPF_PROG_TYPE_SCHED_ACT:
8321 		return true;
8322 	default:
8323 		return false;
8324 	}
8325 }
8326 
8327 /* verify safety of LD_ABS|LD_IND instructions:
8328  * - they can only appear in the programs where ctx == skb
8329  * - since they are wrappers of function calls, they scratch R1-R5 registers,
8330  *   preserve R6-R9, and store return value into R0
8331  *
8332  * Implicit input:
8333  *   ctx == skb == R6 == CTX
8334  *
8335  * Explicit input:
8336  *   SRC == any register
8337  *   IMM == 32-bit immediate
8338  *
8339  * Output:
8340  *   R0 - 8/16/32-bit skb data converted to cpu endianness
8341  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)8342 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8343 {
8344 	struct bpf_reg_state *regs = cur_regs(env);
8345 	static const int ctx_reg = BPF_REG_6;
8346 	u8 mode = BPF_MODE(insn->code);
8347 	int i, err;
8348 
8349 	if (!may_access_skb(resolve_prog_type(env->prog))) {
8350 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8351 		return -EINVAL;
8352 	}
8353 
8354 	if (!env->ops->gen_ld_abs) {
8355 		verbose(env, "bpf verifier is misconfigured\n");
8356 		return -EINVAL;
8357 	}
8358 
8359 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8360 	    BPF_SIZE(insn->code) == BPF_DW ||
8361 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8362 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8363 		return -EINVAL;
8364 	}
8365 
8366 	/* check whether implicit source operand (register R6) is readable */
8367 	err = check_reg_arg(env, ctx_reg, SRC_OP);
8368 	if (err)
8369 		return err;
8370 
8371 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8372 	 * gen_ld_abs() may terminate the program at runtime, leading to
8373 	 * reference leak.
8374 	 */
8375 	err = check_reference_leak(env);
8376 	if (err) {
8377 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8378 		return err;
8379 	}
8380 
8381 	if (env->cur_state->active_spin_lock) {
8382 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8383 		return -EINVAL;
8384 	}
8385 
8386 	if (regs[ctx_reg].type != PTR_TO_CTX) {
8387 		verbose(env,
8388 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8389 		return -EINVAL;
8390 	}
8391 
8392 	if (mode == BPF_IND) {
8393 		/* check explicit source operand */
8394 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
8395 		if (err)
8396 			return err;
8397 	}
8398 
8399 	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
8400 	if (err < 0)
8401 		return err;
8402 
8403 	/* reset caller saved regs to unreadable */
8404 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
8405 		mark_reg_not_init(env, regs, caller_saved[i]);
8406 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8407 	}
8408 
8409 	/* mark destination R0 register as readable, since it contains
8410 	 * the value fetched from the packet.
8411 	 * Already marked as written above.
8412 	 */
8413 	mark_reg_unknown(env, regs, BPF_REG_0);
8414 	/* ld_abs load up to 32-bit skb data. */
8415 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8416 	return 0;
8417 }
8418 
check_return_code(struct bpf_verifier_env * env)8419 static int check_return_code(struct bpf_verifier_env *env)
8420 {
8421 	struct tnum enforce_attach_type_range = tnum_unknown;
8422 	const struct bpf_prog *prog = env->prog;
8423 	struct bpf_reg_state *reg;
8424 	struct tnum range = tnum_range(0, 1);
8425 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8426 	int err;
8427 	const bool is_subprog = env->cur_state->frame[0]->subprogno;
8428 
8429 	/* LSM and struct_ops func-ptr's return type could be "void" */
8430 	if (!is_subprog &&
8431 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8432 	     prog_type == BPF_PROG_TYPE_LSM) &&
8433 	    !prog->aux->attach_func_proto->type)
8434 		return 0;
8435 
8436 	/* eBPF calling convetion is such that R0 is used
8437 	 * to return the value from eBPF program.
8438 	 * Make sure that it's readable at this time
8439 	 * of bpf_exit, which means that program wrote
8440 	 * something into it earlier
8441 	 */
8442 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8443 	if (err)
8444 		return err;
8445 
8446 	if (is_pointer_value(env, BPF_REG_0)) {
8447 		verbose(env, "R0 leaks addr as return value\n");
8448 		return -EACCES;
8449 	}
8450 
8451 	reg = cur_regs(env) + BPF_REG_0;
8452 	if (is_subprog) {
8453 		if (reg->type != SCALAR_VALUE) {
8454 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8455 				reg_type_str(env, reg->type));
8456 			return -EINVAL;
8457 		}
8458 		return 0;
8459 	}
8460 
8461 	switch (prog_type) {
8462 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8463 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8464 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8465 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8466 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8467 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8468 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8469 			range = tnum_range(1, 1);
8470 		break;
8471 	case BPF_PROG_TYPE_CGROUP_SKB:
8472 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8473 			range = tnum_range(0, 3);
8474 			enforce_attach_type_range = tnum_range(2, 3);
8475 		}
8476 		break;
8477 	case BPF_PROG_TYPE_CGROUP_SOCK:
8478 	case BPF_PROG_TYPE_SOCK_OPS:
8479 	case BPF_PROG_TYPE_CGROUP_DEVICE:
8480 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
8481 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8482 		break;
8483 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
8484 		if (!env->prog->aux->attach_btf_id)
8485 			return 0;
8486 		range = tnum_const(0);
8487 		break;
8488 	case BPF_PROG_TYPE_TRACING:
8489 		switch (env->prog->expected_attach_type) {
8490 		case BPF_TRACE_FENTRY:
8491 		case BPF_TRACE_FEXIT:
8492 			range = tnum_const(0);
8493 			break;
8494 		case BPF_TRACE_RAW_TP:
8495 		case BPF_MODIFY_RETURN:
8496 			return 0;
8497 		case BPF_TRACE_ITER:
8498 			break;
8499 		default:
8500 			return -ENOTSUPP;
8501 		}
8502 		break;
8503 	case BPF_PROG_TYPE_SK_LOOKUP:
8504 		range = tnum_range(SK_DROP, SK_PASS);
8505 		break;
8506 	case BPF_PROG_TYPE_EXT:
8507 		/* freplace program can return anything as its return value
8508 		 * depends on the to-be-replaced kernel func or bpf program.
8509 		 */
8510 	default:
8511 		return 0;
8512 	}
8513 
8514 	if (reg->type != SCALAR_VALUE) {
8515 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8516 			reg_type_str(env, reg->type));
8517 		return -EINVAL;
8518 	}
8519 
8520 	if (!tnum_in(range, reg->var_off)) {
8521 		char tn_buf[48];
8522 
8523 		verbose(env, "At program exit the register R0 ");
8524 		if (!tnum_is_unknown(reg->var_off)) {
8525 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8526 			verbose(env, "has value %s", tn_buf);
8527 		} else {
8528 			verbose(env, "has unknown scalar value");
8529 		}
8530 		tnum_strn(tn_buf, sizeof(tn_buf), range);
8531 		verbose(env, " should have been in %s\n", tn_buf);
8532 		return -EINVAL;
8533 	}
8534 
8535 	if (!tnum_is_unknown(enforce_attach_type_range) &&
8536 	    tnum_in(enforce_attach_type_range, reg->var_off))
8537 		env->prog->enforce_expected_attach_type = 1;
8538 	return 0;
8539 }
8540 
8541 /* non-recursive DFS pseudo code
8542  * 1  procedure DFS-iterative(G,v):
8543  * 2      label v as discovered
8544  * 3      let S be a stack
8545  * 4      S.push(v)
8546  * 5      while S is not empty
8547  * 6            t <- S.pop()
8548  * 7            if t is what we're looking for:
8549  * 8                return t
8550  * 9            for all edges e in G.adjacentEdges(t) do
8551  * 10               if edge e is already labelled
8552  * 11                   continue with the next edge
8553  * 12               w <- G.adjacentVertex(t,e)
8554  * 13               if vertex w is not discovered and not explored
8555  * 14                   label e as tree-edge
8556  * 15                   label w as discovered
8557  * 16                   S.push(w)
8558  * 17                   continue at 5
8559  * 18               else if vertex w is discovered
8560  * 19                   label e as back-edge
8561  * 20               else
8562  * 21                   // vertex w is explored
8563  * 22                   label e as forward- or cross-edge
8564  * 23           label t as explored
8565  * 24           S.pop()
8566  *
8567  * convention:
8568  * 0x10 - discovered
8569  * 0x11 - discovered and fall-through edge labelled
8570  * 0x12 - discovered and fall-through and branch edges labelled
8571  * 0x20 - explored
8572  */
8573 
8574 enum {
8575 	DISCOVERED = 0x10,
8576 	EXPLORED = 0x20,
8577 	FALLTHROUGH = 1,
8578 	BRANCH = 2,
8579 };
8580 
state_htab_size(struct bpf_verifier_env * env)8581 static u32 state_htab_size(struct bpf_verifier_env *env)
8582 {
8583 	return env->prog->len;
8584 }
8585 
explored_state(struct bpf_verifier_env * env,int idx)8586 static struct bpf_verifier_state_list **explored_state(
8587 					struct bpf_verifier_env *env,
8588 					int idx)
8589 {
8590 	struct bpf_verifier_state *cur = env->cur_state;
8591 	struct bpf_func_state *state = cur->frame[cur->curframe];
8592 
8593 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8594 }
8595 
init_explored_state(struct bpf_verifier_env * env,int idx)8596 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8597 {
8598 	env->insn_aux_data[idx].prune_point = true;
8599 }
8600 
8601 /* t, w, e - match pseudo-code above:
8602  * t - index of current instruction
8603  * w - next instruction
8604  * e - edge
8605  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)8606 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8607 		     bool loop_ok)
8608 {
8609 	int *insn_stack = env->cfg.insn_stack;
8610 	int *insn_state = env->cfg.insn_state;
8611 
8612 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8613 		return 0;
8614 
8615 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8616 		return 0;
8617 
8618 	if (w < 0 || w >= env->prog->len) {
8619 		verbose_linfo(env, t, "%d: ", t);
8620 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
8621 		return -EINVAL;
8622 	}
8623 
8624 	if (e == BRANCH)
8625 		/* mark branch target for state pruning */
8626 		init_explored_state(env, w);
8627 
8628 	if (insn_state[w] == 0) {
8629 		/* tree-edge */
8630 		insn_state[t] = DISCOVERED | e;
8631 		insn_state[w] = DISCOVERED;
8632 		if (env->cfg.cur_stack >= env->prog->len)
8633 			return -E2BIG;
8634 		insn_stack[env->cfg.cur_stack++] = w;
8635 		return 1;
8636 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8637 		if (loop_ok && env->bpf_capable)
8638 			return 0;
8639 		verbose_linfo(env, t, "%d: ", t);
8640 		verbose_linfo(env, w, "%d: ", w);
8641 		verbose(env, "back-edge from insn %d to %d\n", t, w);
8642 		return -EINVAL;
8643 	} else if (insn_state[w] == EXPLORED) {
8644 		/* forward- or cross-edge */
8645 		insn_state[t] = DISCOVERED | e;
8646 	} else {
8647 		verbose(env, "insn state internal bug\n");
8648 		return -EFAULT;
8649 	}
8650 	return 0;
8651 }
8652 
8653 /* non-recursive depth-first-search to detect loops in BPF program
8654  * loop == back-edge in directed graph
8655  */
check_cfg(struct bpf_verifier_env * env)8656 static int check_cfg(struct bpf_verifier_env *env)
8657 {
8658 	struct bpf_insn *insns = env->prog->insnsi;
8659 	int insn_cnt = env->prog->len;
8660 	int *insn_stack, *insn_state;
8661 	int ret = 0;
8662 	int i, t;
8663 
8664 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8665 	if (!insn_state)
8666 		return -ENOMEM;
8667 
8668 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8669 	if (!insn_stack) {
8670 		kvfree(insn_state);
8671 		return -ENOMEM;
8672 	}
8673 
8674 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8675 	insn_stack[0] = 0; /* 0 is the first instruction */
8676 	env->cfg.cur_stack = 1;
8677 
8678 peek_stack:
8679 	if (env->cfg.cur_stack == 0)
8680 		goto check_state;
8681 	t = insn_stack[env->cfg.cur_stack - 1];
8682 
8683 	if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8684 	    BPF_CLASS(insns[t].code) == BPF_JMP32) {
8685 		u8 opcode = BPF_OP(insns[t].code);
8686 
8687 		if (opcode == BPF_EXIT) {
8688 			goto mark_explored;
8689 		} else if (opcode == BPF_CALL) {
8690 			ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8691 			if (ret == 1)
8692 				goto peek_stack;
8693 			else if (ret < 0)
8694 				goto err_free;
8695 			if (t + 1 < insn_cnt)
8696 				init_explored_state(env, t + 1);
8697 			if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8698 				init_explored_state(env, t);
8699 				ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8700 						env, false);
8701 				if (ret == 1)
8702 					goto peek_stack;
8703 				else if (ret < 0)
8704 					goto err_free;
8705 			}
8706 		} else if (opcode == BPF_JA) {
8707 			if (BPF_SRC(insns[t].code) != BPF_K) {
8708 				ret = -EINVAL;
8709 				goto err_free;
8710 			}
8711 			/* unconditional jump with single edge */
8712 			ret = push_insn(t, t + insns[t].off + 1,
8713 					FALLTHROUGH, env, true);
8714 			if (ret == 1)
8715 				goto peek_stack;
8716 			else if (ret < 0)
8717 				goto err_free;
8718 			/* unconditional jmp is not a good pruning point,
8719 			 * but it's marked, since backtracking needs
8720 			 * to record jmp history in is_state_visited().
8721 			 */
8722 			init_explored_state(env, t + insns[t].off + 1);
8723 			/* tell verifier to check for equivalent states
8724 			 * after every call and jump
8725 			 */
8726 			if (t + 1 < insn_cnt)
8727 				init_explored_state(env, t + 1);
8728 		} else {
8729 			/* conditional jump with two edges */
8730 			init_explored_state(env, t);
8731 			ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8732 			if (ret == 1)
8733 				goto peek_stack;
8734 			else if (ret < 0)
8735 				goto err_free;
8736 
8737 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8738 			if (ret == 1)
8739 				goto peek_stack;
8740 			else if (ret < 0)
8741 				goto err_free;
8742 		}
8743 	} else {
8744 		/* all other non-branch instructions with single
8745 		 * fall-through edge
8746 		 */
8747 		ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8748 		if (ret == 1)
8749 			goto peek_stack;
8750 		else if (ret < 0)
8751 			goto err_free;
8752 	}
8753 
8754 mark_explored:
8755 	insn_state[t] = EXPLORED;
8756 	if (env->cfg.cur_stack-- <= 0) {
8757 		verbose(env, "pop stack internal bug\n");
8758 		ret = -EFAULT;
8759 		goto err_free;
8760 	}
8761 	goto peek_stack;
8762 
8763 check_state:
8764 	for (i = 0; i < insn_cnt; i++) {
8765 		if (insn_state[i] != EXPLORED) {
8766 			verbose(env, "unreachable insn %d\n", i);
8767 			ret = -EINVAL;
8768 			goto err_free;
8769 		}
8770 	}
8771 	ret = 0; /* cfg looks good */
8772 
8773 err_free:
8774 	kvfree(insn_state);
8775 	kvfree(insn_stack);
8776 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
8777 	return ret;
8778 }
8779 
check_abnormal_return(struct bpf_verifier_env * env)8780 static int check_abnormal_return(struct bpf_verifier_env *env)
8781 {
8782 	int i;
8783 
8784 	for (i = 1; i < env->subprog_cnt; i++) {
8785 		if (env->subprog_info[i].has_ld_abs) {
8786 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8787 			return -EINVAL;
8788 		}
8789 		if (env->subprog_info[i].has_tail_call) {
8790 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8791 			return -EINVAL;
8792 		}
8793 	}
8794 	return 0;
8795 }
8796 
8797 /* The minimum supported BTF func info size */
8798 #define MIN_BPF_FUNCINFO_SIZE	8
8799 #define MAX_FUNCINFO_REC_SIZE	252
8800 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8801 static int check_btf_func(struct bpf_verifier_env *env,
8802 			  const union bpf_attr *attr,
8803 			  union bpf_attr __user *uattr)
8804 {
8805 	const struct btf_type *type, *func_proto, *ret_type;
8806 	u32 i, nfuncs, urec_size, min_size;
8807 	u32 krec_size = sizeof(struct bpf_func_info);
8808 	struct bpf_func_info *krecord;
8809 	struct bpf_func_info_aux *info_aux = NULL;
8810 	struct bpf_prog *prog;
8811 	const struct btf *btf;
8812 	void __user *urecord;
8813 	u32 prev_offset = 0;
8814 	bool scalar_return;
8815 	int ret = -ENOMEM;
8816 
8817 	nfuncs = attr->func_info_cnt;
8818 	if (!nfuncs) {
8819 		if (check_abnormal_return(env))
8820 			return -EINVAL;
8821 		return 0;
8822 	}
8823 
8824 	if (nfuncs != env->subprog_cnt) {
8825 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8826 		return -EINVAL;
8827 	}
8828 
8829 	urec_size = attr->func_info_rec_size;
8830 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8831 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
8832 	    urec_size % sizeof(u32)) {
8833 		verbose(env, "invalid func info rec size %u\n", urec_size);
8834 		return -EINVAL;
8835 	}
8836 
8837 	prog = env->prog;
8838 	btf = prog->aux->btf;
8839 
8840 	urecord = u64_to_user_ptr(attr->func_info);
8841 	min_size = min_t(u32, krec_size, urec_size);
8842 
8843 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8844 	if (!krecord)
8845 		return -ENOMEM;
8846 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8847 	if (!info_aux)
8848 		goto err_free;
8849 
8850 	for (i = 0; i < nfuncs; i++) {
8851 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8852 		if (ret) {
8853 			if (ret == -E2BIG) {
8854 				verbose(env, "nonzero tailing record in func info");
8855 				/* set the size kernel expects so loader can zero
8856 				 * out the rest of the record.
8857 				 */
8858 				if (put_user(min_size, &uattr->func_info_rec_size))
8859 					ret = -EFAULT;
8860 			}
8861 			goto err_free;
8862 		}
8863 
8864 		if (copy_from_user(&krecord[i], urecord, min_size)) {
8865 			ret = -EFAULT;
8866 			goto err_free;
8867 		}
8868 
8869 		/* check insn_off */
8870 		ret = -EINVAL;
8871 		if (i == 0) {
8872 			if (krecord[i].insn_off) {
8873 				verbose(env,
8874 					"nonzero insn_off %u for the first func info record",
8875 					krecord[i].insn_off);
8876 				goto err_free;
8877 			}
8878 		} else if (krecord[i].insn_off <= prev_offset) {
8879 			verbose(env,
8880 				"same or smaller insn offset (%u) than previous func info record (%u)",
8881 				krecord[i].insn_off, prev_offset);
8882 			goto err_free;
8883 		}
8884 
8885 		if (env->subprog_info[i].start != krecord[i].insn_off) {
8886 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8887 			goto err_free;
8888 		}
8889 
8890 		/* check type_id */
8891 		type = btf_type_by_id(btf, krecord[i].type_id);
8892 		if (!type || !btf_type_is_func(type)) {
8893 			verbose(env, "invalid type id %d in func info",
8894 				krecord[i].type_id);
8895 			goto err_free;
8896 		}
8897 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8898 
8899 		func_proto = btf_type_by_id(btf, type->type);
8900 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8901 			/* btf_func_check() already verified it during BTF load */
8902 			goto err_free;
8903 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8904 		scalar_return =
8905 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8906 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8907 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8908 			goto err_free;
8909 		}
8910 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8911 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8912 			goto err_free;
8913 		}
8914 
8915 		prev_offset = krecord[i].insn_off;
8916 		urecord += urec_size;
8917 	}
8918 
8919 	prog->aux->func_info = krecord;
8920 	prog->aux->func_info_cnt = nfuncs;
8921 	prog->aux->func_info_aux = info_aux;
8922 	return 0;
8923 
8924 err_free:
8925 	kvfree(krecord);
8926 	kfree(info_aux);
8927 	return ret;
8928 }
8929 
adjust_btf_func(struct bpf_verifier_env * env)8930 static void adjust_btf_func(struct bpf_verifier_env *env)
8931 {
8932 	struct bpf_prog_aux *aux = env->prog->aux;
8933 	int i;
8934 
8935 	if (!aux->func_info)
8936 		return;
8937 
8938 	for (i = 0; i < env->subprog_cnt; i++)
8939 		aux->func_info[i].insn_off = env->subprog_info[i].start;
8940 }
8941 
8942 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
8943 		sizeof(((struct bpf_line_info *)(0))->line_col))
8944 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
8945 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8946 static int check_btf_line(struct bpf_verifier_env *env,
8947 			  const union bpf_attr *attr,
8948 			  union bpf_attr __user *uattr)
8949 {
8950 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8951 	struct bpf_subprog_info *sub;
8952 	struct bpf_line_info *linfo;
8953 	struct bpf_prog *prog;
8954 	const struct btf *btf;
8955 	void __user *ulinfo;
8956 	int err;
8957 
8958 	nr_linfo = attr->line_info_cnt;
8959 	if (!nr_linfo)
8960 		return 0;
8961 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
8962 		return -EINVAL;
8963 
8964 	rec_size = attr->line_info_rec_size;
8965 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8966 	    rec_size > MAX_LINEINFO_REC_SIZE ||
8967 	    rec_size & (sizeof(u32) - 1))
8968 		return -EINVAL;
8969 
8970 	/* Need to zero it in case the userspace may
8971 	 * pass in a smaller bpf_line_info object.
8972 	 */
8973 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8974 			 GFP_KERNEL | __GFP_NOWARN);
8975 	if (!linfo)
8976 		return -ENOMEM;
8977 
8978 	prog = env->prog;
8979 	btf = prog->aux->btf;
8980 
8981 	s = 0;
8982 	sub = env->subprog_info;
8983 	ulinfo = u64_to_user_ptr(attr->line_info);
8984 	expected_size = sizeof(struct bpf_line_info);
8985 	ncopy = min_t(u32, expected_size, rec_size);
8986 	for (i = 0; i < nr_linfo; i++) {
8987 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8988 		if (err) {
8989 			if (err == -E2BIG) {
8990 				verbose(env, "nonzero tailing record in line_info");
8991 				if (put_user(expected_size,
8992 					     &uattr->line_info_rec_size))
8993 					err = -EFAULT;
8994 			}
8995 			goto err_free;
8996 		}
8997 
8998 		if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8999 			err = -EFAULT;
9000 			goto err_free;
9001 		}
9002 
9003 		/*
9004 		 * Check insn_off to ensure
9005 		 * 1) strictly increasing AND
9006 		 * 2) bounded by prog->len
9007 		 *
9008 		 * The linfo[0].insn_off == 0 check logically falls into
9009 		 * the later "missing bpf_line_info for func..." case
9010 		 * because the first linfo[0].insn_off must be the
9011 		 * first sub also and the first sub must have
9012 		 * subprog_info[0].start == 0.
9013 		 */
9014 		if ((i && linfo[i].insn_off <= prev_offset) ||
9015 		    linfo[i].insn_off >= prog->len) {
9016 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9017 				i, linfo[i].insn_off, prev_offset,
9018 				prog->len);
9019 			err = -EINVAL;
9020 			goto err_free;
9021 		}
9022 
9023 		if (!prog->insnsi[linfo[i].insn_off].code) {
9024 			verbose(env,
9025 				"Invalid insn code at line_info[%u].insn_off\n",
9026 				i);
9027 			err = -EINVAL;
9028 			goto err_free;
9029 		}
9030 
9031 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9032 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9033 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9034 			err = -EINVAL;
9035 			goto err_free;
9036 		}
9037 
9038 		if (s != env->subprog_cnt) {
9039 			if (linfo[i].insn_off == sub[s].start) {
9040 				sub[s].linfo_idx = i;
9041 				s++;
9042 			} else if (sub[s].start < linfo[i].insn_off) {
9043 				verbose(env, "missing bpf_line_info for func#%u\n", s);
9044 				err = -EINVAL;
9045 				goto err_free;
9046 			}
9047 		}
9048 
9049 		prev_offset = linfo[i].insn_off;
9050 		ulinfo += rec_size;
9051 	}
9052 
9053 	if (s != env->subprog_cnt) {
9054 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9055 			env->subprog_cnt - s, s);
9056 		err = -EINVAL;
9057 		goto err_free;
9058 	}
9059 
9060 	prog->aux->linfo = linfo;
9061 	prog->aux->nr_linfo = nr_linfo;
9062 
9063 	return 0;
9064 
9065 err_free:
9066 	kvfree(linfo);
9067 	return err;
9068 }
9069 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9070 static int check_btf_info(struct bpf_verifier_env *env,
9071 			  const union bpf_attr *attr,
9072 			  union bpf_attr __user *uattr)
9073 {
9074 	struct btf *btf;
9075 	int err;
9076 
9077 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
9078 		if (check_abnormal_return(env))
9079 			return -EINVAL;
9080 		return 0;
9081 	}
9082 
9083 	btf = btf_get_by_fd(attr->prog_btf_fd);
9084 	if (IS_ERR(btf))
9085 		return PTR_ERR(btf);
9086 	env->prog->aux->btf = btf;
9087 
9088 	err = check_btf_func(env, attr, uattr);
9089 	if (err)
9090 		return err;
9091 
9092 	err = check_btf_line(env, attr, uattr);
9093 	if (err)
9094 		return err;
9095 
9096 	return 0;
9097 }
9098 
9099 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)9100 static bool range_within(struct bpf_reg_state *old,
9101 			 struct bpf_reg_state *cur)
9102 {
9103 	return old->umin_value <= cur->umin_value &&
9104 	       old->umax_value >= cur->umax_value &&
9105 	       old->smin_value <= cur->smin_value &&
9106 	       old->smax_value >= cur->smax_value &&
9107 	       old->u32_min_value <= cur->u32_min_value &&
9108 	       old->u32_max_value >= cur->u32_max_value &&
9109 	       old->s32_min_value <= cur->s32_min_value &&
9110 	       old->s32_max_value >= cur->s32_max_value;
9111 }
9112 
9113 /* If in the old state two registers had the same id, then they need to have
9114  * the same id in the new state as well.  But that id could be different from
9115  * the old state, so we need to track the mapping from old to new ids.
9116  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9117  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
9118  * regs with a different old id could still have new id 9, we don't care about
9119  * that.
9120  * So we look through our idmap to see if this old id has been seen before.  If
9121  * so, we require the new id to match; otherwise, we add the id pair to the map.
9122  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)9123 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9124 {
9125 	unsigned int i;
9126 
9127 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9128 		if (!idmap[i].old) {
9129 			/* Reached an empty slot; haven't seen this id before */
9130 			idmap[i].old = old_id;
9131 			idmap[i].cur = cur_id;
9132 			return true;
9133 		}
9134 		if (idmap[i].old == old_id)
9135 			return idmap[i].cur == cur_id;
9136 	}
9137 	/* We ran out of idmap slots, which should be impossible */
9138 	WARN_ON_ONCE(1);
9139 	return false;
9140 }
9141 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)9142 static void clean_func_state(struct bpf_verifier_env *env,
9143 			     struct bpf_func_state *st)
9144 {
9145 	enum bpf_reg_liveness live;
9146 	int i, j;
9147 
9148 	for (i = 0; i < BPF_REG_FP; i++) {
9149 		live = st->regs[i].live;
9150 		/* liveness must not touch this register anymore */
9151 		st->regs[i].live |= REG_LIVE_DONE;
9152 		if (!(live & REG_LIVE_READ))
9153 			/* since the register is unused, clear its state
9154 			 * to make further comparison simpler
9155 			 */
9156 			__mark_reg_not_init(env, &st->regs[i]);
9157 	}
9158 
9159 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9160 		live = st->stack[i].spilled_ptr.live;
9161 		/* liveness must not touch this stack slot anymore */
9162 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9163 		if (!(live & REG_LIVE_READ)) {
9164 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9165 			for (j = 0; j < BPF_REG_SIZE; j++)
9166 				st->stack[i].slot_type[j] = STACK_INVALID;
9167 		}
9168 	}
9169 }
9170 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)9171 static void clean_verifier_state(struct bpf_verifier_env *env,
9172 				 struct bpf_verifier_state *st)
9173 {
9174 	int i;
9175 
9176 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9177 		/* all regs in this state in all frames were already marked */
9178 		return;
9179 
9180 	for (i = 0; i <= st->curframe; i++)
9181 		clean_func_state(env, st->frame[i]);
9182 }
9183 
9184 /* the parentage chains form a tree.
9185  * the verifier states are added to state lists at given insn and
9186  * pushed into state stack for future exploration.
9187  * when the verifier reaches bpf_exit insn some of the verifer states
9188  * stored in the state lists have their final liveness state already,
9189  * but a lot of states will get revised from liveness point of view when
9190  * the verifier explores other branches.
9191  * Example:
9192  * 1: r0 = 1
9193  * 2: if r1 == 100 goto pc+1
9194  * 3: r0 = 2
9195  * 4: exit
9196  * when the verifier reaches exit insn the register r0 in the state list of
9197  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9198  * of insn 2 and goes exploring further. At the insn 4 it will walk the
9199  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9200  *
9201  * Since the verifier pushes the branch states as it sees them while exploring
9202  * the program the condition of walking the branch instruction for the second
9203  * time means that all states below this branch were already explored and
9204  * their final liveness markes are already propagated.
9205  * Hence when the verifier completes the search of state list in is_state_visited()
9206  * we can call this clean_live_states() function to mark all liveness states
9207  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9208  * will not be used.
9209  * This function also clears the registers and stack for states that !READ
9210  * to simplify state merging.
9211  *
9212  * Important note here that walking the same branch instruction in the callee
9213  * doesn't meant that the states are DONE. The verifier has to compare
9214  * the callsites
9215  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)9216 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9217 			      struct bpf_verifier_state *cur)
9218 {
9219 	struct bpf_verifier_state_list *sl;
9220 	int i;
9221 
9222 	sl = *explored_state(env, insn);
9223 	while (sl) {
9224 		if (sl->state.branches)
9225 			goto next;
9226 		if (sl->state.insn_idx != insn ||
9227 		    sl->state.curframe != cur->curframe)
9228 			goto next;
9229 		for (i = 0; i <= cur->curframe; i++)
9230 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9231 				goto next;
9232 		clean_verifier_state(env, &sl->state);
9233 next:
9234 		sl = sl->next;
9235 	}
9236 }
9237 
9238 /* 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)9239 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9240 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9241 {
9242 	bool equal;
9243 
9244 	if (!(rold->live & REG_LIVE_READ))
9245 		/* explored state didn't use this */
9246 		return true;
9247 
9248 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9249 
9250 	if (rold->type == PTR_TO_STACK)
9251 		/* two stack pointers are equal only if they're pointing to
9252 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
9253 		 */
9254 		return equal && rold->frameno == rcur->frameno;
9255 
9256 	if (equal)
9257 		return true;
9258 
9259 	if (rold->type == NOT_INIT)
9260 		/* explored state can't have used this */
9261 		return true;
9262 	if (rcur->type == NOT_INIT)
9263 		return false;
9264 	switch (base_type(rold->type)) {
9265 	case SCALAR_VALUE:
9266 		if (env->explore_alu_limits)
9267 			return false;
9268 		if (rcur->type == SCALAR_VALUE) {
9269 			if (!rold->precise && !rcur->precise)
9270 				return true;
9271 			/* new val must satisfy old val knowledge */
9272 			return range_within(rold, rcur) &&
9273 			       tnum_in(rold->var_off, rcur->var_off);
9274 		} else {
9275 			/* We're trying to use a pointer in place of a scalar.
9276 			 * Even if the scalar was unbounded, this could lead to
9277 			 * pointer leaks because scalars are allowed to leak
9278 			 * while pointers are not. We could make this safe in
9279 			 * special cases if root is calling us, but it's
9280 			 * probably not worth the hassle.
9281 			 */
9282 			return false;
9283 		}
9284 	case PTR_TO_MAP_VALUE:
9285 		/* a PTR_TO_MAP_VALUE could be safe to use as a
9286 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9287 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9288 		 * checked, doing so could have affected others with the same
9289 		 * id, and we can't check for that because we lost the id when
9290 		 * we converted to a PTR_TO_MAP_VALUE.
9291 		 */
9292 		if (type_may_be_null(rold->type)) {
9293 			if (!type_may_be_null(rcur->type))
9294 				return false;
9295 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9296 				return false;
9297 			/* Check our ids match any regs they're supposed to */
9298 			return check_ids(rold->id, rcur->id, idmap);
9299 		}
9300 
9301 		/* If the new min/max/var_off satisfy the old ones and
9302 		 * everything else matches, we are OK.
9303 		 * 'id' is not compared, since it's only used for maps with
9304 		 * bpf_spin_lock inside map element and in such cases if
9305 		 * the rest of the prog is valid for one map element then
9306 		 * it's valid for all map elements regardless of the key
9307 		 * used in bpf_map_lookup()
9308 		 */
9309 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9310 		       range_within(rold, rcur) &&
9311 		       tnum_in(rold->var_off, rcur->var_off);
9312 	case PTR_TO_PACKET_META:
9313 	case PTR_TO_PACKET:
9314 		if (rcur->type != rold->type)
9315 			return false;
9316 		/* We must have at least as much range as the old ptr
9317 		 * did, so that any accesses which were safe before are
9318 		 * still safe.  This is true even if old range < old off,
9319 		 * since someone could have accessed through (ptr - k), or
9320 		 * even done ptr -= k in a register, to get a safe access.
9321 		 */
9322 		if (rold->range > rcur->range)
9323 			return false;
9324 		/* If the offsets don't match, we can't trust our alignment;
9325 		 * nor can we be sure that we won't fall out of range.
9326 		 */
9327 		if (rold->off != rcur->off)
9328 			return false;
9329 		/* id relations must be preserved */
9330 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9331 			return false;
9332 		/* new val must satisfy old val knowledge */
9333 		return range_within(rold, rcur) &&
9334 		       tnum_in(rold->var_off, rcur->var_off);
9335 	case PTR_TO_CTX:
9336 	case CONST_PTR_TO_MAP:
9337 	case PTR_TO_PACKET_END:
9338 	case PTR_TO_FLOW_KEYS:
9339 	case PTR_TO_SOCKET:
9340 	case PTR_TO_SOCK_COMMON:
9341 	case PTR_TO_TCP_SOCK:
9342 	case PTR_TO_XDP_SOCK:
9343 		/* Only valid matches are exact, which memcmp() above
9344 		 * would have accepted
9345 		 */
9346 	default:
9347 		/* Don't know what's going on, just say it's not safe */
9348 		return false;
9349 	}
9350 
9351 	/* Shouldn't get here; if we do, say it's not safe */
9352 	WARN_ON_ONCE(1);
9353 	return false;
9354 }
9355 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)9356 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9357 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9358 {
9359 	int i, spi;
9360 
9361 	/* walk slots of the explored stack and ignore any additional
9362 	 * slots in the current stack, since explored(safe) state
9363 	 * didn't use them
9364 	 */
9365 	for (i = 0; i < old->allocated_stack; i++) {
9366 		spi = i / BPF_REG_SIZE;
9367 
9368 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9369 			i += BPF_REG_SIZE - 1;
9370 			/* explored state didn't use this */
9371 			continue;
9372 		}
9373 
9374 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9375 			continue;
9376 
9377 		/* explored stack has more populated slots than current stack
9378 		 * and these slots were used
9379 		 */
9380 		if (i >= cur->allocated_stack)
9381 			return false;
9382 
9383 		/* if old state was safe with misc data in the stack
9384 		 * it will be safe with zero-initialized stack.
9385 		 * The opposite is not true
9386 		 */
9387 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9388 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9389 			continue;
9390 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9391 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9392 			/* Ex: old explored (safe) state has STACK_SPILL in
9393 			 * this stack slot, but current has STACK_MISC ->
9394 			 * this verifier states are not equivalent,
9395 			 * return false to continue verification of this path
9396 			 */
9397 			return false;
9398 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9399 			continue;
9400 		if (!is_spilled_reg(&old->stack[spi]))
9401 			continue;
9402 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
9403 			     &cur->stack[spi].spilled_ptr, idmap))
9404 			/* when explored and current stack slot are both storing
9405 			 * spilled registers, check that stored pointers types
9406 			 * are the same as well.
9407 			 * Ex: explored safe path could have stored
9408 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9409 			 * but current path has stored:
9410 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9411 			 * such verifier states are not equivalent.
9412 			 * return false to continue verification of this path
9413 			 */
9414 			return false;
9415 	}
9416 	return true;
9417 }
9418 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)9419 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9420 {
9421 	if (old->acquired_refs != cur->acquired_refs)
9422 		return false;
9423 	return !memcmp(old->refs, cur->refs,
9424 		       sizeof(*old->refs) * old->acquired_refs);
9425 }
9426 
9427 /* compare two verifier states
9428  *
9429  * all states stored in state_list are known to be valid, since
9430  * verifier reached 'bpf_exit' instruction through them
9431  *
9432  * this function is called when verifier exploring different branches of
9433  * execution popped from the state stack. If it sees an old state that has
9434  * more strict register state and more strict stack state then this execution
9435  * branch doesn't need to be explored further, since verifier already
9436  * concluded that more strict state leads to valid finish.
9437  *
9438  * Therefore two states are equivalent if register state is more conservative
9439  * and explored stack state is more conservative than the current one.
9440  * Example:
9441  *       explored                   current
9442  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9443  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9444  *
9445  * In other words if current stack state (one being explored) has more
9446  * valid slots than old one that already passed validation, it means
9447  * the verifier can stop exploring and conclude that current state is valid too
9448  *
9449  * Similarly with registers. If explored state has register type as invalid
9450  * whereas register type in current state is meaningful, it means that
9451  * the current state will reach 'bpf_exit' instruction safely
9452  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)9453 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9454 			      struct bpf_func_state *cur)
9455 {
9456 	int i;
9457 
9458 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9459 	for (i = 0; i < MAX_BPF_REG; i++)
9460 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
9461 			     env->idmap_scratch))
9462 			return false;
9463 
9464 	if (!stacksafe(env, old, cur, env->idmap_scratch))
9465 		return false;
9466 
9467 	if (!refsafe(old, cur))
9468 		return false;
9469 
9470 	return true;
9471 }
9472 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9473 static bool states_equal(struct bpf_verifier_env *env,
9474 			 struct bpf_verifier_state *old,
9475 			 struct bpf_verifier_state *cur)
9476 {
9477 	int i;
9478 
9479 	if (old->curframe != cur->curframe)
9480 		return false;
9481 
9482 	/* Verification state from speculative execution simulation
9483 	 * must never prune a non-speculative execution one.
9484 	 */
9485 	if (old->speculative && !cur->speculative)
9486 		return false;
9487 
9488 	if (old->active_spin_lock != cur->active_spin_lock)
9489 		return false;
9490 
9491 	/* for states to be equal callsites have to be the same
9492 	 * and all frame states need to be equivalent
9493 	 */
9494 	for (i = 0; i <= old->curframe; i++) {
9495 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
9496 			return false;
9497 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9498 			return false;
9499 	}
9500 	return true;
9501 }
9502 
9503 /* Return 0 if no propagation happened. Return negative error code if error
9504  * happened. Otherwise, return the propagated bit.
9505  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)9506 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9507 				  struct bpf_reg_state *reg,
9508 				  struct bpf_reg_state *parent_reg)
9509 {
9510 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9511 	u8 flag = reg->live & REG_LIVE_READ;
9512 	int err;
9513 
9514 	/* When comes here, read flags of PARENT_REG or REG could be any of
9515 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9516 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9517 	 */
9518 	if (parent_flag == REG_LIVE_READ64 ||
9519 	    /* Or if there is no read flag from REG. */
9520 	    !flag ||
9521 	    /* Or if the read flag from REG is the same as PARENT_REG. */
9522 	    parent_flag == flag)
9523 		return 0;
9524 
9525 	err = mark_reg_read(env, reg, parent_reg, flag);
9526 	if (err)
9527 		return err;
9528 
9529 	return flag;
9530 }
9531 
9532 /* A write screens off any subsequent reads; but write marks come from the
9533  * straight-line code between a state and its parent.  When we arrive at an
9534  * equivalent state (jump target or such) we didn't arrive by the straight-line
9535  * code, so read marks in the state must propagate to the parent regardless
9536  * of the state's write marks. That's what 'parent == state->parent' comparison
9537  * in mark_reg_read() is for.
9538  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)9539 static int propagate_liveness(struct bpf_verifier_env *env,
9540 			      const struct bpf_verifier_state *vstate,
9541 			      struct bpf_verifier_state *vparent)
9542 {
9543 	struct bpf_reg_state *state_reg, *parent_reg;
9544 	struct bpf_func_state *state, *parent;
9545 	int i, frame, err = 0;
9546 
9547 	if (vparent->curframe != vstate->curframe) {
9548 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
9549 		     vparent->curframe, vstate->curframe);
9550 		return -EFAULT;
9551 	}
9552 	/* Propagate read liveness of registers... */
9553 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9554 	for (frame = 0; frame <= vstate->curframe; frame++) {
9555 		parent = vparent->frame[frame];
9556 		state = vstate->frame[frame];
9557 		parent_reg = parent->regs;
9558 		state_reg = state->regs;
9559 		/* We don't need to worry about FP liveness, it's read-only */
9560 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9561 			err = propagate_liveness_reg(env, &state_reg[i],
9562 						     &parent_reg[i]);
9563 			if (err < 0)
9564 				return err;
9565 			if (err == REG_LIVE_READ64)
9566 				mark_insn_zext(env, &parent_reg[i]);
9567 		}
9568 
9569 		/* Propagate stack slots. */
9570 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9571 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9572 			parent_reg = &parent->stack[i].spilled_ptr;
9573 			state_reg = &state->stack[i].spilled_ptr;
9574 			err = propagate_liveness_reg(env, state_reg,
9575 						     parent_reg);
9576 			if (err < 0)
9577 				return err;
9578 		}
9579 	}
9580 	return 0;
9581 }
9582 
9583 /* find precise scalars in the previous equivalent state and
9584  * propagate them into the current state
9585  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)9586 static int propagate_precision(struct bpf_verifier_env *env,
9587 			       const struct bpf_verifier_state *old)
9588 {
9589 	struct bpf_reg_state *state_reg;
9590 	struct bpf_func_state *state;
9591 	int i, err = 0, fr;
9592 
9593 	for (fr = old->curframe; fr >= 0; fr--) {
9594 		state = old->frame[fr];
9595 		state_reg = state->regs;
9596 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9597 			if (state_reg->type != SCALAR_VALUE ||
9598 			    !state_reg->precise ||
9599 			    !(state_reg->live & REG_LIVE_READ))
9600 				continue;
9601 			if (env->log.level & BPF_LOG_LEVEL2)
9602 				verbose(env, "frame %d: propagating r%d\n", fr, i);
9603 			err = mark_chain_precision_frame(env, fr, i);
9604 			if (err < 0)
9605 				return err;
9606 		}
9607 
9608 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9609 			if (!is_spilled_reg(&state->stack[i]))
9610 				continue;
9611 			state_reg = &state->stack[i].spilled_ptr;
9612 			if (state_reg->type != SCALAR_VALUE ||
9613 			    !state_reg->precise ||
9614 			    !(state_reg->live & REG_LIVE_READ))
9615 				continue;
9616 			if (env->log.level & BPF_LOG_LEVEL2)
9617 				verbose(env, "frame %d: propagating fp%d\n",
9618 					fr, (-i - 1) * BPF_REG_SIZE);
9619 			err = mark_chain_precision_stack_frame(env, fr, i);
9620 			if (err < 0)
9621 				return err;
9622 		}
9623 	}
9624 	return 0;
9625 }
9626 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9627 static bool states_maybe_looping(struct bpf_verifier_state *old,
9628 				 struct bpf_verifier_state *cur)
9629 {
9630 	struct bpf_func_state *fold, *fcur;
9631 	int i, fr = cur->curframe;
9632 
9633 	if (old->curframe != fr)
9634 		return false;
9635 
9636 	fold = old->frame[fr];
9637 	fcur = cur->frame[fr];
9638 	for (i = 0; i < MAX_BPF_REG; i++)
9639 		if (memcmp(&fold->regs[i], &fcur->regs[i],
9640 			   offsetof(struct bpf_reg_state, parent)))
9641 			return false;
9642 	return true;
9643 }
9644 
9645 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)9646 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9647 {
9648 	struct bpf_verifier_state_list *new_sl;
9649 	struct bpf_verifier_state_list *sl, **pprev;
9650 	struct bpf_verifier_state *cur = env->cur_state, *new;
9651 	int i, j, err, states_cnt = 0;
9652 	bool add_new_state = env->test_state_freq ? true : false;
9653 
9654 	cur->last_insn_idx = env->prev_insn_idx;
9655 	if (!env->insn_aux_data[insn_idx].prune_point)
9656 		/* this 'insn_idx' instruction wasn't marked, so we will not
9657 		 * be doing state search here
9658 		 */
9659 		return 0;
9660 
9661 	/* bpf progs typically have pruning point every 4 instructions
9662 	 * http://vger.kernel.org/bpfconf2019.html#session-1
9663 	 * Do not add new state for future pruning if the verifier hasn't seen
9664 	 * at least 2 jumps and at least 8 instructions.
9665 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9666 	 * In tests that amounts to up to 50% reduction into total verifier
9667 	 * memory consumption and 20% verifier time speedup.
9668 	 */
9669 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9670 	    env->insn_processed - env->prev_insn_processed >= 8)
9671 		add_new_state = true;
9672 
9673 	pprev = explored_state(env, insn_idx);
9674 	sl = *pprev;
9675 
9676 	clean_live_states(env, insn_idx, cur);
9677 
9678 	while (sl) {
9679 		states_cnt++;
9680 		if (sl->state.insn_idx != insn_idx)
9681 			goto next;
9682 		if (sl->state.branches) {
9683 			if (states_maybe_looping(&sl->state, cur) &&
9684 			    states_equal(env, &sl->state, cur)) {
9685 				verbose_linfo(env, insn_idx, "; ");
9686 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9687 				return -EINVAL;
9688 			}
9689 			/* if the verifier is processing a loop, avoid adding new state
9690 			 * too often, since different loop iterations have distinct
9691 			 * states and may not help future pruning.
9692 			 * This threshold shouldn't be too low to make sure that
9693 			 * a loop with large bound will be rejected quickly.
9694 			 * The most abusive loop will be:
9695 			 * r1 += 1
9696 			 * if r1 < 1000000 goto pc-2
9697 			 * 1M insn_procssed limit / 100 == 10k peak states.
9698 			 * This threshold shouldn't be too high either, since states
9699 			 * at the end of the loop are likely to be useful in pruning.
9700 			 */
9701 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9702 			    env->insn_processed - env->prev_insn_processed < 100)
9703 				add_new_state = false;
9704 			goto miss;
9705 		}
9706 		if (states_equal(env, &sl->state, cur)) {
9707 			sl->hit_cnt++;
9708 			/* reached equivalent register/stack state,
9709 			 * prune the search.
9710 			 * Registers read by the continuation are read by us.
9711 			 * If we have any write marks in env->cur_state, they
9712 			 * will prevent corresponding reads in the continuation
9713 			 * from reaching our parent (an explored_state).  Our
9714 			 * own state will get the read marks recorded, but
9715 			 * they'll be immediately forgotten as we're pruning
9716 			 * this state and will pop a new one.
9717 			 */
9718 			err = propagate_liveness(env, &sl->state, cur);
9719 
9720 			/* if previous state reached the exit with precision and
9721 			 * current state is equivalent to it (except precsion marks)
9722 			 * the precision needs to be propagated back in
9723 			 * the current state.
9724 			 */
9725 			err = err ? : push_jmp_history(env, cur);
9726 			err = err ? : propagate_precision(env, &sl->state);
9727 			if (err)
9728 				return err;
9729 			return 1;
9730 		}
9731 miss:
9732 		/* when new state is not going to be added do not increase miss count.
9733 		 * Otherwise several loop iterations will remove the state
9734 		 * recorded earlier. The goal of these heuristics is to have
9735 		 * states from some iterations of the loop (some in the beginning
9736 		 * and some at the end) to help pruning.
9737 		 */
9738 		if (add_new_state)
9739 			sl->miss_cnt++;
9740 		/* heuristic to determine whether this state is beneficial
9741 		 * to keep checking from state equivalence point of view.
9742 		 * Higher numbers increase max_states_per_insn and verification time,
9743 		 * but do not meaningfully decrease insn_processed.
9744 		 */
9745 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9746 			/* the state is unlikely to be useful. Remove it to
9747 			 * speed up verification
9748 			 */
9749 			*pprev = sl->next;
9750 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9751 				u32 br = sl->state.branches;
9752 
9753 				WARN_ONCE(br,
9754 					  "BUG live_done but branches_to_explore %d\n",
9755 					  br);
9756 				free_verifier_state(&sl->state, false);
9757 				kfree(sl);
9758 				env->peak_states--;
9759 			} else {
9760 				/* cannot free this state, since parentage chain may
9761 				 * walk it later. Add it for free_list instead to
9762 				 * be freed at the end of verification
9763 				 */
9764 				sl->next = env->free_list;
9765 				env->free_list = sl;
9766 			}
9767 			sl = *pprev;
9768 			continue;
9769 		}
9770 next:
9771 		pprev = &sl->next;
9772 		sl = *pprev;
9773 	}
9774 
9775 	if (env->max_states_per_insn < states_cnt)
9776 		env->max_states_per_insn = states_cnt;
9777 
9778 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9779 		return push_jmp_history(env, cur);
9780 
9781 	if (!add_new_state)
9782 		return push_jmp_history(env, cur);
9783 
9784 	/* There were no equivalent states, remember the current one.
9785 	 * Technically the current state is not proven to be safe yet,
9786 	 * but it will either reach outer most bpf_exit (which means it's safe)
9787 	 * or it will be rejected. When there are no loops the verifier won't be
9788 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9789 	 * again on the way to bpf_exit.
9790 	 * When looping the sl->state.branches will be > 0 and this state
9791 	 * will not be considered for equivalence until branches == 0.
9792 	 */
9793 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9794 	if (!new_sl)
9795 		return -ENOMEM;
9796 	env->total_states++;
9797 	env->peak_states++;
9798 	env->prev_jmps_processed = env->jmps_processed;
9799 	env->prev_insn_processed = env->insn_processed;
9800 
9801 	/* add new state to the head of linked list */
9802 	new = &new_sl->state;
9803 	err = copy_verifier_state(new, cur);
9804 	if (err) {
9805 		free_verifier_state(new, false);
9806 		kfree(new_sl);
9807 		return err;
9808 	}
9809 	new->insn_idx = insn_idx;
9810 	WARN_ONCE(new->branches != 1,
9811 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9812 
9813 	cur->parent = new;
9814 	cur->first_insn_idx = insn_idx;
9815 	clear_jmp_history(cur);
9816 	new_sl->next = *explored_state(env, insn_idx);
9817 	*explored_state(env, insn_idx) = new_sl;
9818 	/* connect new state to parentage chain. Current frame needs all
9819 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
9820 	 * to the stack implicitly by JITs) so in callers' frames connect just
9821 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9822 	 * the state of the call instruction (with WRITTEN set), and r0 comes
9823 	 * from callee with its full parentage chain, anyway.
9824 	 */
9825 	/* clear write marks in current state: the writes we did are not writes
9826 	 * our child did, so they don't screen off its reads from us.
9827 	 * (There are no read marks in current state, because reads always mark
9828 	 * their parent and current state never has children yet.  Only
9829 	 * explored_states can get read marks.)
9830 	 */
9831 	for (j = 0; j <= cur->curframe; j++) {
9832 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9833 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9834 		for (i = 0; i < BPF_REG_FP; i++)
9835 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9836 	}
9837 
9838 	/* all stack frames are accessible from callee, clear them all */
9839 	for (j = 0; j <= cur->curframe; j++) {
9840 		struct bpf_func_state *frame = cur->frame[j];
9841 		struct bpf_func_state *newframe = new->frame[j];
9842 
9843 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9844 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9845 			frame->stack[i].spilled_ptr.parent =
9846 						&newframe->stack[i].spilled_ptr;
9847 		}
9848 	}
9849 	return 0;
9850 }
9851 
9852 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)9853 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9854 {
9855 	switch (base_type(type)) {
9856 	case PTR_TO_CTX:
9857 	case PTR_TO_SOCKET:
9858 	case PTR_TO_SOCK_COMMON:
9859 	case PTR_TO_TCP_SOCK:
9860 	case PTR_TO_XDP_SOCK:
9861 	case PTR_TO_BTF_ID:
9862 		return false;
9863 	default:
9864 		return true;
9865 	}
9866 }
9867 
9868 /* If an instruction was previously used with particular pointer types, then we
9869  * need to be careful to avoid cases such as the below, where it may be ok
9870  * for one branch accessing the pointer, but not ok for the other branch:
9871  *
9872  * R1 = sock_ptr
9873  * goto X;
9874  * ...
9875  * R1 = some_other_valid_ptr;
9876  * goto X;
9877  * ...
9878  * R2 = *(u32 *)(R1 + 0);
9879  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)9880 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9881 {
9882 	return src != prev && (!reg_type_mismatch_ok(src) ||
9883 			       !reg_type_mismatch_ok(prev));
9884 }
9885 
do_check(struct bpf_verifier_env * env)9886 static int do_check(struct bpf_verifier_env *env)
9887 {
9888 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9889 	struct bpf_verifier_state *state = env->cur_state;
9890 	struct bpf_insn *insns = env->prog->insnsi;
9891 	struct bpf_reg_state *regs;
9892 	int insn_cnt = env->prog->len;
9893 	bool do_print_state = false;
9894 	int prev_insn_idx = -1;
9895 
9896 	for (;;) {
9897 		struct bpf_insn *insn;
9898 		u8 class;
9899 		int err;
9900 
9901 		env->prev_insn_idx = prev_insn_idx;
9902 		if (env->insn_idx >= insn_cnt) {
9903 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
9904 				env->insn_idx, insn_cnt);
9905 			return -EFAULT;
9906 		}
9907 
9908 		insn = &insns[env->insn_idx];
9909 		class = BPF_CLASS(insn->code);
9910 
9911 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9912 			verbose(env,
9913 				"BPF program is too large. Processed %d insn\n",
9914 				env->insn_processed);
9915 			return -E2BIG;
9916 		}
9917 
9918 		err = is_state_visited(env, env->insn_idx);
9919 		if (err < 0)
9920 			return err;
9921 		if (err == 1) {
9922 			/* found equivalent state, can prune the search */
9923 			if (env->log.level & BPF_LOG_LEVEL) {
9924 				if (do_print_state)
9925 					verbose(env, "\nfrom %d to %d%s: safe\n",
9926 						env->prev_insn_idx, env->insn_idx,
9927 						env->cur_state->speculative ?
9928 						" (speculative execution)" : "");
9929 				else
9930 					verbose(env, "%d: safe\n", env->insn_idx);
9931 			}
9932 			goto process_bpf_exit;
9933 		}
9934 
9935 		if (signal_pending(current))
9936 			return -EAGAIN;
9937 
9938 		if (need_resched())
9939 			cond_resched();
9940 
9941 		if (env->log.level & BPF_LOG_LEVEL2 ||
9942 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9943 			if (env->log.level & BPF_LOG_LEVEL2)
9944 				verbose(env, "%d:", env->insn_idx);
9945 			else
9946 				verbose(env, "\nfrom %d to %d%s:",
9947 					env->prev_insn_idx, env->insn_idx,
9948 					env->cur_state->speculative ?
9949 					" (speculative execution)" : "");
9950 			print_verifier_state(env, state->frame[state->curframe]);
9951 			do_print_state = false;
9952 		}
9953 
9954 		if (env->log.level & BPF_LOG_LEVEL) {
9955 			const struct bpf_insn_cbs cbs = {
9956 				.cb_print	= verbose,
9957 				.private_data	= env,
9958 			};
9959 
9960 			verbose_linfo(env, env->insn_idx, "; ");
9961 			verbose(env, "%d: ", env->insn_idx);
9962 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9963 		}
9964 
9965 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
9966 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9967 							   env->prev_insn_idx);
9968 			if (err)
9969 				return err;
9970 		}
9971 
9972 		regs = cur_regs(env);
9973 		sanitize_mark_insn_seen(env);
9974 		prev_insn_idx = env->insn_idx;
9975 
9976 		if (class == BPF_ALU || class == BPF_ALU64) {
9977 			err = check_alu_op(env, insn);
9978 			if (err)
9979 				return err;
9980 
9981 		} else if (class == BPF_LDX) {
9982 			enum bpf_reg_type *prev_src_type, src_reg_type;
9983 
9984 			/* check for reserved fields is already done */
9985 
9986 			/* check src operand */
9987 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
9988 			if (err)
9989 				return err;
9990 
9991 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9992 			if (err)
9993 				return err;
9994 
9995 			src_reg_type = regs[insn->src_reg].type;
9996 
9997 			/* check that memory (src_reg + off) is readable,
9998 			 * the state of dst_reg will be updated by this func
9999 			 */
10000 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
10001 					       insn->off, BPF_SIZE(insn->code),
10002 					       BPF_READ, insn->dst_reg, false);
10003 			if (err)
10004 				return err;
10005 
10006 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10007 
10008 			if (*prev_src_type == NOT_INIT) {
10009 				/* saw a valid insn
10010 				 * dst_reg = *(u32 *)(src_reg + off)
10011 				 * save type to validate intersecting paths
10012 				 */
10013 				*prev_src_type = src_reg_type;
10014 
10015 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10016 				/* ABuser program is trying to use the same insn
10017 				 * dst_reg = *(u32*) (src_reg + off)
10018 				 * with different pointer types:
10019 				 * src_reg == ctx in one branch and
10020 				 * src_reg == stack|map in some other branch.
10021 				 * Reject it.
10022 				 */
10023 				verbose(env, "same insn cannot be used with different pointers\n");
10024 				return -EINVAL;
10025 			}
10026 
10027 		} else if (class == BPF_STX) {
10028 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
10029 
10030 			if (BPF_MODE(insn->code) == BPF_XADD) {
10031 				err = check_xadd(env, env->insn_idx, insn);
10032 				if (err)
10033 					return err;
10034 				env->insn_idx++;
10035 				continue;
10036 			}
10037 
10038 			/* check src1 operand */
10039 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
10040 			if (err)
10041 				return err;
10042 			/* check src2 operand */
10043 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10044 			if (err)
10045 				return err;
10046 
10047 			dst_reg_type = regs[insn->dst_reg].type;
10048 
10049 			/* check that memory (dst_reg + off) is writeable */
10050 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10051 					       insn->off, BPF_SIZE(insn->code),
10052 					       BPF_WRITE, insn->src_reg, false);
10053 			if (err)
10054 				return err;
10055 
10056 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10057 
10058 			if (*prev_dst_type == NOT_INIT) {
10059 				*prev_dst_type = dst_reg_type;
10060 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10061 				verbose(env, "same insn cannot be used with different pointers\n");
10062 				return -EINVAL;
10063 			}
10064 
10065 		} else if (class == BPF_ST) {
10066 			if (BPF_MODE(insn->code) != BPF_MEM ||
10067 			    insn->src_reg != BPF_REG_0) {
10068 				verbose(env, "BPF_ST uses reserved fields\n");
10069 				return -EINVAL;
10070 			}
10071 			/* check src operand */
10072 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10073 			if (err)
10074 				return err;
10075 
10076 			if (is_ctx_reg(env, insn->dst_reg)) {
10077 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10078 					insn->dst_reg,
10079 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
10080 				return -EACCES;
10081 			}
10082 
10083 			/* check that memory (dst_reg + off) is writeable */
10084 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10085 					       insn->off, BPF_SIZE(insn->code),
10086 					       BPF_WRITE, -1, false);
10087 			if (err)
10088 				return err;
10089 
10090 		} else if (class == BPF_JMP || class == BPF_JMP32) {
10091 			u8 opcode = BPF_OP(insn->code);
10092 
10093 			env->jmps_processed++;
10094 			if (opcode == BPF_CALL) {
10095 				if (BPF_SRC(insn->code) != BPF_K ||
10096 				    insn->off != 0 ||
10097 				    (insn->src_reg != BPF_REG_0 &&
10098 				     insn->src_reg != BPF_PSEUDO_CALL) ||
10099 				    insn->dst_reg != BPF_REG_0 ||
10100 				    class == BPF_JMP32) {
10101 					verbose(env, "BPF_CALL uses reserved fields\n");
10102 					return -EINVAL;
10103 				}
10104 
10105 				if (env->cur_state->active_spin_lock &&
10106 				    (insn->src_reg == BPF_PSEUDO_CALL ||
10107 				     insn->imm != BPF_FUNC_spin_unlock)) {
10108 					verbose(env, "function calls are not allowed while holding a lock\n");
10109 					return -EINVAL;
10110 				}
10111 				if (insn->src_reg == BPF_PSEUDO_CALL)
10112 					err = check_func_call(env, insn, &env->insn_idx);
10113 				else
10114 					err = check_helper_call(env, insn->imm, env->insn_idx);
10115 				if (err)
10116 					return err;
10117 
10118 			} else if (opcode == BPF_JA) {
10119 				if (BPF_SRC(insn->code) != BPF_K ||
10120 				    insn->imm != 0 ||
10121 				    insn->src_reg != BPF_REG_0 ||
10122 				    insn->dst_reg != BPF_REG_0 ||
10123 				    class == BPF_JMP32) {
10124 					verbose(env, "BPF_JA uses reserved fields\n");
10125 					return -EINVAL;
10126 				}
10127 
10128 				env->insn_idx += insn->off + 1;
10129 				continue;
10130 
10131 			} else if (opcode == BPF_EXIT) {
10132 				if (BPF_SRC(insn->code) != BPF_K ||
10133 				    insn->imm != 0 ||
10134 				    insn->src_reg != BPF_REG_0 ||
10135 				    insn->dst_reg != BPF_REG_0 ||
10136 				    class == BPF_JMP32) {
10137 					verbose(env, "BPF_EXIT uses reserved fields\n");
10138 					return -EINVAL;
10139 				}
10140 
10141 				if (env->cur_state->active_spin_lock) {
10142 					verbose(env, "bpf_spin_unlock is missing\n");
10143 					return -EINVAL;
10144 				}
10145 
10146 				if (state->curframe) {
10147 					/* exit from nested function */
10148 					err = prepare_func_exit(env, &env->insn_idx);
10149 					if (err)
10150 						return err;
10151 					do_print_state = true;
10152 					continue;
10153 				}
10154 
10155 				err = check_reference_leak(env);
10156 				if (err)
10157 					return err;
10158 
10159 				err = check_return_code(env);
10160 				if (err)
10161 					return err;
10162 process_bpf_exit:
10163 				update_branch_counts(env, env->cur_state);
10164 				err = pop_stack(env, &prev_insn_idx,
10165 						&env->insn_idx, pop_log);
10166 				if (err < 0) {
10167 					if (err != -ENOENT)
10168 						return err;
10169 					break;
10170 				} else {
10171 					do_print_state = true;
10172 					continue;
10173 				}
10174 			} else {
10175 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
10176 				if (err)
10177 					return err;
10178 			}
10179 		} else if (class == BPF_LD) {
10180 			u8 mode = BPF_MODE(insn->code);
10181 
10182 			if (mode == BPF_ABS || mode == BPF_IND) {
10183 				err = check_ld_abs(env, insn);
10184 				if (err)
10185 					return err;
10186 
10187 			} else if (mode == BPF_IMM) {
10188 				err = check_ld_imm(env, insn);
10189 				if (err)
10190 					return err;
10191 
10192 				env->insn_idx++;
10193 				sanitize_mark_insn_seen(env);
10194 			} else {
10195 				verbose(env, "invalid BPF_LD mode\n");
10196 				return -EINVAL;
10197 			}
10198 		} else {
10199 			verbose(env, "unknown insn class %d\n", class);
10200 			return -EINVAL;
10201 		}
10202 
10203 		env->insn_idx++;
10204 	}
10205 
10206 	return 0;
10207 }
10208 
10209 /* 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)10210 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10211 			       struct bpf_insn *insn,
10212 			       struct bpf_insn_aux_data *aux)
10213 {
10214 	const struct btf_var_secinfo *vsi;
10215 	const struct btf_type *datasec;
10216 	const struct btf_type *t;
10217 	const char *sym_name;
10218 	bool percpu = false;
10219 	u32 type, id = insn->imm;
10220 	s32 datasec_id;
10221 	u64 addr;
10222 	int i;
10223 
10224 	if (!btf_vmlinux) {
10225 		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10226 		return -EINVAL;
10227 	}
10228 
10229 	if (insn[1].imm != 0) {
10230 		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10231 		return -EINVAL;
10232 	}
10233 
10234 	t = btf_type_by_id(btf_vmlinux, id);
10235 	if (!t) {
10236 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10237 		return -ENOENT;
10238 	}
10239 
10240 	if (!btf_type_is_var(t)) {
10241 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10242 			id);
10243 		return -EINVAL;
10244 	}
10245 
10246 	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10247 	addr = kallsyms_lookup_name(sym_name);
10248 	if (!addr) {
10249 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10250 			sym_name);
10251 		return -ENOENT;
10252 	}
10253 
10254 	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10255 					   BTF_KIND_DATASEC);
10256 	if (datasec_id > 0) {
10257 		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10258 		for_each_vsi(i, datasec, vsi) {
10259 			if (vsi->type == id) {
10260 				percpu = true;
10261 				break;
10262 			}
10263 		}
10264 	}
10265 
10266 	insn[0].imm = (u32)addr;
10267 	insn[1].imm = addr >> 32;
10268 
10269 	type = t->type;
10270 	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10271 	if (percpu) {
10272 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10273 		aux->btf_var.btf_id = type;
10274 	} else if (!btf_type_is_struct(t)) {
10275 		const struct btf_type *ret;
10276 		const char *tname;
10277 		u32 tsize;
10278 
10279 		/* resolve the type size of ksym. */
10280 		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10281 		if (IS_ERR(ret)) {
10282 			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10283 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10284 				tname, PTR_ERR(ret));
10285 			return -EINVAL;
10286 		}
10287 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
10288 		aux->btf_var.mem_size = tsize;
10289 	} else {
10290 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
10291 		aux->btf_var.btf_id = type;
10292 	}
10293 	return 0;
10294 }
10295 
check_map_prealloc(struct bpf_map * map)10296 static int check_map_prealloc(struct bpf_map *map)
10297 {
10298 	return (map->map_type != BPF_MAP_TYPE_HASH &&
10299 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10300 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10301 		!(map->map_flags & BPF_F_NO_PREALLOC);
10302 }
10303 
is_tracing_prog_type(enum bpf_prog_type type)10304 static bool is_tracing_prog_type(enum bpf_prog_type type)
10305 {
10306 	switch (type) {
10307 	case BPF_PROG_TYPE_KPROBE:
10308 	case BPF_PROG_TYPE_TRACEPOINT:
10309 	case BPF_PROG_TYPE_PERF_EVENT:
10310 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10311 		return true;
10312 	default:
10313 		return false;
10314 	}
10315 }
10316 
is_preallocated_map(struct bpf_map * map)10317 static bool is_preallocated_map(struct bpf_map *map)
10318 {
10319 	if (!check_map_prealloc(map))
10320 		return false;
10321 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10322 		return false;
10323 	return true;
10324 }
10325 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)10326 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10327 					struct bpf_map *map,
10328 					struct bpf_prog *prog)
10329 
10330 {
10331 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10332 	/*
10333 	 * Validate that trace type programs use preallocated hash maps.
10334 	 *
10335 	 * For programs attached to PERF events this is mandatory as the
10336 	 * perf NMI can hit any arbitrary code sequence.
10337 	 *
10338 	 * All other trace types using preallocated hash maps are unsafe as
10339 	 * well because tracepoint or kprobes can be inside locked regions
10340 	 * of the memory allocator or at a place where a recursion into the
10341 	 * memory allocator would see inconsistent state.
10342 	 *
10343 	 * On RT enabled kernels run-time allocation of all trace type
10344 	 * programs is strictly prohibited due to lock type constraints. On
10345 	 * !RT kernels it is allowed for backwards compatibility reasons for
10346 	 * now, but warnings are emitted so developers are made aware of
10347 	 * the unsafety and can fix their programs before this is enforced.
10348 	 */
10349 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10350 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10351 			verbose(env, "perf_event programs can only use preallocated hash map\n");
10352 			return -EINVAL;
10353 		}
10354 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10355 			verbose(env, "trace type programs can only use preallocated hash map\n");
10356 			return -EINVAL;
10357 		}
10358 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10359 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10360 	}
10361 
10362 	if ((is_tracing_prog_type(prog_type) ||
10363 	     prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10364 	    map_value_has_spin_lock(map)) {
10365 		verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10366 		return -EINVAL;
10367 	}
10368 
10369 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10370 	    !bpf_offload_prog_map_match(prog, map)) {
10371 		verbose(env, "offload device mismatch between prog and map\n");
10372 		return -EINVAL;
10373 	}
10374 
10375 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10376 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10377 		return -EINVAL;
10378 	}
10379 
10380 	if (prog->aux->sleepable)
10381 		switch (map->map_type) {
10382 		case BPF_MAP_TYPE_HASH:
10383 		case BPF_MAP_TYPE_LRU_HASH:
10384 		case BPF_MAP_TYPE_ARRAY:
10385 			if (!is_preallocated_map(map)) {
10386 				verbose(env,
10387 					"Sleepable programs can only use preallocated hash maps\n");
10388 				return -EINVAL;
10389 			}
10390 			break;
10391 		default:
10392 			verbose(env,
10393 				"Sleepable programs can only use array and hash maps\n");
10394 			return -EINVAL;
10395 		}
10396 
10397 	return 0;
10398 }
10399 
bpf_map_is_cgroup_storage(struct bpf_map * map)10400 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10401 {
10402 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10403 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10404 }
10405 
10406 /* find and rewrite pseudo imm in ld_imm64 instructions:
10407  *
10408  * 1. if it accesses map FD, replace it with actual map pointer.
10409  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10410  *
10411  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10412  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)10413 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10414 {
10415 	struct bpf_insn *insn = env->prog->insnsi;
10416 	int insn_cnt = env->prog->len;
10417 	int i, j, err;
10418 
10419 	err = bpf_prog_calc_tag(env->prog);
10420 	if (err)
10421 		return err;
10422 
10423 	for (i = 0; i < insn_cnt; i++, insn++) {
10424 		if (BPF_CLASS(insn->code) == BPF_LDX &&
10425 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10426 			verbose(env, "BPF_LDX uses reserved fields\n");
10427 			return -EINVAL;
10428 		}
10429 
10430 		if (BPF_CLASS(insn->code) == BPF_STX &&
10431 		    ((BPF_MODE(insn->code) != BPF_MEM &&
10432 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10433 			verbose(env, "BPF_STX uses reserved fields\n");
10434 			return -EINVAL;
10435 		}
10436 
10437 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10438 			struct bpf_insn_aux_data *aux;
10439 			struct bpf_map *map;
10440 			struct fd f;
10441 			u64 addr;
10442 
10443 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
10444 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10445 			    insn[1].off != 0) {
10446 				verbose(env, "invalid bpf_ld_imm64 insn\n");
10447 				return -EINVAL;
10448 			}
10449 
10450 			if (insn[0].src_reg == 0)
10451 				/* valid generic load 64-bit imm */
10452 				goto next_insn;
10453 
10454 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10455 				aux = &env->insn_aux_data[i];
10456 				err = check_pseudo_btf_id(env, insn, aux);
10457 				if (err)
10458 					return err;
10459 				goto next_insn;
10460 			}
10461 
10462 			/* In final convert_pseudo_ld_imm64() step, this is
10463 			 * converted into regular 64-bit imm load insn.
10464 			 */
10465 			if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10466 			     insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10467 			    (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10468 			     insn[1].imm != 0)) {
10469 				verbose(env,
10470 					"unrecognized bpf_ld_imm64 insn\n");
10471 				return -EINVAL;
10472 			}
10473 
10474 			f = fdget(insn[0].imm);
10475 			map = __bpf_map_get(f);
10476 			if (IS_ERR(map)) {
10477 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
10478 					insn[0].imm);
10479 				return PTR_ERR(map);
10480 			}
10481 
10482 			err = check_map_prog_compatibility(env, map, env->prog);
10483 			if (err) {
10484 				fdput(f);
10485 				return err;
10486 			}
10487 
10488 			aux = &env->insn_aux_data[i];
10489 			if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10490 				addr = (unsigned long)map;
10491 			} else {
10492 				u32 off = insn[1].imm;
10493 
10494 				if (off >= BPF_MAX_VAR_OFF) {
10495 					verbose(env, "direct value offset of %u is not allowed\n", off);
10496 					fdput(f);
10497 					return -EINVAL;
10498 				}
10499 
10500 				if (!map->ops->map_direct_value_addr) {
10501 					verbose(env, "no direct value access support for this map type\n");
10502 					fdput(f);
10503 					return -EINVAL;
10504 				}
10505 
10506 				err = map->ops->map_direct_value_addr(map, &addr, off);
10507 				if (err) {
10508 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10509 						map->value_size, off);
10510 					fdput(f);
10511 					return err;
10512 				}
10513 
10514 				aux->map_off = off;
10515 				addr += off;
10516 			}
10517 
10518 			insn[0].imm = (u32)addr;
10519 			insn[1].imm = addr >> 32;
10520 
10521 			/* check whether we recorded this map already */
10522 			for (j = 0; j < env->used_map_cnt; j++) {
10523 				if (env->used_maps[j] == map) {
10524 					aux->map_index = j;
10525 					fdput(f);
10526 					goto next_insn;
10527 				}
10528 			}
10529 
10530 			if (env->used_map_cnt >= MAX_USED_MAPS) {
10531 				fdput(f);
10532 				return -E2BIG;
10533 			}
10534 
10535 			/* hold the map. If the program is rejected by verifier,
10536 			 * the map will be released by release_maps() or it
10537 			 * will be used by the valid program until it's unloaded
10538 			 * and all maps are released in free_used_maps()
10539 			 */
10540 			bpf_map_inc(map);
10541 
10542 			aux->map_index = env->used_map_cnt;
10543 			env->used_maps[env->used_map_cnt++] = map;
10544 
10545 			if (bpf_map_is_cgroup_storage(map) &&
10546 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
10547 				verbose(env, "only one cgroup storage of each type is allowed\n");
10548 				fdput(f);
10549 				return -EBUSY;
10550 			}
10551 
10552 			fdput(f);
10553 next_insn:
10554 			insn++;
10555 			i++;
10556 			continue;
10557 		}
10558 
10559 		/* Basic sanity check before we invest more work here. */
10560 		if (!bpf_opcode_in_insntable(insn->code)) {
10561 			verbose(env, "unknown opcode %02x\n", insn->code);
10562 			return -EINVAL;
10563 		}
10564 	}
10565 
10566 	/* now all pseudo BPF_LD_IMM64 instructions load valid
10567 	 * 'struct bpf_map *' into a register instead of user map_fd.
10568 	 * These pointers will be used later by verifier to validate map access.
10569 	 */
10570 	return 0;
10571 }
10572 
10573 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)10574 static void release_maps(struct bpf_verifier_env *env)
10575 {
10576 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
10577 			     env->used_map_cnt);
10578 }
10579 
10580 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)10581 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10582 {
10583 	struct bpf_insn *insn = env->prog->insnsi;
10584 	int insn_cnt = env->prog->len;
10585 	int i;
10586 
10587 	for (i = 0; i < insn_cnt; i++, insn++)
10588 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10589 			insn->src_reg = 0;
10590 }
10591 
10592 /* single env->prog->insni[off] instruction was replaced with the range
10593  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
10594  * [0, off) and [off, end) to new locations, so the patched range stays zero
10595  */
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)10596 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10597 				 struct bpf_insn_aux_data *new_data,
10598 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
10599 {
10600 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10601 	struct bpf_insn *insn = new_prog->insnsi;
10602 	u32 old_seen = old_data[off].seen;
10603 	u32 prog_len;
10604 	int i;
10605 
10606 	/* aux info at OFF always needs adjustment, no matter fast path
10607 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10608 	 * original insn at old prog.
10609 	 */
10610 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10611 
10612 	if (cnt == 1)
10613 		return;
10614 	prog_len = new_prog->len;
10615 
10616 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10617 	memcpy(new_data + off + cnt - 1, old_data + off,
10618 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10619 	for (i = off; i < off + cnt - 1; i++) {
10620 		/* Expand insni[off]'s seen count to the patched range. */
10621 		new_data[i].seen = old_seen;
10622 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
10623 	}
10624 	env->insn_aux_data = new_data;
10625 	vfree(old_data);
10626 }
10627 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)10628 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10629 {
10630 	int i;
10631 
10632 	if (len == 1)
10633 		return;
10634 	/* NOTE: fake 'exit' subprog should be updated as well. */
10635 	for (i = 0; i <= env->subprog_cnt; i++) {
10636 		if (env->subprog_info[i].start <= off)
10637 			continue;
10638 		env->subprog_info[i].start += len - 1;
10639 	}
10640 }
10641 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)10642 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10643 {
10644 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10645 	int i, sz = prog->aux->size_poke_tab;
10646 	struct bpf_jit_poke_descriptor *desc;
10647 
10648 	for (i = 0; i < sz; i++) {
10649 		desc = &tab[i];
10650 		if (desc->insn_idx <= off)
10651 			continue;
10652 		desc->insn_idx += len - 1;
10653 	}
10654 }
10655 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)10656 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10657 					    const struct bpf_insn *patch, u32 len)
10658 {
10659 	struct bpf_prog *new_prog;
10660 	struct bpf_insn_aux_data *new_data = NULL;
10661 
10662 	if (len > 1) {
10663 		new_data = vzalloc(array_size(env->prog->len + len - 1,
10664 					      sizeof(struct bpf_insn_aux_data)));
10665 		if (!new_data)
10666 			return NULL;
10667 	}
10668 
10669 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10670 	if (IS_ERR(new_prog)) {
10671 		if (PTR_ERR(new_prog) == -ERANGE)
10672 			verbose(env,
10673 				"insn %d cannot be patched due to 16-bit range\n",
10674 				env->insn_aux_data[off].orig_idx);
10675 		vfree(new_data);
10676 		return NULL;
10677 	}
10678 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
10679 	adjust_subprog_starts(env, off, len);
10680 	adjust_poke_descs(new_prog, off, len);
10681 	return new_prog;
10682 }
10683 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10684 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10685 					      u32 off, u32 cnt)
10686 {
10687 	int i, j;
10688 
10689 	/* find first prog starting at or after off (first to remove) */
10690 	for (i = 0; i < env->subprog_cnt; i++)
10691 		if (env->subprog_info[i].start >= off)
10692 			break;
10693 	/* find first prog starting at or after off + cnt (first to stay) */
10694 	for (j = i; j < env->subprog_cnt; j++)
10695 		if (env->subprog_info[j].start >= off + cnt)
10696 			break;
10697 	/* if j doesn't start exactly at off + cnt, we are just removing
10698 	 * the front of previous prog
10699 	 */
10700 	if (env->subprog_info[j].start != off + cnt)
10701 		j--;
10702 
10703 	if (j > i) {
10704 		struct bpf_prog_aux *aux = env->prog->aux;
10705 		int move;
10706 
10707 		/* move fake 'exit' subprog as well */
10708 		move = env->subprog_cnt + 1 - j;
10709 
10710 		memmove(env->subprog_info + i,
10711 			env->subprog_info + j,
10712 			sizeof(*env->subprog_info) * move);
10713 		env->subprog_cnt -= j - i;
10714 
10715 		/* remove func_info */
10716 		if (aux->func_info) {
10717 			move = aux->func_info_cnt - j;
10718 
10719 			memmove(aux->func_info + i,
10720 				aux->func_info + j,
10721 				sizeof(*aux->func_info) * move);
10722 			aux->func_info_cnt -= j - i;
10723 			/* func_info->insn_off is set after all code rewrites,
10724 			 * in adjust_btf_func() - no need to adjust
10725 			 */
10726 		}
10727 	} else {
10728 		/* convert i from "first prog to remove" to "first to adjust" */
10729 		if (env->subprog_info[i].start == off)
10730 			i++;
10731 	}
10732 
10733 	/* update fake 'exit' subprog as well */
10734 	for (; i <= env->subprog_cnt; i++)
10735 		env->subprog_info[i].start -= cnt;
10736 
10737 	return 0;
10738 }
10739 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10740 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10741 				      u32 cnt)
10742 {
10743 	struct bpf_prog *prog = env->prog;
10744 	u32 i, l_off, l_cnt, nr_linfo;
10745 	struct bpf_line_info *linfo;
10746 
10747 	nr_linfo = prog->aux->nr_linfo;
10748 	if (!nr_linfo)
10749 		return 0;
10750 
10751 	linfo = prog->aux->linfo;
10752 
10753 	/* find first line info to remove, count lines to be removed */
10754 	for (i = 0; i < nr_linfo; i++)
10755 		if (linfo[i].insn_off >= off)
10756 			break;
10757 
10758 	l_off = i;
10759 	l_cnt = 0;
10760 	for (; i < nr_linfo; i++)
10761 		if (linfo[i].insn_off < off + cnt)
10762 			l_cnt++;
10763 		else
10764 			break;
10765 
10766 	/* First live insn doesn't match first live linfo, it needs to "inherit"
10767 	 * last removed linfo.  prog is already modified, so prog->len == off
10768 	 * means no live instructions after (tail of the program was removed).
10769 	 */
10770 	if (prog->len != off && l_cnt &&
10771 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10772 		l_cnt--;
10773 		linfo[--i].insn_off = off + cnt;
10774 	}
10775 
10776 	/* remove the line info which refer to the removed instructions */
10777 	if (l_cnt) {
10778 		memmove(linfo + l_off, linfo + i,
10779 			sizeof(*linfo) * (nr_linfo - i));
10780 
10781 		prog->aux->nr_linfo -= l_cnt;
10782 		nr_linfo = prog->aux->nr_linfo;
10783 	}
10784 
10785 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
10786 	for (i = l_off; i < nr_linfo; i++)
10787 		linfo[i].insn_off -= cnt;
10788 
10789 	/* fix up all subprogs (incl. 'exit') which start >= off */
10790 	for (i = 0; i <= env->subprog_cnt; i++)
10791 		if (env->subprog_info[i].linfo_idx > l_off) {
10792 			/* program may have started in the removed region but
10793 			 * may not be fully removed
10794 			 */
10795 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10796 				env->subprog_info[i].linfo_idx -= l_cnt;
10797 			else
10798 				env->subprog_info[i].linfo_idx = l_off;
10799 		}
10800 
10801 	return 0;
10802 }
10803 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)10804 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10805 {
10806 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10807 	unsigned int orig_prog_len = env->prog->len;
10808 	int err;
10809 
10810 	if (bpf_prog_is_dev_bound(env->prog->aux))
10811 		bpf_prog_offload_remove_insns(env, off, cnt);
10812 
10813 	err = bpf_remove_insns(env->prog, off, cnt);
10814 	if (err)
10815 		return err;
10816 
10817 	err = adjust_subprog_starts_after_remove(env, off, cnt);
10818 	if (err)
10819 		return err;
10820 
10821 	err = bpf_adj_linfo_after_remove(env, off, cnt);
10822 	if (err)
10823 		return err;
10824 
10825 	memmove(aux_data + off,	aux_data + off + cnt,
10826 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
10827 
10828 	return 0;
10829 }
10830 
10831 /* The verifier does more data flow analysis than llvm and will not
10832  * explore branches that are dead at run time. Malicious programs can
10833  * have dead code too. Therefore replace all dead at-run-time code
10834  * with 'ja -1'.
10835  *
10836  * Just nops are not optimal, e.g. if they would sit at the end of the
10837  * program and through another bug we would manage to jump there, then
10838  * we'd execute beyond program memory otherwise. Returning exception
10839  * code also wouldn't work since we can have subprogs where the dead
10840  * code could be located.
10841  */
sanitize_dead_code(struct bpf_verifier_env * env)10842 static void sanitize_dead_code(struct bpf_verifier_env *env)
10843 {
10844 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10845 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10846 	struct bpf_insn *insn = env->prog->insnsi;
10847 	const int insn_cnt = env->prog->len;
10848 	int i;
10849 
10850 	for (i = 0; i < insn_cnt; i++) {
10851 		if (aux_data[i].seen)
10852 			continue;
10853 		memcpy(insn + i, &trap, sizeof(trap));
10854 		aux_data[i].zext_dst = false;
10855 	}
10856 }
10857 
insn_is_cond_jump(u8 code)10858 static bool insn_is_cond_jump(u8 code)
10859 {
10860 	u8 op;
10861 
10862 	if (BPF_CLASS(code) == BPF_JMP32)
10863 		return true;
10864 
10865 	if (BPF_CLASS(code) != BPF_JMP)
10866 		return false;
10867 
10868 	op = BPF_OP(code);
10869 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10870 }
10871 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)10872 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10873 {
10874 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10875 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10876 	struct bpf_insn *insn = env->prog->insnsi;
10877 	const int insn_cnt = env->prog->len;
10878 	int i;
10879 
10880 	for (i = 0; i < insn_cnt; i++, insn++) {
10881 		if (!insn_is_cond_jump(insn->code))
10882 			continue;
10883 
10884 		if (!aux_data[i + 1].seen)
10885 			ja.off = insn->off;
10886 		else if (!aux_data[i + 1 + insn->off].seen)
10887 			ja.off = 0;
10888 		else
10889 			continue;
10890 
10891 		if (bpf_prog_is_dev_bound(env->prog->aux))
10892 			bpf_prog_offload_replace_insn(env, i, &ja);
10893 
10894 		memcpy(insn, &ja, sizeof(ja));
10895 	}
10896 }
10897 
opt_remove_dead_code(struct bpf_verifier_env * env)10898 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10899 {
10900 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10901 	int insn_cnt = env->prog->len;
10902 	int i, err;
10903 
10904 	for (i = 0; i < insn_cnt; i++) {
10905 		int j;
10906 
10907 		j = 0;
10908 		while (i + j < insn_cnt && !aux_data[i + j].seen)
10909 			j++;
10910 		if (!j)
10911 			continue;
10912 
10913 		err = verifier_remove_insns(env, i, j);
10914 		if (err)
10915 			return err;
10916 		insn_cnt = env->prog->len;
10917 	}
10918 
10919 	return 0;
10920 }
10921 
opt_remove_nops(struct bpf_verifier_env * env)10922 static int opt_remove_nops(struct bpf_verifier_env *env)
10923 {
10924 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10925 	struct bpf_insn *insn = env->prog->insnsi;
10926 	int insn_cnt = env->prog->len;
10927 	int i, err;
10928 
10929 	for (i = 0; i < insn_cnt; i++) {
10930 		if (memcmp(&insn[i], &ja, sizeof(ja)))
10931 			continue;
10932 
10933 		err = verifier_remove_insns(env, i, 1);
10934 		if (err)
10935 			return err;
10936 		insn_cnt--;
10937 		i--;
10938 	}
10939 
10940 	return 0;
10941 }
10942 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)10943 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10944 					 const union bpf_attr *attr)
10945 {
10946 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10947 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
10948 	int i, patch_len, delta = 0, len = env->prog->len;
10949 	struct bpf_insn *insns = env->prog->insnsi;
10950 	struct bpf_prog *new_prog;
10951 	bool rnd_hi32;
10952 
10953 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
10954 	zext_patch[1] = BPF_ZEXT_REG(0);
10955 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10956 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10957 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
10958 	for (i = 0; i < len; i++) {
10959 		int adj_idx = i + delta;
10960 		struct bpf_insn insn;
10961 
10962 		insn = insns[adj_idx];
10963 		if (!aux[adj_idx].zext_dst) {
10964 			u8 code, class;
10965 			u32 imm_rnd;
10966 
10967 			if (!rnd_hi32)
10968 				continue;
10969 
10970 			code = insn.code;
10971 			class = BPF_CLASS(code);
10972 			if (insn_no_def(&insn))
10973 				continue;
10974 
10975 			/* NOTE: arg "reg" (the fourth one) is only used for
10976 			 *       BPF_STX which has been ruled out in above
10977 			 *       check, it is safe to pass NULL here.
10978 			 */
10979 			if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10980 				if (class == BPF_LD &&
10981 				    BPF_MODE(code) == BPF_IMM)
10982 					i++;
10983 				continue;
10984 			}
10985 
10986 			/* ctx load could be transformed into wider load. */
10987 			if (class == BPF_LDX &&
10988 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
10989 				continue;
10990 
10991 			imm_rnd = get_random_int();
10992 			rnd_hi32_patch[0] = insn;
10993 			rnd_hi32_patch[1].imm = imm_rnd;
10994 			rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10995 			patch = rnd_hi32_patch;
10996 			patch_len = 4;
10997 			goto apply_patch_buffer;
10998 		}
10999 
11000 		if (!bpf_jit_needs_zext())
11001 			continue;
11002 
11003 		zext_patch[0] = insn;
11004 		zext_patch[1].dst_reg = insn.dst_reg;
11005 		zext_patch[1].src_reg = insn.dst_reg;
11006 		patch = zext_patch;
11007 		patch_len = 2;
11008 apply_patch_buffer:
11009 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11010 		if (!new_prog)
11011 			return -ENOMEM;
11012 		env->prog = new_prog;
11013 		insns = new_prog->insnsi;
11014 		aux = env->insn_aux_data;
11015 		delta += patch_len - 1;
11016 	}
11017 
11018 	return 0;
11019 }
11020 
11021 /* convert load instructions that access fields of a context type into a
11022  * sequence of instructions that access fields of the underlying structure:
11023  *     struct __sk_buff    -> struct sk_buff
11024  *     struct bpf_sock_ops -> struct sock
11025  */
convert_ctx_accesses(struct bpf_verifier_env * env)11026 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11027 {
11028 	const struct bpf_verifier_ops *ops = env->ops;
11029 	int i, cnt, size, ctx_field_size, delta = 0;
11030 	const int insn_cnt = env->prog->len;
11031 	struct bpf_insn insn_buf[16], *insn;
11032 	u32 target_size, size_default, off;
11033 	struct bpf_prog *new_prog;
11034 	enum bpf_access_type type;
11035 	bool is_narrower_load;
11036 
11037 	if (ops->gen_prologue || env->seen_direct_write) {
11038 		if (!ops->gen_prologue) {
11039 			verbose(env, "bpf verifier is misconfigured\n");
11040 			return -EINVAL;
11041 		}
11042 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11043 					env->prog);
11044 		if (cnt >= ARRAY_SIZE(insn_buf)) {
11045 			verbose(env, "bpf verifier is misconfigured\n");
11046 			return -EINVAL;
11047 		} else if (cnt) {
11048 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11049 			if (!new_prog)
11050 				return -ENOMEM;
11051 
11052 			env->prog = new_prog;
11053 			delta += cnt - 1;
11054 		}
11055 	}
11056 
11057 	if (bpf_prog_is_dev_bound(env->prog->aux))
11058 		return 0;
11059 
11060 	insn = env->prog->insnsi + delta;
11061 
11062 	for (i = 0; i < insn_cnt; i++, insn++) {
11063 		bpf_convert_ctx_access_t convert_ctx_access;
11064 		bool ctx_access;
11065 
11066 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11067 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11068 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11069 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11070 			type = BPF_READ;
11071 			ctx_access = true;
11072 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11073 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11074 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11075 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11076 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11077 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11078 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11079 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11080 			type = BPF_WRITE;
11081 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11082 		} else {
11083 			continue;
11084 		}
11085 
11086 		if (type == BPF_WRITE &&
11087 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
11088 			struct bpf_insn patch[] = {
11089 				*insn,
11090 				BPF_ST_NOSPEC(),
11091 			};
11092 
11093 			cnt = ARRAY_SIZE(patch);
11094 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11095 			if (!new_prog)
11096 				return -ENOMEM;
11097 
11098 			delta    += cnt - 1;
11099 			env->prog = new_prog;
11100 			insn      = new_prog->insnsi + i + delta;
11101 			continue;
11102 		}
11103 
11104 		if (!ctx_access)
11105 			continue;
11106 
11107 		switch (env->insn_aux_data[i + delta].ptr_type) {
11108 		case PTR_TO_CTX:
11109 			if (!ops->convert_ctx_access)
11110 				continue;
11111 			convert_ctx_access = ops->convert_ctx_access;
11112 			break;
11113 		case PTR_TO_SOCKET:
11114 		case PTR_TO_SOCK_COMMON:
11115 			convert_ctx_access = bpf_sock_convert_ctx_access;
11116 			break;
11117 		case PTR_TO_TCP_SOCK:
11118 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11119 			break;
11120 		case PTR_TO_XDP_SOCK:
11121 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11122 			break;
11123 		case PTR_TO_BTF_ID:
11124 			if (type == BPF_READ) {
11125 				insn->code = BPF_LDX | BPF_PROBE_MEM |
11126 					BPF_SIZE((insn)->code);
11127 				env->prog->aux->num_exentries++;
11128 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11129 				verbose(env, "Writes through BTF pointers are not allowed\n");
11130 				return -EINVAL;
11131 			}
11132 			continue;
11133 		default:
11134 			continue;
11135 		}
11136 
11137 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11138 		size = BPF_LDST_BYTES(insn);
11139 
11140 		/* If the read access is a narrower load of the field,
11141 		 * convert to a 4/8-byte load, to minimum program type specific
11142 		 * convert_ctx_access changes. If conversion is successful,
11143 		 * we will apply proper mask to the result.
11144 		 */
11145 		is_narrower_load = size < ctx_field_size;
11146 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11147 		off = insn->off;
11148 		if (is_narrower_load) {
11149 			u8 size_code;
11150 
11151 			if (type == BPF_WRITE) {
11152 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11153 				return -EINVAL;
11154 			}
11155 
11156 			size_code = BPF_H;
11157 			if (ctx_field_size == 4)
11158 				size_code = BPF_W;
11159 			else if (ctx_field_size == 8)
11160 				size_code = BPF_DW;
11161 
11162 			insn->off = off & ~(size_default - 1);
11163 			insn->code = BPF_LDX | BPF_MEM | size_code;
11164 		}
11165 
11166 		target_size = 0;
11167 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11168 					 &target_size);
11169 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11170 		    (ctx_field_size && !target_size)) {
11171 			verbose(env, "bpf verifier is misconfigured\n");
11172 			return -EINVAL;
11173 		}
11174 
11175 		if (is_narrower_load && size < target_size) {
11176 			u8 shift = bpf_ctx_narrow_access_offset(
11177 				off, size, size_default) * 8;
11178 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11179 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11180 				return -EINVAL;
11181 			}
11182 			if (ctx_field_size <= 4) {
11183 				if (shift)
11184 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11185 									insn->dst_reg,
11186 									shift);
11187 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11188 								(1 << size * 8) - 1);
11189 			} else {
11190 				if (shift)
11191 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11192 									insn->dst_reg,
11193 									shift);
11194 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11195 								(1ULL << size * 8) - 1);
11196 			}
11197 		}
11198 
11199 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11200 		if (!new_prog)
11201 			return -ENOMEM;
11202 
11203 		delta += cnt - 1;
11204 
11205 		/* keep walking new program and skip insns we just inserted */
11206 		env->prog = new_prog;
11207 		insn      = new_prog->insnsi + i + delta;
11208 	}
11209 
11210 	return 0;
11211 }
11212 
jit_subprogs(struct bpf_verifier_env * env)11213 static int jit_subprogs(struct bpf_verifier_env *env)
11214 {
11215 	struct bpf_prog *prog = env->prog, **func, *tmp;
11216 	int i, j, subprog_start, subprog_end = 0, len, subprog;
11217 	struct bpf_map *map_ptr;
11218 	struct bpf_insn *insn;
11219 	void *old_bpf_func;
11220 	int err, num_exentries;
11221 
11222 	if (env->subprog_cnt <= 1)
11223 		return 0;
11224 
11225 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11226 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11227 		    insn->src_reg != BPF_PSEUDO_CALL)
11228 			continue;
11229 		/* Upon error here we cannot fall back to interpreter but
11230 		 * need a hard reject of the program. Thus -EFAULT is
11231 		 * propagated in any case.
11232 		 */
11233 		subprog = find_subprog(env, i + insn->imm + 1);
11234 		if (subprog < 0) {
11235 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11236 				  i + insn->imm + 1);
11237 			return -EFAULT;
11238 		}
11239 		/* temporarily remember subprog id inside insn instead of
11240 		 * aux_data, since next loop will split up all insns into funcs
11241 		 */
11242 		insn->off = subprog;
11243 		/* remember original imm in case JIT fails and fallback
11244 		 * to interpreter will be needed
11245 		 */
11246 		env->insn_aux_data[i].call_imm = insn->imm;
11247 		/* point imm to __bpf_call_base+1 from JITs point of view */
11248 		insn->imm = 1;
11249 	}
11250 
11251 	err = bpf_prog_alloc_jited_linfo(prog);
11252 	if (err)
11253 		goto out_undo_insn;
11254 
11255 	err = -ENOMEM;
11256 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11257 	if (!func)
11258 		goto out_undo_insn;
11259 
11260 	for (i = 0; i < env->subprog_cnt; i++) {
11261 		subprog_start = subprog_end;
11262 		subprog_end = env->subprog_info[i + 1].start;
11263 
11264 		len = subprog_end - subprog_start;
11265 		/* BPF_PROG_RUN doesn't call subprogs directly,
11266 		 * hence main prog stats include the runtime of subprogs.
11267 		 * subprogs don't have IDs and not reachable via prog_get_next_id
11268 		 * func[i]->aux->stats will never be accessed and stays NULL
11269 		 */
11270 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11271 		if (!func[i])
11272 			goto out_free;
11273 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11274 		       len * sizeof(struct bpf_insn));
11275 		func[i]->type = prog->type;
11276 		func[i]->len = len;
11277 		if (bpf_prog_calc_tag(func[i]))
11278 			goto out_free;
11279 		func[i]->is_func = 1;
11280 		func[i]->aux->func_idx = i;
11281 		/* Below members will be freed only at prog->aux */
11282 		func[i]->aux->btf = prog->aux->btf;
11283 		func[i]->aux->func_info = prog->aux->func_info;
11284 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11285 		func[i]->aux->poke_tab = prog->aux->poke_tab;
11286 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
11287 
11288 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
11289 			struct bpf_jit_poke_descriptor *poke;
11290 
11291 			poke = &prog->aux->poke_tab[j];
11292 			if (poke->insn_idx < subprog_end &&
11293 			    poke->insn_idx >= subprog_start)
11294 				poke->aux = func[i]->aux;
11295 		}
11296 
11297 		func[i]->aux->name[0] = 'F';
11298 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11299 		func[i]->jit_requested = 1;
11300 		func[i]->aux->linfo = prog->aux->linfo;
11301 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11302 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11303 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11304 		num_exentries = 0;
11305 		insn = func[i]->insnsi;
11306 		for (j = 0; j < func[i]->len; j++, insn++) {
11307 			if (BPF_CLASS(insn->code) == BPF_LDX &&
11308 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
11309 				num_exentries++;
11310 		}
11311 		func[i]->aux->num_exentries = num_exentries;
11312 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11313 		func[i] = bpf_int_jit_compile(func[i]);
11314 		if (!func[i]->jited) {
11315 			err = -ENOTSUPP;
11316 			goto out_free;
11317 		}
11318 		cond_resched();
11319 	}
11320 
11321 	/* at this point all bpf functions were successfully JITed
11322 	 * now populate all bpf_calls with correct addresses and
11323 	 * run last pass of JIT
11324 	 */
11325 	for (i = 0; i < env->subprog_cnt; i++) {
11326 		insn = func[i]->insnsi;
11327 		for (j = 0; j < func[i]->len; j++, insn++) {
11328 			if (insn->code != (BPF_JMP | BPF_CALL) ||
11329 			    insn->src_reg != BPF_PSEUDO_CALL)
11330 				continue;
11331 			subprog = insn->off;
11332 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11333 				    __bpf_call_base;
11334 		}
11335 
11336 		/* we use the aux data to keep a list of the start addresses
11337 		 * of the JITed images for each function in the program
11338 		 *
11339 		 * for some architectures, such as powerpc64, the imm field
11340 		 * might not be large enough to hold the offset of the start
11341 		 * address of the callee's JITed image from __bpf_call_base
11342 		 *
11343 		 * in such cases, we can lookup the start address of a callee
11344 		 * by using its subprog id, available from the off field of
11345 		 * the call instruction, as an index for this list
11346 		 */
11347 		func[i]->aux->func = func;
11348 		func[i]->aux->func_cnt = env->subprog_cnt;
11349 	}
11350 	for (i = 0; i < env->subprog_cnt; i++) {
11351 		old_bpf_func = func[i]->bpf_func;
11352 		tmp = bpf_int_jit_compile(func[i]);
11353 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11354 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11355 			err = -ENOTSUPP;
11356 			goto out_free;
11357 		}
11358 		cond_resched();
11359 	}
11360 
11361 	/* finally lock prog and jit images for all functions and
11362 	 * populate kallsysm
11363 	 */
11364 	for (i = 0; i < env->subprog_cnt; i++) {
11365 		bpf_prog_lock_ro(func[i]);
11366 		bpf_prog_kallsyms_add(func[i]);
11367 	}
11368 
11369 	/* Last step: make now unused interpreter insns from main
11370 	 * prog consistent for later dump requests, so they can
11371 	 * later look the same as if they were interpreted only.
11372 	 */
11373 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11374 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11375 		    insn->src_reg != BPF_PSEUDO_CALL)
11376 			continue;
11377 		insn->off = env->insn_aux_data[i].call_imm;
11378 		subprog = find_subprog(env, i + insn->off + 1);
11379 		insn->imm = subprog;
11380 	}
11381 
11382 	prog->jited = 1;
11383 	prog->bpf_func = func[0]->bpf_func;
11384 	prog->aux->func = func;
11385 	prog->aux->func_cnt = env->subprog_cnt;
11386 	bpf_prog_free_unused_jited_linfo(prog);
11387 	return 0;
11388 out_free:
11389 	/* We failed JIT'ing, so at this point we need to unregister poke
11390 	 * descriptors from subprogs, so that kernel is not attempting to
11391 	 * patch it anymore as we're freeing the subprog JIT memory.
11392 	 */
11393 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11394 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11395 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11396 	}
11397 	/* At this point we're guaranteed that poke descriptors are not
11398 	 * live anymore. We can just unlink its descriptor table as it's
11399 	 * released with the main prog.
11400 	 */
11401 	for (i = 0; i < env->subprog_cnt; i++) {
11402 		if (!func[i])
11403 			continue;
11404 		func[i]->aux->poke_tab = NULL;
11405 		bpf_jit_free(func[i]);
11406 	}
11407 	kfree(func);
11408 out_undo_insn:
11409 	/* cleanup main prog to be interpreted */
11410 	prog->jit_requested = 0;
11411 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11412 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11413 		    insn->src_reg != BPF_PSEUDO_CALL)
11414 			continue;
11415 		insn->off = 0;
11416 		insn->imm = env->insn_aux_data[i].call_imm;
11417 	}
11418 	bpf_prog_free_jited_linfo(prog);
11419 	return err;
11420 }
11421 
fixup_call_args(struct bpf_verifier_env * env)11422 static int fixup_call_args(struct bpf_verifier_env *env)
11423 {
11424 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11425 	struct bpf_prog *prog = env->prog;
11426 	struct bpf_insn *insn = prog->insnsi;
11427 	int i, depth;
11428 #endif
11429 	int err = 0;
11430 
11431 	if (env->prog->jit_requested &&
11432 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
11433 		err = jit_subprogs(env);
11434 		if (err == 0)
11435 			return 0;
11436 		if (err == -EFAULT)
11437 			return err;
11438 	}
11439 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11440 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11441 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
11442 		 * have to be rejected, since interpreter doesn't support them yet.
11443 		 */
11444 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11445 		return -EINVAL;
11446 	}
11447 	for (i = 0; i < prog->len; i++, insn++) {
11448 		if (insn->code != (BPF_JMP | BPF_CALL) ||
11449 		    insn->src_reg != BPF_PSEUDO_CALL)
11450 			continue;
11451 		depth = get_callee_stack_depth(env, insn, i);
11452 		if (depth < 0)
11453 			return depth;
11454 		bpf_patch_call_args(insn, depth);
11455 	}
11456 	err = 0;
11457 #endif
11458 	return err;
11459 }
11460 
11461 /* fixup insn->imm field of bpf_call instructions
11462  * and inline eligible helpers as explicit sequence of BPF instructions
11463  *
11464  * this function is called after eBPF program passed verification
11465  */
fixup_bpf_calls(struct bpf_verifier_env * env)11466 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11467 {
11468 	struct bpf_prog *prog = env->prog;
11469 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
11470 	struct bpf_insn *insn = prog->insnsi;
11471 	const struct bpf_func_proto *fn;
11472 	const int insn_cnt = prog->len;
11473 	const struct bpf_map_ops *ops;
11474 	struct bpf_insn_aux_data *aux;
11475 	struct bpf_insn insn_buf[16];
11476 	struct bpf_prog *new_prog;
11477 	struct bpf_map *map_ptr;
11478 	int i, ret, cnt, delta = 0;
11479 
11480 	for (i = 0; i < insn_cnt; i++, insn++) {
11481 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11482 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11483 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11484 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11485 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11486 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11487 			struct bpf_insn *patchlet;
11488 			struct bpf_insn chk_and_div[] = {
11489 				/* [R,W]x div 0 -> 0 */
11490 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11491 					     BPF_JNE | BPF_K, insn->src_reg,
11492 					     0, 2, 0),
11493 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11494 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11495 				*insn,
11496 			};
11497 			struct bpf_insn chk_and_mod[] = {
11498 				/* [R,W]x mod 0 -> [R,W]x */
11499 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11500 					     BPF_JEQ | BPF_K, insn->src_reg,
11501 					     0, 1 + (is64 ? 0 : 1), 0),
11502 				*insn,
11503 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11504 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11505 			};
11506 
11507 			patchlet = isdiv ? chk_and_div : chk_and_mod;
11508 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11509 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11510 
11511 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11512 			if (!new_prog)
11513 				return -ENOMEM;
11514 
11515 			delta    += cnt - 1;
11516 			env->prog = prog = new_prog;
11517 			insn      = new_prog->insnsi + i + delta;
11518 			continue;
11519 		}
11520 
11521 		if (BPF_CLASS(insn->code) == BPF_LD &&
11522 		    (BPF_MODE(insn->code) == BPF_ABS ||
11523 		     BPF_MODE(insn->code) == BPF_IND)) {
11524 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
11525 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11526 				verbose(env, "bpf verifier is misconfigured\n");
11527 				return -EINVAL;
11528 			}
11529 
11530 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11531 			if (!new_prog)
11532 				return -ENOMEM;
11533 
11534 			delta    += cnt - 1;
11535 			env->prog = prog = new_prog;
11536 			insn      = new_prog->insnsi + i + delta;
11537 			continue;
11538 		}
11539 
11540 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11541 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11542 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11543 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11544 			struct bpf_insn insn_buf[16];
11545 			struct bpf_insn *patch = &insn_buf[0];
11546 			bool issrc, isneg, isimm;
11547 			u32 off_reg;
11548 
11549 			aux = &env->insn_aux_data[i + delta];
11550 			if (!aux->alu_state ||
11551 			    aux->alu_state == BPF_ALU_NON_POINTER)
11552 				continue;
11553 
11554 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11555 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11556 				BPF_ALU_SANITIZE_SRC;
11557 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11558 
11559 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
11560 			if (isimm) {
11561 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11562 			} else {
11563 				if (isneg)
11564 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11565 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11566 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11567 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11568 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11569 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11570 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11571 			}
11572 			if (!issrc)
11573 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11574 			insn->src_reg = BPF_REG_AX;
11575 			if (isneg)
11576 				insn->code = insn->code == code_add ?
11577 					     code_sub : code_add;
11578 			*patch++ = *insn;
11579 			if (issrc && isneg && !isimm)
11580 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11581 			cnt = patch - insn_buf;
11582 
11583 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11584 			if (!new_prog)
11585 				return -ENOMEM;
11586 
11587 			delta    += cnt - 1;
11588 			env->prog = prog = new_prog;
11589 			insn      = new_prog->insnsi + i + delta;
11590 			continue;
11591 		}
11592 
11593 		if (insn->code != (BPF_JMP | BPF_CALL))
11594 			continue;
11595 		if (insn->src_reg == BPF_PSEUDO_CALL)
11596 			continue;
11597 
11598 		if (insn->imm == BPF_FUNC_get_route_realm)
11599 			prog->dst_needed = 1;
11600 		if (insn->imm == BPF_FUNC_get_prandom_u32)
11601 			bpf_user_rnd_init_once();
11602 		if (insn->imm == BPF_FUNC_override_return)
11603 			prog->kprobe_override = 1;
11604 		if (insn->imm == BPF_FUNC_tail_call) {
11605 			/* If we tail call into other programs, we
11606 			 * cannot make any assumptions since they can
11607 			 * be replaced dynamically during runtime in
11608 			 * the program array.
11609 			 */
11610 			prog->cb_access = 1;
11611 			if (!allow_tail_call_in_subprogs(env))
11612 				prog->aux->stack_depth = MAX_BPF_STACK;
11613 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11614 
11615 			/* mark bpf_tail_call as different opcode to avoid
11616 			 * conditional branch in the interpeter for every normal
11617 			 * call and to prevent accidental JITing by JIT compiler
11618 			 * that doesn't support bpf_tail_call yet
11619 			 */
11620 			insn->imm = 0;
11621 			insn->code = BPF_JMP | BPF_TAIL_CALL;
11622 
11623 			aux = &env->insn_aux_data[i + delta];
11624 			if (env->bpf_capable && !expect_blinding &&
11625 			    prog->jit_requested &&
11626 			    !bpf_map_key_poisoned(aux) &&
11627 			    !bpf_map_ptr_poisoned(aux) &&
11628 			    !bpf_map_ptr_unpriv(aux)) {
11629 				struct bpf_jit_poke_descriptor desc = {
11630 					.reason = BPF_POKE_REASON_TAIL_CALL,
11631 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11632 					.tail_call.key = bpf_map_key_immediate(aux),
11633 					.insn_idx = i + delta,
11634 				};
11635 
11636 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
11637 				if (ret < 0) {
11638 					verbose(env, "adding tail call poke descriptor failed\n");
11639 					return ret;
11640 				}
11641 
11642 				insn->imm = ret + 1;
11643 				continue;
11644 			}
11645 
11646 			if (!bpf_map_ptr_unpriv(aux))
11647 				continue;
11648 
11649 			/* instead of changing every JIT dealing with tail_call
11650 			 * emit two extra insns:
11651 			 * if (index >= max_entries) goto out;
11652 			 * index &= array->index_mask;
11653 			 * to avoid out-of-bounds cpu speculation
11654 			 */
11655 			if (bpf_map_ptr_poisoned(aux)) {
11656 				verbose(env, "tail_call abusing map_ptr\n");
11657 				return -EINVAL;
11658 			}
11659 
11660 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11661 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11662 						  map_ptr->max_entries, 2);
11663 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11664 						    container_of(map_ptr,
11665 								 struct bpf_array,
11666 								 map)->index_mask);
11667 			insn_buf[2] = *insn;
11668 			cnt = 3;
11669 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11670 			if (!new_prog)
11671 				return -ENOMEM;
11672 
11673 			delta    += cnt - 1;
11674 			env->prog = prog = new_prog;
11675 			insn      = new_prog->insnsi + i + delta;
11676 			continue;
11677 		}
11678 
11679 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11680 		 * and other inlining handlers are currently limited to 64 bit
11681 		 * only.
11682 		 */
11683 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11684 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
11685 		     insn->imm == BPF_FUNC_map_update_elem ||
11686 		     insn->imm == BPF_FUNC_map_delete_elem ||
11687 		     insn->imm == BPF_FUNC_map_push_elem   ||
11688 		     insn->imm == BPF_FUNC_map_pop_elem    ||
11689 		     insn->imm == BPF_FUNC_map_peek_elem)) {
11690 			aux = &env->insn_aux_data[i + delta];
11691 			if (bpf_map_ptr_poisoned(aux))
11692 				goto patch_call_imm;
11693 
11694 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11695 			ops = map_ptr->ops;
11696 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
11697 			    ops->map_gen_lookup) {
11698 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11699 				if (cnt == -EOPNOTSUPP)
11700 					goto patch_map_ops_generic;
11701 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11702 					verbose(env, "bpf verifier is misconfigured\n");
11703 					return -EINVAL;
11704 				}
11705 
11706 				new_prog = bpf_patch_insn_data(env, i + delta,
11707 							       insn_buf, 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 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11718 				     (void *(*)(struct bpf_map *map, void *key))NULL));
11719 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11720 				     (int (*)(struct bpf_map *map, void *key))NULL));
11721 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11722 				     (int (*)(struct bpf_map *map, void *key, void *value,
11723 					      u64 flags))NULL));
11724 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11725 				     (int (*)(struct bpf_map *map, void *value,
11726 					      u64 flags))NULL));
11727 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11728 				     (int (*)(struct bpf_map *map, void *value))NULL));
11729 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11730 				     (int (*)(struct bpf_map *map, void *value))NULL));
11731 patch_map_ops_generic:
11732 			switch (insn->imm) {
11733 			case BPF_FUNC_map_lookup_elem:
11734 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11735 					    __bpf_call_base;
11736 				continue;
11737 			case BPF_FUNC_map_update_elem:
11738 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11739 					    __bpf_call_base;
11740 				continue;
11741 			case BPF_FUNC_map_delete_elem:
11742 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11743 					    __bpf_call_base;
11744 				continue;
11745 			case BPF_FUNC_map_push_elem:
11746 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11747 					    __bpf_call_base;
11748 				continue;
11749 			case BPF_FUNC_map_pop_elem:
11750 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11751 					    __bpf_call_base;
11752 				continue;
11753 			case BPF_FUNC_map_peek_elem:
11754 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11755 					    __bpf_call_base;
11756 				continue;
11757 			}
11758 
11759 			goto patch_call_imm;
11760 		}
11761 
11762 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
11763 		    insn->imm == BPF_FUNC_jiffies64) {
11764 			struct bpf_insn ld_jiffies_addr[2] = {
11765 				BPF_LD_IMM64(BPF_REG_0,
11766 					     (unsigned long)&jiffies),
11767 			};
11768 
11769 			insn_buf[0] = ld_jiffies_addr[0];
11770 			insn_buf[1] = ld_jiffies_addr[1];
11771 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11772 						  BPF_REG_0, 0);
11773 			cnt = 3;
11774 
11775 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11776 						       cnt);
11777 			if (!new_prog)
11778 				return -ENOMEM;
11779 
11780 			delta    += cnt - 1;
11781 			env->prog = prog = new_prog;
11782 			insn      = new_prog->insnsi + i + delta;
11783 			continue;
11784 		}
11785 
11786 patch_call_imm:
11787 		fn = env->ops->get_func_proto(insn->imm, env->prog);
11788 		/* all functions that have prototype and verifier allowed
11789 		 * programs to call them, must be real in-kernel functions
11790 		 */
11791 		if (!fn->func) {
11792 			verbose(env,
11793 				"kernel subsystem misconfigured func %s#%d\n",
11794 				func_id_name(insn->imm), insn->imm);
11795 			return -EFAULT;
11796 		}
11797 		insn->imm = fn->func - __bpf_call_base;
11798 	}
11799 
11800 	/* Since poke tab is now finalized, publish aux to tracker. */
11801 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
11802 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
11803 		if (!map_ptr->ops->map_poke_track ||
11804 		    !map_ptr->ops->map_poke_untrack ||
11805 		    !map_ptr->ops->map_poke_run) {
11806 			verbose(env, "bpf verifier is misconfigured\n");
11807 			return -EINVAL;
11808 		}
11809 
11810 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11811 		if (ret < 0) {
11812 			verbose(env, "tracking tail call prog failed\n");
11813 			return ret;
11814 		}
11815 	}
11816 
11817 	return 0;
11818 }
11819 
free_states(struct bpf_verifier_env * env)11820 static void free_states(struct bpf_verifier_env *env)
11821 {
11822 	struct bpf_verifier_state_list *sl, *sln;
11823 	int i;
11824 
11825 	sl = env->free_list;
11826 	while (sl) {
11827 		sln = sl->next;
11828 		free_verifier_state(&sl->state, false);
11829 		kfree(sl);
11830 		sl = sln;
11831 	}
11832 	env->free_list = NULL;
11833 
11834 	if (!env->explored_states)
11835 		return;
11836 
11837 	for (i = 0; i < state_htab_size(env); i++) {
11838 		sl = env->explored_states[i];
11839 
11840 		while (sl) {
11841 			sln = sl->next;
11842 			free_verifier_state(&sl->state, false);
11843 			kfree(sl);
11844 			sl = sln;
11845 		}
11846 		env->explored_states[i] = NULL;
11847 	}
11848 }
11849 
do_check_common(struct bpf_verifier_env * env,int subprog)11850 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11851 {
11852 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11853 	struct bpf_verifier_state *state;
11854 	struct bpf_reg_state *regs;
11855 	int ret, i;
11856 
11857 	env->prev_linfo = NULL;
11858 	env->pass_cnt++;
11859 
11860 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11861 	if (!state)
11862 		return -ENOMEM;
11863 	state->curframe = 0;
11864 	state->speculative = false;
11865 	state->branches = 1;
11866 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11867 	if (!state->frame[0]) {
11868 		kfree(state);
11869 		return -ENOMEM;
11870 	}
11871 	env->cur_state = state;
11872 	init_func_state(env, state->frame[0],
11873 			BPF_MAIN_FUNC /* callsite */,
11874 			0 /* frameno */,
11875 			subprog);
11876 
11877 	regs = state->frame[state->curframe]->regs;
11878 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11879 		ret = btf_prepare_func_args(env, subprog, regs);
11880 		if (ret)
11881 			goto out;
11882 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11883 			if (regs[i].type == PTR_TO_CTX)
11884 				mark_reg_known_zero(env, regs, i);
11885 			else if (regs[i].type == SCALAR_VALUE)
11886 				mark_reg_unknown(env, regs, i);
11887 		}
11888 	} else {
11889 		/* 1st arg to a function */
11890 		regs[BPF_REG_1].type = PTR_TO_CTX;
11891 		mark_reg_known_zero(env, regs, BPF_REG_1);
11892 		ret = btf_check_func_arg_match(env, subprog, regs);
11893 		if (ret == -EFAULT)
11894 			/* unlikely verifier bug. abort.
11895 			 * ret == 0 and ret < 0 are sadly acceptable for
11896 			 * main() function due to backward compatibility.
11897 			 * Like socket filter program may be written as:
11898 			 * int bpf_prog(struct pt_regs *ctx)
11899 			 * and never dereference that ctx in the program.
11900 			 * 'struct pt_regs' is a type mismatch for socket
11901 			 * filter that should be using 'struct __sk_buff'.
11902 			 */
11903 			goto out;
11904 	}
11905 
11906 	ret = do_check(env);
11907 out:
11908 	/* check for NULL is necessary, since cur_state can be freed inside
11909 	 * do_check() under memory pressure.
11910 	 */
11911 	if (env->cur_state) {
11912 		free_verifier_state(env->cur_state, true);
11913 		env->cur_state = NULL;
11914 	}
11915 	while (!pop_stack(env, NULL, NULL, false));
11916 	if (!ret && pop_log)
11917 		bpf_vlog_reset(&env->log, 0);
11918 	free_states(env);
11919 	return ret;
11920 }
11921 
11922 /* Verify all global functions in a BPF program one by one based on their BTF.
11923  * All global functions must pass verification. Otherwise the whole program is rejected.
11924  * Consider:
11925  * int bar(int);
11926  * int foo(int f)
11927  * {
11928  *    return bar(f);
11929  * }
11930  * int bar(int b)
11931  * {
11932  *    ...
11933  * }
11934  * foo() will be verified first for R1=any_scalar_value. During verification it
11935  * will be assumed that bar() already verified successfully and call to bar()
11936  * from foo() will be checked for type match only. Later bar() will be verified
11937  * independently to check that it's safe for R1=any_scalar_value.
11938  */
do_check_subprogs(struct bpf_verifier_env * env)11939 static int do_check_subprogs(struct bpf_verifier_env *env)
11940 {
11941 	struct bpf_prog_aux *aux = env->prog->aux;
11942 	int i, ret;
11943 
11944 	if (!aux->func_info)
11945 		return 0;
11946 
11947 	for (i = 1; i < env->subprog_cnt; i++) {
11948 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11949 			continue;
11950 		env->insn_idx = env->subprog_info[i].start;
11951 		WARN_ON_ONCE(env->insn_idx == 0);
11952 		ret = do_check_common(env, i);
11953 		if (ret) {
11954 			return ret;
11955 		} else if (env->log.level & BPF_LOG_LEVEL) {
11956 			verbose(env,
11957 				"Func#%d is safe for any args that match its prototype\n",
11958 				i);
11959 		}
11960 	}
11961 	return 0;
11962 }
11963 
do_check_main(struct bpf_verifier_env * env)11964 static int do_check_main(struct bpf_verifier_env *env)
11965 {
11966 	int ret;
11967 
11968 	env->insn_idx = 0;
11969 	ret = do_check_common(env, 0);
11970 	if (!ret)
11971 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11972 	return ret;
11973 }
11974 
11975 
print_verification_stats(struct bpf_verifier_env * env)11976 static void print_verification_stats(struct bpf_verifier_env *env)
11977 {
11978 	int i;
11979 
11980 	if (env->log.level & BPF_LOG_STATS) {
11981 		verbose(env, "verification time %lld usec\n",
11982 			div_u64(env->verification_time, 1000));
11983 		verbose(env, "stack depth ");
11984 		for (i = 0; i < env->subprog_cnt; i++) {
11985 			u32 depth = env->subprog_info[i].stack_depth;
11986 
11987 			verbose(env, "%d", depth);
11988 			if (i + 1 < env->subprog_cnt)
11989 				verbose(env, "+");
11990 		}
11991 		verbose(env, "\n");
11992 	}
11993 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11994 		"total_states %d peak_states %d mark_read %d\n",
11995 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11996 		env->max_states_per_insn, env->total_states,
11997 		env->peak_states, env->longest_mark_read_walk);
11998 }
11999 
check_struct_ops_btf_id(struct bpf_verifier_env * env)12000 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12001 {
12002 	const struct btf_type *t, *func_proto;
12003 	const struct bpf_struct_ops *st_ops;
12004 	const struct btf_member *member;
12005 	struct bpf_prog *prog = env->prog;
12006 	u32 btf_id, member_idx;
12007 	const char *mname;
12008 
12009 	if (!prog->gpl_compatible) {
12010 		verbose(env, "struct ops programs must have a GPL compatible license\n");
12011 		return -EINVAL;
12012 	}
12013 
12014 	btf_id = prog->aux->attach_btf_id;
12015 	st_ops = bpf_struct_ops_find(btf_id);
12016 	if (!st_ops) {
12017 		verbose(env, "attach_btf_id %u is not a supported struct\n",
12018 			btf_id);
12019 		return -ENOTSUPP;
12020 	}
12021 
12022 	t = st_ops->type;
12023 	member_idx = prog->expected_attach_type;
12024 	if (member_idx >= btf_type_vlen(t)) {
12025 		verbose(env, "attach to invalid member idx %u of struct %s\n",
12026 			member_idx, st_ops->name);
12027 		return -EINVAL;
12028 	}
12029 
12030 	member = &btf_type_member(t)[member_idx];
12031 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12032 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12033 					       NULL);
12034 	if (!func_proto) {
12035 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12036 			mname, member_idx, st_ops->name);
12037 		return -EINVAL;
12038 	}
12039 
12040 	if (st_ops->check_member) {
12041 		int err = st_ops->check_member(t, member);
12042 
12043 		if (err) {
12044 			verbose(env, "attach to unsupported member %s of struct %s\n",
12045 				mname, st_ops->name);
12046 			return err;
12047 		}
12048 	}
12049 
12050 	prog->aux->attach_func_proto = func_proto;
12051 	prog->aux->attach_func_name = mname;
12052 	env->ops = st_ops->verifier_ops;
12053 
12054 	return 0;
12055 }
12056 #define SECURITY_PREFIX "security_"
12057 
check_attach_modify_return(unsigned long addr,const char * func_name)12058 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12059 {
12060 	if (within_error_injection_list(addr) ||
12061 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12062 		return 0;
12063 
12064 	return -EINVAL;
12065 }
12066 
12067 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12068 BTF_SET_START(btf_sleepable_lsm_hooks)
12069 #ifdef CONFIG_BPF_LSM
BTF_ID(func,bpf_lsm_bprm_committed_creds)12070 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12071 #else
12072 BTF_ID_UNUSED
12073 #endif
12074 BTF_SET_END(btf_sleepable_lsm_hooks)
12075 
12076 static int check_sleepable_lsm_hook(u32 btf_id)
12077 {
12078 	return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12079 }
12080 
12081 /* list of non-sleepable functions that are otherwise on
12082  * ALLOW_ERROR_INJECTION list
12083  */
12084 BTF_SET_START(btf_non_sleepable_error_inject)
12085 /* Three functions below can be called from sleepable and non-sleepable context.
12086  * Assume non-sleepable from bpf safety point of view.
12087  */
BTF_ID(func,__add_to_page_cache_locked)12088 BTF_ID(func, __add_to_page_cache_locked)
12089 BTF_ID(func, should_fail_alloc_page)
12090 BTF_ID(func, should_failslab)
12091 BTF_SET_END(btf_non_sleepable_error_inject)
12092 
12093 static int check_non_sleepable_error_inject(u32 btf_id)
12094 {
12095 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12096 }
12097 
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)12098 int bpf_check_attach_target(struct bpf_verifier_log *log,
12099 			    const struct bpf_prog *prog,
12100 			    const struct bpf_prog *tgt_prog,
12101 			    u32 btf_id,
12102 			    struct bpf_attach_target_info *tgt_info)
12103 {
12104 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12105 	const char prefix[] = "btf_trace_";
12106 	int ret = 0, subprog = -1, i;
12107 	const struct btf_type *t;
12108 	bool conservative = true;
12109 	const char *tname;
12110 	struct btf *btf;
12111 	long addr = 0;
12112 
12113 	if (!btf_id) {
12114 		bpf_log(log, "Tracing programs must provide btf_id\n");
12115 		return -EINVAL;
12116 	}
12117 	btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12118 	if (!btf) {
12119 		bpf_log(log,
12120 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12121 		return -EINVAL;
12122 	}
12123 	t = btf_type_by_id(btf, btf_id);
12124 	if (!t) {
12125 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12126 		return -EINVAL;
12127 	}
12128 	tname = btf_name_by_offset(btf, t->name_off);
12129 	if (!tname) {
12130 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12131 		return -EINVAL;
12132 	}
12133 	if (tgt_prog) {
12134 		struct bpf_prog_aux *aux = tgt_prog->aux;
12135 
12136 		for (i = 0; i < aux->func_info_cnt; i++)
12137 			if (aux->func_info[i].type_id == btf_id) {
12138 				subprog = i;
12139 				break;
12140 			}
12141 		if (subprog == -1) {
12142 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
12143 			return -EINVAL;
12144 		}
12145 		conservative = aux->func_info_aux[subprog].unreliable;
12146 		if (prog_extension) {
12147 			if (conservative) {
12148 				bpf_log(log,
12149 					"Cannot replace static functions\n");
12150 				return -EINVAL;
12151 			}
12152 			if (!prog->jit_requested) {
12153 				bpf_log(log,
12154 					"Extension programs should be JITed\n");
12155 				return -EINVAL;
12156 			}
12157 		}
12158 		if (!tgt_prog->jited) {
12159 			bpf_log(log, "Can attach to only JITed progs\n");
12160 			return -EINVAL;
12161 		}
12162 		if (tgt_prog->type == prog->type) {
12163 			/* Cannot fentry/fexit another fentry/fexit program.
12164 			 * Cannot attach program extension to another extension.
12165 			 * It's ok to attach fentry/fexit to extension program.
12166 			 */
12167 			bpf_log(log, "Cannot recursively attach\n");
12168 			return -EINVAL;
12169 		}
12170 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12171 		    prog_extension &&
12172 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12173 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12174 			/* Program extensions can extend all program types
12175 			 * except fentry/fexit. The reason is the following.
12176 			 * The fentry/fexit programs are used for performance
12177 			 * analysis, stats and can be attached to any program
12178 			 * type except themselves. When extension program is
12179 			 * replacing XDP function it is necessary to allow
12180 			 * performance analysis of all functions. Both original
12181 			 * XDP program and its program extension. Hence
12182 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12183 			 * allowed. If extending of fentry/fexit was allowed it
12184 			 * would be possible to create long call chain
12185 			 * fentry->extension->fentry->extension beyond
12186 			 * reasonable stack size. Hence extending fentry is not
12187 			 * allowed.
12188 			 */
12189 			bpf_log(log, "Cannot extend fentry/fexit\n");
12190 			return -EINVAL;
12191 		}
12192 	} else {
12193 		if (prog_extension) {
12194 			bpf_log(log, "Cannot replace kernel functions\n");
12195 			return -EINVAL;
12196 		}
12197 	}
12198 
12199 	switch (prog->expected_attach_type) {
12200 	case BPF_TRACE_RAW_TP:
12201 		if (tgt_prog) {
12202 			bpf_log(log,
12203 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12204 			return -EINVAL;
12205 		}
12206 		if (!btf_type_is_typedef(t)) {
12207 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
12208 				btf_id);
12209 			return -EINVAL;
12210 		}
12211 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12212 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12213 				btf_id, tname);
12214 			return -EINVAL;
12215 		}
12216 		tname += sizeof(prefix) - 1;
12217 		t = btf_type_by_id(btf, t->type);
12218 		if (!btf_type_is_ptr(t))
12219 			/* should never happen in valid vmlinux build */
12220 			return -EINVAL;
12221 		t = btf_type_by_id(btf, t->type);
12222 		if (!btf_type_is_func_proto(t))
12223 			/* should never happen in valid vmlinux build */
12224 			return -EINVAL;
12225 
12226 		break;
12227 	case BPF_TRACE_ITER:
12228 		if (!btf_type_is_func(t)) {
12229 			bpf_log(log, "attach_btf_id %u is not a function\n",
12230 				btf_id);
12231 			return -EINVAL;
12232 		}
12233 		t = btf_type_by_id(btf, t->type);
12234 		if (!btf_type_is_func_proto(t))
12235 			return -EINVAL;
12236 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12237 		if (ret)
12238 			return ret;
12239 		break;
12240 	default:
12241 		if (!prog_extension)
12242 			return -EINVAL;
12243 		fallthrough;
12244 	case BPF_MODIFY_RETURN:
12245 	case BPF_LSM_MAC:
12246 	case BPF_TRACE_FENTRY:
12247 	case BPF_TRACE_FEXIT:
12248 		if (!btf_type_is_func(t)) {
12249 			bpf_log(log, "attach_btf_id %u is not a function\n",
12250 				btf_id);
12251 			return -EINVAL;
12252 		}
12253 		if (prog_extension &&
12254 		    btf_check_type_match(log, prog, btf, t))
12255 			return -EINVAL;
12256 		t = btf_type_by_id(btf, t->type);
12257 		if (!btf_type_is_func_proto(t))
12258 			return -EINVAL;
12259 
12260 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12261 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12262 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12263 			return -EINVAL;
12264 
12265 		if (tgt_prog && conservative)
12266 			t = NULL;
12267 
12268 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12269 		if (ret < 0)
12270 			return ret;
12271 
12272 		if (tgt_prog) {
12273 			if (subprog == 0)
12274 				addr = (long) tgt_prog->bpf_func;
12275 			else
12276 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12277 		} else {
12278 			addr = kallsyms_lookup_name(tname);
12279 			if (!addr) {
12280 				bpf_log(log,
12281 					"The address of function %s cannot be found\n",
12282 					tname);
12283 				return -ENOENT;
12284 			}
12285 		}
12286 
12287 		if (prog->aux->sleepable) {
12288 			ret = -EINVAL;
12289 			switch (prog->type) {
12290 			case BPF_PROG_TYPE_TRACING:
12291 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
12292 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12293 				 */
12294 				if (!check_non_sleepable_error_inject(btf_id) &&
12295 				    within_error_injection_list(addr))
12296 					ret = 0;
12297 				break;
12298 			case BPF_PROG_TYPE_LSM:
12299 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
12300 				 * Only some of them are sleepable.
12301 				 */
12302 				if (check_sleepable_lsm_hook(btf_id))
12303 					ret = 0;
12304 				break;
12305 			default:
12306 				break;
12307 			}
12308 			if (ret) {
12309 				bpf_log(log, "%s is not sleepable\n", tname);
12310 				return ret;
12311 			}
12312 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12313 			if (tgt_prog) {
12314 				bpf_log(log, "can't modify return codes of BPF programs\n");
12315 				return -EINVAL;
12316 			}
12317 			ret = check_attach_modify_return(addr, tname);
12318 			if (ret) {
12319 				bpf_log(log, "%s() is not modifiable\n", tname);
12320 				return ret;
12321 			}
12322 		}
12323 
12324 		break;
12325 	}
12326 	tgt_info->tgt_addr = addr;
12327 	tgt_info->tgt_name = tname;
12328 	tgt_info->tgt_type = t;
12329 	return 0;
12330 }
12331 
check_attach_btf_id(struct bpf_verifier_env * env)12332 static int check_attach_btf_id(struct bpf_verifier_env *env)
12333 {
12334 	struct bpf_prog *prog = env->prog;
12335 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12336 	struct bpf_attach_target_info tgt_info = {};
12337 	u32 btf_id = prog->aux->attach_btf_id;
12338 	struct bpf_trampoline *tr;
12339 	int ret;
12340 	u64 key;
12341 
12342 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12343 	    prog->type != BPF_PROG_TYPE_LSM) {
12344 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12345 		return -EINVAL;
12346 	}
12347 
12348 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12349 		return check_struct_ops_btf_id(env);
12350 
12351 	if (prog->type != BPF_PROG_TYPE_TRACING &&
12352 	    prog->type != BPF_PROG_TYPE_LSM &&
12353 	    prog->type != BPF_PROG_TYPE_EXT)
12354 		return 0;
12355 
12356 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12357 	if (ret)
12358 		return ret;
12359 
12360 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12361 		/* to make freplace equivalent to their targets, they need to
12362 		 * inherit env->ops and expected_attach_type for the rest of the
12363 		 * verification
12364 		 */
12365 		env->ops = bpf_verifier_ops[tgt_prog->type];
12366 		prog->expected_attach_type = tgt_prog->expected_attach_type;
12367 	}
12368 
12369 	/* store info about the attachment target that will be used later */
12370 	prog->aux->attach_func_proto = tgt_info.tgt_type;
12371 	prog->aux->attach_func_name = tgt_info.tgt_name;
12372 
12373 	if (tgt_prog) {
12374 		prog->aux->saved_dst_prog_type = tgt_prog->type;
12375 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12376 	}
12377 
12378 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12379 		prog->aux->attach_btf_trace = true;
12380 		return 0;
12381 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12382 		if (!bpf_iter_prog_supported(prog))
12383 			return -EINVAL;
12384 		return 0;
12385 	}
12386 
12387 	if (prog->type == BPF_PROG_TYPE_LSM) {
12388 		ret = bpf_lsm_verify_prog(&env->log, prog);
12389 		if (ret < 0)
12390 			return ret;
12391 	}
12392 
12393 	key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12394 	tr = bpf_trampoline_get(key, &tgt_info);
12395 	if (!tr)
12396 		return -ENOMEM;
12397 
12398 	prog->aux->dst_trampoline = tr;
12399 	return 0;
12400 }
12401 
bpf_get_btf_vmlinux(void)12402 struct btf *bpf_get_btf_vmlinux(void)
12403 {
12404 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12405 		mutex_lock(&bpf_verifier_lock);
12406 		if (!btf_vmlinux)
12407 			btf_vmlinux = btf_parse_vmlinux();
12408 		mutex_unlock(&bpf_verifier_lock);
12409 	}
12410 	return btf_vmlinux;
12411 }
12412 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)12413 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12414 	      union bpf_attr __user *uattr)
12415 {
12416 	u64 start_time = ktime_get_ns();
12417 	struct bpf_verifier_env *env;
12418 	struct bpf_verifier_log *log;
12419 	int i, len, ret = -EINVAL;
12420 	bool is_priv;
12421 
12422 	/* no program is valid */
12423 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12424 		return -EINVAL;
12425 
12426 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
12427 	 * allocate/free it every time bpf_check() is called
12428 	 */
12429 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12430 	if (!env)
12431 		return -ENOMEM;
12432 	log = &env->log;
12433 
12434 	len = (*prog)->len;
12435 	env->insn_aux_data =
12436 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12437 	ret = -ENOMEM;
12438 	if (!env->insn_aux_data)
12439 		goto err_free_env;
12440 	for (i = 0; i < len; i++)
12441 		env->insn_aux_data[i].orig_idx = i;
12442 	env->prog = *prog;
12443 	env->ops = bpf_verifier_ops[env->prog->type];
12444 	is_priv = bpf_capable();
12445 
12446 	bpf_get_btf_vmlinux();
12447 
12448 	/* grab the mutex to protect few globals used by verifier */
12449 	if (!is_priv)
12450 		mutex_lock(&bpf_verifier_lock);
12451 
12452 	if (attr->log_level || attr->log_buf || attr->log_size) {
12453 		/* user requested verbose verifier output
12454 		 * and supplied buffer to store the verification trace
12455 		 */
12456 		log->level = attr->log_level;
12457 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12458 		log->len_total = attr->log_size;
12459 
12460 		/* log attributes have to be sane */
12461 		if (!bpf_verifier_log_attr_valid(log)) {
12462 			ret = -EINVAL;
12463 			goto err_unlock;
12464 		}
12465 	}
12466 
12467 	if (IS_ERR(btf_vmlinux)) {
12468 		/* Either gcc or pahole or kernel are broken. */
12469 		verbose(env, "in-kernel BTF is malformed\n");
12470 		ret = PTR_ERR(btf_vmlinux);
12471 		goto skip_full_check;
12472 	}
12473 
12474 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12475 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12476 		env->strict_alignment = true;
12477 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12478 		env->strict_alignment = false;
12479 
12480 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12481 	env->allow_uninit_stack = bpf_allow_uninit_stack();
12482 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12483 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
12484 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
12485 	env->bpf_capable = bpf_capable();
12486 
12487 	if (is_priv)
12488 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12489 
12490 	env->explored_states = kvcalloc(state_htab_size(env),
12491 				       sizeof(struct bpf_verifier_state_list *),
12492 				       GFP_USER);
12493 	ret = -ENOMEM;
12494 	if (!env->explored_states)
12495 		goto skip_full_check;
12496 
12497 	ret = check_subprogs(env);
12498 	if (ret < 0)
12499 		goto skip_full_check;
12500 
12501 	ret = check_btf_info(env, attr, uattr);
12502 	if (ret < 0)
12503 		goto skip_full_check;
12504 
12505 	ret = check_attach_btf_id(env);
12506 	if (ret)
12507 		goto skip_full_check;
12508 
12509 	ret = resolve_pseudo_ldimm64(env);
12510 	if (ret < 0)
12511 		goto skip_full_check;
12512 
12513 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
12514 		ret = bpf_prog_offload_verifier_prep(env->prog);
12515 		if (ret)
12516 			goto skip_full_check;
12517 	}
12518 
12519 	ret = check_cfg(env);
12520 	if (ret < 0)
12521 		goto skip_full_check;
12522 
12523 	ret = do_check_subprogs(env);
12524 	ret = ret ?: do_check_main(env);
12525 
12526 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12527 		ret = bpf_prog_offload_finalize(env);
12528 
12529 skip_full_check:
12530 	kvfree(env->explored_states);
12531 
12532 	if (ret == 0)
12533 		ret = check_max_stack_depth(env);
12534 
12535 	/* instruction rewrites happen after this point */
12536 	if (is_priv) {
12537 		if (ret == 0)
12538 			opt_hard_wire_dead_code_branches(env);
12539 		if (ret == 0)
12540 			ret = opt_remove_dead_code(env);
12541 		if (ret == 0)
12542 			ret = opt_remove_nops(env);
12543 	} else {
12544 		if (ret == 0)
12545 			sanitize_dead_code(env);
12546 	}
12547 
12548 	if (ret == 0)
12549 		/* program is valid, convert *(u32*)(ctx + off) accesses */
12550 		ret = convert_ctx_accesses(env);
12551 
12552 	if (ret == 0)
12553 		ret = fixup_bpf_calls(env);
12554 
12555 	/* do 32-bit optimization after insn patching has done so those patched
12556 	 * insns could be handled correctly.
12557 	 */
12558 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12559 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12560 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12561 								     : false;
12562 	}
12563 
12564 	if (ret == 0)
12565 		ret = fixup_call_args(env);
12566 
12567 	env->verification_time = ktime_get_ns() - start_time;
12568 	print_verification_stats(env);
12569 
12570 	if (log->level && bpf_verifier_log_full(log))
12571 		ret = -ENOSPC;
12572 	if (log->level && !log->ubuf) {
12573 		ret = -EFAULT;
12574 		goto err_release_maps;
12575 	}
12576 
12577 	if (ret == 0 && env->used_map_cnt) {
12578 		/* if program passed verifier, update used_maps in bpf_prog_info */
12579 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12580 							  sizeof(env->used_maps[0]),
12581 							  GFP_KERNEL);
12582 
12583 		if (!env->prog->aux->used_maps) {
12584 			ret = -ENOMEM;
12585 			goto err_release_maps;
12586 		}
12587 
12588 		memcpy(env->prog->aux->used_maps, env->used_maps,
12589 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
12590 		env->prog->aux->used_map_cnt = env->used_map_cnt;
12591 
12592 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
12593 		 * bpf_ld_imm64 instructions
12594 		 */
12595 		convert_pseudo_ld_imm64(env);
12596 	}
12597 
12598 	if (ret == 0)
12599 		adjust_btf_func(env);
12600 
12601 err_release_maps:
12602 	if (!env->prog->aux->used_maps)
12603 		/* if we didn't copy map pointers into bpf_prog_info, release
12604 		 * them now. Otherwise free_used_maps() will release them.
12605 		 */
12606 		release_maps(env);
12607 
12608 	/* extension progs temporarily inherit the attach_type of their targets
12609 	   for verification purposes, so set it back to zero before returning
12610 	 */
12611 	if (env->prog->type == BPF_PROG_TYPE_EXT)
12612 		env->prog->expected_attach_type = 0;
12613 
12614 	*prog = env->prog;
12615 err_unlock:
12616 	if (!is_priv)
12617 		mutex_unlock(&bpf_verifier_lock);
12618 	vfree(env->insn_aux_data);
12619 err_free_env:
12620 	kfree(env);
12621 	return ret;
12622 }
12623