• 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 paths 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 either 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 
bpf_pseudo_call(const struct bpf_insn * insn)231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233 	return insn->code == (BPF_JMP | BPF_CALL) &&
234 	       insn->src_reg == BPF_PSEUDO_CALL;
235 }
236 
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238 {
239 	return insn->code == (BPF_JMP | BPF_CALL) &&
240 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241 }
242 
243 struct bpf_call_arg_meta {
244 	struct bpf_map *map_ptr;
245 	bool raw_mode;
246 	bool pkt_access;
247 	int regno;
248 	int access_size;
249 	int mem_size;
250 	u64 msize_max_value;
251 	int ref_obj_id;
252 	int map_uid;
253 	int func_id;
254 	struct btf *btf;
255 	u32 btf_id;
256 	struct btf *ret_btf;
257 	u32 ret_btf_id;
258 	u32 subprogno;
259 };
260 
261 struct btf *btf_vmlinux;
262 
263 static DEFINE_MUTEX(bpf_verifier_lock);
264 
265 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)266 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
267 {
268 	const struct bpf_line_info *linfo;
269 	const struct bpf_prog *prog;
270 	u32 i, nr_linfo;
271 
272 	prog = env->prog;
273 	nr_linfo = prog->aux->nr_linfo;
274 
275 	if (!nr_linfo || insn_off >= prog->len)
276 		return NULL;
277 
278 	linfo = prog->aux->linfo;
279 	for (i = 1; i < nr_linfo; i++)
280 		if (insn_off < linfo[i].insn_off)
281 			break;
282 
283 	return &linfo[i - 1];
284 }
285 
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)286 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
287 		       va_list args)
288 {
289 	unsigned int n;
290 
291 	n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
292 
293 	WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
294 		  "verifier log line truncated - local buffer too short\n");
295 
296 	n = min(log->len_total - log->len_used - 1, n);
297 	log->kbuf[n] = '\0';
298 
299 	if (log->level == BPF_LOG_KERNEL) {
300 		pr_err("BPF:%s\n", log->kbuf);
301 		return;
302 	}
303 	if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
304 		log->len_used += n;
305 	else
306 		log->ubuf = NULL;
307 }
308 
bpf_vlog_reset(struct bpf_verifier_log * log,u32 new_pos)309 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
310 {
311 	char zero = 0;
312 
313 	if (!bpf_verifier_log_needed(log))
314 		return;
315 
316 	log->len_used = new_pos;
317 	if (put_user(zero, log->ubuf + new_pos))
318 		log->ubuf = NULL;
319 }
320 
321 /* log_level controls verbosity level of eBPF verifier.
322  * bpf_verifier_log_write() is used to dump the verification trace to the log,
323  * so the user can figure out what's wrong with the program
324  */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)325 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
326 					   const char *fmt, ...)
327 {
328 	va_list args;
329 
330 	if (!bpf_verifier_log_needed(&env->log))
331 		return;
332 
333 	va_start(args, fmt);
334 	bpf_verifier_vlog(&env->log, fmt, args);
335 	va_end(args);
336 }
337 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
338 
verbose(void * private_data,const char * fmt,...)339 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
340 {
341 	struct bpf_verifier_env *env = private_data;
342 	va_list args;
343 
344 	if (!bpf_verifier_log_needed(&env->log))
345 		return;
346 
347 	va_start(args, fmt);
348 	bpf_verifier_vlog(&env->log, fmt, args);
349 	va_end(args);
350 }
351 
bpf_log(struct bpf_verifier_log * log,const char * fmt,...)352 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
353 			    const char *fmt, ...)
354 {
355 	va_list args;
356 
357 	if (!bpf_verifier_log_needed(log))
358 		return;
359 
360 	va_start(args, fmt);
361 	bpf_verifier_vlog(log, fmt, args);
362 	va_end(args);
363 }
364 
ltrim(const char * s)365 static const char *ltrim(const char *s)
366 {
367 	while (isspace(*s))
368 		s++;
369 
370 	return s;
371 }
372 
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)373 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
374 					 u32 insn_off,
375 					 const char *prefix_fmt, ...)
376 {
377 	const struct bpf_line_info *linfo;
378 
379 	if (!bpf_verifier_log_needed(&env->log))
380 		return;
381 
382 	linfo = find_linfo(env, insn_off);
383 	if (!linfo || linfo == env->prev_linfo)
384 		return;
385 
386 	if (prefix_fmt) {
387 		va_list args;
388 
389 		va_start(args, prefix_fmt);
390 		bpf_verifier_vlog(&env->log, prefix_fmt, args);
391 		va_end(args);
392 	}
393 
394 	verbose(env, "%s\n",
395 		ltrim(btf_name_by_offset(env->prog->aux->btf,
396 					 linfo->line_off)));
397 
398 	env->prev_linfo = linfo;
399 }
400 
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct tnum * range,const char * ctx,const char * reg_name)401 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
402 				   struct bpf_reg_state *reg,
403 				   struct tnum *range, const char *ctx,
404 				   const char *reg_name)
405 {
406 	char tn_buf[48];
407 
408 	verbose(env, "At %s the register %s ", ctx, reg_name);
409 	if (!tnum_is_unknown(reg->var_off)) {
410 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
411 		verbose(env, "has value %s", tn_buf);
412 	} else {
413 		verbose(env, "has unknown scalar value");
414 	}
415 	tnum_strn(tn_buf, sizeof(tn_buf), *range);
416 	verbose(env, " should have been in %s\n", tn_buf);
417 }
418 
type_is_pkt_pointer(enum bpf_reg_type type)419 static bool type_is_pkt_pointer(enum bpf_reg_type type)
420 {
421 	return type == PTR_TO_PACKET ||
422 	       type == PTR_TO_PACKET_META;
423 }
424 
type_is_sk_pointer(enum bpf_reg_type type)425 static bool type_is_sk_pointer(enum bpf_reg_type type)
426 {
427 	return type == PTR_TO_SOCKET ||
428 		type == PTR_TO_SOCK_COMMON ||
429 		type == PTR_TO_TCP_SOCK ||
430 		type == PTR_TO_XDP_SOCK;
431 }
432 
reg_type_not_null(enum bpf_reg_type type)433 static bool reg_type_not_null(enum bpf_reg_type type)
434 {
435 	return type == PTR_TO_SOCKET ||
436 		type == PTR_TO_TCP_SOCK ||
437 		type == PTR_TO_MAP_VALUE ||
438 		type == PTR_TO_MAP_KEY ||
439 		type == PTR_TO_SOCK_COMMON;
440 }
441 
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)442 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
443 {
444 	return reg->type == PTR_TO_MAP_VALUE &&
445 		map_value_has_spin_lock(reg->map_ptr);
446 }
447 
reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)448 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
449 {
450 	return base_type(type) == PTR_TO_SOCKET ||
451 		base_type(type) == PTR_TO_TCP_SOCK ||
452 		base_type(type) == PTR_TO_MEM;
453 }
454 
type_is_rdonly_mem(u32 type)455 static bool type_is_rdonly_mem(u32 type)
456 {
457 	return type & MEM_RDONLY;
458 }
459 
arg_type_may_be_refcounted(enum bpf_arg_type type)460 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
461 {
462 	return type == ARG_PTR_TO_SOCK_COMMON;
463 }
464 
type_may_be_null(u32 type)465 static bool type_may_be_null(u32 type)
466 {
467 	return type & PTR_MAYBE_NULL;
468 }
469 
470 /* Determine whether the function releases some resources allocated by another
471  * function call. The first reference type argument will be assumed to be
472  * released by release_reference().
473  */
is_release_function(enum bpf_func_id func_id)474 static bool is_release_function(enum bpf_func_id func_id)
475 {
476 	return func_id == BPF_FUNC_sk_release ||
477 	       func_id == BPF_FUNC_ringbuf_submit ||
478 	       func_id == BPF_FUNC_ringbuf_discard;
479 }
480 
may_be_acquire_function(enum bpf_func_id func_id)481 static bool may_be_acquire_function(enum bpf_func_id func_id)
482 {
483 	return func_id == BPF_FUNC_sk_lookup_tcp ||
484 		func_id == BPF_FUNC_sk_lookup_udp ||
485 		func_id == BPF_FUNC_skc_lookup_tcp ||
486 		func_id == BPF_FUNC_map_lookup_elem ||
487 	        func_id == BPF_FUNC_ringbuf_reserve;
488 }
489 
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)490 static bool is_acquire_function(enum bpf_func_id func_id,
491 				const struct bpf_map *map)
492 {
493 	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
494 
495 	if (func_id == BPF_FUNC_sk_lookup_tcp ||
496 	    func_id == BPF_FUNC_sk_lookup_udp ||
497 	    func_id == BPF_FUNC_skc_lookup_tcp ||
498 	    func_id == BPF_FUNC_ringbuf_reserve)
499 		return true;
500 
501 	if (func_id == BPF_FUNC_map_lookup_elem &&
502 	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
503 	     map_type == BPF_MAP_TYPE_SOCKHASH))
504 		return true;
505 
506 	return false;
507 }
508 
is_ptr_cast_function(enum bpf_func_id func_id)509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511 	return func_id == BPF_FUNC_tcp_sock ||
512 		func_id == BPF_FUNC_sk_fullsock ||
513 		func_id == BPF_FUNC_skc_to_tcp_sock ||
514 		func_id == BPF_FUNC_skc_to_tcp6_sock ||
515 		func_id == BPF_FUNC_skc_to_udp6_sock ||
516 		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
517 		func_id == BPF_FUNC_skc_to_tcp_request_sock;
518 }
519 
is_callback_calling_function(enum bpf_func_id func_id)520 static bool is_callback_calling_function(enum bpf_func_id func_id)
521 {
522 	return func_id == BPF_FUNC_for_each_map_elem ||
523 	       func_id == BPF_FUNC_timer_set_callback;
524 }
525 
is_cmpxchg_insn(const struct bpf_insn * insn)526 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
527 {
528 	return BPF_CLASS(insn->code) == BPF_STX &&
529 	       BPF_MODE(insn->code) == BPF_ATOMIC &&
530 	       insn->imm == BPF_CMPXCHG;
531 }
532 
533 /* string representation of 'enum bpf_reg_type'
534  *
535  * Note that reg_type_str() can not appear more than once in a single verbose()
536  * statement.
537  */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)538 static const char *reg_type_str(struct bpf_verifier_env *env,
539 				enum bpf_reg_type type)
540 {
541 	char postfix[16] = {0}, prefix[16] = {0};
542 	static const char * const str[] = {
543 		[NOT_INIT]		= "?",
544 		[SCALAR_VALUE]		= "inv",
545 		[PTR_TO_CTX]		= "ctx",
546 		[CONST_PTR_TO_MAP]	= "map_ptr",
547 		[PTR_TO_MAP_VALUE]	= "map_value",
548 		[PTR_TO_STACK]		= "fp",
549 		[PTR_TO_PACKET]		= "pkt",
550 		[PTR_TO_PACKET_META]	= "pkt_meta",
551 		[PTR_TO_PACKET_END]	= "pkt_end",
552 		[PTR_TO_FLOW_KEYS]	= "flow_keys",
553 		[PTR_TO_SOCKET]		= "sock",
554 		[PTR_TO_SOCK_COMMON]	= "sock_common",
555 		[PTR_TO_TCP_SOCK]	= "tcp_sock",
556 		[PTR_TO_TP_BUFFER]	= "tp_buffer",
557 		[PTR_TO_XDP_SOCK]	= "xdp_sock",
558 		[PTR_TO_BTF_ID]		= "ptr_",
559 		[PTR_TO_PERCPU_BTF_ID]	= "percpu_ptr_",
560 		[PTR_TO_MEM]		= "mem",
561 		[PTR_TO_BUF]		= "buf",
562 		[PTR_TO_FUNC]		= "func",
563 		[PTR_TO_MAP_KEY]	= "map_key",
564 	};
565 
566 	if (type & PTR_MAYBE_NULL) {
567 		if (base_type(type) == PTR_TO_BTF_ID ||
568 		    base_type(type) == PTR_TO_PERCPU_BTF_ID)
569 			strncpy(postfix, "or_null_", 16);
570 		else
571 			strncpy(postfix, "_or_null", 16);
572 	}
573 
574 	if (type & MEM_RDONLY)
575 		strncpy(prefix, "rdonly_", 16);
576 
577 	snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
578 		 prefix, str[base_type(type)], postfix);
579 	return env->type_str_buf;
580 }
581 
582 static char slot_type_char[] = {
583 	[STACK_INVALID]	= '?',
584 	[STACK_SPILL]	= 'r',
585 	[STACK_MISC]	= 'm',
586 	[STACK_ZERO]	= '0',
587 };
588 
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)589 static void print_liveness(struct bpf_verifier_env *env,
590 			   enum bpf_reg_liveness live)
591 {
592 	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
593 	    verbose(env, "_");
594 	if (live & REG_LIVE_READ)
595 		verbose(env, "r");
596 	if (live & REG_LIVE_WRITTEN)
597 		verbose(env, "w");
598 	if (live & REG_LIVE_DONE)
599 		verbose(env, "D");
600 }
601 
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 				   const struct bpf_reg_state *reg)
604 {
605 	struct bpf_verifier_state *cur = env->cur_state;
606 
607 	return cur->frame[reg->frameno];
608 }
609 
kernel_type_name(const struct btf * btf,u32 id)610 static const char *kernel_type_name(const struct btf* btf, u32 id)
611 {
612 	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
613 }
614 
615 /* The reg state of a pointer or a bounded scalar was saved when
616  * it was spilled to the stack.
617  */
is_spilled_reg(const struct bpf_stack_state * stack)618 static bool is_spilled_reg(const struct bpf_stack_state *stack)
619 {
620 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
621 }
622 
scrub_spilled_slot(u8 * stype)623 static void scrub_spilled_slot(u8 *stype)
624 {
625 	if (*stype != STACK_INVALID)
626 		*stype = STACK_MISC;
627 }
628 
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)629 static void print_verifier_state(struct bpf_verifier_env *env,
630 				 const struct bpf_func_state *state)
631 {
632 	const struct bpf_reg_state *reg;
633 	enum bpf_reg_type t;
634 	int i;
635 
636 	if (state->frameno)
637 		verbose(env, " frame%d:", state->frameno);
638 	for (i = 0; i < MAX_BPF_REG; i++) {
639 		reg = &state->regs[i];
640 		t = reg->type;
641 		if (t == NOT_INIT)
642 			continue;
643 		verbose(env, " R%d", i);
644 		print_liveness(env, reg->live);
645 		verbose(env, "=%s", reg_type_str(env, t));
646 		if (t == SCALAR_VALUE && reg->precise)
647 			verbose(env, "P");
648 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
649 		    tnum_is_const(reg->var_off)) {
650 			/* reg->off should be 0 for SCALAR_VALUE */
651 			verbose(env, "%lld", reg->var_off.value + reg->off);
652 		} else {
653 			if (base_type(t) == PTR_TO_BTF_ID ||
654 			    base_type(t) == PTR_TO_PERCPU_BTF_ID)
655 				verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
656 			verbose(env, "(id=%d", reg->id);
657 			if (reg_type_may_be_refcounted_or_null(t))
658 				verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
659 			if (t != SCALAR_VALUE)
660 				verbose(env, ",off=%d", reg->off);
661 			if (type_is_pkt_pointer(t))
662 				verbose(env, ",r=%d", reg->range);
663 			else if (base_type(t) == CONST_PTR_TO_MAP ||
664 				 base_type(t) == PTR_TO_MAP_KEY ||
665 				 base_type(t) == PTR_TO_MAP_VALUE)
666 				verbose(env, ",ks=%d,vs=%d",
667 					reg->map_ptr->key_size,
668 					reg->map_ptr->value_size);
669 			if (tnum_is_const(reg->var_off)) {
670 				/* Typically an immediate SCALAR_VALUE, but
671 				 * could be a pointer whose offset is too big
672 				 * for reg->off
673 				 */
674 				verbose(env, ",imm=%llx", reg->var_off.value);
675 			} else {
676 				if (reg->smin_value != reg->umin_value &&
677 				    reg->smin_value != S64_MIN)
678 					verbose(env, ",smin_value=%lld",
679 						(long long)reg->smin_value);
680 				if (reg->smax_value != reg->umax_value &&
681 				    reg->smax_value != S64_MAX)
682 					verbose(env, ",smax_value=%lld",
683 						(long long)reg->smax_value);
684 				if (reg->umin_value != 0)
685 					verbose(env, ",umin_value=%llu",
686 						(unsigned long long)reg->umin_value);
687 				if (reg->umax_value != U64_MAX)
688 					verbose(env, ",umax_value=%llu",
689 						(unsigned long long)reg->umax_value);
690 				if (!tnum_is_unknown(reg->var_off)) {
691 					char tn_buf[48];
692 
693 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
694 					verbose(env, ",var_off=%s", tn_buf);
695 				}
696 				if (reg->s32_min_value != reg->smin_value &&
697 				    reg->s32_min_value != S32_MIN)
698 					verbose(env, ",s32_min_value=%d",
699 						(int)(reg->s32_min_value));
700 				if (reg->s32_max_value != reg->smax_value &&
701 				    reg->s32_max_value != S32_MAX)
702 					verbose(env, ",s32_max_value=%d",
703 						(int)(reg->s32_max_value));
704 				if (reg->u32_min_value != reg->umin_value &&
705 				    reg->u32_min_value != U32_MIN)
706 					verbose(env, ",u32_min_value=%d",
707 						(int)(reg->u32_min_value));
708 				if (reg->u32_max_value != reg->umax_value &&
709 				    reg->u32_max_value != U32_MAX)
710 					verbose(env, ",u32_max_value=%d",
711 						(int)(reg->u32_max_value));
712 			}
713 			verbose(env, ")");
714 		}
715 	}
716 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
717 		char types_buf[BPF_REG_SIZE + 1];
718 		bool valid = false;
719 		int j;
720 
721 		for (j = 0; j < BPF_REG_SIZE; j++) {
722 			if (state->stack[i].slot_type[j] != STACK_INVALID)
723 				valid = true;
724 			types_buf[j] = slot_type_char[
725 					state->stack[i].slot_type[j]];
726 		}
727 		types_buf[BPF_REG_SIZE] = 0;
728 		if (!valid)
729 			continue;
730 		verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
731 		print_liveness(env, state->stack[i].spilled_ptr.live);
732 		if (is_spilled_reg(&state->stack[i])) {
733 			reg = &state->stack[i].spilled_ptr;
734 			t = reg->type;
735 			verbose(env, "=%s", reg_type_str(env, t));
736 			if (t == SCALAR_VALUE && reg->precise)
737 				verbose(env, "P");
738 			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
739 				verbose(env, "%lld", reg->var_off.value + reg->off);
740 		} else {
741 			verbose(env, "=%s", types_buf);
742 		}
743 	}
744 	if (state->acquired_refs && state->refs[0].id) {
745 		verbose(env, " refs=%d", state->refs[0].id);
746 		for (i = 1; i < state->acquired_refs; i++)
747 			if (state->refs[i].id)
748 				verbose(env, ",%d", state->refs[i].id);
749 	}
750 	if (state->in_callback_fn)
751 		verbose(env, " cb");
752 	if (state->in_async_callback_fn)
753 		verbose(env, " async_cb");
754 	verbose(env, "\n");
755 }
756 
757 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
758  * small to hold src. This is different from krealloc since we don't want to preserve
759  * the contents of dst.
760  *
761  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
762  * not be allocated.
763  */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)764 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
765 {
766 	size_t bytes;
767 
768 	if (ZERO_OR_NULL_PTR(src))
769 		goto out;
770 
771 	if (unlikely(check_mul_overflow(n, size, &bytes)))
772 		return NULL;
773 
774 	if (ksize(dst) < bytes) {
775 		kfree(dst);
776 		dst = kmalloc_track_caller(bytes, flags);
777 		if (!dst)
778 			return NULL;
779 	}
780 
781 	memcpy(dst, src, bytes);
782 out:
783 	return dst ? dst : ZERO_SIZE_PTR;
784 }
785 
786 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
787  * small to hold new_n items. new items are zeroed out if the array grows.
788  *
789  * Contrary to krealloc_array, does not free arr if new_n is zero.
790  */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)791 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
792 {
793 	void *new_arr;
794 
795 	if (!new_n || old_n == new_n)
796 		goto out;
797 
798 	new_arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
799 	if (!new_arr) {
800 		kfree(arr);
801 		return NULL;
802 	}
803 	arr = new_arr;
804 
805 	if (new_n > old_n)
806 		memset(arr + old_n * size, 0, (new_n - old_n) * size);
807 
808 out:
809 	return arr ? arr : ZERO_SIZE_PTR;
810 }
811 
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)812 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
813 {
814 	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
815 			       sizeof(struct bpf_reference_state), GFP_KERNEL);
816 	if (!dst->refs)
817 		return -ENOMEM;
818 
819 	dst->acquired_refs = src->acquired_refs;
820 	return 0;
821 }
822 
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)823 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
824 {
825 	size_t n = src->allocated_stack / BPF_REG_SIZE;
826 
827 	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
828 				GFP_KERNEL);
829 	if (!dst->stack)
830 		return -ENOMEM;
831 
832 	dst->allocated_stack = src->allocated_stack;
833 	return 0;
834 }
835 
resize_reference_state(struct bpf_func_state * state,size_t n)836 static int resize_reference_state(struct bpf_func_state *state, size_t n)
837 {
838 	state->refs = realloc_array(state->refs, state->acquired_refs, n,
839 				    sizeof(struct bpf_reference_state));
840 	if (!state->refs)
841 		return -ENOMEM;
842 
843 	state->acquired_refs = n;
844 	return 0;
845 }
846 
grow_stack_state(struct bpf_func_state * state,int size)847 static int grow_stack_state(struct bpf_func_state *state, int size)
848 {
849 	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
850 
851 	if (old_n >= n)
852 		return 0;
853 
854 	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
855 	if (!state->stack)
856 		return -ENOMEM;
857 
858 	state->allocated_stack = size;
859 	return 0;
860 }
861 
862 /* Acquire a pointer id from the env and update the state->refs to include
863  * this new pointer reference.
864  * On success, returns a valid pointer id to associate with the register
865  * On failure, returns a negative errno.
866  */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)867 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
868 {
869 	struct bpf_func_state *state = cur_func(env);
870 	int new_ofs = state->acquired_refs;
871 	int id, err;
872 
873 	err = resize_reference_state(state, state->acquired_refs + 1);
874 	if (err)
875 		return err;
876 	id = ++env->id_gen;
877 	state->refs[new_ofs].id = id;
878 	state->refs[new_ofs].insn_idx = insn_idx;
879 	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
880 
881 	return id;
882 }
883 
884 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)885 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
886 {
887 	int i, last_idx;
888 
889 	last_idx = state->acquired_refs - 1;
890 	for (i = 0; i < state->acquired_refs; i++) {
891 		if (state->refs[i].id == ptr_id) {
892 			/* Cannot release caller references in callbacks */
893 			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
894 				return -EINVAL;
895 			if (last_idx && i != last_idx)
896 				memcpy(&state->refs[i], &state->refs[last_idx],
897 				       sizeof(*state->refs));
898 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
899 			state->acquired_refs--;
900 			return 0;
901 		}
902 	}
903 	return -EINVAL;
904 }
905 
free_func_state(struct bpf_func_state * state)906 static void free_func_state(struct bpf_func_state *state)
907 {
908 	if (!state)
909 		return;
910 	kfree(state->refs);
911 	kfree(state->stack);
912 	kfree(state);
913 }
914 
clear_jmp_history(struct bpf_verifier_state * state)915 static void clear_jmp_history(struct bpf_verifier_state *state)
916 {
917 	kfree(state->jmp_history);
918 	state->jmp_history = NULL;
919 	state->jmp_history_cnt = 0;
920 }
921 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)922 static void free_verifier_state(struct bpf_verifier_state *state,
923 				bool free_self)
924 {
925 	int i;
926 
927 	for (i = 0; i <= state->curframe; i++) {
928 		free_func_state(state->frame[i]);
929 		state->frame[i] = NULL;
930 	}
931 	clear_jmp_history(state);
932 	if (free_self)
933 		kfree(state);
934 }
935 
936 /* copy verifier state from src to dst growing dst stack space
937  * when necessary to accommodate larger src stack
938  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)939 static int copy_func_state(struct bpf_func_state *dst,
940 			   const struct bpf_func_state *src)
941 {
942 	int err;
943 
944 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
945 	err = copy_reference_state(dst, src);
946 	if (err)
947 		return err;
948 	return copy_stack_state(dst, src);
949 }
950 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)951 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
952 			       const struct bpf_verifier_state *src)
953 {
954 	struct bpf_func_state *dst;
955 	int i, err;
956 
957 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
958 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
959 					    GFP_USER);
960 	if (!dst_state->jmp_history)
961 		return -ENOMEM;
962 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
963 
964 	/* if dst has more stack frames then src frame, free them */
965 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
966 		free_func_state(dst_state->frame[i]);
967 		dst_state->frame[i] = NULL;
968 	}
969 	dst_state->speculative = src->speculative;
970 	dst_state->curframe = src->curframe;
971 	dst_state->active_spin_lock = src->active_spin_lock;
972 	dst_state->branches = src->branches;
973 	dst_state->parent = src->parent;
974 	dst_state->first_insn_idx = src->first_insn_idx;
975 	dst_state->last_insn_idx = src->last_insn_idx;
976 	for (i = 0; i <= src->curframe; i++) {
977 		dst = dst_state->frame[i];
978 		if (!dst) {
979 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
980 			if (!dst)
981 				return -ENOMEM;
982 			dst_state->frame[i] = dst;
983 		}
984 		err = copy_func_state(dst, src->frame[i]);
985 		if (err)
986 			return err;
987 	}
988 	return 0;
989 }
990 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)991 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
992 {
993 	while (st) {
994 		u32 br = --st->branches;
995 
996 		/* WARN_ON(br > 1) technically makes sense here,
997 		 * but see comment in push_stack(), hence:
998 		 */
999 		WARN_ONCE((int)br < 0,
1000 			  "BUG update_branch_counts:branches_to_explore=%d\n",
1001 			  br);
1002 		if (br)
1003 			break;
1004 		st = st->parent;
1005 	}
1006 }
1007 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)1008 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1009 		     int *insn_idx, bool pop_log)
1010 {
1011 	struct bpf_verifier_state *cur = env->cur_state;
1012 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1013 	int err;
1014 
1015 	if (env->head == NULL)
1016 		return -ENOENT;
1017 
1018 	if (cur) {
1019 		err = copy_verifier_state(cur, &head->st);
1020 		if (err)
1021 			return err;
1022 	}
1023 	if (pop_log)
1024 		bpf_vlog_reset(&env->log, head->log_pos);
1025 	if (insn_idx)
1026 		*insn_idx = head->insn_idx;
1027 	if (prev_insn_idx)
1028 		*prev_insn_idx = head->prev_insn_idx;
1029 	elem = head->next;
1030 	free_verifier_state(&head->st, false);
1031 	kfree(head);
1032 	env->head = elem;
1033 	env->stack_size--;
1034 	return 0;
1035 }
1036 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)1037 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1038 					     int insn_idx, int prev_insn_idx,
1039 					     bool speculative)
1040 {
1041 	struct bpf_verifier_state *cur = env->cur_state;
1042 	struct bpf_verifier_stack_elem *elem;
1043 	int err;
1044 
1045 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1046 	if (!elem)
1047 		goto err;
1048 
1049 	elem->insn_idx = insn_idx;
1050 	elem->prev_insn_idx = prev_insn_idx;
1051 	elem->next = env->head;
1052 	elem->log_pos = env->log.len_used;
1053 	env->head = elem;
1054 	env->stack_size++;
1055 	err = copy_verifier_state(&elem->st, cur);
1056 	if (err)
1057 		goto err;
1058 	elem->st.speculative |= speculative;
1059 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1060 		verbose(env, "The sequence of %d jumps is too complex.\n",
1061 			env->stack_size);
1062 		goto err;
1063 	}
1064 	if (elem->st.parent) {
1065 		++elem->st.parent->branches;
1066 		/* WARN_ON(branches > 2) technically makes sense here,
1067 		 * but
1068 		 * 1. speculative states will bump 'branches' for non-branch
1069 		 * instructions
1070 		 * 2. is_state_visited() heuristics may decide not to create
1071 		 * a new state for a sequence of branches and all such current
1072 		 * and cloned states will be pointing to a single parent state
1073 		 * which might have large 'branches' count.
1074 		 */
1075 	}
1076 	return &elem->st;
1077 err:
1078 	free_verifier_state(env->cur_state, true);
1079 	env->cur_state = NULL;
1080 	/* pop all elements and return */
1081 	while (!pop_stack(env, NULL, NULL, false));
1082 	return NULL;
1083 }
1084 
1085 #define CALLER_SAVED_REGS 6
1086 static const int caller_saved[CALLER_SAVED_REGS] = {
1087 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1088 };
1089 
1090 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1091 				struct bpf_reg_state *reg);
1092 
1093 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1094 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1095 {
1096 	reg->var_off = tnum_const(imm);
1097 	reg->smin_value = (s64)imm;
1098 	reg->smax_value = (s64)imm;
1099 	reg->umin_value = imm;
1100 	reg->umax_value = imm;
1101 
1102 	reg->s32_min_value = (s32)imm;
1103 	reg->s32_max_value = (s32)imm;
1104 	reg->u32_min_value = (u32)imm;
1105 	reg->u32_max_value = (u32)imm;
1106 }
1107 
1108 /* Mark the unknown part of a register (variable offset or scalar value) as
1109  * known to have the value @imm.
1110  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1111 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1112 {
1113 	/* Clear id, off, and union(map_ptr, range) */
1114 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1115 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1116 	___mark_reg_known(reg, imm);
1117 }
1118 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1119 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1120 {
1121 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1122 	reg->s32_min_value = (s32)imm;
1123 	reg->s32_max_value = (s32)imm;
1124 	reg->u32_min_value = (u32)imm;
1125 	reg->u32_max_value = (u32)imm;
1126 }
1127 
1128 /* Mark the 'variable offset' part of a register as zero.  This should be
1129  * used only on registers holding a pointer type.
1130  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1131 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1132 {
1133 	__mark_reg_known(reg, 0);
1134 }
1135 
__mark_reg_const_zero(struct bpf_reg_state * reg)1136 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1137 {
1138 	__mark_reg_known(reg, 0);
1139 	reg->type = SCALAR_VALUE;
1140 }
1141 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1142 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1143 				struct bpf_reg_state *regs, u32 regno)
1144 {
1145 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1146 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1147 		/* Something bad happened, let's kill all regs */
1148 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1149 			__mark_reg_not_init(env, regs + regno);
1150 		return;
1151 	}
1152 	__mark_reg_known_zero(regs + regno);
1153 }
1154 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)1155 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1156 {
1157 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1158 		const struct bpf_map *map = reg->map_ptr;
1159 
1160 		if (map->inner_map_meta) {
1161 			reg->type = CONST_PTR_TO_MAP;
1162 			reg->map_ptr = map->inner_map_meta;
1163 			/* transfer reg's id which is unique for every map_lookup_elem
1164 			 * as UID of the inner map.
1165 			 */
1166 			if (map_value_has_timer(map->inner_map_meta))
1167 				reg->map_uid = reg->id;
1168 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1169 			reg->type = PTR_TO_XDP_SOCK;
1170 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1171 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1172 			reg->type = PTR_TO_SOCKET;
1173 		} else {
1174 			reg->type = PTR_TO_MAP_VALUE;
1175 		}
1176 		return;
1177 	}
1178 
1179 	reg->type &= ~PTR_MAYBE_NULL;
1180 }
1181 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1182 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1183 {
1184 	return type_is_pkt_pointer(reg->type);
1185 }
1186 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1187 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1188 {
1189 	return reg_is_pkt_pointer(reg) ||
1190 	       reg->type == PTR_TO_PACKET_END;
1191 }
1192 
1193 /* 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)1194 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1195 				    enum bpf_reg_type which)
1196 {
1197 	/* The register can already have a range from prior markings.
1198 	 * This is fine as long as it hasn't been advanced from its
1199 	 * origin.
1200 	 */
1201 	return reg->type == which &&
1202 	       reg->id == 0 &&
1203 	       reg->off == 0 &&
1204 	       tnum_equals_const(reg->var_off, 0);
1205 }
1206 
1207 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1208 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1209 {
1210 	reg->smin_value = S64_MIN;
1211 	reg->smax_value = S64_MAX;
1212 	reg->umin_value = 0;
1213 	reg->umax_value = U64_MAX;
1214 
1215 	reg->s32_min_value = S32_MIN;
1216 	reg->s32_max_value = S32_MAX;
1217 	reg->u32_min_value = 0;
1218 	reg->u32_max_value = U32_MAX;
1219 }
1220 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1221 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1222 {
1223 	reg->smin_value = S64_MIN;
1224 	reg->smax_value = S64_MAX;
1225 	reg->umin_value = 0;
1226 	reg->umax_value = U64_MAX;
1227 }
1228 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1229 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1230 {
1231 	reg->s32_min_value = S32_MIN;
1232 	reg->s32_max_value = S32_MAX;
1233 	reg->u32_min_value = 0;
1234 	reg->u32_max_value = U32_MAX;
1235 }
1236 
__update_reg32_bounds(struct bpf_reg_state * reg)1237 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1238 {
1239 	struct tnum var32_off = tnum_subreg(reg->var_off);
1240 
1241 	/* min signed is max(sign bit) | min(other bits) */
1242 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1243 			var32_off.value | (var32_off.mask & S32_MIN));
1244 	/* max signed is min(sign bit) | max(other bits) */
1245 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1246 			var32_off.value | (var32_off.mask & S32_MAX));
1247 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1248 	reg->u32_max_value = min(reg->u32_max_value,
1249 				 (u32)(var32_off.value | var32_off.mask));
1250 }
1251 
__update_reg64_bounds(struct bpf_reg_state * reg)1252 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1253 {
1254 	/* min signed is max(sign bit) | min(other bits) */
1255 	reg->smin_value = max_t(s64, reg->smin_value,
1256 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1257 	/* max signed is min(sign bit) | max(other bits) */
1258 	reg->smax_value = min_t(s64, reg->smax_value,
1259 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1260 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1261 	reg->umax_value = min(reg->umax_value,
1262 			      reg->var_off.value | reg->var_off.mask);
1263 }
1264 
__update_reg_bounds(struct bpf_reg_state * reg)1265 static void __update_reg_bounds(struct bpf_reg_state *reg)
1266 {
1267 	__update_reg32_bounds(reg);
1268 	__update_reg64_bounds(reg);
1269 }
1270 
1271 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1272 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1273 {
1274 	/* Learn sign from signed bounds.
1275 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1276 	 * are the same, so combine.  This works even in the negative case, e.g.
1277 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1278 	 */
1279 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1280 		reg->s32_min_value = reg->u32_min_value =
1281 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1282 		reg->s32_max_value = reg->u32_max_value =
1283 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1284 		return;
1285 	}
1286 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1287 	 * boundary, so we must be careful.
1288 	 */
1289 	if ((s32)reg->u32_max_value >= 0) {
1290 		/* Positive.  We can't learn anything from the smin, but smax
1291 		 * is positive, hence safe.
1292 		 */
1293 		reg->s32_min_value = reg->u32_min_value;
1294 		reg->s32_max_value = reg->u32_max_value =
1295 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1296 	} else if ((s32)reg->u32_min_value < 0) {
1297 		/* Negative.  We can't learn anything from the smax, but smin
1298 		 * is negative, hence safe.
1299 		 */
1300 		reg->s32_min_value = reg->u32_min_value =
1301 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1302 		reg->s32_max_value = reg->u32_max_value;
1303 	}
1304 }
1305 
__reg64_deduce_bounds(struct bpf_reg_state * reg)1306 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1307 {
1308 	/* Learn sign from signed bounds.
1309 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1310 	 * are the same, so combine.  This works even in the negative case, e.g.
1311 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1312 	 */
1313 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1314 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1315 							  reg->umin_value);
1316 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1317 							  reg->umax_value);
1318 		return;
1319 	}
1320 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1321 	 * boundary, so we must be careful.
1322 	 */
1323 	if ((s64)reg->umax_value >= 0) {
1324 		/* Positive.  We can't learn anything from the smin, but smax
1325 		 * is positive, hence safe.
1326 		 */
1327 		reg->smin_value = reg->umin_value;
1328 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1329 							  reg->umax_value);
1330 	} else if ((s64)reg->umin_value < 0) {
1331 		/* Negative.  We can't learn anything from the smax, but smin
1332 		 * is negative, hence safe.
1333 		 */
1334 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1335 							  reg->umin_value);
1336 		reg->smax_value = reg->umax_value;
1337 	}
1338 }
1339 
__reg_deduce_bounds(struct bpf_reg_state * reg)1340 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1341 {
1342 	__reg32_deduce_bounds(reg);
1343 	__reg64_deduce_bounds(reg);
1344 }
1345 
1346 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1347 static void __reg_bound_offset(struct bpf_reg_state *reg)
1348 {
1349 	struct tnum var64_off = tnum_intersect(reg->var_off,
1350 					       tnum_range(reg->umin_value,
1351 							  reg->umax_value));
1352 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1353 						tnum_range(reg->u32_min_value,
1354 							   reg->u32_max_value));
1355 
1356 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1357 }
1358 
reg_bounds_sync(struct bpf_reg_state * reg)1359 static void reg_bounds_sync(struct bpf_reg_state *reg)
1360 {
1361 	/* We might have learned new bounds from the var_off. */
1362 	__update_reg_bounds(reg);
1363 	/* We might have learned something about the sign bit. */
1364 	__reg_deduce_bounds(reg);
1365 	/* We might have learned some bits from the bounds. */
1366 	__reg_bound_offset(reg);
1367 	/* Intersecting with the old var_off might have improved our bounds
1368 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1369 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1370 	 */
1371 	__update_reg_bounds(reg);
1372 }
1373 
__reg32_bound_s64(s32 a)1374 static bool __reg32_bound_s64(s32 a)
1375 {
1376 	return a >= 0 && a <= S32_MAX;
1377 }
1378 
__reg_assign_32_into_64(struct bpf_reg_state * reg)1379 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1380 {
1381 	reg->umin_value = reg->u32_min_value;
1382 	reg->umax_value = reg->u32_max_value;
1383 
1384 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1385 	 * be positive otherwise set to worse case bounds and refine later
1386 	 * from tnum.
1387 	 */
1388 	if (__reg32_bound_s64(reg->s32_min_value) &&
1389 	    __reg32_bound_s64(reg->s32_max_value)) {
1390 		reg->smin_value = reg->s32_min_value;
1391 		reg->smax_value = reg->s32_max_value;
1392 	} else {
1393 		reg->smin_value = 0;
1394 		reg->smax_value = U32_MAX;
1395 	}
1396 }
1397 
__reg_combine_32_into_64(struct bpf_reg_state * reg)1398 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1399 {
1400 	/* special case when 64-bit register has upper 32-bit register
1401 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1402 	 * allowing us to use 32-bit bounds directly,
1403 	 */
1404 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1405 		__reg_assign_32_into_64(reg);
1406 	} else {
1407 		/* Otherwise the best we can do is push lower 32bit known and
1408 		 * unknown bits into register (var_off set from jmp logic)
1409 		 * then learn as much as possible from the 64-bit tnum
1410 		 * known and unknown bits. The previous smin/smax bounds are
1411 		 * invalid here because of jmp32 compare so mark them unknown
1412 		 * so they do not impact tnum bounds calculation.
1413 		 */
1414 		__mark_reg64_unbounded(reg);
1415 	}
1416 	reg_bounds_sync(reg);
1417 }
1418 
__reg64_bound_s32(s64 a)1419 static bool __reg64_bound_s32(s64 a)
1420 {
1421 	return a >= S32_MIN && a <= S32_MAX;
1422 }
1423 
__reg64_bound_u32(u64 a)1424 static bool __reg64_bound_u32(u64 a)
1425 {
1426 	return a >= U32_MIN && a <= U32_MAX;
1427 }
1428 
__reg_combine_64_into_32(struct bpf_reg_state * reg)1429 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1430 {
1431 	__mark_reg32_unbounded(reg);
1432 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1433 		reg->s32_min_value = (s32)reg->smin_value;
1434 		reg->s32_max_value = (s32)reg->smax_value;
1435 	}
1436 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1437 		reg->u32_min_value = (u32)reg->umin_value;
1438 		reg->u32_max_value = (u32)reg->umax_value;
1439 	}
1440 	reg_bounds_sync(reg);
1441 }
1442 
1443 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1444 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1445 			       struct bpf_reg_state *reg)
1446 {
1447 	/*
1448 	 * Clear type, id, off, and union(map_ptr, range) and
1449 	 * padding between 'type' and union
1450 	 */
1451 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1452 	reg->type = SCALAR_VALUE;
1453 	reg->var_off = tnum_unknown;
1454 	reg->frameno = 0;
1455 	reg->precise = !env->bpf_capable;
1456 	__mark_reg_unbounded(reg);
1457 }
1458 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1459 static void mark_reg_unknown(struct bpf_verifier_env *env,
1460 			     struct bpf_reg_state *regs, u32 regno)
1461 {
1462 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1463 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1464 		/* Something bad happened, let's kill all regs except FP */
1465 		for (regno = 0; regno < BPF_REG_FP; regno++)
1466 			__mark_reg_not_init(env, regs + regno);
1467 		return;
1468 	}
1469 	__mark_reg_unknown(env, regs + regno);
1470 }
1471 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1472 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1473 				struct bpf_reg_state *reg)
1474 {
1475 	__mark_reg_unknown(env, reg);
1476 	reg->type = NOT_INIT;
1477 }
1478 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1479 static void mark_reg_not_init(struct bpf_verifier_env *env,
1480 			      struct bpf_reg_state *regs, u32 regno)
1481 {
1482 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1483 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1484 		/* Something bad happened, let's kill all regs except FP */
1485 		for (regno = 0; regno < BPF_REG_FP; regno++)
1486 			__mark_reg_not_init(env, regs + regno);
1487 		return;
1488 	}
1489 	__mark_reg_not_init(env, regs + regno);
1490 }
1491 
mark_btf_ld_reg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum bpf_reg_type reg_type,struct btf * btf,u32 btf_id)1492 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1493 			    struct bpf_reg_state *regs, u32 regno,
1494 			    enum bpf_reg_type reg_type,
1495 			    struct btf *btf, u32 btf_id)
1496 {
1497 	if (reg_type == SCALAR_VALUE) {
1498 		mark_reg_unknown(env, regs, regno);
1499 		return;
1500 	}
1501 	mark_reg_known_zero(env, regs, regno);
1502 	regs[regno].type = PTR_TO_BTF_ID;
1503 	regs[regno].btf = btf;
1504 	regs[regno].btf_id = btf_id;
1505 }
1506 
1507 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1508 static void init_reg_state(struct bpf_verifier_env *env,
1509 			   struct bpf_func_state *state)
1510 {
1511 	struct bpf_reg_state *regs = state->regs;
1512 	int i;
1513 
1514 	for (i = 0; i < MAX_BPF_REG; i++) {
1515 		mark_reg_not_init(env, regs, i);
1516 		regs[i].live = REG_LIVE_NONE;
1517 		regs[i].parent = NULL;
1518 		regs[i].subreg_def = DEF_NOT_SUBREG;
1519 	}
1520 
1521 	/* frame pointer */
1522 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1523 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1524 	regs[BPF_REG_FP].frameno = state->frameno;
1525 }
1526 
1527 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1528 static void init_func_state(struct bpf_verifier_env *env,
1529 			    struct bpf_func_state *state,
1530 			    int callsite, int frameno, int subprogno)
1531 {
1532 	state->callsite = callsite;
1533 	state->frameno = frameno;
1534 	state->subprogno = subprogno;
1535 	init_reg_state(env, state);
1536 }
1537 
1538 /* Similar to push_stack(), but for async callbacks */
push_async_cb(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,int subprog)1539 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1540 						int insn_idx, int prev_insn_idx,
1541 						int subprog)
1542 {
1543 	struct bpf_verifier_stack_elem *elem;
1544 	struct bpf_func_state *frame;
1545 
1546 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1547 	if (!elem)
1548 		goto err;
1549 
1550 	elem->insn_idx = insn_idx;
1551 	elem->prev_insn_idx = prev_insn_idx;
1552 	elem->next = env->head;
1553 	elem->log_pos = env->log.len_used;
1554 	env->head = elem;
1555 	env->stack_size++;
1556 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1557 		verbose(env,
1558 			"The sequence of %d jumps is too complex for async cb.\n",
1559 			env->stack_size);
1560 		goto err;
1561 	}
1562 	/* Unlike push_stack() do not copy_verifier_state().
1563 	 * The caller state doesn't matter.
1564 	 * This is async callback. It starts in a fresh stack.
1565 	 * Initialize it similar to do_check_common().
1566 	 */
1567 	elem->st.branches = 1;
1568 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1569 	if (!frame)
1570 		goto err;
1571 	init_func_state(env, frame,
1572 			BPF_MAIN_FUNC /* callsite */,
1573 			0 /* frameno within this callchain */,
1574 			subprog /* subprog number within this prog */);
1575 	elem->st.frame[0] = frame;
1576 	return &elem->st;
1577 err:
1578 	free_verifier_state(env->cur_state, true);
1579 	env->cur_state = NULL;
1580 	/* pop all elements and return */
1581 	while (!pop_stack(env, NULL, NULL, false));
1582 	return NULL;
1583 }
1584 
1585 
1586 enum reg_arg_type {
1587 	SRC_OP,		/* register is used as source operand */
1588 	DST_OP,		/* register is used as destination operand */
1589 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1590 };
1591 
cmp_subprogs(const void * a,const void * b)1592 static int cmp_subprogs(const void *a, const void *b)
1593 {
1594 	return ((struct bpf_subprog_info *)a)->start -
1595 	       ((struct bpf_subprog_info *)b)->start;
1596 }
1597 
find_subprog(struct bpf_verifier_env * env,int off)1598 static int find_subprog(struct bpf_verifier_env *env, int off)
1599 {
1600 	struct bpf_subprog_info *p;
1601 
1602 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1603 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1604 	if (!p)
1605 		return -ENOENT;
1606 	return p - env->subprog_info;
1607 
1608 }
1609 
add_subprog(struct bpf_verifier_env * env,int off)1610 static int add_subprog(struct bpf_verifier_env *env, int off)
1611 {
1612 	int insn_cnt = env->prog->len;
1613 	int ret;
1614 
1615 	if (off >= insn_cnt || off < 0) {
1616 		verbose(env, "call to invalid destination\n");
1617 		return -EINVAL;
1618 	}
1619 	ret = find_subprog(env, off);
1620 	if (ret >= 0)
1621 		return ret;
1622 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1623 		verbose(env, "too many subprograms\n");
1624 		return -E2BIG;
1625 	}
1626 	/* determine subprog starts. The end is one before the next starts */
1627 	env->subprog_info[env->subprog_cnt++].start = off;
1628 	sort(env->subprog_info, env->subprog_cnt,
1629 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1630 	return env->subprog_cnt - 1;
1631 }
1632 
1633 struct bpf_kfunc_desc {
1634 	struct btf_func_model func_model;
1635 	u32 func_id;
1636 	s32 imm;
1637 };
1638 
1639 #define MAX_KFUNC_DESCS 256
1640 struct bpf_kfunc_desc_tab {
1641 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1642 	u32 nr_descs;
1643 };
1644 
kfunc_desc_cmp_by_id(const void * a,const void * b)1645 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1646 {
1647 	const struct bpf_kfunc_desc *d0 = a;
1648 	const struct bpf_kfunc_desc *d1 = b;
1649 
1650 	/* func_id is not greater than BTF_MAX_TYPE */
1651 	return d0->func_id - d1->func_id;
1652 }
1653 
1654 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id)1655 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1656 {
1657 	struct bpf_kfunc_desc desc = {
1658 		.func_id = func_id,
1659 	};
1660 	struct bpf_kfunc_desc_tab *tab;
1661 
1662 	tab = prog->aux->kfunc_tab;
1663 	return bsearch(&desc, tab->descs, tab->nr_descs,
1664 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1665 }
1666 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id)1667 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1668 {
1669 	const struct btf_type *func, *func_proto;
1670 	struct bpf_kfunc_desc_tab *tab;
1671 	struct bpf_prog_aux *prog_aux;
1672 	struct bpf_kfunc_desc *desc;
1673 	const char *func_name;
1674 	unsigned long addr;
1675 	int err;
1676 
1677 	prog_aux = env->prog->aux;
1678 	tab = prog_aux->kfunc_tab;
1679 	if (!tab) {
1680 		if (!btf_vmlinux) {
1681 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1682 			return -ENOTSUPP;
1683 		}
1684 
1685 		if (!env->prog->jit_requested) {
1686 			verbose(env, "JIT is required for calling kernel function\n");
1687 			return -ENOTSUPP;
1688 		}
1689 
1690 		if (!bpf_jit_supports_kfunc_call()) {
1691 			verbose(env, "JIT does not support calling kernel function\n");
1692 			return -ENOTSUPP;
1693 		}
1694 
1695 		if (!env->prog->gpl_compatible) {
1696 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1697 			return -EINVAL;
1698 		}
1699 
1700 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1701 		if (!tab)
1702 			return -ENOMEM;
1703 		prog_aux->kfunc_tab = tab;
1704 	}
1705 
1706 	if (find_kfunc_desc(env->prog, func_id))
1707 		return 0;
1708 
1709 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1710 		verbose(env, "too many different kernel function calls\n");
1711 		return -E2BIG;
1712 	}
1713 
1714 	func = btf_type_by_id(btf_vmlinux, func_id);
1715 	if (!func || !btf_type_is_func(func)) {
1716 		verbose(env, "kernel btf_id %u is not a function\n",
1717 			func_id);
1718 		return -EINVAL;
1719 	}
1720 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
1721 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1722 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1723 			func_id);
1724 		return -EINVAL;
1725 	}
1726 
1727 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1728 	addr = kallsyms_lookup_name(func_name);
1729 	if (!addr) {
1730 		verbose(env, "cannot find address for kernel function %s\n",
1731 			func_name);
1732 		return -EINVAL;
1733 	}
1734 
1735 	desc = &tab->descs[tab->nr_descs++];
1736 	desc->func_id = func_id;
1737 	desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1738 	err = btf_distill_func_proto(&env->log, btf_vmlinux,
1739 				     func_proto, func_name,
1740 				     &desc->func_model);
1741 	if (!err)
1742 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1743 		     kfunc_desc_cmp_by_id, NULL);
1744 	return err;
1745 }
1746 
kfunc_desc_cmp_by_imm(const void * a,const void * b)1747 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1748 {
1749 	const struct bpf_kfunc_desc *d0 = a;
1750 	const struct bpf_kfunc_desc *d1 = b;
1751 
1752 	if (d0->imm > d1->imm)
1753 		return 1;
1754 	else if (d0->imm < d1->imm)
1755 		return -1;
1756 	return 0;
1757 }
1758 
sort_kfunc_descs_by_imm(struct bpf_prog * prog)1759 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1760 {
1761 	struct bpf_kfunc_desc_tab *tab;
1762 
1763 	tab = prog->aux->kfunc_tab;
1764 	if (!tab)
1765 		return;
1766 
1767 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1768 	     kfunc_desc_cmp_by_imm, NULL);
1769 }
1770 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)1771 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1772 {
1773 	return !!prog->aux->kfunc_tab;
1774 }
1775 
1776 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)1777 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1778 			 const struct bpf_insn *insn)
1779 {
1780 	const struct bpf_kfunc_desc desc = {
1781 		.imm = insn->imm,
1782 	};
1783 	const struct bpf_kfunc_desc *res;
1784 	struct bpf_kfunc_desc_tab *tab;
1785 
1786 	tab = prog->aux->kfunc_tab;
1787 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1788 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1789 
1790 	return res ? &res->func_model : NULL;
1791 }
1792 
add_subprog_and_kfunc(struct bpf_verifier_env * env)1793 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1794 {
1795 	struct bpf_subprog_info *subprog = env->subprog_info;
1796 	struct bpf_insn *insn = env->prog->insnsi;
1797 	int i, ret, insn_cnt = env->prog->len;
1798 
1799 	/* Add entry function. */
1800 	ret = add_subprog(env, 0);
1801 	if (ret)
1802 		return ret;
1803 
1804 	for (i = 0; i < insn_cnt; i++, insn++) {
1805 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1806 		    !bpf_pseudo_kfunc_call(insn))
1807 			continue;
1808 
1809 		if (!env->bpf_capable) {
1810 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1811 			return -EPERM;
1812 		}
1813 
1814 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
1815 			ret = add_subprog(env, i + insn->imm + 1);
1816 		else
1817 			ret = add_kfunc_call(env, insn->imm);
1818 
1819 		if (ret < 0)
1820 			return ret;
1821 	}
1822 
1823 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1824 	 * logic. 'subprog_cnt' should not be increased.
1825 	 */
1826 	subprog[env->subprog_cnt].start = insn_cnt;
1827 
1828 	if (env->log.level & BPF_LOG_LEVEL2)
1829 		for (i = 0; i < env->subprog_cnt; i++)
1830 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1831 
1832 	return 0;
1833 }
1834 
check_subprogs(struct bpf_verifier_env * env)1835 static int check_subprogs(struct bpf_verifier_env *env)
1836 {
1837 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1838 	struct bpf_subprog_info *subprog = env->subprog_info;
1839 	struct bpf_insn *insn = env->prog->insnsi;
1840 	int insn_cnt = env->prog->len;
1841 
1842 	/* now check that all jumps are within the same subprog */
1843 	subprog_start = subprog[cur_subprog].start;
1844 	subprog_end = subprog[cur_subprog + 1].start;
1845 	for (i = 0; i < insn_cnt; i++) {
1846 		u8 code = insn[i].code;
1847 
1848 		if (code == (BPF_JMP | BPF_CALL) &&
1849 		    insn[i].imm == BPF_FUNC_tail_call &&
1850 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1851 			subprog[cur_subprog].has_tail_call = true;
1852 		if (BPF_CLASS(code) == BPF_LD &&
1853 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1854 			subprog[cur_subprog].has_ld_abs = true;
1855 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1856 			goto next;
1857 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1858 			goto next;
1859 		off = i + insn[i].off + 1;
1860 		if (off < subprog_start || off >= subprog_end) {
1861 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1862 			return -EINVAL;
1863 		}
1864 next:
1865 		if (i == subprog_end - 1) {
1866 			/* to avoid fall-through from one subprog into another
1867 			 * the last insn of the subprog should be either exit
1868 			 * or unconditional jump back
1869 			 */
1870 			if (code != (BPF_JMP | BPF_EXIT) &&
1871 			    code != (BPF_JMP | BPF_JA)) {
1872 				verbose(env, "last insn is not an exit or jmp\n");
1873 				return -EINVAL;
1874 			}
1875 			subprog_start = subprog_end;
1876 			cur_subprog++;
1877 			if (cur_subprog < env->subprog_cnt)
1878 				subprog_end = subprog[cur_subprog + 1].start;
1879 		}
1880 	}
1881 	return 0;
1882 }
1883 
1884 /* Parentage chain of this register (or stack slot) should take care of all
1885  * issues like callee-saved registers, stack slot allocation time, etc.
1886  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1887 static int mark_reg_read(struct bpf_verifier_env *env,
1888 			 const struct bpf_reg_state *state,
1889 			 struct bpf_reg_state *parent, u8 flag)
1890 {
1891 	bool writes = parent == state->parent; /* Observe write marks */
1892 	int cnt = 0;
1893 
1894 	while (parent) {
1895 		/* if read wasn't screened by an earlier write ... */
1896 		if (writes && state->live & REG_LIVE_WRITTEN)
1897 			break;
1898 		if (parent->live & REG_LIVE_DONE) {
1899 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1900 				reg_type_str(env, parent->type),
1901 				parent->var_off.value, parent->off);
1902 			return -EFAULT;
1903 		}
1904 		/* The first condition is more likely to be true than the
1905 		 * second, checked it first.
1906 		 */
1907 		if ((parent->live & REG_LIVE_READ) == flag ||
1908 		    parent->live & REG_LIVE_READ64)
1909 			/* The parentage chain never changes and
1910 			 * this parent was already marked as LIVE_READ.
1911 			 * There is no need to keep walking the chain again and
1912 			 * keep re-marking all parents as LIVE_READ.
1913 			 * This case happens when the same register is read
1914 			 * multiple times without writes into it in-between.
1915 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1916 			 * then no need to set the weak REG_LIVE_READ32.
1917 			 */
1918 			break;
1919 		/* ... then we depend on parent's value */
1920 		parent->live |= flag;
1921 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1922 		if (flag == REG_LIVE_READ64)
1923 			parent->live &= ~REG_LIVE_READ32;
1924 		state = parent;
1925 		parent = state->parent;
1926 		writes = true;
1927 		cnt++;
1928 	}
1929 
1930 	if (env->longest_mark_read_walk < cnt)
1931 		env->longest_mark_read_walk = cnt;
1932 	return 0;
1933 }
1934 
1935 /* This function is supposed to be used by the following 32-bit optimization
1936  * code only. It returns TRUE if the source or destination register operates
1937  * on 64-bit, otherwise return FALSE.
1938  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1939 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1940 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1941 {
1942 	u8 code, class, op;
1943 
1944 	code = insn->code;
1945 	class = BPF_CLASS(code);
1946 	op = BPF_OP(code);
1947 	if (class == BPF_JMP) {
1948 		/* BPF_EXIT for "main" will reach here. Return TRUE
1949 		 * conservatively.
1950 		 */
1951 		if (op == BPF_EXIT)
1952 			return true;
1953 		if (op == BPF_CALL) {
1954 			/* BPF to BPF call will reach here because of marking
1955 			 * caller saved clobber with DST_OP_NO_MARK for which we
1956 			 * don't care the register def because they are anyway
1957 			 * marked as NOT_INIT already.
1958 			 */
1959 			if (insn->src_reg == BPF_PSEUDO_CALL)
1960 				return false;
1961 			/* Helper call will reach here because of arg type
1962 			 * check, conservatively return TRUE.
1963 			 */
1964 			if (t == SRC_OP)
1965 				return true;
1966 
1967 			return false;
1968 		}
1969 	}
1970 
1971 	if (class == BPF_ALU64 || class == BPF_JMP ||
1972 	    /* BPF_END always use BPF_ALU class. */
1973 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1974 		return true;
1975 
1976 	if (class == BPF_ALU || class == BPF_JMP32)
1977 		return false;
1978 
1979 	if (class == BPF_LDX) {
1980 		if (t != SRC_OP)
1981 			return BPF_SIZE(code) == BPF_DW;
1982 		/* LDX source must be ptr. */
1983 		return true;
1984 	}
1985 
1986 	if (class == BPF_STX) {
1987 		/* BPF_STX (including atomic variants) has multiple source
1988 		 * operands, one of which is a ptr. Check whether the caller is
1989 		 * asking about it.
1990 		 */
1991 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
1992 			return true;
1993 		return BPF_SIZE(code) == BPF_DW;
1994 	}
1995 
1996 	if (class == BPF_LD) {
1997 		u8 mode = BPF_MODE(code);
1998 
1999 		/* LD_IMM64 */
2000 		if (mode == BPF_IMM)
2001 			return true;
2002 
2003 		/* Both LD_IND and LD_ABS return 32-bit data. */
2004 		if (t != SRC_OP)
2005 			return  false;
2006 
2007 		/* Implicit ctx ptr. */
2008 		if (regno == BPF_REG_6)
2009 			return true;
2010 
2011 		/* Explicit source could be any width. */
2012 		return true;
2013 	}
2014 
2015 	if (class == BPF_ST)
2016 		/* The only source register for BPF_ST is a ptr. */
2017 		return true;
2018 
2019 	/* Conservatively return true at default. */
2020 	return true;
2021 }
2022 
2023 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)2024 static int insn_def_regno(const struct bpf_insn *insn)
2025 {
2026 	switch (BPF_CLASS(insn->code)) {
2027 	case BPF_JMP:
2028 	case BPF_JMP32:
2029 	case BPF_ST:
2030 		return -1;
2031 	case BPF_STX:
2032 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2033 		    (insn->imm & BPF_FETCH)) {
2034 			if (insn->imm == BPF_CMPXCHG)
2035 				return BPF_REG_0;
2036 			else
2037 				return insn->src_reg;
2038 		} else {
2039 			return -1;
2040 		}
2041 	default:
2042 		return insn->dst_reg;
2043 	}
2044 }
2045 
2046 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)2047 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2048 {
2049 	int dst_reg = insn_def_regno(insn);
2050 
2051 	if (dst_reg == -1)
2052 		return false;
2053 
2054 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2055 }
2056 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)2057 static void mark_insn_zext(struct bpf_verifier_env *env,
2058 			   struct bpf_reg_state *reg)
2059 {
2060 	s32 def_idx = reg->subreg_def;
2061 
2062 	if (def_idx == DEF_NOT_SUBREG)
2063 		return;
2064 
2065 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2066 	/* The dst will be zero extended, so won't be sub-register anymore. */
2067 	reg->subreg_def = DEF_NOT_SUBREG;
2068 }
2069 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)2070 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2071 			 enum reg_arg_type t)
2072 {
2073 	struct bpf_verifier_state *vstate = env->cur_state;
2074 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2075 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2076 	struct bpf_reg_state *reg, *regs = state->regs;
2077 	bool rw64;
2078 
2079 	if (regno >= MAX_BPF_REG) {
2080 		verbose(env, "R%d is invalid\n", regno);
2081 		return -EINVAL;
2082 	}
2083 
2084 	reg = &regs[regno];
2085 	rw64 = is_reg64(env, insn, regno, reg, t);
2086 	if (t == SRC_OP) {
2087 		/* check whether register used as source operand can be read */
2088 		if (reg->type == NOT_INIT) {
2089 			verbose(env, "R%d !read_ok\n", regno);
2090 			return -EACCES;
2091 		}
2092 		/* We don't need to worry about FP liveness because it's read-only */
2093 		if (regno == BPF_REG_FP)
2094 			return 0;
2095 
2096 		if (rw64)
2097 			mark_insn_zext(env, reg);
2098 
2099 		return mark_reg_read(env, reg, reg->parent,
2100 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2101 	} else {
2102 		/* check whether register used as dest operand can be written to */
2103 		if (regno == BPF_REG_FP) {
2104 			verbose(env, "frame pointer is read only\n");
2105 			return -EACCES;
2106 		}
2107 		reg->live |= REG_LIVE_WRITTEN;
2108 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2109 		if (t == DST_OP)
2110 			mark_reg_unknown(env, regs, regno);
2111 	}
2112 	return 0;
2113 }
2114 
2115 /* 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)2116 static int push_jmp_history(struct bpf_verifier_env *env,
2117 			    struct bpf_verifier_state *cur)
2118 {
2119 	u32 cnt = cur->jmp_history_cnt;
2120 	struct bpf_idx_pair *p;
2121 
2122 	cnt++;
2123 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2124 	if (!p)
2125 		return -ENOMEM;
2126 	p[cnt - 1].idx = env->insn_idx;
2127 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2128 	cur->jmp_history = p;
2129 	cur->jmp_history_cnt = cnt;
2130 	return 0;
2131 }
2132 
2133 /* Backtrack one insn at a time. If idx is not at the top of recorded
2134  * history then previous instruction came from straight line execution.
2135  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)2136 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2137 			     u32 *history)
2138 {
2139 	u32 cnt = *history;
2140 
2141 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2142 		i = st->jmp_history[cnt - 1].prev_idx;
2143 		(*history)--;
2144 	} else {
2145 		i--;
2146 	}
2147 	return i;
2148 }
2149 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)2150 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2151 {
2152 	const struct btf_type *func;
2153 
2154 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2155 		return NULL;
2156 
2157 	func = btf_type_by_id(btf_vmlinux, insn->imm);
2158 	return btf_name_by_offset(btf_vmlinux, func->name_off);
2159 }
2160 
2161 /* For given verifier state backtrack_insn() is called from the last insn to
2162  * the first insn. Its purpose is to compute a bitmask of registers and
2163  * stack slots that needs precision in the parent verifier state.
2164  */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)2165 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2166 			  u32 *reg_mask, u64 *stack_mask)
2167 {
2168 	const struct bpf_insn_cbs cbs = {
2169 		.cb_call	= disasm_kfunc_name,
2170 		.cb_print	= verbose,
2171 		.private_data	= env,
2172 	};
2173 	struct bpf_insn *insn = env->prog->insnsi + idx;
2174 	u8 class = BPF_CLASS(insn->code);
2175 	u8 opcode = BPF_OP(insn->code);
2176 	u8 mode = BPF_MODE(insn->code);
2177 	u32 dreg = 1u << insn->dst_reg;
2178 	u32 sreg = 1u << insn->src_reg;
2179 	u32 spi;
2180 
2181 	if (insn->code == 0)
2182 		return 0;
2183 	if (env->log.level & BPF_LOG_LEVEL) {
2184 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2185 		verbose(env, "%d: ", idx);
2186 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2187 	}
2188 
2189 	if (class == BPF_ALU || class == BPF_ALU64) {
2190 		if (!(*reg_mask & dreg))
2191 			return 0;
2192 		if (opcode == BPF_END || opcode == BPF_NEG) {
2193 			/* sreg is reserved and unused
2194 			 * dreg still need precision before this insn
2195 			 */
2196 			return 0;
2197 		} else if (opcode == BPF_MOV) {
2198 			if (BPF_SRC(insn->code) == BPF_X) {
2199 				/* dreg = sreg
2200 				 * dreg needs precision after this insn
2201 				 * sreg needs precision before this insn
2202 				 */
2203 				*reg_mask &= ~dreg;
2204 				*reg_mask |= sreg;
2205 			} else {
2206 				/* dreg = K
2207 				 * dreg needs precision after this insn.
2208 				 * Corresponding register is already marked
2209 				 * as precise=true in this verifier state.
2210 				 * No further markings in parent are necessary
2211 				 */
2212 				*reg_mask &= ~dreg;
2213 			}
2214 		} else {
2215 			if (BPF_SRC(insn->code) == BPF_X) {
2216 				/* dreg += sreg
2217 				 * both dreg and sreg need precision
2218 				 * before this insn
2219 				 */
2220 				*reg_mask |= sreg;
2221 			} /* else dreg += K
2222 			   * dreg still needs precision before this insn
2223 			   */
2224 		}
2225 	} else if (class == BPF_LDX) {
2226 		if (!(*reg_mask & dreg))
2227 			return 0;
2228 		*reg_mask &= ~dreg;
2229 
2230 		/* scalars can only be spilled into stack w/o losing precision.
2231 		 * Load from any other memory can be zero extended.
2232 		 * The desire to keep that precision is already indicated
2233 		 * by 'precise' mark in corresponding register of this state.
2234 		 * No further tracking necessary.
2235 		 */
2236 		if (insn->src_reg != BPF_REG_FP)
2237 			return 0;
2238 
2239 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2240 		 * that [fp - off] slot contains scalar that needs to be
2241 		 * tracked with precision
2242 		 */
2243 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2244 		if (spi >= 64) {
2245 			verbose(env, "BUG spi %d\n", spi);
2246 			WARN_ONCE(1, "verifier backtracking bug");
2247 			return -EFAULT;
2248 		}
2249 		*stack_mask |= 1ull << spi;
2250 	} else if (class == BPF_STX || class == BPF_ST) {
2251 		if (*reg_mask & dreg)
2252 			/* stx & st shouldn't be using _scalar_ dst_reg
2253 			 * to access memory. It means backtracking
2254 			 * encountered a case of pointer subtraction.
2255 			 */
2256 			return -ENOTSUPP;
2257 		/* scalars can only be spilled into stack */
2258 		if (insn->dst_reg != BPF_REG_FP)
2259 			return 0;
2260 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2261 		if (spi >= 64) {
2262 			verbose(env, "BUG spi %d\n", spi);
2263 			WARN_ONCE(1, "verifier backtracking bug");
2264 			return -EFAULT;
2265 		}
2266 		if (!(*stack_mask & (1ull << spi)))
2267 			return 0;
2268 		*stack_mask &= ~(1ull << spi);
2269 		if (class == BPF_STX)
2270 			*reg_mask |= sreg;
2271 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2272 		if (opcode == BPF_CALL) {
2273 			if (insn->src_reg == BPF_PSEUDO_CALL)
2274 				return -ENOTSUPP;
2275 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
2276 			 * catch this error later. Make backtracking conservative
2277 			 * with ENOTSUPP.
2278 			 */
2279 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2280 				return -ENOTSUPP;
2281 			/* BPF helpers that invoke callback subprogs are
2282 			 * equivalent to BPF_PSEUDO_CALL above
2283 			 */
2284 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2285 				return -ENOTSUPP;
2286 			/* regular helper call sets R0 */
2287 			*reg_mask &= ~1;
2288 			if (*reg_mask & 0x3f) {
2289 				/* if backtracing was looking for registers R1-R5
2290 				 * they should have been found already.
2291 				 */
2292 				verbose(env, "BUG regs %x\n", *reg_mask);
2293 				WARN_ONCE(1, "verifier backtracking bug");
2294 				return -EFAULT;
2295 			}
2296 		} else if (opcode == BPF_EXIT) {
2297 			return -ENOTSUPP;
2298 		} else if (BPF_SRC(insn->code) == BPF_X) {
2299 			if (!(*reg_mask & (dreg | sreg)))
2300 				return 0;
2301 			/* dreg <cond> sreg
2302 			 * Both dreg and sreg need precision before
2303 			 * this insn. If only sreg was marked precise
2304 			 * before it would be equally necessary to
2305 			 * propagate it to dreg.
2306 			 */
2307 			*reg_mask |= (sreg | dreg);
2308 			 /* else dreg <cond> K
2309 			  * Only dreg still needs precision before
2310 			  * this insn, so for the K-based conditional
2311 			  * there is nothing new to be marked.
2312 			  */
2313 		}
2314 	} else if (class == BPF_LD) {
2315 		if (!(*reg_mask & dreg))
2316 			return 0;
2317 		*reg_mask &= ~dreg;
2318 		/* It's ld_imm64 or ld_abs or ld_ind.
2319 		 * For ld_imm64 no further tracking of precision
2320 		 * into parent is necessary
2321 		 */
2322 		if (mode == BPF_IND || mode == BPF_ABS)
2323 			/* to be analyzed */
2324 			return -ENOTSUPP;
2325 	}
2326 	return 0;
2327 }
2328 
2329 /* the scalar precision tracking algorithm:
2330  * . at the start all registers have precise=false.
2331  * . scalar ranges are tracked as normal through alu and jmp insns.
2332  * . once precise value of the scalar register is used in:
2333  *   .  ptr + scalar alu
2334  *   . if (scalar cond K|scalar)
2335  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2336  *   backtrack through the verifier states and mark all registers and
2337  *   stack slots with spilled constants that these scalar regisers
2338  *   should be precise.
2339  * . during state pruning two registers (or spilled stack slots)
2340  *   are equivalent if both are not precise.
2341  *
2342  * Note the verifier cannot simply walk register parentage chain,
2343  * since many different registers and stack slots could have been
2344  * used to compute single precise scalar.
2345  *
2346  * The approach of starting with precise=true for all registers and then
2347  * backtrack to mark a register as not precise when the verifier detects
2348  * that program doesn't care about specific value (e.g., when helper
2349  * takes register as ARG_ANYTHING parameter) is not safe.
2350  *
2351  * It's ok to walk single parentage chain of the verifier states.
2352  * It's possible that this backtracking will go all the way till 1st insn.
2353  * All other branches will be explored for needing precision later.
2354  *
2355  * The backtracking needs to deal with cases like:
2356  *   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)
2357  * r9 -= r8
2358  * r5 = r9
2359  * if r5 > 0x79f goto pc+7
2360  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2361  * r5 += 1
2362  * ...
2363  * call bpf_perf_event_output#25
2364  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2365  *
2366  * and this case:
2367  * r6 = 1
2368  * call foo // uses callee's r6 inside to compute r0
2369  * r0 += r6
2370  * if r0 == 0 goto
2371  *
2372  * to track above reg_mask/stack_mask needs to be independent for each frame.
2373  *
2374  * Also if parent's curframe > frame where backtracking started,
2375  * the verifier need to mark registers in both frames, otherwise callees
2376  * may incorrectly prune callers. This is similar to
2377  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2378  *
2379  * For now backtracking falls back into conservative marking.
2380  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2381 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2382 				     struct bpf_verifier_state *st)
2383 {
2384 	struct bpf_func_state *func;
2385 	struct bpf_reg_state *reg;
2386 	int i, j;
2387 
2388 	/* big hammer: mark all scalars precise in this path.
2389 	 * pop_stack may still get !precise scalars.
2390 	 * We also skip current state and go straight to first parent state,
2391 	 * because precision markings in current non-checkpointed state are
2392 	 * not needed. See why in the comment in __mark_chain_precision below.
2393 	 */
2394 	for (st = st->parent; st; st = st->parent) {
2395 		for (i = 0; i <= st->curframe; i++) {
2396 			func = st->frame[i];
2397 			for (j = 0; j < BPF_REG_FP; j++) {
2398 				reg = &func->regs[j];
2399 				if (reg->type != SCALAR_VALUE)
2400 					continue;
2401 				reg->precise = true;
2402 			}
2403 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2404 				if (!is_spilled_reg(&func->stack[j]))
2405 					continue;
2406 				reg = &func->stack[j].spilled_ptr;
2407 				if (reg->type != SCALAR_VALUE)
2408 					continue;
2409 				reg->precise = true;
2410 			}
2411 		}
2412 	}
2413 }
2414 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2415 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2416 {
2417 	struct bpf_func_state *func;
2418 	struct bpf_reg_state *reg;
2419 	int i, j;
2420 
2421 	for (i = 0; i <= st->curframe; i++) {
2422 		func = st->frame[i];
2423 		for (j = 0; j < BPF_REG_FP; j++) {
2424 			reg = &func->regs[j];
2425 			if (reg->type != SCALAR_VALUE)
2426 				continue;
2427 			reg->precise = false;
2428 		}
2429 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2430 			if (!is_spilled_reg(&func->stack[j]))
2431 				continue;
2432 			reg = &func->stack[j].spilled_ptr;
2433 			if (reg->type != SCALAR_VALUE)
2434 				continue;
2435 			reg->precise = false;
2436 		}
2437 	}
2438 }
2439 
2440 /*
2441  * __mark_chain_precision() backtracks BPF program instruction sequence and
2442  * chain of verifier states making sure that register *regno* (if regno >= 0)
2443  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2444  * SCALARS, as well as any other registers and slots that contribute to
2445  * a tracked state of given registers/stack slots, depending on specific BPF
2446  * assembly instructions (see backtrack_insns() for exact instruction handling
2447  * logic). This backtracking relies on recorded jmp_history and is able to
2448  * traverse entire chain of parent states. This process ends only when all the
2449  * necessary registers/slots and their transitive dependencies are marked as
2450  * precise.
2451  *
2452  * One important and subtle aspect is that precise marks *do not matter* in
2453  * the currently verified state (current state). It is important to understand
2454  * why this is the case.
2455  *
2456  * First, note that current state is the state that is not yet "checkpointed",
2457  * i.e., it is not yet put into env->explored_states, and it has no children
2458  * states as well. It's ephemeral, and can end up either a) being discarded if
2459  * compatible explored state is found at some point or BPF_EXIT instruction is
2460  * reached or b) checkpointed and put into env->explored_states, branching out
2461  * into one or more children states.
2462  *
2463  * In the former case, precise markings in current state are completely
2464  * ignored by state comparison code (see regsafe() for details). Only
2465  * checkpointed ("old") state precise markings are important, and if old
2466  * state's register/slot is precise, regsafe() assumes current state's
2467  * register/slot as precise and checks value ranges exactly and precisely. If
2468  * states turn out to be compatible, current state's necessary precise
2469  * markings and any required parent states' precise markings are enforced
2470  * after the fact with propagate_precision() logic, after the fact. But it's
2471  * important to realize that in this case, even after marking current state
2472  * registers/slots as precise, we immediately discard current state. So what
2473  * actually matters is any of the precise markings propagated into current
2474  * state's parent states, which are always checkpointed (due to b) case above).
2475  * As such, for scenario a) it doesn't matter if current state has precise
2476  * markings set or not.
2477  *
2478  * Now, for the scenario b), checkpointing and forking into child(ren)
2479  * state(s). Note that before current state gets to checkpointing step, any
2480  * processed instruction always assumes precise SCALAR register/slot
2481  * knowledge: if precise value or range is useful to prune jump branch, BPF
2482  * verifier takes this opportunity enthusiastically. Similarly, when
2483  * register's value is used to calculate offset or memory address, exact
2484  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2485  * what we mentioned above about state comparison ignoring precise markings
2486  * during state comparison, BPF verifier ignores and also assumes precise
2487  * markings *at will* during instruction verification process. But as verifier
2488  * assumes precision, it also propagates any precision dependencies across
2489  * parent states, which are not yet finalized, so can be further restricted
2490  * based on new knowledge gained from restrictions enforced by their children
2491  * states. This is so that once those parent states are finalized, i.e., when
2492  * they have no more active children state, state comparison logic in
2493  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2494  * required for correctness.
2495  *
2496  * To build a bit more intuition, note also that once a state is checkpointed,
2497  * the path we took to get to that state is not important. This is crucial
2498  * property for state pruning. When state is checkpointed and finalized at
2499  * some instruction index, it can be correctly and safely used to "short
2500  * circuit" any *compatible* state that reaches exactly the same instruction
2501  * index. I.e., if we jumped to that instruction from a completely different
2502  * code path than original finalized state was derived from, it doesn't
2503  * matter, current state can be discarded because from that instruction
2504  * forward having a compatible state will ensure we will safely reach the
2505  * exit. States describe preconditions for further exploration, but completely
2506  * forget the history of how we got here.
2507  *
2508  * This also means that even if we needed precise SCALAR range to get to
2509  * finalized state, but from that point forward *that same* SCALAR register is
2510  * never used in a precise context (i.e., it's precise value is not needed for
2511  * correctness), it's correct and safe to mark such register as "imprecise"
2512  * (i.e., precise marking set to false). This is what we rely on when we do
2513  * not set precise marking in current state. If no child state requires
2514  * precision for any given SCALAR register, it's safe to dictate that it can
2515  * be imprecise. If any child state does require this register to be precise,
2516  * we'll mark it precise later retroactively during precise markings
2517  * propagation from child state to parent states.
2518  *
2519  * Skipping precise marking setting in current state is a mild version of
2520  * relying on the above observation. But we can utilize this property even
2521  * more aggressively by proactively forgetting any precise marking in the
2522  * current state (which we inherited from the parent state), right before we
2523  * checkpoint it and branch off into new child state. This is done by
2524  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2525  * finalized states which help in short circuiting more future states.
2526  */
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2527 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2528 				  int spi)
2529 {
2530 	struct bpf_verifier_state *st = env->cur_state;
2531 	int first_idx = st->first_insn_idx;
2532 	int last_idx = env->insn_idx;
2533 	struct bpf_func_state *func;
2534 	struct bpf_reg_state *reg;
2535 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2536 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2537 	bool skip_first = true;
2538 	bool new_marks = false;
2539 	int i, err;
2540 
2541 	if (!env->bpf_capable)
2542 		return 0;
2543 
2544 	/* Do sanity checks against current state of register and/or stack
2545 	 * slot, but don't set precise flag in current state, as precision
2546 	 * tracking in the current state is unnecessary.
2547 	 */
2548 	func = st->frame[frame];
2549 	if (regno >= 0) {
2550 		reg = &func->regs[regno];
2551 		if (reg->type != SCALAR_VALUE) {
2552 			WARN_ONCE(1, "backtracing misuse");
2553 			return -EFAULT;
2554 		}
2555 		new_marks = true;
2556 	}
2557 
2558 	while (spi >= 0) {
2559 		if (!is_spilled_reg(&func->stack[spi])) {
2560 			stack_mask = 0;
2561 			break;
2562 		}
2563 		reg = &func->stack[spi].spilled_ptr;
2564 		if (reg->type != SCALAR_VALUE) {
2565 			stack_mask = 0;
2566 			break;
2567 		}
2568 		new_marks = true;
2569 		break;
2570 	}
2571 
2572 	if (!new_marks)
2573 		return 0;
2574 	if (!reg_mask && !stack_mask)
2575 		return 0;
2576 
2577 	for (;;) {
2578 		DECLARE_BITMAP(mask, 64);
2579 		u32 history = st->jmp_history_cnt;
2580 
2581 		if (env->log.level & BPF_LOG_LEVEL)
2582 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2583 
2584 		if (last_idx < 0) {
2585 			/* we are at the entry into subprog, which
2586 			 * is expected for global funcs, but only if
2587 			 * requested precise registers are R1-R5
2588 			 * (which are global func's input arguments)
2589 			 */
2590 			if (st->curframe == 0 &&
2591 			    st->frame[0]->subprogno > 0 &&
2592 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
2593 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2594 				bitmap_from_u64(mask, reg_mask);
2595 				for_each_set_bit(i, mask, 32) {
2596 					reg = &st->frame[0]->regs[i];
2597 					if (reg->type != SCALAR_VALUE) {
2598 						reg_mask &= ~(1u << i);
2599 						continue;
2600 					}
2601 					reg->precise = true;
2602 				}
2603 				return 0;
2604 			}
2605 
2606 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2607 				st->frame[0]->subprogno, reg_mask, stack_mask);
2608 			WARN_ONCE(1, "verifier backtracking bug");
2609 			return -EFAULT;
2610 		}
2611 
2612 		for (i = last_idx;;) {
2613 			if (skip_first) {
2614 				err = 0;
2615 				skip_first = false;
2616 			} else {
2617 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2618 			}
2619 			if (err == -ENOTSUPP) {
2620 				mark_all_scalars_precise(env, st);
2621 				return 0;
2622 			} else if (err) {
2623 				return err;
2624 			}
2625 			if (!reg_mask && !stack_mask)
2626 				/* Found assignment(s) into tracked register in this state.
2627 				 * Since this state is already marked, just return.
2628 				 * Nothing to be tracked further in the parent state.
2629 				 */
2630 				return 0;
2631 			if (i == first_idx)
2632 				break;
2633 			i = get_prev_insn_idx(st, i, &history);
2634 			if (i >= env->prog->len) {
2635 				/* This can happen if backtracking reached insn 0
2636 				 * and there are still reg_mask or stack_mask
2637 				 * to backtrack.
2638 				 * It means the backtracking missed the spot where
2639 				 * particular register was initialized with a constant.
2640 				 */
2641 				verbose(env, "BUG backtracking idx %d\n", i);
2642 				WARN_ONCE(1, "verifier backtracking bug");
2643 				return -EFAULT;
2644 			}
2645 		}
2646 		st = st->parent;
2647 		if (!st)
2648 			break;
2649 
2650 		new_marks = false;
2651 		func = st->frame[frame];
2652 		bitmap_from_u64(mask, reg_mask);
2653 		for_each_set_bit(i, mask, 32) {
2654 			reg = &func->regs[i];
2655 			if (reg->type != SCALAR_VALUE) {
2656 				reg_mask &= ~(1u << i);
2657 				continue;
2658 			}
2659 			if (!reg->precise)
2660 				new_marks = true;
2661 			reg->precise = true;
2662 		}
2663 
2664 		bitmap_from_u64(mask, stack_mask);
2665 		for_each_set_bit(i, mask, 64) {
2666 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2667 				/* the sequence of instructions:
2668 				 * 2: (bf) r3 = r10
2669 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2670 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2671 				 * doesn't contain jmps. It's backtracked
2672 				 * as a single block.
2673 				 * During backtracking insn 3 is not recognized as
2674 				 * stack access, so at the end of backtracking
2675 				 * stack slot fp-8 is still marked in stack_mask.
2676 				 * However the parent state may not have accessed
2677 				 * fp-8 and it's "unallocated" stack space.
2678 				 * In such case fallback to conservative.
2679 				 */
2680 				mark_all_scalars_precise(env, st);
2681 				return 0;
2682 			}
2683 
2684 			if (!is_spilled_reg(&func->stack[i])) {
2685 				stack_mask &= ~(1ull << i);
2686 				continue;
2687 			}
2688 			reg = &func->stack[i].spilled_ptr;
2689 			if (reg->type != SCALAR_VALUE) {
2690 				stack_mask &= ~(1ull << i);
2691 				continue;
2692 			}
2693 			if (!reg->precise)
2694 				new_marks = true;
2695 			reg->precise = true;
2696 		}
2697 		if (env->log.level & BPF_LOG_LEVEL) {
2698 			print_verifier_state(env, func);
2699 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2700 				new_marks ? "didn't have" : "already had",
2701 				reg_mask, stack_mask);
2702 		}
2703 
2704 		if (!reg_mask && !stack_mask)
2705 			break;
2706 		if (!new_marks)
2707 			break;
2708 
2709 		last_idx = st->last_insn_idx;
2710 		first_idx = st->first_insn_idx;
2711 	}
2712 	return 0;
2713 }
2714 
mark_chain_precision(struct bpf_verifier_env * env,int regno)2715 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2716 {
2717 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2718 }
2719 
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2720 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2721 {
2722 	return __mark_chain_precision(env, frame, regno, -1);
2723 }
2724 
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2725 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2726 {
2727 	return __mark_chain_precision(env, frame, -1, spi);
2728 }
2729 
is_spillable_regtype(enum bpf_reg_type type)2730 static bool is_spillable_regtype(enum bpf_reg_type type)
2731 {
2732 	switch (base_type(type)) {
2733 	case PTR_TO_MAP_VALUE:
2734 	case PTR_TO_STACK:
2735 	case PTR_TO_CTX:
2736 	case PTR_TO_PACKET:
2737 	case PTR_TO_PACKET_META:
2738 	case PTR_TO_PACKET_END:
2739 	case PTR_TO_FLOW_KEYS:
2740 	case CONST_PTR_TO_MAP:
2741 	case PTR_TO_SOCKET:
2742 	case PTR_TO_SOCK_COMMON:
2743 	case PTR_TO_TCP_SOCK:
2744 	case PTR_TO_XDP_SOCK:
2745 	case PTR_TO_BTF_ID:
2746 	case PTR_TO_BUF:
2747 	case PTR_TO_PERCPU_BTF_ID:
2748 	case PTR_TO_MEM:
2749 	case PTR_TO_FUNC:
2750 	case PTR_TO_MAP_KEY:
2751 		return true;
2752 	default:
2753 		return false;
2754 	}
2755 }
2756 
2757 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2758 static bool register_is_null(struct bpf_reg_state *reg)
2759 {
2760 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2761 }
2762 
register_is_const(struct bpf_reg_state * reg)2763 static bool register_is_const(struct bpf_reg_state *reg)
2764 {
2765 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2766 }
2767 
__is_scalar_unbounded(struct bpf_reg_state * reg)2768 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2769 {
2770 	return tnum_is_unknown(reg->var_off) &&
2771 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2772 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2773 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2774 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2775 }
2776 
register_is_bounded(struct bpf_reg_state * reg)2777 static bool register_is_bounded(struct bpf_reg_state *reg)
2778 {
2779 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2780 }
2781 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)2782 static bool __is_pointer_value(bool allow_ptr_leaks,
2783 			       const struct bpf_reg_state *reg)
2784 {
2785 	if (allow_ptr_leaks)
2786 		return false;
2787 
2788 	return reg->type != SCALAR_VALUE;
2789 }
2790 
2791 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)2792 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2793 {
2794 	struct bpf_reg_state *parent = dst->parent;
2795 	enum bpf_reg_liveness live = dst->live;
2796 
2797 	*dst = *src;
2798 	dst->parent = parent;
2799 	dst->live = live;
2800 }
2801 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)2802 static void save_register_state(struct bpf_func_state *state,
2803 				int spi, struct bpf_reg_state *reg,
2804 				int size)
2805 {
2806 	int i;
2807 
2808 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
2809 	if (size == BPF_REG_SIZE)
2810 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2811 
2812 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2813 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2814 
2815 	/* size < 8 bytes spill */
2816 	for (; i; i--)
2817 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2818 }
2819 
is_bpf_st_mem(struct bpf_insn * insn)2820 static bool is_bpf_st_mem(struct bpf_insn *insn)
2821 {
2822 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
2823 }
2824 
2825 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2826  * stack boundary and alignment are checked in check_mem_access()
2827  */
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)2828 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2829 				       /* stack frame we're writing to */
2830 				       struct bpf_func_state *state,
2831 				       int off, int size, int value_regno,
2832 				       int insn_idx)
2833 {
2834 	struct bpf_func_state *cur; /* state of the current function */
2835 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2836 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
2837 	struct bpf_reg_state *reg = NULL;
2838 	u32 dst_reg = insn->dst_reg;
2839 
2840 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2841 	if (err)
2842 		return err;
2843 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2844 	 * so it's aligned access and [off, off + size) are within stack limits
2845 	 */
2846 	if (!env->allow_ptr_leaks &&
2847 	    is_spilled_reg(&state->stack[spi]) &&
2848 	    size != BPF_REG_SIZE) {
2849 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2850 		return -EACCES;
2851 	}
2852 
2853 	cur = env->cur_state->frame[env->cur_state->curframe];
2854 	if (value_regno >= 0)
2855 		reg = &cur->regs[value_regno];
2856 	if (!env->bypass_spec_v4) {
2857 		bool sanitize = reg && is_spillable_regtype(reg->type);
2858 
2859 		for (i = 0; i < size; i++) {
2860 			u8 type = state->stack[spi].slot_type[i];
2861 
2862 			if (type != STACK_MISC && type != STACK_ZERO) {
2863 				sanitize = true;
2864 				break;
2865 			}
2866 		}
2867 
2868 		if (sanitize)
2869 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2870 	}
2871 
2872 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2873 	    !register_is_null(reg) && env->bpf_capable) {
2874 		if (dst_reg != BPF_REG_FP) {
2875 			/* The backtracking logic can only recognize explicit
2876 			 * stack slot address like [fp - 8]. Other spill of
2877 			 * scalar via different register has to be conservative.
2878 			 * Backtrack from here and mark all registers as precise
2879 			 * that contributed into 'reg' being a constant.
2880 			 */
2881 			err = mark_chain_precision(env, value_regno);
2882 			if (err)
2883 				return err;
2884 		}
2885 		save_register_state(state, spi, reg, size);
2886 		/* Break the relation on a narrowing spill. */
2887 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
2888 			state->stack[spi].spilled_ptr.id = 0;
2889 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
2890 		   insn->imm != 0 && env->bpf_capable) {
2891 		struct bpf_reg_state fake_reg = {};
2892 
2893 		__mark_reg_known(&fake_reg, insn->imm);
2894 		fake_reg.type = SCALAR_VALUE;
2895 		save_register_state(state, spi, &fake_reg, size);
2896 	} else if (reg && is_spillable_regtype(reg->type)) {
2897 		/* register containing pointer is being spilled into stack */
2898 		if (size != BPF_REG_SIZE) {
2899 			verbose_linfo(env, insn_idx, "; ");
2900 			verbose(env, "invalid size of register spill\n");
2901 			return -EACCES;
2902 		}
2903 		if (state != cur && reg->type == PTR_TO_STACK) {
2904 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2905 			return -EINVAL;
2906 		}
2907 		save_register_state(state, spi, reg, size);
2908 	} else {
2909 		u8 type = STACK_MISC;
2910 
2911 		/* regular write of data into stack destroys any spilled ptr */
2912 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2913 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2914 		if (is_spilled_reg(&state->stack[spi]))
2915 			for (i = 0; i < BPF_REG_SIZE; i++)
2916 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2917 
2918 		/* only mark the slot as written if all 8 bytes were written
2919 		 * otherwise read propagation may incorrectly stop too soon
2920 		 * when stack slots are partially written.
2921 		 * This heuristic means that read propagation will be
2922 		 * conservative, since it will add reg_live_read marks
2923 		 * to stack slots all the way to first state when programs
2924 		 * writes+reads less than 8 bytes
2925 		 */
2926 		if (size == BPF_REG_SIZE)
2927 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2928 
2929 		/* when we zero initialize stack slots mark them as such */
2930 		if ((reg && register_is_null(reg)) ||
2931 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
2932 			/* backtracking doesn't work for STACK_ZERO yet. */
2933 			err = mark_chain_precision(env, value_regno);
2934 			if (err)
2935 				return err;
2936 			type = STACK_ZERO;
2937 		}
2938 
2939 		/* Mark slots affected by this stack write. */
2940 		for (i = 0; i < size; i++)
2941 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2942 				type;
2943 	}
2944 	return 0;
2945 }
2946 
2947 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2948  * known to contain a variable offset.
2949  * This function checks whether the write is permitted and conservatively
2950  * tracks the effects of the write, considering that each stack slot in the
2951  * dynamic range is potentially written to.
2952  *
2953  * 'off' includes 'regno->off'.
2954  * 'value_regno' can be -1, meaning that an unknown value is being written to
2955  * the stack.
2956  *
2957  * Spilled pointers in range are not marked as written because we don't know
2958  * what's going to be actually written. This means that read propagation for
2959  * future reads cannot be terminated by this write.
2960  *
2961  * For privileged programs, uninitialized stack slots are considered
2962  * initialized by this write (even though we don't know exactly what offsets
2963  * are going to be written to). The idea is that we don't want the verifier to
2964  * reject future reads that access slots written to through variable offsets.
2965  */
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)2966 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2967 				     /* func where register points to */
2968 				     struct bpf_func_state *state,
2969 				     int ptr_regno, int off, int size,
2970 				     int value_regno, int insn_idx)
2971 {
2972 	struct bpf_func_state *cur; /* state of the current function */
2973 	int min_off, max_off;
2974 	int i, err;
2975 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2976 	bool writing_zero = false;
2977 	/* set if the fact that we're writing a zero is used to let any
2978 	 * stack slots remain STACK_ZERO
2979 	 */
2980 	bool zero_used = false;
2981 
2982 	cur = env->cur_state->frame[env->cur_state->curframe];
2983 	ptr_reg = &cur->regs[ptr_regno];
2984 	min_off = ptr_reg->smin_value + off;
2985 	max_off = ptr_reg->smax_value + off + size;
2986 	if (value_regno >= 0)
2987 		value_reg = &cur->regs[value_regno];
2988 	if (value_reg && register_is_null(value_reg))
2989 		writing_zero = true;
2990 
2991 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2992 	if (err)
2993 		return err;
2994 
2995 
2996 	/* Variable offset writes destroy any spilled pointers in range. */
2997 	for (i = min_off; i < max_off; i++) {
2998 		u8 new_type, *stype;
2999 		int slot, spi;
3000 
3001 		slot = -i - 1;
3002 		spi = slot / BPF_REG_SIZE;
3003 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3004 
3005 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3006 			/* Reject the write if range we may write to has not
3007 			 * been initialized beforehand. If we didn't reject
3008 			 * here, the ptr status would be erased below (even
3009 			 * though not all slots are actually overwritten),
3010 			 * possibly opening the door to leaks.
3011 			 *
3012 			 * We do however catch STACK_INVALID case below, and
3013 			 * only allow reading possibly uninitialized memory
3014 			 * later for CAP_PERFMON, as the write may not happen to
3015 			 * that slot.
3016 			 */
3017 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3018 				insn_idx, i);
3019 			return -EINVAL;
3020 		}
3021 
3022 		/* Erase all spilled pointers. */
3023 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3024 
3025 		/* Update the slot type. */
3026 		new_type = STACK_MISC;
3027 		if (writing_zero && *stype == STACK_ZERO) {
3028 			new_type = STACK_ZERO;
3029 			zero_used = true;
3030 		}
3031 		/* If the slot is STACK_INVALID, we check whether it's OK to
3032 		 * pretend that it will be initialized by this write. The slot
3033 		 * might not actually be written to, and so if we mark it as
3034 		 * initialized future reads might leak uninitialized memory.
3035 		 * For privileged programs, we will accept such reads to slots
3036 		 * that may or may not be written because, if we're reject
3037 		 * them, the error would be too confusing.
3038 		 */
3039 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3040 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3041 					insn_idx, i);
3042 			return -EINVAL;
3043 		}
3044 		*stype = new_type;
3045 	}
3046 	if (zero_used) {
3047 		/* backtracking doesn't work for STACK_ZERO yet. */
3048 		err = mark_chain_precision(env, value_regno);
3049 		if (err)
3050 			return err;
3051 	}
3052 	return 0;
3053 }
3054 
3055 /* When register 'dst_regno' is assigned some values from stack[min_off,
3056  * max_off), we set the register's type according to the types of the
3057  * respective stack slots. If all the stack values are known to be zeros, then
3058  * so is the destination reg. Otherwise, the register is considered to be
3059  * SCALAR. This function does not deal with register filling; the caller must
3060  * ensure that all spilled registers in the stack range have been marked as
3061  * read.
3062  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)3063 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3064 				/* func where src register points to */
3065 				struct bpf_func_state *ptr_state,
3066 				int min_off, int max_off, int dst_regno)
3067 {
3068 	struct bpf_verifier_state *vstate = env->cur_state;
3069 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3070 	int i, slot, spi;
3071 	u8 *stype;
3072 	int zeros = 0;
3073 
3074 	for (i = min_off; i < max_off; i++) {
3075 		slot = -i - 1;
3076 		spi = slot / BPF_REG_SIZE;
3077 		stype = ptr_state->stack[spi].slot_type;
3078 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3079 			break;
3080 		zeros++;
3081 	}
3082 	if (zeros == max_off - min_off) {
3083 		/* any access_size read into register is zero extended,
3084 		 * so the whole register == const_zero
3085 		 */
3086 		__mark_reg_const_zero(&state->regs[dst_regno]);
3087 		/* backtracking doesn't support STACK_ZERO yet,
3088 		 * so mark it precise here, so that later
3089 		 * backtracking can stop here.
3090 		 * Backtracking may not need this if this register
3091 		 * doesn't participate in pointer adjustment.
3092 		 * Forward propagation of precise flag is not
3093 		 * necessary either. This mark is only to stop
3094 		 * backtracking. Any register that contributed
3095 		 * to const 0 was marked precise before spill.
3096 		 */
3097 		state->regs[dst_regno].precise = true;
3098 	} else {
3099 		/* have read misc data from the stack */
3100 		mark_reg_unknown(env, state->regs, dst_regno);
3101 	}
3102 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3103 }
3104 
3105 /* Read the stack at 'off' and put the results into the register indicated by
3106  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3107  * spilled reg.
3108  *
3109  * 'dst_regno' can be -1, meaning that the read value is not going to a
3110  * register.
3111  *
3112  * The access is assumed to be within the current stack bounds.
3113  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)3114 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3115 				      /* func where src register points to */
3116 				      struct bpf_func_state *reg_state,
3117 				      int off, int size, int dst_regno)
3118 {
3119 	struct bpf_verifier_state *vstate = env->cur_state;
3120 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3121 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3122 	struct bpf_reg_state *reg;
3123 	u8 *stype, type;
3124 
3125 	stype = reg_state->stack[spi].slot_type;
3126 	reg = &reg_state->stack[spi].spilled_ptr;
3127 
3128 	if (is_spilled_reg(&reg_state->stack[spi])) {
3129 		u8 spill_size = 1;
3130 
3131 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3132 			spill_size++;
3133 
3134 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3135 			if (reg->type != SCALAR_VALUE) {
3136 				verbose_linfo(env, env->insn_idx, "; ");
3137 				verbose(env, "invalid size of register fill\n");
3138 				return -EACCES;
3139 			}
3140 
3141 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3142 			if (dst_regno < 0)
3143 				return 0;
3144 
3145 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3146 				/* The earlier check_reg_arg() has decided the
3147 				 * subreg_def for this insn.  Save it first.
3148 				 */
3149 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3150 
3151 				copy_register_state(&state->regs[dst_regno], reg);
3152 				state->regs[dst_regno].subreg_def = subreg_def;
3153 			} else {
3154 				for (i = 0; i < size; i++) {
3155 					type = stype[(slot - i) % BPF_REG_SIZE];
3156 					if (type == STACK_SPILL)
3157 						continue;
3158 					if (type == STACK_MISC)
3159 						continue;
3160 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3161 						off, i, size);
3162 					return -EACCES;
3163 				}
3164 				mark_reg_unknown(env, state->regs, dst_regno);
3165 			}
3166 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3167 			return 0;
3168 		}
3169 
3170 		if (dst_regno >= 0) {
3171 			/* restore register state from stack */
3172 			copy_register_state(&state->regs[dst_regno], reg);
3173 			/* mark reg as written since spilled pointer state likely
3174 			 * has its liveness marks cleared by is_state_visited()
3175 			 * which resets stack/reg liveness for state transitions
3176 			 */
3177 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3178 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3179 			/* If dst_regno==-1, the caller is asking us whether
3180 			 * it is acceptable to use this value as a SCALAR_VALUE
3181 			 * (e.g. for XADD).
3182 			 * We must not allow unprivileged callers to do that
3183 			 * with spilled pointers.
3184 			 */
3185 			verbose(env, "leaking pointer from stack off %d\n",
3186 				off);
3187 			return -EACCES;
3188 		}
3189 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3190 	} else {
3191 		for (i = 0; i < size; i++) {
3192 			type = stype[(slot - i) % BPF_REG_SIZE];
3193 			if (type == STACK_MISC)
3194 				continue;
3195 			if (type == STACK_ZERO)
3196 				continue;
3197 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3198 				off, i, size);
3199 			return -EACCES;
3200 		}
3201 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3202 		if (dst_regno >= 0)
3203 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3204 	}
3205 	return 0;
3206 }
3207 
3208 enum stack_access_src {
3209 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3210 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3211 };
3212 
3213 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3214 					 int regno, int off, int access_size,
3215 					 bool zero_size_allowed,
3216 					 enum stack_access_src type,
3217 					 struct bpf_call_arg_meta *meta);
3218 
reg_state(struct bpf_verifier_env * env,int regno)3219 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3220 {
3221 	return cur_regs(env) + regno;
3222 }
3223 
3224 /* Read the stack at 'ptr_regno + off' and put the result into the register
3225  * 'dst_regno'.
3226  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3227  * but not its variable offset.
3228  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3229  *
3230  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3231  * filling registers (i.e. reads of spilled register cannot be detected when
3232  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3233  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3234  * offset; for a fixed offset check_stack_read_fixed_off should be used
3235  * instead.
3236  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3237 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3238 				    int ptr_regno, int off, int size, int dst_regno)
3239 {
3240 	/* The state of the source register. */
3241 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3242 	struct bpf_func_state *ptr_state = func(env, reg);
3243 	int err;
3244 	int min_off, max_off;
3245 
3246 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3247 	 */
3248 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3249 					    false, ACCESS_DIRECT, NULL);
3250 	if (err)
3251 		return err;
3252 
3253 	min_off = reg->smin_value + off;
3254 	max_off = reg->smax_value + off;
3255 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3256 	return 0;
3257 }
3258 
3259 /* check_stack_read dispatches to check_stack_read_fixed_off or
3260  * check_stack_read_var_off.
3261  *
3262  * The caller must ensure that the offset falls within the allocated stack
3263  * bounds.
3264  *
3265  * 'dst_regno' is a register which will receive the value from the stack. It
3266  * can be -1, meaning that the read value is not going to a register.
3267  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3268 static int check_stack_read(struct bpf_verifier_env *env,
3269 			    int ptr_regno, int off, int size,
3270 			    int dst_regno)
3271 {
3272 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3273 	struct bpf_func_state *state = func(env, reg);
3274 	int err;
3275 	/* Some accesses are only permitted with a static offset. */
3276 	bool var_off = !tnum_is_const(reg->var_off);
3277 
3278 	/* The offset is required to be static when reads don't go to a
3279 	 * register, in order to not leak pointers (see
3280 	 * check_stack_read_fixed_off).
3281 	 */
3282 	if (dst_regno < 0 && var_off) {
3283 		char tn_buf[48];
3284 
3285 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3286 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3287 			tn_buf, off, size);
3288 		return -EACCES;
3289 	}
3290 	/* Variable offset is prohibited for unprivileged mode for simplicity
3291 	 * since it requires corresponding support in Spectre masking for stack
3292 	 * ALU. See also retrieve_ptr_limit(). The check in
3293 	 * check_stack_access_for_ptr_arithmetic() called by
3294 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3295 	 * with variable offsets, therefore no check is required here. Further,
3296 	 * just checking it here would be insufficient as speculative stack
3297 	 * writes could still lead to unsafe speculative behaviour.
3298 	 */
3299 	if (!var_off) {
3300 		off += reg->var_off.value;
3301 		err = check_stack_read_fixed_off(env, state, off, size,
3302 						 dst_regno);
3303 	} else {
3304 		/* Variable offset stack reads need more conservative handling
3305 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3306 		 * branch.
3307 		 */
3308 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3309 					       dst_regno);
3310 	}
3311 	return err;
3312 }
3313 
3314 
3315 /* check_stack_write dispatches to check_stack_write_fixed_off or
3316  * check_stack_write_var_off.
3317  *
3318  * 'ptr_regno' is the register used as a pointer into the stack.
3319  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3320  * 'value_regno' is the register whose value we're writing to the stack. It can
3321  * be -1, meaning that we're not writing from a register.
3322  *
3323  * The caller must ensure that the offset falls within the maximum stack size.
3324  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)3325 static int check_stack_write(struct bpf_verifier_env *env,
3326 			     int ptr_regno, int off, int size,
3327 			     int value_regno, int insn_idx)
3328 {
3329 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3330 	struct bpf_func_state *state = func(env, reg);
3331 	int err;
3332 
3333 	if (tnum_is_const(reg->var_off)) {
3334 		off += reg->var_off.value;
3335 		err = check_stack_write_fixed_off(env, state, off, size,
3336 						  value_regno, insn_idx);
3337 	} else {
3338 		/* Variable offset stack reads need more conservative handling
3339 		 * than fixed offset ones.
3340 		 */
3341 		err = check_stack_write_var_off(env, state,
3342 						ptr_regno, off, size,
3343 						value_regno, insn_idx);
3344 	}
3345 	return err;
3346 }
3347 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)3348 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3349 				 int off, int size, enum bpf_access_type type)
3350 {
3351 	struct bpf_reg_state *regs = cur_regs(env);
3352 	struct bpf_map *map = regs[regno].map_ptr;
3353 	u32 cap = bpf_map_flags_to_cap(map);
3354 
3355 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3356 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3357 			map->value_size, off, size);
3358 		return -EACCES;
3359 	}
3360 
3361 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3362 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3363 			map->value_size, off, size);
3364 		return -EACCES;
3365 	}
3366 
3367 	return 0;
3368 }
3369 
3370 /* 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)3371 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3372 			      int off, int size, u32 mem_size,
3373 			      bool zero_size_allowed)
3374 {
3375 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3376 	struct bpf_reg_state *reg;
3377 
3378 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3379 		return 0;
3380 
3381 	reg = &cur_regs(env)[regno];
3382 	switch (reg->type) {
3383 	case PTR_TO_MAP_KEY:
3384 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3385 			mem_size, off, size);
3386 		break;
3387 	case PTR_TO_MAP_VALUE:
3388 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3389 			mem_size, off, size);
3390 		break;
3391 	case PTR_TO_PACKET:
3392 	case PTR_TO_PACKET_META:
3393 	case PTR_TO_PACKET_END:
3394 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3395 			off, size, regno, reg->id, off, mem_size);
3396 		break;
3397 	case PTR_TO_MEM:
3398 	default:
3399 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3400 			mem_size, off, size);
3401 	}
3402 
3403 	return -EACCES;
3404 }
3405 
3406 /* 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)3407 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3408 				   int off, int size, u32 mem_size,
3409 				   bool zero_size_allowed)
3410 {
3411 	struct bpf_verifier_state *vstate = env->cur_state;
3412 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3413 	struct bpf_reg_state *reg = &state->regs[regno];
3414 	int err;
3415 
3416 	/* We may have adjusted the register pointing to memory region, so we
3417 	 * need to try adding each of min_value and max_value to off
3418 	 * to make sure our theoretical access will be safe.
3419 	 */
3420 	if (env->log.level & BPF_LOG_LEVEL)
3421 		print_verifier_state(env, state);
3422 
3423 	/* The minimum value is only important with signed
3424 	 * comparisons where we can't assume the floor of a
3425 	 * value is 0.  If we are using signed variables for our
3426 	 * index'es we need to make sure that whatever we use
3427 	 * will have a set floor within our range.
3428 	 */
3429 	if (reg->smin_value < 0 &&
3430 	    (reg->smin_value == S64_MIN ||
3431 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3432 	      reg->smin_value + off < 0)) {
3433 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3434 			regno);
3435 		return -EACCES;
3436 	}
3437 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3438 				 mem_size, zero_size_allowed);
3439 	if (err) {
3440 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3441 			regno);
3442 		return err;
3443 	}
3444 
3445 	/* If we haven't set a max value then we need to bail since we can't be
3446 	 * sure we won't do bad things.
3447 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3448 	 */
3449 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3450 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3451 			regno);
3452 		return -EACCES;
3453 	}
3454 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3455 				 mem_size, zero_size_allowed);
3456 	if (err) {
3457 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3458 			regno);
3459 		return err;
3460 	}
3461 
3462 	return 0;
3463 }
3464 
3465 /* 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)3466 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3467 			    int off, int size, bool zero_size_allowed)
3468 {
3469 	struct bpf_verifier_state *vstate = env->cur_state;
3470 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3471 	struct bpf_reg_state *reg = &state->regs[regno];
3472 	struct bpf_map *map = reg->map_ptr;
3473 	int err;
3474 
3475 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3476 				      zero_size_allowed);
3477 	if (err)
3478 		return err;
3479 
3480 	if (map_value_has_spin_lock(map)) {
3481 		u32 lock = map->spin_lock_off;
3482 
3483 		/* if any part of struct bpf_spin_lock can be touched by
3484 		 * load/store reject this program.
3485 		 * To check that [x1, x2) overlaps with [y1, y2)
3486 		 * it is sufficient to check x1 < y2 && y1 < x2.
3487 		 */
3488 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3489 		     lock < reg->umax_value + off + size) {
3490 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3491 			return -EACCES;
3492 		}
3493 	}
3494 	if (map_value_has_timer(map)) {
3495 		u32 t = map->timer_off;
3496 
3497 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3498 		     t < reg->umax_value + off + size) {
3499 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3500 			return -EACCES;
3501 		}
3502 	}
3503 	return err;
3504 }
3505 
3506 #define MAX_PACKET_OFF 0xffff
3507 
resolve_prog_type(struct bpf_prog * prog)3508 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3509 {
3510 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3511 }
3512 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)3513 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3514 				       const struct bpf_call_arg_meta *meta,
3515 				       enum bpf_access_type t)
3516 {
3517 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3518 
3519 	switch (prog_type) {
3520 	/* Program types only with direct read access go here! */
3521 	case BPF_PROG_TYPE_LWT_IN:
3522 	case BPF_PROG_TYPE_LWT_OUT:
3523 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3524 	case BPF_PROG_TYPE_SK_REUSEPORT:
3525 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3526 	case BPF_PROG_TYPE_CGROUP_SKB:
3527 		if (t == BPF_WRITE)
3528 			return false;
3529 		fallthrough;
3530 
3531 	/* Program types with direct read + write access go here! */
3532 	case BPF_PROG_TYPE_SCHED_CLS:
3533 	case BPF_PROG_TYPE_SCHED_ACT:
3534 	case BPF_PROG_TYPE_XDP:
3535 	case BPF_PROG_TYPE_LWT_XMIT:
3536 	case BPF_PROG_TYPE_SK_SKB:
3537 	case BPF_PROG_TYPE_SK_MSG:
3538 		if (meta)
3539 			return meta->pkt_access;
3540 
3541 		env->seen_direct_write = true;
3542 		return true;
3543 
3544 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3545 		if (t == BPF_WRITE)
3546 			env->seen_direct_write = true;
3547 
3548 		return true;
3549 
3550 	default:
3551 		return false;
3552 	}
3553 }
3554 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)3555 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3556 			       int size, bool zero_size_allowed)
3557 {
3558 	struct bpf_reg_state *regs = cur_regs(env);
3559 	struct bpf_reg_state *reg = &regs[regno];
3560 	int err;
3561 
3562 	/* We may have added a variable offset to the packet pointer; but any
3563 	 * reg->range we have comes after that.  We are only checking the fixed
3564 	 * offset.
3565 	 */
3566 
3567 	/* We don't allow negative numbers, because we aren't tracking enough
3568 	 * detail to prove they're safe.
3569 	 */
3570 	if (reg->smin_value < 0) {
3571 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3572 			regno);
3573 		return -EACCES;
3574 	}
3575 
3576 	err = reg->range < 0 ? -EINVAL :
3577 	      __check_mem_access(env, regno, off, size, reg->range,
3578 				 zero_size_allowed);
3579 	if (err) {
3580 		verbose(env, "R%d offset is outside of the packet\n", regno);
3581 		return err;
3582 	}
3583 
3584 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3585 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3586 	 * otherwise find_good_pkt_pointers would have refused to set range info
3587 	 * that __check_mem_access would have rejected this pkt access.
3588 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3589 	 */
3590 	env->prog->aux->max_pkt_offset =
3591 		max_t(u32, env->prog->aux->max_pkt_offset,
3592 		      off + reg->umax_value + size - 1);
3593 
3594 	return err;
3595 }
3596 
3597 /* 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,struct btf ** btf,u32 * btf_id)3598 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3599 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3600 			    struct btf **btf, u32 *btf_id)
3601 {
3602 	struct bpf_insn_access_aux info = {
3603 		.reg_type = *reg_type,
3604 		.log = &env->log,
3605 	};
3606 
3607 	if (env->ops->is_valid_access &&
3608 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3609 		/* A non zero info.ctx_field_size indicates that this field is a
3610 		 * candidate for later verifier transformation to load the whole
3611 		 * field and then apply a mask when accessed with a narrower
3612 		 * access than actual ctx access size. A zero info.ctx_field_size
3613 		 * will only allow for whole field access and rejects any other
3614 		 * type of narrower access.
3615 		 */
3616 		*reg_type = info.reg_type;
3617 
3618 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3619 			*btf = info.btf;
3620 			*btf_id = info.btf_id;
3621 		} else {
3622 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3623 		}
3624 		/* remember the offset of last byte accessed in ctx */
3625 		if (env->prog->aux->max_ctx_offset < off + size)
3626 			env->prog->aux->max_ctx_offset = off + size;
3627 		return 0;
3628 	}
3629 
3630 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3631 	return -EACCES;
3632 }
3633 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)3634 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3635 				  int size)
3636 {
3637 	if (size < 0 || off < 0 ||
3638 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3639 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3640 			off, size);
3641 		return -EACCES;
3642 	}
3643 	return 0;
3644 }
3645 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)3646 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3647 			     u32 regno, int off, int size,
3648 			     enum bpf_access_type t)
3649 {
3650 	struct bpf_reg_state *regs = cur_regs(env);
3651 	struct bpf_reg_state *reg = &regs[regno];
3652 	struct bpf_insn_access_aux info = {};
3653 	bool valid;
3654 
3655 	if (reg->smin_value < 0) {
3656 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3657 			regno);
3658 		return -EACCES;
3659 	}
3660 
3661 	switch (reg->type) {
3662 	case PTR_TO_SOCK_COMMON:
3663 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3664 		break;
3665 	case PTR_TO_SOCKET:
3666 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3667 		break;
3668 	case PTR_TO_TCP_SOCK:
3669 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3670 		break;
3671 	case PTR_TO_XDP_SOCK:
3672 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3673 		break;
3674 	default:
3675 		valid = false;
3676 	}
3677 
3678 
3679 	if (valid) {
3680 		env->insn_aux_data[insn_idx].ctx_field_size =
3681 			info.ctx_field_size;
3682 		return 0;
3683 	}
3684 
3685 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3686 		regno, reg_type_str(env, reg->type), off, size);
3687 
3688 	return -EACCES;
3689 }
3690 
is_pointer_value(struct bpf_verifier_env * env,int regno)3691 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3692 {
3693 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3694 }
3695 
is_ctx_reg(struct bpf_verifier_env * env,int regno)3696 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3697 {
3698 	const struct bpf_reg_state *reg = reg_state(env, regno);
3699 
3700 	return reg->type == PTR_TO_CTX;
3701 }
3702 
is_sk_reg(struct bpf_verifier_env * env,int regno)3703 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3704 {
3705 	const struct bpf_reg_state *reg = reg_state(env, regno);
3706 
3707 	return type_is_sk_pointer(reg->type);
3708 }
3709 
is_pkt_reg(struct bpf_verifier_env * env,int regno)3710 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3711 {
3712 	const struct bpf_reg_state *reg = reg_state(env, regno);
3713 
3714 	return type_is_pkt_pointer(reg->type);
3715 }
3716 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)3717 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3718 {
3719 	const struct bpf_reg_state *reg = reg_state(env, regno);
3720 
3721 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3722 	return reg->type == PTR_TO_FLOW_KEYS;
3723 }
3724 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)3725 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3726 				   const struct bpf_reg_state *reg,
3727 				   int off, int size, bool strict)
3728 {
3729 	struct tnum reg_off;
3730 	int ip_align;
3731 
3732 	/* Byte size accesses are always allowed. */
3733 	if (!strict || size == 1)
3734 		return 0;
3735 
3736 	/* For platforms that do not have a Kconfig enabling
3737 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3738 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3739 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3740 	 * to this code only in strict mode where we want to emulate
3741 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3742 	 * unconditional IP align value of '2'.
3743 	 */
3744 	ip_align = 2;
3745 
3746 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3747 	if (!tnum_is_aligned(reg_off, size)) {
3748 		char tn_buf[48];
3749 
3750 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3751 		verbose(env,
3752 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3753 			ip_align, tn_buf, reg->off, off, size);
3754 		return -EACCES;
3755 	}
3756 
3757 	return 0;
3758 }
3759 
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)3760 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3761 				       const struct bpf_reg_state *reg,
3762 				       const char *pointer_desc,
3763 				       int off, int size, bool strict)
3764 {
3765 	struct tnum reg_off;
3766 
3767 	/* Byte size accesses are always allowed. */
3768 	if (!strict || size == 1)
3769 		return 0;
3770 
3771 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3772 	if (!tnum_is_aligned(reg_off, size)) {
3773 		char tn_buf[48];
3774 
3775 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3776 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3777 			pointer_desc, tn_buf, reg->off, off, size);
3778 		return -EACCES;
3779 	}
3780 
3781 	return 0;
3782 }
3783 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)3784 static int check_ptr_alignment(struct bpf_verifier_env *env,
3785 			       const struct bpf_reg_state *reg, int off,
3786 			       int size, bool strict_alignment_once)
3787 {
3788 	bool strict = env->strict_alignment || strict_alignment_once;
3789 	const char *pointer_desc = "";
3790 
3791 	switch (reg->type) {
3792 	case PTR_TO_PACKET:
3793 	case PTR_TO_PACKET_META:
3794 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3795 		 * right in front, treat it the very same way.
3796 		 */
3797 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3798 	case PTR_TO_FLOW_KEYS:
3799 		pointer_desc = "flow keys ";
3800 		break;
3801 	case PTR_TO_MAP_KEY:
3802 		pointer_desc = "key ";
3803 		break;
3804 	case PTR_TO_MAP_VALUE:
3805 		pointer_desc = "value ";
3806 		break;
3807 	case PTR_TO_CTX:
3808 		pointer_desc = "context ";
3809 		break;
3810 	case PTR_TO_STACK:
3811 		pointer_desc = "stack ";
3812 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3813 		 * and check_stack_read_fixed_off() relies on stack accesses being
3814 		 * aligned.
3815 		 */
3816 		strict = true;
3817 		break;
3818 	case PTR_TO_SOCKET:
3819 		pointer_desc = "sock ";
3820 		break;
3821 	case PTR_TO_SOCK_COMMON:
3822 		pointer_desc = "sock_common ";
3823 		break;
3824 	case PTR_TO_TCP_SOCK:
3825 		pointer_desc = "tcp_sock ";
3826 		break;
3827 	case PTR_TO_XDP_SOCK:
3828 		pointer_desc = "xdp_sock ";
3829 		break;
3830 	default:
3831 		break;
3832 	}
3833 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3834 					   strict);
3835 }
3836 
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)3837 static int update_stack_depth(struct bpf_verifier_env *env,
3838 			      const struct bpf_func_state *func,
3839 			      int off)
3840 {
3841 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3842 
3843 	if (stack >= -off)
3844 		return 0;
3845 
3846 	/* update known max for given subprogram */
3847 	env->subprog_info[func->subprogno].stack_depth = -off;
3848 	return 0;
3849 }
3850 
3851 /* starting from main bpf function walk all instructions of the function
3852  * and recursively walk all callees that given function can call.
3853  * Ignore jump and exit insns.
3854  * Since recursion is prevented by check_cfg() this algorithm
3855  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3856  */
check_max_stack_depth(struct bpf_verifier_env * env)3857 static int check_max_stack_depth(struct bpf_verifier_env *env)
3858 {
3859 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3860 	struct bpf_subprog_info *subprog = env->subprog_info;
3861 	struct bpf_insn *insn = env->prog->insnsi;
3862 	bool tail_call_reachable = false;
3863 	int ret_insn[MAX_CALL_FRAMES];
3864 	int ret_prog[MAX_CALL_FRAMES];
3865 	int j;
3866 
3867 process_func:
3868 	/* protect against potential stack overflow that might happen when
3869 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3870 	 * depth for such case down to 256 so that the worst case scenario
3871 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3872 	 * 8k).
3873 	 *
3874 	 * To get the idea what might happen, see an example:
3875 	 * func1 -> sub rsp, 128
3876 	 *  subfunc1 -> sub rsp, 256
3877 	 *  tailcall1 -> add rsp, 256
3878 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3879 	 *   subfunc2 -> sub rsp, 64
3880 	 *   subfunc22 -> sub rsp, 128
3881 	 *   tailcall2 -> add rsp, 128
3882 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3883 	 *
3884 	 * tailcall will unwind the current stack frame but it will not get rid
3885 	 * of caller's stack as shown on the example above.
3886 	 */
3887 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3888 		verbose(env,
3889 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3890 			depth);
3891 		return -EACCES;
3892 	}
3893 	/* round up to 32-bytes, since this is granularity
3894 	 * of interpreter stack size
3895 	 */
3896 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3897 	if (depth > MAX_BPF_STACK) {
3898 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3899 			frame + 1, depth);
3900 		return -EACCES;
3901 	}
3902 continue_func:
3903 	subprog_end = subprog[idx + 1].start;
3904 	for (; i < subprog_end; i++) {
3905 		int next_insn, sidx;
3906 
3907 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3908 			continue;
3909 		/* remember insn and function to return to */
3910 		ret_insn[frame] = i + 1;
3911 		ret_prog[frame] = idx;
3912 
3913 		/* find the callee */
3914 		next_insn = i + insn[i].imm + 1;
3915 		sidx = find_subprog(env, next_insn);
3916 		if (sidx < 0) {
3917 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3918 				  next_insn);
3919 			return -EFAULT;
3920 		}
3921 		if (subprog[sidx].is_async_cb) {
3922 			if (subprog[sidx].has_tail_call) {
3923 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3924 				return -EFAULT;
3925 			}
3926 			/* async callbacks don't increase bpf prog stack size unless called directly */
3927 			if (!bpf_pseudo_call(insn + i))
3928 				continue;
3929 		}
3930 		i = next_insn;
3931 		idx = sidx;
3932 
3933 		if (subprog[idx].has_tail_call)
3934 			tail_call_reachable = true;
3935 
3936 		frame++;
3937 		if (frame >= MAX_CALL_FRAMES) {
3938 			verbose(env, "the call stack of %d frames is too deep !\n",
3939 				frame);
3940 			return -E2BIG;
3941 		}
3942 		goto process_func;
3943 	}
3944 	/* if tail call got detected across bpf2bpf calls then mark each of the
3945 	 * currently present subprog frames as tail call reachable subprogs;
3946 	 * this info will be utilized by JIT so that we will be preserving the
3947 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3948 	 */
3949 	if (tail_call_reachable)
3950 		for (j = 0; j < frame; j++)
3951 			subprog[ret_prog[j]].tail_call_reachable = true;
3952 	if (subprog[0].tail_call_reachable)
3953 		env->prog->aux->tail_call_reachable = true;
3954 
3955 	/* end of for() loop means the last insn of the 'subprog'
3956 	 * was reached. Doesn't matter whether it was JA or EXIT
3957 	 */
3958 	if (frame == 0)
3959 		return 0;
3960 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3961 	frame--;
3962 	i = ret_insn[frame];
3963 	idx = ret_prog[frame];
3964 	goto continue_func;
3965 }
3966 
3967 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)3968 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3969 				  const struct bpf_insn *insn, int idx)
3970 {
3971 	int start = idx + insn->imm + 1, subprog;
3972 
3973 	subprog = find_subprog(env, start);
3974 	if (subprog < 0) {
3975 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3976 			  start);
3977 		return -EFAULT;
3978 	}
3979 	return env->subprog_info[subprog].stack_depth;
3980 }
3981 #endif
3982 
check_ctx_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3983 int check_ctx_reg(struct bpf_verifier_env *env,
3984 		  const struct bpf_reg_state *reg, int regno)
3985 {
3986 	/* Access to ctx or passing it to a helper is only allowed in
3987 	 * its original, unmodified form.
3988 	 */
3989 
3990 	if (reg->off) {
3991 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3992 			regno, reg->off);
3993 		return -EACCES;
3994 	}
3995 
3996 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3997 		char tn_buf[48];
3998 
3999 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4000 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
4001 		return -EACCES;
4002 	}
4003 
4004 	return 0;
4005 }
4006 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)4007 static int __check_buffer_access(struct bpf_verifier_env *env,
4008 				 const char *buf_info,
4009 				 const struct bpf_reg_state *reg,
4010 				 int regno, int off, int size)
4011 {
4012 	if (off < 0) {
4013 		verbose(env,
4014 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4015 			regno, buf_info, off, size);
4016 		return -EACCES;
4017 	}
4018 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4019 		char tn_buf[48];
4020 
4021 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4022 		verbose(env,
4023 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4024 			regno, off, tn_buf);
4025 		return -EACCES;
4026 	}
4027 
4028 	return 0;
4029 }
4030 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)4031 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4032 				  const struct bpf_reg_state *reg,
4033 				  int regno, int off, int size)
4034 {
4035 	int err;
4036 
4037 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4038 	if (err)
4039 		return err;
4040 
4041 	if (off + size > env->prog->aux->max_tp_access)
4042 		env->prog->aux->max_tp_access = off + size;
4043 
4044 	return 0;
4045 }
4046 
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)4047 static int check_buffer_access(struct bpf_verifier_env *env,
4048 			       const struct bpf_reg_state *reg,
4049 			       int regno, int off, int size,
4050 			       bool zero_size_allowed,
4051 			       const char *buf_info,
4052 			       u32 *max_access)
4053 {
4054 	int err;
4055 
4056 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4057 	if (err)
4058 		return err;
4059 
4060 	if (off + size > *max_access)
4061 		*max_access = off + size;
4062 
4063 	return 0;
4064 }
4065 
4066 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)4067 static void zext_32_to_64(struct bpf_reg_state *reg)
4068 {
4069 	reg->var_off = tnum_subreg(reg->var_off);
4070 	__reg_assign_32_into_64(reg);
4071 }
4072 
4073 /* truncate register to smaller size (in bytes)
4074  * must be called with size < BPF_REG_SIZE
4075  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)4076 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4077 {
4078 	u64 mask;
4079 
4080 	/* clear high bits in bit representation */
4081 	reg->var_off = tnum_cast(reg->var_off, size);
4082 
4083 	/* fix arithmetic bounds */
4084 	mask = ((u64)1 << (size * 8)) - 1;
4085 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4086 		reg->umin_value &= mask;
4087 		reg->umax_value &= mask;
4088 	} else {
4089 		reg->umin_value = 0;
4090 		reg->umax_value = mask;
4091 	}
4092 	reg->smin_value = reg->umin_value;
4093 	reg->smax_value = reg->umax_value;
4094 
4095 	/* If size is smaller than 32bit register the 32bit register
4096 	 * values are also truncated so we push 64-bit bounds into
4097 	 * 32-bit bounds. Above were truncated < 32-bits already.
4098 	 */
4099 	if (size >= 4)
4100 		return;
4101 	__reg_combine_64_into_32(reg);
4102 }
4103 
bpf_map_is_rdonly(const struct bpf_map * map)4104 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4105 {
4106 	/* A map is considered read-only if the following condition are true:
4107 	 *
4108 	 * 1) BPF program side cannot change any of the map content. The
4109 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4110 	 *    and was set at map creation time.
4111 	 * 2) The map value(s) have been initialized from user space by a
4112 	 *    loader and then "frozen", such that no new map update/delete
4113 	 *    operations from syscall side are possible for the rest of
4114 	 *    the map's lifetime from that point onwards.
4115 	 * 3) Any parallel/pending map update/delete operations from syscall
4116 	 *    side have been completed. Only after that point, it's safe to
4117 	 *    assume that map value(s) are immutable.
4118 	 */
4119 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4120 	       READ_ONCE(map->frozen) &&
4121 	       !bpf_map_write_active(map);
4122 }
4123 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)4124 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4125 {
4126 	void *ptr;
4127 	u64 addr;
4128 	int err;
4129 
4130 	err = map->ops->map_direct_value_addr(map, &addr, off);
4131 	if (err)
4132 		return err;
4133 	ptr = (void *)(long)addr + off;
4134 
4135 	switch (size) {
4136 	case sizeof(u8):
4137 		*val = (u64)*(u8 *)ptr;
4138 		break;
4139 	case sizeof(u16):
4140 		*val = (u64)*(u16 *)ptr;
4141 		break;
4142 	case sizeof(u32):
4143 		*val = (u64)*(u32 *)ptr;
4144 		break;
4145 	case sizeof(u64):
4146 		*val = *(u64 *)ptr;
4147 		break;
4148 	default:
4149 		return -EINVAL;
4150 	}
4151 	return 0;
4152 }
4153 
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)4154 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4155 				   struct bpf_reg_state *regs,
4156 				   int regno, int off, int size,
4157 				   enum bpf_access_type atype,
4158 				   int value_regno)
4159 {
4160 	struct bpf_reg_state *reg = regs + regno;
4161 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4162 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4163 	u32 btf_id;
4164 	int ret;
4165 
4166 	if (off < 0) {
4167 		verbose(env,
4168 			"R%d is ptr_%s invalid negative access: off=%d\n",
4169 			regno, tname, off);
4170 		return -EACCES;
4171 	}
4172 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4173 		char tn_buf[48];
4174 
4175 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4176 		verbose(env,
4177 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4178 			regno, tname, off, tn_buf);
4179 		return -EACCES;
4180 	}
4181 
4182 	if (env->ops->btf_struct_access) {
4183 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4184 						  off, size, atype, &btf_id);
4185 	} else {
4186 		if (atype != BPF_READ) {
4187 			verbose(env, "only read is supported\n");
4188 			return -EACCES;
4189 		}
4190 
4191 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4192 					atype, &btf_id);
4193 	}
4194 
4195 	if (ret < 0)
4196 		return ret;
4197 
4198 	if (atype == BPF_READ && value_regno >= 0)
4199 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4200 
4201 	return 0;
4202 }
4203 
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)4204 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4205 				   struct bpf_reg_state *regs,
4206 				   int regno, int off, int size,
4207 				   enum bpf_access_type atype,
4208 				   int value_regno)
4209 {
4210 	struct bpf_reg_state *reg = regs + regno;
4211 	struct bpf_map *map = reg->map_ptr;
4212 	const struct btf_type *t;
4213 	const char *tname;
4214 	u32 btf_id;
4215 	int ret;
4216 
4217 	if (!btf_vmlinux) {
4218 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4219 		return -ENOTSUPP;
4220 	}
4221 
4222 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4223 		verbose(env, "map_ptr access not supported for map type %d\n",
4224 			map->map_type);
4225 		return -ENOTSUPP;
4226 	}
4227 
4228 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4229 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4230 
4231 	if (!env->allow_ptr_to_map_access) {
4232 		verbose(env,
4233 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4234 			tname);
4235 		return -EPERM;
4236 	}
4237 
4238 	if (off < 0) {
4239 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4240 			regno, tname, off);
4241 		return -EACCES;
4242 	}
4243 
4244 	if (atype != BPF_READ) {
4245 		verbose(env, "only read from %s is supported\n", tname);
4246 		return -EACCES;
4247 	}
4248 
4249 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4250 	if (ret < 0)
4251 		return ret;
4252 
4253 	if (value_regno >= 0)
4254 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4255 
4256 	return 0;
4257 }
4258 
4259 /* Check that the stack access at the given offset is within bounds. The
4260  * maximum valid offset is -1.
4261  *
4262  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4263  * -state->allocated_stack for reads.
4264  */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)4265 static int check_stack_slot_within_bounds(int off,
4266 					  struct bpf_func_state *state,
4267 					  enum bpf_access_type t)
4268 {
4269 	int min_valid_off;
4270 
4271 	if (t == BPF_WRITE)
4272 		min_valid_off = -MAX_BPF_STACK;
4273 	else
4274 		min_valid_off = -state->allocated_stack;
4275 
4276 	if (off < min_valid_off || off > -1)
4277 		return -EACCES;
4278 	return 0;
4279 }
4280 
4281 /* Check that the stack access at 'regno + off' falls within the maximum stack
4282  * bounds.
4283  *
4284  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4285  */
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)4286 static int check_stack_access_within_bounds(
4287 		struct bpf_verifier_env *env,
4288 		int regno, int off, int access_size,
4289 		enum stack_access_src src, enum bpf_access_type type)
4290 {
4291 	struct bpf_reg_state *regs = cur_regs(env);
4292 	struct bpf_reg_state *reg = regs + regno;
4293 	struct bpf_func_state *state = func(env, reg);
4294 	int min_off, max_off;
4295 	int err;
4296 	char *err_extra;
4297 
4298 	if (src == ACCESS_HELPER)
4299 		/* We don't know if helpers are reading or writing (or both). */
4300 		err_extra = " indirect access to";
4301 	else if (type == BPF_READ)
4302 		err_extra = " read from";
4303 	else
4304 		err_extra = " write to";
4305 
4306 	if (tnum_is_const(reg->var_off)) {
4307 		min_off = reg->var_off.value + off;
4308 		max_off = min_off + access_size;
4309 	} else {
4310 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4311 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4312 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4313 				err_extra, regno);
4314 			return -EACCES;
4315 		}
4316 		min_off = reg->smin_value + off;
4317 		max_off = reg->smax_value + off + access_size;
4318 	}
4319 
4320 	err = check_stack_slot_within_bounds(min_off, state, type);
4321 	if (!err && max_off > 0)
4322 		err = -EINVAL; /* out of stack access into non-negative offsets */
4323 
4324 	if (err) {
4325 		if (tnum_is_const(reg->var_off)) {
4326 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4327 				err_extra, regno, off, access_size);
4328 		} else {
4329 			char tn_buf[48];
4330 
4331 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4332 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4333 				err_extra, regno, tn_buf, access_size);
4334 		}
4335 	}
4336 	return err;
4337 }
4338 
4339 /* check whether memory at (regno + off) is accessible for t = (read | write)
4340  * if t==write, value_regno is a register which value is stored into memory
4341  * if t==read, value_regno is a register which will receive the value from memory
4342  * if t==write && value_regno==-1, some unknown value is stored into memory
4343  * if t==read && value_regno==-1, don't care what we read from memory
4344  */
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)4345 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4346 			    int off, int bpf_size, enum bpf_access_type t,
4347 			    int value_regno, bool strict_alignment_once)
4348 {
4349 	struct bpf_reg_state *regs = cur_regs(env);
4350 	struct bpf_reg_state *reg = regs + regno;
4351 	struct bpf_func_state *state;
4352 	int size, err = 0;
4353 
4354 	size = bpf_size_to_bytes(bpf_size);
4355 	if (size < 0)
4356 		return size;
4357 
4358 	/* alignment checks will add in reg->off themselves */
4359 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4360 	if (err)
4361 		return err;
4362 
4363 	/* for access checks, reg->off is just part of off */
4364 	off += reg->off;
4365 
4366 	if (reg->type == PTR_TO_MAP_KEY) {
4367 		if (t == BPF_WRITE) {
4368 			verbose(env, "write to change key R%d not allowed\n", regno);
4369 			return -EACCES;
4370 		}
4371 
4372 		err = check_mem_region_access(env, regno, off, size,
4373 					      reg->map_ptr->key_size, false);
4374 		if (err)
4375 			return err;
4376 		if (value_regno >= 0)
4377 			mark_reg_unknown(env, regs, value_regno);
4378 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4379 		if (t == BPF_WRITE && value_regno >= 0 &&
4380 		    is_pointer_value(env, value_regno)) {
4381 			verbose(env, "R%d leaks addr into map\n", value_regno);
4382 			return -EACCES;
4383 		}
4384 		err = check_map_access_type(env, regno, off, size, t);
4385 		if (err)
4386 			return err;
4387 		err = check_map_access(env, regno, off, size, false);
4388 		if (!err && t == BPF_READ && value_regno >= 0) {
4389 			struct bpf_map *map = reg->map_ptr;
4390 
4391 			/* if map is read-only, track its contents as scalars */
4392 			if (tnum_is_const(reg->var_off) &&
4393 			    bpf_map_is_rdonly(map) &&
4394 			    map->ops->map_direct_value_addr) {
4395 				int map_off = off + reg->var_off.value;
4396 				u64 val = 0;
4397 
4398 				err = bpf_map_direct_read(map, map_off, size,
4399 							  &val);
4400 				if (err)
4401 					return err;
4402 
4403 				regs[value_regno].type = SCALAR_VALUE;
4404 				__mark_reg_known(&regs[value_regno], val);
4405 			} else {
4406 				mark_reg_unknown(env, regs, value_regno);
4407 			}
4408 		}
4409 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4410 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4411 
4412 		if (type_may_be_null(reg->type)) {
4413 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4414 				reg_type_str(env, reg->type));
4415 			return -EACCES;
4416 		}
4417 
4418 		if (t == BPF_WRITE && rdonly_mem) {
4419 			verbose(env, "R%d cannot write into %s\n",
4420 				regno, reg_type_str(env, reg->type));
4421 			return -EACCES;
4422 		}
4423 
4424 		if (t == BPF_WRITE && value_regno >= 0 &&
4425 		    is_pointer_value(env, value_regno)) {
4426 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4427 			return -EACCES;
4428 		}
4429 
4430 		err = check_mem_region_access(env, regno, off, size,
4431 					      reg->mem_size, false);
4432 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4433 			mark_reg_unknown(env, regs, value_regno);
4434 	} else if (reg->type == PTR_TO_CTX) {
4435 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4436 		struct btf *btf = NULL;
4437 		u32 btf_id = 0;
4438 
4439 		if (t == BPF_WRITE && value_regno >= 0 &&
4440 		    is_pointer_value(env, value_regno)) {
4441 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4442 			return -EACCES;
4443 		}
4444 
4445 		err = check_ctx_reg(env, reg, regno);
4446 		if (err < 0)
4447 			return err;
4448 
4449 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4450 		if (err)
4451 			verbose_linfo(env, insn_idx, "; ");
4452 		if (!err && t == BPF_READ && value_regno >= 0) {
4453 			/* ctx access returns either a scalar, or a
4454 			 * PTR_TO_PACKET[_META,_END]. In the latter
4455 			 * case, we know the offset is zero.
4456 			 */
4457 			if (reg_type == SCALAR_VALUE) {
4458 				mark_reg_unknown(env, regs, value_regno);
4459 			} else {
4460 				mark_reg_known_zero(env, regs,
4461 						    value_regno);
4462 				if (type_may_be_null(reg_type))
4463 					regs[value_regno].id = ++env->id_gen;
4464 				/* A load of ctx field could have different
4465 				 * actual load size with the one encoded in the
4466 				 * insn. When the dst is PTR, it is for sure not
4467 				 * a sub-register.
4468 				 */
4469 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4470 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4471 					regs[value_regno].btf = btf;
4472 					regs[value_regno].btf_id = btf_id;
4473 				}
4474 			}
4475 			regs[value_regno].type = reg_type;
4476 		}
4477 
4478 	} else if (reg->type == PTR_TO_STACK) {
4479 		/* Basic bounds checks. */
4480 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4481 		if (err)
4482 			return err;
4483 
4484 		state = func(env, reg);
4485 		err = update_stack_depth(env, state, off);
4486 		if (err)
4487 			return err;
4488 
4489 		if (t == BPF_READ)
4490 			err = check_stack_read(env, regno, off, size,
4491 					       value_regno);
4492 		else
4493 			err = check_stack_write(env, regno, off, size,
4494 						value_regno, insn_idx);
4495 	} else if (reg_is_pkt_pointer(reg)) {
4496 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4497 			verbose(env, "cannot write into packet\n");
4498 			return -EACCES;
4499 		}
4500 		if (t == BPF_WRITE && value_regno >= 0 &&
4501 		    is_pointer_value(env, value_regno)) {
4502 			verbose(env, "R%d leaks addr into packet\n",
4503 				value_regno);
4504 			return -EACCES;
4505 		}
4506 		err = check_packet_access(env, regno, off, size, false);
4507 		if (!err && t == BPF_READ && value_regno >= 0)
4508 			mark_reg_unknown(env, regs, value_regno);
4509 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4510 		if (t == BPF_WRITE && value_regno >= 0 &&
4511 		    is_pointer_value(env, value_regno)) {
4512 			verbose(env, "R%d leaks addr into flow keys\n",
4513 				value_regno);
4514 			return -EACCES;
4515 		}
4516 
4517 		err = check_flow_keys_access(env, off, size);
4518 		if (!err && t == BPF_READ && value_regno >= 0)
4519 			mark_reg_unknown(env, regs, value_regno);
4520 	} else if (type_is_sk_pointer(reg->type)) {
4521 		if (t == BPF_WRITE) {
4522 			verbose(env, "R%d cannot write into %s\n",
4523 				regno, reg_type_str(env, reg->type));
4524 			return -EACCES;
4525 		}
4526 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4527 		if (!err && value_regno >= 0)
4528 			mark_reg_unknown(env, regs, value_regno);
4529 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4530 		err = check_tp_buffer_access(env, reg, regno, off, size);
4531 		if (!err && t == BPF_READ && value_regno >= 0)
4532 			mark_reg_unknown(env, regs, value_regno);
4533 	} else if (reg->type == PTR_TO_BTF_ID) {
4534 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4535 					      value_regno);
4536 	} else if (reg->type == CONST_PTR_TO_MAP) {
4537 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4538 					      value_regno);
4539 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4540 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4541 		const char *buf_info;
4542 		u32 *max_access;
4543 
4544 		if (rdonly_mem) {
4545 			if (t == BPF_WRITE) {
4546 				verbose(env, "R%d cannot write into %s\n",
4547 					regno, reg_type_str(env, reg->type));
4548 				return -EACCES;
4549 			}
4550 			buf_info = "rdonly";
4551 			max_access = &env->prog->aux->max_rdonly_access;
4552 		} else {
4553 			buf_info = "rdwr";
4554 			max_access = &env->prog->aux->max_rdwr_access;
4555 		}
4556 
4557 		err = check_buffer_access(env, reg, regno, off, size, false,
4558 					  buf_info, max_access);
4559 
4560 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4561 			mark_reg_unknown(env, regs, value_regno);
4562 	} else {
4563 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4564 			reg_type_str(env, reg->type));
4565 		return -EACCES;
4566 	}
4567 
4568 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4569 	    regs[value_regno].type == SCALAR_VALUE) {
4570 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4571 		coerce_reg_to_size(&regs[value_regno], size);
4572 	}
4573 	return err;
4574 }
4575 
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)4576 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4577 {
4578 	int load_reg;
4579 	int err;
4580 
4581 	switch (insn->imm) {
4582 	case BPF_ADD:
4583 	case BPF_ADD | BPF_FETCH:
4584 	case BPF_AND:
4585 	case BPF_AND | BPF_FETCH:
4586 	case BPF_OR:
4587 	case BPF_OR | BPF_FETCH:
4588 	case BPF_XOR:
4589 	case BPF_XOR | BPF_FETCH:
4590 	case BPF_XCHG:
4591 	case BPF_CMPXCHG:
4592 		break;
4593 	default:
4594 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4595 		return -EINVAL;
4596 	}
4597 
4598 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4599 		verbose(env, "invalid atomic operand size\n");
4600 		return -EINVAL;
4601 	}
4602 
4603 	/* check src1 operand */
4604 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4605 	if (err)
4606 		return err;
4607 
4608 	/* check src2 operand */
4609 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4610 	if (err)
4611 		return err;
4612 
4613 	if (insn->imm == BPF_CMPXCHG) {
4614 		/* Check comparison of R0 with memory location */
4615 		const u32 aux_reg = BPF_REG_0;
4616 
4617 		err = check_reg_arg(env, aux_reg, SRC_OP);
4618 		if (err)
4619 			return err;
4620 
4621 		if (is_pointer_value(env, aux_reg)) {
4622 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
4623 			return -EACCES;
4624 		}
4625 	}
4626 
4627 	if (is_pointer_value(env, insn->src_reg)) {
4628 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4629 		return -EACCES;
4630 	}
4631 
4632 	if (is_ctx_reg(env, insn->dst_reg) ||
4633 	    is_pkt_reg(env, insn->dst_reg) ||
4634 	    is_flow_key_reg(env, insn->dst_reg) ||
4635 	    is_sk_reg(env, insn->dst_reg)) {
4636 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4637 			insn->dst_reg,
4638 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4639 		return -EACCES;
4640 	}
4641 
4642 	if (insn->imm & BPF_FETCH) {
4643 		if (insn->imm == BPF_CMPXCHG)
4644 			load_reg = BPF_REG_0;
4645 		else
4646 			load_reg = insn->src_reg;
4647 
4648 		/* check and record load of old value */
4649 		err = check_reg_arg(env, load_reg, DST_OP);
4650 		if (err)
4651 			return err;
4652 	} else {
4653 		/* This instruction accesses a memory location but doesn't
4654 		 * actually load it into a register.
4655 		 */
4656 		load_reg = -1;
4657 	}
4658 
4659 	/* Check whether we can read the memory, with second call for fetch
4660 	 * case to simulate the register fill.
4661 	 */
4662 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4663 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4664 	if (!err && load_reg >= 0)
4665 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4666 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
4667 				       true);
4668 	if (err)
4669 		return err;
4670 
4671 	/* Check whether we can write into the same memory. */
4672 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4673 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4674 	if (err)
4675 		return err;
4676 
4677 	return 0;
4678 }
4679 
4680 /* When register 'regno' is used to read the stack (either directly or through
4681  * a helper function) make sure that it's within stack boundary and, depending
4682  * on the access type, that all elements of the stack are initialized.
4683  *
4684  * 'off' includes 'regno->off', but not its dynamic part (if any).
4685  *
4686  * All registers that have been spilled on the stack in the slots within the
4687  * read offsets are marked as read.
4688  */
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)4689 static int check_stack_range_initialized(
4690 		struct bpf_verifier_env *env, int regno, int off,
4691 		int access_size, bool zero_size_allowed,
4692 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4693 {
4694 	struct bpf_reg_state *reg = reg_state(env, regno);
4695 	struct bpf_func_state *state = func(env, reg);
4696 	int err, min_off, max_off, i, j, slot, spi;
4697 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4698 	enum bpf_access_type bounds_check_type;
4699 	/* Some accesses can write anything into the stack, others are
4700 	 * read-only.
4701 	 */
4702 	bool clobber = false;
4703 
4704 	if (access_size == 0 && !zero_size_allowed) {
4705 		verbose(env, "invalid zero-sized read\n");
4706 		return -EACCES;
4707 	}
4708 
4709 	if (type == ACCESS_HELPER) {
4710 		/* The bounds checks for writes are more permissive than for
4711 		 * reads. However, if raw_mode is not set, we'll do extra
4712 		 * checks below.
4713 		 */
4714 		bounds_check_type = BPF_WRITE;
4715 		clobber = true;
4716 	} else {
4717 		bounds_check_type = BPF_READ;
4718 	}
4719 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4720 					       type, bounds_check_type);
4721 	if (err)
4722 		return err;
4723 
4724 
4725 	if (tnum_is_const(reg->var_off)) {
4726 		min_off = max_off = reg->var_off.value + off;
4727 	} else {
4728 		/* Variable offset is prohibited for unprivileged mode for
4729 		 * simplicity since it requires corresponding support in
4730 		 * Spectre masking for stack ALU.
4731 		 * See also retrieve_ptr_limit().
4732 		 */
4733 		if (!env->bypass_spec_v1) {
4734 			char tn_buf[48];
4735 
4736 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4737 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4738 				regno, err_extra, tn_buf);
4739 			return -EACCES;
4740 		}
4741 		/* Only initialized buffer on stack is allowed to be accessed
4742 		 * with variable offset. With uninitialized buffer it's hard to
4743 		 * guarantee that whole memory is marked as initialized on
4744 		 * helper return since specific bounds are unknown what may
4745 		 * cause uninitialized stack leaking.
4746 		 */
4747 		if (meta && meta->raw_mode)
4748 			meta = NULL;
4749 
4750 		min_off = reg->smin_value + off;
4751 		max_off = reg->smax_value + off;
4752 	}
4753 
4754 	if (meta && meta->raw_mode) {
4755 		meta->access_size = access_size;
4756 		meta->regno = regno;
4757 		return 0;
4758 	}
4759 
4760 	for (i = min_off; i < max_off + access_size; i++) {
4761 		u8 *stype;
4762 
4763 		slot = -i - 1;
4764 		spi = slot / BPF_REG_SIZE;
4765 		if (state->allocated_stack <= slot)
4766 			goto err;
4767 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4768 		if (*stype == STACK_MISC)
4769 			goto mark;
4770 		if (*stype == STACK_ZERO) {
4771 			if (clobber) {
4772 				/* helper can write anything into the stack */
4773 				*stype = STACK_MISC;
4774 			}
4775 			goto mark;
4776 		}
4777 
4778 		if (is_spilled_reg(&state->stack[spi]) &&
4779 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4780 			goto mark;
4781 
4782 		if (is_spilled_reg(&state->stack[spi]) &&
4783 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4784 		     env->allow_ptr_leaks)) {
4785 			if (clobber) {
4786 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4787 				for (j = 0; j < BPF_REG_SIZE; j++)
4788 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4789 			}
4790 			goto mark;
4791 		}
4792 
4793 err:
4794 		if (tnum_is_const(reg->var_off)) {
4795 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4796 				err_extra, regno, min_off, i - min_off, access_size);
4797 		} else {
4798 			char tn_buf[48];
4799 
4800 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4801 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4802 				err_extra, regno, tn_buf, i - min_off, access_size);
4803 		}
4804 		return -EACCES;
4805 mark:
4806 		/* reading any byte out of 8-byte 'spill_slot' will cause
4807 		 * the whole slot to be marked as 'read'
4808 		 */
4809 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4810 			      state->stack[spi].spilled_ptr.parent,
4811 			      REG_LIVE_READ64);
4812 	}
4813 	return update_stack_depth(env, state, min_off);
4814 }
4815 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)4816 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4817 				   int access_size, bool zero_size_allowed,
4818 				   struct bpf_call_arg_meta *meta)
4819 {
4820 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4821 	const char *buf_info;
4822 	u32 *max_access;
4823 
4824 	switch (base_type(reg->type)) {
4825 	case PTR_TO_PACKET:
4826 	case PTR_TO_PACKET_META:
4827 		return check_packet_access(env, regno, reg->off, access_size,
4828 					   zero_size_allowed);
4829 	case PTR_TO_MAP_KEY:
4830 		if (meta && meta->raw_mode) {
4831 			verbose(env, "R%d cannot write into %s\n", regno,
4832 				reg_type_str(env, reg->type));
4833 			return -EACCES;
4834 		}
4835 		return check_mem_region_access(env, regno, reg->off, access_size,
4836 					       reg->map_ptr->key_size, false);
4837 	case PTR_TO_MAP_VALUE:
4838 		if (check_map_access_type(env, regno, reg->off, access_size,
4839 					  meta && meta->raw_mode ? BPF_WRITE :
4840 					  BPF_READ))
4841 			return -EACCES;
4842 		return check_map_access(env, regno, reg->off, access_size,
4843 					zero_size_allowed);
4844 	case PTR_TO_MEM:
4845 		if (type_is_rdonly_mem(reg->type)) {
4846 			if (meta && meta->raw_mode) {
4847 				verbose(env, "R%d cannot write into %s\n", regno,
4848 					reg_type_str(env, reg->type));
4849 				return -EACCES;
4850 			}
4851 		}
4852 		return check_mem_region_access(env, regno, reg->off,
4853 					       access_size, reg->mem_size,
4854 					       zero_size_allowed);
4855 	case PTR_TO_BUF:
4856 		if (type_is_rdonly_mem(reg->type)) {
4857 			if (meta && meta->raw_mode) {
4858 				verbose(env, "R%d cannot write into %s\n", regno,
4859 					reg_type_str(env, reg->type));
4860 				return -EACCES;
4861 			}
4862 
4863 			buf_info = "rdonly";
4864 			max_access = &env->prog->aux->max_rdonly_access;
4865 		} else {
4866 			buf_info = "rdwr";
4867 			max_access = &env->prog->aux->max_rdwr_access;
4868 		}
4869 		return check_buffer_access(env, reg, regno, reg->off,
4870 					   access_size, zero_size_allowed,
4871 					   buf_info, max_access);
4872 	case PTR_TO_STACK:
4873 		return check_stack_range_initialized(
4874 				env,
4875 				regno, reg->off, access_size,
4876 				zero_size_allowed, ACCESS_HELPER, meta);
4877 	default: /* scalar_value or invalid ptr */
4878 		/* Allow zero-byte read from NULL, regardless of pointer type */
4879 		if (zero_size_allowed && access_size == 0 &&
4880 		    register_is_null(reg))
4881 			return 0;
4882 
4883 		verbose(env, "R%d type=%s ", regno,
4884 			reg_type_str(env, reg->type));
4885 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4886 		return -EACCES;
4887 	}
4888 }
4889 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)4890 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4891 		   u32 regno, u32 mem_size)
4892 {
4893 	if (register_is_null(reg))
4894 		return 0;
4895 
4896 	if (type_may_be_null(reg->type)) {
4897 		/* Assuming that the register contains a value check if the memory
4898 		 * access is safe. Temporarily save and restore the register's state as
4899 		 * the conversion shouldn't be visible to a caller.
4900 		 */
4901 		const struct bpf_reg_state saved_reg = *reg;
4902 		int rv;
4903 
4904 		mark_ptr_not_null_reg(reg);
4905 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4906 		*reg = saved_reg;
4907 		return rv;
4908 	}
4909 
4910 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4911 }
4912 
4913 /* Implementation details:
4914  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4915  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4916  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4917  * value_or_null->value transition, since the verifier only cares about
4918  * the range of access to valid map value pointer and doesn't care about actual
4919  * address of the map element.
4920  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4921  * reg->id > 0 after value_or_null->value transition. By doing so
4922  * two bpf_map_lookups will be considered two different pointers that
4923  * point to different bpf_spin_locks.
4924  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4925  * dead-locks.
4926  * Since only one bpf_spin_lock is allowed the checks are simpler than
4927  * reg_is_refcounted() logic. The verifier needs to remember only
4928  * one spin_lock instead of array of acquired_refs.
4929  * cur_state->active_spin_lock remembers which map value element got locked
4930  * and clears it after bpf_spin_unlock.
4931  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)4932 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4933 			     bool is_lock)
4934 {
4935 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4936 	struct bpf_verifier_state *cur = env->cur_state;
4937 	bool is_const = tnum_is_const(reg->var_off);
4938 	struct bpf_map *map = reg->map_ptr;
4939 	u64 val = reg->var_off.value;
4940 
4941 	if (!is_const) {
4942 		verbose(env,
4943 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4944 			regno);
4945 		return -EINVAL;
4946 	}
4947 	if (!map->btf) {
4948 		verbose(env,
4949 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4950 			map->name);
4951 		return -EINVAL;
4952 	}
4953 	if (!map_value_has_spin_lock(map)) {
4954 		if (map->spin_lock_off == -E2BIG)
4955 			verbose(env,
4956 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4957 				map->name);
4958 		else if (map->spin_lock_off == -ENOENT)
4959 			verbose(env,
4960 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4961 				map->name);
4962 		else
4963 			verbose(env,
4964 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4965 				map->name);
4966 		return -EINVAL;
4967 	}
4968 	if (map->spin_lock_off != val + reg->off) {
4969 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4970 			val + reg->off);
4971 		return -EINVAL;
4972 	}
4973 	if (is_lock) {
4974 		if (cur->active_spin_lock) {
4975 			verbose(env,
4976 				"Locking two bpf_spin_locks are not allowed\n");
4977 			return -EINVAL;
4978 		}
4979 		cur->active_spin_lock = reg->id;
4980 	} else {
4981 		if (!cur->active_spin_lock) {
4982 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4983 			return -EINVAL;
4984 		}
4985 		if (cur->active_spin_lock != reg->id) {
4986 			verbose(env, "bpf_spin_unlock of different lock\n");
4987 			return -EINVAL;
4988 		}
4989 		cur->active_spin_lock = 0;
4990 	}
4991 	return 0;
4992 }
4993 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)4994 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4995 			      struct bpf_call_arg_meta *meta)
4996 {
4997 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4998 	bool is_const = tnum_is_const(reg->var_off);
4999 	struct bpf_map *map = reg->map_ptr;
5000 	u64 val = reg->var_off.value;
5001 
5002 	if (!is_const) {
5003 		verbose(env,
5004 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5005 			regno);
5006 		return -EINVAL;
5007 	}
5008 	if (!map->btf) {
5009 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5010 			map->name);
5011 		return -EINVAL;
5012 	}
5013 	if (!map_value_has_timer(map)) {
5014 		if (map->timer_off == -E2BIG)
5015 			verbose(env,
5016 				"map '%s' has more than one 'struct bpf_timer'\n",
5017 				map->name);
5018 		else if (map->timer_off == -ENOENT)
5019 			verbose(env,
5020 				"map '%s' doesn't have 'struct bpf_timer'\n",
5021 				map->name);
5022 		else
5023 			verbose(env,
5024 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5025 				map->name);
5026 		return -EINVAL;
5027 	}
5028 	if (map->timer_off != val + reg->off) {
5029 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5030 			val + reg->off, map->timer_off);
5031 		return -EINVAL;
5032 	}
5033 	if (meta->map_ptr) {
5034 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5035 		return -EFAULT;
5036 	}
5037 	meta->map_uid = reg->map_uid;
5038 	meta->map_ptr = map;
5039 	return 0;
5040 }
5041 
arg_type_is_mem_ptr(enum bpf_arg_type type)5042 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
5043 {
5044 	return base_type(type) == ARG_PTR_TO_MEM ||
5045 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
5046 }
5047 
arg_type_is_mem_size(enum bpf_arg_type type)5048 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5049 {
5050 	return type == ARG_CONST_SIZE ||
5051 	       type == ARG_CONST_SIZE_OR_ZERO;
5052 }
5053 
arg_type_is_alloc_size(enum bpf_arg_type type)5054 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5055 {
5056 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5057 }
5058 
arg_type_is_int_ptr(enum bpf_arg_type type)5059 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5060 {
5061 	return type == ARG_PTR_TO_INT ||
5062 	       type == ARG_PTR_TO_LONG;
5063 }
5064 
int_ptr_type_to_size(enum bpf_arg_type type)5065 static int int_ptr_type_to_size(enum bpf_arg_type type)
5066 {
5067 	if (type == ARG_PTR_TO_INT)
5068 		return sizeof(u32);
5069 	else if (type == ARG_PTR_TO_LONG)
5070 		return sizeof(u64);
5071 
5072 	return -EINVAL;
5073 }
5074 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)5075 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5076 				 const struct bpf_call_arg_meta *meta,
5077 				 enum bpf_arg_type *arg_type)
5078 {
5079 	if (!meta->map_ptr) {
5080 		/* kernel subsystem misconfigured verifier */
5081 		verbose(env, "invalid map_ptr to access map->type\n");
5082 		return -EACCES;
5083 	}
5084 
5085 	switch (meta->map_ptr->map_type) {
5086 	case BPF_MAP_TYPE_SOCKMAP:
5087 	case BPF_MAP_TYPE_SOCKHASH:
5088 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5089 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5090 		} else {
5091 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5092 			return -EINVAL;
5093 		}
5094 		break;
5095 
5096 	default:
5097 		break;
5098 	}
5099 	return 0;
5100 }
5101 
5102 struct bpf_reg_types {
5103 	const enum bpf_reg_type types[10];
5104 	u32 *btf_id;
5105 };
5106 
5107 static const struct bpf_reg_types map_key_value_types = {
5108 	.types = {
5109 		PTR_TO_STACK,
5110 		PTR_TO_PACKET,
5111 		PTR_TO_PACKET_META,
5112 		PTR_TO_MAP_KEY,
5113 		PTR_TO_MAP_VALUE,
5114 	},
5115 };
5116 
5117 static const struct bpf_reg_types sock_types = {
5118 	.types = {
5119 		PTR_TO_SOCK_COMMON,
5120 		PTR_TO_SOCKET,
5121 		PTR_TO_TCP_SOCK,
5122 		PTR_TO_XDP_SOCK,
5123 	},
5124 };
5125 
5126 #ifdef CONFIG_NET
5127 static const struct bpf_reg_types btf_id_sock_common_types = {
5128 	.types = {
5129 		PTR_TO_SOCK_COMMON,
5130 		PTR_TO_SOCKET,
5131 		PTR_TO_TCP_SOCK,
5132 		PTR_TO_XDP_SOCK,
5133 		PTR_TO_BTF_ID,
5134 	},
5135 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5136 };
5137 #endif
5138 
5139 static const struct bpf_reg_types mem_types = {
5140 	.types = {
5141 		PTR_TO_STACK,
5142 		PTR_TO_PACKET,
5143 		PTR_TO_PACKET_META,
5144 		PTR_TO_MAP_KEY,
5145 		PTR_TO_MAP_VALUE,
5146 		PTR_TO_MEM,
5147 		PTR_TO_BUF,
5148 	},
5149 };
5150 
5151 static const struct bpf_reg_types int_ptr_types = {
5152 	.types = {
5153 		PTR_TO_STACK,
5154 		PTR_TO_PACKET,
5155 		PTR_TO_PACKET_META,
5156 		PTR_TO_MAP_KEY,
5157 		PTR_TO_MAP_VALUE,
5158 	},
5159 };
5160 
5161 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5162 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5163 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5164 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
5165 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5166 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5167 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5168 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
5169 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5170 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5171 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5172 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5173 
5174 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5175 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5176 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5177 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
5178 	[ARG_CONST_SIZE]		= &scalar_types,
5179 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5180 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5181 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5182 	[ARG_PTR_TO_CTX]		= &context_types,
5183 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5184 #ifdef CONFIG_NET
5185 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5186 #endif
5187 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5188 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5189 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5190 	[ARG_PTR_TO_MEM]		= &mem_types,
5191 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
5192 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5193 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5194 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5195 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5196 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5197 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5198 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5199 	[ARG_PTR_TO_TIMER]		= &timer_types,
5200 };
5201 
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id)5202 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5203 			  enum bpf_arg_type arg_type,
5204 			  const u32 *arg_btf_id)
5205 {
5206 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5207 	enum bpf_reg_type expected, type = reg->type;
5208 	const struct bpf_reg_types *compatible;
5209 	int i, j;
5210 
5211 	compatible = compatible_reg_types[base_type(arg_type)];
5212 	if (!compatible) {
5213 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5214 		return -EFAULT;
5215 	}
5216 
5217 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5218 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5219 	 *
5220 	 * Same for MAYBE_NULL:
5221 	 *
5222 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5223 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5224 	 *
5225 	 * Therefore we fold these flags depending on the arg_type before comparison.
5226 	 */
5227 	if (arg_type & MEM_RDONLY)
5228 		type &= ~MEM_RDONLY;
5229 	if (arg_type & PTR_MAYBE_NULL)
5230 		type &= ~PTR_MAYBE_NULL;
5231 
5232 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5233 		expected = compatible->types[i];
5234 		if (expected == NOT_INIT)
5235 			break;
5236 
5237 		if (type == expected)
5238 			goto found;
5239 	}
5240 
5241 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5242 	for (j = 0; j + 1 < i; j++)
5243 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5244 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5245 	return -EACCES;
5246 
5247 found:
5248 	if (reg->type == PTR_TO_BTF_ID) {
5249 		if (!arg_btf_id) {
5250 			if (!compatible->btf_id) {
5251 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5252 				return -EFAULT;
5253 			}
5254 			arg_btf_id = compatible->btf_id;
5255 		}
5256 
5257 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5258 					  btf_vmlinux, *arg_btf_id)) {
5259 			verbose(env, "R%d is of type %s but %s is expected\n",
5260 				regno, kernel_type_name(reg->btf, reg->btf_id),
5261 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5262 			return -EACCES;
5263 		}
5264 
5265 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5266 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5267 				regno);
5268 			return -EACCES;
5269 		}
5270 	}
5271 
5272 	return 0;
5273 }
5274 
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)5275 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5276 			  struct bpf_call_arg_meta *meta,
5277 			  const struct bpf_func_proto *fn)
5278 {
5279 	u32 regno = BPF_REG_1 + arg;
5280 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5281 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5282 	enum bpf_reg_type type = reg->type;
5283 	int err = 0;
5284 
5285 	if (arg_type == ARG_DONTCARE)
5286 		return 0;
5287 
5288 	err = check_reg_arg(env, regno, SRC_OP);
5289 	if (err)
5290 		return err;
5291 
5292 	if (arg_type == ARG_ANYTHING) {
5293 		if (is_pointer_value(env, regno)) {
5294 			verbose(env, "R%d leaks addr into helper function\n",
5295 				regno);
5296 			return -EACCES;
5297 		}
5298 		return 0;
5299 	}
5300 
5301 	if (type_is_pkt_pointer(type) &&
5302 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5303 		verbose(env, "helper access to the packet is not allowed\n");
5304 		return -EACCES;
5305 	}
5306 
5307 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5308 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5309 		err = resolve_map_arg_type(env, meta, &arg_type);
5310 		if (err)
5311 			return err;
5312 	}
5313 
5314 	if (register_is_null(reg) && type_may_be_null(arg_type))
5315 		/* A NULL register has a SCALAR_VALUE type, so skip
5316 		 * type checking.
5317 		 */
5318 		goto skip_type_check;
5319 
5320 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5321 	if (err)
5322 		return err;
5323 
5324 	if (type == PTR_TO_CTX) {
5325 		err = check_ctx_reg(env, reg, regno);
5326 		if (err < 0)
5327 			return err;
5328 	}
5329 
5330 skip_type_check:
5331 	if (reg->ref_obj_id) {
5332 		if (meta->ref_obj_id) {
5333 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5334 				regno, reg->ref_obj_id,
5335 				meta->ref_obj_id);
5336 			return -EFAULT;
5337 		}
5338 		meta->ref_obj_id = reg->ref_obj_id;
5339 	}
5340 
5341 	if (arg_type == ARG_CONST_MAP_PTR) {
5342 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5343 		if (meta->map_ptr) {
5344 			/* Use map_uid (which is unique id of inner map) to reject:
5345 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5346 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5347 			 * if (inner_map1 && inner_map2) {
5348 			 *     timer = bpf_map_lookup_elem(inner_map1);
5349 			 *     if (timer)
5350 			 *         // mismatch would have been allowed
5351 			 *         bpf_timer_init(timer, inner_map2);
5352 			 * }
5353 			 *
5354 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5355 			 */
5356 			if (meta->map_ptr != reg->map_ptr ||
5357 			    meta->map_uid != reg->map_uid) {
5358 				verbose(env,
5359 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5360 					meta->map_uid, reg->map_uid);
5361 				return -EINVAL;
5362 			}
5363 		}
5364 		meta->map_ptr = reg->map_ptr;
5365 		meta->map_uid = reg->map_uid;
5366 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5367 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5368 		 * check that [key, key + map->key_size) are within
5369 		 * stack limits and initialized
5370 		 */
5371 		if (!meta->map_ptr) {
5372 			/* in function declaration map_ptr must come before
5373 			 * map_key, so that it's verified and known before
5374 			 * we have to check map_key here. Otherwise it means
5375 			 * that kernel subsystem misconfigured verifier
5376 			 */
5377 			verbose(env, "invalid map_ptr to access map->key\n");
5378 			return -EACCES;
5379 		}
5380 		err = check_helper_mem_access(env, regno,
5381 					      meta->map_ptr->key_size, false,
5382 					      NULL);
5383 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5384 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5385 		if (type_may_be_null(arg_type) && register_is_null(reg))
5386 			return 0;
5387 
5388 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5389 		 * check [value, value + map->value_size) validity
5390 		 */
5391 		if (!meta->map_ptr) {
5392 			/* kernel subsystem misconfigured verifier */
5393 			verbose(env, "invalid map_ptr to access map->value\n");
5394 			return -EACCES;
5395 		}
5396 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5397 		err = check_helper_mem_access(env, regno,
5398 					      meta->map_ptr->value_size, false,
5399 					      meta);
5400 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5401 		if (!reg->btf_id) {
5402 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5403 			return -EACCES;
5404 		}
5405 		meta->ret_btf = reg->btf;
5406 		meta->ret_btf_id = reg->btf_id;
5407 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5408 		if (meta->func_id == BPF_FUNC_spin_lock) {
5409 			if (process_spin_lock(env, regno, true))
5410 				return -EACCES;
5411 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5412 			if (process_spin_lock(env, regno, false))
5413 				return -EACCES;
5414 		} else {
5415 			verbose(env, "verifier internal error\n");
5416 			return -EFAULT;
5417 		}
5418 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5419 		if (process_timer_func(env, regno, meta))
5420 			return -EACCES;
5421 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5422 		meta->subprogno = reg->subprogno;
5423 	} else if (arg_type_is_mem_ptr(arg_type)) {
5424 		/* The access to this pointer is only checked when we hit the
5425 		 * next is_mem_size argument below.
5426 		 */
5427 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5428 	} else if (arg_type_is_mem_size(arg_type)) {
5429 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5430 
5431 		/* This is used to refine r0 return value bounds for helpers
5432 		 * that enforce this value as an upper bound on return values.
5433 		 * See do_refine_retval_range() for helpers that can refine
5434 		 * the return value. C type of helper is u32 so we pull register
5435 		 * bound from umax_value however, if negative verifier errors
5436 		 * out. Only upper bounds can be learned because retval is an
5437 		 * int type and negative retvals are allowed.
5438 		 */
5439 		meta->msize_max_value = reg->umax_value;
5440 
5441 		/* The register is SCALAR_VALUE; the access check
5442 		 * happens using its boundaries.
5443 		 */
5444 		if (!tnum_is_const(reg->var_off))
5445 			/* For unprivileged variable accesses, disable raw
5446 			 * mode so that the program is required to
5447 			 * initialize all the memory that the helper could
5448 			 * just partially fill up.
5449 			 */
5450 			meta = NULL;
5451 
5452 		if (reg->smin_value < 0) {
5453 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5454 				regno);
5455 			return -EACCES;
5456 		}
5457 
5458 		if (reg->umin_value == 0) {
5459 			err = check_helper_mem_access(env, regno - 1, 0,
5460 						      zero_size_allowed,
5461 						      meta);
5462 			if (err)
5463 				return err;
5464 		}
5465 
5466 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5467 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5468 				regno);
5469 			return -EACCES;
5470 		}
5471 		err = check_helper_mem_access(env, regno - 1,
5472 					      reg->umax_value,
5473 					      zero_size_allowed, meta);
5474 		if (!err)
5475 			err = mark_chain_precision(env, regno);
5476 	} else if (arg_type_is_alloc_size(arg_type)) {
5477 		if (!tnum_is_const(reg->var_off)) {
5478 			verbose(env, "R%d is not a known constant'\n",
5479 				regno);
5480 			return -EACCES;
5481 		}
5482 		meta->mem_size = reg->var_off.value;
5483 	} else if (arg_type_is_int_ptr(arg_type)) {
5484 		int size = int_ptr_type_to_size(arg_type);
5485 
5486 		err = check_helper_mem_access(env, regno, size, false, meta);
5487 		if (err)
5488 			return err;
5489 		err = check_ptr_alignment(env, reg, 0, size, true);
5490 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5491 		struct bpf_map *map = reg->map_ptr;
5492 		int map_off;
5493 		u64 map_addr;
5494 		char *str_ptr;
5495 
5496 		if (!bpf_map_is_rdonly(map)) {
5497 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5498 			return -EACCES;
5499 		}
5500 
5501 		if (!tnum_is_const(reg->var_off)) {
5502 			verbose(env, "R%d is not a constant address'\n", regno);
5503 			return -EACCES;
5504 		}
5505 
5506 		if (!map->ops->map_direct_value_addr) {
5507 			verbose(env, "no direct value access support for this map type\n");
5508 			return -EACCES;
5509 		}
5510 
5511 		err = check_map_access(env, regno, reg->off,
5512 				       map->value_size - reg->off, false);
5513 		if (err)
5514 			return err;
5515 
5516 		map_off = reg->off + reg->var_off.value;
5517 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5518 		if (err) {
5519 			verbose(env, "direct value access on string failed\n");
5520 			return err;
5521 		}
5522 
5523 		str_ptr = (char *)(long)(map_addr);
5524 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5525 			verbose(env, "string is not zero-terminated\n");
5526 			return -EINVAL;
5527 		}
5528 	}
5529 
5530 	return err;
5531 }
5532 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)5533 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5534 {
5535 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5536 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5537 
5538 	if (func_id != BPF_FUNC_map_update_elem)
5539 		return false;
5540 
5541 	/* It's not possible to get access to a locked struct sock in these
5542 	 * contexts, so updating is safe.
5543 	 */
5544 	switch (type) {
5545 	case BPF_PROG_TYPE_TRACING:
5546 		if (eatype == BPF_TRACE_ITER)
5547 			return true;
5548 		break;
5549 	case BPF_PROG_TYPE_SOCKET_FILTER:
5550 	case BPF_PROG_TYPE_SCHED_CLS:
5551 	case BPF_PROG_TYPE_SCHED_ACT:
5552 	case BPF_PROG_TYPE_XDP:
5553 	case BPF_PROG_TYPE_SK_REUSEPORT:
5554 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5555 	case BPF_PROG_TYPE_SK_LOOKUP:
5556 		return true;
5557 	default:
5558 		break;
5559 	}
5560 
5561 	verbose(env, "cannot update sockmap in this context\n");
5562 	return false;
5563 }
5564 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)5565 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5566 {
5567 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5568 }
5569 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)5570 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5571 					struct bpf_map *map, int func_id)
5572 {
5573 	if (!map)
5574 		return 0;
5575 
5576 	/* We need a two way check, first is from map perspective ... */
5577 	switch (map->map_type) {
5578 	case BPF_MAP_TYPE_PROG_ARRAY:
5579 		if (func_id != BPF_FUNC_tail_call)
5580 			goto error;
5581 		break;
5582 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5583 		if (func_id != BPF_FUNC_perf_event_read &&
5584 		    func_id != BPF_FUNC_perf_event_output &&
5585 		    func_id != BPF_FUNC_skb_output &&
5586 		    func_id != BPF_FUNC_perf_event_read_value &&
5587 		    func_id != BPF_FUNC_xdp_output)
5588 			goto error;
5589 		break;
5590 	case BPF_MAP_TYPE_RINGBUF:
5591 		if (func_id != BPF_FUNC_ringbuf_output &&
5592 		    func_id != BPF_FUNC_ringbuf_reserve &&
5593 		    func_id != BPF_FUNC_ringbuf_query)
5594 			goto error;
5595 		break;
5596 	case BPF_MAP_TYPE_STACK_TRACE:
5597 		if (func_id != BPF_FUNC_get_stackid)
5598 			goto error;
5599 		break;
5600 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5601 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5602 		    func_id != BPF_FUNC_current_task_under_cgroup)
5603 			goto error;
5604 		break;
5605 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5606 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5607 		if (func_id != BPF_FUNC_get_local_storage)
5608 			goto error;
5609 		break;
5610 	case BPF_MAP_TYPE_DEVMAP:
5611 	case BPF_MAP_TYPE_DEVMAP_HASH:
5612 		if (func_id != BPF_FUNC_redirect_map &&
5613 		    func_id != BPF_FUNC_map_lookup_elem)
5614 			goto error;
5615 		break;
5616 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5617 	 * appear.
5618 	 */
5619 	case BPF_MAP_TYPE_CPUMAP:
5620 		if (func_id != BPF_FUNC_redirect_map)
5621 			goto error;
5622 		break;
5623 	case BPF_MAP_TYPE_XSKMAP:
5624 		if (func_id != BPF_FUNC_redirect_map &&
5625 		    func_id != BPF_FUNC_map_lookup_elem)
5626 			goto error;
5627 		break;
5628 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5629 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5630 		if (func_id != BPF_FUNC_map_lookup_elem)
5631 			goto error;
5632 		break;
5633 	case BPF_MAP_TYPE_SOCKMAP:
5634 		if (func_id != BPF_FUNC_sk_redirect_map &&
5635 		    func_id != BPF_FUNC_sock_map_update &&
5636 		    func_id != BPF_FUNC_map_delete_elem &&
5637 		    func_id != BPF_FUNC_msg_redirect_map &&
5638 		    func_id != BPF_FUNC_sk_select_reuseport &&
5639 		    func_id != BPF_FUNC_map_lookup_elem &&
5640 		    !may_update_sockmap(env, func_id))
5641 			goto error;
5642 		break;
5643 	case BPF_MAP_TYPE_SOCKHASH:
5644 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5645 		    func_id != BPF_FUNC_sock_hash_update &&
5646 		    func_id != BPF_FUNC_map_delete_elem &&
5647 		    func_id != BPF_FUNC_msg_redirect_hash &&
5648 		    func_id != BPF_FUNC_sk_select_reuseport &&
5649 		    func_id != BPF_FUNC_map_lookup_elem &&
5650 		    !may_update_sockmap(env, func_id))
5651 			goto error;
5652 		break;
5653 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5654 		if (func_id != BPF_FUNC_sk_select_reuseport)
5655 			goto error;
5656 		break;
5657 	case BPF_MAP_TYPE_QUEUE:
5658 	case BPF_MAP_TYPE_STACK:
5659 		if (func_id != BPF_FUNC_map_peek_elem &&
5660 		    func_id != BPF_FUNC_map_pop_elem &&
5661 		    func_id != BPF_FUNC_map_push_elem)
5662 			goto error;
5663 		break;
5664 	case BPF_MAP_TYPE_SK_STORAGE:
5665 		if (func_id != BPF_FUNC_sk_storage_get &&
5666 		    func_id != BPF_FUNC_sk_storage_delete)
5667 			goto error;
5668 		break;
5669 	case BPF_MAP_TYPE_INODE_STORAGE:
5670 		if (func_id != BPF_FUNC_inode_storage_get &&
5671 		    func_id != BPF_FUNC_inode_storage_delete)
5672 			goto error;
5673 		break;
5674 	case BPF_MAP_TYPE_TASK_STORAGE:
5675 		if (func_id != BPF_FUNC_task_storage_get &&
5676 		    func_id != BPF_FUNC_task_storage_delete)
5677 			goto error;
5678 		break;
5679 	default:
5680 		break;
5681 	}
5682 
5683 	/* ... and second from the function itself. */
5684 	switch (func_id) {
5685 	case BPF_FUNC_tail_call:
5686 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5687 			goto error;
5688 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5689 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5690 			return -EINVAL;
5691 		}
5692 		break;
5693 	case BPF_FUNC_perf_event_read:
5694 	case BPF_FUNC_perf_event_output:
5695 	case BPF_FUNC_perf_event_read_value:
5696 	case BPF_FUNC_skb_output:
5697 	case BPF_FUNC_xdp_output:
5698 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5699 			goto error;
5700 		break;
5701 	case BPF_FUNC_ringbuf_output:
5702 	case BPF_FUNC_ringbuf_reserve:
5703 	case BPF_FUNC_ringbuf_query:
5704 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5705 			goto error;
5706 		break;
5707 	case BPF_FUNC_get_stackid:
5708 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5709 			goto error;
5710 		break;
5711 	case BPF_FUNC_current_task_under_cgroup:
5712 	case BPF_FUNC_skb_under_cgroup:
5713 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5714 			goto error;
5715 		break;
5716 	case BPF_FUNC_redirect_map:
5717 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5718 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5719 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5720 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5721 			goto error;
5722 		break;
5723 	case BPF_FUNC_sk_redirect_map:
5724 	case BPF_FUNC_msg_redirect_map:
5725 	case BPF_FUNC_sock_map_update:
5726 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5727 			goto error;
5728 		break;
5729 	case BPF_FUNC_sk_redirect_hash:
5730 	case BPF_FUNC_msg_redirect_hash:
5731 	case BPF_FUNC_sock_hash_update:
5732 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5733 			goto error;
5734 		break;
5735 	case BPF_FUNC_get_local_storage:
5736 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5737 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5738 			goto error;
5739 		break;
5740 	case BPF_FUNC_sk_select_reuseport:
5741 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5742 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5743 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5744 			goto error;
5745 		break;
5746 	case BPF_FUNC_map_peek_elem:
5747 	case BPF_FUNC_map_pop_elem:
5748 	case BPF_FUNC_map_push_elem:
5749 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5750 		    map->map_type != BPF_MAP_TYPE_STACK)
5751 			goto error;
5752 		break;
5753 	case BPF_FUNC_sk_storage_get:
5754 	case BPF_FUNC_sk_storage_delete:
5755 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5756 			goto error;
5757 		break;
5758 	case BPF_FUNC_inode_storage_get:
5759 	case BPF_FUNC_inode_storage_delete:
5760 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5761 			goto error;
5762 		break;
5763 	case BPF_FUNC_task_storage_get:
5764 	case BPF_FUNC_task_storage_delete:
5765 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5766 			goto error;
5767 		break;
5768 	default:
5769 		break;
5770 	}
5771 
5772 	return 0;
5773 error:
5774 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5775 		map->map_type, func_id_name(func_id), func_id);
5776 	return -EINVAL;
5777 }
5778 
check_raw_mode_ok(const struct bpf_func_proto * fn)5779 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5780 {
5781 	int count = 0;
5782 
5783 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5784 		count++;
5785 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5786 		count++;
5787 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5788 		count++;
5789 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5790 		count++;
5791 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5792 		count++;
5793 
5794 	/* We only support one arg being in raw mode at the moment,
5795 	 * which is sufficient for the helper functions we have
5796 	 * right now.
5797 	 */
5798 	return count <= 1;
5799 }
5800 
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)5801 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5802 				    enum bpf_arg_type arg_next)
5803 {
5804 	return (arg_type_is_mem_ptr(arg_curr) &&
5805 	        !arg_type_is_mem_size(arg_next)) ||
5806 	       (!arg_type_is_mem_ptr(arg_curr) &&
5807 		arg_type_is_mem_size(arg_next));
5808 }
5809 
check_arg_pair_ok(const struct bpf_func_proto * fn)5810 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5811 {
5812 	/* bpf_xxx(..., buf, len) call will access 'len'
5813 	 * bytes from memory 'buf'. Both arg types need
5814 	 * to be paired, so make sure there's no buggy
5815 	 * helper function specification.
5816 	 */
5817 	if (arg_type_is_mem_size(fn->arg1_type) ||
5818 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5819 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5820 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5821 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5822 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5823 		return false;
5824 
5825 	return true;
5826 }
5827 
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5828 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5829 {
5830 	int count = 0;
5831 
5832 	if (arg_type_may_be_refcounted(fn->arg1_type))
5833 		count++;
5834 	if (arg_type_may_be_refcounted(fn->arg2_type))
5835 		count++;
5836 	if (arg_type_may_be_refcounted(fn->arg3_type))
5837 		count++;
5838 	if (arg_type_may_be_refcounted(fn->arg4_type))
5839 		count++;
5840 	if (arg_type_may_be_refcounted(fn->arg5_type))
5841 		count++;
5842 
5843 	/* A reference acquiring function cannot acquire
5844 	 * another refcounted ptr.
5845 	 */
5846 	if (may_be_acquire_function(func_id) && count)
5847 		return false;
5848 
5849 	/* We only support one arg being unreferenced at the moment,
5850 	 * which is sufficient for the helper functions we have right now.
5851 	 */
5852 	return count <= 1;
5853 }
5854 
check_btf_id_ok(const struct bpf_func_proto * fn)5855 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5856 {
5857 	int i;
5858 
5859 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5860 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5861 			return false;
5862 
5863 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5864 			return false;
5865 	}
5866 
5867 	return true;
5868 }
5869 
check_func_proto(const struct bpf_func_proto * fn,int func_id)5870 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5871 {
5872 	return check_raw_mode_ok(fn) &&
5873 	       check_arg_pair_ok(fn) &&
5874 	       check_btf_id_ok(fn) &&
5875 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5876 }
5877 
5878 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5879  * are now invalid, so turn them into unknown SCALAR_VALUE.
5880  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5881 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5882 {
5883 	struct bpf_func_state *state;
5884 	struct bpf_reg_state *reg;
5885 
5886 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5887 		if (reg_is_pkt_pointer_any(reg))
5888 			__mark_reg_unknown(env, reg);
5889 	}));
5890 }
5891 
5892 enum {
5893 	AT_PKT_END = -1,
5894 	BEYOND_PKT_END = -2,
5895 };
5896 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5897 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5898 {
5899 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5900 	struct bpf_reg_state *reg = &state->regs[regn];
5901 
5902 	if (reg->type != PTR_TO_PACKET)
5903 		/* PTR_TO_PACKET_META is not supported yet */
5904 		return;
5905 
5906 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5907 	 * How far beyond pkt_end it goes is unknown.
5908 	 * if (!range_open) it's the case of pkt >= pkt_end
5909 	 * if (range_open) it's the case of pkt > pkt_end
5910 	 * hence this pointer is at least 1 byte bigger than pkt_end
5911 	 */
5912 	if (range_open)
5913 		reg->range = BEYOND_PKT_END;
5914 	else
5915 		reg->range = AT_PKT_END;
5916 }
5917 
5918 /* The pointer with the specified id has released its reference to kernel
5919  * resources. Identify all copies of the same pointer and clear the reference.
5920  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5921 static int release_reference(struct bpf_verifier_env *env,
5922 			     int ref_obj_id)
5923 {
5924 	struct bpf_func_state *state;
5925 	struct bpf_reg_state *reg;
5926 	int err;
5927 
5928 	err = release_reference_state(cur_func(env), ref_obj_id);
5929 	if (err)
5930 		return err;
5931 
5932 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5933 		if (reg->ref_obj_id == ref_obj_id) {
5934 			if (!env->allow_ptr_leaks)
5935 				__mark_reg_not_init(env, reg);
5936 			else
5937 				__mark_reg_unknown(env, reg);
5938 		}
5939 	}));
5940 
5941 	return 0;
5942 }
5943 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5944 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5945 				    struct bpf_reg_state *regs)
5946 {
5947 	int i;
5948 
5949 	/* after the call registers r0 - r5 were scratched */
5950 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5951 		mark_reg_not_init(env, regs, caller_saved[i]);
5952 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5953 	}
5954 }
5955 
5956 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5957 				   struct bpf_func_state *caller,
5958 				   struct bpf_func_state *callee,
5959 				   int insn_idx);
5960 
5961 static int set_callee_state(struct bpf_verifier_env *env,
5962 			    struct bpf_func_state *caller,
5963 			    struct bpf_func_state *callee, int insn_idx);
5964 
__check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx,int subprog,set_callee_state_fn set_callee_state_cb)5965 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5966 			     int *insn_idx, int subprog,
5967 			     set_callee_state_fn set_callee_state_cb)
5968 {
5969 	struct bpf_verifier_state *state = env->cur_state;
5970 	struct bpf_func_info_aux *func_info_aux;
5971 	struct bpf_func_state *caller, *callee;
5972 	int err;
5973 	bool is_global = false;
5974 
5975 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5976 		verbose(env, "the call stack of %d frames is too deep\n",
5977 			state->curframe + 2);
5978 		return -E2BIG;
5979 	}
5980 
5981 	caller = state->frame[state->curframe];
5982 	if (state->frame[state->curframe + 1]) {
5983 		verbose(env, "verifier bug. Frame %d already allocated\n",
5984 			state->curframe + 1);
5985 		return -EFAULT;
5986 	}
5987 
5988 	func_info_aux = env->prog->aux->func_info_aux;
5989 	if (func_info_aux)
5990 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5991 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5992 	if (err == -EFAULT)
5993 		return err;
5994 	if (is_global) {
5995 		if (err) {
5996 			verbose(env, "Caller passes invalid args into func#%d\n",
5997 				subprog);
5998 			return err;
5999 		} else {
6000 			if (env->log.level & BPF_LOG_LEVEL)
6001 				verbose(env,
6002 					"Func#%d is global and valid. Skipping.\n",
6003 					subprog);
6004 			clear_caller_saved_regs(env, caller->regs);
6005 
6006 			/* All global functions return a 64-bit SCALAR_VALUE */
6007 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6008 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6009 
6010 			/* continue with next insn after call */
6011 			return 0;
6012 		}
6013 	}
6014 
6015 	/* set_callee_state is used for direct subprog calls, but we are
6016 	 * interested in validating only BPF helpers that can call subprogs as
6017 	 * callbacks
6018 	 */
6019 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6020 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6021 			func_id_name(insn->imm), insn->imm);
6022 		return -EFAULT;
6023 	}
6024 
6025 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6026 	    insn->src_reg == 0 &&
6027 	    insn->imm == BPF_FUNC_timer_set_callback) {
6028 		struct bpf_verifier_state *async_cb;
6029 
6030 		/* there is no real recursion here. timer callbacks are async */
6031 		env->subprog_info[subprog].is_async_cb = true;
6032 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6033 					 *insn_idx, subprog);
6034 		if (!async_cb)
6035 			return -EFAULT;
6036 		callee = async_cb->frame[0];
6037 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6038 
6039 		/* Convert bpf_timer_set_callback() args into timer callback args */
6040 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6041 		if (err)
6042 			return err;
6043 
6044 		clear_caller_saved_regs(env, caller->regs);
6045 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6046 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6047 		/* continue with next insn after call */
6048 		return 0;
6049 	}
6050 
6051 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6052 	if (!callee)
6053 		return -ENOMEM;
6054 	state->frame[state->curframe + 1] = callee;
6055 
6056 	/* callee cannot access r0, r6 - r9 for reading and has to write
6057 	 * into its own stack before reading from it.
6058 	 * callee can read/write into caller's stack
6059 	 */
6060 	init_func_state(env, callee,
6061 			/* remember the callsite, it will be used by bpf_exit */
6062 			*insn_idx /* callsite */,
6063 			state->curframe + 1 /* frameno within this callchain */,
6064 			subprog /* subprog number within this prog */);
6065 
6066 	/* Transfer references to the callee */
6067 	err = copy_reference_state(callee, caller);
6068 	if (err)
6069 		goto err_out;
6070 
6071 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6072 	if (err)
6073 		goto err_out;
6074 
6075 	clear_caller_saved_regs(env, caller->regs);
6076 
6077 	/* only increment it after check_reg_arg() finished */
6078 	state->curframe++;
6079 
6080 	/* and go analyze first insn of the callee */
6081 	*insn_idx = env->subprog_info[subprog].start - 1;
6082 
6083 	if (env->log.level & BPF_LOG_LEVEL) {
6084 		verbose(env, "caller:\n");
6085 		print_verifier_state(env, caller);
6086 		verbose(env, "callee:\n");
6087 		print_verifier_state(env, callee);
6088 	}
6089 	return 0;
6090 
6091 err_out:
6092 	free_func_state(callee);
6093 	state->frame[state->curframe + 1] = NULL;
6094 	return err;
6095 }
6096 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)6097 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6098 				   struct bpf_func_state *caller,
6099 				   struct bpf_func_state *callee)
6100 {
6101 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6102 	 *      void *callback_ctx, u64 flags);
6103 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6104 	 *      void *callback_ctx);
6105 	 */
6106 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6107 
6108 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6109 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6110 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6111 
6112 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6113 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6114 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6115 
6116 	/* pointer to stack or null */
6117 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6118 
6119 	/* unused */
6120 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6121 	return 0;
6122 }
6123 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6124 static int set_callee_state(struct bpf_verifier_env *env,
6125 			    struct bpf_func_state *caller,
6126 			    struct bpf_func_state *callee, int insn_idx)
6127 {
6128 	int i;
6129 
6130 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6131 	 * pointers, which connects us up to the liveness chain
6132 	 */
6133 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6134 		callee->regs[i] = caller->regs[i];
6135 	return 0;
6136 }
6137 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)6138 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6139 			   int *insn_idx)
6140 {
6141 	int subprog, target_insn;
6142 
6143 	target_insn = *insn_idx + insn->imm + 1;
6144 	subprog = find_subprog(env, target_insn);
6145 	if (subprog < 0) {
6146 		verbose(env, "verifier bug. No program starts at insn %d\n",
6147 			target_insn);
6148 		return -EFAULT;
6149 	}
6150 
6151 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6152 }
6153 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6154 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6155 				       struct bpf_func_state *caller,
6156 				       struct bpf_func_state *callee,
6157 				       int insn_idx)
6158 {
6159 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6160 	struct bpf_map *map;
6161 	int err;
6162 
6163 	if (bpf_map_ptr_poisoned(insn_aux)) {
6164 		verbose(env, "tail_call abusing map_ptr\n");
6165 		return -EINVAL;
6166 	}
6167 
6168 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6169 	if (!map->ops->map_set_for_each_callback_args ||
6170 	    !map->ops->map_for_each_callback) {
6171 		verbose(env, "callback function not allowed for map\n");
6172 		return -ENOTSUPP;
6173 	}
6174 
6175 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6176 	if (err)
6177 		return err;
6178 
6179 	callee->in_callback_fn = true;
6180 	return 0;
6181 }
6182 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6183 static int set_timer_callback_state(struct bpf_verifier_env *env,
6184 				    struct bpf_func_state *caller,
6185 				    struct bpf_func_state *callee,
6186 				    int insn_idx)
6187 {
6188 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6189 
6190 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6191 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6192 	 */
6193 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6194 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6195 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6196 
6197 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6198 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6199 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6200 
6201 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6202 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6203 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6204 
6205 	/* unused */
6206 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6207 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6208 	callee->in_async_callback_fn = true;
6209 	return 0;
6210 }
6211 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)6212 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6213 {
6214 	struct bpf_verifier_state *state = env->cur_state;
6215 	struct bpf_func_state *caller, *callee;
6216 	struct bpf_reg_state *r0;
6217 	int err;
6218 
6219 	callee = state->frame[state->curframe];
6220 	r0 = &callee->regs[BPF_REG_0];
6221 	if (r0->type == PTR_TO_STACK) {
6222 		/* technically it's ok to return caller's stack pointer
6223 		 * (or caller's caller's pointer) back to the caller,
6224 		 * since these pointers are valid. Only current stack
6225 		 * pointer will be invalid as soon as function exits,
6226 		 * but let's be conservative
6227 		 */
6228 		verbose(env, "cannot return stack pointer to the caller\n");
6229 		return -EINVAL;
6230 	}
6231 
6232 	caller = state->frame[state->curframe - 1];
6233 	if (callee->in_callback_fn) {
6234 		/* enforce R0 return value range [0, 1]. */
6235 		struct tnum range = tnum_range(0, 1);
6236 
6237 		if (r0->type != SCALAR_VALUE) {
6238 			verbose(env, "R0 not a scalar value\n");
6239 			return -EACCES;
6240 		}
6241 
6242 		/* we are going to rely on register's precise value */
6243 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
6244 		err = err ?: mark_chain_precision(env, BPF_REG_0);
6245 		if (err)
6246 			return err;
6247 
6248 		if (!tnum_in(range, r0->var_off)) {
6249 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6250 			return -EINVAL;
6251 		}
6252 	} else {
6253 		/* return to the caller whatever r0 had in the callee */
6254 		caller->regs[BPF_REG_0] = *r0;
6255 	}
6256 
6257 	/* callback_fn frame should have released its own additions to parent's
6258 	 * reference state at this point, or check_reference_leak would
6259 	 * complain, hence it must be the same as the caller. There is no need
6260 	 * to copy it back.
6261 	 */
6262 	if (!callee->in_callback_fn) {
6263 		/* Transfer references to the caller */
6264 		err = copy_reference_state(caller, callee);
6265 		if (err)
6266 			return err;
6267 	}
6268 
6269 	*insn_idx = callee->callsite + 1;
6270 	if (env->log.level & BPF_LOG_LEVEL) {
6271 		verbose(env, "returning from callee:\n");
6272 		print_verifier_state(env, callee);
6273 		verbose(env, "to caller at %d:\n", *insn_idx);
6274 		print_verifier_state(env, caller);
6275 	}
6276 	/* clear everything in the callee */
6277 	free_func_state(callee);
6278 	state->frame[state->curframe--] = NULL;
6279 	return 0;
6280 }
6281 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)6282 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6283 				   int func_id,
6284 				   struct bpf_call_arg_meta *meta)
6285 {
6286 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6287 
6288 	if (ret_type != RET_INTEGER ||
6289 	    (func_id != BPF_FUNC_get_stack &&
6290 	     func_id != BPF_FUNC_get_task_stack &&
6291 	     func_id != BPF_FUNC_probe_read_str &&
6292 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6293 	     func_id != BPF_FUNC_probe_read_user_str))
6294 		return;
6295 
6296 	ret_reg->smax_value = meta->msize_max_value;
6297 	ret_reg->s32_max_value = meta->msize_max_value;
6298 	ret_reg->smin_value = -MAX_ERRNO;
6299 	ret_reg->s32_min_value = -MAX_ERRNO;
6300 	reg_bounds_sync(ret_reg);
6301 }
6302 
6303 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)6304 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6305 		int func_id, int insn_idx)
6306 {
6307 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6308 	struct bpf_map *map = meta->map_ptr;
6309 
6310 	if (func_id != BPF_FUNC_tail_call &&
6311 	    func_id != BPF_FUNC_map_lookup_elem &&
6312 	    func_id != BPF_FUNC_map_update_elem &&
6313 	    func_id != BPF_FUNC_map_delete_elem &&
6314 	    func_id != BPF_FUNC_map_push_elem &&
6315 	    func_id != BPF_FUNC_map_pop_elem &&
6316 	    func_id != BPF_FUNC_map_peek_elem &&
6317 	    func_id != BPF_FUNC_for_each_map_elem &&
6318 	    func_id != BPF_FUNC_redirect_map)
6319 		return 0;
6320 
6321 	if (map == NULL) {
6322 		verbose(env, "kernel subsystem misconfigured verifier\n");
6323 		return -EINVAL;
6324 	}
6325 
6326 	/* In case of read-only, some additional restrictions
6327 	 * need to be applied in order to prevent altering the
6328 	 * state of the map from program side.
6329 	 */
6330 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6331 	    (func_id == BPF_FUNC_map_delete_elem ||
6332 	     func_id == BPF_FUNC_map_update_elem ||
6333 	     func_id == BPF_FUNC_map_push_elem ||
6334 	     func_id == BPF_FUNC_map_pop_elem)) {
6335 		verbose(env, "write into map forbidden\n");
6336 		return -EACCES;
6337 	}
6338 
6339 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6340 		bpf_map_ptr_store(aux, meta->map_ptr,
6341 				  !meta->map_ptr->bypass_spec_v1);
6342 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6343 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6344 				  !meta->map_ptr->bypass_spec_v1);
6345 	return 0;
6346 }
6347 
6348 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)6349 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6350 		int func_id, int insn_idx)
6351 {
6352 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6353 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6354 	struct bpf_map *map = meta->map_ptr;
6355 	u64 val, max;
6356 	int err;
6357 
6358 	if (func_id != BPF_FUNC_tail_call)
6359 		return 0;
6360 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6361 		verbose(env, "kernel subsystem misconfigured verifier\n");
6362 		return -EINVAL;
6363 	}
6364 
6365 	reg = &regs[BPF_REG_3];
6366 	val = reg->var_off.value;
6367 	max = map->max_entries;
6368 
6369 	if (!(register_is_const(reg) && val < max)) {
6370 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6371 		return 0;
6372 	}
6373 
6374 	err = mark_chain_precision(env, BPF_REG_3);
6375 	if (err)
6376 		return err;
6377 	if (bpf_map_key_unseen(aux))
6378 		bpf_map_key_store(aux, val);
6379 	else if (!bpf_map_key_poisoned(aux) &&
6380 		  bpf_map_key_immediate(aux) != val)
6381 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6382 	return 0;
6383 }
6384 
check_reference_leak(struct bpf_verifier_env * env)6385 static int check_reference_leak(struct bpf_verifier_env *env)
6386 {
6387 	struct bpf_func_state *state = cur_func(env);
6388 	bool refs_lingering = false;
6389 	int i;
6390 
6391 	if (state->frameno && !state->in_callback_fn)
6392 		return 0;
6393 
6394 	for (i = 0; i < state->acquired_refs; i++) {
6395 		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
6396 			continue;
6397 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6398 			state->refs[i].id, state->refs[i].insn_idx);
6399 		refs_lingering = true;
6400 	}
6401 	return refs_lingering ? -EINVAL : 0;
6402 }
6403 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)6404 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6405 				   struct bpf_reg_state *regs)
6406 {
6407 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6408 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6409 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6410 	struct bpf_bprintf_data data = {};
6411 	int err, fmt_map_off, num_args;
6412 	u64 fmt_addr;
6413 	char *fmt;
6414 
6415 	/* data must be an array of u64 */
6416 	if (data_len_reg->var_off.value % 8)
6417 		return -EINVAL;
6418 	num_args = data_len_reg->var_off.value / 8;
6419 
6420 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6421 	 * and map_direct_value_addr is set.
6422 	 */
6423 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6424 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6425 						  fmt_map_off);
6426 	if (err) {
6427 		verbose(env, "verifier bug\n");
6428 		return -EFAULT;
6429 	}
6430 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6431 
6432 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6433 	 * can focus on validating the format specifiers.
6434 	 */
6435 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
6436 	if (err < 0)
6437 		verbose(env, "Invalid format string\n");
6438 
6439 	return err;
6440 }
6441 
check_get_func_ip(struct bpf_verifier_env * env)6442 static int check_get_func_ip(struct bpf_verifier_env *env)
6443 {
6444 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6445 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6446 	int func_id = BPF_FUNC_get_func_ip;
6447 
6448 	if (type == BPF_PROG_TYPE_TRACING) {
6449 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6450 		    eatype != BPF_MODIFY_RETURN) {
6451 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6452 				func_id_name(func_id), func_id);
6453 			return -ENOTSUPP;
6454 		}
6455 		return 0;
6456 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6457 		return 0;
6458 	}
6459 
6460 	verbose(env, "func %s#%d not supported for program type %d\n",
6461 		func_id_name(func_id), func_id, type);
6462 	return -ENOTSUPP;
6463 }
6464 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)6465 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6466 			     int *insn_idx_p)
6467 {
6468 	const struct bpf_func_proto *fn = NULL;
6469 	enum bpf_return_type ret_type;
6470 	enum bpf_type_flag ret_flag;
6471 	struct bpf_reg_state *regs;
6472 	struct bpf_call_arg_meta meta;
6473 	int insn_idx = *insn_idx_p;
6474 	bool changes_data;
6475 	int i, err, func_id;
6476 
6477 	/* find function prototype */
6478 	func_id = insn->imm;
6479 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6480 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6481 			func_id);
6482 		return -EINVAL;
6483 	}
6484 
6485 	if (env->ops->get_func_proto)
6486 		fn = env->ops->get_func_proto(func_id, env->prog);
6487 	if (!fn) {
6488 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6489 			func_id);
6490 		return -EINVAL;
6491 	}
6492 
6493 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6494 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6495 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6496 		return -EINVAL;
6497 	}
6498 
6499 	if (fn->allowed && !fn->allowed(env->prog)) {
6500 		verbose(env, "helper call is not allowed in probe\n");
6501 		return -EINVAL;
6502 	}
6503 
6504 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6505 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6506 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6507 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6508 			func_id_name(func_id), func_id);
6509 		return -EINVAL;
6510 	}
6511 
6512 	memset(&meta, 0, sizeof(meta));
6513 	meta.pkt_access = fn->pkt_access;
6514 
6515 	err = check_func_proto(fn, func_id);
6516 	if (err) {
6517 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6518 			func_id_name(func_id), func_id);
6519 		return err;
6520 	}
6521 
6522 	meta.func_id = func_id;
6523 	/* check args */
6524 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6525 		err = check_func_arg(env, i, &meta, fn);
6526 		if (err)
6527 			return err;
6528 	}
6529 
6530 	err = record_func_map(env, &meta, func_id, insn_idx);
6531 	if (err)
6532 		return err;
6533 
6534 	err = record_func_key(env, &meta, func_id, insn_idx);
6535 	if (err)
6536 		return err;
6537 
6538 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6539 	 * is inferred from register state.
6540 	 */
6541 	for (i = 0; i < meta.access_size; i++) {
6542 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6543 				       BPF_WRITE, -1, false);
6544 		if (err)
6545 			return err;
6546 	}
6547 
6548 	if (func_id == BPF_FUNC_tail_call) {
6549 		err = check_reference_leak(env);
6550 		if (err) {
6551 			verbose(env, "tail_call would lead to reference leak\n");
6552 			return err;
6553 		}
6554 	} else if (is_release_function(func_id)) {
6555 		err = release_reference(env, meta.ref_obj_id);
6556 		if (err) {
6557 			verbose(env, "func %s#%d reference has not been acquired before\n",
6558 				func_id_name(func_id), func_id);
6559 			return err;
6560 		}
6561 	}
6562 
6563 	regs = cur_regs(env);
6564 
6565 	/* check that flags argument in get_local_storage(map, flags) is 0,
6566 	 * this is required because get_local_storage() can't return an error.
6567 	 */
6568 	if (func_id == BPF_FUNC_get_local_storage &&
6569 	    !register_is_null(&regs[BPF_REG_2])) {
6570 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6571 		return -EINVAL;
6572 	}
6573 
6574 	if (func_id == BPF_FUNC_for_each_map_elem) {
6575 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6576 					set_map_elem_callback_state);
6577 		if (err < 0)
6578 			return -EINVAL;
6579 	}
6580 
6581 	if (func_id == BPF_FUNC_timer_set_callback) {
6582 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6583 					set_timer_callback_state);
6584 		if (err < 0)
6585 			return -EINVAL;
6586 	}
6587 
6588 	if (func_id == BPF_FUNC_snprintf) {
6589 		err = check_bpf_snprintf_call(env, regs);
6590 		if (err < 0)
6591 			return err;
6592 	}
6593 
6594 	/* reset caller saved regs */
6595 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6596 		mark_reg_not_init(env, regs, caller_saved[i]);
6597 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6598 	}
6599 
6600 	/* helper call returns 64-bit value. */
6601 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6602 
6603 	/* update return register (already marked as written above) */
6604 	ret_type = fn->ret_type;
6605 	ret_flag = type_flag(fn->ret_type);
6606 	if (ret_type == RET_INTEGER) {
6607 		/* sets type to SCALAR_VALUE */
6608 		mark_reg_unknown(env, regs, BPF_REG_0);
6609 	} else if (ret_type == RET_VOID) {
6610 		regs[BPF_REG_0].type = NOT_INIT;
6611 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
6612 		/* There is no offset yet applied, variable or fixed */
6613 		mark_reg_known_zero(env, regs, BPF_REG_0);
6614 		/* remember map_ptr, so that check_map_access()
6615 		 * can check 'value_size' boundary of memory access
6616 		 * to map element returned from bpf_map_lookup_elem()
6617 		 */
6618 		if (meta.map_ptr == NULL) {
6619 			verbose(env,
6620 				"kernel subsystem misconfigured verifier\n");
6621 			return -EINVAL;
6622 		}
6623 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6624 		regs[BPF_REG_0].map_uid = meta.map_uid;
6625 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6626 		if (!type_may_be_null(ret_type) &&
6627 		    map_value_has_spin_lock(meta.map_ptr)) {
6628 			regs[BPF_REG_0].id = ++env->id_gen;
6629 		}
6630 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
6631 		mark_reg_known_zero(env, regs, BPF_REG_0);
6632 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
6633 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
6634 		mark_reg_known_zero(env, regs, BPF_REG_0);
6635 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
6636 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
6637 		mark_reg_known_zero(env, regs, BPF_REG_0);
6638 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
6639 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
6640 		mark_reg_known_zero(env, regs, BPF_REG_0);
6641 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6642 		regs[BPF_REG_0].mem_size = meta.mem_size;
6643 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
6644 		const struct btf_type *t;
6645 
6646 		mark_reg_known_zero(env, regs, BPF_REG_0);
6647 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6648 		if (!btf_type_is_struct(t)) {
6649 			u32 tsize;
6650 			const struct btf_type *ret;
6651 			const char *tname;
6652 
6653 			/* resolve the type size of ksym. */
6654 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6655 			if (IS_ERR(ret)) {
6656 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6657 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6658 					tname, PTR_ERR(ret));
6659 				return -EINVAL;
6660 			}
6661 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6662 			regs[BPF_REG_0].mem_size = tsize;
6663 		} else {
6664 			/* MEM_RDONLY may be carried from ret_flag, but it
6665 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6666 			 * it will confuse the check of PTR_TO_BTF_ID in
6667 			 * check_mem_access().
6668 			 */
6669 			ret_flag &= ~MEM_RDONLY;
6670 
6671 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6672 			regs[BPF_REG_0].btf = meta.ret_btf;
6673 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6674 		}
6675 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
6676 		int ret_btf_id;
6677 
6678 		mark_reg_known_zero(env, regs, BPF_REG_0);
6679 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6680 		ret_btf_id = *fn->ret_btf_id;
6681 		if (ret_btf_id == 0) {
6682 			verbose(env, "invalid return type %u of func %s#%d\n",
6683 				base_type(ret_type), func_id_name(func_id),
6684 				func_id);
6685 			return -EINVAL;
6686 		}
6687 		/* current BPF helper definitions are only coming from
6688 		 * built-in code with type IDs from  vmlinux BTF
6689 		 */
6690 		regs[BPF_REG_0].btf = btf_vmlinux;
6691 		regs[BPF_REG_0].btf_id = ret_btf_id;
6692 	} else {
6693 		verbose(env, "unknown return type %u of func %s#%d\n",
6694 			base_type(ret_type), func_id_name(func_id), func_id);
6695 		return -EINVAL;
6696 	}
6697 
6698 	if (type_may_be_null(regs[BPF_REG_0].type))
6699 		regs[BPF_REG_0].id = ++env->id_gen;
6700 
6701 	if (is_ptr_cast_function(func_id)) {
6702 		/* For release_reference() */
6703 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6704 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6705 		int id = acquire_reference_state(env, insn_idx);
6706 
6707 		if (id < 0)
6708 			return id;
6709 		/* For mark_ptr_or_null_reg() */
6710 		regs[BPF_REG_0].id = id;
6711 		/* For release_reference() */
6712 		regs[BPF_REG_0].ref_obj_id = id;
6713 	}
6714 
6715 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6716 
6717 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6718 	if (err)
6719 		return err;
6720 
6721 	if ((func_id == BPF_FUNC_get_stack ||
6722 	     func_id == BPF_FUNC_get_task_stack) &&
6723 	    !env->prog->has_callchain_buf) {
6724 		const char *err_str;
6725 
6726 #ifdef CONFIG_PERF_EVENTS
6727 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6728 		err_str = "cannot get callchain buffer for func %s#%d\n";
6729 #else
6730 		err = -ENOTSUPP;
6731 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6732 #endif
6733 		if (err) {
6734 			verbose(env, err_str, func_id_name(func_id), func_id);
6735 			return err;
6736 		}
6737 
6738 		env->prog->has_callchain_buf = true;
6739 	}
6740 
6741 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6742 		env->prog->call_get_stack = true;
6743 
6744 	if (func_id == BPF_FUNC_get_func_ip) {
6745 		if (check_get_func_ip(env))
6746 			return -ENOTSUPP;
6747 		env->prog->call_get_func_ip = true;
6748 	}
6749 
6750 	if (changes_data)
6751 		clear_all_pkt_pointers(env);
6752 	return 0;
6753 }
6754 
6755 /* mark_btf_func_reg_size() is used when the reg size is determined by
6756  * the BTF func_proto's return value size and argument.
6757  */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)6758 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6759 				   size_t reg_size)
6760 {
6761 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6762 
6763 	if (regno == BPF_REG_0) {
6764 		/* Function return value */
6765 		reg->live |= REG_LIVE_WRITTEN;
6766 		reg->subreg_def = reg_size == sizeof(u64) ?
6767 			DEF_NOT_SUBREG : env->insn_idx + 1;
6768 	} else {
6769 		/* Function argument */
6770 		if (reg_size == sizeof(u64)) {
6771 			mark_insn_zext(env, reg);
6772 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6773 		} else {
6774 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6775 		}
6776 	}
6777 }
6778 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn)6779 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6780 {
6781 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6782 	struct bpf_reg_state *regs = cur_regs(env);
6783 	const char *func_name, *ptr_type_name;
6784 	u32 i, nargs, func_id, ptr_type_id;
6785 	const struct btf_param *args;
6786 	int err;
6787 
6788 	func_id = insn->imm;
6789 	func = btf_type_by_id(btf_vmlinux, func_id);
6790 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6791 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
6792 
6793 	if (!env->ops->check_kfunc_call ||
6794 	    !env->ops->check_kfunc_call(func_id)) {
6795 		verbose(env, "calling kernel function %s is not allowed\n",
6796 			func_name);
6797 		return -EACCES;
6798 	}
6799 
6800 	/* Check the arguments */
6801 	err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6802 	if (err)
6803 		return err;
6804 
6805 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6806 		mark_reg_not_init(env, regs, caller_saved[i]);
6807 
6808 	/* Check return type */
6809 	t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6810 	if (btf_type_is_scalar(t)) {
6811 		mark_reg_unknown(env, regs, BPF_REG_0);
6812 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6813 	} else if (btf_type_is_ptr(t)) {
6814 		ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6815 						   &ptr_type_id);
6816 		if (!btf_type_is_struct(ptr_type)) {
6817 			ptr_type_name = btf_name_by_offset(btf_vmlinux,
6818 							   ptr_type->name_off);
6819 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6820 				func_name, btf_type_str(ptr_type),
6821 				ptr_type_name);
6822 			return -EINVAL;
6823 		}
6824 		mark_reg_known_zero(env, regs, BPF_REG_0);
6825 		regs[BPF_REG_0].btf = btf_vmlinux;
6826 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6827 		regs[BPF_REG_0].btf_id = ptr_type_id;
6828 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6829 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6830 
6831 	nargs = btf_type_vlen(func_proto);
6832 	args = (const struct btf_param *)(func_proto + 1);
6833 	for (i = 0; i < nargs; i++) {
6834 		u32 regno = i + 1;
6835 
6836 		t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6837 		if (btf_type_is_ptr(t))
6838 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6839 		else
6840 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6841 			mark_btf_func_reg_size(env, regno, t->size);
6842 	}
6843 
6844 	return 0;
6845 }
6846 
signed_add_overflows(s64 a,s64 b)6847 static bool signed_add_overflows(s64 a, s64 b)
6848 {
6849 	/* Do the add in u64, where overflow is well-defined */
6850 	s64 res = (s64)((u64)a + (u64)b);
6851 
6852 	if (b < 0)
6853 		return res > a;
6854 	return res < a;
6855 }
6856 
signed_add32_overflows(s32 a,s32 b)6857 static bool signed_add32_overflows(s32 a, s32 b)
6858 {
6859 	/* Do the add in u32, where overflow is well-defined */
6860 	s32 res = (s32)((u32)a + (u32)b);
6861 
6862 	if (b < 0)
6863 		return res > a;
6864 	return res < a;
6865 }
6866 
signed_sub_overflows(s64 a,s64 b)6867 static bool signed_sub_overflows(s64 a, s64 b)
6868 {
6869 	/* Do the sub in u64, where overflow is well-defined */
6870 	s64 res = (s64)((u64)a - (u64)b);
6871 
6872 	if (b < 0)
6873 		return res < a;
6874 	return res > a;
6875 }
6876 
signed_sub32_overflows(s32 a,s32 b)6877 static bool signed_sub32_overflows(s32 a, s32 b)
6878 {
6879 	/* Do the sub in u32, where overflow is well-defined */
6880 	s32 res = (s32)((u32)a - (u32)b);
6881 
6882 	if (b < 0)
6883 		return res < a;
6884 	return res > a;
6885 }
6886 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)6887 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6888 				  const struct bpf_reg_state *reg,
6889 				  enum bpf_reg_type type)
6890 {
6891 	bool known = tnum_is_const(reg->var_off);
6892 	s64 val = reg->var_off.value;
6893 	s64 smin = reg->smin_value;
6894 
6895 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6896 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6897 			reg_type_str(env, type), val);
6898 		return false;
6899 	}
6900 
6901 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6902 		verbose(env, "%s pointer offset %d is not allowed\n",
6903 			reg_type_str(env, type), reg->off);
6904 		return false;
6905 	}
6906 
6907 	if (smin == S64_MIN) {
6908 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6909 			reg_type_str(env, type));
6910 		return false;
6911 	}
6912 
6913 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6914 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6915 			smin, reg_type_str(env, type));
6916 		return false;
6917 	}
6918 
6919 	return true;
6920 }
6921 
cur_aux(struct bpf_verifier_env * env)6922 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6923 {
6924 	return &env->insn_aux_data[env->insn_idx];
6925 }
6926 
6927 enum {
6928 	REASON_BOUNDS	= -1,
6929 	REASON_TYPE	= -2,
6930 	REASON_PATHS	= -3,
6931 	REASON_LIMIT	= -4,
6932 	REASON_STACK	= -5,
6933 };
6934 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)6935 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6936 			      u32 *alu_limit, bool mask_to_left)
6937 {
6938 	u32 max = 0, ptr_limit = 0;
6939 
6940 	switch (ptr_reg->type) {
6941 	case PTR_TO_STACK:
6942 		/* Offset 0 is out-of-bounds, but acceptable start for the
6943 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6944 		 * offset where we would need to deal with min/max bounds is
6945 		 * currently prohibited for unprivileged.
6946 		 */
6947 		max = MAX_BPF_STACK + mask_to_left;
6948 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6949 		break;
6950 	case PTR_TO_MAP_VALUE:
6951 		max = ptr_reg->map_ptr->value_size;
6952 		ptr_limit = (mask_to_left ?
6953 			     ptr_reg->smin_value :
6954 			     ptr_reg->umax_value) + ptr_reg->off;
6955 		break;
6956 	default:
6957 		return REASON_TYPE;
6958 	}
6959 
6960 	if (ptr_limit >= max)
6961 		return REASON_LIMIT;
6962 	*alu_limit = ptr_limit;
6963 	return 0;
6964 }
6965 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)6966 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6967 				    const struct bpf_insn *insn)
6968 {
6969 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6970 }
6971 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)6972 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6973 				       u32 alu_state, u32 alu_limit)
6974 {
6975 	/* If we arrived here from different branches with different
6976 	 * state or limits to sanitize, then this won't work.
6977 	 */
6978 	if (aux->alu_state &&
6979 	    (aux->alu_state != alu_state ||
6980 	     aux->alu_limit != alu_limit))
6981 		return REASON_PATHS;
6982 
6983 	/* Corresponding fixup done in do_misc_fixups(). */
6984 	aux->alu_state = alu_state;
6985 	aux->alu_limit = alu_limit;
6986 	return 0;
6987 }
6988 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)6989 static int sanitize_val_alu(struct bpf_verifier_env *env,
6990 			    struct bpf_insn *insn)
6991 {
6992 	struct bpf_insn_aux_data *aux = cur_aux(env);
6993 
6994 	if (can_skip_alu_sanitation(env, insn))
6995 		return 0;
6996 
6997 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6998 }
6999 
sanitize_needed(u8 opcode)7000 static bool sanitize_needed(u8 opcode)
7001 {
7002 	return opcode == BPF_ADD || opcode == BPF_SUB;
7003 }
7004 
7005 struct bpf_sanitize_info {
7006 	struct bpf_insn_aux_data aux;
7007 	bool mask_to_left;
7008 };
7009 
7010 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)7011 sanitize_speculative_path(struct bpf_verifier_env *env,
7012 			  const struct bpf_insn *insn,
7013 			  u32 next_idx, u32 curr_idx)
7014 {
7015 	struct bpf_verifier_state *branch;
7016 	struct bpf_reg_state *regs;
7017 
7018 	branch = push_stack(env, next_idx, curr_idx, true);
7019 	if (branch && insn) {
7020 		regs = branch->frame[branch->curframe]->regs;
7021 		if (BPF_SRC(insn->code) == BPF_K) {
7022 			mark_reg_unknown(env, regs, insn->dst_reg);
7023 		} else if (BPF_SRC(insn->code) == BPF_X) {
7024 			mark_reg_unknown(env, regs, insn->dst_reg);
7025 			mark_reg_unknown(env, regs, insn->src_reg);
7026 		}
7027 	}
7028 	return branch;
7029 }
7030 
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)7031 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7032 			    struct bpf_insn *insn,
7033 			    const struct bpf_reg_state *ptr_reg,
7034 			    const struct bpf_reg_state *off_reg,
7035 			    struct bpf_reg_state *dst_reg,
7036 			    struct bpf_sanitize_info *info,
7037 			    const bool commit_window)
7038 {
7039 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7040 	struct bpf_verifier_state *vstate = env->cur_state;
7041 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7042 	bool off_is_neg = off_reg->smin_value < 0;
7043 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7044 	u8 opcode = BPF_OP(insn->code);
7045 	u32 alu_state, alu_limit;
7046 	struct bpf_reg_state tmp;
7047 	bool ret;
7048 	int err;
7049 
7050 	if (can_skip_alu_sanitation(env, insn))
7051 		return 0;
7052 
7053 	/* We already marked aux for masking from non-speculative
7054 	 * paths, thus we got here in the first place. We only care
7055 	 * to explore bad access from here.
7056 	 */
7057 	if (vstate->speculative)
7058 		goto do_sim;
7059 
7060 	if (!commit_window) {
7061 		if (!tnum_is_const(off_reg->var_off) &&
7062 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7063 			return REASON_BOUNDS;
7064 
7065 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7066 				     (opcode == BPF_SUB && !off_is_neg);
7067 	}
7068 
7069 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7070 	if (err < 0)
7071 		return err;
7072 
7073 	if (commit_window) {
7074 		/* In commit phase we narrow the masking window based on
7075 		 * the observed pointer move after the simulated operation.
7076 		 */
7077 		alu_state = info->aux.alu_state;
7078 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7079 	} else {
7080 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7081 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7082 		alu_state |= ptr_is_dst_reg ?
7083 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7084 
7085 		/* Limit pruning on unknown scalars to enable deep search for
7086 		 * potential masking differences from other program paths.
7087 		 */
7088 		if (!off_is_imm)
7089 			env->explore_alu_limits = true;
7090 	}
7091 
7092 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7093 	if (err < 0)
7094 		return err;
7095 do_sim:
7096 	/* If we're in commit phase, we're done here given we already
7097 	 * pushed the truncated dst_reg into the speculative verification
7098 	 * stack.
7099 	 *
7100 	 * Also, when register is a known constant, we rewrite register-based
7101 	 * operation to immediate-based, and thus do not need masking (and as
7102 	 * a consequence, do not need to simulate the zero-truncation either).
7103 	 */
7104 	if (commit_window || off_is_imm)
7105 		return 0;
7106 
7107 	/* Simulate and find potential out-of-bounds access under
7108 	 * speculative execution from truncation as a result of
7109 	 * masking when off was not within expected range. If off
7110 	 * sits in dst, then we temporarily need to move ptr there
7111 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7112 	 * for cases where we use K-based arithmetic in one direction
7113 	 * and truncated reg-based in the other in order to explore
7114 	 * bad access.
7115 	 */
7116 	if (!ptr_is_dst_reg) {
7117 		tmp = *dst_reg;
7118 		copy_register_state(dst_reg, ptr_reg);
7119 	}
7120 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7121 					env->insn_idx);
7122 	if (!ptr_is_dst_reg && ret)
7123 		*dst_reg = tmp;
7124 	return !ret ? REASON_STACK : 0;
7125 }
7126 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)7127 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7128 {
7129 	struct bpf_verifier_state *vstate = env->cur_state;
7130 
7131 	/* If we simulate paths under speculation, we don't update the
7132 	 * insn as 'seen' such that when we verify unreachable paths in
7133 	 * the non-speculative domain, sanitize_dead_code() can still
7134 	 * rewrite/sanitize them.
7135 	 */
7136 	if (!vstate->speculative)
7137 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7138 }
7139 
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)7140 static int sanitize_err(struct bpf_verifier_env *env,
7141 			const struct bpf_insn *insn, int reason,
7142 			const struct bpf_reg_state *off_reg,
7143 			const struct bpf_reg_state *dst_reg)
7144 {
7145 	static const char *err = "pointer arithmetic with it prohibited for !root";
7146 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7147 	u32 dst = insn->dst_reg, src = insn->src_reg;
7148 
7149 	switch (reason) {
7150 	case REASON_BOUNDS:
7151 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7152 			off_reg == dst_reg ? dst : src, err);
7153 		break;
7154 	case REASON_TYPE:
7155 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7156 			off_reg == dst_reg ? src : dst, err);
7157 		break;
7158 	case REASON_PATHS:
7159 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7160 			dst, op, err);
7161 		break;
7162 	case REASON_LIMIT:
7163 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7164 			dst, op, err);
7165 		break;
7166 	case REASON_STACK:
7167 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7168 			dst, err);
7169 		break;
7170 	default:
7171 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7172 			reason);
7173 		break;
7174 	}
7175 
7176 	return -EACCES;
7177 }
7178 
7179 /* check that stack access falls within stack limits and that 'reg' doesn't
7180  * have a variable offset.
7181  *
7182  * Variable offset is prohibited for unprivileged mode for simplicity since it
7183  * requires corresponding support in Spectre masking for stack ALU.  See also
7184  * retrieve_ptr_limit().
7185  *
7186  *
7187  * 'off' includes 'reg->off'.
7188  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)7189 static int check_stack_access_for_ptr_arithmetic(
7190 				struct bpf_verifier_env *env,
7191 				int regno,
7192 				const struct bpf_reg_state *reg,
7193 				int off)
7194 {
7195 	if (!tnum_is_const(reg->var_off)) {
7196 		char tn_buf[48];
7197 
7198 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7199 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7200 			regno, tn_buf, off);
7201 		return -EACCES;
7202 	}
7203 
7204 	if (off >= 0 || off < -MAX_BPF_STACK) {
7205 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7206 			"prohibited for !root; off=%d\n", regno, off);
7207 		return -EACCES;
7208 	}
7209 
7210 	return 0;
7211 }
7212 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)7213 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7214 				 const struct bpf_insn *insn,
7215 				 const struct bpf_reg_state *dst_reg)
7216 {
7217 	u32 dst = insn->dst_reg;
7218 
7219 	/* For unprivileged we require that resulting offset must be in bounds
7220 	 * in order to be able to sanitize access later on.
7221 	 */
7222 	if (env->bypass_spec_v1)
7223 		return 0;
7224 
7225 	switch (dst_reg->type) {
7226 	case PTR_TO_STACK:
7227 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7228 					dst_reg->off + dst_reg->var_off.value))
7229 			return -EACCES;
7230 		break;
7231 	case PTR_TO_MAP_VALUE:
7232 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7233 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7234 				"prohibited for !root\n", dst);
7235 			return -EACCES;
7236 		}
7237 		break;
7238 	default:
7239 		break;
7240 	}
7241 
7242 	return 0;
7243 }
7244 
7245 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7246  * Caller should also handle BPF_MOV case separately.
7247  * If we return -EACCES, caller may want to try again treating pointer as a
7248  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7249  */
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)7250 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7251 				   struct bpf_insn *insn,
7252 				   const struct bpf_reg_state *ptr_reg,
7253 				   const struct bpf_reg_state *off_reg)
7254 {
7255 	struct bpf_verifier_state *vstate = env->cur_state;
7256 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7257 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7258 	bool known = tnum_is_const(off_reg->var_off);
7259 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7260 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7261 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7262 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7263 	struct bpf_sanitize_info info = {};
7264 	u8 opcode = BPF_OP(insn->code);
7265 	u32 dst = insn->dst_reg;
7266 	int ret;
7267 
7268 	dst_reg = &regs[dst];
7269 
7270 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7271 	    smin_val > smax_val || umin_val > umax_val) {
7272 		/* Taint dst register if offset had invalid bounds derived from
7273 		 * e.g. dead branches.
7274 		 */
7275 		__mark_reg_unknown(env, dst_reg);
7276 		return 0;
7277 	}
7278 
7279 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7280 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7281 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7282 			__mark_reg_unknown(env, dst_reg);
7283 			return 0;
7284 		}
7285 
7286 		verbose(env,
7287 			"R%d 32-bit pointer arithmetic prohibited\n",
7288 			dst);
7289 		return -EACCES;
7290 	}
7291 
7292 	if (ptr_reg->type & PTR_MAYBE_NULL) {
7293 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7294 			dst, reg_type_str(env, ptr_reg->type));
7295 		return -EACCES;
7296 	}
7297 
7298 	switch (base_type(ptr_reg->type)) {
7299 	case PTR_TO_FLOW_KEYS:
7300 		if (known)
7301 			break;
7302 		fallthrough;
7303 	case CONST_PTR_TO_MAP:
7304 		/* smin_val represents the known value */
7305 		if (known && smin_val == 0 && opcode == BPF_ADD)
7306 			break;
7307 		fallthrough;
7308 	case PTR_TO_PACKET_END:
7309 	case PTR_TO_SOCKET:
7310 	case PTR_TO_SOCK_COMMON:
7311 	case PTR_TO_TCP_SOCK:
7312 	case PTR_TO_XDP_SOCK:
7313 reject:
7314 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7315 			dst, reg_type_str(env, ptr_reg->type));
7316 		return -EACCES;
7317 	default:
7318 		if (type_may_be_null(ptr_reg->type))
7319 			goto reject;
7320 		break;
7321 	}
7322 
7323 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7324 	 * The id may be overwritten later if we create a new variable offset.
7325 	 */
7326 	dst_reg->type = ptr_reg->type;
7327 	dst_reg->id = ptr_reg->id;
7328 
7329 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7330 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7331 		return -EINVAL;
7332 
7333 	/* pointer types do not carry 32-bit bounds at the moment. */
7334 	__mark_reg32_unbounded(dst_reg);
7335 
7336 	if (sanitize_needed(opcode)) {
7337 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7338 				       &info, false);
7339 		if (ret < 0)
7340 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7341 	}
7342 
7343 	switch (opcode) {
7344 	case BPF_ADD:
7345 		/* We can take a fixed offset as long as it doesn't overflow
7346 		 * the s32 'off' field
7347 		 */
7348 		if (known && (ptr_reg->off + smin_val ==
7349 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7350 			/* pointer += K.  Accumulate it into fixed offset */
7351 			dst_reg->smin_value = smin_ptr;
7352 			dst_reg->smax_value = smax_ptr;
7353 			dst_reg->umin_value = umin_ptr;
7354 			dst_reg->umax_value = umax_ptr;
7355 			dst_reg->var_off = ptr_reg->var_off;
7356 			dst_reg->off = ptr_reg->off + smin_val;
7357 			dst_reg->raw = ptr_reg->raw;
7358 			break;
7359 		}
7360 		/* A new variable offset is created.  Note that off_reg->off
7361 		 * == 0, since it's a scalar.
7362 		 * dst_reg gets the pointer type and since some positive
7363 		 * integer value was added to the pointer, give it a new 'id'
7364 		 * if it's a PTR_TO_PACKET.
7365 		 * this creates a new 'base' pointer, off_reg (variable) gets
7366 		 * added into the variable offset, and we copy the fixed offset
7367 		 * from ptr_reg.
7368 		 */
7369 		if (signed_add_overflows(smin_ptr, smin_val) ||
7370 		    signed_add_overflows(smax_ptr, smax_val)) {
7371 			dst_reg->smin_value = S64_MIN;
7372 			dst_reg->smax_value = S64_MAX;
7373 		} else {
7374 			dst_reg->smin_value = smin_ptr + smin_val;
7375 			dst_reg->smax_value = smax_ptr + smax_val;
7376 		}
7377 		if (umin_ptr + umin_val < umin_ptr ||
7378 		    umax_ptr + umax_val < umax_ptr) {
7379 			dst_reg->umin_value = 0;
7380 			dst_reg->umax_value = U64_MAX;
7381 		} else {
7382 			dst_reg->umin_value = umin_ptr + umin_val;
7383 			dst_reg->umax_value = umax_ptr + umax_val;
7384 		}
7385 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7386 		dst_reg->off = ptr_reg->off;
7387 		dst_reg->raw = ptr_reg->raw;
7388 		if (reg_is_pkt_pointer(ptr_reg)) {
7389 			dst_reg->id = ++env->id_gen;
7390 			/* something was added to pkt_ptr, set range to zero */
7391 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7392 		}
7393 		break;
7394 	case BPF_SUB:
7395 		if (dst_reg == off_reg) {
7396 			/* scalar -= pointer.  Creates an unknown scalar */
7397 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7398 				dst);
7399 			return -EACCES;
7400 		}
7401 		/* We don't allow subtraction from FP, because (according to
7402 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7403 		 * be able to deal with it.
7404 		 */
7405 		if (ptr_reg->type == PTR_TO_STACK) {
7406 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7407 				dst);
7408 			return -EACCES;
7409 		}
7410 		if (known && (ptr_reg->off - smin_val ==
7411 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7412 			/* pointer -= K.  Subtract it from fixed offset */
7413 			dst_reg->smin_value = smin_ptr;
7414 			dst_reg->smax_value = smax_ptr;
7415 			dst_reg->umin_value = umin_ptr;
7416 			dst_reg->umax_value = umax_ptr;
7417 			dst_reg->var_off = ptr_reg->var_off;
7418 			dst_reg->id = ptr_reg->id;
7419 			dst_reg->off = ptr_reg->off - smin_val;
7420 			dst_reg->raw = ptr_reg->raw;
7421 			break;
7422 		}
7423 		/* A new variable offset is created.  If the subtrahend is known
7424 		 * nonnegative, then any reg->range we had before is still good.
7425 		 */
7426 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7427 		    signed_sub_overflows(smax_ptr, smin_val)) {
7428 			/* Overflow possible, we know nothing */
7429 			dst_reg->smin_value = S64_MIN;
7430 			dst_reg->smax_value = S64_MAX;
7431 		} else {
7432 			dst_reg->smin_value = smin_ptr - smax_val;
7433 			dst_reg->smax_value = smax_ptr - smin_val;
7434 		}
7435 		if (umin_ptr < umax_val) {
7436 			/* Overflow possible, we know nothing */
7437 			dst_reg->umin_value = 0;
7438 			dst_reg->umax_value = U64_MAX;
7439 		} else {
7440 			/* Cannot overflow (as long as bounds are consistent) */
7441 			dst_reg->umin_value = umin_ptr - umax_val;
7442 			dst_reg->umax_value = umax_ptr - umin_val;
7443 		}
7444 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7445 		dst_reg->off = ptr_reg->off;
7446 		dst_reg->raw = ptr_reg->raw;
7447 		if (reg_is_pkt_pointer(ptr_reg)) {
7448 			dst_reg->id = ++env->id_gen;
7449 			/* something was added to pkt_ptr, set range to zero */
7450 			if (smin_val < 0)
7451 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7452 		}
7453 		break;
7454 	case BPF_AND:
7455 	case BPF_OR:
7456 	case BPF_XOR:
7457 		/* bitwise ops on pointers are troublesome, prohibit. */
7458 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7459 			dst, bpf_alu_string[opcode >> 4]);
7460 		return -EACCES;
7461 	default:
7462 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7463 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7464 			dst, bpf_alu_string[opcode >> 4]);
7465 		return -EACCES;
7466 	}
7467 
7468 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7469 		return -EINVAL;
7470 	reg_bounds_sync(dst_reg);
7471 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7472 		return -EACCES;
7473 	if (sanitize_needed(opcode)) {
7474 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7475 				       &info, true);
7476 		if (ret < 0)
7477 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7478 	}
7479 
7480 	return 0;
7481 }
7482 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7483 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7484 				 struct bpf_reg_state *src_reg)
7485 {
7486 	s32 smin_val = src_reg->s32_min_value;
7487 	s32 smax_val = src_reg->s32_max_value;
7488 	u32 umin_val = src_reg->u32_min_value;
7489 	u32 umax_val = src_reg->u32_max_value;
7490 
7491 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7492 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7493 		dst_reg->s32_min_value = S32_MIN;
7494 		dst_reg->s32_max_value = S32_MAX;
7495 	} else {
7496 		dst_reg->s32_min_value += smin_val;
7497 		dst_reg->s32_max_value += smax_val;
7498 	}
7499 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7500 	    dst_reg->u32_max_value + umax_val < umax_val) {
7501 		dst_reg->u32_min_value = 0;
7502 		dst_reg->u32_max_value = U32_MAX;
7503 	} else {
7504 		dst_reg->u32_min_value += umin_val;
7505 		dst_reg->u32_max_value += umax_val;
7506 	}
7507 }
7508 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7509 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7510 			       struct bpf_reg_state *src_reg)
7511 {
7512 	s64 smin_val = src_reg->smin_value;
7513 	s64 smax_val = src_reg->smax_value;
7514 	u64 umin_val = src_reg->umin_value;
7515 	u64 umax_val = src_reg->umax_value;
7516 
7517 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7518 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7519 		dst_reg->smin_value = S64_MIN;
7520 		dst_reg->smax_value = S64_MAX;
7521 	} else {
7522 		dst_reg->smin_value += smin_val;
7523 		dst_reg->smax_value += smax_val;
7524 	}
7525 	if (dst_reg->umin_value + umin_val < umin_val ||
7526 	    dst_reg->umax_value + umax_val < umax_val) {
7527 		dst_reg->umin_value = 0;
7528 		dst_reg->umax_value = U64_MAX;
7529 	} else {
7530 		dst_reg->umin_value += umin_val;
7531 		dst_reg->umax_value += umax_val;
7532 	}
7533 }
7534 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7535 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7536 				 struct bpf_reg_state *src_reg)
7537 {
7538 	s32 smin_val = src_reg->s32_min_value;
7539 	s32 smax_val = src_reg->s32_max_value;
7540 	u32 umin_val = src_reg->u32_min_value;
7541 	u32 umax_val = src_reg->u32_max_value;
7542 
7543 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7544 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7545 		/* Overflow possible, we know nothing */
7546 		dst_reg->s32_min_value = S32_MIN;
7547 		dst_reg->s32_max_value = S32_MAX;
7548 	} else {
7549 		dst_reg->s32_min_value -= smax_val;
7550 		dst_reg->s32_max_value -= smin_val;
7551 	}
7552 	if (dst_reg->u32_min_value < umax_val) {
7553 		/* Overflow possible, we know nothing */
7554 		dst_reg->u32_min_value = 0;
7555 		dst_reg->u32_max_value = U32_MAX;
7556 	} else {
7557 		/* Cannot overflow (as long as bounds are consistent) */
7558 		dst_reg->u32_min_value -= umax_val;
7559 		dst_reg->u32_max_value -= umin_val;
7560 	}
7561 }
7562 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7563 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7564 			       struct bpf_reg_state *src_reg)
7565 {
7566 	s64 smin_val = src_reg->smin_value;
7567 	s64 smax_val = src_reg->smax_value;
7568 	u64 umin_val = src_reg->umin_value;
7569 	u64 umax_val = src_reg->umax_value;
7570 
7571 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7572 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7573 		/* Overflow possible, we know nothing */
7574 		dst_reg->smin_value = S64_MIN;
7575 		dst_reg->smax_value = S64_MAX;
7576 	} else {
7577 		dst_reg->smin_value -= smax_val;
7578 		dst_reg->smax_value -= smin_val;
7579 	}
7580 	if (dst_reg->umin_value < umax_val) {
7581 		/* Overflow possible, we know nothing */
7582 		dst_reg->umin_value = 0;
7583 		dst_reg->umax_value = U64_MAX;
7584 	} else {
7585 		/* Cannot overflow (as long as bounds are consistent) */
7586 		dst_reg->umin_value -= umax_val;
7587 		dst_reg->umax_value -= umin_val;
7588 	}
7589 }
7590 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7591 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7592 				 struct bpf_reg_state *src_reg)
7593 {
7594 	s32 smin_val = src_reg->s32_min_value;
7595 	u32 umin_val = src_reg->u32_min_value;
7596 	u32 umax_val = src_reg->u32_max_value;
7597 
7598 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7599 		/* Ain't nobody got time to multiply that sign */
7600 		__mark_reg32_unbounded(dst_reg);
7601 		return;
7602 	}
7603 	/* Both values are positive, so we can work with unsigned and
7604 	 * copy the result to signed (unless it exceeds S32_MAX).
7605 	 */
7606 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7607 		/* Potential overflow, we know nothing */
7608 		__mark_reg32_unbounded(dst_reg);
7609 		return;
7610 	}
7611 	dst_reg->u32_min_value *= umin_val;
7612 	dst_reg->u32_max_value *= umax_val;
7613 	if (dst_reg->u32_max_value > S32_MAX) {
7614 		/* Overflow possible, we know nothing */
7615 		dst_reg->s32_min_value = S32_MIN;
7616 		dst_reg->s32_max_value = S32_MAX;
7617 	} else {
7618 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7619 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7620 	}
7621 }
7622 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7623 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7624 			       struct bpf_reg_state *src_reg)
7625 {
7626 	s64 smin_val = src_reg->smin_value;
7627 	u64 umin_val = src_reg->umin_value;
7628 	u64 umax_val = src_reg->umax_value;
7629 
7630 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7631 		/* Ain't nobody got time to multiply that sign */
7632 		__mark_reg64_unbounded(dst_reg);
7633 		return;
7634 	}
7635 	/* Both values are positive, so we can work with unsigned and
7636 	 * copy the result to signed (unless it exceeds S64_MAX).
7637 	 */
7638 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7639 		/* Potential overflow, we know nothing */
7640 		__mark_reg64_unbounded(dst_reg);
7641 		return;
7642 	}
7643 	dst_reg->umin_value *= umin_val;
7644 	dst_reg->umax_value *= umax_val;
7645 	if (dst_reg->umax_value > S64_MAX) {
7646 		/* Overflow possible, we know nothing */
7647 		dst_reg->smin_value = S64_MIN;
7648 		dst_reg->smax_value = S64_MAX;
7649 	} else {
7650 		dst_reg->smin_value = dst_reg->umin_value;
7651 		dst_reg->smax_value = dst_reg->umax_value;
7652 	}
7653 }
7654 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7655 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7656 				 struct bpf_reg_state *src_reg)
7657 {
7658 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7659 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7660 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7661 	s32 smin_val = src_reg->s32_min_value;
7662 	u32 umax_val = src_reg->u32_max_value;
7663 
7664 	if (src_known && dst_known) {
7665 		__mark_reg32_known(dst_reg, var32_off.value);
7666 		return;
7667 	}
7668 
7669 	/* We get our minimum from the var_off, since that's inherently
7670 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7671 	 */
7672 	dst_reg->u32_min_value = var32_off.value;
7673 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7674 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7675 		/* Lose signed bounds when ANDing negative numbers,
7676 		 * ain't nobody got time for that.
7677 		 */
7678 		dst_reg->s32_min_value = S32_MIN;
7679 		dst_reg->s32_max_value = S32_MAX;
7680 	} else {
7681 		/* ANDing two positives gives a positive, so safe to
7682 		 * cast result into s64.
7683 		 */
7684 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7685 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7686 	}
7687 }
7688 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7689 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7690 			       struct bpf_reg_state *src_reg)
7691 {
7692 	bool src_known = tnum_is_const(src_reg->var_off);
7693 	bool dst_known = tnum_is_const(dst_reg->var_off);
7694 	s64 smin_val = src_reg->smin_value;
7695 	u64 umax_val = src_reg->umax_value;
7696 
7697 	if (src_known && dst_known) {
7698 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7699 		return;
7700 	}
7701 
7702 	/* We get our minimum from the var_off, since that's inherently
7703 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7704 	 */
7705 	dst_reg->umin_value = dst_reg->var_off.value;
7706 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7707 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7708 		/* Lose signed bounds when ANDing negative numbers,
7709 		 * ain't nobody got time for that.
7710 		 */
7711 		dst_reg->smin_value = S64_MIN;
7712 		dst_reg->smax_value = S64_MAX;
7713 	} else {
7714 		/* ANDing two positives gives a positive, so safe to
7715 		 * cast result into s64.
7716 		 */
7717 		dst_reg->smin_value = dst_reg->umin_value;
7718 		dst_reg->smax_value = dst_reg->umax_value;
7719 	}
7720 	/* We may learn something more from the var_off */
7721 	__update_reg_bounds(dst_reg);
7722 }
7723 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7724 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7725 				struct bpf_reg_state *src_reg)
7726 {
7727 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7728 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7729 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7730 	s32 smin_val = src_reg->s32_min_value;
7731 	u32 umin_val = src_reg->u32_min_value;
7732 
7733 	if (src_known && dst_known) {
7734 		__mark_reg32_known(dst_reg, var32_off.value);
7735 		return;
7736 	}
7737 
7738 	/* We get our maximum from the var_off, and our minimum is the
7739 	 * maximum of the operands' minima
7740 	 */
7741 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7742 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7743 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7744 		/* Lose signed bounds when ORing negative numbers,
7745 		 * ain't nobody got time for that.
7746 		 */
7747 		dst_reg->s32_min_value = S32_MIN;
7748 		dst_reg->s32_max_value = S32_MAX;
7749 	} else {
7750 		/* ORing two positives gives a positive, so safe to
7751 		 * cast result into s64.
7752 		 */
7753 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7754 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7755 	}
7756 }
7757 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7758 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7759 			      struct bpf_reg_state *src_reg)
7760 {
7761 	bool src_known = tnum_is_const(src_reg->var_off);
7762 	bool dst_known = tnum_is_const(dst_reg->var_off);
7763 	s64 smin_val = src_reg->smin_value;
7764 	u64 umin_val = src_reg->umin_value;
7765 
7766 	if (src_known && dst_known) {
7767 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7768 		return;
7769 	}
7770 
7771 	/* We get our maximum from the var_off, and our minimum is the
7772 	 * maximum of the operands' minima
7773 	 */
7774 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7775 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7776 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7777 		/* Lose signed bounds when ORing negative numbers,
7778 		 * ain't nobody got time for that.
7779 		 */
7780 		dst_reg->smin_value = S64_MIN;
7781 		dst_reg->smax_value = S64_MAX;
7782 	} else {
7783 		/* ORing two positives gives a positive, so safe to
7784 		 * cast result into s64.
7785 		 */
7786 		dst_reg->smin_value = dst_reg->umin_value;
7787 		dst_reg->smax_value = dst_reg->umax_value;
7788 	}
7789 	/* We may learn something more from the var_off */
7790 	__update_reg_bounds(dst_reg);
7791 }
7792 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7793 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7794 				 struct bpf_reg_state *src_reg)
7795 {
7796 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7797 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7798 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7799 	s32 smin_val = src_reg->s32_min_value;
7800 
7801 	if (src_known && dst_known) {
7802 		__mark_reg32_known(dst_reg, var32_off.value);
7803 		return;
7804 	}
7805 
7806 	/* We get both minimum and maximum from the var32_off. */
7807 	dst_reg->u32_min_value = var32_off.value;
7808 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7809 
7810 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7811 		/* XORing two positive sign numbers gives a positive,
7812 		 * so safe to cast u32 result into s32.
7813 		 */
7814 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7815 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7816 	} else {
7817 		dst_reg->s32_min_value = S32_MIN;
7818 		dst_reg->s32_max_value = S32_MAX;
7819 	}
7820 }
7821 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7822 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7823 			       struct bpf_reg_state *src_reg)
7824 {
7825 	bool src_known = tnum_is_const(src_reg->var_off);
7826 	bool dst_known = tnum_is_const(dst_reg->var_off);
7827 	s64 smin_val = src_reg->smin_value;
7828 
7829 	if (src_known && dst_known) {
7830 		/* dst_reg->var_off.value has been updated earlier */
7831 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7832 		return;
7833 	}
7834 
7835 	/* We get both minimum and maximum from the var_off. */
7836 	dst_reg->umin_value = dst_reg->var_off.value;
7837 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7838 
7839 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7840 		/* XORing two positive sign numbers gives a positive,
7841 		 * so safe to cast u64 result into s64.
7842 		 */
7843 		dst_reg->smin_value = dst_reg->umin_value;
7844 		dst_reg->smax_value = dst_reg->umax_value;
7845 	} else {
7846 		dst_reg->smin_value = S64_MIN;
7847 		dst_reg->smax_value = S64_MAX;
7848 	}
7849 
7850 	__update_reg_bounds(dst_reg);
7851 }
7852 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)7853 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7854 				   u64 umin_val, u64 umax_val)
7855 {
7856 	/* We lose all sign bit information (except what we can pick
7857 	 * up from var_off)
7858 	 */
7859 	dst_reg->s32_min_value = S32_MIN;
7860 	dst_reg->s32_max_value = S32_MAX;
7861 	/* If we might shift our top bit out, then we know nothing */
7862 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7863 		dst_reg->u32_min_value = 0;
7864 		dst_reg->u32_max_value = U32_MAX;
7865 	} else {
7866 		dst_reg->u32_min_value <<= umin_val;
7867 		dst_reg->u32_max_value <<= umax_val;
7868 	}
7869 }
7870 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7871 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7872 				 struct bpf_reg_state *src_reg)
7873 {
7874 	u32 umax_val = src_reg->u32_max_value;
7875 	u32 umin_val = src_reg->u32_min_value;
7876 	/* u32 alu operation will zext upper bits */
7877 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7878 
7879 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7880 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7881 	/* Not required but being careful mark reg64 bounds as unknown so
7882 	 * that we are forced to pick them up from tnum and zext later and
7883 	 * if some path skips this step we are still safe.
7884 	 */
7885 	__mark_reg64_unbounded(dst_reg);
7886 	__update_reg32_bounds(dst_reg);
7887 }
7888 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)7889 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7890 				   u64 umin_val, u64 umax_val)
7891 {
7892 	/* Special case <<32 because it is a common compiler pattern to sign
7893 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7894 	 * positive we know this shift will also be positive so we can track
7895 	 * bounds correctly. Otherwise we lose all sign bit information except
7896 	 * what we can pick up from var_off. Perhaps we can generalize this
7897 	 * later to shifts of any length.
7898 	 */
7899 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7900 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7901 	else
7902 		dst_reg->smax_value = S64_MAX;
7903 
7904 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7905 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7906 	else
7907 		dst_reg->smin_value = S64_MIN;
7908 
7909 	/* If we might shift our top bit out, then we know nothing */
7910 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7911 		dst_reg->umin_value = 0;
7912 		dst_reg->umax_value = U64_MAX;
7913 	} else {
7914 		dst_reg->umin_value <<= umin_val;
7915 		dst_reg->umax_value <<= umax_val;
7916 	}
7917 }
7918 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7919 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7920 			       struct bpf_reg_state *src_reg)
7921 {
7922 	u64 umax_val = src_reg->umax_value;
7923 	u64 umin_val = src_reg->umin_value;
7924 
7925 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7926 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7927 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7928 
7929 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7930 	/* We may learn something more from the var_off */
7931 	__update_reg_bounds(dst_reg);
7932 }
7933 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7934 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7935 				 struct bpf_reg_state *src_reg)
7936 {
7937 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7938 	u32 umax_val = src_reg->u32_max_value;
7939 	u32 umin_val = src_reg->u32_min_value;
7940 
7941 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7942 	 * be negative, then either:
7943 	 * 1) src_reg might be zero, so the sign bit of the result is
7944 	 *    unknown, so we lose our signed bounds
7945 	 * 2) it's known negative, thus the unsigned bounds capture the
7946 	 *    signed bounds
7947 	 * 3) the signed bounds cross zero, so they tell us nothing
7948 	 *    about the result
7949 	 * If the value in dst_reg is known nonnegative, then again the
7950 	 * unsigned bounds capture the signed bounds.
7951 	 * Thus, in all cases it suffices to blow away our signed bounds
7952 	 * and rely on inferring new ones from the unsigned bounds and
7953 	 * var_off of the result.
7954 	 */
7955 	dst_reg->s32_min_value = S32_MIN;
7956 	dst_reg->s32_max_value = S32_MAX;
7957 
7958 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7959 	dst_reg->u32_min_value >>= umax_val;
7960 	dst_reg->u32_max_value >>= umin_val;
7961 
7962 	__mark_reg64_unbounded(dst_reg);
7963 	__update_reg32_bounds(dst_reg);
7964 }
7965 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7966 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7967 			       struct bpf_reg_state *src_reg)
7968 {
7969 	u64 umax_val = src_reg->umax_value;
7970 	u64 umin_val = src_reg->umin_value;
7971 
7972 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7973 	 * be negative, then either:
7974 	 * 1) src_reg might be zero, so the sign bit of the result is
7975 	 *    unknown, so we lose our signed bounds
7976 	 * 2) it's known negative, thus the unsigned bounds capture the
7977 	 *    signed bounds
7978 	 * 3) the signed bounds cross zero, so they tell us nothing
7979 	 *    about the result
7980 	 * If the value in dst_reg is known nonnegative, then again the
7981 	 * unsigned bounds capture the signed bounds.
7982 	 * Thus, in all cases it suffices to blow away our signed bounds
7983 	 * and rely on inferring new ones from the unsigned bounds and
7984 	 * var_off of the result.
7985 	 */
7986 	dst_reg->smin_value = S64_MIN;
7987 	dst_reg->smax_value = S64_MAX;
7988 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7989 	dst_reg->umin_value >>= umax_val;
7990 	dst_reg->umax_value >>= umin_val;
7991 
7992 	/* Its not easy to operate on alu32 bounds here because it depends
7993 	 * on bits being shifted in. Take easy way out and mark unbounded
7994 	 * so we can recalculate later from tnum.
7995 	 */
7996 	__mark_reg32_unbounded(dst_reg);
7997 	__update_reg_bounds(dst_reg);
7998 }
7999 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8000 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8001 				  struct bpf_reg_state *src_reg)
8002 {
8003 	u64 umin_val = src_reg->u32_min_value;
8004 
8005 	/* Upon reaching here, src_known is true and
8006 	 * umax_val is equal to umin_val.
8007 	 */
8008 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8009 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8010 
8011 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8012 
8013 	/* blow away the dst_reg umin_value/umax_value and rely on
8014 	 * dst_reg var_off to refine the result.
8015 	 */
8016 	dst_reg->u32_min_value = 0;
8017 	dst_reg->u32_max_value = U32_MAX;
8018 
8019 	__mark_reg64_unbounded(dst_reg);
8020 	__update_reg32_bounds(dst_reg);
8021 }
8022 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8023 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8024 				struct bpf_reg_state *src_reg)
8025 {
8026 	u64 umin_val = src_reg->umin_value;
8027 
8028 	/* Upon reaching here, src_known is true and umax_val is equal
8029 	 * to umin_val.
8030 	 */
8031 	dst_reg->smin_value >>= umin_val;
8032 	dst_reg->smax_value >>= umin_val;
8033 
8034 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8035 
8036 	/* blow away the dst_reg umin_value/umax_value and rely on
8037 	 * dst_reg var_off to refine the result.
8038 	 */
8039 	dst_reg->umin_value = 0;
8040 	dst_reg->umax_value = U64_MAX;
8041 
8042 	/* Its not easy to operate on alu32 bounds here because it depends
8043 	 * on bits being shifted in from upper 32-bits. Take easy way out
8044 	 * and mark unbounded so we can recalculate later from tnum.
8045 	 */
8046 	__mark_reg32_unbounded(dst_reg);
8047 	__update_reg_bounds(dst_reg);
8048 }
8049 
8050 /* WARNING: This function does calculations on 64-bit values, but the actual
8051  * execution may occur on 32-bit values. Therefore, things like bitshifts
8052  * need extra checks in the 32-bit case.
8053  */
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)8054 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8055 				      struct bpf_insn *insn,
8056 				      struct bpf_reg_state *dst_reg,
8057 				      struct bpf_reg_state src_reg)
8058 {
8059 	struct bpf_reg_state *regs = cur_regs(env);
8060 	u8 opcode = BPF_OP(insn->code);
8061 	bool src_known;
8062 	s64 smin_val, smax_val;
8063 	u64 umin_val, umax_val;
8064 	s32 s32_min_val, s32_max_val;
8065 	u32 u32_min_val, u32_max_val;
8066 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8067 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8068 	int ret;
8069 
8070 	smin_val = src_reg.smin_value;
8071 	smax_val = src_reg.smax_value;
8072 	umin_val = src_reg.umin_value;
8073 	umax_val = src_reg.umax_value;
8074 
8075 	s32_min_val = src_reg.s32_min_value;
8076 	s32_max_val = src_reg.s32_max_value;
8077 	u32_min_val = src_reg.u32_min_value;
8078 	u32_max_val = src_reg.u32_max_value;
8079 
8080 	if (alu32) {
8081 		src_known = tnum_subreg_is_const(src_reg.var_off);
8082 		if ((src_known &&
8083 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8084 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8085 			/* Taint dst register if offset had invalid bounds
8086 			 * derived from e.g. dead branches.
8087 			 */
8088 			__mark_reg_unknown(env, dst_reg);
8089 			return 0;
8090 		}
8091 	} else {
8092 		src_known = tnum_is_const(src_reg.var_off);
8093 		if ((src_known &&
8094 		     (smin_val != smax_val || umin_val != umax_val)) ||
8095 		    smin_val > smax_val || umin_val > umax_val) {
8096 			/* Taint dst register if offset had invalid bounds
8097 			 * derived from e.g. dead branches.
8098 			 */
8099 			__mark_reg_unknown(env, dst_reg);
8100 			return 0;
8101 		}
8102 	}
8103 
8104 	if (!src_known &&
8105 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8106 		__mark_reg_unknown(env, dst_reg);
8107 		return 0;
8108 	}
8109 
8110 	if (sanitize_needed(opcode)) {
8111 		ret = sanitize_val_alu(env, insn);
8112 		if (ret < 0)
8113 			return sanitize_err(env, insn, ret, NULL, NULL);
8114 	}
8115 
8116 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8117 	 * There are two classes of instructions: The first class we track both
8118 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8119 	 * greatest amount of precision when alu operations are mixed with jmp32
8120 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8121 	 * and BPF_OR. This is possible because these ops have fairly easy to
8122 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8123 	 * See alu32 verifier tests for examples. The second class of
8124 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8125 	 * with regards to tracking sign/unsigned bounds because the bits may
8126 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8127 	 * the reg unbounded in the subreg bound space and use the resulting
8128 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8129 	 */
8130 	switch (opcode) {
8131 	case BPF_ADD:
8132 		scalar32_min_max_add(dst_reg, &src_reg);
8133 		scalar_min_max_add(dst_reg, &src_reg);
8134 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8135 		break;
8136 	case BPF_SUB:
8137 		scalar32_min_max_sub(dst_reg, &src_reg);
8138 		scalar_min_max_sub(dst_reg, &src_reg);
8139 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8140 		break;
8141 	case BPF_MUL:
8142 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8143 		scalar32_min_max_mul(dst_reg, &src_reg);
8144 		scalar_min_max_mul(dst_reg, &src_reg);
8145 		break;
8146 	case BPF_AND:
8147 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8148 		scalar32_min_max_and(dst_reg, &src_reg);
8149 		scalar_min_max_and(dst_reg, &src_reg);
8150 		break;
8151 	case BPF_OR:
8152 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8153 		scalar32_min_max_or(dst_reg, &src_reg);
8154 		scalar_min_max_or(dst_reg, &src_reg);
8155 		break;
8156 	case BPF_XOR:
8157 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8158 		scalar32_min_max_xor(dst_reg, &src_reg);
8159 		scalar_min_max_xor(dst_reg, &src_reg);
8160 		break;
8161 	case BPF_LSH:
8162 		if (umax_val >= insn_bitness) {
8163 			/* Shifts greater than 31 or 63 are undefined.
8164 			 * This includes shifts by a negative number.
8165 			 */
8166 			mark_reg_unknown(env, regs, insn->dst_reg);
8167 			break;
8168 		}
8169 		if (alu32)
8170 			scalar32_min_max_lsh(dst_reg, &src_reg);
8171 		else
8172 			scalar_min_max_lsh(dst_reg, &src_reg);
8173 		break;
8174 	case BPF_RSH:
8175 		if (umax_val >= insn_bitness) {
8176 			/* Shifts greater than 31 or 63 are undefined.
8177 			 * This includes shifts by a negative number.
8178 			 */
8179 			mark_reg_unknown(env, regs, insn->dst_reg);
8180 			break;
8181 		}
8182 		if (alu32)
8183 			scalar32_min_max_rsh(dst_reg, &src_reg);
8184 		else
8185 			scalar_min_max_rsh(dst_reg, &src_reg);
8186 		break;
8187 	case BPF_ARSH:
8188 		if (umax_val >= insn_bitness) {
8189 			/* Shifts greater than 31 or 63 are undefined.
8190 			 * This includes shifts by a negative number.
8191 			 */
8192 			mark_reg_unknown(env, regs, insn->dst_reg);
8193 			break;
8194 		}
8195 		if (alu32)
8196 			scalar32_min_max_arsh(dst_reg, &src_reg);
8197 		else
8198 			scalar_min_max_arsh(dst_reg, &src_reg);
8199 		break;
8200 	default:
8201 		mark_reg_unknown(env, regs, insn->dst_reg);
8202 		break;
8203 	}
8204 
8205 	/* ALU32 ops are zero extended into 64bit register */
8206 	if (alu32)
8207 		zext_32_to_64(dst_reg);
8208 	reg_bounds_sync(dst_reg);
8209 	return 0;
8210 }
8211 
8212 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8213  * and var_off.
8214  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)8215 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8216 				   struct bpf_insn *insn)
8217 {
8218 	struct bpf_verifier_state *vstate = env->cur_state;
8219 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8220 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8221 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8222 	u8 opcode = BPF_OP(insn->code);
8223 	int err;
8224 
8225 	dst_reg = &regs[insn->dst_reg];
8226 	src_reg = NULL;
8227 	if (dst_reg->type != SCALAR_VALUE)
8228 		ptr_reg = dst_reg;
8229 	else
8230 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8231 		 * incorrectly propagated into other registers by find_equal_scalars()
8232 		 */
8233 		dst_reg->id = 0;
8234 	if (BPF_SRC(insn->code) == BPF_X) {
8235 		src_reg = &regs[insn->src_reg];
8236 		if (src_reg->type != SCALAR_VALUE) {
8237 			if (dst_reg->type != SCALAR_VALUE) {
8238 				/* Combining two pointers by any ALU op yields
8239 				 * an arbitrary scalar. Disallow all math except
8240 				 * pointer subtraction
8241 				 */
8242 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8243 					mark_reg_unknown(env, regs, insn->dst_reg);
8244 					return 0;
8245 				}
8246 				verbose(env, "R%d pointer %s pointer prohibited\n",
8247 					insn->dst_reg,
8248 					bpf_alu_string[opcode >> 4]);
8249 				return -EACCES;
8250 			} else {
8251 				/* scalar += pointer
8252 				 * This is legal, but we have to reverse our
8253 				 * src/dest handling in computing the range
8254 				 */
8255 				err = mark_chain_precision(env, insn->dst_reg);
8256 				if (err)
8257 					return err;
8258 				return adjust_ptr_min_max_vals(env, insn,
8259 							       src_reg, dst_reg);
8260 			}
8261 		} else if (ptr_reg) {
8262 			/* pointer += scalar */
8263 			err = mark_chain_precision(env, insn->src_reg);
8264 			if (err)
8265 				return err;
8266 			return adjust_ptr_min_max_vals(env, insn,
8267 						       dst_reg, src_reg);
8268 		} else if (dst_reg->precise) {
8269 			/* if dst_reg is precise, src_reg should be precise as well */
8270 			err = mark_chain_precision(env, insn->src_reg);
8271 			if (err)
8272 				return err;
8273 		}
8274 	} else {
8275 		/* Pretend the src is a reg with a known value, since we only
8276 		 * need to be able to read from this state.
8277 		 */
8278 		off_reg.type = SCALAR_VALUE;
8279 		__mark_reg_known(&off_reg, insn->imm);
8280 		src_reg = &off_reg;
8281 		if (ptr_reg) /* pointer += K */
8282 			return adjust_ptr_min_max_vals(env, insn,
8283 						       ptr_reg, src_reg);
8284 	}
8285 
8286 	/* Got here implies adding two SCALAR_VALUEs */
8287 	if (WARN_ON_ONCE(ptr_reg)) {
8288 		print_verifier_state(env, state);
8289 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8290 		return -EINVAL;
8291 	}
8292 	if (WARN_ON(!src_reg)) {
8293 		print_verifier_state(env, state);
8294 		verbose(env, "verifier internal error: no src_reg\n");
8295 		return -EINVAL;
8296 	}
8297 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8298 }
8299 
8300 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)8301 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8302 {
8303 	struct bpf_reg_state *regs = cur_regs(env);
8304 	u8 opcode = BPF_OP(insn->code);
8305 	int err;
8306 
8307 	if (opcode == BPF_END || opcode == BPF_NEG) {
8308 		if (opcode == BPF_NEG) {
8309 			if (BPF_SRC(insn->code) != 0 ||
8310 			    insn->src_reg != BPF_REG_0 ||
8311 			    insn->off != 0 || insn->imm != 0) {
8312 				verbose(env, "BPF_NEG uses reserved fields\n");
8313 				return -EINVAL;
8314 			}
8315 		} else {
8316 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8317 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8318 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8319 				verbose(env, "BPF_END uses reserved fields\n");
8320 				return -EINVAL;
8321 			}
8322 		}
8323 
8324 		/* check src operand */
8325 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8326 		if (err)
8327 			return err;
8328 
8329 		if (is_pointer_value(env, insn->dst_reg)) {
8330 			verbose(env, "R%d pointer arithmetic prohibited\n",
8331 				insn->dst_reg);
8332 			return -EACCES;
8333 		}
8334 
8335 		/* check dest operand */
8336 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8337 		if (err)
8338 			return err;
8339 
8340 	} else if (opcode == BPF_MOV) {
8341 
8342 		if (BPF_SRC(insn->code) == BPF_X) {
8343 			if (insn->imm != 0 || insn->off != 0) {
8344 				verbose(env, "BPF_MOV uses reserved fields\n");
8345 				return -EINVAL;
8346 			}
8347 
8348 			/* check src operand */
8349 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8350 			if (err)
8351 				return err;
8352 		} else {
8353 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8354 				verbose(env, "BPF_MOV uses reserved fields\n");
8355 				return -EINVAL;
8356 			}
8357 		}
8358 
8359 		/* check dest operand, mark as required later */
8360 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8361 		if (err)
8362 			return err;
8363 
8364 		if (BPF_SRC(insn->code) == BPF_X) {
8365 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8366 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8367 
8368 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8369 				/* case: R1 = R2
8370 				 * copy register state to dest reg
8371 				 */
8372 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8373 					/* Assign src and dst registers the same ID
8374 					 * that will be used by find_equal_scalars()
8375 					 * to propagate min/max range.
8376 					 */
8377 					src_reg->id = ++env->id_gen;
8378 				copy_register_state(dst_reg, src_reg);
8379 				dst_reg->live |= REG_LIVE_WRITTEN;
8380 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8381 			} else {
8382 				/* R1 = (u32) R2 */
8383 				if (is_pointer_value(env, insn->src_reg)) {
8384 					verbose(env,
8385 						"R%d partial copy of pointer\n",
8386 						insn->src_reg);
8387 					return -EACCES;
8388 				} else if (src_reg->type == SCALAR_VALUE) {
8389 					copy_register_state(dst_reg, src_reg);
8390 					/* Make sure ID is cleared otherwise
8391 					 * dst_reg min/max could be incorrectly
8392 					 * propagated into src_reg by find_equal_scalars()
8393 					 */
8394 					dst_reg->id = 0;
8395 					dst_reg->live |= REG_LIVE_WRITTEN;
8396 					dst_reg->subreg_def = env->insn_idx + 1;
8397 				} else {
8398 					mark_reg_unknown(env, regs,
8399 							 insn->dst_reg);
8400 				}
8401 				zext_32_to_64(dst_reg);
8402 				reg_bounds_sync(dst_reg);
8403 			}
8404 		} else {
8405 			/* case: R = imm
8406 			 * remember the value we stored into this reg
8407 			 */
8408 			/* clear any state __mark_reg_known doesn't set */
8409 			mark_reg_unknown(env, regs, insn->dst_reg);
8410 			regs[insn->dst_reg].type = SCALAR_VALUE;
8411 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8412 				__mark_reg_known(regs + insn->dst_reg,
8413 						 insn->imm);
8414 			} else {
8415 				__mark_reg_known(regs + insn->dst_reg,
8416 						 (u32)insn->imm);
8417 			}
8418 		}
8419 
8420 	} else if (opcode > BPF_END) {
8421 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8422 		return -EINVAL;
8423 
8424 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8425 
8426 		if (BPF_SRC(insn->code) == BPF_X) {
8427 			if (insn->imm != 0 || insn->off != 0) {
8428 				verbose(env, "BPF_ALU uses reserved fields\n");
8429 				return -EINVAL;
8430 			}
8431 			/* check src1 operand */
8432 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8433 			if (err)
8434 				return err;
8435 		} else {
8436 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8437 				verbose(env, "BPF_ALU uses reserved fields\n");
8438 				return -EINVAL;
8439 			}
8440 		}
8441 
8442 		/* check src2 operand */
8443 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8444 		if (err)
8445 			return err;
8446 
8447 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8448 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8449 			verbose(env, "div by zero\n");
8450 			return -EINVAL;
8451 		}
8452 
8453 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8454 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8455 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8456 
8457 			if (insn->imm < 0 || insn->imm >= size) {
8458 				verbose(env, "invalid shift %d\n", insn->imm);
8459 				return -EINVAL;
8460 			}
8461 		}
8462 
8463 		/* check dest operand */
8464 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8465 		if (err)
8466 			return err;
8467 
8468 		return adjust_reg_min_max_vals(env, insn);
8469 	}
8470 
8471 	return 0;
8472 }
8473 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)8474 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8475 				   struct bpf_reg_state *dst_reg,
8476 				   enum bpf_reg_type type,
8477 				   bool range_right_open)
8478 {
8479 	struct bpf_func_state *state;
8480 	struct bpf_reg_state *reg;
8481 	int new_range;
8482 
8483 	if (dst_reg->off < 0 ||
8484 	    (dst_reg->off == 0 && range_right_open))
8485 		/* This doesn't give us any range */
8486 		return;
8487 
8488 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8489 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8490 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8491 		 * than pkt_end, but that's because it's also less than pkt.
8492 		 */
8493 		return;
8494 
8495 	new_range = dst_reg->off;
8496 	if (range_right_open)
8497 		new_range++;
8498 
8499 	/* Examples for register markings:
8500 	 *
8501 	 * pkt_data in dst register:
8502 	 *
8503 	 *   r2 = r3;
8504 	 *   r2 += 8;
8505 	 *   if (r2 > pkt_end) goto <handle exception>
8506 	 *   <access okay>
8507 	 *
8508 	 *   r2 = r3;
8509 	 *   r2 += 8;
8510 	 *   if (r2 < pkt_end) goto <access okay>
8511 	 *   <handle exception>
8512 	 *
8513 	 *   Where:
8514 	 *     r2 == dst_reg, pkt_end == src_reg
8515 	 *     r2=pkt(id=n,off=8,r=0)
8516 	 *     r3=pkt(id=n,off=0,r=0)
8517 	 *
8518 	 * pkt_data in src register:
8519 	 *
8520 	 *   r2 = r3;
8521 	 *   r2 += 8;
8522 	 *   if (pkt_end >= r2) goto <access okay>
8523 	 *   <handle exception>
8524 	 *
8525 	 *   r2 = r3;
8526 	 *   r2 += 8;
8527 	 *   if (pkt_end <= r2) goto <handle exception>
8528 	 *   <access okay>
8529 	 *
8530 	 *   Where:
8531 	 *     pkt_end == dst_reg, r2 == src_reg
8532 	 *     r2=pkt(id=n,off=8,r=0)
8533 	 *     r3=pkt(id=n,off=0,r=0)
8534 	 *
8535 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8536 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8537 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8538 	 * the check.
8539 	 */
8540 
8541 	/* If our ids match, then we must have the same max_value.  And we
8542 	 * don't care about the other reg's fixed offset, since if it's too big
8543 	 * the range won't allow anything.
8544 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8545 	 */
8546 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8547 		if (reg->type == type && reg->id == dst_reg->id)
8548 			/* keep the maximum range already checked */
8549 			reg->range = max(reg->range, new_range);
8550 	}));
8551 }
8552 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)8553 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8554 {
8555 	struct tnum subreg = tnum_subreg(reg->var_off);
8556 	s32 sval = (s32)val;
8557 
8558 	switch (opcode) {
8559 	case BPF_JEQ:
8560 		if (tnum_is_const(subreg))
8561 			return !!tnum_equals_const(subreg, val);
8562 		break;
8563 	case BPF_JNE:
8564 		if (tnum_is_const(subreg))
8565 			return !tnum_equals_const(subreg, val);
8566 		break;
8567 	case BPF_JSET:
8568 		if ((~subreg.mask & subreg.value) & val)
8569 			return 1;
8570 		if (!((subreg.mask | subreg.value) & val))
8571 			return 0;
8572 		break;
8573 	case BPF_JGT:
8574 		if (reg->u32_min_value > val)
8575 			return 1;
8576 		else if (reg->u32_max_value <= val)
8577 			return 0;
8578 		break;
8579 	case BPF_JSGT:
8580 		if (reg->s32_min_value > sval)
8581 			return 1;
8582 		else if (reg->s32_max_value <= sval)
8583 			return 0;
8584 		break;
8585 	case BPF_JLT:
8586 		if (reg->u32_max_value < val)
8587 			return 1;
8588 		else if (reg->u32_min_value >= val)
8589 			return 0;
8590 		break;
8591 	case BPF_JSLT:
8592 		if (reg->s32_max_value < sval)
8593 			return 1;
8594 		else if (reg->s32_min_value >= sval)
8595 			return 0;
8596 		break;
8597 	case BPF_JGE:
8598 		if (reg->u32_min_value >= val)
8599 			return 1;
8600 		else if (reg->u32_max_value < val)
8601 			return 0;
8602 		break;
8603 	case BPF_JSGE:
8604 		if (reg->s32_min_value >= sval)
8605 			return 1;
8606 		else if (reg->s32_max_value < sval)
8607 			return 0;
8608 		break;
8609 	case BPF_JLE:
8610 		if (reg->u32_max_value <= val)
8611 			return 1;
8612 		else if (reg->u32_min_value > val)
8613 			return 0;
8614 		break;
8615 	case BPF_JSLE:
8616 		if (reg->s32_max_value <= sval)
8617 			return 1;
8618 		else if (reg->s32_min_value > sval)
8619 			return 0;
8620 		break;
8621 	}
8622 
8623 	return -1;
8624 }
8625 
8626 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)8627 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8628 {
8629 	s64 sval = (s64)val;
8630 
8631 	switch (opcode) {
8632 	case BPF_JEQ:
8633 		if (tnum_is_const(reg->var_off))
8634 			return !!tnum_equals_const(reg->var_off, val);
8635 		break;
8636 	case BPF_JNE:
8637 		if (tnum_is_const(reg->var_off))
8638 			return !tnum_equals_const(reg->var_off, val);
8639 		break;
8640 	case BPF_JSET:
8641 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8642 			return 1;
8643 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8644 			return 0;
8645 		break;
8646 	case BPF_JGT:
8647 		if (reg->umin_value > val)
8648 			return 1;
8649 		else if (reg->umax_value <= val)
8650 			return 0;
8651 		break;
8652 	case BPF_JSGT:
8653 		if (reg->smin_value > sval)
8654 			return 1;
8655 		else if (reg->smax_value <= sval)
8656 			return 0;
8657 		break;
8658 	case BPF_JLT:
8659 		if (reg->umax_value < val)
8660 			return 1;
8661 		else if (reg->umin_value >= val)
8662 			return 0;
8663 		break;
8664 	case BPF_JSLT:
8665 		if (reg->smax_value < sval)
8666 			return 1;
8667 		else if (reg->smin_value >= sval)
8668 			return 0;
8669 		break;
8670 	case BPF_JGE:
8671 		if (reg->umin_value >= val)
8672 			return 1;
8673 		else if (reg->umax_value < val)
8674 			return 0;
8675 		break;
8676 	case BPF_JSGE:
8677 		if (reg->smin_value >= sval)
8678 			return 1;
8679 		else if (reg->smax_value < sval)
8680 			return 0;
8681 		break;
8682 	case BPF_JLE:
8683 		if (reg->umax_value <= val)
8684 			return 1;
8685 		else if (reg->umin_value > val)
8686 			return 0;
8687 		break;
8688 	case BPF_JSLE:
8689 		if (reg->smax_value <= sval)
8690 			return 1;
8691 		else if (reg->smin_value > sval)
8692 			return 0;
8693 		break;
8694 	}
8695 
8696 	return -1;
8697 }
8698 
8699 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8700  * and return:
8701  *  1 - branch will be taken and "goto target" will be executed
8702  *  0 - branch will not be taken and fall-through to next insn
8703  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8704  *      range [0,10]
8705  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)8706 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8707 			   bool is_jmp32)
8708 {
8709 	if (__is_pointer_value(false, reg)) {
8710 		if (!reg_type_not_null(reg->type))
8711 			return -1;
8712 
8713 		/* If pointer is valid tests against zero will fail so we can
8714 		 * use this to direct branch taken.
8715 		 */
8716 		if (val != 0)
8717 			return -1;
8718 
8719 		switch (opcode) {
8720 		case BPF_JEQ:
8721 			return 0;
8722 		case BPF_JNE:
8723 			return 1;
8724 		default:
8725 			return -1;
8726 		}
8727 	}
8728 
8729 	if (is_jmp32)
8730 		return is_branch32_taken(reg, val, opcode);
8731 	return is_branch64_taken(reg, val, opcode);
8732 }
8733 
flip_opcode(u32 opcode)8734 static int flip_opcode(u32 opcode)
8735 {
8736 	/* How can we transform "a <op> b" into "b <op> a"? */
8737 	static const u8 opcode_flip[16] = {
8738 		/* these stay the same */
8739 		[BPF_JEQ  >> 4] = BPF_JEQ,
8740 		[BPF_JNE  >> 4] = BPF_JNE,
8741 		[BPF_JSET >> 4] = BPF_JSET,
8742 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8743 		[BPF_JGE  >> 4] = BPF_JLE,
8744 		[BPF_JGT  >> 4] = BPF_JLT,
8745 		[BPF_JLE  >> 4] = BPF_JGE,
8746 		[BPF_JLT  >> 4] = BPF_JGT,
8747 		[BPF_JSGE >> 4] = BPF_JSLE,
8748 		[BPF_JSGT >> 4] = BPF_JSLT,
8749 		[BPF_JSLE >> 4] = BPF_JSGE,
8750 		[BPF_JSLT >> 4] = BPF_JSGT
8751 	};
8752 	return opcode_flip[opcode >> 4];
8753 }
8754 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)8755 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8756 				   struct bpf_reg_state *src_reg,
8757 				   u8 opcode)
8758 {
8759 	struct bpf_reg_state *pkt;
8760 
8761 	if (src_reg->type == PTR_TO_PACKET_END) {
8762 		pkt = dst_reg;
8763 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8764 		pkt = src_reg;
8765 		opcode = flip_opcode(opcode);
8766 	} else {
8767 		return -1;
8768 	}
8769 
8770 	if (pkt->range >= 0)
8771 		return -1;
8772 
8773 	switch (opcode) {
8774 	case BPF_JLE:
8775 		/* pkt <= pkt_end */
8776 		fallthrough;
8777 	case BPF_JGT:
8778 		/* pkt > pkt_end */
8779 		if (pkt->range == BEYOND_PKT_END)
8780 			/* pkt has at last one extra byte beyond pkt_end */
8781 			return opcode == BPF_JGT;
8782 		break;
8783 	case BPF_JLT:
8784 		/* pkt < pkt_end */
8785 		fallthrough;
8786 	case BPF_JGE:
8787 		/* pkt >= pkt_end */
8788 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8789 			return opcode == BPF_JGE;
8790 		break;
8791 	}
8792 	return -1;
8793 }
8794 
8795 /* Adjusts the register min/max values in the case that the dst_reg is the
8796  * variable register that we are working on, and src_reg is a constant or we're
8797  * simply doing a BPF_K check.
8798  * In JEQ/JNE cases we also adjust the var_off values.
8799  */
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)8800 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8801 			    struct bpf_reg_state *false_reg,
8802 			    u64 val, u32 val32,
8803 			    u8 opcode, bool is_jmp32)
8804 {
8805 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8806 	struct tnum false_64off = false_reg->var_off;
8807 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8808 	struct tnum true_64off = true_reg->var_off;
8809 	s64 sval = (s64)val;
8810 	s32 sval32 = (s32)val32;
8811 
8812 	/* If the dst_reg is a pointer, we can't learn anything about its
8813 	 * variable offset from the compare (unless src_reg were a pointer into
8814 	 * the same object, but we don't bother with that.
8815 	 * Since false_reg and true_reg have the same type by construction, we
8816 	 * only need to check one of them for pointerness.
8817 	 */
8818 	if (__is_pointer_value(false, false_reg))
8819 		return;
8820 
8821 	switch (opcode) {
8822 	/* JEQ/JNE comparison doesn't change the register equivalence.
8823 	 *
8824 	 * r1 = r2;
8825 	 * if (r1 == 42) goto label;
8826 	 * ...
8827 	 * label: // here both r1 and r2 are known to be 42.
8828 	 *
8829 	 * Hence when marking register as known preserve it's ID.
8830 	 */
8831 	case BPF_JEQ:
8832 		if (is_jmp32) {
8833 			__mark_reg32_known(true_reg, val32);
8834 			true_32off = tnum_subreg(true_reg->var_off);
8835 		} else {
8836 			___mark_reg_known(true_reg, val);
8837 			true_64off = true_reg->var_off;
8838 		}
8839 		break;
8840 	case BPF_JNE:
8841 		if (is_jmp32) {
8842 			__mark_reg32_known(false_reg, val32);
8843 			false_32off = tnum_subreg(false_reg->var_off);
8844 		} else {
8845 			___mark_reg_known(false_reg, val);
8846 			false_64off = false_reg->var_off;
8847 		}
8848 		break;
8849 	case BPF_JSET:
8850 		if (is_jmp32) {
8851 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8852 			if (is_power_of_2(val32))
8853 				true_32off = tnum_or(true_32off,
8854 						     tnum_const(val32));
8855 		} else {
8856 			false_64off = tnum_and(false_64off, tnum_const(~val));
8857 			if (is_power_of_2(val))
8858 				true_64off = tnum_or(true_64off,
8859 						     tnum_const(val));
8860 		}
8861 		break;
8862 	case BPF_JGE:
8863 	case BPF_JGT:
8864 	{
8865 		if (is_jmp32) {
8866 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8867 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8868 
8869 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8870 						       false_umax);
8871 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8872 						      true_umin);
8873 		} else {
8874 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8875 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8876 
8877 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8878 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8879 		}
8880 		break;
8881 	}
8882 	case BPF_JSGE:
8883 	case BPF_JSGT:
8884 	{
8885 		if (is_jmp32) {
8886 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8887 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8888 
8889 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8890 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8891 		} else {
8892 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8893 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8894 
8895 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8896 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8897 		}
8898 		break;
8899 	}
8900 	case BPF_JLE:
8901 	case BPF_JLT:
8902 	{
8903 		if (is_jmp32) {
8904 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8905 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8906 
8907 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8908 						       false_umin);
8909 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8910 						      true_umax);
8911 		} else {
8912 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8913 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8914 
8915 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8916 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8917 		}
8918 		break;
8919 	}
8920 	case BPF_JSLE:
8921 	case BPF_JSLT:
8922 	{
8923 		if (is_jmp32) {
8924 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8925 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8926 
8927 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8928 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8929 		} else {
8930 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8931 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8932 
8933 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8934 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8935 		}
8936 		break;
8937 	}
8938 	default:
8939 		return;
8940 	}
8941 
8942 	if (is_jmp32) {
8943 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8944 					     tnum_subreg(false_32off));
8945 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8946 					    tnum_subreg(true_32off));
8947 		__reg_combine_32_into_64(false_reg);
8948 		__reg_combine_32_into_64(true_reg);
8949 	} else {
8950 		false_reg->var_off = false_64off;
8951 		true_reg->var_off = true_64off;
8952 		__reg_combine_64_into_32(false_reg);
8953 		__reg_combine_64_into_32(true_reg);
8954 	}
8955 }
8956 
8957 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8958  * the variable reg.
8959  */
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)8960 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8961 				struct bpf_reg_state *false_reg,
8962 				u64 val, u32 val32,
8963 				u8 opcode, bool is_jmp32)
8964 {
8965 	opcode = flip_opcode(opcode);
8966 	/* This uses zero as "not present in table"; luckily the zero opcode,
8967 	 * BPF_JA, can't get here.
8968 	 */
8969 	if (opcode)
8970 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8971 }
8972 
8973 /* 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)8974 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8975 				  struct bpf_reg_state *dst_reg)
8976 {
8977 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8978 							dst_reg->umin_value);
8979 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8980 							dst_reg->umax_value);
8981 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8982 							dst_reg->smin_value);
8983 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8984 							dst_reg->smax_value);
8985 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8986 							     dst_reg->var_off);
8987 	reg_bounds_sync(src_reg);
8988 	reg_bounds_sync(dst_reg);
8989 }
8990 
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)8991 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8992 				struct bpf_reg_state *true_dst,
8993 				struct bpf_reg_state *false_src,
8994 				struct bpf_reg_state *false_dst,
8995 				u8 opcode)
8996 {
8997 	switch (opcode) {
8998 	case BPF_JEQ:
8999 		__reg_combine_min_max(true_src, true_dst);
9000 		break;
9001 	case BPF_JNE:
9002 		__reg_combine_min_max(false_src, false_dst);
9003 		break;
9004 	}
9005 }
9006 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)9007 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9008 				 struct bpf_reg_state *reg, u32 id,
9009 				 bool is_null)
9010 {
9011 	if (type_may_be_null(reg->type) && reg->id == id &&
9012 	    !WARN_ON_ONCE(!reg->id)) {
9013 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9014 				 !tnum_equals_const(reg->var_off, 0) ||
9015 				 reg->off)) {
9016 			/* Old offset (both fixed and variable parts) should
9017 			 * have been known-zero, because we don't allow pointer
9018 			 * arithmetic on pointers that might be NULL. If we
9019 			 * see this happening, don't convert the register.
9020 			 */
9021 			return;
9022 		}
9023 		if (is_null) {
9024 			reg->type = SCALAR_VALUE;
9025 			/* We don't need id and ref_obj_id from this point
9026 			 * onwards anymore, thus we should better reset it,
9027 			 * so that state pruning has chances to take effect.
9028 			 */
9029 			reg->id = 0;
9030 			reg->ref_obj_id = 0;
9031 
9032 			return;
9033 		}
9034 
9035 		mark_ptr_not_null_reg(reg);
9036 
9037 		if (!reg_may_point_to_spin_lock(reg)) {
9038 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9039 			 * in release_reference().
9040 			 *
9041 			 * reg->id is still used by spin_lock ptr. Other
9042 			 * than spin_lock ptr type, reg->id can be reset.
9043 			 */
9044 			reg->id = 0;
9045 		}
9046 	}
9047 }
9048 
9049 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9050  * be folded together at some point.
9051  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)9052 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9053 				  bool is_null)
9054 {
9055 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9056 	struct bpf_reg_state *regs = state->regs, *reg;
9057 	u32 ref_obj_id = regs[regno].ref_obj_id;
9058 	u32 id = regs[regno].id;
9059 
9060 	if (ref_obj_id && ref_obj_id == id && is_null)
9061 		/* regs[regno] is in the " == NULL" branch.
9062 		 * No one could have freed the reference state before
9063 		 * doing the NULL check.
9064 		 */
9065 		WARN_ON_ONCE(release_reference_state(state, id));
9066 
9067 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9068 		mark_ptr_or_null_reg(state, reg, id, is_null);
9069 	}));
9070 }
9071 
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)9072 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9073 				   struct bpf_reg_state *dst_reg,
9074 				   struct bpf_reg_state *src_reg,
9075 				   struct bpf_verifier_state *this_branch,
9076 				   struct bpf_verifier_state *other_branch)
9077 {
9078 	if (BPF_SRC(insn->code) != BPF_X)
9079 		return false;
9080 
9081 	/* Pointers are always 64-bit. */
9082 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9083 		return false;
9084 
9085 	switch (BPF_OP(insn->code)) {
9086 	case BPF_JGT:
9087 		if ((dst_reg->type == PTR_TO_PACKET &&
9088 		     src_reg->type == PTR_TO_PACKET_END) ||
9089 		    (dst_reg->type == PTR_TO_PACKET_META &&
9090 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9091 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9092 			find_good_pkt_pointers(this_branch, dst_reg,
9093 					       dst_reg->type, false);
9094 			mark_pkt_end(other_branch, insn->dst_reg, true);
9095 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9096 			    src_reg->type == PTR_TO_PACKET) ||
9097 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9098 			    src_reg->type == PTR_TO_PACKET_META)) {
9099 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9100 			find_good_pkt_pointers(other_branch, src_reg,
9101 					       src_reg->type, true);
9102 			mark_pkt_end(this_branch, insn->src_reg, false);
9103 		} else {
9104 			return false;
9105 		}
9106 		break;
9107 	case BPF_JLT:
9108 		if ((dst_reg->type == PTR_TO_PACKET &&
9109 		     src_reg->type == PTR_TO_PACKET_END) ||
9110 		    (dst_reg->type == PTR_TO_PACKET_META &&
9111 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9112 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9113 			find_good_pkt_pointers(other_branch, dst_reg,
9114 					       dst_reg->type, true);
9115 			mark_pkt_end(this_branch, insn->dst_reg, false);
9116 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9117 			    src_reg->type == PTR_TO_PACKET) ||
9118 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9119 			    src_reg->type == PTR_TO_PACKET_META)) {
9120 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9121 			find_good_pkt_pointers(this_branch, src_reg,
9122 					       src_reg->type, false);
9123 			mark_pkt_end(other_branch, insn->src_reg, true);
9124 		} else {
9125 			return false;
9126 		}
9127 		break;
9128 	case BPF_JGE:
9129 		if ((dst_reg->type == PTR_TO_PACKET &&
9130 		     src_reg->type == PTR_TO_PACKET_END) ||
9131 		    (dst_reg->type == PTR_TO_PACKET_META &&
9132 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9133 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9134 			find_good_pkt_pointers(this_branch, dst_reg,
9135 					       dst_reg->type, true);
9136 			mark_pkt_end(other_branch, insn->dst_reg, false);
9137 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9138 			    src_reg->type == PTR_TO_PACKET) ||
9139 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9140 			    src_reg->type == PTR_TO_PACKET_META)) {
9141 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9142 			find_good_pkt_pointers(other_branch, src_reg,
9143 					       src_reg->type, false);
9144 			mark_pkt_end(this_branch, insn->src_reg, true);
9145 		} else {
9146 			return false;
9147 		}
9148 		break;
9149 	case BPF_JLE:
9150 		if ((dst_reg->type == PTR_TO_PACKET &&
9151 		     src_reg->type == PTR_TO_PACKET_END) ||
9152 		    (dst_reg->type == PTR_TO_PACKET_META &&
9153 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9154 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9155 			find_good_pkt_pointers(other_branch, dst_reg,
9156 					       dst_reg->type, false);
9157 			mark_pkt_end(this_branch, insn->dst_reg, true);
9158 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9159 			    src_reg->type == PTR_TO_PACKET) ||
9160 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9161 			    src_reg->type == PTR_TO_PACKET_META)) {
9162 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9163 			find_good_pkt_pointers(this_branch, src_reg,
9164 					       src_reg->type, true);
9165 			mark_pkt_end(other_branch, insn->src_reg, false);
9166 		} else {
9167 			return false;
9168 		}
9169 		break;
9170 	default:
9171 		return false;
9172 	}
9173 
9174 	return true;
9175 }
9176 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)9177 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9178 			       struct bpf_reg_state *known_reg)
9179 {
9180 	struct bpf_func_state *state;
9181 	struct bpf_reg_state *reg;
9182 
9183 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9184 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9185 			copy_register_state(reg, known_reg);
9186 	}));
9187 }
9188 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)9189 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9190 			     struct bpf_insn *insn, int *insn_idx)
9191 {
9192 	struct bpf_verifier_state *this_branch = env->cur_state;
9193 	struct bpf_verifier_state *other_branch;
9194 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9195 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9196 	u8 opcode = BPF_OP(insn->code);
9197 	bool is_jmp32;
9198 	int pred = -1;
9199 	int err;
9200 
9201 	/* Only conditional jumps are expected to reach here. */
9202 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9203 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9204 		return -EINVAL;
9205 	}
9206 
9207 	if (BPF_SRC(insn->code) == BPF_X) {
9208 		if (insn->imm != 0) {
9209 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9210 			return -EINVAL;
9211 		}
9212 
9213 		/* check src1 operand */
9214 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9215 		if (err)
9216 			return err;
9217 
9218 		if (is_pointer_value(env, insn->src_reg)) {
9219 			verbose(env, "R%d pointer comparison prohibited\n",
9220 				insn->src_reg);
9221 			return -EACCES;
9222 		}
9223 		src_reg = &regs[insn->src_reg];
9224 	} else {
9225 		if (insn->src_reg != BPF_REG_0) {
9226 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9227 			return -EINVAL;
9228 		}
9229 	}
9230 
9231 	/* check src2 operand */
9232 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9233 	if (err)
9234 		return err;
9235 
9236 	dst_reg = &regs[insn->dst_reg];
9237 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9238 
9239 	if (BPF_SRC(insn->code) == BPF_K) {
9240 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9241 	} else if (src_reg->type == SCALAR_VALUE &&
9242 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9243 		pred = is_branch_taken(dst_reg,
9244 				       tnum_subreg(src_reg->var_off).value,
9245 				       opcode,
9246 				       is_jmp32);
9247 	} else if (src_reg->type == SCALAR_VALUE &&
9248 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9249 		pred = is_branch_taken(dst_reg,
9250 				       src_reg->var_off.value,
9251 				       opcode,
9252 				       is_jmp32);
9253 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9254 		   reg_is_pkt_pointer_any(src_reg) &&
9255 		   !is_jmp32) {
9256 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9257 	}
9258 
9259 	if (pred >= 0) {
9260 		/* If we get here with a dst_reg pointer type it is because
9261 		 * above is_branch_taken() special cased the 0 comparison.
9262 		 */
9263 		if (!__is_pointer_value(false, dst_reg))
9264 			err = mark_chain_precision(env, insn->dst_reg);
9265 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9266 		    !__is_pointer_value(false, src_reg))
9267 			err = mark_chain_precision(env, insn->src_reg);
9268 		if (err)
9269 			return err;
9270 	}
9271 
9272 	if (pred == 1) {
9273 		/* Only follow the goto, ignore fall-through. If needed, push
9274 		 * the fall-through branch for simulation under speculative
9275 		 * execution.
9276 		 */
9277 		if (!env->bypass_spec_v1 &&
9278 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9279 					       *insn_idx))
9280 			return -EFAULT;
9281 		*insn_idx += insn->off;
9282 		return 0;
9283 	} else if (pred == 0) {
9284 		/* Only follow the fall-through branch, since that's where the
9285 		 * program will go. If needed, push the goto branch for
9286 		 * simulation under speculative execution.
9287 		 */
9288 		if (!env->bypass_spec_v1 &&
9289 		    !sanitize_speculative_path(env, insn,
9290 					       *insn_idx + insn->off + 1,
9291 					       *insn_idx))
9292 			return -EFAULT;
9293 		return 0;
9294 	}
9295 
9296 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9297 				  false);
9298 	if (!other_branch)
9299 		return -EFAULT;
9300 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9301 
9302 	/* detect if we are comparing against a constant value so we can adjust
9303 	 * our min/max values for our dst register.
9304 	 * this is only legit if both are scalars (or pointers to the same
9305 	 * object, I suppose, but we don't support that right now), because
9306 	 * otherwise the different base pointers mean the offsets aren't
9307 	 * comparable.
9308 	 */
9309 	if (BPF_SRC(insn->code) == BPF_X) {
9310 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9311 
9312 		if (dst_reg->type == SCALAR_VALUE &&
9313 		    src_reg->type == SCALAR_VALUE) {
9314 			if (tnum_is_const(src_reg->var_off) ||
9315 			    (is_jmp32 &&
9316 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9317 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9318 						dst_reg,
9319 						src_reg->var_off.value,
9320 						tnum_subreg(src_reg->var_off).value,
9321 						opcode, is_jmp32);
9322 			else if (tnum_is_const(dst_reg->var_off) ||
9323 				 (is_jmp32 &&
9324 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9325 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9326 						    src_reg,
9327 						    dst_reg->var_off.value,
9328 						    tnum_subreg(dst_reg->var_off).value,
9329 						    opcode, is_jmp32);
9330 			else if (!is_jmp32 &&
9331 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9332 				/* Comparing for equality, we can combine knowledge */
9333 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9334 						    &other_branch_regs[insn->dst_reg],
9335 						    src_reg, dst_reg, opcode);
9336 			if (src_reg->id &&
9337 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9338 				find_equal_scalars(this_branch, src_reg);
9339 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9340 			}
9341 
9342 		}
9343 	} else if (dst_reg->type == SCALAR_VALUE) {
9344 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9345 					dst_reg, insn->imm, (u32)insn->imm,
9346 					opcode, is_jmp32);
9347 	}
9348 
9349 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9350 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9351 		find_equal_scalars(this_branch, dst_reg);
9352 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9353 	}
9354 
9355 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9356 	 * NOTE: these optimizations below are related with pointer comparison
9357 	 *       which will never be JMP32.
9358 	 */
9359 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9360 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9361 	    type_may_be_null(dst_reg->type)) {
9362 		/* Mark all identical registers in each branch as either
9363 		 * safe or unknown depending R == 0 or R != 0 conditional.
9364 		 */
9365 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9366 				      opcode == BPF_JNE);
9367 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9368 				      opcode == BPF_JEQ);
9369 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9370 					   this_branch, other_branch) &&
9371 		   is_pointer_value(env, insn->dst_reg)) {
9372 		verbose(env, "R%d pointer comparison prohibited\n",
9373 			insn->dst_reg);
9374 		return -EACCES;
9375 	}
9376 	if (env->log.level & BPF_LOG_LEVEL)
9377 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9378 	return 0;
9379 }
9380 
9381 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)9382 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9383 {
9384 	struct bpf_insn_aux_data *aux = cur_aux(env);
9385 	struct bpf_reg_state *regs = cur_regs(env);
9386 	struct bpf_reg_state *dst_reg;
9387 	struct bpf_map *map;
9388 	int err;
9389 
9390 	if (BPF_SIZE(insn->code) != BPF_DW) {
9391 		verbose(env, "invalid BPF_LD_IMM insn\n");
9392 		return -EINVAL;
9393 	}
9394 	if (insn->off != 0) {
9395 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9396 		return -EINVAL;
9397 	}
9398 
9399 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9400 	if (err)
9401 		return err;
9402 
9403 	dst_reg = &regs[insn->dst_reg];
9404 	if (insn->src_reg == 0) {
9405 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9406 
9407 		dst_reg->type = SCALAR_VALUE;
9408 		__mark_reg_known(&regs[insn->dst_reg], imm);
9409 		return 0;
9410 	}
9411 
9412 	/* All special src_reg cases are listed below. From this point onwards
9413 	 * we either succeed and assign a corresponding dst_reg->type after
9414 	 * zeroing the offset, or fail and reject the program.
9415 	 */
9416 	mark_reg_known_zero(env, regs, insn->dst_reg);
9417 
9418 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9419 		dst_reg->type = aux->btf_var.reg_type;
9420 		switch (base_type(dst_reg->type)) {
9421 		case PTR_TO_MEM:
9422 			dst_reg->mem_size = aux->btf_var.mem_size;
9423 			break;
9424 		case PTR_TO_BTF_ID:
9425 		case PTR_TO_PERCPU_BTF_ID:
9426 			dst_reg->btf = aux->btf_var.btf;
9427 			dst_reg->btf_id = aux->btf_var.btf_id;
9428 			break;
9429 		default:
9430 			verbose(env, "bpf verifier is misconfigured\n");
9431 			return -EFAULT;
9432 		}
9433 		return 0;
9434 	}
9435 
9436 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9437 		struct bpf_prog_aux *aux = env->prog->aux;
9438 		u32 subprogno = find_subprog(env,
9439 					     env->insn_idx + insn->imm + 1);
9440 
9441 		if (!aux->func_info) {
9442 			verbose(env, "missing btf func_info\n");
9443 			return -EINVAL;
9444 		}
9445 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9446 			verbose(env, "callback function not static\n");
9447 			return -EINVAL;
9448 		}
9449 
9450 		dst_reg->type = PTR_TO_FUNC;
9451 		dst_reg->subprogno = subprogno;
9452 		return 0;
9453 	}
9454 
9455 	map = env->used_maps[aux->map_index];
9456 	dst_reg->map_ptr = map;
9457 
9458 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9459 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9460 		dst_reg->type = PTR_TO_MAP_VALUE;
9461 		dst_reg->off = aux->map_off;
9462 		if (map_value_has_spin_lock(map))
9463 			dst_reg->id = ++env->id_gen;
9464 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9465 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9466 		dst_reg->type = CONST_PTR_TO_MAP;
9467 	} else {
9468 		verbose(env, "bpf verifier is misconfigured\n");
9469 		return -EINVAL;
9470 	}
9471 
9472 	return 0;
9473 }
9474 
may_access_skb(enum bpf_prog_type type)9475 static bool may_access_skb(enum bpf_prog_type type)
9476 {
9477 	switch (type) {
9478 	case BPF_PROG_TYPE_SOCKET_FILTER:
9479 	case BPF_PROG_TYPE_SCHED_CLS:
9480 	case BPF_PROG_TYPE_SCHED_ACT:
9481 		return true;
9482 	default:
9483 		return false;
9484 	}
9485 }
9486 
9487 /* verify safety of LD_ABS|LD_IND instructions:
9488  * - they can only appear in the programs where ctx == skb
9489  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9490  *   preserve R6-R9, and store return value into R0
9491  *
9492  * Implicit input:
9493  *   ctx == skb == R6 == CTX
9494  *
9495  * Explicit input:
9496  *   SRC == any register
9497  *   IMM == 32-bit immediate
9498  *
9499  * Output:
9500  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9501  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)9502 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9503 {
9504 	struct bpf_reg_state *regs = cur_regs(env);
9505 	static const int ctx_reg = BPF_REG_6;
9506 	u8 mode = BPF_MODE(insn->code);
9507 	int i, err;
9508 
9509 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9510 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9511 		return -EINVAL;
9512 	}
9513 
9514 	if (!env->ops->gen_ld_abs) {
9515 		verbose(env, "bpf verifier is misconfigured\n");
9516 		return -EINVAL;
9517 	}
9518 
9519 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9520 	    BPF_SIZE(insn->code) == BPF_DW ||
9521 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9522 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9523 		return -EINVAL;
9524 	}
9525 
9526 	/* check whether implicit source operand (register R6) is readable */
9527 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9528 	if (err)
9529 		return err;
9530 
9531 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9532 	 * gen_ld_abs() may terminate the program at runtime, leading to
9533 	 * reference leak.
9534 	 */
9535 	err = check_reference_leak(env);
9536 	if (err) {
9537 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9538 		return err;
9539 	}
9540 
9541 	if (env->cur_state->active_spin_lock) {
9542 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9543 		return -EINVAL;
9544 	}
9545 
9546 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9547 		verbose(env,
9548 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9549 		return -EINVAL;
9550 	}
9551 
9552 	if (mode == BPF_IND) {
9553 		/* check explicit source operand */
9554 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9555 		if (err)
9556 			return err;
9557 	}
9558 
9559 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9560 	if (err < 0)
9561 		return err;
9562 
9563 	/* reset caller saved regs to unreadable */
9564 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9565 		mark_reg_not_init(env, regs, caller_saved[i]);
9566 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9567 	}
9568 
9569 	/* mark destination R0 register as readable, since it contains
9570 	 * the value fetched from the packet.
9571 	 * Already marked as written above.
9572 	 */
9573 	mark_reg_unknown(env, regs, BPF_REG_0);
9574 	/* ld_abs load up to 32-bit skb data. */
9575 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9576 	return 0;
9577 }
9578 
check_return_code(struct bpf_verifier_env * env)9579 static int check_return_code(struct bpf_verifier_env *env)
9580 {
9581 	struct tnum enforce_attach_type_range = tnum_unknown;
9582 	const struct bpf_prog *prog = env->prog;
9583 	struct bpf_reg_state *reg;
9584 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
9585 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9586 	int err;
9587 	struct bpf_func_state *frame = env->cur_state->frame[0];
9588 	const bool is_subprog = frame->subprogno;
9589 
9590 	/* LSM and struct_ops func-ptr's return type could be "void" */
9591 	if (!is_subprog &&
9592 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9593 	     prog_type == BPF_PROG_TYPE_LSM) &&
9594 	    !prog->aux->attach_func_proto->type)
9595 		return 0;
9596 
9597 	/* eBPF calling convention is such that R0 is used
9598 	 * to return the value from eBPF program.
9599 	 * Make sure that it's readable at this time
9600 	 * of bpf_exit, which means that program wrote
9601 	 * something into it earlier
9602 	 */
9603 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9604 	if (err)
9605 		return err;
9606 
9607 	if (is_pointer_value(env, BPF_REG_0)) {
9608 		verbose(env, "R0 leaks addr as return value\n");
9609 		return -EACCES;
9610 	}
9611 
9612 	reg = cur_regs(env) + BPF_REG_0;
9613 
9614 	if (frame->in_async_callback_fn) {
9615 		/* enforce return zero from async callbacks like timer */
9616 		if (reg->type != SCALAR_VALUE) {
9617 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9618 				reg_type_str(env, reg->type));
9619 			return -EINVAL;
9620 		}
9621 
9622 		if (!tnum_in(const_0, reg->var_off)) {
9623 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
9624 			return -EINVAL;
9625 		}
9626 		return 0;
9627 	}
9628 
9629 	if (is_subprog) {
9630 		if (reg->type != SCALAR_VALUE) {
9631 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9632 				reg_type_str(env, reg->type));
9633 			return -EINVAL;
9634 		}
9635 		return 0;
9636 	}
9637 
9638 	switch (prog_type) {
9639 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9640 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9641 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9642 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9643 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9644 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9645 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9646 			range = tnum_range(1, 1);
9647 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9648 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9649 			range = tnum_range(0, 3);
9650 		break;
9651 	case BPF_PROG_TYPE_CGROUP_SKB:
9652 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9653 			range = tnum_range(0, 3);
9654 			enforce_attach_type_range = tnum_range(2, 3);
9655 		}
9656 		break;
9657 	case BPF_PROG_TYPE_CGROUP_SOCK:
9658 	case BPF_PROG_TYPE_SOCK_OPS:
9659 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9660 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9661 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9662 		break;
9663 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9664 		if (!env->prog->aux->attach_btf_id)
9665 			return 0;
9666 		range = tnum_const(0);
9667 		break;
9668 	case BPF_PROG_TYPE_TRACING:
9669 		switch (env->prog->expected_attach_type) {
9670 		case BPF_TRACE_FENTRY:
9671 		case BPF_TRACE_FEXIT:
9672 			range = tnum_const(0);
9673 			break;
9674 		case BPF_TRACE_RAW_TP:
9675 		case BPF_MODIFY_RETURN:
9676 			return 0;
9677 		case BPF_TRACE_ITER:
9678 			break;
9679 		default:
9680 			return -ENOTSUPP;
9681 		}
9682 		break;
9683 	case BPF_PROG_TYPE_SK_LOOKUP:
9684 		range = tnum_range(SK_DROP, SK_PASS);
9685 		break;
9686 	case BPF_PROG_TYPE_EXT:
9687 		/* freplace program can return anything as its return value
9688 		 * depends on the to-be-replaced kernel func or bpf program.
9689 		 */
9690 	default:
9691 		return 0;
9692 	}
9693 
9694 	if (reg->type != SCALAR_VALUE) {
9695 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9696 			reg_type_str(env, reg->type));
9697 		return -EINVAL;
9698 	}
9699 
9700 	if (!tnum_in(range, reg->var_off)) {
9701 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9702 		return -EINVAL;
9703 	}
9704 
9705 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9706 	    tnum_in(enforce_attach_type_range, reg->var_off))
9707 		env->prog->enforce_expected_attach_type = 1;
9708 	return 0;
9709 }
9710 
9711 /* non-recursive DFS pseudo code
9712  * 1  procedure DFS-iterative(G,v):
9713  * 2      label v as discovered
9714  * 3      let S be a stack
9715  * 4      S.push(v)
9716  * 5      while S is not empty
9717  * 6            t <- S.pop()
9718  * 7            if t is what we're looking for:
9719  * 8                return t
9720  * 9            for all edges e in G.adjacentEdges(t) do
9721  * 10               if edge e is already labelled
9722  * 11                   continue with the next edge
9723  * 12               w <- G.adjacentVertex(t,e)
9724  * 13               if vertex w is not discovered and not explored
9725  * 14                   label e as tree-edge
9726  * 15                   label w as discovered
9727  * 16                   S.push(w)
9728  * 17                   continue at 5
9729  * 18               else if vertex w is discovered
9730  * 19                   label e as back-edge
9731  * 20               else
9732  * 21                   // vertex w is explored
9733  * 22                   label e as forward- or cross-edge
9734  * 23           label t as explored
9735  * 24           S.pop()
9736  *
9737  * convention:
9738  * 0x10 - discovered
9739  * 0x11 - discovered and fall-through edge labelled
9740  * 0x12 - discovered and fall-through and branch edges labelled
9741  * 0x20 - explored
9742  */
9743 
9744 enum {
9745 	DISCOVERED = 0x10,
9746 	EXPLORED = 0x20,
9747 	FALLTHROUGH = 1,
9748 	BRANCH = 2,
9749 };
9750 
state_htab_size(struct bpf_verifier_env * env)9751 static u32 state_htab_size(struct bpf_verifier_env *env)
9752 {
9753 	return env->prog->len;
9754 }
9755 
explored_state(struct bpf_verifier_env * env,int idx)9756 static struct bpf_verifier_state_list **explored_state(
9757 					struct bpf_verifier_env *env,
9758 					int idx)
9759 {
9760 	struct bpf_verifier_state *cur = env->cur_state;
9761 	struct bpf_func_state *state = cur->frame[cur->curframe];
9762 
9763 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9764 }
9765 
init_explored_state(struct bpf_verifier_env * env,int idx)9766 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9767 {
9768 	env->insn_aux_data[idx].prune_point = true;
9769 }
9770 
9771 enum {
9772 	DONE_EXPLORING = 0,
9773 	KEEP_EXPLORING = 1,
9774 };
9775 
9776 /* t, w, e - match pseudo-code above:
9777  * t - index of current instruction
9778  * w - next instruction
9779  * e - edge
9780  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)9781 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9782 		     bool loop_ok)
9783 {
9784 	int *insn_stack = env->cfg.insn_stack;
9785 	int *insn_state = env->cfg.insn_state;
9786 
9787 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9788 		return DONE_EXPLORING;
9789 
9790 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9791 		return DONE_EXPLORING;
9792 
9793 	if (w < 0 || w >= env->prog->len) {
9794 		verbose_linfo(env, t, "%d: ", t);
9795 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9796 		return -EINVAL;
9797 	}
9798 
9799 	if (e == BRANCH)
9800 		/* mark branch target for state pruning */
9801 		init_explored_state(env, w);
9802 
9803 	if (insn_state[w] == 0) {
9804 		/* tree-edge */
9805 		insn_state[t] = DISCOVERED | e;
9806 		insn_state[w] = DISCOVERED;
9807 		if (env->cfg.cur_stack >= env->prog->len)
9808 			return -E2BIG;
9809 		insn_stack[env->cfg.cur_stack++] = w;
9810 		return KEEP_EXPLORING;
9811 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9812 		if (loop_ok && env->bpf_capable)
9813 			return DONE_EXPLORING;
9814 		verbose_linfo(env, t, "%d: ", t);
9815 		verbose_linfo(env, w, "%d: ", w);
9816 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9817 		return -EINVAL;
9818 	} else if (insn_state[w] == EXPLORED) {
9819 		/* forward- or cross-edge */
9820 		insn_state[t] = DISCOVERED | e;
9821 	} else {
9822 		verbose(env, "insn state internal bug\n");
9823 		return -EFAULT;
9824 	}
9825 	return DONE_EXPLORING;
9826 }
9827 
visit_func_call_insn(int t,int insn_cnt,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)9828 static int visit_func_call_insn(int t, int insn_cnt,
9829 				struct bpf_insn *insns,
9830 				struct bpf_verifier_env *env,
9831 				bool visit_callee)
9832 {
9833 	int ret;
9834 
9835 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9836 	if (ret)
9837 		return ret;
9838 
9839 	if (t + 1 < insn_cnt)
9840 		init_explored_state(env, t + 1);
9841 	if (visit_callee) {
9842 		init_explored_state(env, t);
9843 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9844 				/* It's ok to allow recursion from CFG point of
9845 				 * view. __check_func_call() will do the actual
9846 				 * check.
9847 				 */
9848 				bpf_pseudo_func(insns + t));
9849 	}
9850 	return ret;
9851 }
9852 
9853 /* Visits the instruction at index t and returns one of the following:
9854  *  < 0 - an error occurred
9855  *  DONE_EXPLORING - the instruction was fully explored
9856  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9857  */
visit_insn(int t,int insn_cnt,struct bpf_verifier_env * env)9858 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9859 {
9860 	struct bpf_insn *insns = env->prog->insnsi;
9861 	int ret;
9862 
9863 	if (bpf_pseudo_func(insns + t))
9864 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9865 
9866 	/* All non-branch instructions have a single fall-through edge. */
9867 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9868 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9869 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9870 
9871 	switch (BPF_OP(insns[t].code)) {
9872 	case BPF_EXIT:
9873 		return DONE_EXPLORING;
9874 
9875 	case BPF_CALL:
9876 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9877 			/* Mark this call insn to trigger is_state_visited() check
9878 			 * before call itself is processed by __check_func_call().
9879 			 * Otherwise new async state will be pushed for further
9880 			 * exploration.
9881 			 */
9882 			init_explored_state(env, t);
9883 		return visit_func_call_insn(t, insn_cnt, insns, env,
9884 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9885 
9886 	case BPF_JA:
9887 		if (BPF_SRC(insns[t].code) != BPF_K)
9888 			return -EINVAL;
9889 
9890 		/* unconditional jump with single edge */
9891 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9892 				true);
9893 		if (ret)
9894 			return ret;
9895 
9896 		/* unconditional jmp is not a good pruning point,
9897 		 * but it's marked, since backtracking needs
9898 		 * to record jmp history in is_state_visited().
9899 		 */
9900 		init_explored_state(env, t + insns[t].off + 1);
9901 		/* tell verifier to check for equivalent states
9902 		 * after every call and jump
9903 		 */
9904 		if (t + 1 < insn_cnt)
9905 			init_explored_state(env, t + 1);
9906 
9907 		return ret;
9908 
9909 	default:
9910 		/* conditional jump with two edges */
9911 		init_explored_state(env, t);
9912 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9913 		if (ret)
9914 			return ret;
9915 
9916 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9917 	}
9918 }
9919 
9920 /* non-recursive depth-first-search to detect loops in BPF program
9921  * loop == back-edge in directed graph
9922  */
check_cfg(struct bpf_verifier_env * env)9923 static int check_cfg(struct bpf_verifier_env *env)
9924 {
9925 	int insn_cnt = env->prog->len;
9926 	int *insn_stack, *insn_state;
9927 	int ret = 0;
9928 	int i;
9929 
9930 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9931 	if (!insn_state)
9932 		return -ENOMEM;
9933 
9934 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9935 	if (!insn_stack) {
9936 		kvfree(insn_state);
9937 		return -ENOMEM;
9938 	}
9939 
9940 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9941 	insn_stack[0] = 0; /* 0 is the first instruction */
9942 	env->cfg.cur_stack = 1;
9943 
9944 	while (env->cfg.cur_stack > 0) {
9945 		int t = insn_stack[env->cfg.cur_stack - 1];
9946 
9947 		ret = visit_insn(t, insn_cnt, env);
9948 		switch (ret) {
9949 		case DONE_EXPLORING:
9950 			insn_state[t] = EXPLORED;
9951 			env->cfg.cur_stack--;
9952 			break;
9953 		case KEEP_EXPLORING:
9954 			break;
9955 		default:
9956 			if (ret > 0) {
9957 				verbose(env, "visit_insn internal bug\n");
9958 				ret = -EFAULT;
9959 			}
9960 			goto err_free;
9961 		}
9962 	}
9963 
9964 	if (env->cfg.cur_stack < 0) {
9965 		verbose(env, "pop stack internal bug\n");
9966 		ret = -EFAULT;
9967 		goto err_free;
9968 	}
9969 
9970 	for (i = 0; i < insn_cnt; i++) {
9971 		if (insn_state[i] != EXPLORED) {
9972 			verbose(env, "unreachable insn %d\n", i);
9973 			ret = -EINVAL;
9974 			goto err_free;
9975 		}
9976 	}
9977 	ret = 0; /* cfg looks good */
9978 
9979 err_free:
9980 	kvfree(insn_state);
9981 	kvfree(insn_stack);
9982 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9983 	return ret;
9984 }
9985 
check_abnormal_return(struct bpf_verifier_env * env)9986 static int check_abnormal_return(struct bpf_verifier_env *env)
9987 {
9988 	int i;
9989 
9990 	for (i = 1; i < env->subprog_cnt; i++) {
9991 		if (env->subprog_info[i].has_ld_abs) {
9992 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9993 			return -EINVAL;
9994 		}
9995 		if (env->subprog_info[i].has_tail_call) {
9996 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9997 			return -EINVAL;
9998 		}
9999 	}
10000 	return 0;
10001 }
10002 
10003 /* The minimum supported BTF func info size */
10004 #define MIN_BPF_FUNCINFO_SIZE	8
10005 #define MAX_FUNCINFO_REC_SIZE	252
10006 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)10007 static int check_btf_func(struct bpf_verifier_env *env,
10008 			  const union bpf_attr *attr,
10009 			  bpfptr_t uattr)
10010 {
10011 	const struct btf_type *type, *func_proto, *ret_type;
10012 	u32 i, nfuncs, urec_size, min_size;
10013 	u32 krec_size = sizeof(struct bpf_func_info);
10014 	struct bpf_func_info *krecord;
10015 	struct bpf_func_info_aux *info_aux = NULL;
10016 	struct bpf_prog *prog;
10017 	const struct btf *btf;
10018 	bpfptr_t urecord;
10019 	u32 prev_offset = 0;
10020 	bool scalar_return;
10021 	int ret = -ENOMEM;
10022 
10023 	nfuncs = attr->func_info_cnt;
10024 	if (!nfuncs) {
10025 		if (check_abnormal_return(env))
10026 			return -EINVAL;
10027 		return 0;
10028 	}
10029 
10030 	if (nfuncs != env->subprog_cnt) {
10031 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10032 		return -EINVAL;
10033 	}
10034 
10035 	urec_size = attr->func_info_rec_size;
10036 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10037 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10038 	    urec_size % sizeof(u32)) {
10039 		verbose(env, "invalid func info rec size %u\n", urec_size);
10040 		return -EINVAL;
10041 	}
10042 
10043 	prog = env->prog;
10044 	btf = prog->aux->btf;
10045 
10046 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10047 	min_size = min_t(u32, krec_size, urec_size);
10048 
10049 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10050 	if (!krecord)
10051 		return -ENOMEM;
10052 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10053 	if (!info_aux)
10054 		goto err_free;
10055 
10056 	for (i = 0; i < nfuncs; i++) {
10057 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10058 		if (ret) {
10059 			if (ret == -E2BIG) {
10060 				verbose(env, "nonzero tailing record in func info");
10061 				/* set the size kernel expects so loader can zero
10062 				 * out the rest of the record.
10063 				 */
10064 				if (copy_to_bpfptr_offset(uattr,
10065 							  offsetof(union bpf_attr, func_info_rec_size),
10066 							  &min_size, sizeof(min_size)))
10067 					ret = -EFAULT;
10068 			}
10069 			goto err_free;
10070 		}
10071 
10072 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10073 			ret = -EFAULT;
10074 			goto err_free;
10075 		}
10076 
10077 		/* check insn_off */
10078 		ret = -EINVAL;
10079 		if (i == 0) {
10080 			if (krecord[i].insn_off) {
10081 				verbose(env,
10082 					"nonzero insn_off %u for the first func info record",
10083 					krecord[i].insn_off);
10084 				goto err_free;
10085 			}
10086 		} else if (krecord[i].insn_off <= prev_offset) {
10087 			verbose(env,
10088 				"same or smaller insn offset (%u) than previous func info record (%u)",
10089 				krecord[i].insn_off, prev_offset);
10090 			goto err_free;
10091 		}
10092 
10093 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10094 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10095 			goto err_free;
10096 		}
10097 
10098 		/* check type_id */
10099 		type = btf_type_by_id(btf, krecord[i].type_id);
10100 		if (!type || !btf_type_is_func(type)) {
10101 			verbose(env, "invalid type id %d in func info",
10102 				krecord[i].type_id);
10103 			goto err_free;
10104 		}
10105 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10106 
10107 		func_proto = btf_type_by_id(btf, type->type);
10108 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10109 			/* btf_func_check() already verified it during BTF load */
10110 			goto err_free;
10111 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10112 		scalar_return =
10113 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10114 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10115 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10116 			goto err_free;
10117 		}
10118 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10119 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10120 			goto err_free;
10121 		}
10122 
10123 		prev_offset = krecord[i].insn_off;
10124 		bpfptr_add(&urecord, urec_size);
10125 	}
10126 
10127 	prog->aux->func_info = krecord;
10128 	prog->aux->func_info_cnt = nfuncs;
10129 	prog->aux->func_info_aux = info_aux;
10130 	return 0;
10131 
10132 err_free:
10133 	kvfree(krecord);
10134 	kfree(info_aux);
10135 	return ret;
10136 }
10137 
adjust_btf_func(struct bpf_verifier_env * env)10138 static void adjust_btf_func(struct bpf_verifier_env *env)
10139 {
10140 	struct bpf_prog_aux *aux = env->prog->aux;
10141 	int i;
10142 
10143 	if (!aux->func_info)
10144 		return;
10145 
10146 	for (i = 0; i < env->subprog_cnt; i++)
10147 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10148 }
10149 
10150 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
10151 		sizeof(((struct bpf_line_info *)(0))->line_col))
10152 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10153 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)10154 static int check_btf_line(struct bpf_verifier_env *env,
10155 			  const union bpf_attr *attr,
10156 			  bpfptr_t uattr)
10157 {
10158 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10159 	struct bpf_subprog_info *sub;
10160 	struct bpf_line_info *linfo;
10161 	struct bpf_prog *prog;
10162 	const struct btf *btf;
10163 	bpfptr_t ulinfo;
10164 	int err;
10165 
10166 	nr_linfo = attr->line_info_cnt;
10167 	if (!nr_linfo)
10168 		return 0;
10169 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10170 		return -EINVAL;
10171 
10172 	rec_size = attr->line_info_rec_size;
10173 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10174 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10175 	    rec_size & (sizeof(u32) - 1))
10176 		return -EINVAL;
10177 
10178 	/* Need to zero it in case the userspace may
10179 	 * pass in a smaller bpf_line_info object.
10180 	 */
10181 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10182 			 GFP_KERNEL | __GFP_NOWARN);
10183 	if (!linfo)
10184 		return -ENOMEM;
10185 
10186 	prog = env->prog;
10187 	btf = prog->aux->btf;
10188 
10189 	s = 0;
10190 	sub = env->subprog_info;
10191 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10192 	expected_size = sizeof(struct bpf_line_info);
10193 	ncopy = min_t(u32, expected_size, rec_size);
10194 	for (i = 0; i < nr_linfo; i++) {
10195 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10196 		if (err) {
10197 			if (err == -E2BIG) {
10198 				verbose(env, "nonzero tailing record in line_info");
10199 				if (copy_to_bpfptr_offset(uattr,
10200 							  offsetof(union bpf_attr, line_info_rec_size),
10201 							  &expected_size, sizeof(expected_size)))
10202 					err = -EFAULT;
10203 			}
10204 			goto err_free;
10205 		}
10206 
10207 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10208 			err = -EFAULT;
10209 			goto err_free;
10210 		}
10211 
10212 		/*
10213 		 * Check insn_off to ensure
10214 		 * 1) strictly increasing AND
10215 		 * 2) bounded by prog->len
10216 		 *
10217 		 * The linfo[0].insn_off == 0 check logically falls into
10218 		 * the later "missing bpf_line_info for func..." case
10219 		 * because the first linfo[0].insn_off must be the
10220 		 * first sub also and the first sub must have
10221 		 * subprog_info[0].start == 0.
10222 		 */
10223 		if ((i && linfo[i].insn_off <= prev_offset) ||
10224 		    linfo[i].insn_off >= prog->len) {
10225 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10226 				i, linfo[i].insn_off, prev_offset,
10227 				prog->len);
10228 			err = -EINVAL;
10229 			goto err_free;
10230 		}
10231 
10232 		if (!prog->insnsi[linfo[i].insn_off].code) {
10233 			verbose(env,
10234 				"Invalid insn code at line_info[%u].insn_off\n",
10235 				i);
10236 			err = -EINVAL;
10237 			goto err_free;
10238 		}
10239 
10240 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10241 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10242 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10243 			err = -EINVAL;
10244 			goto err_free;
10245 		}
10246 
10247 		if (s != env->subprog_cnt) {
10248 			if (linfo[i].insn_off == sub[s].start) {
10249 				sub[s].linfo_idx = i;
10250 				s++;
10251 			} else if (sub[s].start < linfo[i].insn_off) {
10252 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10253 				err = -EINVAL;
10254 				goto err_free;
10255 			}
10256 		}
10257 
10258 		prev_offset = linfo[i].insn_off;
10259 		bpfptr_add(&ulinfo, rec_size);
10260 	}
10261 
10262 	if (s != env->subprog_cnt) {
10263 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10264 			env->subprog_cnt - s, s);
10265 		err = -EINVAL;
10266 		goto err_free;
10267 	}
10268 
10269 	prog->aux->linfo = linfo;
10270 	prog->aux->nr_linfo = nr_linfo;
10271 
10272 	return 0;
10273 
10274 err_free:
10275 	kvfree(linfo);
10276 	return err;
10277 }
10278 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)10279 static int check_btf_info(struct bpf_verifier_env *env,
10280 			  const union bpf_attr *attr,
10281 			  bpfptr_t uattr)
10282 {
10283 	struct btf *btf;
10284 	int err;
10285 
10286 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10287 		if (check_abnormal_return(env))
10288 			return -EINVAL;
10289 		return 0;
10290 	}
10291 
10292 	btf = btf_get_by_fd(attr->prog_btf_fd);
10293 	if (IS_ERR(btf))
10294 		return PTR_ERR(btf);
10295 	if (btf_is_kernel(btf)) {
10296 		btf_put(btf);
10297 		return -EACCES;
10298 	}
10299 	env->prog->aux->btf = btf;
10300 
10301 	err = check_btf_func(env, attr, uattr);
10302 	if (err)
10303 		return err;
10304 
10305 	err = check_btf_line(env, attr, uattr);
10306 	if (err)
10307 		return err;
10308 
10309 	return 0;
10310 }
10311 
10312 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)10313 static bool range_within(struct bpf_reg_state *old,
10314 			 struct bpf_reg_state *cur)
10315 {
10316 	return old->umin_value <= cur->umin_value &&
10317 	       old->umax_value >= cur->umax_value &&
10318 	       old->smin_value <= cur->smin_value &&
10319 	       old->smax_value >= cur->smax_value &&
10320 	       old->u32_min_value <= cur->u32_min_value &&
10321 	       old->u32_max_value >= cur->u32_max_value &&
10322 	       old->s32_min_value <= cur->s32_min_value &&
10323 	       old->s32_max_value >= cur->s32_max_value;
10324 }
10325 
10326 /* If in the old state two registers had the same id, then they need to have
10327  * the same id in the new state as well.  But that id could be different from
10328  * the old state, so we need to track the mapping from old to new ids.
10329  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10330  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10331  * regs with a different old id could still have new id 9, we don't care about
10332  * that.
10333  * So we look through our idmap to see if this old id has been seen before.  If
10334  * so, we require the new id to match; otherwise, we add the id pair to the map.
10335  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)10336 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10337 {
10338 	unsigned int i;
10339 
10340 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10341 		if (!idmap[i].old) {
10342 			/* Reached an empty slot; haven't seen this id before */
10343 			idmap[i].old = old_id;
10344 			idmap[i].cur = cur_id;
10345 			return true;
10346 		}
10347 		if (idmap[i].old == old_id)
10348 			return idmap[i].cur == cur_id;
10349 	}
10350 	/* We ran out of idmap slots, which should be impossible */
10351 	WARN_ON_ONCE(1);
10352 	return false;
10353 }
10354 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)10355 static void clean_func_state(struct bpf_verifier_env *env,
10356 			     struct bpf_func_state *st)
10357 {
10358 	enum bpf_reg_liveness live;
10359 	int i, j;
10360 
10361 	for (i = 0; i < BPF_REG_FP; i++) {
10362 		live = st->regs[i].live;
10363 		/* liveness must not touch this register anymore */
10364 		st->regs[i].live |= REG_LIVE_DONE;
10365 		if (!(live & REG_LIVE_READ))
10366 			/* since the register is unused, clear its state
10367 			 * to make further comparison simpler
10368 			 */
10369 			__mark_reg_not_init(env, &st->regs[i]);
10370 	}
10371 
10372 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10373 		live = st->stack[i].spilled_ptr.live;
10374 		/* liveness must not touch this stack slot anymore */
10375 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10376 		if (!(live & REG_LIVE_READ)) {
10377 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10378 			for (j = 0; j < BPF_REG_SIZE; j++)
10379 				st->stack[i].slot_type[j] = STACK_INVALID;
10380 		}
10381 	}
10382 }
10383 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)10384 static void clean_verifier_state(struct bpf_verifier_env *env,
10385 				 struct bpf_verifier_state *st)
10386 {
10387 	int i;
10388 
10389 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10390 		/* all regs in this state in all frames were already marked */
10391 		return;
10392 
10393 	for (i = 0; i <= st->curframe; i++)
10394 		clean_func_state(env, st->frame[i]);
10395 }
10396 
10397 /* the parentage chains form a tree.
10398  * the verifier states are added to state lists at given insn and
10399  * pushed into state stack for future exploration.
10400  * when the verifier reaches bpf_exit insn some of the verifer states
10401  * stored in the state lists have their final liveness state already,
10402  * but a lot of states will get revised from liveness point of view when
10403  * the verifier explores other branches.
10404  * Example:
10405  * 1: r0 = 1
10406  * 2: if r1 == 100 goto pc+1
10407  * 3: r0 = 2
10408  * 4: exit
10409  * when the verifier reaches exit insn the register r0 in the state list of
10410  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10411  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10412  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10413  *
10414  * Since the verifier pushes the branch states as it sees them while exploring
10415  * the program the condition of walking the branch instruction for the second
10416  * time means that all states below this branch were already explored and
10417  * their final liveness marks are already propagated.
10418  * Hence when the verifier completes the search of state list in is_state_visited()
10419  * we can call this clean_live_states() function to mark all liveness states
10420  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10421  * will not be used.
10422  * This function also clears the registers and stack for states that !READ
10423  * to simplify state merging.
10424  *
10425  * Important note here that walking the same branch instruction in the callee
10426  * doesn't meant that the states are DONE. The verifier has to compare
10427  * the callsites
10428  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)10429 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10430 			      struct bpf_verifier_state *cur)
10431 {
10432 	struct bpf_verifier_state_list *sl;
10433 	int i;
10434 
10435 	sl = *explored_state(env, insn);
10436 	while (sl) {
10437 		if (sl->state.branches)
10438 			goto next;
10439 		if (sl->state.insn_idx != insn ||
10440 		    sl->state.curframe != cur->curframe)
10441 			goto next;
10442 		for (i = 0; i <= cur->curframe; i++)
10443 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10444 				goto next;
10445 		clean_verifier_state(env, &sl->state);
10446 next:
10447 		sl = sl->next;
10448 	}
10449 }
10450 
10451 /* 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)10452 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10453 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10454 {
10455 	bool equal;
10456 
10457 	if (!(rold->live & REG_LIVE_READ))
10458 		/* explored state didn't use this */
10459 		return true;
10460 
10461 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10462 
10463 	if (rold->type == PTR_TO_STACK)
10464 		/* two stack pointers are equal only if they're pointing to
10465 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10466 		 */
10467 		return equal && rold->frameno == rcur->frameno;
10468 
10469 	if (equal)
10470 		return true;
10471 
10472 	if (rold->type == NOT_INIT)
10473 		/* explored state can't have used this */
10474 		return true;
10475 	if (rcur->type == NOT_INIT)
10476 		return false;
10477 	switch (base_type(rold->type)) {
10478 	case SCALAR_VALUE:
10479 		if (env->explore_alu_limits)
10480 			return false;
10481 		if (rcur->type == SCALAR_VALUE) {
10482 			if (!rold->precise)
10483 				return true;
10484 			/* new val must satisfy old val knowledge */
10485 			return range_within(rold, rcur) &&
10486 			       tnum_in(rold->var_off, rcur->var_off);
10487 		} else {
10488 			/* We're trying to use a pointer in place of a scalar.
10489 			 * Even if the scalar was unbounded, this could lead to
10490 			 * pointer leaks because scalars are allowed to leak
10491 			 * while pointers are not. We could make this safe in
10492 			 * special cases if root is calling us, but it's
10493 			 * probably not worth the hassle.
10494 			 */
10495 			return false;
10496 		}
10497 	case PTR_TO_MAP_KEY:
10498 	case PTR_TO_MAP_VALUE:
10499 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10500 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10501 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10502 		 * checked, doing so could have affected others with the same
10503 		 * id, and we can't check for that because we lost the id when
10504 		 * we converted to a PTR_TO_MAP_VALUE.
10505 		 */
10506 		if (type_may_be_null(rold->type)) {
10507 			if (!type_may_be_null(rcur->type))
10508 				return false;
10509 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10510 				return false;
10511 			/* Check our ids match any regs they're supposed to */
10512 			return check_ids(rold->id, rcur->id, idmap);
10513 		}
10514 
10515 		/* If the new min/max/var_off satisfy the old ones and
10516 		 * everything else matches, we are OK.
10517 		 * 'id' is not compared, since it's only used for maps with
10518 		 * bpf_spin_lock inside map element and in such cases if
10519 		 * the rest of the prog is valid for one map element then
10520 		 * it's valid for all map elements regardless of the key
10521 		 * used in bpf_map_lookup()
10522 		 */
10523 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10524 		       range_within(rold, rcur) &&
10525 		       tnum_in(rold->var_off, rcur->var_off);
10526 	case PTR_TO_PACKET_META:
10527 	case PTR_TO_PACKET:
10528 		if (rcur->type != rold->type)
10529 			return false;
10530 		/* We must have at least as much range as the old ptr
10531 		 * did, so that any accesses which were safe before are
10532 		 * still safe.  This is true even if old range < old off,
10533 		 * since someone could have accessed through (ptr - k), or
10534 		 * even done ptr -= k in a register, to get a safe access.
10535 		 */
10536 		if (rold->range > rcur->range)
10537 			return false;
10538 		/* If the offsets don't match, we can't trust our alignment;
10539 		 * nor can we be sure that we won't fall out of range.
10540 		 */
10541 		if (rold->off != rcur->off)
10542 			return false;
10543 		/* id relations must be preserved */
10544 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10545 			return false;
10546 		/* new val must satisfy old val knowledge */
10547 		return range_within(rold, rcur) &&
10548 		       tnum_in(rold->var_off, rcur->var_off);
10549 	case PTR_TO_CTX:
10550 	case CONST_PTR_TO_MAP:
10551 	case PTR_TO_PACKET_END:
10552 	case PTR_TO_FLOW_KEYS:
10553 	case PTR_TO_SOCKET:
10554 	case PTR_TO_SOCK_COMMON:
10555 	case PTR_TO_TCP_SOCK:
10556 	case PTR_TO_XDP_SOCK:
10557 		/* Only valid matches are exact, which memcmp() above
10558 		 * would have accepted
10559 		 */
10560 	default:
10561 		/* Don't know what's going on, just say it's not safe */
10562 		return false;
10563 	}
10564 
10565 	/* Shouldn't get here; if we do, say it's not safe */
10566 	WARN_ON_ONCE(1);
10567 	return false;
10568 }
10569 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)10570 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10571 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10572 {
10573 	int i, spi;
10574 
10575 	/* walk slots of the explored stack and ignore any additional
10576 	 * slots in the current stack, since explored(safe) state
10577 	 * didn't use them
10578 	 */
10579 	for (i = 0; i < old->allocated_stack; i++) {
10580 		spi = i / BPF_REG_SIZE;
10581 
10582 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10583 			i += BPF_REG_SIZE - 1;
10584 			/* explored state didn't use this */
10585 			continue;
10586 		}
10587 
10588 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10589 			continue;
10590 
10591 		/* explored stack has more populated slots than current stack
10592 		 * and these slots were used
10593 		 */
10594 		if (i >= cur->allocated_stack)
10595 			return false;
10596 
10597 		/* if old state was safe with misc data in the stack
10598 		 * it will be safe with zero-initialized stack.
10599 		 * The opposite is not true
10600 		 */
10601 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10602 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10603 			continue;
10604 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10605 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10606 			/* Ex: old explored (safe) state has STACK_SPILL in
10607 			 * this stack slot, but current has STACK_MISC ->
10608 			 * this verifier states are not equivalent,
10609 			 * return false to continue verification of this path
10610 			 */
10611 			return false;
10612 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10613 			continue;
10614 		if (!is_spilled_reg(&old->stack[spi]))
10615 			continue;
10616 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10617 			     &cur->stack[spi].spilled_ptr, idmap))
10618 			/* when explored and current stack slot are both storing
10619 			 * spilled registers, check that stored pointers types
10620 			 * are the same as well.
10621 			 * Ex: explored safe path could have stored
10622 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10623 			 * but current path has stored:
10624 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10625 			 * such verifier states are not equivalent.
10626 			 * return false to continue verification of this path
10627 			 */
10628 			return false;
10629 	}
10630 	return true;
10631 }
10632 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)10633 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10634 {
10635 	if (old->acquired_refs != cur->acquired_refs)
10636 		return false;
10637 	return !memcmp(old->refs, cur->refs,
10638 		       sizeof(*old->refs) * old->acquired_refs);
10639 }
10640 
10641 /* compare two verifier states
10642  *
10643  * all states stored in state_list are known to be valid, since
10644  * verifier reached 'bpf_exit' instruction through them
10645  *
10646  * this function is called when verifier exploring different branches of
10647  * execution popped from the state stack. If it sees an old state that has
10648  * more strict register state and more strict stack state then this execution
10649  * branch doesn't need to be explored further, since verifier already
10650  * concluded that more strict state leads to valid finish.
10651  *
10652  * Therefore two states are equivalent if register state is more conservative
10653  * and explored stack state is more conservative than the current one.
10654  * Example:
10655  *       explored                   current
10656  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10657  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10658  *
10659  * In other words if current stack state (one being explored) has more
10660  * valid slots than old one that already passed validation, it means
10661  * the verifier can stop exploring and conclude that current state is valid too
10662  *
10663  * Similarly with registers. If explored state has register type as invalid
10664  * whereas register type in current state is meaningful, it means that
10665  * the current state will reach 'bpf_exit' instruction safely
10666  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)10667 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10668 			      struct bpf_func_state *cur)
10669 {
10670 	int i;
10671 
10672 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10673 	for (i = 0; i < MAX_BPF_REG; i++)
10674 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10675 			     env->idmap_scratch))
10676 			return false;
10677 
10678 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10679 		return false;
10680 
10681 	if (!refsafe(old, cur))
10682 		return false;
10683 
10684 	return true;
10685 }
10686 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)10687 static bool states_equal(struct bpf_verifier_env *env,
10688 			 struct bpf_verifier_state *old,
10689 			 struct bpf_verifier_state *cur)
10690 {
10691 	int i;
10692 
10693 	if (old->curframe != cur->curframe)
10694 		return false;
10695 
10696 	/* Verification state from speculative execution simulation
10697 	 * must never prune a non-speculative execution one.
10698 	 */
10699 	if (old->speculative && !cur->speculative)
10700 		return false;
10701 
10702 	if (old->active_spin_lock != cur->active_spin_lock)
10703 		return false;
10704 
10705 	/* for states to be equal callsites have to be the same
10706 	 * and all frame states need to be equivalent
10707 	 */
10708 	for (i = 0; i <= old->curframe; i++) {
10709 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10710 			return false;
10711 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10712 			return false;
10713 	}
10714 	return true;
10715 }
10716 
10717 /* Return 0 if no propagation happened. Return negative error code if error
10718  * happened. Otherwise, return the propagated bit.
10719  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)10720 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10721 				  struct bpf_reg_state *reg,
10722 				  struct bpf_reg_state *parent_reg)
10723 {
10724 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10725 	u8 flag = reg->live & REG_LIVE_READ;
10726 	int err;
10727 
10728 	/* When comes here, read flags of PARENT_REG or REG could be any of
10729 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10730 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10731 	 */
10732 	if (parent_flag == REG_LIVE_READ64 ||
10733 	    /* Or if there is no read flag from REG. */
10734 	    !flag ||
10735 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10736 	    parent_flag == flag)
10737 		return 0;
10738 
10739 	err = mark_reg_read(env, reg, parent_reg, flag);
10740 	if (err)
10741 		return err;
10742 
10743 	return flag;
10744 }
10745 
10746 /* A write screens off any subsequent reads; but write marks come from the
10747  * straight-line code between a state and its parent.  When we arrive at an
10748  * equivalent state (jump target or such) we didn't arrive by the straight-line
10749  * code, so read marks in the state must propagate to the parent regardless
10750  * of the state's write marks. That's what 'parent == state->parent' comparison
10751  * in mark_reg_read() is for.
10752  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)10753 static int propagate_liveness(struct bpf_verifier_env *env,
10754 			      const struct bpf_verifier_state *vstate,
10755 			      struct bpf_verifier_state *vparent)
10756 {
10757 	struct bpf_reg_state *state_reg, *parent_reg;
10758 	struct bpf_func_state *state, *parent;
10759 	int i, frame, err = 0;
10760 
10761 	if (vparent->curframe != vstate->curframe) {
10762 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10763 		     vparent->curframe, vstate->curframe);
10764 		return -EFAULT;
10765 	}
10766 	/* Propagate read liveness of registers... */
10767 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10768 	for (frame = 0; frame <= vstate->curframe; frame++) {
10769 		parent = vparent->frame[frame];
10770 		state = vstate->frame[frame];
10771 		parent_reg = parent->regs;
10772 		state_reg = state->regs;
10773 		/* We don't need to worry about FP liveness, it's read-only */
10774 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10775 			err = propagate_liveness_reg(env, &state_reg[i],
10776 						     &parent_reg[i]);
10777 			if (err < 0)
10778 				return err;
10779 			if (err == REG_LIVE_READ64)
10780 				mark_insn_zext(env, &parent_reg[i]);
10781 		}
10782 
10783 		/* Propagate stack slots. */
10784 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10785 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10786 			parent_reg = &parent->stack[i].spilled_ptr;
10787 			state_reg = &state->stack[i].spilled_ptr;
10788 			err = propagate_liveness_reg(env, state_reg,
10789 						     parent_reg);
10790 			if (err < 0)
10791 				return err;
10792 		}
10793 	}
10794 	return 0;
10795 }
10796 
10797 /* find precise scalars in the previous equivalent state and
10798  * propagate them into the current state
10799  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)10800 static int propagate_precision(struct bpf_verifier_env *env,
10801 			       const struct bpf_verifier_state *old)
10802 {
10803 	struct bpf_reg_state *state_reg;
10804 	struct bpf_func_state *state;
10805 	int i, err = 0, fr;
10806 
10807 	for (fr = old->curframe; fr >= 0; fr--) {
10808 		state = old->frame[fr];
10809 		state_reg = state->regs;
10810 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10811 			if (state_reg->type != SCALAR_VALUE ||
10812 			    !state_reg->precise ||
10813 			    !(state_reg->live & REG_LIVE_READ))
10814 				continue;
10815 			if (env->log.level & BPF_LOG_LEVEL2)
10816 				verbose(env, "frame %d: propagating r%d\n", fr, i);
10817 			err = mark_chain_precision_frame(env, fr, i);
10818 			if (err < 0)
10819 				return err;
10820 		}
10821 
10822 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10823 			if (!is_spilled_reg(&state->stack[i]))
10824 				continue;
10825 			state_reg = &state->stack[i].spilled_ptr;
10826 			if (state_reg->type != SCALAR_VALUE ||
10827 			    !state_reg->precise ||
10828 			    !(state_reg->live & REG_LIVE_READ))
10829 				continue;
10830 			if (env->log.level & BPF_LOG_LEVEL2)
10831 				verbose(env, "frame %d: propagating fp%d\n",
10832 					fr, (-i - 1) * BPF_REG_SIZE);
10833 			err = mark_chain_precision_stack_frame(env, fr, i);
10834 			if (err < 0)
10835 				return err;
10836 		}
10837 	}
10838 	return 0;
10839 }
10840 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)10841 static bool states_maybe_looping(struct bpf_verifier_state *old,
10842 				 struct bpf_verifier_state *cur)
10843 {
10844 	struct bpf_func_state *fold, *fcur;
10845 	int i, fr = cur->curframe;
10846 
10847 	if (old->curframe != fr)
10848 		return false;
10849 
10850 	fold = old->frame[fr];
10851 	fcur = cur->frame[fr];
10852 	for (i = 0; i < MAX_BPF_REG; i++)
10853 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10854 			   offsetof(struct bpf_reg_state, parent)))
10855 			return false;
10856 	return true;
10857 }
10858 
10859 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)10860 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10861 {
10862 	struct bpf_verifier_state_list *new_sl;
10863 	struct bpf_verifier_state_list *sl, **pprev;
10864 	struct bpf_verifier_state *cur = env->cur_state, *new;
10865 	int i, j, err, states_cnt = 0;
10866 	bool add_new_state = env->test_state_freq ? true : false;
10867 
10868 	cur->last_insn_idx = env->prev_insn_idx;
10869 	if (!env->insn_aux_data[insn_idx].prune_point)
10870 		/* this 'insn_idx' instruction wasn't marked, so we will not
10871 		 * be doing state search here
10872 		 */
10873 		return 0;
10874 
10875 	/* bpf progs typically have pruning point every 4 instructions
10876 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10877 	 * Do not add new state for future pruning if the verifier hasn't seen
10878 	 * at least 2 jumps and at least 8 instructions.
10879 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10880 	 * In tests that amounts to up to 50% reduction into total verifier
10881 	 * memory consumption and 20% verifier time speedup.
10882 	 */
10883 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10884 	    env->insn_processed - env->prev_insn_processed >= 8)
10885 		add_new_state = true;
10886 
10887 	pprev = explored_state(env, insn_idx);
10888 	sl = *pprev;
10889 
10890 	clean_live_states(env, insn_idx, cur);
10891 
10892 	while (sl) {
10893 		states_cnt++;
10894 		if (sl->state.insn_idx != insn_idx)
10895 			goto next;
10896 
10897 		if (sl->state.branches) {
10898 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10899 
10900 			if (frame->in_async_callback_fn &&
10901 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10902 				/* Different async_entry_cnt means that the verifier is
10903 				 * processing another entry into async callback.
10904 				 * Seeing the same state is not an indication of infinite
10905 				 * loop or infinite recursion.
10906 				 * But finding the same state doesn't mean that it's safe
10907 				 * to stop processing the current state. The previous state
10908 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10909 				 * Checking in_async_callback_fn alone is not enough either.
10910 				 * Since the verifier still needs to catch infinite loops
10911 				 * inside async callbacks.
10912 				 */
10913 			} else if (states_maybe_looping(&sl->state, cur) &&
10914 				   states_equal(env, &sl->state, cur)) {
10915 				verbose_linfo(env, insn_idx, "; ");
10916 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10917 				return -EINVAL;
10918 			}
10919 			/* if the verifier is processing a loop, avoid adding new state
10920 			 * too often, since different loop iterations have distinct
10921 			 * states and may not help future pruning.
10922 			 * This threshold shouldn't be too low to make sure that
10923 			 * a loop with large bound will be rejected quickly.
10924 			 * The most abusive loop will be:
10925 			 * r1 += 1
10926 			 * if r1 < 1000000 goto pc-2
10927 			 * 1M insn_procssed limit / 100 == 10k peak states.
10928 			 * This threshold shouldn't be too high either, since states
10929 			 * at the end of the loop are likely to be useful in pruning.
10930 			 */
10931 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10932 			    env->insn_processed - env->prev_insn_processed < 100)
10933 				add_new_state = false;
10934 			goto miss;
10935 		}
10936 		if (states_equal(env, &sl->state, cur)) {
10937 			sl->hit_cnt++;
10938 			/* reached equivalent register/stack state,
10939 			 * prune the search.
10940 			 * Registers read by the continuation are read by us.
10941 			 * If we have any write marks in env->cur_state, they
10942 			 * will prevent corresponding reads in the continuation
10943 			 * from reaching our parent (an explored_state).  Our
10944 			 * own state will get the read marks recorded, but
10945 			 * they'll be immediately forgotten as we're pruning
10946 			 * this state and will pop a new one.
10947 			 */
10948 			err = propagate_liveness(env, &sl->state, cur);
10949 
10950 			/* if previous state reached the exit with precision and
10951 			 * current state is equivalent to it (except precsion marks)
10952 			 * the precision needs to be propagated back in
10953 			 * the current state.
10954 			 */
10955 			err = err ? : push_jmp_history(env, cur);
10956 			err = err ? : propagate_precision(env, &sl->state);
10957 			if (err)
10958 				return err;
10959 			return 1;
10960 		}
10961 miss:
10962 		/* when new state is not going to be added do not increase miss count.
10963 		 * Otherwise several loop iterations will remove the state
10964 		 * recorded earlier. The goal of these heuristics is to have
10965 		 * states from some iterations of the loop (some in the beginning
10966 		 * and some at the end) to help pruning.
10967 		 */
10968 		if (add_new_state)
10969 			sl->miss_cnt++;
10970 		/* heuristic to determine whether this state is beneficial
10971 		 * to keep checking from state equivalence point of view.
10972 		 * Higher numbers increase max_states_per_insn and verification time,
10973 		 * but do not meaningfully decrease insn_processed.
10974 		 */
10975 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10976 			/* the state is unlikely to be useful. Remove it to
10977 			 * speed up verification
10978 			 */
10979 			*pprev = sl->next;
10980 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10981 				u32 br = sl->state.branches;
10982 
10983 				WARN_ONCE(br,
10984 					  "BUG live_done but branches_to_explore %d\n",
10985 					  br);
10986 				free_verifier_state(&sl->state, false);
10987 				kfree(sl);
10988 				env->peak_states--;
10989 			} else {
10990 				/* cannot free this state, since parentage chain may
10991 				 * walk it later. Add it for free_list instead to
10992 				 * be freed at the end of verification
10993 				 */
10994 				sl->next = env->free_list;
10995 				env->free_list = sl;
10996 			}
10997 			sl = *pprev;
10998 			continue;
10999 		}
11000 next:
11001 		pprev = &sl->next;
11002 		sl = *pprev;
11003 	}
11004 
11005 	if (env->max_states_per_insn < states_cnt)
11006 		env->max_states_per_insn = states_cnt;
11007 
11008 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11009 		return push_jmp_history(env, cur);
11010 
11011 	if (!add_new_state)
11012 		return push_jmp_history(env, cur);
11013 
11014 	/* There were no equivalent states, remember the current one.
11015 	 * Technically the current state is not proven to be safe yet,
11016 	 * but it will either reach outer most bpf_exit (which means it's safe)
11017 	 * or it will be rejected. When there are no loops the verifier won't be
11018 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11019 	 * again on the way to bpf_exit.
11020 	 * When looping the sl->state.branches will be > 0 and this state
11021 	 * will not be considered for equivalence until branches == 0.
11022 	 */
11023 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11024 	if (!new_sl)
11025 		return -ENOMEM;
11026 	env->total_states++;
11027 	env->peak_states++;
11028 	env->prev_jmps_processed = env->jmps_processed;
11029 	env->prev_insn_processed = env->insn_processed;
11030 
11031 	/* forget precise markings we inherited, see __mark_chain_precision */
11032 	if (env->bpf_capable)
11033 		mark_all_scalars_imprecise(env, cur);
11034 
11035 	/* add new state to the head of linked list */
11036 	new = &new_sl->state;
11037 	err = copy_verifier_state(new, cur);
11038 	if (err) {
11039 		free_verifier_state(new, false);
11040 		kfree(new_sl);
11041 		return err;
11042 	}
11043 	new->insn_idx = insn_idx;
11044 	WARN_ONCE(new->branches != 1,
11045 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11046 
11047 	cur->parent = new;
11048 	cur->first_insn_idx = insn_idx;
11049 	clear_jmp_history(cur);
11050 	new_sl->next = *explored_state(env, insn_idx);
11051 	*explored_state(env, insn_idx) = new_sl;
11052 	/* connect new state to parentage chain. Current frame needs all
11053 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
11054 	 * to the stack implicitly by JITs) so in callers' frames connect just
11055 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11056 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11057 	 * from callee with its full parentage chain, anyway.
11058 	 */
11059 	/* clear write marks in current state: the writes we did are not writes
11060 	 * our child did, so they don't screen off its reads from us.
11061 	 * (There are no read marks in current state, because reads always mark
11062 	 * their parent and current state never has children yet.  Only
11063 	 * explored_states can get read marks.)
11064 	 */
11065 	for (j = 0; j <= cur->curframe; j++) {
11066 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11067 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11068 		for (i = 0; i < BPF_REG_FP; i++)
11069 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11070 	}
11071 
11072 	/* all stack frames are accessible from callee, clear them all */
11073 	for (j = 0; j <= cur->curframe; j++) {
11074 		struct bpf_func_state *frame = cur->frame[j];
11075 		struct bpf_func_state *newframe = new->frame[j];
11076 
11077 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11078 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11079 			frame->stack[i].spilled_ptr.parent =
11080 						&newframe->stack[i].spilled_ptr;
11081 		}
11082 	}
11083 	return 0;
11084 }
11085 
11086 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)11087 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11088 {
11089 	switch (base_type(type)) {
11090 	case PTR_TO_CTX:
11091 	case PTR_TO_SOCKET:
11092 	case PTR_TO_SOCK_COMMON:
11093 	case PTR_TO_TCP_SOCK:
11094 	case PTR_TO_XDP_SOCK:
11095 	case PTR_TO_BTF_ID:
11096 		return false;
11097 	default:
11098 		return true;
11099 	}
11100 }
11101 
11102 /* If an instruction was previously used with particular pointer types, then we
11103  * need to be careful to avoid cases such as the below, where it may be ok
11104  * for one branch accessing the pointer, but not ok for the other branch:
11105  *
11106  * R1 = sock_ptr
11107  * goto X;
11108  * ...
11109  * R1 = some_other_valid_ptr;
11110  * goto X;
11111  * ...
11112  * R2 = *(u32 *)(R1 + 0);
11113  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)11114 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11115 {
11116 	return src != prev && (!reg_type_mismatch_ok(src) ||
11117 			       !reg_type_mismatch_ok(prev));
11118 }
11119 
do_check(struct bpf_verifier_env * env)11120 static int do_check(struct bpf_verifier_env *env)
11121 {
11122 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11123 	struct bpf_verifier_state *state = env->cur_state;
11124 	struct bpf_insn *insns = env->prog->insnsi;
11125 	struct bpf_reg_state *regs;
11126 	int insn_cnt = env->prog->len;
11127 	bool do_print_state = false;
11128 	int prev_insn_idx = -1;
11129 
11130 	for (;;) {
11131 		struct bpf_insn *insn;
11132 		u8 class;
11133 		int err;
11134 
11135 		env->prev_insn_idx = prev_insn_idx;
11136 		if (env->insn_idx >= insn_cnt) {
11137 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11138 				env->insn_idx, insn_cnt);
11139 			return -EFAULT;
11140 		}
11141 
11142 		insn = &insns[env->insn_idx];
11143 		class = BPF_CLASS(insn->code);
11144 
11145 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11146 			verbose(env,
11147 				"BPF program is too large. Processed %d insn\n",
11148 				env->insn_processed);
11149 			return -E2BIG;
11150 		}
11151 
11152 		err = is_state_visited(env, env->insn_idx);
11153 		if (err < 0)
11154 			return err;
11155 		if (err == 1) {
11156 			/* found equivalent state, can prune the search */
11157 			if (env->log.level & BPF_LOG_LEVEL) {
11158 				if (do_print_state)
11159 					verbose(env, "\nfrom %d to %d%s: safe\n",
11160 						env->prev_insn_idx, env->insn_idx,
11161 						env->cur_state->speculative ?
11162 						" (speculative execution)" : "");
11163 				else
11164 					verbose(env, "%d: safe\n", env->insn_idx);
11165 			}
11166 			goto process_bpf_exit;
11167 		}
11168 
11169 		if (signal_pending(current))
11170 			return -EAGAIN;
11171 
11172 		if (need_resched())
11173 			cond_resched();
11174 
11175 		if (env->log.level & BPF_LOG_LEVEL2 ||
11176 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
11177 			if (env->log.level & BPF_LOG_LEVEL2)
11178 				verbose(env, "%d:", env->insn_idx);
11179 			else
11180 				verbose(env, "\nfrom %d to %d%s:",
11181 					env->prev_insn_idx, env->insn_idx,
11182 					env->cur_state->speculative ?
11183 					" (speculative execution)" : "");
11184 			print_verifier_state(env, state->frame[state->curframe]);
11185 			do_print_state = false;
11186 		}
11187 
11188 		if (env->log.level & BPF_LOG_LEVEL) {
11189 			const struct bpf_insn_cbs cbs = {
11190 				.cb_call	= disasm_kfunc_name,
11191 				.cb_print	= verbose,
11192 				.private_data	= env,
11193 			};
11194 
11195 			verbose_linfo(env, env->insn_idx, "; ");
11196 			verbose(env, "%d: ", env->insn_idx);
11197 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11198 		}
11199 
11200 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11201 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11202 							   env->prev_insn_idx);
11203 			if (err)
11204 				return err;
11205 		}
11206 
11207 		regs = cur_regs(env);
11208 		sanitize_mark_insn_seen(env);
11209 		prev_insn_idx = env->insn_idx;
11210 
11211 		if (class == BPF_ALU || class == BPF_ALU64) {
11212 			err = check_alu_op(env, insn);
11213 			if (err)
11214 				return err;
11215 
11216 		} else if (class == BPF_LDX) {
11217 			enum bpf_reg_type *prev_src_type, src_reg_type;
11218 
11219 			/* check for reserved fields is already done */
11220 
11221 			/* check src operand */
11222 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11223 			if (err)
11224 				return err;
11225 
11226 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11227 			if (err)
11228 				return err;
11229 
11230 			src_reg_type = regs[insn->src_reg].type;
11231 
11232 			/* check that memory (src_reg + off) is readable,
11233 			 * the state of dst_reg will be updated by this func
11234 			 */
11235 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11236 					       insn->off, BPF_SIZE(insn->code),
11237 					       BPF_READ, insn->dst_reg, false);
11238 			if (err)
11239 				return err;
11240 
11241 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11242 
11243 			if (*prev_src_type == NOT_INIT) {
11244 				/* saw a valid insn
11245 				 * dst_reg = *(u32 *)(src_reg + off)
11246 				 * save type to validate intersecting paths
11247 				 */
11248 				*prev_src_type = src_reg_type;
11249 
11250 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11251 				/* ABuser program is trying to use the same insn
11252 				 * dst_reg = *(u32*) (src_reg + off)
11253 				 * with different pointer types:
11254 				 * src_reg == ctx in one branch and
11255 				 * src_reg == stack|map in some other branch.
11256 				 * Reject it.
11257 				 */
11258 				verbose(env, "same insn cannot be used with different pointers\n");
11259 				return -EINVAL;
11260 			}
11261 
11262 		} else if (class == BPF_STX) {
11263 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11264 
11265 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11266 				err = check_atomic(env, env->insn_idx, insn);
11267 				if (err)
11268 					return err;
11269 				env->insn_idx++;
11270 				continue;
11271 			}
11272 
11273 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11274 				verbose(env, "BPF_STX uses reserved fields\n");
11275 				return -EINVAL;
11276 			}
11277 
11278 			/* check src1 operand */
11279 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11280 			if (err)
11281 				return err;
11282 			/* check src2 operand */
11283 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11284 			if (err)
11285 				return err;
11286 
11287 			dst_reg_type = regs[insn->dst_reg].type;
11288 
11289 			/* check that memory (dst_reg + off) is writeable */
11290 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11291 					       insn->off, BPF_SIZE(insn->code),
11292 					       BPF_WRITE, insn->src_reg, false);
11293 			if (err)
11294 				return err;
11295 
11296 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11297 
11298 			if (*prev_dst_type == NOT_INIT) {
11299 				*prev_dst_type = dst_reg_type;
11300 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11301 				verbose(env, "same insn cannot be used with different pointers\n");
11302 				return -EINVAL;
11303 			}
11304 
11305 		} else if (class == BPF_ST) {
11306 			if (BPF_MODE(insn->code) != BPF_MEM ||
11307 			    insn->src_reg != BPF_REG_0) {
11308 				verbose(env, "BPF_ST uses reserved fields\n");
11309 				return -EINVAL;
11310 			}
11311 			/* check src operand */
11312 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11313 			if (err)
11314 				return err;
11315 
11316 			if (is_ctx_reg(env, insn->dst_reg)) {
11317 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11318 					insn->dst_reg,
11319 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
11320 				return -EACCES;
11321 			}
11322 
11323 			/* check that memory (dst_reg + off) is writeable */
11324 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11325 					       insn->off, BPF_SIZE(insn->code),
11326 					       BPF_WRITE, -1, false);
11327 			if (err)
11328 				return err;
11329 
11330 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11331 			u8 opcode = BPF_OP(insn->code);
11332 
11333 			env->jmps_processed++;
11334 			if (opcode == BPF_CALL) {
11335 				if (BPF_SRC(insn->code) != BPF_K ||
11336 				    insn->off != 0 ||
11337 				    (insn->src_reg != BPF_REG_0 &&
11338 				     insn->src_reg != BPF_PSEUDO_CALL &&
11339 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11340 				    insn->dst_reg != BPF_REG_0 ||
11341 				    class == BPF_JMP32) {
11342 					verbose(env, "BPF_CALL uses reserved fields\n");
11343 					return -EINVAL;
11344 				}
11345 
11346 				if (env->cur_state->active_spin_lock &&
11347 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11348 				     insn->imm != BPF_FUNC_spin_unlock)) {
11349 					verbose(env, "function calls are not allowed while holding a lock\n");
11350 					return -EINVAL;
11351 				}
11352 				if (insn->src_reg == BPF_PSEUDO_CALL)
11353 					err = check_func_call(env, insn, &env->insn_idx);
11354 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11355 					err = check_kfunc_call(env, insn);
11356 				else
11357 					err = check_helper_call(env, insn, &env->insn_idx);
11358 				if (err)
11359 					return err;
11360 			} else if (opcode == BPF_JA) {
11361 				if (BPF_SRC(insn->code) != BPF_K ||
11362 				    insn->imm != 0 ||
11363 				    insn->src_reg != BPF_REG_0 ||
11364 				    insn->dst_reg != BPF_REG_0 ||
11365 				    class == BPF_JMP32) {
11366 					verbose(env, "BPF_JA uses reserved fields\n");
11367 					return -EINVAL;
11368 				}
11369 
11370 				env->insn_idx += insn->off + 1;
11371 				continue;
11372 
11373 			} else if (opcode == BPF_EXIT) {
11374 				if (BPF_SRC(insn->code) != BPF_K ||
11375 				    insn->imm != 0 ||
11376 				    insn->src_reg != BPF_REG_0 ||
11377 				    insn->dst_reg != BPF_REG_0 ||
11378 				    class == BPF_JMP32) {
11379 					verbose(env, "BPF_EXIT uses reserved fields\n");
11380 					return -EINVAL;
11381 				}
11382 
11383 				if (env->cur_state->active_spin_lock) {
11384 					verbose(env, "bpf_spin_unlock is missing\n");
11385 					return -EINVAL;
11386 				}
11387 
11388 				/* We must do check_reference_leak here before
11389 				 * prepare_func_exit to handle the case when
11390 				 * state->curframe > 0, it may be a callback
11391 				 * function, for which reference_state must
11392 				 * match caller reference state when it exits.
11393 				 */
11394 				err = check_reference_leak(env);
11395 				if (err)
11396 					return err;
11397 
11398 				if (state->curframe) {
11399 					/* exit from nested function */
11400 					err = prepare_func_exit(env, &env->insn_idx);
11401 					if (err)
11402 						return err;
11403 					do_print_state = true;
11404 					continue;
11405 				}
11406 
11407 				err = check_return_code(env);
11408 				if (err)
11409 					return err;
11410 process_bpf_exit:
11411 				update_branch_counts(env, env->cur_state);
11412 				err = pop_stack(env, &prev_insn_idx,
11413 						&env->insn_idx, pop_log);
11414 				if (err < 0) {
11415 					if (err != -ENOENT)
11416 						return err;
11417 					break;
11418 				} else {
11419 					do_print_state = true;
11420 					continue;
11421 				}
11422 			} else {
11423 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11424 				if (err)
11425 					return err;
11426 			}
11427 		} else if (class == BPF_LD) {
11428 			u8 mode = BPF_MODE(insn->code);
11429 
11430 			if (mode == BPF_ABS || mode == BPF_IND) {
11431 				err = check_ld_abs(env, insn);
11432 				if (err)
11433 					return err;
11434 
11435 			} else if (mode == BPF_IMM) {
11436 				err = check_ld_imm(env, insn);
11437 				if (err)
11438 					return err;
11439 
11440 				env->insn_idx++;
11441 				sanitize_mark_insn_seen(env);
11442 			} else {
11443 				verbose(env, "invalid BPF_LD mode\n");
11444 				return -EINVAL;
11445 			}
11446 		} else {
11447 			verbose(env, "unknown insn class %d\n", class);
11448 			return -EINVAL;
11449 		}
11450 
11451 		env->insn_idx++;
11452 	}
11453 
11454 	return 0;
11455 }
11456 
find_btf_percpu_datasec(struct btf * btf)11457 static int find_btf_percpu_datasec(struct btf *btf)
11458 {
11459 	const struct btf_type *t;
11460 	const char *tname;
11461 	int i, n;
11462 
11463 	/*
11464 	 * Both vmlinux and module each have their own ".data..percpu"
11465 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11466 	 * types to look at only module's own BTF types.
11467 	 */
11468 	n = btf_nr_types(btf);
11469 	if (btf_is_module(btf))
11470 		i = btf_nr_types(btf_vmlinux);
11471 	else
11472 		i = 1;
11473 
11474 	for(; i < n; i++) {
11475 		t = btf_type_by_id(btf, i);
11476 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11477 			continue;
11478 
11479 		tname = btf_name_by_offset(btf, t->name_off);
11480 		if (!strcmp(tname, ".data..percpu"))
11481 			return i;
11482 	}
11483 
11484 	return -ENOENT;
11485 }
11486 
11487 /* 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)11488 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11489 			       struct bpf_insn *insn,
11490 			       struct bpf_insn_aux_data *aux)
11491 {
11492 	const struct btf_var_secinfo *vsi;
11493 	const struct btf_type *datasec;
11494 	struct btf_mod_pair *btf_mod;
11495 	const struct btf_type *t;
11496 	const char *sym_name;
11497 	bool percpu = false;
11498 	u32 type, id = insn->imm;
11499 	struct btf *btf;
11500 	s32 datasec_id;
11501 	u64 addr;
11502 	int i, btf_fd, err;
11503 
11504 	btf_fd = insn[1].imm;
11505 	if (btf_fd) {
11506 		btf = btf_get_by_fd(btf_fd);
11507 		if (IS_ERR(btf)) {
11508 			verbose(env, "invalid module BTF object FD specified.\n");
11509 			return -EINVAL;
11510 		}
11511 	} else {
11512 		if (!btf_vmlinux) {
11513 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11514 			return -EINVAL;
11515 		}
11516 		btf = btf_vmlinux;
11517 		btf_get(btf);
11518 	}
11519 
11520 	t = btf_type_by_id(btf, id);
11521 	if (!t) {
11522 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11523 		err = -ENOENT;
11524 		goto err_put;
11525 	}
11526 
11527 	if (!btf_type_is_var(t)) {
11528 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11529 		err = -EINVAL;
11530 		goto err_put;
11531 	}
11532 
11533 	sym_name = btf_name_by_offset(btf, t->name_off);
11534 	addr = kallsyms_lookup_name(sym_name);
11535 	if (!addr) {
11536 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11537 			sym_name);
11538 		err = -ENOENT;
11539 		goto err_put;
11540 	}
11541 
11542 	datasec_id = find_btf_percpu_datasec(btf);
11543 	if (datasec_id > 0) {
11544 		datasec = btf_type_by_id(btf, datasec_id);
11545 		for_each_vsi(i, datasec, vsi) {
11546 			if (vsi->type == id) {
11547 				percpu = true;
11548 				break;
11549 			}
11550 		}
11551 	}
11552 
11553 	insn[0].imm = (u32)addr;
11554 	insn[1].imm = addr >> 32;
11555 
11556 	type = t->type;
11557 	t = btf_type_skip_modifiers(btf, type, NULL);
11558 	if (percpu) {
11559 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11560 		aux->btf_var.btf = btf;
11561 		aux->btf_var.btf_id = type;
11562 	} else if (!btf_type_is_struct(t)) {
11563 		const struct btf_type *ret;
11564 		const char *tname;
11565 		u32 tsize;
11566 
11567 		/* resolve the type size of ksym. */
11568 		ret = btf_resolve_size(btf, t, &tsize);
11569 		if (IS_ERR(ret)) {
11570 			tname = btf_name_by_offset(btf, t->name_off);
11571 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11572 				tname, PTR_ERR(ret));
11573 			err = -EINVAL;
11574 			goto err_put;
11575 		}
11576 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
11577 		aux->btf_var.mem_size = tsize;
11578 	} else {
11579 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11580 		aux->btf_var.btf = btf;
11581 		aux->btf_var.btf_id = type;
11582 	}
11583 
11584 	/* check whether we recorded this BTF (and maybe module) already */
11585 	for (i = 0; i < env->used_btf_cnt; i++) {
11586 		if (env->used_btfs[i].btf == btf) {
11587 			btf_put(btf);
11588 			return 0;
11589 		}
11590 	}
11591 
11592 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11593 		err = -E2BIG;
11594 		goto err_put;
11595 	}
11596 
11597 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11598 	btf_mod->btf = btf;
11599 	btf_mod->module = NULL;
11600 
11601 	/* if we reference variables from kernel module, bump its refcount */
11602 	if (btf_is_module(btf)) {
11603 		btf_mod->module = btf_try_get_module(btf);
11604 		if (!btf_mod->module) {
11605 			err = -ENXIO;
11606 			goto err_put;
11607 		}
11608 	}
11609 
11610 	env->used_btf_cnt++;
11611 
11612 	return 0;
11613 err_put:
11614 	btf_put(btf);
11615 	return err;
11616 }
11617 
check_map_prealloc(struct bpf_map * map)11618 static int check_map_prealloc(struct bpf_map *map)
11619 {
11620 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11621 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11622 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11623 		!(map->map_flags & BPF_F_NO_PREALLOC);
11624 }
11625 
is_tracing_prog_type(enum bpf_prog_type type)11626 static bool is_tracing_prog_type(enum bpf_prog_type type)
11627 {
11628 	switch (type) {
11629 	case BPF_PROG_TYPE_KPROBE:
11630 	case BPF_PROG_TYPE_TRACEPOINT:
11631 	case BPF_PROG_TYPE_PERF_EVENT:
11632 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11633 		return true;
11634 	default:
11635 		return false;
11636 	}
11637 }
11638 
is_preallocated_map(struct bpf_map * map)11639 static bool is_preallocated_map(struct bpf_map *map)
11640 {
11641 	if (!check_map_prealloc(map))
11642 		return false;
11643 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11644 		return false;
11645 	return true;
11646 }
11647 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)11648 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11649 					struct bpf_map *map,
11650 					struct bpf_prog *prog)
11651 
11652 {
11653 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11654 	/*
11655 	 * Validate that trace type programs use preallocated hash maps.
11656 	 *
11657 	 * For programs attached to PERF events this is mandatory as the
11658 	 * perf NMI can hit any arbitrary code sequence.
11659 	 *
11660 	 * All other trace types using preallocated hash maps are unsafe as
11661 	 * well because tracepoint or kprobes can be inside locked regions
11662 	 * of the memory allocator or at a place where a recursion into the
11663 	 * memory allocator would see inconsistent state.
11664 	 *
11665 	 * On RT enabled kernels run-time allocation of all trace type
11666 	 * programs is strictly prohibited due to lock type constraints. On
11667 	 * !RT kernels it is allowed for backwards compatibility reasons for
11668 	 * now, but warnings are emitted so developers are made aware of
11669 	 * the unsafety and can fix their programs before this is enforced.
11670 	 */
11671 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11672 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11673 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11674 			return -EINVAL;
11675 		}
11676 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11677 			verbose(env, "trace type programs can only use preallocated hash map\n");
11678 			return -EINVAL;
11679 		}
11680 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11681 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11682 	}
11683 
11684 	if (map_value_has_spin_lock(map)) {
11685 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11686 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11687 			return -EINVAL;
11688 		}
11689 
11690 		if (is_tracing_prog_type(prog_type)) {
11691 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11692 			return -EINVAL;
11693 		}
11694 
11695 		if (prog->aux->sleepable) {
11696 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11697 			return -EINVAL;
11698 		}
11699 	}
11700 
11701 	if (map_value_has_timer(map)) {
11702 		if (is_tracing_prog_type(prog_type)) {
11703 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
11704 			return -EINVAL;
11705 		}
11706 	}
11707 
11708 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11709 	    !bpf_offload_prog_map_match(prog, map)) {
11710 		verbose(env, "offload device mismatch between prog and map\n");
11711 		return -EINVAL;
11712 	}
11713 
11714 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11715 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11716 		return -EINVAL;
11717 	}
11718 
11719 	if (prog->aux->sleepable)
11720 		switch (map->map_type) {
11721 		case BPF_MAP_TYPE_HASH:
11722 		case BPF_MAP_TYPE_LRU_HASH:
11723 		case BPF_MAP_TYPE_ARRAY:
11724 		case BPF_MAP_TYPE_PERCPU_HASH:
11725 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11726 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11727 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11728 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11729 			if (!is_preallocated_map(map)) {
11730 				verbose(env,
11731 					"Sleepable programs can only use preallocated maps\n");
11732 				return -EINVAL;
11733 			}
11734 			break;
11735 		case BPF_MAP_TYPE_RINGBUF:
11736 			break;
11737 		default:
11738 			verbose(env,
11739 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11740 			return -EINVAL;
11741 		}
11742 
11743 	return 0;
11744 }
11745 
bpf_map_is_cgroup_storage(struct bpf_map * map)11746 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11747 {
11748 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11749 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11750 }
11751 
11752 /* find and rewrite pseudo imm in ld_imm64 instructions:
11753  *
11754  * 1. if it accesses map FD, replace it with actual map pointer.
11755  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11756  *
11757  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11758  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)11759 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11760 {
11761 	struct bpf_insn *insn = env->prog->insnsi;
11762 	int insn_cnt = env->prog->len;
11763 	int i, j, err;
11764 
11765 	err = bpf_prog_calc_tag(env->prog);
11766 	if (err)
11767 		return err;
11768 
11769 	for (i = 0; i < insn_cnt; i++, insn++) {
11770 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11771 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11772 			verbose(env, "BPF_LDX uses reserved fields\n");
11773 			return -EINVAL;
11774 		}
11775 
11776 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11777 			struct bpf_insn_aux_data *aux;
11778 			struct bpf_map *map;
11779 			struct fd f;
11780 			u64 addr;
11781 			u32 fd;
11782 
11783 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11784 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11785 			    insn[1].off != 0) {
11786 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11787 				return -EINVAL;
11788 			}
11789 
11790 			if (insn[0].src_reg == 0)
11791 				/* valid generic load 64-bit imm */
11792 				goto next_insn;
11793 
11794 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11795 				aux = &env->insn_aux_data[i];
11796 				err = check_pseudo_btf_id(env, insn, aux);
11797 				if (err)
11798 					return err;
11799 				goto next_insn;
11800 			}
11801 
11802 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11803 				aux = &env->insn_aux_data[i];
11804 				aux->ptr_type = PTR_TO_FUNC;
11805 				goto next_insn;
11806 			}
11807 
11808 			/* In final convert_pseudo_ld_imm64() step, this is
11809 			 * converted into regular 64-bit imm load insn.
11810 			 */
11811 			switch (insn[0].src_reg) {
11812 			case BPF_PSEUDO_MAP_VALUE:
11813 			case BPF_PSEUDO_MAP_IDX_VALUE:
11814 				break;
11815 			case BPF_PSEUDO_MAP_FD:
11816 			case BPF_PSEUDO_MAP_IDX:
11817 				if (insn[1].imm == 0)
11818 					break;
11819 				fallthrough;
11820 			default:
11821 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11822 				return -EINVAL;
11823 			}
11824 
11825 			switch (insn[0].src_reg) {
11826 			case BPF_PSEUDO_MAP_IDX_VALUE:
11827 			case BPF_PSEUDO_MAP_IDX:
11828 				if (bpfptr_is_null(env->fd_array)) {
11829 					verbose(env, "fd_idx without fd_array is invalid\n");
11830 					return -EPROTO;
11831 				}
11832 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11833 							    insn[0].imm * sizeof(fd),
11834 							    sizeof(fd)))
11835 					return -EFAULT;
11836 				break;
11837 			default:
11838 				fd = insn[0].imm;
11839 				break;
11840 			}
11841 
11842 			f = fdget(fd);
11843 			map = __bpf_map_get(f);
11844 			if (IS_ERR(map)) {
11845 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11846 					insn[0].imm);
11847 				return PTR_ERR(map);
11848 			}
11849 
11850 			err = check_map_prog_compatibility(env, map, env->prog);
11851 			if (err) {
11852 				fdput(f);
11853 				return err;
11854 			}
11855 
11856 			aux = &env->insn_aux_data[i];
11857 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11858 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11859 				addr = (unsigned long)map;
11860 			} else {
11861 				u32 off = insn[1].imm;
11862 
11863 				if (off >= BPF_MAX_VAR_OFF) {
11864 					verbose(env, "direct value offset of %u is not allowed\n", off);
11865 					fdput(f);
11866 					return -EINVAL;
11867 				}
11868 
11869 				if (!map->ops->map_direct_value_addr) {
11870 					verbose(env, "no direct value access support for this map type\n");
11871 					fdput(f);
11872 					return -EINVAL;
11873 				}
11874 
11875 				err = map->ops->map_direct_value_addr(map, &addr, off);
11876 				if (err) {
11877 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11878 						map->value_size, off);
11879 					fdput(f);
11880 					return err;
11881 				}
11882 
11883 				aux->map_off = off;
11884 				addr += off;
11885 			}
11886 
11887 			insn[0].imm = (u32)addr;
11888 			insn[1].imm = addr >> 32;
11889 
11890 			/* check whether we recorded this map already */
11891 			for (j = 0; j < env->used_map_cnt; j++) {
11892 				if (env->used_maps[j] == map) {
11893 					aux->map_index = j;
11894 					fdput(f);
11895 					goto next_insn;
11896 				}
11897 			}
11898 
11899 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11900 				fdput(f);
11901 				return -E2BIG;
11902 			}
11903 
11904 			/* hold the map. If the program is rejected by verifier,
11905 			 * the map will be released by release_maps() or it
11906 			 * will be used by the valid program until it's unloaded
11907 			 * and all maps are released in free_used_maps()
11908 			 */
11909 			bpf_map_inc(map);
11910 
11911 			aux->map_index = env->used_map_cnt;
11912 			env->used_maps[env->used_map_cnt++] = map;
11913 
11914 			if (bpf_map_is_cgroup_storage(map) &&
11915 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11916 				verbose(env, "only one cgroup storage of each type is allowed\n");
11917 				fdput(f);
11918 				return -EBUSY;
11919 			}
11920 
11921 			fdput(f);
11922 next_insn:
11923 			insn++;
11924 			i++;
11925 			continue;
11926 		}
11927 
11928 		/* Basic sanity check before we invest more work here. */
11929 		if (!bpf_opcode_in_insntable(insn->code)) {
11930 			verbose(env, "unknown opcode %02x\n", insn->code);
11931 			return -EINVAL;
11932 		}
11933 	}
11934 
11935 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11936 	 * 'struct bpf_map *' into a register instead of user map_fd.
11937 	 * These pointers will be used later by verifier to validate map access.
11938 	 */
11939 	return 0;
11940 }
11941 
11942 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)11943 static void release_maps(struct bpf_verifier_env *env)
11944 {
11945 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11946 			     env->used_map_cnt);
11947 }
11948 
11949 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)11950 static void release_btfs(struct bpf_verifier_env *env)
11951 {
11952 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11953 			     env->used_btf_cnt);
11954 }
11955 
11956 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)11957 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11958 {
11959 	struct bpf_insn *insn = env->prog->insnsi;
11960 	int insn_cnt = env->prog->len;
11961 	int i;
11962 
11963 	for (i = 0; i < insn_cnt; i++, insn++) {
11964 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11965 			continue;
11966 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11967 			continue;
11968 		insn->src_reg = 0;
11969 	}
11970 }
11971 
11972 /* single env->prog->insni[off] instruction was replaced with the range
11973  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11974  * [0, off) and [off, end) to new locations, so the patched range stays zero
11975  */
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)11976 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11977 				 struct bpf_insn_aux_data *new_data,
11978 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11979 {
11980 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11981 	struct bpf_insn *insn = new_prog->insnsi;
11982 	u32 old_seen = old_data[off].seen;
11983 	u32 prog_len;
11984 	int i;
11985 
11986 	/* aux info at OFF always needs adjustment, no matter fast path
11987 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11988 	 * original insn at old prog.
11989 	 */
11990 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11991 
11992 	if (cnt == 1)
11993 		return;
11994 	prog_len = new_prog->len;
11995 
11996 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11997 	memcpy(new_data + off + cnt - 1, old_data + off,
11998 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11999 	for (i = off; i < off + cnt - 1; i++) {
12000 		/* Expand insni[off]'s seen count to the patched range. */
12001 		new_data[i].seen = old_seen;
12002 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
12003 	}
12004 	env->insn_aux_data = new_data;
12005 	vfree(old_data);
12006 }
12007 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)12008 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12009 {
12010 	int i;
12011 
12012 	if (len == 1)
12013 		return;
12014 	/* NOTE: fake 'exit' subprog should be updated as well. */
12015 	for (i = 0; i <= env->subprog_cnt; i++) {
12016 		if (env->subprog_info[i].start <= off)
12017 			continue;
12018 		env->subprog_info[i].start += len - 1;
12019 	}
12020 }
12021 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)12022 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12023 {
12024 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12025 	int i, sz = prog->aux->size_poke_tab;
12026 	struct bpf_jit_poke_descriptor *desc;
12027 
12028 	for (i = 0; i < sz; i++) {
12029 		desc = &tab[i];
12030 		if (desc->insn_idx <= off)
12031 			continue;
12032 		desc->insn_idx += len - 1;
12033 	}
12034 }
12035 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)12036 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12037 					    const struct bpf_insn *patch, u32 len)
12038 {
12039 	struct bpf_prog *new_prog;
12040 	struct bpf_insn_aux_data *new_data = NULL;
12041 
12042 	if (len > 1) {
12043 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12044 					      sizeof(struct bpf_insn_aux_data)));
12045 		if (!new_data)
12046 			return NULL;
12047 	}
12048 
12049 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12050 	if (IS_ERR(new_prog)) {
12051 		if (PTR_ERR(new_prog) == -ERANGE)
12052 			verbose(env,
12053 				"insn %d cannot be patched due to 16-bit range\n",
12054 				env->insn_aux_data[off].orig_idx);
12055 		vfree(new_data);
12056 		return NULL;
12057 	}
12058 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12059 	adjust_subprog_starts(env, off, len);
12060 	adjust_poke_descs(new_prog, off, len);
12061 	return new_prog;
12062 }
12063 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)12064 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12065 					      u32 off, u32 cnt)
12066 {
12067 	int i, j;
12068 
12069 	/* find first prog starting at or after off (first to remove) */
12070 	for (i = 0; i < env->subprog_cnt; i++)
12071 		if (env->subprog_info[i].start >= off)
12072 			break;
12073 	/* find first prog starting at or after off + cnt (first to stay) */
12074 	for (j = i; j < env->subprog_cnt; j++)
12075 		if (env->subprog_info[j].start >= off + cnt)
12076 			break;
12077 	/* if j doesn't start exactly at off + cnt, we are just removing
12078 	 * the front of previous prog
12079 	 */
12080 	if (env->subprog_info[j].start != off + cnt)
12081 		j--;
12082 
12083 	if (j > i) {
12084 		struct bpf_prog_aux *aux = env->prog->aux;
12085 		int move;
12086 
12087 		/* move fake 'exit' subprog as well */
12088 		move = env->subprog_cnt + 1 - j;
12089 
12090 		memmove(env->subprog_info + i,
12091 			env->subprog_info + j,
12092 			sizeof(*env->subprog_info) * move);
12093 		env->subprog_cnt -= j - i;
12094 
12095 		/* remove func_info */
12096 		if (aux->func_info) {
12097 			move = aux->func_info_cnt - j;
12098 
12099 			memmove(aux->func_info + i,
12100 				aux->func_info + j,
12101 				sizeof(*aux->func_info) * move);
12102 			aux->func_info_cnt -= j - i;
12103 			/* func_info->insn_off is set after all code rewrites,
12104 			 * in adjust_btf_func() - no need to adjust
12105 			 */
12106 		}
12107 	} else {
12108 		/* convert i from "first prog to remove" to "first to adjust" */
12109 		if (env->subprog_info[i].start == off)
12110 			i++;
12111 	}
12112 
12113 	/* update fake 'exit' subprog as well */
12114 	for (; i <= env->subprog_cnt; i++)
12115 		env->subprog_info[i].start -= cnt;
12116 
12117 	return 0;
12118 }
12119 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)12120 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12121 				      u32 cnt)
12122 {
12123 	struct bpf_prog *prog = env->prog;
12124 	u32 i, l_off, l_cnt, nr_linfo;
12125 	struct bpf_line_info *linfo;
12126 
12127 	nr_linfo = prog->aux->nr_linfo;
12128 	if (!nr_linfo)
12129 		return 0;
12130 
12131 	linfo = prog->aux->linfo;
12132 
12133 	/* find first line info to remove, count lines to be removed */
12134 	for (i = 0; i < nr_linfo; i++)
12135 		if (linfo[i].insn_off >= off)
12136 			break;
12137 
12138 	l_off = i;
12139 	l_cnt = 0;
12140 	for (; i < nr_linfo; i++)
12141 		if (linfo[i].insn_off < off + cnt)
12142 			l_cnt++;
12143 		else
12144 			break;
12145 
12146 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12147 	 * last removed linfo.  prog is already modified, so prog->len == off
12148 	 * means no live instructions after (tail of the program was removed).
12149 	 */
12150 	if (prog->len != off && l_cnt &&
12151 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12152 		l_cnt--;
12153 		linfo[--i].insn_off = off + cnt;
12154 	}
12155 
12156 	/* remove the line info which refer to the removed instructions */
12157 	if (l_cnt) {
12158 		memmove(linfo + l_off, linfo + i,
12159 			sizeof(*linfo) * (nr_linfo - i));
12160 
12161 		prog->aux->nr_linfo -= l_cnt;
12162 		nr_linfo = prog->aux->nr_linfo;
12163 	}
12164 
12165 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12166 	for (i = l_off; i < nr_linfo; i++)
12167 		linfo[i].insn_off -= cnt;
12168 
12169 	/* fix up all subprogs (incl. 'exit') which start >= off */
12170 	for (i = 0; i <= env->subprog_cnt; i++)
12171 		if (env->subprog_info[i].linfo_idx > l_off) {
12172 			/* program may have started in the removed region but
12173 			 * may not be fully removed
12174 			 */
12175 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12176 				env->subprog_info[i].linfo_idx -= l_cnt;
12177 			else
12178 				env->subprog_info[i].linfo_idx = l_off;
12179 		}
12180 
12181 	return 0;
12182 }
12183 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)12184 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12185 {
12186 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12187 	unsigned int orig_prog_len = env->prog->len;
12188 	int err;
12189 
12190 	if (bpf_prog_is_dev_bound(env->prog->aux))
12191 		bpf_prog_offload_remove_insns(env, off, cnt);
12192 
12193 	err = bpf_remove_insns(env->prog, off, cnt);
12194 	if (err)
12195 		return err;
12196 
12197 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12198 	if (err)
12199 		return err;
12200 
12201 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12202 	if (err)
12203 		return err;
12204 
12205 	memmove(aux_data + off,	aux_data + off + cnt,
12206 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12207 
12208 	return 0;
12209 }
12210 
12211 /* The verifier does more data flow analysis than llvm and will not
12212  * explore branches that are dead at run time. Malicious programs can
12213  * have dead code too. Therefore replace all dead at-run-time code
12214  * with 'ja -1'.
12215  *
12216  * Just nops are not optimal, e.g. if they would sit at the end of the
12217  * program and through another bug we would manage to jump there, then
12218  * we'd execute beyond program memory otherwise. Returning exception
12219  * code also wouldn't work since we can have subprogs where the dead
12220  * code could be located.
12221  */
sanitize_dead_code(struct bpf_verifier_env * env)12222 static void sanitize_dead_code(struct bpf_verifier_env *env)
12223 {
12224 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12225 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12226 	struct bpf_insn *insn = env->prog->insnsi;
12227 	const int insn_cnt = env->prog->len;
12228 	int i;
12229 
12230 	for (i = 0; i < insn_cnt; i++) {
12231 		if (aux_data[i].seen)
12232 			continue;
12233 		memcpy(insn + i, &trap, sizeof(trap));
12234 		aux_data[i].zext_dst = false;
12235 	}
12236 }
12237 
insn_is_cond_jump(u8 code)12238 static bool insn_is_cond_jump(u8 code)
12239 {
12240 	u8 op;
12241 
12242 	if (BPF_CLASS(code) == BPF_JMP32)
12243 		return true;
12244 
12245 	if (BPF_CLASS(code) != BPF_JMP)
12246 		return false;
12247 
12248 	op = BPF_OP(code);
12249 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12250 }
12251 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)12252 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12253 {
12254 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12255 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12256 	struct bpf_insn *insn = env->prog->insnsi;
12257 	const int insn_cnt = env->prog->len;
12258 	int i;
12259 
12260 	for (i = 0; i < insn_cnt; i++, insn++) {
12261 		if (!insn_is_cond_jump(insn->code))
12262 			continue;
12263 
12264 		if (!aux_data[i + 1].seen)
12265 			ja.off = insn->off;
12266 		else if (!aux_data[i + 1 + insn->off].seen)
12267 			ja.off = 0;
12268 		else
12269 			continue;
12270 
12271 		if (bpf_prog_is_dev_bound(env->prog->aux))
12272 			bpf_prog_offload_replace_insn(env, i, &ja);
12273 
12274 		memcpy(insn, &ja, sizeof(ja));
12275 	}
12276 }
12277 
opt_remove_dead_code(struct bpf_verifier_env * env)12278 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12279 {
12280 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12281 	int insn_cnt = env->prog->len;
12282 	int i, err;
12283 
12284 	for (i = 0; i < insn_cnt; i++) {
12285 		int j;
12286 
12287 		j = 0;
12288 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12289 			j++;
12290 		if (!j)
12291 			continue;
12292 
12293 		err = verifier_remove_insns(env, i, j);
12294 		if (err)
12295 			return err;
12296 		insn_cnt = env->prog->len;
12297 	}
12298 
12299 	return 0;
12300 }
12301 
opt_remove_nops(struct bpf_verifier_env * env)12302 static int opt_remove_nops(struct bpf_verifier_env *env)
12303 {
12304 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12305 	struct bpf_insn *insn = env->prog->insnsi;
12306 	int insn_cnt = env->prog->len;
12307 	int i, err;
12308 
12309 	for (i = 0; i < insn_cnt; i++) {
12310 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12311 			continue;
12312 
12313 		err = verifier_remove_insns(env, i, 1);
12314 		if (err)
12315 			return err;
12316 		insn_cnt--;
12317 		i--;
12318 	}
12319 
12320 	return 0;
12321 }
12322 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)12323 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12324 					 const union bpf_attr *attr)
12325 {
12326 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12327 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12328 	int i, patch_len, delta = 0, len = env->prog->len;
12329 	struct bpf_insn *insns = env->prog->insnsi;
12330 	struct bpf_prog *new_prog;
12331 	bool rnd_hi32;
12332 
12333 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12334 	zext_patch[1] = BPF_ZEXT_REG(0);
12335 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12336 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12337 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12338 	for (i = 0; i < len; i++) {
12339 		int adj_idx = i + delta;
12340 		struct bpf_insn insn;
12341 		int load_reg;
12342 
12343 		insn = insns[adj_idx];
12344 		load_reg = insn_def_regno(&insn);
12345 		if (!aux[adj_idx].zext_dst) {
12346 			u8 code, class;
12347 			u32 imm_rnd;
12348 
12349 			if (!rnd_hi32)
12350 				continue;
12351 
12352 			code = insn.code;
12353 			class = BPF_CLASS(code);
12354 			if (load_reg == -1)
12355 				continue;
12356 
12357 			/* NOTE: arg "reg" (the fourth one) is only used for
12358 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12359 			 *       here.
12360 			 */
12361 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12362 				if (class == BPF_LD &&
12363 				    BPF_MODE(code) == BPF_IMM)
12364 					i++;
12365 				continue;
12366 			}
12367 
12368 			/* ctx load could be transformed into wider load. */
12369 			if (class == BPF_LDX &&
12370 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12371 				continue;
12372 
12373 			imm_rnd = get_random_int();
12374 			rnd_hi32_patch[0] = insn;
12375 			rnd_hi32_patch[1].imm = imm_rnd;
12376 			rnd_hi32_patch[3].dst_reg = load_reg;
12377 			patch = rnd_hi32_patch;
12378 			patch_len = 4;
12379 			goto apply_patch_buffer;
12380 		}
12381 
12382 		/* Add in an zero-extend instruction if a) the JIT has requested
12383 		 * it or b) it's a CMPXCHG.
12384 		 *
12385 		 * The latter is because: BPF_CMPXCHG always loads a value into
12386 		 * R0, therefore always zero-extends. However some archs'
12387 		 * equivalent instruction only does this load when the
12388 		 * comparison is successful. This detail of CMPXCHG is
12389 		 * orthogonal to the general zero-extension behaviour of the
12390 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12391 		 */
12392 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12393 			continue;
12394 
12395 		/* Zero-extension is done by the caller. */
12396 		if (bpf_pseudo_kfunc_call(&insn))
12397 			continue;
12398 
12399 		if (WARN_ON(load_reg == -1)) {
12400 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12401 			return -EFAULT;
12402 		}
12403 
12404 		zext_patch[0] = insn;
12405 		zext_patch[1].dst_reg = load_reg;
12406 		zext_patch[1].src_reg = load_reg;
12407 		patch = zext_patch;
12408 		patch_len = 2;
12409 apply_patch_buffer:
12410 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12411 		if (!new_prog)
12412 			return -ENOMEM;
12413 		env->prog = new_prog;
12414 		insns = new_prog->insnsi;
12415 		aux = env->insn_aux_data;
12416 		delta += patch_len - 1;
12417 	}
12418 
12419 	return 0;
12420 }
12421 
12422 /* convert load instructions that access fields of a context type into a
12423  * sequence of instructions that access fields of the underlying structure:
12424  *     struct __sk_buff    -> struct sk_buff
12425  *     struct bpf_sock_ops -> struct sock
12426  */
convert_ctx_accesses(struct bpf_verifier_env * env)12427 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12428 {
12429 	const struct bpf_verifier_ops *ops = env->ops;
12430 	int i, cnt, size, ctx_field_size, delta = 0;
12431 	const int insn_cnt = env->prog->len;
12432 	struct bpf_insn insn_buf[16], *insn;
12433 	u32 target_size, size_default, off;
12434 	struct bpf_prog *new_prog;
12435 	enum bpf_access_type type;
12436 	bool is_narrower_load;
12437 
12438 	if (ops->gen_prologue || env->seen_direct_write) {
12439 		if (!ops->gen_prologue) {
12440 			verbose(env, "bpf verifier is misconfigured\n");
12441 			return -EINVAL;
12442 		}
12443 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12444 					env->prog);
12445 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12446 			verbose(env, "bpf verifier is misconfigured\n");
12447 			return -EINVAL;
12448 		} else if (cnt) {
12449 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12450 			if (!new_prog)
12451 				return -ENOMEM;
12452 
12453 			env->prog = new_prog;
12454 			delta += cnt - 1;
12455 		}
12456 	}
12457 
12458 	if (bpf_prog_is_dev_bound(env->prog->aux))
12459 		return 0;
12460 
12461 	insn = env->prog->insnsi + delta;
12462 
12463 	for (i = 0; i < insn_cnt; i++, insn++) {
12464 		bpf_convert_ctx_access_t convert_ctx_access;
12465 		bool ctx_access;
12466 
12467 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12468 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12469 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12470 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12471 			type = BPF_READ;
12472 			ctx_access = true;
12473 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12474 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12475 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12476 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12477 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12478 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12479 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12480 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12481 			type = BPF_WRITE;
12482 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12483 		} else {
12484 			continue;
12485 		}
12486 
12487 		if (type == BPF_WRITE &&
12488 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12489 			struct bpf_insn patch[] = {
12490 				*insn,
12491 				BPF_ST_NOSPEC(),
12492 			};
12493 
12494 			cnt = ARRAY_SIZE(patch);
12495 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12496 			if (!new_prog)
12497 				return -ENOMEM;
12498 
12499 			delta    += cnt - 1;
12500 			env->prog = new_prog;
12501 			insn      = new_prog->insnsi + i + delta;
12502 			continue;
12503 		}
12504 
12505 		if (!ctx_access)
12506 			continue;
12507 
12508 		switch (env->insn_aux_data[i + delta].ptr_type) {
12509 		case PTR_TO_CTX:
12510 			if (!ops->convert_ctx_access)
12511 				continue;
12512 			convert_ctx_access = ops->convert_ctx_access;
12513 			break;
12514 		case PTR_TO_SOCKET:
12515 		case PTR_TO_SOCK_COMMON:
12516 			convert_ctx_access = bpf_sock_convert_ctx_access;
12517 			break;
12518 		case PTR_TO_TCP_SOCK:
12519 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12520 			break;
12521 		case PTR_TO_XDP_SOCK:
12522 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12523 			break;
12524 		case PTR_TO_BTF_ID:
12525 			if (type == BPF_READ) {
12526 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12527 					BPF_SIZE((insn)->code);
12528 				env->prog->aux->num_exentries++;
12529 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12530 				verbose(env, "Writes through BTF pointers are not allowed\n");
12531 				return -EINVAL;
12532 			}
12533 			continue;
12534 		default:
12535 			continue;
12536 		}
12537 
12538 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12539 		size = BPF_LDST_BYTES(insn);
12540 
12541 		/* If the read access is a narrower load of the field,
12542 		 * convert to a 4/8-byte load, to minimum program type specific
12543 		 * convert_ctx_access changes. If conversion is successful,
12544 		 * we will apply proper mask to the result.
12545 		 */
12546 		is_narrower_load = size < ctx_field_size;
12547 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12548 		off = insn->off;
12549 		if (is_narrower_load) {
12550 			u8 size_code;
12551 
12552 			if (type == BPF_WRITE) {
12553 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12554 				return -EINVAL;
12555 			}
12556 
12557 			size_code = BPF_H;
12558 			if (ctx_field_size == 4)
12559 				size_code = BPF_W;
12560 			else if (ctx_field_size == 8)
12561 				size_code = BPF_DW;
12562 
12563 			insn->off = off & ~(size_default - 1);
12564 			insn->code = BPF_LDX | BPF_MEM | size_code;
12565 		}
12566 
12567 		target_size = 0;
12568 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12569 					 &target_size);
12570 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12571 		    (ctx_field_size && !target_size)) {
12572 			verbose(env, "bpf verifier is misconfigured\n");
12573 			return -EINVAL;
12574 		}
12575 
12576 		if (is_narrower_load && size < target_size) {
12577 			u8 shift = bpf_ctx_narrow_access_offset(
12578 				off, size, size_default) * 8;
12579 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12580 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12581 				return -EINVAL;
12582 			}
12583 			if (ctx_field_size <= 4) {
12584 				if (shift)
12585 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12586 									insn->dst_reg,
12587 									shift);
12588 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12589 								(1 << size * 8) - 1);
12590 			} else {
12591 				if (shift)
12592 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12593 									insn->dst_reg,
12594 									shift);
12595 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12596 								(1ULL << size * 8) - 1);
12597 			}
12598 		}
12599 
12600 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12601 		if (!new_prog)
12602 			return -ENOMEM;
12603 
12604 		delta += cnt - 1;
12605 
12606 		/* keep walking new program and skip insns we just inserted */
12607 		env->prog = new_prog;
12608 		insn      = new_prog->insnsi + i + delta;
12609 	}
12610 
12611 	return 0;
12612 }
12613 
jit_subprogs(struct bpf_verifier_env * env)12614 static int jit_subprogs(struct bpf_verifier_env *env)
12615 {
12616 	struct bpf_prog *prog = env->prog, **func, *tmp;
12617 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12618 	struct bpf_map *map_ptr;
12619 	struct bpf_insn *insn;
12620 	void *old_bpf_func;
12621 	int err, num_exentries;
12622 
12623 	if (env->subprog_cnt <= 1)
12624 		return 0;
12625 
12626 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12627 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
12628 			continue;
12629 
12630 		/* Upon error here we cannot fall back to interpreter but
12631 		 * need a hard reject of the program. Thus -EFAULT is
12632 		 * propagated in any case.
12633 		 */
12634 		subprog = find_subprog(env, i + insn->imm + 1);
12635 		if (subprog < 0) {
12636 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12637 				  i + insn->imm + 1);
12638 			return -EFAULT;
12639 		}
12640 		/* temporarily remember subprog id inside insn instead of
12641 		 * aux_data, since next loop will split up all insns into funcs
12642 		 */
12643 		insn->off = subprog;
12644 		/* remember original imm in case JIT fails and fallback
12645 		 * to interpreter will be needed
12646 		 */
12647 		env->insn_aux_data[i].call_imm = insn->imm;
12648 		/* point imm to __bpf_call_base+1 from JITs point of view */
12649 		insn->imm = 1;
12650 		if (bpf_pseudo_func(insn))
12651 			/* jit (e.g. x86_64) may emit fewer instructions
12652 			 * if it learns a u32 imm is the same as a u64 imm.
12653 			 * Force a non zero here.
12654 			 */
12655 			insn[1].imm = 1;
12656 	}
12657 
12658 	err = bpf_prog_alloc_jited_linfo(prog);
12659 	if (err)
12660 		goto out_undo_insn;
12661 
12662 	err = -ENOMEM;
12663 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12664 	if (!func)
12665 		goto out_undo_insn;
12666 
12667 	for (i = 0; i < env->subprog_cnt; i++) {
12668 		subprog_start = subprog_end;
12669 		subprog_end = env->subprog_info[i + 1].start;
12670 
12671 		len = subprog_end - subprog_start;
12672 		/* bpf_prog_run() doesn't call subprogs directly,
12673 		 * hence main prog stats include the runtime of subprogs.
12674 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12675 		 * func[i]->stats will never be accessed and stays NULL
12676 		 */
12677 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12678 		if (!func[i])
12679 			goto out_free;
12680 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12681 		       len * sizeof(struct bpf_insn));
12682 		func[i]->type = prog->type;
12683 		func[i]->len = len;
12684 		if (bpf_prog_calc_tag(func[i]))
12685 			goto out_free;
12686 		func[i]->is_func = 1;
12687 		func[i]->aux->func_idx = i;
12688 		/* Below members will be freed only at prog->aux */
12689 		func[i]->aux->btf = prog->aux->btf;
12690 		func[i]->aux->func_info = prog->aux->func_info;
12691 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
12692 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12693 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12694 
12695 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12696 			struct bpf_jit_poke_descriptor *poke;
12697 
12698 			poke = &prog->aux->poke_tab[j];
12699 			if (poke->insn_idx < subprog_end &&
12700 			    poke->insn_idx >= subprog_start)
12701 				poke->aux = func[i]->aux;
12702 		}
12703 
12704 		func[i]->aux->name[0] = 'F';
12705 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12706 		func[i]->jit_requested = 1;
12707 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12708 		func[i]->aux->linfo = prog->aux->linfo;
12709 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12710 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12711 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12712 		num_exentries = 0;
12713 		insn = func[i]->insnsi;
12714 		for (j = 0; j < func[i]->len; j++, insn++) {
12715 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12716 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12717 				num_exentries++;
12718 		}
12719 		func[i]->aux->num_exentries = num_exentries;
12720 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12721 		func[i] = bpf_int_jit_compile(func[i]);
12722 		if (!func[i]->jited) {
12723 			err = -ENOTSUPP;
12724 			goto out_free;
12725 		}
12726 		cond_resched();
12727 	}
12728 
12729 	/* at this point all bpf functions were successfully JITed
12730 	 * now populate all bpf_calls with correct addresses and
12731 	 * run last pass of JIT
12732 	 */
12733 	for (i = 0; i < env->subprog_cnt; i++) {
12734 		insn = func[i]->insnsi;
12735 		for (j = 0; j < func[i]->len; j++, insn++) {
12736 			if (bpf_pseudo_func(insn)) {
12737 				subprog = insn->off;
12738 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12739 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12740 				continue;
12741 			}
12742 			if (!bpf_pseudo_call(insn))
12743 				continue;
12744 			subprog = insn->off;
12745 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12746 				    __bpf_call_base;
12747 		}
12748 
12749 		/* we use the aux data to keep a list of the start addresses
12750 		 * of the JITed images for each function in the program
12751 		 *
12752 		 * for some architectures, such as powerpc64, the imm field
12753 		 * might not be large enough to hold the offset of the start
12754 		 * address of the callee's JITed image from __bpf_call_base
12755 		 *
12756 		 * in such cases, we can lookup the start address of a callee
12757 		 * by using its subprog id, available from the off field of
12758 		 * the call instruction, as an index for this list
12759 		 */
12760 		func[i]->aux->func = func;
12761 		func[i]->aux->func_cnt = env->subprog_cnt;
12762 	}
12763 	for (i = 0; i < env->subprog_cnt; i++) {
12764 		old_bpf_func = func[i]->bpf_func;
12765 		tmp = bpf_int_jit_compile(func[i]);
12766 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12767 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12768 			err = -ENOTSUPP;
12769 			goto out_free;
12770 		}
12771 		cond_resched();
12772 	}
12773 
12774 	/* finally lock prog and jit images for all functions and
12775 	 * populate kallsysm. Begin at the first subprogram, since
12776 	 * bpf_prog_load will add the kallsyms for the main program.
12777 	 */
12778 	for (i = 1; i < env->subprog_cnt; i++) {
12779 		bpf_prog_lock_ro(func[i]);
12780 		bpf_prog_kallsyms_add(func[i]);
12781 	}
12782 
12783 	/* Last step: make now unused interpreter insns from main
12784 	 * prog consistent for later dump requests, so they can
12785 	 * later look the same as if they were interpreted only.
12786 	 */
12787 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12788 		if (bpf_pseudo_func(insn)) {
12789 			insn[0].imm = env->insn_aux_data[i].call_imm;
12790 			insn[1].imm = insn->off;
12791 			insn->off = 0;
12792 			continue;
12793 		}
12794 		if (!bpf_pseudo_call(insn))
12795 			continue;
12796 		insn->off = env->insn_aux_data[i].call_imm;
12797 		subprog = find_subprog(env, i + insn->off + 1);
12798 		insn->imm = subprog;
12799 	}
12800 
12801 	prog->jited = 1;
12802 	prog->bpf_func = func[0]->bpf_func;
12803 	prog->aux->extable = func[0]->aux->extable;
12804 	prog->aux->num_exentries = func[0]->aux->num_exentries;
12805 	prog->aux->func = func;
12806 	prog->aux->func_cnt = env->subprog_cnt;
12807 	bpf_prog_jit_attempt_done(prog);
12808 	return 0;
12809 out_free:
12810 	/* We failed JIT'ing, so at this point we need to unregister poke
12811 	 * descriptors from subprogs, so that kernel is not attempting to
12812 	 * patch it anymore as we're freeing the subprog JIT memory.
12813 	 */
12814 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12815 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12816 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12817 	}
12818 	/* At this point we're guaranteed that poke descriptors are not
12819 	 * live anymore. We can just unlink its descriptor table as it's
12820 	 * released with the main prog.
12821 	 */
12822 	for (i = 0; i < env->subprog_cnt; i++) {
12823 		if (!func[i])
12824 			continue;
12825 		func[i]->aux->poke_tab = NULL;
12826 		bpf_jit_free(func[i]);
12827 	}
12828 	kfree(func);
12829 out_undo_insn:
12830 	/* cleanup main prog to be interpreted */
12831 	prog->jit_requested = 0;
12832 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12833 		if (!bpf_pseudo_call(insn))
12834 			continue;
12835 		insn->off = 0;
12836 		insn->imm = env->insn_aux_data[i].call_imm;
12837 	}
12838 	bpf_prog_jit_attempt_done(prog);
12839 	return err;
12840 }
12841 
fixup_call_args(struct bpf_verifier_env * env)12842 static int fixup_call_args(struct bpf_verifier_env *env)
12843 {
12844 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12845 	struct bpf_prog *prog = env->prog;
12846 	struct bpf_insn *insn = prog->insnsi;
12847 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12848 	int i, depth;
12849 #endif
12850 	int err = 0;
12851 
12852 	if (env->prog->jit_requested &&
12853 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12854 		err = jit_subprogs(env);
12855 		if (err == 0)
12856 			return 0;
12857 		if (err == -EFAULT)
12858 			return err;
12859 	}
12860 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12861 	if (has_kfunc_call) {
12862 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12863 		return -EINVAL;
12864 	}
12865 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12866 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12867 		 * have to be rejected, since interpreter doesn't support them yet.
12868 		 */
12869 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12870 		return -EINVAL;
12871 	}
12872 	for (i = 0; i < prog->len; i++, insn++) {
12873 		if (bpf_pseudo_func(insn)) {
12874 			/* When JIT fails the progs with callback calls
12875 			 * have to be rejected, since interpreter doesn't support them yet.
12876 			 */
12877 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12878 			return -EINVAL;
12879 		}
12880 
12881 		if (!bpf_pseudo_call(insn))
12882 			continue;
12883 		depth = get_callee_stack_depth(env, insn, i);
12884 		if (depth < 0)
12885 			return depth;
12886 		bpf_patch_call_args(insn, depth);
12887 	}
12888 	err = 0;
12889 #endif
12890 	return err;
12891 }
12892 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn)12893 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12894 			    struct bpf_insn *insn)
12895 {
12896 	const struct bpf_kfunc_desc *desc;
12897 
12898 	/* insn->imm has the btf func_id. Replace it with
12899 	 * an address (relative to __bpf_base_call).
12900 	 */
12901 	desc = find_kfunc_desc(env->prog, insn->imm);
12902 	if (!desc) {
12903 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12904 			insn->imm);
12905 		return -EFAULT;
12906 	}
12907 
12908 	insn->imm = desc->imm;
12909 
12910 	return 0;
12911 }
12912 
12913 /* Do various post-verification rewrites in a single program pass.
12914  * These rewrites simplify JIT and interpreter implementations.
12915  */
do_misc_fixups(struct bpf_verifier_env * env)12916 static int do_misc_fixups(struct bpf_verifier_env *env)
12917 {
12918 	struct bpf_prog *prog = env->prog;
12919 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12920 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12921 	struct bpf_insn *insn = prog->insnsi;
12922 	const struct bpf_func_proto *fn;
12923 	const int insn_cnt = prog->len;
12924 	const struct bpf_map_ops *ops;
12925 	struct bpf_insn_aux_data *aux;
12926 	struct bpf_insn insn_buf[16];
12927 	struct bpf_prog *new_prog;
12928 	struct bpf_map *map_ptr;
12929 	int i, ret, cnt, delta = 0;
12930 
12931 	for (i = 0; i < insn_cnt; i++, insn++) {
12932 		/* Make divide-by-zero exceptions impossible. */
12933 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12934 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12935 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12936 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12937 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12938 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12939 			struct bpf_insn *patchlet;
12940 			struct bpf_insn chk_and_div[] = {
12941 				/* [R,W]x div 0 -> 0 */
12942 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12943 					     BPF_JNE | BPF_K, insn->src_reg,
12944 					     0, 2, 0),
12945 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12946 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12947 				*insn,
12948 			};
12949 			struct bpf_insn chk_and_mod[] = {
12950 				/* [R,W]x mod 0 -> [R,W]x */
12951 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12952 					     BPF_JEQ | BPF_K, insn->src_reg,
12953 					     0, 1 + (is64 ? 0 : 1), 0),
12954 				*insn,
12955 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12956 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12957 			};
12958 
12959 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12960 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12961 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12962 
12963 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12964 			if (!new_prog)
12965 				return -ENOMEM;
12966 
12967 			delta    += cnt - 1;
12968 			env->prog = prog = new_prog;
12969 			insn      = new_prog->insnsi + i + delta;
12970 			continue;
12971 		}
12972 
12973 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12974 		if (BPF_CLASS(insn->code) == BPF_LD &&
12975 		    (BPF_MODE(insn->code) == BPF_ABS ||
12976 		     BPF_MODE(insn->code) == BPF_IND)) {
12977 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12978 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12979 				verbose(env, "bpf verifier is misconfigured\n");
12980 				return -EINVAL;
12981 			}
12982 
12983 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12984 			if (!new_prog)
12985 				return -ENOMEM;
12986 
12987 			delta    += cnt - 1;
12988 			env->prog = prog = new_prog;
12989 			insn      = new_prog->insnsi + i + delta;
12990 			continue;
12991 		}
12992 
12993 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12994 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12995 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12996 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12997 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12998 			struct bpf_insn *patch = &insn_buf[0];
12999 			bool issrc, isneg, isimm;
13000 			u32 off_reg;
13001 
13002 			aux = &env->insn_aux_data[i + delta];
13003 			if (!aux->alu_state ||
13004 			    aux->alu_state == BPF_ALU_NON_POINTER)
13005 				continue;
13006 
13007 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13008 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13009 				BPF_ALU_SANITIZE_SRC;
13010 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13011 
13012 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
13013 			if (isimm) {
13014 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13015 			} else {
13016 				if (isneg)
13017 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13018 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13019 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13020 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13021 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13022 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13023 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13024 			}
13025 			if (!issrc)
13026 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13027 			insn->src_reg = BPF_REG_AX;
13028 			if (isneg)
13029 				insn->code = insn->code == code_add ?
13030 					     code_sub : code_add;
13031 			*patch++ = *insn;
13032 			if (issrc && isneg && !isimm)
13033 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13034 			cnt = patch - insn_buf;
13035 
13036 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13037 			if (!new_prog)
13038 				return -ENOMEM;
13039 
13040 			delta    += cnt - 1;
13041 			env->prog = prog = new_prog;
13042 			insn      = new_prog->insnsi + i + delta;
13043 			continue;
13044 		}
13045 
13046 		if (insn->code != (BPF_JMP | BPF_CALL))
13047 			continue;
13048 		if (insn->src_reg == BPF_PSEUDO_CALL)
13049 			continue;
13050 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13051 			ret = fixup_kfunc_call(env, insn);
13052 			if (ret)
13053 				return ret;
13054 			continue;
13055 		}
13056 
13057 		if (insn->imm == BPF_FUNC_get_route_realm)
13058 			prog->dst_needed = 1;
13059 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13060 			bpf_user_rnd_init_once();
13061 		if (insn->imm == BPF_FUNC_override_return)
13062 			prog->kprobe_override = 1;
13063 		if (insn->imm == BPF_FUNC_tail_call) {
13064 			/* If we tail call into other programs, we
13065 			 * cannot make any assumptions since they can
13066 			 * be replaced dynamically during runtime in
13067 			 * the program array.
13068 			 */
13069 			prog->cb_access = 1;
13070 			if (!allow_tail_call_in_subprogs(env))
13071 				prog->aux->stack_depth = MAX_BPF_STACK;
13072 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13073 
13074 			/* mark bpf_tail_call as different opcode to avoid
13075 			 * conditional branch in the interpreter for every normal
13076 			 * call and to prevent accidental JITing by JIT compiler
13077 			 * that doesn't support bpf_tail_call yet
13078 			 */
13079 			insn->imm = 0;
13080 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13081 
13082 			aux = &env->insn_aux_data[i + delta];
13083 			if (env->bpf_capable && !expect_blinding &&
13084 			    prog->jit_requested &&
13085 			    !bpf_map_key_poisoned(aux) &&
13086 			    !bpf_map_ptr_poisoned(aux) &&
13087 			    !bpf_map_ptr_unpriv(aux)) {
13088 				struct bpf_jit_poke_descriptor desc = {
13089 					.reason = BPF_POKE_REASON_TAIL_CALL,
13090 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13091 					.tail_call.key = bpf_map_key_immediate(aux),
13092 					.insn_idx = i + delta,
13093 				};
13094 
13095 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13096 				if (ret < 0) {
13097 					verbose(env, "adding tail call poke descriptor failed\n");
13098 					return ret;
13099 				}
13100 
13101 				insn->imm = ret + 1;
13102 				continue;
13103 			}
13104 
13105 			if (!bpf_map_ptr_unpriv(aux))
13106 				continue;
13107 
13108 			/* instead of changing every JIT dealing with tail_call
13109 			 * emit two extra insns:
13110 			 * if (index >= max_entries) goto out;
13111 			 * index &= array->index_mask;
13112 			 * to avoid out-of-bounds cpu speculation
13113 			 */
13114 			if (bpf_map_ptr_poisoned(aux)) {
13115 				verbose(env, "tail_call abusing map_ptr\n");
13116 				return -EINVAL;
13117 			}
13118 
13119 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13120 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13121 						  map_ptr->max_entries, 2);
13122 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13123 						    container_of(map_ptr,
13124 								 struct bpf_array,
13125 								 map)->index_mask);
13126 			insn_buf[2] = *insn;
13127 			cnt = 3;
13128 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13129 			if (!new_prog)
13130 				return -ENOMEM;
13131 
13132 			delta    += cnt - 1;
13133 			env->prog = prog = new_prog;
13134 			insn      = new_prog->insnsi + i + delta;
13135 			continue;
13136 		}
13137 
13138 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13139 			/* The verifier will process callback_fn as many times as necessary
13140 			 * with different maps and the register states prepared by
13141 			 * set_timer_callback_state will be accurate.
13142 			 *
13143 			 * The following use case is valid:
13144 			 *   map1 is shared by prog1, prog2, prog3.
13145 			 *   prog1 calls bpf_timer_init for some map1 elements
13146 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13147 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13148 			 *   prog3 calls bpf_timer_start for some map1 elements.
13149 			 *     Those that were not both bpf_timer_init-ed and
13150 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13151 			 */
13152 			struct bpf_insn ld_addrs[2] = {
13153 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13154 			};
13155 
13156 			insn_buf[0] = ld_addrs[0];
13157 			insn_buf[1] = ld_addrs[1];
13158 			insn_buf[2] = *insn;
13159 			cnt = 3;
13160 
13161 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13162 			if (!new_prog)
13163 				return -ENOMEM;
13164 
13165 			delta    += cnt - 1;
13166 			env->prog = prog = new_prog;
13167 			insn      = new_prog->insnsi + i + delta;
13168 			goto patch_call_imm;
13169 		}
13170 
13171 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13172 		 * and other inlining handlers are currently limited to 64 bit
13173 		 * only.
13174 		 */
13175 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13176 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13177 		     insn->imm == BPF_FUNC_map_update_elem ||
13178 		     insn->imm == BPF_FUNC_map_delete_elem ||
13179 		     insn->imm == BPF_FUNC_map_push_elem   ||
13180 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13181 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13182 		     insn->imm == BPF_FUNC_redirect_map)) {
13183 			aux = &env->insn_aux_data[i + delta];
13184 			if (bpf_map_ptr_poisoned(aux))
13185 				goto patch_call_imm;
13186 
13187 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13188 			ops = map_ptr->ops;
13189 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13190 			    ops->map_gen_lookup) {
13191 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13192 				if (cnt == -EOPNOTSUPP)
13193 					goto patch_map_ops_generic;
13194 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13195 					verbose(env, "bpf verifier is misconfigured\n");
13196 					return -EINVAL;
13197 				}
13198 
13199 				new_prog = bpf_patch_insn_data(env, i + delta,
13200 							       insn_buf, cnt);
13201 				if (!new_prog)
13202 					return -ENOMEM;
13203 
13204 				delta    += cnt - 1;
13205 				env->prog = prog = new_prog;
13206 				insn      = new_prog->insnsi + i + delta;
13207 				continue;
13208 			}
13209 
13210 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13211 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13212 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13213 				     (int (*)(struct bpf_map *map, void *key))NULL));
13214 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13215 				     (int (*)(struct bpf_map *map, void *key, void *value,
13216 					      u64 flags))NULL));
13217 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13218 				     (int (*)(struct bpf_map *map, void *value,
13219 					      u64 flags))NULL));
13220 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13221 				     (int (*)(struct bpf_map *map, void *value))NULL));
13222 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13223 				     (int (*)(struct bpf_map *map, void *value))NULL));
13224 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13225 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13226 
13227 patch_map_ops_generic:
13228 			switch (insn->imm) {
13229 			case BPF_FUNC_map_lookup_elem:
13230 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
13231 					    __bpf_call_base;
13232 				continue;
13233 			case BPF_FUNC_map_update_elem:
13234 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
13235 					    __bpf_call_base;
13236 				continue;
13237 			case BPF_FUNC_map_delete_elem:
13238 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
13239 					    __bpf_call_base;
13240 				continue;
13241 			case BPF_FUNC_map_push_elem:
13242 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
13243 					    __bpf_call_base;
13244 				continue;
13245 			case BPF_FUNC_map_pop_elem:
13246 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
13247 					    __bpf_call_base;
13248 				continue;
13249 			case BPF_FUNC_map_peek_elem:
13250 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
13251 					    __bpf_call_base;
13252 				continue;
13253 			case BPF_FUNC_redirect_map:
13254 				insn->imm = BPF_CAST_CALL(ops->map_redirect) -
13255 					    __bpf_call_base;
13256 				continue;
13257 			}
13258 
13259 			goto patch_call_imm;
13260 		}
13261 
13262 		/* Implement bpf_jiffies64 inline. */
13263 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13264 		    insn->imm == BPF_FUNC_jiffies64) {
13265 			struct bpf_insn ld_jiffies_addr[2] = {
13266 				BPF_LD_IMM64(BPF_REG_0,
13267 					     (unsigned long)&jiffies),
13268 			};
13269 
13270 			insn_buf[0] = ld_jiffies_addr[0];
13271 			insn_buf[1] = ld_jiffies_addr[1];
13272 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13273 						  BPF_REG_0, 0);
13274 			cnt = 3;
13275 
13276 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13277 						       cnt);
13278 			if (!new_prog)
13279 				return -ENOMEM;
13280 
13281 			delta    += cnt - 1;
13282 			env->prog = prog = new_prog;
13283 			insn      = new_prog->insnsi + i + delta;
13284 			continue;
13285 		}
13286 
13287 		/* Implement bpf_get_func_ip inline. */
13288 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13289 		    insn->imm == BPF_FUNC_get_func_ip) {
13290 			/* Load IP address from ctx - 8 */
13291 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13292 
13293 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13294 			if (!new_prog)
13295 				return -ENOMEM;
13296 
13297 			env->prog = prog = new_prog;
13298 			insn      = new_prog->insnsi + i + delta;
13299 			continue;
13300 		}
13301 
13302 patch_call_imm:
13303 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13304 		/* all functions that have prototype and verifier allowed
13305 		 * programs to call them, must be real in-kernel functions
13306 		 */
13307 		if (!fn->func) {
13308 			verbose(env,
13309 				"kernel subsystem misconfigured func %s#%d\n",
13310 				func_id_name(insn->imm), insn->imm);
13311 			return -EFAULT;
13312 		}
13313 		insn->imm = fn->func - __bpf_call_base;
13314 	}
13315 
13316 	/* Since poke tab is now finalized, publish aux to tracker. */
13317 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13318 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13319 		if (!map_ptr->ops->map_poke_track ||
13320 		    !map_ptr->ops->map_poke_untrack ||
13321 		    !map_ptr->ops->map_poke_run) {
13322 			verbose(env, "bpf verifier is misconfigured\n");
13323 			return -EINVAL;
13324 		}
13325 
13326 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13327 		if (ret < 0) {
13328 			verbose(env, "tracking tail call prog failed\n");
13329 			return ret;
13330 		}
13331 	}
13332 
13333 	sort_kfunc_descs_by_imm(env->prog);
13334 
13335 	return 0;
13336 }
13337 
free_states(struct bpf_verifier_env * env)13338 static void free_states(struct bpf_verifier_env *env)
13339 {
13340 	struct bpf_verifier_state_list *sl, *sln;
13341 	int i;
13342 
13343 	sl = env->free_list;
13344 	while (sl) {
13345 		sln = sl->next;
13346 		free_verifier_state(&sl->state, false);
13347 		kfree(sl);
13348 		sl = sln;
13349 	}
13350 	env->free_list = NULL;
13351 
13352 	if (!env->explored_states)
13353 		return;
13354 
13355 	for (i = 0; i < state_htab_size(env); i++) {
13356 		sl = env->explored_states[i];
13357 
13358 		while (sl) {
13359 			sln = sl->next;
13360 			free_verifier_state(&sl->state, false);
13361 			kfree(sl);
13362 			sl = sln;
13363 		}
13364 		env->explored_states[i] = NULL;
13365 	}
13366 }
13367 
do_check_common(struct bpf_verifier_env * env,int subprog)13368 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13369 {
13370 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13371 	struct bpf_verifier_state *state;
13372 	struct bpf_reg_state *regs;
13373 	int ret, i;
13374 
13375 	env->prev_linfo = NULL;
13376 	env->pass_cnt++;
13377 
13378 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13379 	if (!state)
13380 		return -ENOMEM;
13381 	state->curframe = 0;
13382 	state->speculative = false;
13383 	state->branches = 1;
13384 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13385 	if (!state->frame[0]) {
13386 		kfree(state);
13387 		return -ENOMEM;
13388 	}
13389 	env->cur_state = state;
13390 	init_func_state(env, state->frame[0],
13391 			BPF_MAIN_FUNC /* callsite */,
13392 			0 /* frameno */,
13393 			subprog);
13394 	state->first_insn_idx = env->subprog_info[subprog].start;
13395 	state->last_insn_idx = -1;
13396 
13397 	regs = state->frame[state->curframe]->regs;
13398 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13399 		ret = btf_prepare_func_args(env, subprog, regs);
13400 		if (ret)
13401 			goto out;
13402 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13403 			if (regs[i].type == PTR_TO_CTX)
13404 				mark_reg_known_zero(env, regs, i);
13405 			else if (regs[i].type == SCALAR_VALUE)
13406 				mark_reg_unknown(env, regs, i);
13407 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
13408 				const u32 mem_size = regs[i].mem_size;
13409 
13410 				mark_reg_known_zero(env, regs, i);
13411 				regs[i].mem_size = mem_size;
13412 				regs[i].id = ++env->id_gen;
13413 			}
13414 		}
13415 	} else {
13416 		/* 1st arg to a function */
13417 		regs[BPF_REG_1].type = PTR_TO_CTX;
13418 		mark_reg_known_zero(env, regs, BPF_REG_1);
13419 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13420 		if (ret == -EFAULT)
13421 			/* unlikely verifier bug. abort.
13422 			 * ret == 0 and ret < 0 are sadly acceptable for
13423 			 * main() function due to backward compatibility.
13424 			 * Like socket filter program may be written as:
13425 			 * int bpf_prog(struct pt_regs *ctx)
13426 			 * and never dereference that ctx in the program.
13427 			 * 'struct pt_regs' is a type mismatch for socket
13428 			 * filter that should be using 'struct __sk_buff'.
13429 			 */
13430 			goto out;
13431 	}
13432 
13433 	ret = do_check(env);
13434 out:
13435 	/* check for NULL is necessary, since cur_state can be freed inside
13436 	 * do_check() under memory pressure.
13437 	 */
13438 	if (env->cur_state) {
13439 		free_verifier_state(env->cur_state, true);
13440 		env->cur_state = NULL;
13441 	}
13442 	while (!pop_stack(env, NULL, NULL, false));
13443 	if (!ret && pop_log)
13444 		bpf_vlog_reset(&env->log, 0);
13445 	free_states(env);
13446 	return ret;
13447 }
13448 
13449 /* Verify all global functions in a BPF program one by one based on their BTF.
13450  * All global functions must pass verification. Otherwise the whole program is rejected.
13451  * Consider:
13452  * int bar(int);
13453  * int foo(int f)
13454  * {
13455  *    return bar(f);
13456  * }
13457  * int bar(int b)
13458  * {
13459  *    ...
13460  * }
13461  * foo() will be verified first for R1=any_scalar_value. During verification it
13462  * will be assumed that bar() already verified successfully and call to bar()
13463  * from foo() will be checked for type match only. Later bar() will be verified
13464  * independently to check that it's safe for R1=any_scalar_value.
13465  */
do_check_subprogs(struct bpf_verifier_env * env)13466 static int do_check_subprogs(struct bpf_verifier_env *env)
13467 {
13468 	struct bpf_prog_aux *aux = env->prog->aux;
13469 	int i, ret;
13470 
13471 	if (!aux->func_info)
13472 		return 0;
13473 
13474 	for (i = 1; i < env->subprog_cnt; i++) {
13475 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13476 			continue;
13477 		env->insn_idx = env->subprog_info[i].start;
13478 		WARN_ON_ONCE(env->insn_idx == 0);
13479 		ret = do_check_common(env, i);
13480 		if (ret) {
13481 			return ret;
13482 		} else if (env->log.level & BPF_LOG_LEVEL) {
13483 			verbose(env,
13484 				"Func#%d is safe for any args that match its prototype\n",
13485 				i);
13486 		}
13487 	}
13488 	return 0;
13489 }
13490 
do_check_main(struct bpf_verifier_env * env)13491 static int do_check_main(struct bpf_verifier_env *env)
13492 {
13493 	int ret;
13494 
13495 	env->insn_idx = 0;
13496 	ret = do_check_common(env, 0);
13497 	if (!ret)
13498 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13499 	return ret;
13500 }
13501 
13502 
print_verification_stats(struct bpf_verifier_env * env)13503 static void print_verification_stats(struct bpf_verifier_env *env)
13504 {
13505 	int i;
13506 
13507 	if (env->log.level & BPF_LOG_STATS) {
13508 		verbose(env, "verification time %lld usec\n",
13509 			div_u64(env->verification_time, 1000));
13510 		verbose(env, "stack depth ");
13511 		for (i = 0; i < env->subprog_cnt; i++) {
13512 			u32 depth = env->subprog_info[i].stack_depth;
13513 
13514 			verbose(env, "%d", depth);
13515 			if (i + 1 < env->subprog_cnt)
13516 				verbose(env, "+");
13517 		}
13518 		verbose(env, "\n");
13519 	}
13520 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13521 		"total_states %d peak_states %d mark_read %d\n",
13522 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13523 		env->max_states_per_insn, env->total_states,
13524 		env->peak_states, env->longest_mark_read_walk);
13525 }
13526 
check_struct_ops_btf_id(struct bpf_verifier_env * env)13527 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13528 {
13529 	const struct btf_type *t, *func_proto;
13530 	const struct bpf_struct_ops *st_ops;
13531 	const struct btf_member *member;
13532 	struct bpf_prog *prog = env->prog;
13533 	u32 btf_id, member_idx;
13534 	const char *mname;
13535 
13536 	if (!prog->gpl_compatible) {
13537 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13538 		return -EINVAL;
13539 	}
13540 
13541 	btf_id = prog->aux->attach_btf_id;
13542 	st_ops = bpf_struct_ops_find(btf_id);
13543 	if (!st_ops) {
13544 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13545 			btf_id);
13546 		return -ENOTSUPP;
13547 	}
13548 
13549 	t = st_ops->type;
13550 	member_idx = prog->expected_attach_type;
13551 	if (member_idx >= btf_type_vlen(t)) {
13552 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13553 			member_idx, st_ops->name);
13554 		return -EINVAL;
13555 	}
13556 
13557 	member = &btf_type_member(t)[member_idx];
13558 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13559 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13560 					       NULL);
13561 	if (!func_proto) {
13562 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13563 			mname, member_idx, st_ops->name);
13564 		return -EINVAL;
13565 	}
13566 
13567 	if (st_ops->check_member) {
13568 		int err = st_ops->check_member(t, member);
13569 
13570 		if (err) {
13571 			verbose(env, "attach to unsupported member %s of struct %s\n",
13572 				mname, st_ops->name);
13573 			return err;
13574 		}
13575 	}
13576 
13577 	prog->aux->attach_func_proto = func_proto;
13578 	prog->aux->attach_func_name = mname;
13579 	env->ops = st_ops->verifier_ops;
13580 
13581 	return 0;
13582 }
13583 #define SECURITY_PREFIX "security_"
13584 
check_attach_modify_return(unsigned long addr,const char * func_name)13585 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13586 {
13587 	if (within_error_injection_list(addr) ||
13588 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13589 		return 0;
13590 
13591 	return -EINVAL;
13592 }
13593 
13594 /* list of non-sleepable functions that are otherwise on
13595  * ALLOW_ERROR_INJECTION list
13596  */
13597 BTF_SET_START(btf_non_sleepable_error_inject)
13598 /* Three functions below can be called from sleepable and non-sleepable context.
13599  * Assume non-sleepable from bpf safety point of view.
13600  */
BTF_ID(func,__add_to_page_cache_locked)13601 BTF_ID(func, __add_to_page_cache_locked)
13602 BTF_ID(func, should_fail_alloc_page)
13603 BTF_ID(func, should_failslab)
13604 BTF_SET_END(btf_non_sleepable_error_inject)
13605 
13606 static int check_non_sleepable_error_inject(u32 btf_id)
13607 {
13608 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13609 }
13610 
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)13611 int bpf_check_attach_target(struct bpf_verifier_log *log,
13612 			    const struct bpf_prog *prog,
13613 			    const struct bpf_prog *tgt_prog,
13614 			    u32 btf_id,
13615 			    struct bpf_attach_target_info *tgt_info)
13616 {
13617 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13618 	const char prefix[] = "btf_trace_";
13619 	int ret = 0, subprog = -1, i;
13620 	const struct btf_type *t;
13621 	bool conservative = true;
13622 	const char *tname;
13623 	struct btf *btf;
13624 	long addr = 0;
13625 
13626 	if (!btf_id) {
13627 		bpf_log(log, "Tracing programs must provide btf_id\n");
13628 		return -EINVAL;
13629 	}
13630 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13631 	if (!btf) {
13632 		bpf_log(log,
13633 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13634 		return -EINVAL;
13635 	}
13636 	t = btf_type_by_id(btf, btf_id);
13637 	if (!t) {
13638 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13639 		return -EINVAL;
13640 	}
13641 	tname = btf_name_by_offset(btf, t->name_off);
13642 	if (!tname) {
13643 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13644 		return -EINVAL;
13645 	}
13646 	if (tgt_prog) {
13647 		struct bpf_prog_aux *aux = tgt_prog->aux;
13648 
13649 		for (i = 0; i < aux->func_info_cnt; i++)
13650 			if (aux->func_info[i].type_id == btf_id) {
13651 				subprog = i;
13652 				break;
13653 			}
13654 		if (subprog == -1) {
13655 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13656 			return -EINVAL;
13657 		}
13658 		conservative = aux->func_info_aux[subprog].unreliable;
13659 		if (prog_extension) {
13660 			if (conservative) {
13661 				bpf_log(log,
13662 					"Cannot replace static functions\n");
13663 				return -EINVAL;
13664 			}
13665 			if (!prog->jit_requested) {
13666 				bpf_log(log,
13667 					"Extension programs should be JITed\n");
13668 				return -EINVAL;
13669 			}
13670 		}
13671 		if (!tgt_prog->jited) {
13672 			bpf_log(log, "Can attach to only JITed progs\n");
13673 			return -EINVAL;
13674 		}
13675 		if (tgt_prog->type == prog->type) {
13676 			/* Cannot fentry/fexit another fentry/fexit program.
13677 			 * Cannot attach program extension to another extension.
13678 			 * It's ok to attach fentry/fexit to extension program.
13679 			 */
13680 			bpf_log(log, "Cannot recursively attach\n");
13681 			return -EINVAL;
13682 		}
13683 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13684 		    prog_extension &&
13685 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13686 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13687 			/* Program extensions can extend all program types
13688 			 * except fentry/fexit. The reason is the following.
13689 			 * The fentry/fexit programs are used for performance
13690 			 * analysis, stats and can be attached to any program
13691 			 * type except themselves. When extension program is
13692 			 * replacing XDP function it is necessary to allow
13693 			 * performance analysis of all functions. Both original
13694 			 * XDP program and its program extension. Hence
13695 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13696 			 * allowed. If extending of fentry/fexit was allowed it
13697 			 * would be possible to create long call chain
13698 			 * fentry->extension->fentry->extension beyond
13699 			 * reasonable stack size. Hence extending fentry is not
13700 			 * allowed.
13701 			 */
13702 			bpf_log(log, "Cannot extend fentry/fexit\n");
13703 			return -EINVAL;
13704 		}
13705 	} else {
13706 		if (prog_extension) {
13707 			bpf_log(log, "Cannot replace kernel functions\n");
13708 			return -EINVAL;
13709 		}
13710 	}
13711 
13712 	switch (prog->expected_attach_type) {
13713 	case BPF_TRACE_RAW_TP:
13714 		if (tgt_prog) {
13715 			bpf_log(log,
13716 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13717 			return -EINVAL;
13718 		}
13719 		if (!btf_type_is_typedef(t)) {
13720 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13721 				btf_id);
13722 			return -EINVAL;
13723 		}
13724 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13725 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13726 				btf_id, tname);
13727 			return -EINVAL;
13728 		}
13729 		tname += sizeof(prefix) - 1;
13730 		t = btf_type_by_id(btf, t->type);
13731 		if (!btf_type_is_ptr(t))
13732 			/* should never happen in valid vmlinux build */
13733 			return -EINVAL;
13734 		t = btf_type_by_id(btf, t->type);
13735 		if (!btf_type_is_func_proto(t))
13736 			/* should never happen in valid vmlinux build */
13737 			return -EINVAL;
13738 
13739 		break;
13740 	case BPF_TRACE_ITER:
13741 		if (!btf_type_is_func(t)) {
13742 			bpf_log(log, "attach_btf_id %u is not a function\n",
13743 				btf_id);
13744 			return -EINVAL;
13745 		}
13746 		t = btf_type_by_id(btf, t->type);
13747 		if (!btf_type_is_func_proto(t))
13748 			return -EINVAL;
13749 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13750 		if (ret)
13751 			return ret;
13752 		break;
13753 	default:
13754 		if (!prog_extension)
13755 			return -EINVAL;
13756 		fallthrough;
13757 	case BPF_MODIFY_RETURN:
13758 	case BPF_LSM_MAC:
13759 	case BPF_TRACE_FENTRY:
13760 	case BPF_TRACE_FEXIT:
13761 		if (!btf_type_is_func(t)) {
13762 			bpf_log(log, "attach_btf_id %u is not a function\n",
13763 				btf_id);
13764 			return -EINVAL;
13765 		}
13766 		if (prog_extension &&
13767 		    btf_check_type_match(log, prog, btf, t))
13768 			return -EINVAL;
13769 		t = btf_type_by_id(btf, t->type);
13770 		if (!btf_type_is_func_proto(t))
13771 			return -EINVAL;
13772 
13773 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13774 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13775 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13776 			return -EINVAL;
13777 
13778 		if (tgt_prog && conservative)
13779 			t = NULL;
13780 
13781 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13782 		if (ret < 0)
13783 			return ret;
13784 
13785 		if (tgt_prog) {
13786 			if (subprog == 0)
13787 				addr = (long) tgt_prog->bpf_func;
13788 			else
13789 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13790 		} else {
13791 			addr = kallsyms_lookup_name(tname);
13792 			if (!addr) {
13793 				bpf_log(log,
13794 					"The address of function %s cannot be found\n",
13795 					tname);
13796 				return -ENOENT;
13797 			}
13798 		}
13799 
13800 		if (prog->aux->sleepable) {
13801 			ret = -EINVAL;
13802 			switch (prog->type) {
13803 			case BPF_PROG_TYPE_TRACING:
13804 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13805 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13806 				 */
13807 				if (!check_non_sleepable_error_inject(btf_id) &&
13808 				    within_error_injection_list(addr))
13809 					ret = 0;
13810 				break;
13811 			case BPF_PROG_TYPE_LSM:
13812 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13813 				 * Only some of them are sleepable.
13814 				 */
13815 				if (bpf_lsm_is_sleepable_hook(btf_id))
13816 					ret = 0;
13817 				break;
13818 			default:
13819 				break;
13820 			}
13821 			if (ret) {
13822 				bpf_log(log, "%s is not sleepable\n", tname);
13823 				return ret;
13824 			}
13825 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13826 			if (tgt_prog) {
13827 				bpf_log(log, "can't modify return codes of BPF programs\n");
13828 				return -EINVAL;
13829 			}
13830 			ret = check_attach_modify_return(addr, tname);
13831 			if (ret) {
13832 				bpf_log(log, "%s() is not modifiable\n", tname);
13833 				return ret;
13834 			}
13835 		}
13836 
13837 		break;
13838 	}
13839 	tgt_info->tgt_addr = addr;
13840 	tgt_info->tgt_name = tname;
13841 	tgt_info->tgt_type = t;
13842 	return 0;
13843 }
13844 
BTF_SET_START(btf_id_deny)13845 BTF_SET_START(btf_id_deny)
13846 BTF_ID_UNUSED
13847 #ifdef CONFIG_SMP
13848 BTF_ID(func, migrate_disable)
13849 BTF_ID(func, migrate_enable)
13850 #endif
13851 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13852 BTF_ID(func, rcu_read_unlock_strict)
13853 #endif
13854 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
13855 BTF_ID(func, preempt_count_add)
13856 BTF_ID(func, preempt_count_sub)
13857 #endif
13858 BTF_SET_END(btf_id_deny)
13859 
13860 static int check_attach_btf_id(struct bpf_verifier_env *env)
13861 {
13862 	struct bpf_prog *prog = env->prog;
13863 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13864 	struct bpf_attach_target_info tgt_info = {};
13865 	u32 btf_id = prog->aux->attach_btf_id;
13866 	struct bpf_trampoline *tr;
13867 	int ret;
13868 	u64 key;
13869 
13870 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13871 		if (prog->aux->sleepable)
13872 			/* attach_btf_id checked to be zero already */
13873 			return 0;
13874 		verbose(env, "Syscall programs can only be sleepable\n");
13875 		return -EINVAL;
13876 	}
13877 
13878 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13879 	    prog->type != BPF_PROG_TYPE_LSM) {
13880 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13881 		return -EINVAL;
13882 	}
13883 
13884 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13885 		return check_struct_ops_btf_id(env);
13886 
13887 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13888 	    prog->type != BPF_PROG_TYPE_LSM &&
13889 	    prog->type != BPF_PROG_TYPE_EXT)
13890 		return 0;
13891 
13892 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13893 	if (ret)
13894 		return ret;
13895 
13896 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13897 		/* to make freplace equivalent to their targets, they need to
13898 		 * inherit env->ops and expected_attach_type for the rest of the
13899 		 * verification
13900 		 */
13901 		env->ops = bpf_verifier_ops[tgt_prog->type];
13902 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13903 	}
13904 
13905 	/* store info about the attachment target that will be used later */
13906 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13907 	prog->aux->attach_func_name = tgt_info.tgt_name;
13908 
13909 	if (tgt_prog) {
13910 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13911 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13912 	}
13913 
13914 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13915 		prog->aux->attach_btf_trace = true;
13916 		return 0;
13917 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13918 		if (!bpf_iter_prog_supported(prog))
13919 			return -EINVAL;
13920 		return 0;
13921 	}
13922 
13923 	if (prog->type == BPF_PROG_TYPE_LSM) {
13924 		ret = bpf_lsm_verify_prog(&env->log, prog);
13925 		if (ret < 0)
13926 			return ret;
13927 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13928 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13929 		return -EINVAL;
13930 	}
13931 
13932 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13933 	tr = bpf_trampoline_get(key, &tgt_info);
13934 	if (!tr)
13935 		return -ENOMEM;
13936 
13937 	prog->aux->dst_trampoline = tr;
13938 	return 0;
13939 }
13940 
bpf_get_btf_vmlinux(void)13941 struct btf *bpf_get_btf_vmlinux(void)
13942 {
13943 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13944 		mutex_lock(&bpf_verifier_lock);
13945 		if (!btf_vmlinux)
13946 			btf_vmlinux = btf_parse_vmlinux();
13947 		mutex_unlock(&bpf_verifier_lock);
13948 	}
13949 	return btf_vmlinux;
13950 }
13951 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr)13952 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13953 {
13954 	u64 start_time = ktime_get_ns();
13955 	struct bpf_verifier_env *env;
13956 	struct bpf_verifier_log *log;
13957 	int i, len, ret = -EINVAL;
13958 	bool is_priv;
13959 
13960 	/* no program is valid */
13961 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13962 		return -EINVAL;
13963 
13964 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13965 	 * allocate/free it every time bpf_check() is called
13966 	 */
13967 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13968 	if (!env)
13969 		return -ENOMEM;
13970 	log = &env->log;
13971 
13972 	len = (*prog)->len;
13973 	env->insn_aux_data =
13974 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13975 	ret = -ENOMEM;
13976 	if (!env->insn_aux_data)
13977 		goto err_free_env;
13978 	for (i = 0; i < len; i++)
13979 		env->insn_aux_data[i].orig_idx = i;
13980 	env->prog = *prog;
13981 	env->ops = bpf_verifier_ops[env->prog->type];
13982 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13983 	is_priv = bpf_capable();
13984 
13985 	bpf_get_btf_vmlinux();
13986 
13987 	/* grab the mutex to protect few globals used by verifier */
13988 	if (!is_priv)
13989 		mutex_lock(&bpf_verifier_lock);
13990 
13991 	if (attr->log_level || attr->log_buf || attr->log_size) {
13992 		/* user requested verbose verifier output
13993 		 * and supplied buffer to store the verification trace
13994 		 */
13995 		log->level = attr->log_level;
13996 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13997 		log->len_total = attr->log_size;
13998 
13999 		/* log attributes have to be sane */
14000 		if (!bpf_verifier_log_attr_valid(log)) {
14001 			ret = -EINVAL;
14002 			goto err_unlock;
14003 		}
14004 	}
14005 
14006 	if (IS_ERR(btf_vmlinux)) {
14007 		/* Either gcc or pahole or kernel are broken. */
14008 		verbose(env, "in-kernel BTF is malformed\n");
14009 		ret = PTR_ERR(btf_vmlinux);
14010 		goto skip_full_check;
14011 	}
14012 
14013 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14014 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
14015 		env->strict_alignment = true;
14016 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14017 		env->strict_alignment = false;
14018 
14019 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
14020 	env->allow_uninit_stack = bpf_allow_uninit_stack();
14021 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
14022 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
14023 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
14024 	env->bpf_capable = bpf_capable();
14025 
14026 	if (is_priv)
14027 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14028 
14029 	env->explored_states = kvcalloc(state_htab_size(env),
14030 				       sizeof(struct bpf_verifier_state_list *),
14031 				       GFP_USER);
14032 	ret = -ENOMEM;
14033 	if (!env->explored_states)
14034 		goto skip_full_check;
14035 
14036 	ret = add_subprog_and_kfunc(env);
14037 	if (ret < 0)
14038 		goto skip_full_check;
14039 
14040 	ret = check_subprogs(env);
14041 	if (ret < 0)
14042 		goto skip_full_check;
14043 
14044 	ret = check_btf_info(env, attr, uattr);
14045 	if (ret < 0)
14046 		goto skip_full_check;
14047 
14048 	ret = check_attach_btf_id(env);
14049 	if (ret)
14050 		goto skip_full_check;
14051 
14052 	ret = resolve_pseudo_ldimm64(env);
14053 	if (ret < 0)
14054 		goto skip_full_check;
14055 
14056 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
14057 		ret = bpf_prog_offload_verifier_prep(env->prog);
14058 		if (ret)
14059 			goto skip_full_check;
14060 	}
14061 
14062 	ret = check_cfg(env);
14063 	if (ret < 0)
14064 		goto skip_full_check;
14065 
14066 	ret = do_check_subprogs(env);
14067 	ret = ret ?: do_check_main(env);
14068 
14069 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14070 		ret = bpf_prog_offload_finalize(env);
14071 
14072 skip_full_check:
14073 	kvfree(env->explored_states);
14074 
14075 	if (ret == 0)
14076 		ret = check_max_stack_depth(env);
14077 
14078 	/* instruction rewrites happen after this point */
14079 	if (is_priv) {
14080 		if (ret == 0)
14081 			opt_hard_wire_dead_code_branches(env);
14082 		if (ret == 0)
14083 			ret = opt_remove_dead_code(env);
14084 		if (ret == 0)
14085 			ret = opt_remove_nops(env);
14086 	} else {
14087 		if (ret == 0)
14088 			sanitize_dead_code(env);
14089 	}
14090 
14091 	if (ret == 0)
14092 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14093 		ret = convert_ctx_accesses(env);
14094 
14095 	if (ret == 0)
14096 		ret = do_misc_fixups(env);
14097 
14098 	/* do 32-bit optimization after insn patching has done so those patched
14099 	 * insns could be handled correctly.
14100 	 */
14101 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14102 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14103 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14104 								     : false;
14105 	}
14106 
14107 	if (ret == 0)
14108 		ret = fixup_call_args(env);
14109 
14110 	env->verification_time = ktime_get_ns() - start_time;
14111 	print_verification_stats(env);
14112 
14113 	if (log->level && bpf_verifier_log_full(log))
14114 		ret = -ENOSPC;
14115 	if (log->level && !log->ubuf) {
14116 		ret = -EFAULT;
14117 		goto err_release_maps;
14118 	}
14119 
14120 	if (ret)
14121 		goto err_release_maps;
14122 
14123 	if (env->used_map_cnt) {
14124 		/* if program passed verifier, update used_maps in bpf_prog_info */
14125 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14126 							  sizeof(env->used_maps[0]),
14127 							  GFP_KERNEL);
14128 
14129 		if (!env->prog->aux->used_maps) {
14130 			ret = -ENOMEM;
14131 			goto err_release_maps;
14132 		}
14133 
14134 		memcpy(env->prog->aux->used_maps, env->used_maps,
14135 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14136 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14137 	}
14138 	if (env->used_btf_cnt) {
14139 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14140 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14141 							  sizeof(env->used_btfs[0]),
14142 							  GFP_KERNEL);
14143 		if (!env->prog->aux->used_btfs) {
14144 			ret = -ENOMEM;
14145 			goto err_release_maps;
14146 		}
14147 
14148 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14149 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14150 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14151 	}
14152 	if (env->used_map_cnt || env->used_btf_cnt) {
14153 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14154 		 * bpf_ld_imm64 instructions
14155 		 */
14156 		convert_pseudo_ld_imm64(env);
14157 	}
14158 
14159 	adjust_btf_func(env);
14160 
14161 err_release_maps:
14162 	if (!env->prog->aux->used_maps)
14163 		/* if we didn't copy map pointers into bpf_prog_info, release
14164 		 * them now. Otherwise free_used_maps() will release them.
14165 		 */
14166 		release_maps(env);
14167 	if (!env->prog->aux->used_btfs)
14168 		release_btfs(env);
14169 
14170 	/* extension progs temporarily inherit the attach_type of their targets
14171 	   for verification purposes, so set it back to zero before returning
14172 	 */
14173 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14174 		env->prog->expected_attach_type = 0;
14175 
14176 	*prog = env->prog;
14177 err_unlock:
14178 	if (!is_priv)
14179 		mutex_unlock(&bpf_verifier_lock);
14180 	vfree(env->insn_aux_data);
14181 err_free_env:
14182 	kfree(env);
14183 	return ret;
14184 }
14185