• 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 
880 	return id;
881 }
882 
883 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)884 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
885 {
886 	int i, last_idx;
887 
888 	last_idx = state->acquired_refs - 1;
889 	for (i = 0; i < state->acquired_refs; i++) {
890 		if (state->refs[i].id == ptr_id) {
891 			if (last_idx && i != last_idx)
892 				memcpy(&state->refs[i], &state->refs[last_idx],
893 				       sizeof(*state->refs));
894 			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
895 			state->acquired_refs--;
896 			return 0;
897 		}
898 	}
899 	return -EINVAL;
900 }
901 
free_func_state(struct bpf_func_state * state)902 static void free_func_state(struct bpf_func_state *state)
903 {
904 	if (!state)
905 		return;
906 	kfree(state->refs);
907 	kfree(state->stack);
908 	kfree(state);
909 }
910 
clear_jmp_history(struct bpf_verifier_state * state)911 static void clear_jmp_history(struct bpf_verifier_state *state)
912 {
913 	kfree(state->jmp_history);
914 	state->jmp_history = NULL;
915 	state->jmp_history_cnt = 0;
916 }
917 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)918 static void free_verifier_state(struct bpf_verifier_state *state,
919 				bool free_self)
920 {
921 	int i;
922 
923 	for (i = 0; i <= state->curframe; i++) {
924 		free_func_state(state->frame[i]);
925 		state->frame[i] = NULL;
926 	}
927 	clear_jmp_history(state);
928 	if (free_self)
929 		kfree(state);
930 }
931 
932 /* copy verifier state from src to dst growing dst stack space
933  * when necessary to accommodate larger src stack
934  */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)935 static int copy_func_state(struct bpf_func_state *dst,
936 			   const struct bpf_func_state *src)
937 {
938 	int err;
939 
940 	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
941 	err = copy_reference_state(dst, src);
942 	if (err)
943 		return err;
944 	return copy_stack_state(dst, src);
945 }
946 
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)947 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
948 			       const struct bpf_verifier_state *src)
949 {
950 	struct bpf_func_state *dst;
951 	int i, err;
952 
953 	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
954 					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
955 					    GFP_USER);
956 	if (!dst_state->jmp_history)
957 		return -ENOMEM;
958 	dst_state->jmp_history_cnt = src->jmp_history_cnt;
959 
960 	/* if dst has more stack frames then src frame, free them */
961 	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
962 		free_func_state(dst_state->frame[i]);
963 		dst_state->frame[i] = NULL;
964 	}
965 	dst_state->speculative = src->speculative;
966 	dst_state->curframe = src->curframe;
967 	dst_state->active_spin_lock = src->active_spin_lock;
968 	dst_state->branches = src->branches;
969 	dst_state->parent = src->parent;
970 	dst_state->first_insn_idx = src->first_insn_idx;
971 	dst_state->last_insn_idx = src->last_insn_idx;
972 	for (i = 0; i <= src->curframe; i++) {
973 		dst = dst_state->frame[i];
974 		if (!dst) {
975 			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
976 			if (!dst)
977 				return -ENOMEM;
978 			dst_state->frame[i] = dst;
979 		}
980 		err = copy_func_state(dst, src->frame[i]);
981 		if (err)
982 			return err;
983 	}
984 	return 0;
985 }
986 
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
988 {
989 	while (st) {
990 		u32 br = --st->branches;
991 
992 		/* WARN_ON(br > 1) technically makes sense here,
993 		 * but see comment in push_stack(), hence:
994 		 */
995 		WARN_ONCE((int)br < 0,
996 			  "BUG update_branch_counts:branches_to_explore=%d\n",
997 			  br);
998 		if (br)
999 			break;
1000 		st = st->parent;
1001 	}
1002 }
1003 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)1004 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1005 		     int *insn_idx, bool pop_log)
1006 {
1007 	struct bpf_verifier_state *cur = env->cur_state;
1008 	struct bpf_verifier_stack_elem *elem, *head = env->head;
1009 	int err;
1010 
1011 	if (env->head == NULL)
1012 		return -ENOENT;
1013 
1014 	if (cur) {
1015 		err = copy_verifier_state(cur, &head->st);
1016 		if (err)
1017 			return err;
1018 	}
1019 	if (pop_log)
1020 		bpf_vlog_reset(&env->log, head->log_pos);
1021 	if (insn_idx)
1022 		*insn_idx = head->insn_idx;
1023 	if (prev_insn_idx)
1024 		*prev_insn_idx = head->prev_insn_idx;
1025 	elem = head->next;
1026 	free_verifier_state(&head->st, false);
1027 	kfree(head);
1028 	env->head = elem;
1029 	env->stack_size--;
1030 	return 0;
1031 }
1032 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)1033 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1034 					     int insn_idx, int prev_insn_idx,
1035 					     bool speculative)
1036 {
1037 	struct bpf_verifier_state *cur = env->cur_state;
1038 	struct bpf_verifier_stack_elem *elem;
1039 	int err;
1040 
1041 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1042 	if (!elem)
1043 		goto err;
1044 
1045 	elem->insn_idx = insn_idx;
1046 	elem->prev_insn_idx = prev_insn_idx;
1047 	elem->next = env->head;
1048 	elem->log_pos = env->log.len_used;
1049 	env->head = elem;
1050 	env->stack_size++;
1051 	err = copy_verifier_state(&elem->st, cur);
1052 	if (err)
1053 		goto err;
1054 	elem->st.speculative |= speculative;
1055 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1056 		verbose(env, "The sequence of %d jumps is too complex.\n",
1057 			env->stack_size);
1058 		goto err;
1059 	}
1060 	if (elem->st.parent) {
1061 		++elem->st.parent->branches;
1062 		/* WARN_ON(branches > 2) technically makes sense here,
1063 		 * but
1064 		 * 1. speculative states will bump 'branches' for non-branch
1065 		 * instructions
1066 		 * 2. is_state_visited() heuristics may decide not to create
1067 		 * a new state for a sequence of branches and all such current
1068 		 * and cloned states will be pointing to a single parent state
1069 		 * which might have large 'branches' count.
1070 		 */
1071 	}
1072 	return &elem->st;
1073 err:
1074 	free_verifier_state(env->cur_state, true);
1075 	env->cur_state = NULL;
1076 	/* pop all elements and return */
1077 	while (!pop_stack(env, NULL, NULL, false));
1078 	return NULL;
1079 }
1080 
1081 #define CALLER_SAVED_REGS 6
1082 static const int caller_saved[CALLER_SAVED_REGS] = {
1083 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1084 };
1085 
1086 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1087 				struct bpf_reg_state *reg);
1088 
1089 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1090 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1091 {
1092 	reg->var_off = tnum_const(imm);
1093 	reg->smin_value = (s64)imm;
1094 	reg->smax_value = (s64)imm;
1095 	reg->umin_value = imm;
1096 	reg->umax_value = imm;
1097 
1098 	reg->s32_min_value = (s32)imm;
1099 	reg->s32_max_value = (s32)imm;
1100 	reg->u32_min_value = (u32)imm;
1101 	reg->u32_max_value = (u32)imm;
1102 }
1103 
1104 /* Mark the unknown part of a register (variable offset or scalar value) as
1105  * known to have the value @imm.
1106  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1107 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1108 {
1109 	/* Clear id, off, and union(map_ptr, range) */
1110 	memset(((u8 *)reg) + sizeof(reg->type), 0,
1111 	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1112 	___mark_reg_known(reg, imm);
1113 }
1114 
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1115 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1116 {
1117 	reg->var_off = tnum_const_subreg(reg->var_off, imm);
1118 	reg->s32_min_value = (s32)imm;
1119 	reg->s32_max_value = (s32)imm;
1120 	reg->u32_min_value = (u32)imm;
1121 	reg->u32_max_value = (u32)imm;
1122 }
1123 
1124 /* Mark the 'variable offset' part of a register as zero.  This should be
1125  * used only on registers holding a pointer type.
1126  */
__mark_reg_known_zero(struct bpf_reg_state * reg)1127 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1128 {
1129 	__mark_reg_known(reg, 0);
1130 }
1131 
__mark_reg_const_zero(struct bpf_reg_state * reg)1132 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1133 {
1134 	__mark_reg_known(reg, 0);
1135 	reg->type = SCALAR_VALUE;
1136 }
1137 
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1138 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1139 				struct bpf_reg_state *regs, u32 regno)
1140 {
1141 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1142 		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1143 		/* Something bad happened, let's kill all regs */
1144 		for (regno = 0; regno < MAX_BPF_REG; regno++)
1145 			__mark_reg_not_init(env, regs + regno);
1146 		return;
1147 	}
1148 	__mark_reg_known_zero(regs + regno);
1149 }
1150 
mark_ptr_not_null_reg(struct bpf_reg_state * reg)1151 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1152 {
1153 	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1154 		const struct bpf_map *map = reg->map_ptr;
1155 
1156 		if (map->inner_map_meta) {
1157 			reg->type = CONST_PTR_TO_MAP;
1158 			reg->map_ptr = map->inner_map_meta;
1159 			/* transfer reg's id which is unique for every map_lookup_elem
1160 			 * as UID of the inner map.
1161 			 */
1162 			if (map_value_has_timer(map->inner_map_meta))
1163 				reg->map_uid = reg->id;
1164 		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1165 			reg->type = PTR_TO_XDP_SOCK;
1166 		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1167 			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1168 			reg->type = PTR_TO_SOCKET;
1169 		} else {
1170 			reg->type = PTR_TO_MAP_VALUE;
1171 		}
1172 		return;
1173 	}
1174 
1175 	reg->type &= ~PTR_MAYBE_NULL;
1176 }
1177 
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1178 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1179 {
1180 	return type_is_pkt_pointer(reg->type);
1181 }
1182 
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1183 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1184 {
1185 	return reg_is_pkt_pointer(reg) ||
1186 	       reg->type == PTR_TO_PACKET_END;
1187 }
1188 
1189 /* 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)1190 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1191 				    enum bpf_reg_type which)
1192 {
1193 	/* The register can already have a range from prior markings.
1194 	 * This is fine as long as it hasn't been advanced from its
1195 	 * origin.
1196 	 */
1197 	return reg->type == which &&
1198 	       reg->id == 0 &&
1199 	       reg->off == 0 &&
1200 	       tnum_equals_const(reg->var_off, 0);
1201 }
1202 
1203 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1204 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1205 {
1206 	reg->smin_value = S64_MIN;
1207 	reg->smax_value = S64_MAX;
1208 	reg->umin_value = 0;
1209 	reg->umax_value = U64_MAX;
1210 
1211 	reg->s32_min_value = S32_MIN;
1212 	reg->s32_max_value = S32_MAX;
1213 	reg->u32_min_value = 0;
1214 	reg->u32_max_value = U32_MAX;
1215 }
1216 
__mark_reg64_unbounded(struct bpf_reg_state * reg)1217 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1218 {
1219 	reg->smin_value = S64_MIN;
1220 	reg->smax_value = S64_MAX;
1221 	reg->umin_value = 0;
1222 	reg->umax_value = U64_MAX;
1223 }
1224 
__mark_reg32_unbounded(struct bpf_reg_state * reg)1225 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1226 {
1227 	reg->s32_min_value = S32_MIN;
1228 	reg->s32_max_value = S32_MAX;
1229 	reg->u32_min_value = 0;
1230 	reg->u32_max_value = U32_MAX;
1231 }
1232 
__update_reg32_bounds(struct bpf_reg_state * reg)1233 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1234 {
1235 	struct tnum var32_off = tnum_subreg(reg->var_off);
1236 
1237 	/* min signed is max(sign bit) | min(other bits) */
1238 	reg->s32_min_value = max_t(s32, reg->s32_min_value,
1239 			var32_off.value | (var32_off.mask & S32_MIN));
1240 	/* max signed is min(sign bit) | max(other bits) */
1241 	reg->s32_max_value = min_t(s32, reg->s32_max_value,
1242 			var32_off.value | (var32_off.mask & S32_MAX));
1243 	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1244 	reg->u32_max_value = min(reg->u32_max_value,
1245 				 (u32)(var32_off.value | var32_off.mask));
1246 }
1247 
__update_reg64_bounds(struct bpf_reg_state * reg)1248 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1249 {
1250 	/* min signed is max(sign bit) | min(other bits) */
1251 	reg->smin_value = max_t(s64, reg->smin_value,
1252 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
1253 	/* max signed is min(sign bit) | max(other bits) */
1254 	reg->smax_value = min_t(s64, reg->smax_value,
1255 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
1256 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
1257 	reg->umax_value = min(reg->umax_value,
1258 			      reg->var_off.value | reg->var_off.mask);
1259 }
1260 
__update_reg_bounds(struct bpf_reg_state * reg)1261 static void __update_reg_bounds(struct bpf_reg_state *reg)
1262 {
1263 	__update_reg32_bounds(reg);
1264 	__update_reg64_bounds(reg);
1265 }
1266 
1267 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1268 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1269 {
1270 	/* Learn sign from signed bounds.
1271 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1272 	 * are the same, so combine.  This works even in the negative case, e.g.
1273 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1274 	 */
1275 	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1276 		reg->s32_min_value = reg->u32_min_value =
1277 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1278 		reg->s32_max_value = reg->u32_max_value =
1279 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1280 		return;
1281 	}
1282 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1283 	 * boundary, so we must be careful.
1284 	 */
1285 	if ((s32)reg->u32_max_value >= 0) {
1286 		/* Positive.  We can't learn anything from the smin, but smax
1287 		 * is positive, hence safe.
1288 		 */
1289 		reg->s32_min_value = reg->u32_min_value;
1290 		reg->s32_max_value = reg->u32_max_value =
1291 			min_t(u32, reg->s32_max_value, reg->u32_max_value);
1292 	} else if ((s32)reg->u32_min_value < 0) {
1293 		/* Negative.  We can't learn anything from the smax, but smin
1294 		 * is negative, hence safe.
1295 		 */
1296 		reg->s32_min_value = reg->u32_min_value =
1297 			max_t(u32, reg->s32_min_value, reg->u32_min_value);
1298 		reg->s32_max_value = reg->u32_max_value;
1299 	}
1300 }
1301 
__reg64_deduce_bounds(struct bpf_reg_state * reg)1302 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1303 {
1304 	/* Learn sign from signed bounds.
1305 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
1306 	 * are the same, so combine.  This works even in the negative case, e.g.
1307 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1308 	 */
1309 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
1310 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1311 							  reg->umin_value);
1312 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1313 							  reg->umax_value);
1314 		return;
1315 	}
1316 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
1317 	 * boundary, so we must be careful.
1318 	 */
1319 	if ((s64)reg->umax_value >= 0) {
1320 		/* Positive.  We can't learn anything from the smin, but smax
1321 		 * is positive, hence safe.
1322 		 */
1323 		reg->smin_value = reg->umin_value;
1324 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1325 							  reg->umax_value);
1326 	} else if ((s64)reg->umin_value < 0) {
1327 		/* Negative.  We can't learn anything from the smax, but smin
1328 		 * is negative, hence safe.
1329 		 */
1330 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1331 							  reg->umin_value);
1332 		reg->smax_value = reg->umax_value;
1333 	}
1334 }
1335 
__reg_deduce_bounds(struct bpf_reg_state * reg)1336 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1337 {
1338 	__reg32_deduce_bounds(reg);
1339 	__reg64_deduce_bounds(reg);
1340 }
1341 
1342 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1343 static void __reg_bound_offset(struct bpf_reg_state *reg)
1344 {
1345 	struct tnum var64_off = tnum_intersect(reg->var_off,
1346 					       tnum_range(reg->umin_value,
1347 							  reg->umax_value));
1348 	struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1349 						tnum_range(reg->u32_min_value,
1350 							   reg->u32_max_value));
1351 
1352 	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1353 }
1354 
reg_bounds_sync(struct bpf_reg_state * reg)1355 static void reg_bounds_sync(struct bpf_reg_state *reg)
1356 {
1357 	/* We might have learned new bounds from the var_off. */
1358 	__update_reg_bounds(reg);
1359 	/* We might have learned something about the sign bit. */
1360 	__reg_deduce_bounds(reg);
1361 	/* We might have learned some bits from the bounds. */
1362 	__reg_bound_offset(reg);
1363 	/* Intersecting with the old var_off might have improved our bounds
1364 	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1365 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
1366 	 */
1367 	__update_reg_bounds(reg);
1368 }
1369 
__reg32_bound_s64(s32 a)1370 static bool __reg32_bound_s64(s32 a)
1371 {
1372 	return a >= 0 && a <= S32_MAX;
1373 }
1374 
__reg_assign_32_into_64(struct bpf_reg_state * reg)1375 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1376 {
1377 	reg->umin_value = reg->u32_min_value;
1378 	reg->umax_value = reg->u32_max_value;
1379 
1380 	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1381 	 * be positive otherwise set to worse case bounds and refine later
1382 	 * from tnum.
1383 	 */
1384 	if (__reg32_bound_s64(reg->s32_min_value) &&
1385 	    __reg32_bound_s64(reg->s32_max_value)) {
1386 		reg->smin_value = reg->s32_min_value;
1387 		reg->smax_value = reg->s32_max_value;
1388 	} else {
1389 		reg->smin_value = 0;
1390 		reg->smax_value = U32_MAX;
1391 	}
1392 }
1393 
__reg_combine_32_into_64(struct bpf_reg_state * reg)1394 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1395 {
1396 	/* special case when 64-bit register has upper 32-bit register
1397 	 * zeroed. Typically happens after zext or <<32, >>32 sequence
1398 	 * allowing us to use 32-bit bounds directly,
1399 	 */
1400 	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1401 		__reg_assign_32_into_64(reg);
1402 	} else {
1403 		/* Otherwise the best we can do is push lower 32bit known and
1404 		 * unknown bits into register (var_off set from jmp logic)
1405 		 * then learn as much as possible from the 64-bit tnum
1406 		 * known and unknown bits. The previous smin/smax bounds are
1407 		 * invalid here because of jmp32 compare so mark them unknown
1408 		 * so they do not impact tnum bounds calculation.
1409 		 */
1410 		__mark_reg64_unbounded(reg);
1411 	}
1412 	reg_bounds_sync(reg);
1413 }
1414 
__reg64_bound_s32(s64 a)1415 static bool __reg64_bound_s32(s64 a)
1416 {
1417 	return a >= S32_MIN && a <= S32_MAX;
1418 }
1419 
__reg64_bound_u32(u64 a)1420 static bool __reg64_bound_u32(u64 a)
1421 {
1422 	return a >= U32_MIN && a <= U32_MAX;
1423 }
1424 
__reg_combine_64_into_32(struct bpf_reg_state * reg)1425 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1426 {
1427 	__mark_reg32_unbounded(reg);
1428 	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1429 		reg->s32_min_value = (s32)reg->smin_value;
1430 		reg->s32_max_value = (s32)reg->smax_value;
1431 	}
1432 	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1433 		reg->u32_min_value = (u32)reg->umin_value;
1434 		reg->u32_max_value = (u32)reg->umax_value;
1435 	}
1436 	reg_bounds_sync(reg);
1437 }
1438 
1439 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1440 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1441 			       struct bpf_reg_state *reg)
1442 {
1443 	/*
1444 	 * Clear type, id, off, and union(map_ptr, range) and
1445 	 * padding between 'type' and union
1446 	 */
1447 	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1448 	reg->type = SCALAR_VALUE;
1449 	reg->var_off = tnum_unknown;
1450 	reg->frameno = 0;
1451 	reg->precise = !env->bpf_capable;
1452 	__mark_reg_unbounded(reg);
1453 }
1454 
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1455 static void mark_reg_unknown(struct bpf_verifier_env *env,
1456 			     struct bpf_reg_state *regs, u32 regno)
1457 {
1458 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1459 		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1460 		/* Something bad happened, let's kill all regs except FP */
1461 		for (regno = 0; regno < BPF_REG_FP; regno++)
1462 			__mark_reg_not_init(env, regs + regno);
1463 		return;
1464 	}
1465 	__mark_reg_unknown(env, regs + regno);
1466 }
1467 
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1468 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1469 				struct bpf_reg_state *reg)
1470 {
1471 	__mark_reg_unknown(env, reg);
1472 	reg->type = NOT_INIT;
1473 }
1474 
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1475 static void mark_reg_not_init(struct bpf_verifier_env *env,
1476 			      struct bpf_reg_state *regs, u32 regno)
1477 {
1478 	if (WARN_ON(regno >= MAX_BPF_REG)) {
1479 		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1480 		/* Something bad happened, let's kill all regs except FP */
1481 		for (regno = 0; regno < BPF_REG_FP; regno++)
1482 			__mark_reg_not_init(env, regs + regno);
1483 		return;
1484 	}
1485 	__mark_reg_not_init(env, regs + regno);
1486 }
1487 
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)1488 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1489 			    struct bpf_reg_state *regs, u32 regno,
1490 			    enum bpf_reg_type reg_type,
1491 			    struct btf *btf, u32 btf_id)
1492 {
1493 	if (reg_type == SCALAR_VALUE) {
1494 		mark_reg_unknown(env, regs, regno);
1495 		return;
1496 	}
1497 	mark_reg_known_zero(env, regs, regno);
1498 	regs[regno].type = PTR_TO_BTF_ID;
1499 	regs[regno].btf = btf;
1500 	regs[regno].btf_id = btf_id;
1501 }
1502 
1503 #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1504 static void init_reg_state(struct bpf_verifier_env *env,
1505 			   struct bpf_func_state *state)
1506 {
1507 	struct bpf_reg_state *regs = state->regs;
1508 	int i;
1509 
1510 	for (i = 0; i < MAX_BPF_REG; i++) {
1511 		mark_reg_not_init(env, regs, i);
1512 		regs[i].live = REG_LIVE_NONE;
1513 		regs[i].parent = NULL;
1514 		regs[i].subreg_def = DEF_NOT_SUBREG;
1515 	}
1516 
1517 	/* frame pointer */
1518 	regs[BPF_REG_FP].type = PTR_TO_STACK;
1519 	mark_reg_known_zero(env, regs, BPF_REG_FP);
1520 	regs[BPF_REG_FP].frameno = state->frameno;
1521 }
1522 
1523 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1524 static void init_func_state(struct bpf_verifier_env *env,
1525 			    struct bpf_func_state *state,
1526 			    int callsite, int frameno, int subprogno)
1527 {
1528 	state->callsite = callsite;
1529 	state->frameno = frameno;
1530 	state->subprogno = subprogno;
1531 	init_reg_state(env, state);
1532 }
1533 
1534 /* 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)1535 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1536 						int insn_idx, int prev_insn_idx,
1537 						int subprog)
1538 {
1539 	struct bpf_verifier_stack_elem *elem;
1540 	struct bpf_func_state *frame;
1541 
1542 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1543 	if (!elem)
1544 		goto err;
1545 
1546 	elem->insn_idx = insn_idx;
1547 	elem->prev_insn_idx = prev_insn_idx;
1548 	elem->next = env->head;
1549 	elem->log_pos = env->log.len_used;
1550 	env->head = elem;
1551 	env->stack_size++;
1552 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1553 		verbose(env,
1554 			"The sequence of %d jumps is too complex for async cb.\n",
1555 			env->stack_size);
1556 		goto err;
1557 	}
1558 	/* Unlike push_stack() do not copy_verifier_state().
1559 	 * The caller state doesn't matter.
1560 	 * This is async callback. It starts in a fresh stack.
1561 	 * Initialize it similar to do_check_common().
1562 	 */
1563 	elem->st.branches = 1;
1564 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1565 	if (!frame)
1566 		goto err;
1567 	init_func_state(env, frame,
1568 			BPF_MAIN_FUNC /* callsite */,
1569 			0 /* frameno within this callchain */,
1570 			subprog /* subprog number within this prog */);
1571 	elem->st.frame[0] = frame;
1572 	return &elem->st;
1573 err:
1574 	free_verifier_state(env->cur_state, true);
1575 	env->cur_state = NULL;
1576 	/* pop all elements and return */
1577 	while (!pop_stack(env, NULL, NULL, false));
1578 	return NULL;
1579 }
1580 
1581 
1582 enum reg_arg_type {
1583 	SRC_OP,		/* register is used as source operand */
1584 	DST_OP,		/* register is used as destination operand */
1585 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1586 };
1587 
cmp_subprogs(const void * a,const void * b)1588 static int cmp_subprogs(const void *a, const void *b)
1589 {
1590 	return ((struct bpf_subprog_info *)a)->start -
1591 	       ((struct bpf_subprog_info *)b)->start;
1592 }
1593 
find_subprog(struct bpf_verifier_env * env,int off)1594 static int find_subprog(struct bpf_verifier_env *env, int off)
1595 {
1596 	struct bpf_subprog_info *p;
1597 
1598 	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1599 		    sizeof(env->subprog_info[0]), cmp_subprogs);
1600 	if (!p)
1601 		return -ENOENT;
1602 	return p - env->subprog_info;
1603 
1604 }
1605 
add_subprog(struct bpf_verifier_env * env,int off)1606 static int add_subprog(struct bpf_verifier_env *env, int off)
1607 {
1608 	int insn_cnt = env->prog->len;
1609 	int ret;
1610 
1611 	if (off >= insn_cnt || off < 0) {
1612 		verbose(env, "call to invalid destination\n");
1613 		return -EINVAL;
1614 	}
1615 	ret = find_subprog(env, off);
1616 	if (ret >= 0)
1617 		return ret;
1618 	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1619 		verbose(env, "too many subprograms\n");
1620 		return -E2BIG;
1621 	}
1622 	/* determine subprog starts. The end is one before the next starts */
1623 	env->subprog_info[env->subprog_cnt++].start = off;
1624 	sort(env->subprog_info, env->subprog_cnt,
1625 	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1626 	return env->subprog_cnt - 1;
1627 }
1628 
1629 struct bpf_kfunc_desc {
1630 	struct btf_func_model func_model;
1631 	u32 func_id;
1632 	s32 imm;
1633 };
1634 
1635 #define MAX_KFUNC_DESCS 256
1636 struct bpf_kfunc_desc_tab {
1637 	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1638 	u32 nr_descs;
1639 };
1640 
kfunc_desc_cmp_by_id(const void * a,const void * b)1641 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1642 {
1643 	const struct bpf_kfunc_desc *d0 = a;
1644 	const struct bpf_kfunc_desc *d1 = b;
1645 
1646 	/* func_id is not greater than BTF_MAX_TYPE */
1647 	return d0->func_id - d1->func_id;
1648 }
1649 
1650 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id)1651 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1652 {
1653 	struct bpf_kfunc_desc desc = {
1654 		.func_id = func_id,
1655 	};
1656 	struct bpf_kfunc_desc_tab *tab;
1657 
1658 	tab = prog->aux->kfunc_tab;
1659 	return bsearch(&desc, tab->descs, tab->nr_descs,
1660 		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1661 }
1662 
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id)1663 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1664 {
1665 	const struct btf_type *func, *func_proto;
1666 	struct bpf_kfunc_desc_tab *tab;
1667 	struct bpf_prog_aux *prog_aux;
1668 	struct bpf_kfunc_desc *desc;
1669 	const char *func_name;
1670 	unsigned long addr;
1671 	int err;
1672 
1673 	prog_aux = env->prog->aux;
1674 	tab = prog_aux->kfunc_tab;
1675 	if (!tab) {
1676 		if (!btf_vmlinux) {
1677 			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1678 			return -ENOTSUPP;
1679 		}
1680 
1681 		if (!env->prog->jit_requested) {
1682 			verbose(env, "JIT is required for calling kernel function\n");
1683 			return -ENOTSUPP;
1684 		}
1685 
1686 		if (!bpf_jit_supports_kfunc_call()) {
1687 			verbose(env, "JIT does not support calling kernel function\n");
1688 			return -ENOTSUPP;
1689 		}
1690 
1691 		if (!env->prog->gpl_compatible) {
1692 			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1693 			return -EINVAL;
1694 		}
1695 
1696 		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1697 		if (!tab)
1698 			return -ENOMEM;
1699 		prog_aux->kfunc_tab = tab;
1700 	}
1701 
1702 	if (find_kfunc_desc(env->prog, func_id))
1703 		return 0;
1704 
1705 	if (tab->nr_descs == MAX_KFUNC_DESCS) {
1706 		verbose(env, "too many different kernel function calls\n");
1707 		return -E2BIG;
1708 	}
1709 
1710 	func = btf_type_by_id(btf_vmlinux, func_id);
1711 	if (!func || !btf_type_is_func(func)) {
1712 		verbose(env, "kernel btf_id %u is not a function\n",
1713 			func_id);
1714 		return -EINVAL;
1715 	}
1716 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
1717 	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1718 		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1719 			func_id);
1720 		return -EINVAL;
1721 	}
1722 
1723 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1724 	addr = kallsyms_lookup_name(func_name);
1725 	if (!addr) {
1726 		verbose(env, "cannot find address for kernel function %s\n",
1727 			func_name);
1728 		return -EINVAL;
1729 	}
1730 
1731 	desc = &tab->descs[tab->nr_descs++];
1732 	desc->func_id = func_id;
1733 	desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1734 	err = btf_distill_func_proto(&env->log, btf_vmlinux,
1735 				     func_proto, func_name,
1736 				     &desc->func_model);
1737 	if (!err)
1738 		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1739 		     kfunc_desc_cmp_by_id, NULL);
1740 	return err;
1741 }
1742 
kfunc_desc_cmp_by_imm(const void * a,const void * b)1743 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1744 {
1745 	const struct bpf_kfunc_desc *d0 = a;
1746 	const struct bpf_kfunc_desc *d1 = b;
1747 
1748 	if (d0->imm > d1->imm)
1749 		return 1;
1750 	else if (d0->imm < d1->imm)
1751 		return -1;
1752 	return 0;
1753 }
1754 
sort_kfunc_descs_by_imm(struct bpf_prog * prog)1755 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1756 {
1757 	struct bpf_kfunc_desc_tab *tab;
1758 
1759 	tab = prog->aux->kfunc_tab;
1760 	if (!tab)
1761 		return;
1762 
1763 	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1764 	     kfunc_desc_cmp_by_imm, NULL);
1765 }
1766 
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)1767 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1768 {
1769 	return !!prog->aux->kfunc_tab;
1770 }
1771 
1772 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)1773 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1774 			 const struct bpf_insn *insn)
1775 {
1776 	const struct bpf_kfunc_desc desc = {
1777 		.imm = insn->imm,
1778 	};
1779 	const struct bpf_kfunc_desc *res;
1780 	struct bpf_kfunc_desc_tab *tab;
1781 
1782 	tab = prog->aux->kfunc_tab;
1783 	res = bsearch(&desc, tab->descs, tab->nr_descs,
1784 		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1785 
1786 	return res ? &res->func_model : NULL;
1787 }
1788 
add_subprog_and_kfunc(struct bpf_verifier_env * env)1789 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1790 {
1791 	struct bpf_subprog_info *subprog = env->subprog_info;
1792 	struct bpf_insn *insn = env->prog->insnsi;
1793 	int i, ret, insn_cnt = env->prog->len;
1794 
1795 	/* Add entry function. */
1796 	ret = add_subprog(env, 0);
1797 	if (ret)
1798 		return ret;
1799 
1800 	for (i = 0; i < insn_cnt; i++, insn++) {
1801 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1802 		    !bpf_pseudo_kfunc_call(insn))
1803 			continue;
1804 
1805 		if (!env->bpf_capable) {
1806 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1807 			return -EPERM;
1808 		}
1809 
1810 		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
1811 			ret = add_subprog(env, i + insn->imm + 1);
1812 		else
1813 			ret = add_kfunc_call(env, insn->imm);
1814 
1815 		if (ret < 0)
1816 			return ret;
1817 	}
1818 
1819 	/* Add a fake 'exit' subprog which could simplify subprog iteration
1820 	 * logic. 'subprog_cnt' should not be increased.
1821 	 */
1822 	subprog[env->subprog_cnt].start = insn_cnt;
1823 
1824 	if (env->log.level & BPF_LOG_LEVEL2)
1825 		for (i = 0; i < env->subprog_cnt; i++)
1826 			verbose(env, "func#%d @%d\n", i, subprog[i].start);
1827 
1828 	return 0;
1829 }
1830 
check_subprogs(struct bpf_verifier_env * env)1831 static int check_subprogs(struct bpf_verifier_env *env)
1832 {
1833 	int i, subprog_start, subprog_end, off, cur_subprog = 0;
1834 	struct bpf_subprog_info *subprog = env->subprog_info;
1835 	struct bpf_insn *insn = env->prog->insnsi;
1836 	int insn_cnt = env->prog->len;
1837 
1838 	/* now check that all jumps are within the same subprog */
1839 	subprog_start = subprog[cur_subprog].start;
1840 	subprog_end = subprog[cur_subprog + 1].start;
1841 	for (i = 0; i < insn_cnt; i++) {
1842 		u8 code = insn[i].code;
1843 
1844 		if (code == (BPF_JMP | BPF_CALL) &&
1845 		    insn[i].imm == BPF_FUNC_tail_call &&
1846 		    insn[i].src_reg != BPF_PSEUDO_CALL)
1847 			subprog[cur_subprog].has_tail_call = true;
1848 		if (BPF_CLASS(code) == BPF_LD &&
1849 		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1850 			subprog[cur_subprog].has_ld_abs = true;
1851 		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1852 			goto next;
1853 		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1854 			goto next;
1855 		off = i + insn[i].off + 1;
1856 		if (off < subprog_start || off >= subprog_end) {
1857 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
1858 			return -EINVAL;
1859 		}
1860 next:
1861 		if (i == subprog_end - 1) {
1862 			/* to avoid fall-through from one subprog into another
1863 			 * the last insn of the subprog should be either exit
1864 			 * or unconditional jump back
1865 			 */
1866 			if (code != (BPF_JMP | BPF_EXIT) &&
1867 			    code != (BPF_JMP | BPF_JA)) {
1868 				verbose(env, "last insn is not an exit or jmp\n");
1869 				return -EINVAL;
1870 			}
1871 			subprog_start = subprog_end;
1872 			cur_subprog++;
1873 			if (cur_subprog < env->subprog_cnt)
1874 				subprog_end = subprog[cur_subprog + 1].start;
1875 		}
1876 	}
1877 	return 0;
1878 }
1879 
1880 /* Parentage chain of this register (or stack slot) should take care of all
1881  * issues like callee-saved registers, stack slot allocation time, etc.
1882  */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1883 static int mark_reg_read(struct bpf_verifier_env *env,
1884 			 const struct bpf_reg_state *state,
1885 			 struct bpf_reg_state *parent, u8 flag)
1886 {
1887 	bool writes = parent == state->parent; /* Observe write marks */
1888 	int cnt = 0;
1889 
1890 	while (parent) {
1891 		/* if read wasn't screened by an earlier write ... */
1892 		if (writes && state->live & REG_LIVE_WRITTEN)
1893 			break;
1894 		if (parent->live & REG_LIVE_DONE) {
1895 			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1896 				reg_type_str(env, parent->type),
1897 				parent->var_off.value, parent->off);
1898 			return -EFAULT;
1899 		}
1900 		/* The first condition is more likely to be true than the
1901 		 * second, checked it first.
1902 		 */
1903 		if ((parent->live & REG_LIVE_READ) == flag ||
1904 		    parent->live & REG_LIVE_READ64)
1905 			/* The parentage chain never changes and
1906 			 * this parent was already marked as LIVE_READ.
1907 			 * There is no need to keep walking the chain again and
1908 			 * keep re-marking all parents as LIVE_READ.
1909 			 * This case happens when the same register is read
1910 			 * multiple times without writes into it in-between.
1911 			 * Also, if parent has the stronger REG_LIVE_READ64 set,
1912 			 * then no need to set the weak REG_LIVE_READ32.
1913 			 */
1914 			break;
1915 		/* ... then we depend on parent's value */
1916 		parent->live |= flag;
1917 		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1918 		if (flag == REG_LIVE_READ64)
1919 			parent->live &= ~REG_LIVE_READ32;
1920 		state = parent;
1921 		parent = state->parent;
1922 		writes = true;
1923 		cnt++;
1924 	}
1925 
1926 	if (env->longest_mark_read_walk < cnt)
1927 		env->longest_mark_read_walk = cnt;
1928 	return 0;
1929 }
1930 
1931 /* This function is supposed to be used by the following 32-bit optimization
1932  * code only. It returns TRUE if the source or destination register operates
1933  * on 64-bit, otherwise return FALSE.
1934  */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1935 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1936 		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1937 {
1938 	u8 code, class, op;
1939 
1940 	code = insn->code;
1941 	class = BPF_CLASS(code);
1942 	op = BPF_OP(code);
1943 	if (class == BPF_JMP) {
1944 		/* BPF_EXIT for "main" will reach here. Return TRUE
1945 		 * conservatively.
1946 		 */
1947 		if (op == BPF_EXIT)
1948 			return true;
1949 		if (op == BPF_CALL) {
1950 			/* BPF to BPF call will reach here because of marking
1951 			 * caller saved clobber with DST_OP_NO_MARK for which we
1952 			 * don't care the register def because they are anyway
1953 			 * marked as NOT_INIT already.
1954 			 */
1955 			if (insn->src_reg == BPF_PSEUDO_CALL)
1956 				return false;
1957 			/* Helper call will reach here because of arg type
1958 			 * check, conservatively return TRUE.
1959 			 */
1960 			if (t == SRC_OP)
1961 				return true;
1962 
1963 			return false;
1964 		}
1965 	}
1966 
1967 	if (class == BPF_ALU64 || class == BPF_JMP ||
1968 	    /* BPF_END always use BPF_ALU class. */
1969 	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1970 		return true;
1971 
1972 	if (class == BPF_ALU || class == BPF_JMP32)
1973 		return false;
1974 
1975 	if (class == BPF_LDX) {
1976 		if (t != SRC_OP)
1977 			return BPF_SIZE(code) == BPF_DW;
1978 		/* LDX source must be ptr. */
1979 		return true;
1980 	}
1981 
1982 	if (class == BPF_STX) {
1983 		/* BPF_STX (including atomic variants) has multiple source
1984 		 * operands, one of which is a ptr. Check whether the caller is
1985 		 * asking about it.
1986 		 */
1987 		if (t == SRC_OP && reg->type != SCALAR_VALUE)
1988 			return true;
1989 		return BPF_SIZE(code) == BPF_DW;
1990 	}
1991 
1992 	if (class == BPF_LD) {
1993 		u8 mode = BPF_MODE(code);
1994 
1995 		/* LD_IMM64 */
1996 		if (mode == BPF_IMM)
1997 			return true;
1998 
1999 		/* Both LD_IND and LD_ABS return 32-bit data. */
2000 		if (t != SRC_OP)
2001 			return  false;
2002 
2003 		/* Implicit ctx ptr. */
2004 		if (regno == BPF_REG_6)
2005 			return true;
2006 
2007 		/* Explicit source could be any width. */
2008 		return true;
2009 	}
2010 
2011 	if (class == BPF_ST)
2012 		/* The only source register for BPF_ST is a ptr. */
2013 		return true;
2014 
2015 	/* Conservatively return true at default. */
2016 	return true;
2017 }
2018 
2019 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)2020 static int insn_def_regno(const struct bpf_insn *insn)
2021 {
2022 	switch (BPF_CLASS(insn->code)) {
2023 	case BPF_JMP:
2024 	case BPF_JMP32:
2025 	case BPF_ST:
2026 		return -1;
2027 	case BPF_STX:
2028 		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2029 		    (insn->imm & BPF_FETCH)) {
2030 			if (insn->imm == BPF_CMPXCHG)
2031 				return BPF_REG_0;
2032 			else
2033 				return insn->src_reg;
2034 		} else {
2035 			return -1;
2036 		}
2037 	default:
2038 		return insn->dst_reg;
2039 	}
2040 }
2041 
2042 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)2043 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2044 {
2045 	int dst_reg = insn_def_regno(insn);
2046 
2047 	if (dst_reg == -1)
2048 		return false;
2049 
2050 	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2051 }
2052 
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)2053 static void mark_insn_zext(struct bpf_verifier_env *env,
2054 			   struct bpf_reg_state *reg)
2055 {
2056 	s32 def_idx = reg->subreg_def;
2057 
2058 	if (def_idx == DEF_NOT_SUBREG)
2059 		return;
2060 
2061 	env->insn_aux_data[def_idx - 1].zext_dst = true;
2062 	/* The dst will be zero extended, so won't be sub-register anymore. */
2063 	reg->subreg_def = DEF_NOT_SUBREG;
2064 }
2065 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)2066 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2067 			 enum reg_arg_type t)
2068 {
2069 	struct bpf_verifier_state *vstate = env->cur_state;
2070 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
2071 	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2072 	struct bpf_reg_state *reg, *regs = state->regs;
2073 	bool rw64;
2074 
2075 	if (regno >= MAX_BPF_REG) {
2076 		verbose(env, "R%d is invalid\n", regno);
2077 		return -EINVAL;
2078 	}
2079 
2080 	reg = &regs[regno];
2081 	rw64 = is_reg64(env, insn, regno, reg, t);
2082 	if (t == SRC_OP) {
2083 		/* check whether register used as source operand can be read */
2084 		if (reg->type == NOT_INIT) {
2085 			verbose(env, "R%d !read_ok\n", regno);
2086 			return -EACCES;
2087 		}
2088 		/* We don't need to worry about FP liveness because it's read-only */
2089 		if (regno == BPF_REG_FP)
2090 			return 0;
2091 
2092 		if (rw64)
2093 			mark_insn_zext(env, reg);
2094 
2095 		return mark_reg_read(env, reg, reg->parent,
2096 				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2097 	} else {
2098 		/* check whether register used as dest operand can be written to */
2099 		if (regno == BPF_REG_FP) {
2100 			verbose(env, "frame pointer is read only\n");
2101 			return -EACCES;
2102 		}
2103 		reg->live |= REG_LIVE_WRITTEN;
2104 		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2105 		if (t == DST_OP)
2106 			mark_reg_unknown(env, regs, regno);
2107 	}
2108 	return 0;
2109 }
2110 
2111 /* 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)2112 static int push_jmp_history(struct bpf_verifier_env *env,
2113 			    struct bpf_verifier_state *cur)
2114 {
2115 	u32 cnt = cur->jmp_history_cnt;
2116 	struct bpf_idx_pair *p;
2117 
2118 	cnt++;
2119 	p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2120 	if (!p)
2121 		return -ENOMEM;
2122 	p[cnt - 1].idx = env->insn_idx;
2123 	p[cnt - 1].prev_idx = env->prev_insn_idx;
2124 	cur->jmp_history = p;
2125 	cur->jmp_history_cnt = cnt;
2126 	return 0;
2127 }
2128 
2129 /* Backtrack one insn at a time. If idx is not at the top of recorded
2130  * history then previous instruction came from straight line execution.
2131  */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)2132 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2133 			     u32 *history)
2134 {
2135 	u32 cnt = *history;
2136 
2137 	if (cnt && st->jmp_history[cnt - 1].idx == i) {
2138 		i = st->jmp_history[cnt - 1].prev_idx;
2139 		(*history)--;
2140 	} else {
2141 		i--;
2142 	}
2143 	return i;
2144 }
2145 
disasm_kfunc_name(void * data,const struct bpf_insn * insn)2146 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2147 {
2148 	const struct btf_type *func;
2149 
2150 	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2151 		return NULL;
2152 
2153 	func = btf_type_by_id(btf_vmlinux, insn->imm);
2154 	return btf_name_by_offset(btf_vmlinux, func->name_off);
2155 }
2156 
2157 /* For given verifier state backtrack_insn() is called from the last insn to
2158  * the first insn. Its purpose is to compute a bitmask of registers and
2159  * stack slots that needs precision in the parent verifier state.
2160  */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)2161 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2162 			  u32 *reg_mask, u64 *stack_mask)
2163 {
2164 	const struct bpf_insn_cbs cbs = {
2165 		.cb_call	= disasm_kfunc_name,
2166 		.cb_print	= verbose,
2167 		.private_data	= env,
2168 	};
2169 	struct bpf_insn *insn = env->prog->insnsi + idx;
2170 	u8 class = BPF_CLASS(insn->code);
2171 	u8 opcode = BPF_OP(insn->code);
2172 	u8 mode = BPF_MODE(insn->code);
2173 	u32 dreg = 1u << insn->dst_reg;
2174 	u32 sreg = 1u << insn->src_reg;
2175 	u32 spi;
2176 
2177 	if (insn->code == 0)
2178 		return 0;
2179 	if (env->log.level & BPF_LOG_LEVEL) {
2180 		verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2181 		verbose(env, "%d: ", idx);
2182 		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2183 	}
2184 
2185 	if (class == BPF_ALU || class == BPF_ALU64) {
2186 		if (!(*reg_mask & dreg))
2187 			return 0;
2188 		if (opcode == BPF_END || opcode == BPF_NEG) {
2189 			/* sreg is reserved and unused
2190 			 * dreg still need precision before this insn
2191 			 */
2192 			return 0;
2193 		} else if (opcode == BPF_MOV) {
2194 			if (BPF_SRC(insn->code) == BPF_X) {
2195 				/* dreg = sreg
2196 				 * dreg needs precision after this insn
2197 				 * sreg needs precision before this insn
2198 				 */
2199 				*reg_mask &= ~dreg;
2200 				*reg_mask |= sreg;
2201 			} else {
2202 				/* dreg = K
2203 				 * dreg needs precision after this insn.
2204 				 * Corresponding register is already marked
2205 				 * as precise=true in this verifier state.
2206 				 * No further markings in parent are necessary
2207 				 */
2208 				*reg_mask &= ~dreg;
2209 			}
2210 		} else {
2211 			if (BPF_SRC(insn->code) == BPF_X) {
2212 				/* dreg += sreg
2213 				 * both dreg and sreg need precision
2214 				 * before this insn
2215 				 */
2216 				*reg_mask |= sreg;
2217 			} /* else dreg += K
2218 			   * dreg still needs precision before this insn
2219 			   */
2220 		}
2221 	} else if (class == BPF_LDX) {
2222 		if (!(*reg_mask & dreg))
2223 			return 0;
2224 		*reg_mask &= ~dreg;
2225 
2226 		/* scalars can only be spilled into stack w/o losing precision.
2227 		 * Load from any other memory can be zero extended.
2228 		 * The desire to keep that precision is already indicated
2229 		 * by 'precise' mark in corresponding register of this state.
2230 		 * No further tracking necessary.
2231 		 */
2232 		if (insn->src_reg != BPF_REG_FP)
2233 			return 0;
2234 
2235 		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
2236 		 * that [fp - off] slot contains scalar that needs to be
2237 		 * tracked with precision
2238 		 */
2239 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2240 		if (spi >= 64) {
2241 			verbose(env, "BUG spi %d\n", spi);
2242 			WARN_ONCE(1, "verifier backtracking bug");
2243 			return -EFAULT;
2244 		}
2245 		*stack_mask |= 1ull << spi;
2246 	} else if (class == BPF_STX || class == BPF_ST) {
2247 		if (*reg_mask & dreg)
2248 			/* stx & st shouldn't be using _scalar_ dst_reg
2249 			 * to access memory. It means backtracking
2250 			 * encountered a case of pointer subtraction.
2251 			 */
2252 			return -ENOTSUPP;
2253 		/* scalars can only be spilled into stack */
2254 		if (insn->dst_reg != BPF_REG_FP)
2255 			return 0;
2256 		spi = (-insn->off - 1) / BPF_REG_SIZE;
2257 		if (spi >= 64) {
2258 			verbose(env, "BUG spi %d\n", spi);
2259 			WARN_ONCE(1, "verifier backtracking bug");
2260 			return -EFAULT;
2261 		}
2262 		if (!(*stack_mask & (1ull << spi)))
2263 			return 0;
2264 		*stack_mask &= ~(1ull << spi);
2265 		if (class == BPF_STX)
2266 			*reg_mask |= sreg;
2267 	} else if (class == BPF_JMP || class == BPF_JMP32) {
2268 		if (opcode == BPF_CALL) {
2269 			if (insn->src_reg == BPF_PSEUDO_CALL)
2270 				return -ENOTSUPP;
2271 			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
2272 			 * catch this error later. Make backtracking conservative
2273 			 * with ENOTSUPP.
2274 			 */
2275 			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2276 				return -ENOTSUPP;
2277 			/* BPF helpers that invoke callback subprogs are
2278 			 * equivalent to BPF_PSEUDO_CALL above
2279 			 */
2280 			if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2281 				return -ENOTSUPP;
2282 			/* regular helper call sets R0 */
2283 			*reg_mask &= ~1;
2284 			if (*reg_mask & 0x3f) {
2285 				/* if backtracing was looking for registers R1-R5
2286 				 * they should have been found already.
2287 				 */
2288 				verbose(env, "BUG regs %x\n", *reg_mask);
2289 				WARN_ONCE(1, "verifier backtracking bug");
2290 				return -EFAULT;
2291 			}
2292 		} else if (opcode == BPF_EXIT) {
2293 			return -ENOTSUPP;
2294 		} else if (BPF_SRC(insn->code) == BPF_X) {
2295 			if (!(*reg_mask & (dreg | sreg)))
2296 				return 0;
2297 			/* dreg <cond> sreg
2298 			 * Both dreg and sreg need precision before
2299 			 * this insn. If only sreg was marked precise
2300 			 * before it would be equally necessary to
2301 			 * propagate it to dreg.
2302 			 */
2303 			*reg_mask |= (sreg | dreg);
2304 			 /* else dreg <cond> K
2305 			  * Only dreg still needs precision before
2306 			  * this insn, so for the K-based conditional
2307 			  * there is nothing new to be marked.
2308 			  */
2309 		}
2310 	} else if (class == BPF_LD) {
2311 		if (!(*reg_mask & dreg))
2312 			return 0;
2313 		*reg_mask &= ~dreg;
2314 		/* It's ld_imm64 or ld_abs or ld_ind.
2315 		 * For ld_imm64 no further tracking of precision
2316 		 * into parent is necessary
2317 		 */
2318 		if (mode == BPF_IND || mode == BPF_ABS)
2319 			/* to be analyzed */
2320 			return -ENOTSUPP;
2321 	}
2322 	return 0;
2323 }
2324 
2325 /* the scalar precision tracking algorithm:
2326  * . at the start all registers have precise=false.
2327  * . scalar ranges are tracked as normal through alu and jmp insns.
2328  * . once precise value of the scalar register is used in:
2329  *   .  ptr + scalar alu
2330  *   . if (scalar cond K|scalar)
2331  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2332  *   backtrack through the verifier states and mark all registers and
2333  *   stack slots with spilled constants that these scalar regisers
2334  *   should be precise.
2335  * . during state pruning two registers (or spilled stack slots)
2336  *   are equivalent if both are not precise.
2337  *
2338  * Note the verifier cannot simply walk register parentage chain,
2339  * since many different registers and stack slots could have been
2340  * used to compute single precise scalar.
2341  *
2342  * The approach of starting with precise=true for all registers and then
2343  * backtrack to mark a register as not precise when the verifier detects
2344  * that program doesn't care about specific value (e.g., when helper
2345  * takes register as ARG_ANYTHING parameter) is not safe.
2346  *
2347  * It's ok to walk single parentage chain of the verifier states.
2348  * It's possible that this backtracking will go all the way till 1st insn.
2349  * All other branches will be explored for needing precision later.
2350  *
2351  * The backtracking needs to deal with cases like:
2352  *   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)
2353  * r9 -= r8
2354  * r5 = r9
2355  * if r5 > 0x79f goto pc+7
2356  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2357  * r5 += 1
2358  * ...
2359  * call bpf_perf_event_output#25
2360  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2361  *
2362  * and this case:
2363  * r6 = 1
2364  * call foo // uses callee's r6 inside to compute r0
2365  * r0 += r6
2366  * if r0 == 0 goto
2367  *
2368  * to track above reg_mask/stack_mask needs to be independent for each frame.
2369  *
2370  * Also if parent's curframe > frame where backtracking started,
2371  * the verifier need to mark registers in both frames, otherwise callees
2372  * may incorrectly prune callers. This is similar to
2373  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2374  *
2375  * For now backtracking falls back into conservative marking.
2376  */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2377 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2378 				     struct bpf_verifier_state *st)
2379 {
2380 	struct bpf_func_state *func;
2381 	struct bpf_reg_state *reg;
2382 	int i, j;
2383 
2384 	/* big hammer: mark all scalars precise in this path.
2385 	 * pop_stack may still get !precise scalars.
2386 	 * We also skip current state and go straight to first parent state,
2387 	 * because precision markings in current non-checkpointed state are
2388 	 * not needed. See why in the comment in __mark_chain_precision below.
2389 	 */
2390 	for (st = st->parent; st; st = st->parent) {
2391 		for (i = 0; i <= st->curframe; i++) {
2392 			func = st->frame[i];
2393 			for (j = 0; j < BPF_REG_FP; j++) {
2394 				reg = &func->regs[j];
2395 				if (reg->type != SCALAR_VALUE)
2396 					continue;
2397 				reg->precise = true;
2398 			}
2399 			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2400 				if (!is_spilled_reg(&func->stack[j]))
2401 					continue;
2402 				reg = &func->stack[j].spilled_ptr;
2403 				if (reg->type != SCALAR_VALUE)
2404 					continue;
2405 				reg->precise = true;
2406 			}
2407 		}
2408 	}
2409 }
2410 
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2411 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2412 {
2413 	struct bpf_func_state *func;
2414 	struct bpf_reg_state *reg;
2415 	int i, j;
2416 
2417 	for (i = 0; i <= st->curframe; i++) {
2418 		func = st->frame[i];
2419 		for (j = 0; j < BPF_REG_FP; j++) {
2420 			reg = &func->regs[j];
2421 			if (reg->type != SCALAR_VALUE)
2422 				continue;
2423 			reg->precise = false;
2424 		}
2425 		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2426 			if (!is_spilled_reg(&func->stack[j]))
2427 				continue;
2428 			reg = &func->stack[j].spilled_ptr;
2429 			if (reg->type != SCALAR_VALUE)
2430 				continue;
2431 			reg->precise = false;
2432 		}
2433 	}
2434 }
2435 
2436 /*
2437  * __mark_chain_precision() backtracks BPF program instruction sequence and
2438  * chain of verifier states making sure that register *regno* (if regno >= 0)
2439  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2440  * SCALARS, as well as any other registers and slots that contribute to
2441  * a tracked state of given registers/stack slots, depending on specific BPF
2442  * assembly instructions (see backtrack_insns() for exact instruction handling
2443  * logic). This backtracking relies on recorded jmp_history and is able to
2444  * traverse entire chain of parent states. This process ends only when all the
2445  * necessary registers/slots and their transitive dependencies are marked as
2446  * precise.
2447  *
2448  * One important and subtle aspect is that precise marks *do not matter* in
2449  * the currently verified state (current state). It is important to understand
2450  * why this is the case.
2451  *
2452  * First, note that current state is the state that is not yet "checkpointed",
2453  * i.e., it is not yet put into env->explored_states, and it has no children
2454  * states as well. It's ephemeral, and can end up either a) being discarded if
2455  * compatible explored state is found at some point or BPF_EXIT instruction is
2456  * reached or b) checkpointed and put into env->explored_states, branching out
2457  * into one or more children states.
2458  *
2459  * In the former case, precise markings in current state are completely
2460  * ignored by state comparison code (see regsafe() for details). Only
2461  * checkpointed ("old") state precise markings are important, and if old
2462  * state's register/slot is precise, regsafe() assumes current state's
2463  * register/slot as precise and checks value ranges exactly and precisely. If
2464  * states turn out to be compatible, current state's necessary precise
2465  * markings and any required parent states' precise markings are enforced
2466  * after the fact with propagate_precision() logic, after the fact. But it's
2467  * important to realize that in this case, even after marking current state
2468  * registers/slots as precise, we immediately discard current state. So what
2469  * actually matters is any of the precise markings propagated into current
2470  * state's parent states, which are always checkpointed (due to b) case above).
2471  * As such, for scenario a) it doesn't matter if current state has precise
2472  * markings set or not.
2473  *
2474  * Now, for the scenario b), checkpointing and forking into child(ren)
2475  * state(s). Note that before current state gets to checkpointing step, any
2476  * processed instruction always assumes precise SCALAR register/slot
2477  * knowledge: if precise value or range is useful to prune jump branch, BPF
2478  * verifier takes this opportunity enthusiastically. Similarly, when
2479  * register's value is used to calculate offset or memory address, exact
2480  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2481  * what we mentioned above about state comparison ignoring precise markings
2482  * during state comparison, BPF verifier ignores and also assumes precise
2483  * markings *at will* during instruction verification process. But as verifier
2484  * assumes precision, it also propagates any precision dependencies across
2485  * parent states, which are not yet finalized, so can be further restricted
2486  * based on new knowledge gained from restrictions enforced by their children
2487  * states. This is so that once those parent states are finalized, i.e., when
2488  * they have no more active children state, state comparison logic in
2489  * is_state_visited() would enforce strict and precise SCALAR ranges, if
2490  * required for correctness.
2491  *
2492  * To build a bit more intuition, note also that once a state is checkpointed,
2493  * the path we took to get to that state is not important. This is crucial
2494  * property for state pruning. When state is checkpointed and finalized at
2495  * some instruction index, it can be correctly and safely used to "short
2496  * circuit" any *compatible* state that reaches exactly the same instruction
2497  * index. I.e., if we jumped to that instruction from a completely different
2498  * code path than original finalized state was derived from, it doesn't
2499  * matter, current state can be discarded because from that instruction
2500  * forward having a compatible state will ensure we will safely reach the
2501  * exit. States describe preconditions for further exploration, but completely
2502  * forget the history of how we got here.
2503  *
2504  * This also means that even if we needed precise SCALAR range to get to
2505  * finalized state, but from that point forward *that same* SCALAR register is
2506  * never used in a precise context (i.e., it's precise value is not needed for
2507  * correctness), it's correct and safe to mark such register as "imprecise"
2508  * (i.e., precise marking set to false). This is what we rely on when we do
2509  * not set precise marking in current state. If no child state requires
2510  * precision for any given SCALAR register, it's safe to dictate that it can
2511  * be imprecise. If any child state does require this register to be precise,
2512  * we'll mark it precise later retroactively during precise markings
2513  * propagation from child state to parent states.
2514  *
2515  * Skipping precise marking setting in current state is a mild version of
2516  * relying on the above observation. But we can utilize this property even
2517  * more aggressively by proactively forgetting any precise marking in the
2518  * current state (which we inherited from the parent state), right before we
2519  * checkpoint it and branch off into new child state. This is done by
2520  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2521  * finalized states which help in short circuiting more future states.
2522  */
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2523 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2524 				  int spi)
2525 {
2526 	struct bpf_verifier_state *st = env->cur_state;
2527 	int first_idx = st->first_insn_idx;
2528 	int last_idx = env->insn_idx;
2529 	struct bpf_func_state *func;
2530 	struct bpf_reg_state *reg;
2531 	u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2532 	u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2533 	bool skip_first = true;
2534 	bool new_marks = false;
2535 	int i, err;
2536 
2537 	if (!env->bpf_capable)
2538 		return 0;
2539 
2540 	/* Do sanity checks against current state of register and/or stack
2541 	 * slot, but don't set precise flag in current state, as precision
2542 	 * tracking in the current state is unnecessary.
2543 	 */
2544 	func = st->frame[frame];
2545 	if (regno >= 0) {
2546 		reg = &func->regs[regno];
2547 		if (reg->type != SCALAR_VALUE) {
2548 			WARN_ONCE(1, "backtracing misuse");
2549 			return -EFAULT;
2550 		}
2551 		new_marks = true;
2552 	}
2553 
2554 	while (spi >= 0) {
2555 		if (!is_spilled_reg(&func->stack[spi])) {
2556 			stack_mask = 0;
2557 			break;
2558 		}
2559 		reg = &func->stack[spi].spilled_ptr;
2560 		if (reg->type != SCALAR_VALUE) {
2561 			stack_mask = 0;
2562 			break;
2563 		}
2564 		new_marks = true;
2565 		break;
2566 	}
2567 
2568 	if (!new_marks)
2569 		return 0;
2570 	if (!reg_mask && !stack_mask)
2571 		return 0;
2572 
2573 	for (;;) {
2574 		DECLARE_BITMAP(mask, 64);
2575 		u32 history = st->jmp_history_cnt;
2576 
2577 		if (env->log.level & BPF_LOG_LEVEL)
2578 			verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2579 
2580 		if (last_idx < 0) {
2581 			/* we are at the entry into subprog, which
2582 			 * is expected for global funcs, but only if
2583 			 * requested precise registers are R1-R5
2584 			 * (which are global func's input arguments)
2585 			 */
2586 			if (st->curframe == 0 &&
2587 			    st->frame[0]->subprogno > 0 &&
2588 			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
2589 			    stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2590 				bitmap_from_u64(mask, reg_mask);
2591 				for_each_set_bit(i, mask, 32) {
2592 					reg = &st->frame[0]->regs[i];
2593 					if (reg->type != SCALAR_VALUE) {
2594 						reg_mask &= ~(1u << i);
2595 						continue;
2596 					}
2597 					reg->precise = true;
2598 				}
2599 				return 0;
2600 			}
2601 
2602 			verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2603 				st->frame[0]->subprogno, reg_mask, stack_mask);
2604 			WARN_ONCE(1, "verifier backtracking bug");
2605 			return -EFAULT;
2606 		}
2607 
2608 		for (i = last_idx;;) {
2609 			if (skip_first) {
2610 				err = 0;
2611 				skip_first = false;
2612 			} else {
2613 				err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2614 			}
2615 			if (err == -ENOTSUPP) {
2616 				mark_all_scalars_precise(env, st);
2617 				return 0;
2618 			} else if (err) {
2619 				return err;
2620 			}
2621 			if (!reg_mask && !stack_mask)
2622 				/* Found assignment(s) into tracked register in this state.
2623 				 * Since this state is already marked, just return.
2624 				 * Nothing to be tracked further in the parent state.
2625 				 */
2626 				return 0;
2627 			if (i == first_idx)
2628 				break;
2629 			i = get_prev_insn_idx(st, i, &history);
2630 			if (i >= env->prog->len) {
2631 				/* This can happen if backtracking reached insn 0
2632 				 * and there are still reg_mask or stack_mask
2633 				 * to backtrack.
2634 				 * It means the backtracking missed the spot where
2635 				 * particular register was initialized with a constant.
2636 				 */
2637 				verbose(env, "BUG backtracking idx %d\n", i);
2638 				WARN_ONCE(1, "verifier backtracking bug");
2639 				return -EFAULT;
2640 			}
2641 		}
2642 		st = st->parent;
2643 		if (!st)
2644 			break;
2645 
2646 		new_marks = false;
2647 		func = st->frame[frame];
2648 		bitmap_from_u64(mask, reg_mask);
2649 		for_each_set_bit(i, mask, 32) {
2650 			reg = &func->regs[i];
2651 			if (reg->type != SCALAR_VALUE) {
2652 				reg_mask &= ~(1u << i);
2653 				continue;
2654 			}
2655 			if (!reg->precise)
2656 				new_marks = true;
2657 			reg->precise = true;
2658 		}
2659 
2660 		bitmap_from_u64(mask, stack_mask);
2661 		for_each_set_bit(i, mask, 64) {
2662 			if (i >= func->allocated_stack / BPF_REG_SIZE) {
2663 				/* the sequence of instructions:
2664 				 * 2: (bf) r3 = r10
2665 				 * 3: (7b) *(u64 *)(r3 -8) = r0
2666 				 * 4: (79) r4 = *(u64 *)(r10 -8)
2667 				 * doesn't contain jmps. It's backtracked
2668 				 * as a single block.
2669 				 * During backtracking insn 3 is not recognized as
2670 				 * stack access, so at the end of backtracking
2671 				 * stack slot fp-8 is still marked in stack_mask.
2672 				 * However the parent state may not have accessed
2673 				 * fp-8 and it's "unallocated" stack space.
2674 				 * In such case fallback to conservative.
2675 				 */
2676 				mark_all_scalars_precise(env, st);
2677 				return 0;
2678 			}
2679 
2680 			if (!is_spilled_reg(&func->stack[i])) {
2681 				stack_mask &= ~(1ull << i);
2682 				continue;
2683 			}
2684 			reg = &func->stack[i].spilled_ptr;
2685 			if (reg->type != SCALAR_VALUE) {
2686 				stack_mask &= ~(1ull << i);
2687 				continue;
2688 			}
2689 			if (!reg->precise)
2690 				new_marks = true;
2691 			reg->precise = true;
2692 		}
2693 		if (env->log.level & BPF_LOG_LEVEL) {
2694 			print_verifier_state(env, func);
2695 			verbose(env, "parent %s regs=%x stack=%llx marks\n",
2696 				new_marks ? "didn't have" : "already had",
2697 				reg_mask, stack_mask);
2698 		}
2699 
2700 		if (!reg_mask && !stack_mask)
2701 			break;
2702 		if (!new_marks)
2703 			break;
2704 
2705 		last_idx = st->last_insn_idx;
2706 		first_idx = st->first_insn_idx;
2707 	}
2708 	return 0;
2709 }
2710 
mark_chain_precision(struct bpf_verifier_env * env,int regno)2711 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2712 {
2713 	return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2714 }
2715 
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2716 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2717 {
2718 	return __mark_chain_precision(env, frame, regno, -1);
2719 }
2720 
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2721 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2722 {
2723 	return __mark_chain_precision(env, frame, -1, spi);
2724 }
2725 
is_spillable_regtype(enum bpf_reg_type type)2726 static bool is_spillable_regtype(enum bpf_reg_type type)
2727 {
2728 	switch (base_type(type)) {
2729 	case PTR_TO_MAP_VALUE:
2730 	case PTR_TO_STACK:
2731 	case PTR_TO_CTX:
2732 	case PTR_TO_PACKET:
2733 	case PTR_TO_PACKET_META:
2734 	case PTR_TO_PACKET_END:
2735 	case PTR_TO_FLOW_KEYS:
2736 	case CONST_PTR_TO_MAP:
2737 	case PTR_TO_SOCKET:
2738 	case PTR_TO_SOCK_COMMON:
2739 	case PTR_TO_TCP_SOCK:
2740 	case PTR_TO_XDP_SOCK:
2741 	case PTR_TO_BTF_ID:
2742 	case PTR_TO_BUF:
2743 	case PTR_TO_PERCPU_BTF_ID:
2744 	case PTR_TO_MEM:
2745 	case PTR_TO_FUNC:
2746 	case PTR_TO_MAP_KEY:
2747 		return true;
2748 	default:
2749 		return false;
2750 	}
2751 }
2752 
2753 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2754 static bool register_is_null(struct bpf_reg_state *reg)
2755 {
2756 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2757 }
2758 
register_is_const(struct bpf_reg_state * reg)2759 static bool register_is_const(struct bpf_reg_state *reg)
2760 {
2761 	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2762 }
2763 
__is_scalar_unbounded(struct bpf_reg_state * reg)2764 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2765 {
2766 	return tnum_is_unknown(reg->var_off) &&
2767 	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2768 	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2769 	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2770 	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2771 }
2772 
register_is_bounded(struct bpf_reg_state * reg)2773 static bool register_is_bounded(struct bpf_reg_state *reg)
2774 {
2775 	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2776 }
2777 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)2778 static bool __is_pointer_value(bool allow_ptr_leaks,
2779 			       const struct bpf_reg_state *reg)
2780 {
2781 	if (allow_ptr_leaks)
2782 		return false;
2783 
2784 	return reg->type != SCALAR_VALUE;
2785 }
2786 
2787 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)2788 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2789 {
2790 	struct bpf_reg_state *parent = dst->parent;
2791 	enum bpf_reg_liveness live = dst->live;
2792 
2793 	*dst = *src;
2794 	dst->parent = parent;
2795 	dst->live = live;
2796 }
2797 
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)2798 static void save_register_state(struct bpf_func_state *state,
2799 				int spi, struct bpf_reg_state *reg,
2800 				int size)
2801 {
2802 	int i;
2803 
2804 	copy_register_state(&state->stack[spi].spilled_ptr, reg);
2805 	if (size == BPF_REG_SIZE)
2806 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2807 
2808 	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2809 		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2810 
2811 	/* size < 8 bytes spill */
2812 	for (; i; i--)
2813 		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2814 }
2815 
is_bpf_st_mem(struct bpf_insn * insn)2816 static bool is_bpf_st_mem(struct bpf_insn *insn)
2817 {
2818 	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
2819 }
2820 
2821 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2822  * stack boundary and alignment are checked in check_mem_access()
2823  */
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)2824 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2825 				       /* stack frame we're writing to */
2826 				       struct bpf_func_state *state,
2827 				       int off, int size, int value_regno,
2828 				       int insn_idx)
2829 {
2830 	struct bpf_func_state *cur; /* state of the current function */
2831 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2832 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
2833 	struct bpf_reg_state *reg = NULL;
2834 	u32 dst_reg = insn->dst_reg;
2835 
2836 	err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2837 	if (err)
2838 		return err;
2839 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2840 	 * so it's aligned access and [off, off + size) are within stack limits
2841 	 */
2842 	if (!env->allow_ptr_leaks &&
2843 	    is_spilled_reg(&state->stack[spi]) &&
2844 	    size != BPF_REG_SIZE) {
2845 		verbose(env, "attempt to corrupt spilled pointer on stack\n");
2846 		return -EACCES;
2847 	}
2848 
2849 	cur = env->cur_state->frame[env->cur_state->curframe];
2850 	if (value_regno >= 0)
2851 		reg = &cur->regs[value_regno];
2852 	if (!env->bypass_spec_v4) {
2853 		bool sanitize = reg && is_spillable_regtype(reg->type);
2854 
2855 		for (i = 0; i < size; i++) {
2856 			u8 type = state->stack[spi].slot_type[i];
2857 
2858 			if (type != STACK_MISC && type != STACK_ZERO) {
2859 				sanitize = true;
2860 				break;
2861 			}
2862 		}
2863 
2864 		if (sanitize)
2865 			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2866 	}
2867 
2868 	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2869 	    !register_is_null(reg) && env->bpf_capable) {
2870 		if (dst_reg != BPF_REG_FP) {
2871 			/* The backtracking logic can only recognize explicit
2872 			 * stack slot address like [fp - 8]. Other spill of
2873 			 * scalar via different register has to be conservative.
2874 			 * Backtrack from here and mark all registers as precise
2875 			 * that contributed into 'reg' being a constant.
2876 			 */
2877 			err = mark_chain_precision(env, value_regno);
2878 			if (err)
2879 				return err;
2880 		}
2881 		save_register_state(state, spi, reg, size);
2882 		/* Break the relation on a narrowing spill. */
2883 		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
2884 			state->stack[spi].spilled_ptr.id = 0;
2885 	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
2886 		   insn->imm != 0 && env->bpf_capable) {
2887 		struct bpf_reg_state fake_reg = {};
2888 
2889 		__mark_reg_known(&fake_reg, insn->imm);
2890 		fake_reg.type = SCALAR_VALUE;
2891 		save_register_state(state, spi, &fake_reg, size);
2892 	} else if (reg && is_spillable_regtype(reg->type)) {
2893 		/* register containing pointer is being spilled into stack */
2894 		if (size != BPF_REG_SIZE) {
2895 			verbose_linfo(env, insn_idx, "; ");
2896 			verbose(env, "invalid size of register spill\n");
2897 			return -EACCES;
2898 		}
2899 		if (state != cur && reg->type == PTR_TO_STACK) {
2900 			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2901 			return -EINVAL;
2902 		}
2903 		save_register_state(state, spi, reg, size);
2904 	} else {
2905 		u8 type = STACK_MISC;
2906 
2907 		/* regular write of data into stack destroys any spilled ptr */
2908 		state->stack[spi].spilled_ptr.type = NOT_INIT;
2909 		/* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2910 		if (is_spilled_reg(&state->stack[spi]))
2911 			for (i = 0; i < BPF_REG_SIZE; i++)
2912 				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2913 
2914 		/* only mark the slot as written if all 8 bytes were written
2915 		 * otherwise read propagation may incorrectly stop too soon
2916 		 * when stack slots are partially written.
2917 		 * This heuristic means that read propagation will be
2918 		 * conservative, since it will add reg_live_read marks
2919 		 * to stack slots all the way to first state when programs
2920 		 * writes+reads less than 8 bytes
2921 		 */
2922 		if (size == BPF_REG_SIZE)
2923 			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2924 
2925 		/* when we zero initialize stack slots mark them as such */
2926 		if ((reg && register_is_null(reg)) ||
2927 		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
2928 			/* backtracking doesn't work for STACK_ZERO yet. */
2929 			err = mark_chain_precision(env, value_regno);
2930 			if (err)
2931 				return err;
2932 			type = STACK_ZERO;
2933 		}
2934 
2935 		/* Mark slots affected by this stack write. */
2936 		for (i = 0; i < size; i++)
2937 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2938 				type;
2939 	}
2940 	return 0;
2941 }
2942 
2943 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2944  * known to contain a variable offset.
2945  * This function checks whether the write is permitted and conservatively
2946  * tracks the effects of the write, considering that each stack slot in the
2947  * dynamic range is potentially written to.
2948  *
2949  * 'off' includes 'regno->off'.
2950  * 'value_regno' can be -1, meaning that an unknown value is being written to
2951  * the stack.
2952  *
2953  * Spilled pointers in range are not marked as written because we don't know
2954  * what's going to be actually written. This means that read propagation for
2955  * future reads cannot be terminated by this write.
2956  *
2957  * For privileged programs, uninitialized stack slots are considered
2958  * initialized by this write (even though we don't know exactly what offsets
2959  * are going to be written to). The idea is that we don't want the verifier to
2960  * reject future reads that access slots written to through variable offsets.
2961  */
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)2962 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2963 				     /* func where register points to */
2964 				     struct bpf_func_state *state,
2965 				     int ptr_regno, int off, int size,
2966 				     int value_regno, int insn_idx)
2967 {
2968 	struct bpf_func_state *cur; /* state of the current function */
2969 	int min_off, max_off;
2970 	int i, err;
2971 	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2972 	bool writing_zero = false;
2973 	/* set if the fact that we're writing a zero is used to let any
2974 	 * stack slots remain STACK_ZERO
2975 	 */
2976 	bool zero_used = false;
2977 
2978 	cur = env->cur_state->frame[env->cur_state->curframe];
2979 	ptr_reg = &cur->regs[ptr_regno];
2980 	min_off = ptr_reg->smin_value + off;
2981 	max_off = ptr_reg->smax_value + off + size;
2982 	if (value_regno >= 0)
2983 		value_reg = &cur->regs[value_regno];
2984 	if (value_reg && register_is_null(value_reg))
2985 		writing_zero = true;
2986 
2987 	err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2988 	if (err)
2989 		return err;
2990 
2991 
2992 	/* Variable offset writes destroy any spilled pointers in range. */
2993 	for (i = min_off; i < max_off; i++) {
2994 		u8 new_type, *stype;
2995 		int slot, spi;
2996 
2997 		slot = -i - 1;
2998 		spi = slot / BPF_REG_SIZE;
2999 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3000 
3001 		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3002 			/* Reject the write if range we may write to has not
3003 			 * been initialized beforehand. If we didn't reject
3004 			 * here, the ptr status would be erased below (even
3005 			 * though not all slots are actually overwritten),
3006 			 * possibly opening the door to leaks.
3007 			 *
3008 			 * We do however catch STACK_INVALID case below, and
3009 			 * only allow reading possibly uninitialized memory
3010 			 * later for CAP_PERFMON, as the write may not happen to
3011 			 * that slot.
3012 			 */
3013 			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3014 				insn_idx, i);
3015 			return -EINVAL;
3016 		}
3017 
3018 		/* Erase all spilled pointers. */
3019 		state->stack[spi].spilled_ptr.type = NOT_INIT;
3020 
3021 		/* Update the slot type. */
3022 		new_type = STACK_MISC;
3023 		if (writing_zero && *stype == STACK_ZERO) {
3024 			new_type = STACK_ZERO;
3025 			zero_used = true;
3026 		}
3027 		/* If the slot is STACK_INVALID, we check whether it's OK to
3028 		 * pretend that it will be initialized by this write. The slot
3029 		 * might not actually be written to, and so if we mark it as
3030 		 * initialized future reads might leak uninitialized memory.
3031 		 * For privileged programs, we will accept such reads to slots
3032 		 * that may or may not be written because, if we're reject
3033 		 * them, the error would be too confusing.
3034 		 */
3035 		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3036 			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3037 					insn_idx, i);
3038 			return -EINVAL;
3039 		}
3040 		*stype = new_type;
3041 	}
3042 	if (zero_used) {
3043 		/* backtracking doesn't work for STACK_ZERO yet. */
3044 		err = mark_chain_precision(env, value_regno);
3045 		if (err)
3046 			return err;
3047 	}
3048 	return 0;
3049 }
3050 
3051 /* When register 'dst_regno' is assigned some values from stack[min_off,
3052  * max_off), we set the register's type according to the types of the
3053  * respective stack slots. If all the stack values are known to be zeros, then
3054  * so is the destination reg. Otherwise, the register is considered to be
3055  * SCALAR. This function does not deal with register filling; the caller must
3056  * ensure that all spilled registers in the stack range have been marked as
3057  * read.
3058  */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)3059 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3060 				/* func where src register points to */
3061 				struct bpf_func_state *ptr_state,
3062 				int min_off, int max_off, int dst_regno)
3063 {
3064 	struct bpf_verifier_state *vstate = env->cur_state;
3065 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3066 	int i, slot, spi;
3067 	u8 *stype;
3068 	int zeros = 0;
3069 
3070 	for (i = min_off; i < max_off; i++) {
3071 		slot = -i - 1;
3072 		spi = slot / BPF_REG_SIZE;
3073 		stype = ptr_state->stack[spi].slot_type;
3074 		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3075 			break;
3076 		zeros++;
3077 	}
3078 	if (zeros == max_off - min_off) {
3079 		/* any access_size read into register is zero extended,
3080 		 * so the whole register == const_zero
3081 		 */
3082 		__mark_reg_const_zero(&state->regs[dst_regno]);
3083 		/* backtracking doesn't support STACK_ZERO yet,
3084 		 * so mark it precise here, so that later
3085 		 * backtracking can stop here.
3086 		 * Backtracking may not need this if this register
3087 		 * doesn't participate in pointer adjustment.
3088 		 * Forward propagation of precise flag is not
3089 		 * necessary either. This mark is only to stop
3090 		 * backtracking. Any register that contributed
3091 		 * to const 0 was marked precise before spill.
3092 		 */
3093 		state->regs[dst_regno].precise = true;
3094 	} else {
3095 		/* have read misc data from the stack */
3096 		mark_reg_unknown(env, state->regs, dst_regno);
3097 	}
3098 	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3099 }
3100 
3101 /* Read the stack at 'off' and put the results into the register indicated by
3102  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3103  * spilled reg.
3104  *
3105  * 'dst_regno' can be -1, meaning that the read value is not going to a
3106  * register.
3107  *
3108  * The access is assumed to be within the current stack bounds.
3109  */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)3110 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3111 				      /* func where src register points to */
3112 				      struct bpf_func_state *reg_state,
3113 				      int off, int size, int dst_regno)
3114 {
3115 	struct bpf_verifier_state *vstate = env->cur_state;
3116 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3117 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3118 	struct bpf_reg_state *reg;
3119 	u8 *stype, type;
3120 
3121 	stype = reg_state->stack[spi].slot_type;
3122 	reg = &reg_state->stack[spi].spilled_ptr;
3123 
3124 	if (is_spilled_reg(&reg_state->stack[spi])) {
3125 		u8 spill_size = 1;
3126 
3127 		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3128 			spill_size++;
3129 
3130 		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3131 			if (reg->type != SCALAR_VALUE) {
3132 				verbose_linfo(env, env->insn_idx, "; ");
3133 				verbose(env, "invalid size of register fill\n");
3134 				return -EACCES;
3135 			}
3136 
3137 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3138 			if (dst_regno < 0)
3139 				return 0;
3140 
3141 			if (!(off % BPF_REG_SIZE) && size == spill_size) {
3142 				/* The earlier check_reg_arg() has decided the
3143 				 * subreg_def for this insn.  Save it first.
3144 				 */
3145 				s32 subreg_def = state->regs[dst_regno].subreg_def;
3146 
3147 				copy_register_state(&state->regs[dst_regno], reg);
3148 				state->regs[dst_regno].subreg_def = subreg_def;
3149 			} else {
3150 				for (i = 0; i < size; i++) {
3151 					type = stype[(slot - i) % BPF_REG_SIZE];
3152 					if (type == STACK_SPILL)
3153 						continue;
3154 					if (type == STACK_MISC)
3155 						continue;
3156 					verbose(env, "invalid read from stack off %d+%d size %d\n",
3157 						off, i, size);
3158 					return -EACCES;
3159 				}
3160 				mark_reg_unknown(env, state->regs, dst_regno);
3161 			}
3162 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3163 			return 0;
3164 		}
3165 
3166 		if (dst_regno >= 0) {
3167 			/* restore register state from stack */
3168 			copy_register_state(&state->regs[dst_regno], reg);
3169 			/* mark reg as written since spilled pointer state likely
3170 			 * has its liveness marks cleared by is_state_visited()
3171 			 * which resets stack/reg liveness for state transitions
3172 			 */
3173 			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3174 		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3175 			/* If dst_regno==-1, the caller is asking us whether
3176 			 * it is acceptable to use this value as a SCALAR_VALUE
3177 			 * (e.g. for XADD).
3178 			 * We must not allow unprivileged callers to do that
3179 			 * with spilled pointers.
3180 			 */
3181 			verbose(env, "leaking pointer from stack off %d\n",
3182 				off);
3183 			return -EACCES;
3184 		}
3185 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3186 	} else {
3187 		for (i = 0; i < size; i++) {
3188 			type = stype[(slot - i) % BPF_REG_SIZE];
3189 			if (type == STACK_MISC)
3190 				continue;
3191 			if (type == STACK_ZERO)
3192 				continue;
3193 			verbose(env, "invalid read from stack off %d+%d size %d\n",
3194 				off, i, size);
3195 			return -EACCES;
3196 		}
3197 		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3198 		if (dst_regno >= 0)
3199 			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3200 	}
3201 	return 0;
3202 }
3203 
3204 enum stack_access_src {
3205 	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3206 	ACCESS_HELPER = 2,  /* the access is performed by a helper */
3207 };
3208 
3209 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3210 					 int regno, int off, int access_size,
3211 					 bool zero_size_allowed,
3212 					 enum stack_access_src type,
3213 					 struct bpf_call_arg_meta *meta);
3214 
reg_state(struct bpf_verifier_env * env,int regno)3215 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3216 {
3217 	return cur_regs(env) + regno;
3218 }
3219 
3220 /* Read the stack at 'ptr_regno + off' and put the result into the register
3221  * 'dst_regno'.
3222  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3223  * but not its variable offset.
3224  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3225  *
3226  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3227  * filling registers (i.e. reads of spilled register cannot be detected when
3228  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3229  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3230  * offset; for a fixed offset check_stack_read_fixed_off should be used
3231  * instead.
3232  */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3233 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3234 				    int ptr_regno, int off, int size, int dst_regno)
3235 {
3236 	/* The state of the source register. */
3237 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3238 	struct bpf_func_state *ptr_state = func(env, reg);
3239 	int err;
3240 	int min_off, max_off;
3241 
3242 	/* Note that we pass a NULL meta, so raw access will not be permitted.
3243 	 */
3244 	err = check_stack_range_initialized(env, ptr_regno, off, size,
3245 					    false, ACCESS_DIRECT, NULL);
3246 	if (err)
3247 		return err;
3248 
3249 	min_off = reg->smin_value + off;
3250 	max_off = reg->smax_value + off;
3251 	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3252 	return 0;
3253 }
3254 
3255 /* check_stack_read dispatches to check_stack_read_fixed_off or
3256  * check_stack_read_var_off.
3257  *
3258  * The caller must ensure that the offset falls within the allocated stack
3259  * bounds.
3260  *
3261  * 'dst_regno' is a register which will receive the value from the stack. It
3262  * can be -1, meaning that the read value is not going to a register.
3263  */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3264 static int check_stack_read(struct bpf_verifier_env *env,
3265 			    int ptr_regno, int off, int size,
3266 			    int dst_regno)
3267 {
3268 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3269 	struct bpf_func_state *state = func(env, reg);
3270 	int err;
3271 	/* Some accesses are only permitted with a static offset. */
3272 	bool var_off = !tnum_is_const(reg->var_off);
3273 
3274 	/* The offset is required to be static when reads don't go to a
3275 	 * register, in order to not leak pointers (see
3276 	 * check_stack_read_fixed_off).
3277 	 */
3278 	if (dst_regno < 0 && var_off) {
3279 		char tn_buf[48];
3280 
3281 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3282 		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3283 			tn_buf, off, size);
3284 		return -EACCES;
3285 	}
3286 	/* Variable offset is prohibited for unprivileged mode for simplicity
3287 	 * since it requires corresponding support in Spectre masking for stack
3288 	 * ALU. See also retrieve_ptr_limit(). The check in
3289 	 * check_stack_access_for_ptr_arithmetic() called by
3290 	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3291 	 * with variable offsets, therefore no check is required here. Further,
3292 	 * just checking it here would be insufficient as speculative stack
3293 	 * writes could still lead to unsafe speculative behaviour.
3294 	 */
3295 	if (!var_off) {
3296 		off += reg->var_off.value;
3297 		err = check_stack_read_fixed_off(env, state, off, size,
3298 						 dst_regno);
3299 	} else {
3300 		/* Variable offset stack reads need more conservative handling
3301 		 * than fixed offset ones. Note that dst_regno >= 0 on this
3302 		 * branch.
3303 		 */
3304 		err = check_stack_read_var_off(env, ptr_regno, off, size,
3305 					       dst_regno);
3306 	}
3307 	return err;
3308 }
3309 
3310 
3311 /* check_stack_write dispatches to check_stack_write_fixed_off or
3312  * check_stack_write_var_off.
3313  *
3314  * 'ptr_regno' is the register used as a pointer into the stack.
3315  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3316  * 'value_regno' is the register whose value we're writing to the stack. It can
3317  * be -1, meaning that we're not writing from a register.
3318  *
3319  * The caller must ensure that the offset falls within the maximum stack size.
3320  */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)3321 static int check_stack_write(struct bpf_verifier_env *env,
3322 			     int ptr_regno, int off, int size,
3323 			     int value_regno, int insn_idx)
3324 {
3325 	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3326 	struct bpf_func_state *state = func(env, reg);
3327 	int err;
3328 
3329 	if (tnum_is_const(reg->var_off)) {
3330 		off += reg->var_off.value;
3331 		err = check_stack_write_fixed_off(env, state, off, size,
3332 						  value_regno, insn_idx);
3333 	} else {
3334 		/* Variable offset stack reads need more conservative handling
3335 		 * than fixed offset ones.
3336 		 */
3337 		err = check_stack_write_var_off(env, state,
3338 						ptr_regno, off, size,
3339 						value_regno, insn_idx);
3340 	}
3341 	return err;
3342 }
3343 
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)3344 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3345 				 int off, int size, enum bpf_access_type type)
3346 {
3347 	struct bpf_reg_state *regs = cur_regs(env);
3348 	struct bpf_map *map = regs[regno].map_ptr;
3349 	u32 cap = bpf_map_flags_to_cap(map);
3350 
3351 	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3352 		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3353 			map->value_size, off, size);
3354 		return -EACCES;
3355 	}
3356 
3357 	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3358 		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3359 			map->value_size, off, size);
3360 		return -EACCES;
3361 	}
3362 
3363 	return 0;
3364 }
3365 
3366 /* 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)3367 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3368 			      int off, int size, u32 mem_size,
3369 			      bool zero_size_allowed)
3370 {
3371 	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3372 	struct bpf_reg_state *reg;
3373 
3374 	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3375 		return 0;
3376 
3377 	reg = &cur_regs(env)[regno];
3378 	switch (reg->type) {
3379 	case PTR_TO_MAP_KEY:
3380 		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3381 			mem_size, off, size);
3382 		break;
3383 	case PTR_TO_MAP_VALUE:
3384 		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3385 			mem_size, off, size);
3386 		break;
3387 	case PTR_TO_PACKET:
3388 	case PTR_TO_PACKET_META:
3389 	case PTR_TO_PACKET_END:
3390 		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3391 			off, size, regno, reg->id, off, mem_size);
3392 		break;
3393 	case PTR_TO_MEM:
3394 	default:
3395 		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3396 			mem_size, off, size);
3397 	}
3398 
3399 	return -EACCES;
3400 }
3401 
3402 /* 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)3403 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3404 				   int off, int size, u32 mem_size,
3405 				   bool zero_size_allowed)
3406 {
3407 	struct bpf_verifier_state *vstate = env->cur_state;
3408 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3409 	struct bpf_reg_state *reg = &state->regs[regno];
3410 	int err;
3411 
3412 	/* We may have adjusted the register pointing to memory region, so we
3413 	 * need to try adding each of min_value and max_value to off
3414 	 * to make sure our theoretical access will be safe.
3415 	 */
3416 	if (env->log.level & BPF_LOG_LEVEL)
3417 		print_verifier_state(env, state);
3418 
3419 	/* The minimum value is only important with signed
3420 	 * comparisons where we can't assume the floor of a
3421 	 * value is 0.  If we are using signed variables for our
3422 	 * index'es we need to make sure that whatever we use
3423 	 * will have a set floor within our range.
3424 	 */
3425 	if (reg->smin_value < 0 &&
3426 	    (reg->smin_value == S64_MIN ||
3427 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3428 	      reg->smin_value + off < 0)) {
3429 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3430 			regno);
3431 		return -EACCES;
3432 	}
3433 	err = __check_mem_access(env, regno, reg->smin_value + off, size,
3434 				 mem_size, zero_size_allowed);
3435 	if (err) {
3436 		verbose(env, "R%d min value is outside of the allowed memory range\n",
3437 			regno);
3438 		return err;
3439 	}
3440 
3441 	/* If we haven't set a max value then we need to bail since we can't be
3442 	 * sure we won't do bad things.
3443 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
3444 	 */
3445 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3446 		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3447 			regno);
3448 		return -EACCES;
3449 	}
3450 	err = __check_mem_access(env, regno, reg->umax_value + off, size,
3451 				 mem_size, zero_size_allowed);
3452 	if (err) {
3453 		verbose(env, "R%d max value is outside of the allowed memory range\n",
3454 			regno);
3455 		return err;
3456 	}
3457 
3458 	return 0;
3459 }
3460 
3461 /* 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)3462 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3463 			    int off, int size, bool zero_size_allowed)
3464 {
3465 	struct bpf_verifier_state *vstate = env->cur_state;
3466 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3467 	struct bpf_reg_state *reg = &state->regs[regno];
3468 	struct bpf_map *map = reg->map_ptr;
3469 	int err;
3470 
3471 	err = check_mem_region_access(env, regno, off, size, map->value_size,
3472 				      zero_size_allowed);
3473 	if (err)
3474 		return err;
3475 
3476 	if (map_value_has_spin_lock(map)) {
3477 		u32 lock = map->spin_lock_off;
3478 
3479 		/* if any part of struct bpf_spin_lock can be touched by
3480 		 * load/store reject this program.
3481 		 * To check that [x1, x2) overlaps with [y1, y2)
3482 		 * it is sufficient to check x1 < y2 && y1 < x2.
3483 		 */
3484 		if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3485 		     lock < reg->umax_value + off + size) {
3486 			verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3487 			return -EACCES;
3488 		}
3489 	}
3490 	if (map_value_has_timer(map)) {
3491 		u32 t = map->timer_off;
3492 
3493 		if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3494 		     t < reg->umax_value + off + size) {
3495 			verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3496 			return -EACCES;
3497 		}
3498 	}
3499 	return err;
3500 }
3501 
3502 #define MAX_PACKET_OFF 0xffff
3503 
resolve_prog_type(struct bpf_prog * prog)3504 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3505 {
3506 	return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3507 }
3508 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)3509 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3510 				       const struct bpf_call_arg_meta *meta,
3511 				       enum bpf_access_type t)
3512 {
3513 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3514 
3515 	switch (prog_type) {
3516 	/* Program types only with direct read access go here! */
3517 	case BPF_PROG_TYPE_LWT_IN:
3518 	case BPF_PROG_TYPE_LWT_OUT:
3519 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3520 	case BPF_PROG_TYPE_SK_REUSEPORT:
3521 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
3522 	case BPF_PROG_TYPE_CGROUP_SKB:
3523 		if (t == BPF_WRITE)
3524 			return false;
3525 		fallthrough;
3526 
3527 	/* Program types with direct read + write access go here! */
3528 	case BPF_PROG_TYPE_SCHED_CLS:
3529 	case BPF_PROG_TYPE_SCHED_ACT:
3530 	case BPF_PROG_TYPE_XDP:
3531 	case BPF_PROG_TYPE_LWT_XMIT:
3532 	case BPF_PROG_TYPE_SK_SKB:
3533 	case BPF_PROG_TYPE_SK_MSG:
3534 		if (meta)
3535 			return meta->pkt_access;
3536 
3537 		env->seen_direct_write = true;
3538 		return true;
3539 
3540 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3541 		if (t == BPF_WRITE)
3542 			env->seen_direct_write = true;
3543 
3544 		return true;
3545 
3546 	default:
3547 		return false;
3548 	}
3549 }
3550 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)3551 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3552 			       int size, bool zero_size_allowed)
3553 {
3554 	struct bpf_reg_state *regs = cur_regs(env);
3555 	struct bpf_reg_state *reg = &regs[regno];
3556 	int err;
3557 
3558 	/* We may have added a variable offset to the packet pointer; but any
3559 	 * reg->range we have comes after that.  We are only checking the fixed
3560 	 * offset.
3561 	 */
3562 
3563 	/* We don't allow negative numbers, because we aren't tracking enough
3564 	 * detail to prove they're safe.
3565 	 */
3566 	if (reg->smin_value < 0) {
3567 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3568 			regno);
3569 		return -EACCES;
3570 	}
3571 
3572 	err = reg->range < 0 ? -EINVAL :
3573 	      __check_mem_access(env, regno, off, size, reg->range,
3574 				 zero_size_allowed);
3575 	if (err) {
3576 		verbose(env, "R%d offset is outside of the packet\n", regno);
3577 		return err;
3578 	}
3579 
3580 	/* __check_mem_access has made sure "off + size - 1" is within u16.
3581 	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3582 	 * otherwise find_good_pkt_pointers would have refused to set range info
3583 	 * that __check_mem_access would have rejected this pkt access.
3584 	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3585 	 */
3586 	env->prog->aux->max_pkt_offset =
3587 		max_t(u32, env->prog->aux->max_pkt_offset,
3588 		      off + reg->umax_value + size - 1);
3589 
3590 	return err;
3591 }
3592 
3593 /* 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)3594 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3595 			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
3596 			    struct btf **btf, u32 *btf_id)
3597 {
3598 	struct bpf_insn_access_aux info = {
3599 		.reg_type = *reg_type,
3600 		.log = &env->log,
3601 	};
3602 
3603 	if (env->ops->is_valid_access &&
3604 	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3605 		/* A non zero info.ctx_field_size indicates that this field is a
3606 		 * candidate for later verifier transformation to load the whole
3607 		 * field and then apply a mask when accessed with a narrower
3608 		 * access than actual ctx access size. A zero info.ctx_field_size
3609 		 * will only allow for whole field access and rejects any other
3610 		 * type of narrower access.
3611 		 */
3612 		*reg_type = info.reg_type;
3613 
3614 		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3615 			*btf = info.btf;
3616 			*btf_id = info.btf_id;
3617 		} else {
3618 			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3619 		}
3620 		/* remember the offset of last byte accessed in ctx */
3621 		if (env->prog->aux->max_ctx_offset < off + size)
3622 			env->prog->aux->max_ctx_offset = off + size;
3623 		return 0;
3624 	}
3625 
3626 	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3627 	return -EACCES;
3628 }
3629 
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)3630 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3631 				  int size)
3632 {
3633 	if (size < 0 || off < 0 ||
3634 	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
3635 		verbose(env, "invalid access to flow keys off=%d size=%d\n",
3636 			off, size);
3637 		return -EACCES;
3638 	}
3639 	return 0;
3640 }
3641 
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)3642 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3643 			     u32 regno, int off, int size,
3644 			     enum bpf_access_type t)
3645 {
3646 	struct bpf_reg_state *regs = cur_regs(env);
3647 	struct bpf_reg_state *reg = &regs[regno];
3648 	struct bpf_insn_access_aux info = {};
3649 	bool valid;
3650 
3651 	if (reg->smin_value < 0) {
3652 		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3653 			regno);
3654 		return -EACCES;
3655 	}
3656 
3657 	switch (reg->type) {
3658 	case PTR_TO_SOCK_COMMON:
3659 		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3660 		break;
3661 	case PTR_TO_SOCKET:
3662 		valid = bpf_sock_is_valid_access(off, size, t, &info);
3663 		break;
3664 	case PTR_TO_TCP_SOCK:
3665 		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3666 		break;
3667 	case PTR_TO_XDP_SOCK:
3668 		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3669 		break;
3670 	default:
3671 		valid = false;
3672 	}
3673 
3674 
3675 	if (valid) {
3676 		env->insn_aux_data[insn_idx].ctx_field_size =
3677 			info.ctx_field_size;
3678 		return 0;
3679 	}
3680 
3681 	verbose(env, "R%d invalid %s access off=%d size=%d\n",
3682 		regno, reg_type_str(env, reg->type), off, size);
3683 
3684 	return -EACCES;
3685 }
3686 
is_pointer_value(struct bpf_verifier_env * env,int regno)3687 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3688 {
3689 	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3690 }
3691 
is_ctx_reg(struct bpf_verifier_env * env,int regno)3692 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3693 {
3694 	const struct bpf_reg_state *reg = reg_state(env, regno);
3695 
3696 	return reg->type == PTR_TO_CTX;
3697 }
3698 
is_sk_reg(struct bpf_verifier_env * env,int regno)3699 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3700 {
3701 	const struct bpf_reg_state *reg = reg_state(env, regno);
3702 
3703 	return type_is_sk_pointer(reg->type);
3704 }
3705 
is_pkt_reg(struct bpf_verifier_env * env,int regno)3706 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3707 {
3708 	const struct bpf_reg_state *reg = reg_state(env, regno);
3709 
3710 	return type_is_pkt_pointer(reg->type);
3711 }
3712 
is_flow_key_reg(struct bpf_verifier_env * env,int regno)3713 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3714 {
3715 	const struct bpf_reg_state *reg = reg_state(env, regno);
3716 
3717 	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3718 	return reg->type == PTR_TO_FLOW_KEYS;
3719 }
3720 
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)3721 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3722 				   const struct bpf_reg_state *reg,
3723 				   int off, int size, bool strict)
3724 {
3725 	struct tnum reg_off;
3726 	int ip_align;
3727 
3728 	/* Byte size accesses are always allowed. */
3729 	if (!strict || size == 1)
3730 		return 0;
3731 
3732 	/* For platforms that do not have a Kconfig enabling
3733 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3734 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
3735 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3736 	 * to this code only in strict mode where we want to emulate
3737 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
3738 	 * unconditional IP align value of '2'.
3739 	 */
3740 	ip_align = 2;
3741 
3742 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3743 	if (!tnum_is_aligned(reg_off, size)) {
3744 		char tn_buf[48];
3745 
3746 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3747 		verbose(env,
3748 			"misaligned packet access off %d+%s+%d+%d size %d\n",
3749 			ip_align, tn_buf, reg->off, off, size);
3750 		return -EACCES;
3751 	}
3752 
3753 	return 0;
3754 }
3755 
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)3756 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3757 				       const struct bpf_reg_state *reg,
3758 				       const char *pointer_desc,
3759 				       int off, int size, bool strict)
3760 {
3761 	struct tnum reg_off;
3762 
3763 	/* Byte size accesses are always allowed. */
3764 	if (!strict || size == 1)
3765 		return 0;
3766 
3767 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3768 	if (!tnum_is_aligned(reg_off, size)) {
3769 		char tn_buf[48];
3770 
3771 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3772 		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3773 			pointer_desc, tn_buf, reg->off, off, size);
3774 		return -EACCES;
3775 	}
3776 
3777 	return 0;
3778 }
3779 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)3780 static int check_ptr_alignment(struct bpf_verifier_env *env,
3781 			       const struct bpf_reg_state *reg, int off,
3782 			       int size, bool strict_alignment_once)
3783 {
3784 	bool strict = env->strict_alignment || strict_alignment_once;
3785 	const char *pointer_desc = "";
3786 
3787 	switch (reg->type) {
3788 	case PTR_TO_PACKET:
3789 	case PTR_TO_PACKET_META:
3790 		/* Special case, because of NET_IP_ALIGN. Given metadata sits
3791 		 * right in front, treat it the very same way.
3792 		 */
3793 		return check_pkt_ptr_alignment(env, reg, off, size, strict);
3794 	case PTR_TO_FLOW_KEYS:
3795 		pointer_desc = "flow keys ";
3796 		break;
3797 	case PTR_TO_MAP_KEY:
3798 		pointer_desc = "key ";
3799 		break;
3800 	case PTR_TO_MAP_VALUE:
3801 		pointer_desc = "value ";
3802 		break;
3803 	case PTR_TO_CTX:
3804 		pointer_desc = "context ";
3805 		break;
3806 	case PTR_TO_STACK:
3807 		pointer_desc = "stack ";
3808 		/* The stack spill tracking logic in check_stack_write_fixed_off()
3809 		 * and check_stack_read_fixed_off() relies on stack accesses being
3810 		 * aligned.
3811 		 */
3812 		strict = true;
3813 		break;
3814 	case PTR_TO_SOCKET:
3815 		pointer_desc = "sock ";
3816 		break;
3817 	case PTR_TO_SOCK_COMMON:
3818 		pointer_desc = "sock_common ";
3819 		break;
3820 	case PTR_TO_TCP_SOCK:
3821 		pointer_desc = "tcp_sock ";
3822 		break;
3823 	case PTR_TO_XDP_SOCK:
3824 		pointer_desc = "xdp_sock ";
3825 		break;
3826 	default:
3827 		break;
3828 	}
3829 	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3830 					   strict);
3831 }
3832 
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)3833 static int update_stack_depth(struct bpf_verifier_env *env,
3834 			      const struct bpf_func_state *func,
3835 			      int off)
3836 {
3837 	u16 stack = env->subprog_info[func->subprogno].stack_depth;
3838 
3839 	if (stack >= -off)
3840 		return 0;
3841 
3842 	/* update known max for given subprogram */
3843 	env->subprog_info[func->subprogno].stack_depth = -off;
3844 	return 0;
3845 }
3846 
3847 /* starting from main bpf function walk all instructions of the function
3848  * and recursively walk all callees that given function can call.
3849  * Ignore jump and exit insns.
3850  * Since recursion is prevented by check_cfg() this algorithm
3851  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3852  */
check_max_stack_depth(struct bpf_verifier_env * env)3853 static int check_max_stack_depth(struct bpf_verifier_env *env)
3854 {
3855 	int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3856 	struct bpf_subprog_info *subprog = env->subprog_info;
3857 	struct bpf_insn *insn = env->prog->insnsi;
3858 	bool tail_call_reachable = false;
3859 	int ret_insn[MAX_CALL_FRAMES];
3860 	int ret_prog[MAX_CALL_FRAMES];
3861 	int j;
3862 
3863 process_func:
3864 	/* protect against potential stack overflow that might happen when
3865 	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3866 	 * depth for such case down to 256 so that the worst case scenario
3867 	 * would result in 8k stack size (32 which is tailcall limit * 256 =
3868 	 * 8k).
3869 	 *
3870 	 * To get the idea what might happen, see an example:
3871 	 * func1 -> sub rsp, 128
3872 	 *  subfunc1 -> sub rsp, 256
3873 	 *  tailcall1 -> add rsp, 256
3874 	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3875 	 *   subfunc2 -> sub rsp, 64
3876 	 *   subfunc22 -> sub rsp, 128
3877 	 *   tailcall2 -> add rsp, 128
3878 	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3879 	 *
3880 	 * tailcall will unwind the current stack frame but it will not get rid
3881 	 * of caller's stack as shown on the example above.
3882 	 */
3883 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
3884 		verbose(env,
3885 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3886 			depth);
3887 		return -EACCES;
3888 	}
3889 	/* round up to 32-bytes, since this is granularity
3890 	 * of interpreter stack size
3891 	 */
3892 	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3893 	if (depth > MAX_BPF_STACK) {
3894 		verbose(env, "combined stack size of %d calls is %d. Too large\n",
3895 			frame + 1, depth);
3896 		return -EACCES;
3897 	}
3898 continue_func:
3899 	subprog_end = subprog[idx + 1].start;
3900 	for (; i < subprog_end; i++) {
3901 		int next_insn, sidx;
3902 
3903 		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3904 			continue;
3905 		/* remember insn and function to return to */
3906 		ret_insn[frame] = i + 1;
3907 		ret_prog[frame] = idx;
3908 
3909 		/* find the callee */
3910 		next_insn = i + insn[i].imm + 1;
3911 		sidx = find_subprog(env, next_insn);
3912 		if (sidx < 0) {
3913 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3914 				  next_insn);
3915 			return -EFAULT;
3916 		}
3917 		if (subprog[sidx].is_async_cb) {
3918 			if (subprog[sidx].has_tail_call) {
3919 				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3920 				return -EFAULT;
3921 			}
3922 			/* async callbacks don't increase bpf prog stack size unless called directly */
3923 			if (!bpf_pseudo_call(insn + i))
3924 				continue;
3925 		}
3926 		i = next_insn;
3927 		idx = sidx;
3928 
3929 		if (subprog[idx].has_tail_call)
3930 			tail_call_reachable = true;
3931 
3932 		frame++;
3933 		if (frame >= MAX_CALL_FRAMES) {
3934 			verbose(env, "the call stack of %d frames is too deep !\n",
3935 				frame);
3936 			return -E2BIG;
3937 		}
3938 		goto process_func;
3939 	}
3940 	/* if tail call got detected across bpf2bpf calls then mark each of the
3941 	 * currently present subprog frames as tail call reachable subprogs;
3942 	 * this info will be utilized by JIT so that we will be preserving the
3943 	 * tail call counter throughout bpf2bpf calls combined with tailcalls
3944 	 */
3945 	if (tail_call_reachable)
3946 		for (j = 0; j < frame; j++)
3947 			subprog[ret_prog[j]].tail_call_reachable = true;
3948 	if (subprog[0].tail_call_reachable)
3949 		env->prog->aux->tail_call_reachable = true;
3950 
3951 	/* end of for() loop means the last insn of the 'subprog'
3952 	 * was reached. Doesn't matter whether it was JA or EXIT
3953 	 */
3954 	if (frame == 0)
3955 		return 0;
3956 	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3957 	frame--;
3958 	i = ret_insn[frame];
3959 	idx = ret_prog[frame];
3960 	goto continue_func;
3961 }
3962 
3963 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)3964 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3965 				  const struct bpf_insn *insn, int idx)
3966 {
3967 	int start = idx + insn->imm + 1, subprog;
3968 
3969 	subprog = find_subprog(env, start);
3970 	if (subprog < 0) {
3971 		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3972 			  start);
3973 		return -EFAULT;
3974 	}
3975 	return env->subprog_info[subprog].stack_depth;
3976 }
3977 #endif
3978 
check_ctx_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3979 int check_ctx_reg(struct bpf_verifier_env *env,
3980 		  const struct bpf_reg_state *reg, int regno)
3981 {
3982 	/* Access to ctx or passing it to a helper is only allowed in
3983 	 * its original, unmodified form.
3984 	 */
3985 
3986 	if (reg->off) {
3987 		verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3988 			regno, reg->off);
3989 		return -EACCES;
3990 	}
3991 
3992 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3993 		char tn_buf[48];
3994 
3995 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3996 		verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3997 		return -EACCES;
3998 	}
3999 
4000 	return 0;
4001 }
4002 
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)4003 static int __check_buffer_access(struct bpf_verifier_env *env,
4004 				 const char *buf_info,
4005 				 const struct bpf_reg_state *reg,
4006 				 int regno, int off, int size)
4007 {
4008 	if (off < 0) {
4009 		verbose(env,
4010 			"R%d invalid %s buffer access: off=%d, size=%d\n",
4011 			regno, buf_info, off, size);
4012 		return -EACCES;
4013 	}
4014 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4015 		char tn_buf[48];
4016 
4017 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4018 		verbose(env,
4019 			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4020 			regno, off, tn_buf);
4021 		return -EACCES;
4022 	}
4023 
4024 	return 0;
4025 }
4026 
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)4027 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4028 				  const struct bpf_reg_state *reg,
4029 				  int regno, int off, int size)
4030 {
4031 	int err;
4032 
4033 	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4034 	if (err)
4035 		return err;
4036 
4037 	if (off + size > env->prog->aux->max_tp_access)
4038 		env->prog->aux->max_tp_access = off + size;
4039 
4040 	return 0;
4041 }
4042 
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)4043 static int check_buffer_access(struct bpf_verifier_env *env,
4044 			       const struct bpf_reg_state *reg,
4045 			       int regno, int off, int size,
4046 			       bool zero_size_allowed,
4047 			       const char *buf_info,
4048 			       u32 *max_access)
4049 {
4050 	int err;
4051 
4052 	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4053 	if (err)
4054 		return err;
4055 
4056 	if (off + size > *max_access)
4057 		*max_access = off + size;
4058 
4059 	return 0;
4060 }
4061 
4062 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)4063 static void zext_32_to_64(struct bpf_reg_state *reg)
4064 {
4065 	reg->var_off = tnum_subreg(reg->var_off);
4066 	__reg_assign_32_into_64(reg);
4067 }
4068 
4069 /* truncate register to smaller size (in bytes)
4070  * must be called with size < BPF_REG_SIZE
4071  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)4072 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4073 {
4074 	u64 mask;
4075 
4076 	/* clear high bits in bit representation */
4077 	reg->var_off = tnum_cast(reg->var_off, size);
4078 
4079 	/* fix arithmetic bounds */
4080 	mask = ((u64)1 << (size * 8)) - 1;
4081 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4082 		reg->umin_value &= mask;
4083 		reg->umax_value &= mask;
4084 	} else {
4085 		reg->umin_value = 0;
4086 		reg->umax_value = mask;
4087 	}
4088 	reg->smin_value = reg->umin_value;
4089 	reg->smax_value = reg->umax_value;
4090 
4091 	/* If size is smaller than 32bit register the 32bit register
4092 	 * values are also truncated so we push 64-bit bounds into
4093 	 * 32-bit bounds. Above were truncated < 32-bits already.
4094 	 */
4095 	if (size >= 4)
4096 		return;
4097 	__reg_combine_64_into_32(reg);
4098 }
4099 
bpf_map_is_rdonly(const struct bpf_map * map)4100 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4101 {
4102 	/* A map is considered read-only if the following condition are true:
4103 	 *
4104 	 * 1) BPF program side cannot change any of the map content. The
4105 	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4106 	 *    and was set at map creation time.
4107 	 * 2) The map value(s) have been initialized from user space by a
4108 	 *    loader and then "frozen", such that no new map update/delete
4109 	 *    operations from syscall side are possible for the rest of
4110 	 *    the map's lifetime from that point onwards.
4111 	 * 3) Any parallel/pending map update/delete operations from syscall
4112 	 *    side have been completed. Only after that point, it's safe to
4113 	 *    assume that map value(s) are immutable.
4114 	 */
4115 	return (map->map_flags & BPF_F_RDONLY_PROG) &&
4116 	       READ_ONCE(map->frozen) &&
4117 	       !bpf_map_write_active(map);
4118 }
4119 
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)4120 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4121 {
4122 	void *ptr;
4123 	u64 addr;
4124 	int err;
4125 
4126 	err = map->ops->map_direct_value_addr(map, &addr, off);
4127 	if (err)
4128 		return err;
4129 	ptr = (void *)(long)addr + off;
4130 
4131 	switch (size) {
4132 	case sizeof(u8):
4133 		*val = (u64)*(u8 *)ptr;
4134 		break;
4135 	case sizeof(u16):
4136 		*val = (u64)*(u16 *)ptr;
4137 		break;
4138 	case sizeof(u32):
4139 		*val = (u64)*(u32 *)ptr;
4140 		break;
4141 	case sizeof(u64):
4142 		*val = *(u64 *)ptr;
4143 		break;
4144 	default:
4145 		return -EINVAL;
4146 	}
4147 	return 0;
4148 }
4149 
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)4150 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4151 				   struct bpf_reg_state *regs,
4152 				   int regno, int off, int size,
4153 				   enum bpf_access_type atype,
4154 				   int value_regno)
4155 {
4156 	struct bpf_reg_state *reg = regs + regno;
4157 	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4158 	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4159 	u32 btf_id;
4160 	int ret;
4161 
4162 	if (off < 0) {
4163 		verbose(env,
4164 			"R%d is ptr_%s invalid negative access: off=%d\n",
4165 			regno, tname, off);
4166 		return -EACCES;
4167 	}
4168 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4169 		char tn_buf[48];
4170 
4171 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4172 		verbose(env,
4173 			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4174 			regno, tname, off, tn_buf);
4175 		return -EACCES;
4176 	}
4177 
4178 	if (env->ops->btf_struct_access) {
4179 		ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4180 						  off, size, atype, &btf_id);
4181 	} else {
4182 		if (atype != BPF_READ) {
4183 			verbose(env, "only read is supported\n");
4184 			return -EACCES;
4185 		}
4186 
4187 		ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4188 					atype, &btf_id);
4189 	}
4190 
4191 	if (ret < 0)
4192 		return ret;
4193 
4194 	if (atype == BPF_READ && value_regno >= 0)
4195 		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
4196 
4197 	return 0;
4198 }
4199 
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)4200 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4201 				   struct bpf_reg_state *regs,
4202 				   int regno, int off, int size,
4203 				   enum bpf_access_type atype,
4204 				   int value_regno)
4205 {
4206 	struct bpf_reg_state *reg = regs + regno;
4207 	struct bpf_map *map = reg->map_ptr;
4208 	const struct btf_type *t;
4209 	const char *tname;
4210 	u32 btf_id;
4211 	int ret;
4212 
4213 	if (!btf_vmlinux) {
4214 		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4215 		return -ENOTSUPP;
4216 	}
4217 
4218 	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4219 		verbose(env, "map_ptr access not supported for map type %d\n",
4220 			map->map_type);
4221 		return -ENOTSUPP;
4222 	}
4223 
4224 	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4225 	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4226 
4227 	if (!env->allow_ptr_to_map_access) {
4228 		verbose(env,
4229 			"%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4230 			tname);
4231 		return -EPERM;
4232 	}
4233 
4234 	if (off < 0) {
4235 		verbose(env, "R%d is %s invalid negative access: off=%d\n",
4236 			regno, tname, off);
4237 		return -EACCES;
4238 	}
4239 
4240 	if (atype != BPF_READ) {
4241 		verbose(env, "only read from %s is supported\n", tname);
4242 		return -EACCES;
4243 	}
4244 
4245 	ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4246 	if (ret < 0)
4247 		return ret;
4248 
4249 	if (value_regno >= 0)
4250 		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4251 
4252 	return 0;
4253 }
4254 
4255 /* Check that the stack access at the given offset is within bounds. The
4256  * maximum valid offset is -1.
4257  *
4258  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4259  * -state->allocated_stack for reads.
4260  */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)4261 static int check_stack_slot_within_bounds(int off,
4262 					  struct bpf_func_state *state,
4263 					  enum bpf_access_type t)
4264 {
4265 	int min_valid_off;
4266 
4267 	if (t == BPF_WRITE)
4268 		min_valid_off = -MAX_BPF_STACK;
4269 	else
4270 		min_valid_off = -state->allocated_stack;
4271 
4272 	if (off < min_valid_off || off > -1)
4273 		return -EACCES;
4274 	return 0;
4275 }
4276 
4277 /* Check that the stack access at 'regno + off' falls within the maximum stack
4278  * bounds.
4279  *
4280  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4281  */
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)4282 static int check_stack_access_within_bounds(
4283 		struct bpf_verifier_env *env,
4284 		int regno, int off, int access_size,
4285 		enum stack_access_src src, enum bpf_access_type type)
4286 {
4287 	struct bpf_reg_state *regs = cur_regs(env);
4288 	struct bpf_reg_state *reg = regs + regno;
4289 	struct bpf_func_state *state = func(env, reg);
4290 	int min_off, max_off;
4291 	int err;
4292 	char *err_extra;
4293 
4294 	if (src == ACCESS_HELPER)
4295 		/* We don't know if helpers are reading or writing (or both). */
4296 		err_extra = " indirect access to";
4297 	else if (type == BPF_READ)
4298 		err_extra = " read from";
4299 	else
4300 		err_extra = " write to";
4301 
4302 	if (tnum_is_const(reg->var_off)) {
4303 		min_off = reg->var_off.value + off;
4304 		max_off = min_off + access_size;
4305 	} else {
4306 		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4307 		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
4308 			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4309 				err_extra, regno);
4310 			return -EACCES;
4311 		}
4312 		min_off = reg->smin_value + off;
4313 		max_off = reg->smax_value + off + access_size;
4314 	}
4315 
4316 	err = check_stack_slot_within_bounds(min_off, state, type);
4317 	if (!err && max_off > 0)
4318 		err = -EINVAL; /* out of stack access into non-negative offsets */
4319 
4320 	if (err) {
4321 		if (tnum_is_const(reg->var_off)) {
4322 			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4323 				err_extra, regno, off, access_size);
4324 		} else {
4325 			char tn_buf[48];
4326 
4327 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4328 			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4329 				err_extra, regno, tn_buf, access_size);
4330 		}
4331 	}
4332 	return err;
4333 }
4334 
4335 /* check whether memory at (regno + off) is accessible for t = (read | write)
4336  * if t==write, value_regno is a register which value is stored into memory
4337  * if t==read, value_regno is a register which will receive the value from memory
4338  * if t==write && value_regno==-1, some unknown value is stored into memory
4339  * if t==read && value_regno==-1, don't care what we read from memory
4340  */
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)4341 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4342 			    int off, int bpf_size, enum bpf_access_type t,
4343 			    int value_regno, bool strict_alignment_once)
4344 {
4345 	struct bpf_reg_state *regs = cur_regs(env);
4346 	struct bpf_reg_state *reg = regs + regno;
4347 	struct bpf_func_state *state;
4348 	int size, err = 0;
4349 
4350 	size = bpf_size_to_bytes(bpf_size);
4351 	if (size < 0)
4352 		return size;
4353 
4354 	/* alignment checks will add in reg->off themselves */
4355 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4356 	if (err)
4357 		return err;
4358 
4359 	/* for access checks, reg->off is just part of off */
4360 	off += reg->off;
4361 
4362 	if (reg->type == PTR_TO_MAP_KEY) {
4363 		if (t == BPF_WRITE) {
4364 			verbose(env, "write to change key R%d not allowed\n", regno);
4365 			return -EACCES;
4366 		}
4367 
4368 		err = check_mem_region_access(env, regno, off, size,
4369 					      reg->map_ptr->key_size, false);
4370 		if (err)
4371 			return err;
4372 		if (value_regno >= 0)
4373 			mark_reg_unknown(env, regs, value_regno);
4374 	} else if (reg->type == PTR_TO_MAP_VALUE) {
4375 		if (t == BPF_WRITE && value_regno >= 0 &&
4376 		    is_pointer_value(env, value_regno)) {
4377 			verbose(env, "R%d leaks addr into map\n", value_regno);
4378 			return -EACCES;
4379 		}
4380 		err = check_map_access_type(env, regno, off, size, t);
4381 		if (err)
4382 			return err;
4383 		err = check_map_access(env, regno, off, size, false);
4384 		if (!err && t == BPF_READ && value_regno >= 0) {
4385 			struct bpf_map *map = reg->map_ptr;
4386 
4387 			/* if map is read-only, track its contents as scalars */
4388 			if (tnum_is_const(reg->var_off) &&
4389 			    bpf_map_is_rdonly(map) &&
4390 			    map->ops->map_direct_value_addr) {
4391 				int map_off = off + reg->var_off.value;
4392 				u64 val = 0;
4393 
4394 				err = bpf_map_direct_read(map, map_off, size,
4395 							  &val);
4396 				if (err)
4397 					return err;
4398 
4399 				regs[value_regno].type = SCALAR_VALUE;
4400 				__mark_reg_known(&regs[value_regno], val);
4401 			} else {
4402 				mark_reg_unknown(env, regs, value_regno);
4403 			}
4404 		}
4405 	} else if (base_type(reg->type) == PTR_TO_MEM) {
4406 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4407 
4408 		if (type_may_be_null(reg->type)) {
4409 			verbose(env, "R%d invalid mem access '%s'\n", regno,
4410 				reg_type_str(env, reg->type));
4411 			return -EACCES;
4412 		}
4413 
4414 		if (t == BPF_WRITE && rdonly_mem) {
4415 			verbose(env, "R%d cannot write into %s\n",
4416 				regno, reg_type_str(env, reg->type));
4417 			return -EACCES;
4418 		}
4419 
4420 		if (t == BPF_WRITE && value_regno >= 0 &&
4421 		    is_pointer_value(env, value_regno)) {
4422 			verbose(env, "R%d leaks addr into mem\n", value_regno);
4423 			return -EACCES;
4424 		}
4425 
4426 		err = check_mem_region_access(env, regno, off, size,
4427 					      reg->mem_size, false);
4428 		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4429 			mark_reg_unknown(env, regs, value_regno);
4430 	} else if (reg->type == PTR_TO_CTX) {
4431 		enum bpf_reg_type reg_type = SCALAR_VALUE;
4432 		struct btf *btf = NULL;
4433 		u32 btf_id = 0;
4434 
4435 		if (t == BPF_WRITE && value_regno >= 0 &&
4436 		    is_pointer_value(env, value_regno)) {
4437 			verbose(env, "R%d leaks addr into ctx\n", value_regno);
4438 			return -EACCES;
4439 		}
4440 
4441 		err = check_ctx_reg(env, reg, regno);
4442 		if (err < 0)
4443 			return err;
4444 
4445 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4446 		if (err)
4447 			verbose_linfo(env, insn_idx, "; ");
4448 		if (!err && t == BPF_READ && value_regno >= 0) {
4449 			/* ctx access returns either a scalar, or a
4450 			 * PTR_TO_PACKET[_META,_END]. In the latter
4451 			 * case, we know the offset is zero.
4452 			 */
4453 			if (reg_type == SCALAR_VALUE) {
4454 				mark_reg_unknown(env, regs, value_regno);
4455 			} else {
4456 				mark_reg_known_zero(env, regs,
4457 						    value_regno);
4458 				if (type_may_be_null(reg_type))
4459 					regs[value_regno].id = ++env->id_gen;
4460 				/* A load of ctx field could have different
4461 				 * actual load size with the one encoded in the
4462 				 * insn. When the dst is PTR, it is for sure not
4463 				 * a sub-register.
4464 				 */
4465 				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4466 				if (base_type(reg_type) == PTR_TO_BTF_ID) {
4467 					regs[value_regno].btf = btf;
4468 					regs[value_regno].btf_id = btf_id;
4469 				}
4470 			}
4471 			regs[value_regno].type = reg_type;
4472 		}
4473 
4474 	} else if (reg->type == PTR_TO_STACK) {
4475 		/* Basic bounds checks. */
4476 		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4477 		if (err)
4478 			return err;
4479 
4480 		state = func(env, reg);
4481 		err = update_stack_depth(env, state, off);
4482 		if (err)
4483 			return err;
4484 
4485 		if (t == BPF_READ)
4486 			err = check_stack_read(env, regno, off, size,
4487 					       value_regno);
4488 		else
4489 			err = check_stack_write(env, regno, off, size,
4490 						value_regno, insn_idx);
4491 	} else if (reg_is_pkt_pointer(reg)) {
4492 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4493 			verbose(env, "cannot write into packet\n");
4494 			return -EACCES;
4495 		}
4496 		if (t == BPF_WRITE && value_regno >= 0 &&
4497 		    is_pointer_value(env, value_regno)) {
4498 			verbose(env, "R%d leaks addr into packet\n",
4499 				value_regno);
4500 			return -EACCES;
4501 		}
4502 		err = check_packet_access(env, regno, off, size, false);
4503 		if (!err && t == BPF_READ && value_regno >= 0)
4504 			mark_reg_unknown(env, regs, value_regno);
4505 	} else if (reg->type == PTR_TO_FLOW_KEYS) {
4506 		if (t == BPF_WRITE && value_regno >= 0 &&
4507 		    is_pointer_value(env, value_regno)) {
4508 			verbose(env, "R%d leaks addr into flow keys\n",
4509 				value_regno);
4510 			return -EACCES;
4511 		}
4512 
4513 		err = check_flow_keys_access(env, off, size);
4514 		if (!err && t == BPF_READ && value_regno >= 0)
4515 			mark_reg_unknown(env, regs, value_regno);
4516 	} else if (type_is_sk_pointer(reg->type)) {
4517 		if (t == BPF_WRITE) {
4518 			verbose(env, "R%d cannot write into %s\n",
4519 				regno, reg_type_str(env, reg->type));
4520 			return -EACCES;
4521 		}
4522 		err = check_sock_access(env, insn_idx, regno, off, size, t);
4523 		if (!err && value_regno >= 0)
4524 			mark_reg_unknown(env, regs, value_regno);
4525 	} else if (reg->type == PTR_TO_TP_BUFFER) {
4526 		err = check_tp_buffer_access(env, reg, regno, off, size);
4527 		if (!err && t == BPF_READ && value_regno >= 0)
4528 			mark_reg_unknown(env, regs, value_regno);
4529 	} else if (reg->type == PTR_TO_BTF_ID) {
4530 		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4531 					      value_regno);
4532 	} else if (reg->type == CONST_PTR_TO_MAP) {
4533 		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4534 					      value_regno);
4535 	} else if (base_type(reg->type) == PTR_TO_BUF) {
4536 		bool rdonly_mem = type_is_rdonly_mem(reg->type);
4537 		const char *buf_info;
4538 		u32 *max_access;
4539 
4540 		if (rdonly_mem) {
4541 			if (t == BPF_WRITE) {
4542 				verbose(env, "R%d cannot write into %s\n",
4543 					regno, reg_type_str(env, reg->type));
4544 				return -EACCES;
4545 			}
4546 			buf_info = "rdonly";
4547 			max_access = &env->prog->aux->max_rdonly_access;
4548 		} else {
4549 			buf_info = "rdwr";
4550 			max_access = &env->prog->aux->max_rdwr_access;
4551 		}
4552 
4553 		err = check_buffer_access(env, reg, regno, off, size, false,
4554 					  buf_info, max_access);
4555 
4556 		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4557 			mark_reg_unknown(env, regs, value_regno);
4558 	} else {
4559 		verbose(env, "R%d invalid mem access '%s'\n", regno,
4560 			reg_type_str(env, reg->type));
4561 		return -EACCES;
4562 	}
4563 
4564 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4565 	    regs[value_regno].type == SCALAR_VALUE) {
4566 		/* b/h/w load zero-extends, mark upper bits as known 0 */
4567 		coerce_reg_to_size(&regs[value_regno], size);
4568 	}
4569 	return err;
4570 }
4571 
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)4572 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4573 {
4574 	int load_reg;
4575 	int err;
4576 
4577 	switch (insn->imm) {
4578 	case BPF_ADD:
4579 	case BPF_ADD | BPF_FETCH:
4580 	case BPF_AND:
4581 	case BPF_AND | BPF_FETCH:
4582 	case BPF_OR:
4583 	case BPF_OR | BPF_FETCH:
4584 	case BPF_XOR:
4585 	case BPF_XOR | BPF_FETCH:
4586 	case BPF_XCHG:
4587 	case BPF_CMPXCHG:
4588 		break;
4589 	default:
4590 		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4591 		return -EINVAL;
4592 	}
4593 
4594 	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4595 		verbose(env, "invalid atomic operand size\n");
4596 		return -EINVAL;
4597 	}
4598 
4599 	/* check src1 operand */
4600 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
4601 	if (err)
4602 		return err;
4603 
4604 	/* check src2 operand */
4605 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4606 	if (err)
4607 		return err;
4608 
4609 	if (insn->imm == BPF_CMPXCHG) {
4610 		/* Check comparison of R0 with memory location */
4611 		const u32 aux_reg = BPF_REG_0;
4612 
4613 		err = check_reg_arg(env, aux_reg, SRC_OP);
4614 		if (err)
4615 			return err;
4616 
4617 		if (is_pointer_value(env, aux_reg)) {
4618 			verbose(env, "R%d leaks addr into mem\n", aux_reg);
4619 			return -EACCES;
4620 		}
4621 	}
4622 
4623 	if (is_pointer_value(env, insn->src_reg)) {
4624 		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4625 		return -EACCES;
4626 	}
4627 
4628 	if (is_ctx_reg(env, insn->dst_reg) ||
4629 	    is_pkt_reg(env, insn->dst_reg) ||
4630 	    is_flow_key_reg(env, insn->dst_reg) ||
4631 	    is_sk_reg(env, insn->dst_reg)) {
4632 		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4633 			insn->dst_reg,
4634 			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4635 		return -EACCES;
4636 	}
4637 
4638 	if (insn->imm & BPF_FETCH) {
4639 		if (insn->imm == BPF_CMPXCHG)
4640 			load_reg = BPF_REG_0;
4641 		else
4642 			load_reg = insn->src_reg;
4643 
4644 		/* check and record load of old value */
4645 		err = check_reg_arg(env, load_reg, DST_OP);
4646 		if (err)
4647 			return err;
4648 	} else {
4649 		/* This instruction accesses a memory location but doesn't
4650 		 * actually load it into a register.
4651 		 */
4652 		load_reg = -1;
4653 	}
4654 
4655 	/* Check whether we can read the memory, with second call for fetch
4656 	 * case to simulate the register fill.
4657 	 */
4658 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4659 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
4660 	if (!err && load_reg >= 0)
4661 		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4662 				       BPF_SIZE(insn->code), BPF_READ, load_reg,
4663 				       true);
4664 	if (err)
4665 		return err;
4666 
4667 	/* Check whether we can write into the same memory. */
4668 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4669 			       BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4670 	if (err)
4671 		return err;
4672 
4673 	return 0;
4674 }
4675 
4676 /* When register 'regno' is used to read the stack (either directly or through
4677  * a helper function) make sure that it's within stack boundary and, depending
4678  * on the access type, that all elements of the stack are initialized.
4679  *
4680  * 'off' includes 'regno->off', but not its dynamic part (if any).
4681  *
4682  * All registers that have been spilled on the stack in the slots within the
4683  * read offsets are marked as read.
4684  */
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)4685 static int check_stack_range_initialized(
4686 		struct bpf_verifier_env *env, int regno, int off,
4687 		int access_size, bool zero_size_allowed,
4688 		enum stack_access_src type, struct bpf_call_arg_meta *meta)
4689 {
4690 	struct bpf_reg_state *reg = reg_state(env, regno);
4691 	struct bpf_func_state *state = func(env, reg);
4692 	int err, min_off, max_off, i, j, slot, spi;
4693 	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4694 	enum bpf_access_type bounds_check_type;
4695 	/* Some accesses can write anything into the stack, others are
4696 	 * read-only.
4697 	 */
4698 	bool clobber = false;
4699 
4700 	if (access_size == 0 && !zero_size_allowed) {
4701 		verbose(env, "invalid zero-sized read\n");
4702 		return -EACCES;
4703 	}
4704 
4705 	if (type == ACCESS_HELPER) {
4706 		/* The bounds checks for writes are more permissive than for
4707 		 * reads. However, if raw_mode is not set, we'll do extra
4708 		 * checks below.
4709 		 */
4710 		bounds_check_type = BPF_WRITE;
4711 		clobber = true;
4712 	} else {
4713 		bounds_check_type = BPF_READ;
4714 	}
4715 	err = check_stack_access_within_bounds(env, regno, off, access_size,
4716 					       type, bounds_check_type);
4717 	if (err)
4718 		return err;
4719 
4720 
4721 	if (tnum_is_const(reg->var_off)) {
4722 		min_off = max_off = reg->var_off.value + off;
4723 	} else {
4724 		/* Variable offset is prohibited for unprivileged mode for
4725 		 * simplicity since it requires corresponding support in
4726 		 * Spectre masking for stack ALU.
4727 		 * See also retrieve_ptr_limit().
4728 		 */
4729 		if (!env->bypass_spec_v1) {
4730 			char tn_buf[48];
4731 
4732 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4733 			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4734 				regno, err_extra, tn_buf);
4735 			return -EACCES;
4736 		}
4737 		/* Only initialized buffer on stack is allowed to be accessed
4738 		 * with variable offset. With uninitialized buffer it's hard to
4739 		 * guarantee that whole memory is marked as initialized on
4740 		 * helper return since specific bounds are unknown what may
4741 		 * cause uninitialized stack leaking.
4742 		 */
4743 		if (meta && meta->raw_mode)
4744 			meta = NULL;
4745 
4746 		min_off = reg->smin_value + off;
4747 		max_off = reg->smax_value + off;
4748 	}
4749 
4750 	if (meta && meta->raw_mode) {
4751 		meta->access_size = access_size;
4752 		meta->regno = regno;
4753 		return 0;
4754 	}
4755 
4756 	for (i = min_off; i < max_off + access_size; i++) {
4757 		u8 *stype;
4758 
4759 		slot = -i - 1;
4760 		spi = slot / BPF_REG_SIZE;
4761 		if (state->allocated_stack <= slot)
4762 			goto err;
4763 		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4764 		if (*stype == STACK_MISC)
4765 			goto mark;
4766 		if (*stype == STACK_ZERO) {
4767 			if (clobber) {
4768 				/* helper can write anything into the stack */
4769 				*stype = STACK_MISC;
4770 			}
4771 			goto mark;
4772 		}
4773 
4774 		if (is_spilled_reg(&state->stack[spi]) &&
4775 		    state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4776 			goto mark;
4777 
4778 		if (is_spilled_reg(&state->stack[spi]) &&
4779 		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4780 		     env->allow_ptr_leaks)) {
4781 			if (clobber) {
4782 				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4783 				for (j = 0; j < BPF_REG_SIZE; j++)
4784 					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4785 			}
4786 			goto mark;
4787 		}
4788 
4789 err:
4790 		if (tnum_is_const(reg->var_off)) {
4791 			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4792 				err_extra, regno, min_off, i - min_off, access_size);
4793 		} else {
4794 			char tn_buf[48];
4795 
4796 			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4797 			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4798 				err_extra, regno, tn_buf, i - min_off, access_size);
4799 		}
4800 		return -EACCES;
4801 mark:
4802 		/* reading any byte out of 8-byte 'spill_slot' will cause
4803 		 * the whole slot to be marked as 'read'
4804 		 */
4805 		mark_reg_read(env, &state->stack[spi].spilled_ptr,
4806 			      state->stack[spi].spilled_ptr.parent,
4807 			      REG_LIVE_READ64);
4808 	}
4809 	return update_stack_depth(env, state, min_off);
4810 }
4811 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)4812 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4813 				   int access_size, bool zero_size_allowed,
4814 				   struct bpf_call_arg_meta *meta)
4815 {
4816 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4817 	const char *buf_info;
4818 	u32 *max_access;
4819 
4820 	switch (base_type(reg->type)) {
4821 	case PTR_TO_PACKET:
4822 	case PTR_TO_PACKET_META:
4823 		return check_packet_access(env, regno, reg->off, access_size,
4824 					   zero_size_allowed);
4825 	case PTR_TO_MAP_KEY:
4826 		if (meta && meta->raw_mode) {
4827 			verbose(env, "R%d cannot write into %s\n", regno,
4828 				reg_type_str(env, reg->type));
4829 			return -EACCES;
4830 		}
4831 		return check_mem_region_access(env, regno, reg->off, access_size,
4832 					       reg->map_ptr->key_size, false);
4833 	case PTR_TO_MAP_VALUE:
4834 		if (check_map_access_type(env, regno, reg->off, access_size,
4835 					  meta && meta->raw_mode ? BPF_WRITE :
4836 					  BPF_READ))
4837 			return -EACCES;
4838 		return check_map_access(env, regno, reg->off, access_size,
4839 					zero_size_allowed);
4840 	case PTR_TO_MEM:
4841 		if (type_is_rdonly_mem(reg->type)) {
4842 			if (meta && meta->raw_mode) {
4843 				verbose(env, "R%d cannot write into %s\n", regno,
4844 					reg_type_str(env, reg->type));
4845 				return -EACCES;
4846 			}
4847 		}
4848 		return check_mem_region_access(env, regno, reg->off,
4849 					       access_size, reg->mem_size,
4850 					       zero_size_allowed);
4851 	case PTR_TO_BUF:
4852 		if (type_is_rdonly_mem(reg->type)) {
4853 			if (meta && meta->raw_mode) {
4854 				verbose(env, "R%d cannot write into %s\n", regno,
4855 					reg_type_str(env, reg->type));
4856 				return -EACCES;
4857 			}
4858 
4859 			buf_info = "rdonly";
4860 			max_access = &env->prog->aux->max_rdonly_access;
4861 		} else {
4862 			buf_info = "rdwr";
4863 			max_access = &env->prog->aux->max_rdwr_access;
4864 		}
4865 		return check_buffer_access(env, reg, regno, reg->off,
4866 					   access_size, zero_size_allowed,
4867 					   buf_info, max_access);
4868 	case PTR_TO_STACK:
4869 		return check_stack_range_initialized(
4870 				env,
4871 				regno, reg->off, access_size,
4872 				zero_size_allowed, ACCESS_HELPER, meta);
4873 	default: /* scalar_value or invalid ptr */
4874 		/* Allow zero-byte read from NULL, regardless of pointer type */
4875 		if (zero_size_allowed && access_size == 0 &&
4876 		    register_is_null(reg))
4877 			return 0;
4878 
4879 		verbose(env, "R%d type=%s ", regno,
4880 			reg_type_str(env, reg->type));
4881 		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
4882 		return -EACCES;
4883 	}
4884 }
4885 
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)4886 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4887 		   u32 regno, u32 mem_size)
4888 {
4889 	if (register_is_null(reg))
4890 		return 0;
4891 
4892 	if (type_may_be_null(reg->type)) {
4893 		/* Assuming that the register contains a value check if the memory
4894 		 * access is safe. Temporarily save and restore the register's state as
4895 		 * the conversion shouldn't be visible to a caller.
4896 		 */
4897 		const struct bpf_reg_state saved_reg = *reg;
4898 		int rv;
4899 
4900 		mark_ptr_not_null_reg(reg);
4901 		rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4902 		*reg = saved_reg;
4903 		return rv;
4904 	}
4905 
4906 	return check_helper_mem_access(env, regno, mem_size, true, NULL);
4907 }
4908 
4909 /* Implementation details:
4910  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4911  * Two bpf_map_lookups (even with the same key) will have different reg->id.
4912  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4913  * value_or_null->value transition, since the verifier only cares about
4914  * the range of access to valid map value pointer and doesn't care about actual
4915  * address of the map element.
4916  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4917  * reg->id > 0 after value_or_null->value transition. By doing so
4918  * two bpf_map_lookups will be considered two different pointers that
4919  * point to different bpf_spin_locks.
4920  * The verifier allows taking only one bpf_spin_lock at a time to avoid
4921  * dead-locks.
4922  * Since only one bpf_spin_lock is allowed the checks are simpler than
4923  * reg_is_refcounted() logic. The verifier needs to remember only
4924  * one spin_lock instead of array of acquired_refs.
4925  * cur_state->active_spin_lock remembers which map value element got locked
4926  * and clears it after bpf_spin_unlock.
4927  */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)4928 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4929 			     bool is_lock)
4930 {
4931 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4932 	struct bpf_verifier_state *cur = env->cur_state;
4933 	bool is_const = tnum_is_const(reg->var_off);
4934 	struct bpf_map *map = reg->map_ptr;
4935 	u64 val = reg->var_off.value;
4936 
4937 	if (!is_const) {
4938 		verbose(env,
4939 			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4940 			regno);
4941 		return -EINVAL;
4942 	}
4943 	if (!map->btf) {
4944 		verbose(env,
4945 			"map '%s' has to have BTF in order to use bpf_spin_lock\n",
4946 			map->name);
4947 		return -EINVAL;
4948 	}
4949 	if (!map_value_has_spin_lock(map)) {
4950 		if (map->spin_lock_off == -E2BIG)
4951 			verbose(env,
4952 				"map '%s' has more than one 'struct bpf_spin_lock'\n",
4953 				map->name);
4954 		else if (map->spin_lock_off == -ENOENT)
4955 			verbose(env,
4956 				"map '%s' doesn't have 'struct bpf_spin_lock'\n",
4957 				map->name);
4958 		else
4959 			verbose(env,
4960 				"map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4961 				map->name);
4962 		return -EINVAL;
4963 	}
4964 	if (map->spin_lock_off != val + reg->off) {
4965 		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4966 			val + reg->off);
4967 		return -EINVAL;
4968 	}
4969 	if (is_lock) {
4970 		if (cur->active_spin_lock) {
4971 			verbose(env,
4972 				"Locking two bpf_spin_locks are not allowed\n");
4973 			return -EINVAL;
4974 		}
4975 		cur->active_spin_lock = reg->id;
4976 	} else {
4977 		if (!cur->active_spin_lock) {
4978 			verbose(env, "bpf_spin_unlock without taking a lock\n");
4979 			return -EINVAL;
4980 		}
4981 		if (cur->active_spin_lock != reg->id) {
4982 			verbose(env, "bpf_spin_unlock of different lock\n");
4983 			return -EINVAL;
4984 		}
4985 		cur->active_spin_lock = 0;
4986 	}
4987 	return 0;
4988 }
4989 
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)4990 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4991 			      struct bpf_call_arg_meta *meta)
4992 {
4993 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4994 	bool is_const = tnum_is_const(reg->var_off);
4995 	struct bpf_map *map = reg->map_ptr;
4996 	u64 val = reg->var_off.value;
4997 
4998 	if (!is_const) {
4999 		verbose(env,
5000 			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5001 			regno);
5002 		return -EINVAL;
5003 	}
5004 	if (!map->btf) {
5005 		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5006 			map->name);
5007 		return -EINVAL;
5008 	}
5009 	if (!map_value_has_timer(map)) {
5010 		if (map->timer_off == -E2BIG)
5011 			verbose(env,
5012 				"map '%s' has more than one 'struct bpf_timer'\n",
5013 				map->name);
5014 		else if (map->timer_off == -ENOENT)
5015 			verbose(env,
5016 				"map '%s' doesn't have 'struct bpf_timer'\n",
5017 				map->name);
5018 		else
5019 			verbose(env,
5020 				"map '%s' is not a struct type or bpf_timer is mangled\n",
5021 				map->name);
5022 		return -EINVAL;
5023 	}
5024 	if (map->timer_off != val + reg->off) {
5025 		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5026 			val + reg->off, map->timer_off);
5027 		return -EINVAL;
5028 	}
5029 	if (meta->map_ptr) {
5030 		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5031 		return -EFAULT;
5032 	}
5033 	meta->map_uid = reg->map_uid;
5034 	meta->map_ptr = map;
5035 	return 0;
5036 }
5037 
arg_type_is_mem_ptr(enum bpf_arg_type type)5038 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
5039 {
5040 	return base_type(type) == ARG_PTR_TO_MEM ||
5041 	       base_type(type) == ARG_PTR_TO_UNINIT_MEM;
5042 }
5043 
arg_type_is_mem_size(enum bpf_arg_type type)5044 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5045 {
5046 	return type == ARG_CONST_SIZE ||
5047 	       type == ARG_CONST_SIZE_OR_ZERO;
5048 }
5049 
arg_type_is_alloc_size(enum bpf_arg_type type)5050 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5051 {
5052 	return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5053 }
5054 
arg_type_is_int_ptr(enum bpf_arg_type type)5055 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5056 {
5057 	return type == ARG_PTR_TO_INT ||
5058 	       type == ARG_PTR_TO_LONG;
5059 }
5060 
int_ptr_type_to_size(enum bpf_arg_type type)5061 static int int_ptr_type_to_size(enum bpf_arg_type type)
5062 {
5063 	if (type == ARG_PTR_TO_INT)
5064 		return sizeof(u32);
5065 	else if (type == ARG_PTR_TO_LONG)
5066 		return sizeof(u64);
5067 
5068 	return -EINVAL;
5069 }
5070 
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)5071 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5072 				 const struct bpf_call_arg_meta *meta,
5073 				 enum bpf_arg_type *arg_type)
5074 {
5075 	if (!meta->map_ptr) {
5076 		/* kernel subsystem misconfigured verifier */
5077 		verbose(env, "invalid map_ptr to access map->type\n");
5078 		return -EACCES;
5079 	}
5080 
5081 	switch (meta->map_ptr->map_type) {
5082 	case BPF_MAP_TYPE_SOCKMAP:
5083 	case BPF_MAP_TYPE_SOCKHASH:
5084 		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5085 			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5086 		} else {
5087 			verbose(env, "invalid arg_type for sockmap/sockhash\n");
5088 			return -EINVAL;
5089 		}
5090 		break;
5091 
5092 	default:
5093 		break;
5094 	}
5095 	return 0;
5096 }
5097 
5098 struct bpf_reg_types {
5099 	const enum bpf_reg_type types[10];
5100 	u32 *btf_id;
5101 };
5102 
5103 static const struct bpf_reg_types map_key_value_types = {
5104 	.types = {
5105 		PTR_TO_STACK,
5106 		PTR_TO_PACKET,
5107 		PTR_TO_PACKET_META,
5108 		PTR_TO_MAP_KEY,
5109 		PTR_TO_MAP_VALUE,
5110 	},
5111 };
5112 
5113 static const struct bpf_reg_types sock_types = {
5114 	.types = {
5115 		PTR_TO_SOCK_COMMON,
5116 		PTR_TO_SOCKET,
5117 		PTR_TO_TCP_SOCK,
5118 		PTR_TO_XDP_SOCK,
5119 	},
5120 };
5121 
5122 #ifdef CONFIG_NET
5123 static const struct bpf_reg_types btf_id_sock_common_types = {
5124 	.types = {
5125 		PTR_TO_SOCK_COMMON,
5126 		PTR_TO_SOCKET,
5127 		PTR_TO_TCP_SOCK,
5128 		PTR_TO_XDP_SOCK,
5129 		PTR_TO_BTF_ID,
5130 	},
5131 	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5132 };
5133 #endif
5134 
5135 static const struct bpf_reg_types mem_types = {
5136 	.types = {
5137 		PTR_TO_STACK,
5138 		PTR_TO_PACKET,
5139 		PTR_TO_PACKET_META,
5140 		PTR_TO_MAP_KEY,
5141 		PTR_TO_MAP_VALUE,
5142 		PTR_TO_MEM,
5143 		PTR_TO_BUF,
5144 	},
5145 };
5146 
5147 static const struct bpf_reg_types int_ptr_types = {
5148 	.types = {
5149 		PTR_TO_STACK,
5150 		PTR_TO_PACKET,
5151 		PTR_TO_PACKET_META,
5152 		PTR_TO_MAP_KEY,
5153 		PTR_TO_MAP_VALUE,
5154 	},
5155 };
5156 
5157 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5158 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5159 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5160 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
5161 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5162 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5163 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5164 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
5165 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5166 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5167 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5168 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5169 
5170 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5171 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
5172 	[ARG_PTR_TO_MAP_VALUE]		= &map_key_value_types,
5173 	[ARG_PTR_TO_UNINIT_MAP_VALUE]	= &map_key_value_types,
5174 	[ARG_CONST_SIZE]		= &scalar_types,
5175 	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
5176 	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
5177 	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
5178 	[ARG_PTR_TO_CTX]		= &context_types,
5179 	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
5180 #ifdef CONFIG_NET
5181 	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
5182 #endif
5183 	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
5184 	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
5185 	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
5186 	[ARG_PTR_TO_MEM]		= &mem_types,
5187 	[ARG_PTR_TO_UNINIT_MEM]		= &mem_types,
5188 	[ARG_PTR_TO_ALLOC_MEM]		= &alloc_mem_types,
5189 	[ARG_PTR_TO_INT]		= &int_ptr_types,
5190 	[ARG_PTR_TO_LONG]		= &int_ptr_types,
5191 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
5192 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
5193 	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
5194 	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
5195 	[ARG_PTR_TO_TIMER]		= &timer_types,
5196 };
5197 
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id)5198 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5199 			  enum bpf_arg_type arg_type,
5200 			  const u32 *arg_btf_id)
5201 {
5202 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5203 	enum bpf_reg_type expected, type = reg->type;
5204 	const struct bpf_reg_types *compatible;
5205 	int i, j;
5206 
5207 	compatible = compatible_reg_types[base_type(arg_type)];
5208 	if (!compatible) {
5209 		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5210 		return -EFAULT;
5211 	}
5212 
5213 	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5214 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5215 	 *
5216 	 * Same for MAYBE_NULL:
5217 	 *
5218 	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5219 	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5220 	 *
5221 	 * Therefore we fold these flags depending on the arg_type before comparison.
5222 	 */
5223 	if (arg_type & MEM_RDONLY)
5224 		type &= ~MEM_RDONLY;
5225 	if (arg_type & PTR_MAYBE_NULL)
5226 		type &= ~PTR_MAYBE_NULL;
5227 
5228 	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5229 		expected = compatible->types[i];
5230 		if (expected == NOT_INIT)
5231 			break;
5232 
5233 		if (type == expected)
5234 			goto found;
5235 	}
5236 
5237 	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5238 	for (j = 0; j + 1 < i; j++)
5239 		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5240 	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5241 	return -EACCES;
5242 
5243 found:
5244 	if (reg->type == PTR_TO_BTF_ID) {
5245 		if (!arg_btf_id) {
5246 			if (!compatible->btf_id) {
5247 				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5248 				return -EFAULT;
5249 			}
5250 			arg_btf_id = compatible->btf_id;
5251 		}
5252 
5253 		if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5254 					  btf_vmlinux, *arg_btf_id)) {
5255 			verbose(env, "R%d is of type %s but %s is expected\n",
5256 				regno, kernel_type_name(reg->btf, reg->btf_id),
5257 				kernel_type_name(btf_vmlinux, *arg_btf_id));
5258 			return -EACCES;
5259 		}
5260 
5261 		if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5262 			verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5263 				regno);
5264 			return -EACCES;
5265 		}
5266 	}
5267 
5268 	return 0;
5269 }
5270 
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)5271 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5272 			  struct bpf_call_arg_meta *meta,
5273 			  const struct bpf_func_proto *fn)
5274 {
5275 	u32 regno = BPF_REG_1 + arg;
5276 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5277 	enum bpf_arg_type arg_type = fn->arg_type[arg];
5278 	enum bpf_reg_type type = reg->type;
5279 	int err = 0;
5280 
5281 	if (arg_type == ARG_DONTCARE)
5282 		return 0;
5283 
5284 	err = check_reg_arg(env, regno, SRC_OP);
5285 	if (err)
5286 		return err;
5287 
5288 	if (arg_type == ARG_ANYTHING) {
5289 		if (is_pointer_value(env, regno)) {
5290 			verbose(env, "R%d leaks addr into helper function\n",
5291 				regno);
5292 			return -EACCES;
5293 		}
5294 		return 0;
5295 	}
5296 
5297 	if (type_is_pkt_pointer(type) &&
5298 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5299 		verbose(env, "helper access to the packet is not allowed\n");
5300 		return -EACCES;
5301 	}
5302 
5303 	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5304 	    base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5305 		err = resolve_map_arg_type(env, meta, &arg_type);
5306 		if (err)
5307 			return err;
5308 	}
5309 
5310 	if (register_is_null(reg) && type_may_be_null(arg_type))
5311 		/* A NULL register has a SCALAR_VALUE type, so skip
5312 		 * type checking.
5313 		 */
5314 		goto skip_type_check;
5315 
5316 	err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5317 	if (err)
5318 		return err;
5319 
5320 	if (type == PTR_TO_CTX) {
5321 		err = check_ctx_reg(env, reg, regno);
5322 		if (err < 0)
5323 			return err;
5324 	}
5325 
5326 skip_type_check:
5327 	if (reg->ref_obj_id) {
5328 		if (meta->ref_obj_id) {
5329 			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5330 				regno, reg->ref_obj_id,
5331 				meta->ref_obj_id);
5332 			return -EFAULT;
5333 		}
5334 		meta->ref_obj_id = reg->ref_obj_id;
5335 	}
5336 
5337 	if (arg_type == ARG_CONST_MAP_PTR) {
5338 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5339 		if (meta->map_ptr) {
5340 			/* Use map_uid (which is unique id of inner map) to reject:
5341 			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5342 			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5343 			 * if (inner_map1 && inner_map2) {
5344 			 *     timer = bpf_map_lookup_elem(inner_map1);
5345 			 *     if (timer)
5346 			 *         // mismatch would have been allowed
5347 			 *         bpf_timer_init(timer, inner_map2);
5348 			 * }
5349 			 *
5350 			 * Comparing map_ptr is enough to distinguish normal and outer maps.
5351 			 */
5352 			if (meta->map_ptr != reg->map_ptr ||
5353 			    meta->map_uid != reg->map_uid) {
5354 				verbose(env,
5355 					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5356 					meta->map_uid, reg->map_uid);
5357 				return -EINVAL;
5358 			}
5359 		}
5360 		meta->map_ptr = reg->map_ptr;
5361 		meta->map_uid = reg->map_uid;
5362 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5363 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
5364 		 * check that [key, key + map->key_size) are within
5365 		 * stack limits and initialized
5366 		 */
5367 		if (!meta->map_ptr) {
5368 			/* in function declaration map_ptr must come before
5369 			 * map_key, so that it's verified and known before
5370 			 * we have to check map_key here. Otherwise it means
5371 			 * that kernel subsystem misconfigured verifier
5372 			 */
5373 			verbose(env, "invalid map_ptr to access map->key\n");
5374 			return -EACCES;
5375 		}
5376 		err = check_helper_mem_access(env, regno,
5377 					      meta->map_ptr->key_size, false,
5378 					      NULL);
5379 	} else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE ||
5380 		   base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5381 		if (type_may_be_null(arg_type) && register_is_null(reg))
5382 			return 0;
5383 
5384 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
5385 		 * check [value, value + map->value_size) validity
5386 		 */
5387 		if (!meta->map_ptr) {
5388 			/* kernel subsystem misconfigured verifier */
5389 			verbose(env, "invalid map_ptr to access map->value\n");
5390 			return -EACCES;
5391 		}
5392 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5393 		err = check_helper_mem_access(env, regno,
5394 					      meta->map_ptr->value_size, false,
5395 					      meta);
5396 	} else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5397 		if (!reg->btf_id) {
5398 			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5399 			return -EACCES;
5400 		}
5401 		meta->ret_btf = reg->btf;
5402 		meta->ret_btf_id = reg->btf_id;
5403 	} else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5404 		if (meta->func_id == BPF_FUNC_spin_lock) {
5405 			if (process_spin_lock(env, regno, true))
5406 				return -EACCES;
5407 		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
5408 			if (process_spin_lock(env, regno, false))
5409 				return -EACCES;
5410 		} else {
5411 			verbose(env, "verifier internal error\n");
5412 			return -EFAULT;
5413 		}
5414 	} else if (arg_type == ARG_PTR_TO_TIMER) {
5415 		if (process_timer_func(env, regno, meta))
5416 			return -EACCES;
5417 	} else if (arg_type == ARG_PTR_TO_FUNC) {
5418 		meta->subprogno = reg->subprogno;
5419 	} else if (arg_type_is_mem_ptr(arg_type)) {
5420 		/* The access to this pointer is only checked when we hit the
5421 		 * next is_mem_size argument below.
5422 		 */
5423 		meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5424 	} else if (arg_type_is_mem_size(arg_type)) {
5425 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5426 
5427 		/* This is used to refine r0 return value bounds for helpers
5428 		 * that enforce this value as an upper bound on return values.
5429 		 * See do_refine_retval_range() for helpers that can refine
5430 		 * the return value. C type of helper is u32 so we pull register
5431 		 * bound from umax_value however, if negative verifier errors
5432 		 * out. Only upper bounds can be learned because retval is an
5433 		 * int type and negative retvals are allowed.
5434 		 */
5435 		meta->msize_max_value = reg->umax_value;
5436 
5437 		/* The register is SCALAR_VALUE; the access check
5438 		 * happens using its boundaries.
5439 		 */
5440 		if (!tnum_is_const(reg->var_off))
5441 			/* For unprivileged variable accesses, disable raw
5442 			 * mode so that the program is required to
5443 			 * initialize all the memory that the helper could
5444 			 * just partially fill up.
5445 			 */
5446 			meta = NULL;
5447 
5448 		if (reg->smin_value < 0) {
5449 			verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5450 				regno);
5451 			return -EACCES;
5452 		}
5453 
5454 		if (reg->umin_value == 0) {
5455 			err = check_helper_mem_access(env, regno - 1, 0,
5456 						      zero_size_allowed,
5457 						      meta);
5458 			if (err)
5459 				return err;
5460 		}
5461 
5462 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5463 			verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5464 				regno);
5465 			return -EACCES;
5466 		}
5467 		err = check_helper_mem_access(env, regno - 1,
5468 					      reg->umax_value,
5469 					      zero_size_allowed, meta);
5470 		if (!err)
5471 			err = mark_chain_precision(env, regno);
5472 	} else if (arg_type_is_alloc_size(arg_type)) {
5473 		if (!tnum_is_const(reg->var_off)) {
5474 			verbose(env, "R%d is not a known constant'\n",
5475 				regno);
5476 			return -EACCES;
5477 		}
5478 		meta->mem_size = reg->var_off.value;
5479 	} else if (arg_type_is_int_ptr(arg_type)) {
5480 		int size = int_ptr_type_to_size(arg_type);
5481 
5482 		err = check_helper_mem_access(env, regno, size, false, meta);
5483 		if (err)
5484 			return err;
5485 		err = check_ptr_alignment(env, reg, 0, size, true);
5486 	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
5487 		struct bpf_map *map = reg->map_ptr;
5488 		int map_off;
5489 		u64 map_addr;
5490 		char *str_ptr;
5491 
5492 		if (!bpf_map_is_rdonly(map)) {
5493 			verbose(env, "R%d does not point to a readonly map'\n", regno);
5494 			return -EACCES;
5495 		}
5496 
5497 		if (!tnum_is_const(reg->var_off)) {
5498 			verbose(env, "R%d is not a constant address'\n", regno);
5499 			return -EACCES;
5500 		}
5501 
5502 		if (!map->ops->map_direct_value_addr) {
5503 			verbose(env, "no direct value access support for this map type\n");
5504 			return -EACCES;
5505 		}
5506 
5507 		err = check_map_access(env, regno, reg->off,
5508 				       map->value_size - reg->off, false);
5509 		if (err)
5510 			return err;
5511 
5512 		map_off = reg->off + reg->var_off.value;
5513 		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5514 		if (err) {
5515 			verbose(env, "direct value access on string failed\n");
5516 			return err;
5517 		}
5518 
5519 		str_ptr = (char *)(long)(map_addr);
5520 		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5521 			verbose(env, "string is not zero-terminated\n");
5522 			return -EINVAL;
5523 		}
5524 	}
5525 
5526 	return err;
5527 }
5528 
may_update_sockmap(struct bpf_verifier_env * env,int func_id)5529 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5530 {
5531 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
5532 	enum bpf_prog_type type = resolve_prog_type(env->prog);
5533 
5534 	if (func_id != BPF_FUNC_map_update_elem)
5535 		return false;
5536 
5537 	/* It's not possible to get access to a locked struct sock in these
5538 	 * contexts, so updating is safe.
5539 	 */
5540 	switch (type) {
5541 	case BPF_PROG_TYPE_TRACING:
5542 		if (eatype == BPF_TRACE_ITER)
5543 			return true;
5544 		break;
5545 	case BPF_PROG_TYPE_SOCKET_FILTER:
5546 	case BPF_PROG_TYPE_SCHED_CLS:
5547 	case BPF_PROG_TYPE_SCHED_ACT:
5548 	case BPF_PROG_TYPE_XDP:
5549 	case BPF_PROG_TYPE_SK_REUSEPORT:
5550 	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5551 	case BPF_PROG_TYPE_SK_LOOKUP:
5552 		return true;
5553 	default:
5554 		break;
5555 	}
5556 
5557 	verbose(env, "cannot update sockmap in this context\n");
5558 	return false;
5559 }
5560 
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)5561 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5562 {
5563 	return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5564 }
5565 
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)5566 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5567 					struct bpf_map *map, int func_id)
5568 {
5569 	if (!map)
5570 		return 0;
5571 
5572 	/* We need a two way check, first is from map perspective ... */
5573 	switch (map->map_type) {
5574 	case BPF_MAP_TYPE_PROG_ARRAY:
5575 		if (func_id != BPF_FUNC_tail_call)
5576 			goto error;
5577 		break;
5578 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5579 		if (func_id != BPF_FUNC_perf_event_read &&
5580 		    func_id != BPF_FUNC_perf_event_output &&
5581 		    func_id != BPF_FUNC_skb_output &&
5582 		    func_id != BPF_FUNC_perf_event_read_value &&
5583 		    func_id != BPF_FUNC_xdp_output)
5584 			goto error;
5585 		break;
5586 	case BPF_MAP_TYPE_RINGBUF:
5587 		if (func_id != BPF_FUNC_ringbuf_output &&
5588 		    func_id != BPF_FUNC_ringbuf_reserve &&
5589 		    func_id != BPF_FUNC_ringbuf_query)
5590 			goto error;
5591 		break;
5592 	case BPF_MAP_TYPE_STACK_TRACE:
5593 		if (func_id != BPF_FUNC_get_stackid)
5594 			goto error;
5595 		break;
5596 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5597 		if (func_id != BPF_FUNC_skb_under_cgroup &&
5598 		    func_id != BPF_FUNC_current_task_under_cgroup)
5599 			goto error;
5600 		break;
5601 	case BPF_MAP_TYPE_CGROUP_STORAGE:
5602 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5603 		if (func_id != BPF_FUNC_get_local_storage)
5604 			goto error;
5605 		break;
5606 	case BPF_MAP_TYPE_DEVMAP:
5607 	case BPF_MAP_TYPE_DEVMAP_HASH:
5608 		if (func_id != BPF_FUNC_redirect_map &&
5609 		    func_id != BPF_FUNC_map_lookup_elem)
5610 			goto error;
5611 		break;
5612 	/* Restrict bpf side of cpumap and xskmap, open when use-cases
5613 	 * appear.
5614 	 */
5615 	case BPF_MAP_TYPE_CPUMAP:
5616 		if (func_id != BPF_FUNC_redirect_map)
5617 			goto error;
5618 		break;
5619 	case BPF_MAP_TYPE_XSKMAP:
5620 		if (func_id != BPF_FUNC_redirect_map &&
5621 		    func_id != BPF_FUNC_map_lookup_elem)
5622 			goto error;
5623 		break;
5624 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5625 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5626 		if (func_id != BPF_FUNC_map_lookup_elem)
5627 			goto error;
5628 		break;
5629 	case BPF_MAP_TYPE_SOCKMAP:
5630 		if (func_id != BPF_FUNC_sk_redirect_map &&
5631 		    func_id != BPF_FUNC_sock_map_update &&
5632 		    func_id != BPF_FUNC_map_delete_elem &&
5633 		    func_id != BPF_FUNC_msg_redirect_map &&
5634 		    func_id != BPF_FUNC_sk_select_reuseport &&
5635 		    func_id != BPF_FUNC_map_lookup_elem &&
5636 		    !may_update_sockmap(env, func_id))
5637 			goto error;
5638 		break;
5639 	case BPF_MAP_TYPE_SOCKHASH:
5640 		if (func_id != BPF_FUNC_sk_redirect_hash &&
5641 		    func_id != BPF_FUNC_sock_hash_update &&
5642 		    func_id != BPF_FUNC_map_delete_elem &&
5643 		    func_id != BPF_FUNC_msg_redirect_hash &&
5644 		    func_id != BPF_FUNC_sk_select_reuseport &&
5645 		    func_id != BPF_FUNC_map_lookup_elem &&
5646 		    !may_update_sockmap(env, func_id))
5647 			goto error;
5648 		break;
5649 	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5650 		if (func_id != BPF_FUNC_sk_select_reuseport)
5651 			goto error;
5652 		break;
5653 	case BPF_MAP_TYPE_QUEUE:
5654 	case BPF_MAP_TYPE_STACK:
5655 		if (func_id != BPF_FUNC_map_peek_elem &&
5656 		    func_id != BPF_FUNC_map_pop_elem &&
5657 		    func_id != BPF_FUNC_map_push_elem)
5658 			goto error;
5659 		break;
5660 	case BPF_MAP_TYPE_SK_STORAGE:
5661 		if (func_id != BPF_FUNC_sk_storage_get &&
5662 		    func_id != BPF_FUNC_sk_storage_delete)
5663 			goto error;
5664 		break;
5665 	case BPF_MAP_TYPE_INODE_STORAGE:
5666 		if (func_id != BPF_FUNC_inode_storage_get &&
5667 		    func_id != BPF_FUNC_inode_storage_delete)
5668 			goto error;
5669 		break;
5670 	case BPF_MAP_TYPE_TASK_STORAGE:
5671 		if (func_id != BPF_FUNC_task_storage_get &&
5672 		    func_id != BPF_FUNC_task_storage_delete)
5673 			goto error;
5674 		break;
5675 	default:
5676 		break;
5677 	}
5678 
5679 	/* ... and second from the function itself. */
5680 	switch (func_id) {
5681 	case BPF_FUNC_tail_call:
5682 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5683 			goto error;
5684 		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5685 			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5686 			return -EINVAL;
5687 		}
5688 		break;
5689 	case BPF_FUNC_perf_event_read:
5690 	case BPF_FUNC_perf_event_output:
5691 	case BPF_FUNC_perf_event_read_value:
5692 	case BPF_FUNC_skb_output:
5693 	case BPF_FUNC_xdp_output:
5694 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5695 			goto error;
5696 		break;
5697 	case BPF_FUNC_ringbuf_output:
5698 	case BPF_FUNC_ringbuf_reserve:
5699 	case BPF_FUNC_ringbuf_query:
5700 		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5701 			goto error;
5702 		break;
5703 	case BPF_FUNC_get_stackid:
5704 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5705 			goto error;
5706 		break;
5707 	case BPF_FUNC_current_task_under_cgroup:
5708 	case BPF_FUNC_skb_under_cgroup:
5709 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5710 			goto error;
5711 		break;
5712 	case BPF_FUNC_redirect_map:
5713 		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5714 		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5715 		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
5716 		    map->map_type != BPF_MAP_TYPE_XSKMAP)
5717 			goto error;
5718 		break;
5719 	case BPF_FUNC_sk_redirect_map:
5720 	case BPF_FUNC_msg_redirect_map:
5721 	case BPF_FUNC_sock_map_update:
5722 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5723 			goto error;
5724 		break;
5725 	case BPF_FUNC_sk_redirect_hash:
5726 	case BPF_FUNC_msg_redirect_hash:
5727 	case BPF_FUNC_sock_hash_update:
5728 		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5729 			goto error;
5730 		break;
5731 	case BPF_FUNC_get_local_storage:
5732 		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5733 		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5734 			goto error;
5735 		break;
5736 	case BPF_FUNC_sk_select_reuseport:
5737 		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5738 		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5739 		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
5740 			goto error;
5741 		break;
5742 	case BPF_FUNC_map_peek_elem:
5743 	case BPF_FUNC_map_pop_elem:
5744 	case BPF_FUNC_map_push_elem:
5745 		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5746 		    map->map_type != BPF_MAP_TYPE_STACK)
5747 			goto error;
5748 		break;
5749 	case BPF_FUNC_sk_storage_get:
5750 	case BPF_FUNC_sk_storage_delete:
5751 		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5752 			goto error;
5753 		break;
5754 	case BPF_FUNC_inode_storage_get:
5755 	case BPF_FUNC_inode_storage_delete:
5756 		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5757 			goto error;
5758 		break;
5759 	case BPF_FUNC_task_storage_get:
5760 	case BPF_FUNC_task_storage_delete:
5761 		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5762 			goto error;
5763 		break;
5764 	default:
5765 		break;
5766 	}
5767 
5768 	return 0;
5769 error:
5770 	verbose(env, "cannot pass map_type %d into func %s#%d\n",
5771 		map->map_type, func_id_name(func_id), func_id);
5772 	return -EINVAL;
5773 }
5774 
check_raw_mode_ok(const struct bpf_func_proto * fn)5775 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5776 {
5777 	int count = 0;
5778 
5779 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5780 		count++;
5781 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5782 		count++;
5783 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5784 		count++;
5785 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5786 		count++;
5787 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5788 		count++;
5789 
5790 	/* We only support one arg being in raw mode at the moment,
5791 	 * which is sufficient for the helper functions we have
5792 	 * right now.
5793 	 */
5794 	return count <= 1;
5795 }
5796 
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)5797 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5798 				    enum bpf_arg_type arg_next)
5799 {
5800 	return (arg_type_is_mem_ptr(arg_curr) &&
5801 	        !arg_type_is_mem_size(arg_next)) ||
5802 	       (!arg_type_is_mem_ptr(arg_curr) &&
5803 		arg_type_is_mem_size(arg_next));
5804 }
5805 
check_arg_pair_ok(const struct bpf_func_proto * fn)5806 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5807 {
5808 	/* bpf_xxx(..., buf, len) call will access 'len'
5809 	 * bytes from memory 'buf'. Both arg types need
5810 	 * to be paired, so make sure there's no buggy
5811 	 * helper function specification.
5812 	 */
5813 	if (arg_type_is_mem_size(fn->arg1_type) ||
5814 	    arg_type_is_mem_ptr(fn->arg5_type)  ||
5815 	    check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5816 	    check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5817 	    check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5818 	    check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5819 		return false;
5820 
5821 	return true;
5822 }
5823 
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5824 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5825 {
5826 	int count = 0;
5827 
5828 	if (arg_type_may_be_refcounted(fn->arg1_type))
5829 		count++;
5830 	if (arg_type_may_be_refcounted(fn->arg2_type))
5831 		count++;
5832 	if (arg_type_may_be_refcounted(fn->arg3_type))
5833 		count++;
5834 	if (arg_type_may_be_refcounted(fn->arg4_type))
5835 		count++;
5836 	if (arg_type_may_be_refcounted(fn->arg5_type))
5837 		count++;
5838 
5839 	/* A reference acquiring function cannot acquire
5840 	 * another refcounted ptr.
5841 	 */
5842 	if (may_be_acquire_function(func_id) && count)
5843 		return false;
5844 
5845 	/* We only support one arg being unreferenced at the moment,
5846 	 * which is sufficient for the helper functions we have right now.
5847 	 */
5848 	return count <= 1;
5849 }
5850 
check_btf_id_ok(const struct bpf_func_proto * fn)5851 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5852 {
5853 	int i;
5854 
5855 	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5856 		if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5857 			return false;
5858 
5859 		if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5860 			return false;
5861 	}
5862 
5863 	return true;
5864 }
5865 
check_func_proto(const struct bpf_func_proto * fn,int func_id)5866 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5867 {
5868 	return check_raw_mode_ok(fn) &&
5869 	       check_arg_pair_ok(fn) &&
5870 	       check_btf_id_ok(fn) &&
5871 	       check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5872 }
5873 
5874 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5875  * are now invalid, so turn them into unknown SCALAR_VALUE.
5876  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5877 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5878 {
5879 	struct bpf_func_state *state;
5880 	struct bpf_reg_state *reg;
5881 
5882 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5883 		if (reg_is_pkt_pointer_any(reg))
5884 			__mark_reg_unknown(env, reg);
5885 	}));
5886 }
5887 
5888 enum {
5889 	AT_PKT_END = -1,
5890 	BEYOND_PKT_END = -2,
5891 };
5892 
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5893 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5894 {
5895 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5896 	struct bpf_reg_state *reg = &state->regs[regn];
5897 
5898 	if (reg->type != PTR_TO_PACKET)
5899 		/* PTR_TO_PACKET_META is not supported yet */
5900 		return;
5901 
5902 	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5903 	 * How far beyond pkt_end it goes is unknown.
5904 	 * if (!range_open) it's the case of pkt >= pkt_end
5905 	 * if (range_open) it's the case of pkt > pkt_end
5906 	 * hence this pointer is at least 1 byte bigger than pkt_end
5907 	 */
5908 	if (range_open)
5909 		reg->range = BEYOND_PKT_END;
5910 	else
5911 		reg->range = AT_PKT_END;
5912 }
5913 
5914 /* The pointer with the specified id has released its reference to kernel
5915  * resources. Identify all copies of the same pointer and clear the reference.
5916  */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5917 static int release_reference(struct bpf_verifier_env *env,
5918 			     int ref_obj_id)
5919 {
5920 	struct bpf_func_state *state;
5921 	struct bpf_reg_state *reg;
5922 	int err;
5923 
5924 	err = release_reference_state(cur_func(env), ref_obj_id);
5925 	if (err)
5926 		return err;
5927 
5928 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5929 		if (reg->ref_obj_id == ref_obj_id) {
5930 			if (!env->allow_ptr_leaks)
5931 				__mark_reg_not_init(env, reg);
5932 			else
5933 				__mark_reg_unknown(env, reg);
5934 		}
5935 	}));
5936 
5937 	return 0;
5938 }
5939 
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5940 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5941 				    struct bpf_reg_state *regs)
5942 {
5943 	int i;
5944 
5945 	/* after the call registers r0 - r5 were scratched */
5946 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
5947 		mark_reg_not_init(env, regs, caller_saved[i]);
5948 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5949 	}
5950 }
5951 
5952 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5953 				   struct bpf_func_state *caller,
5954 				   struct bpf_func_state *callee,
5955 				   int insn_idx);
5956 
5957 static int set_callee_state(struct bpf_verifier_env *env,
5958 			    struct bpf_func_state *caller,
5959 			    struct bpf_func_state *callee, int insn_idx);
5960 
__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)5961 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5962 			     int *insn_idx, int subprog,
5963 			     set_callee_state_fn set_callee_state_cb)
5964 {
5965 	struct bpf_verifier_state *state = env->cur_state;
5966 	struct bpf_func_info_aux *func_info_aux;
5967 	struct bpf_func_state *caller, *callee;
5968 	int err;
5969 	bool is_global = false;
5970 
5971 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5972 		verbose(env, "the call stack of %d frames is too deep\n",
5973 			state->curframe + 2);
5974 		return -E2BIG;
5975 	}
5976 
5977 	caller = state->frame[state->curframe];
5978 	if (state->frame[state->curframe + 1]) {
5979 		verbose(env, "verifier bug. Frame %d already allocated\n",
5980 			state->curframe + 1);
5981 		return -EFAULT;
5982 	}
5983 
5984 	func_info_aux = env->prog->aux->func_info_aux;
5985 	if (func_info_aux)
5986 		is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5987 	err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5988 	if (err == -EFAULT)
5989 		return err;
5990 	if (is_global) {
5991 		if (err) {
5992 			verbose(env, "Caller passes invalid args into func#%d\n",
5993 				subprog);
5994 			return err;
5995 		} else {
5996 			if (env->log.level & BPF_LOG_LEVEL)
5997 				verbose(env,
5998 					"Func#%d is global and valid. Skipping.\n",
5999 					subprog);
6000 			clear_caller_saved_regs(env, caller->regs);
6001 
6002 			/* All global functions return a 64-bit SCALAR_VALUE */
6003 			mark_reg_unknown(env, caller->regs, BPF_REG_0);
6004 			caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6005 
6006 			/* continue with next insn after call */
6007 			return 0;
6008 		}
6009 	}
6010 
6011 	/* set_callee_state is used for direct subprog calls, but we are
6012 	 * interested in validating only BPF helpers that can call subprogs as
6013 	 * callbacks
6014 	 */
6015 	if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6016 		verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6017 			func_id_name(insn->imm), insn->imm);
6018 		return -EFAULT;
6019 	}
6020 
6021 	if (insn->code == (BPF_JMP | BPF_CALL) &&
6022 	    insn->src_reg == 0 &&
6023 	    insn->imm == BPF_FUNC_timer_set_callback) {
6024 		struct bpf_verifier_state *async_cb;
6025 
6026 		/* there is no real recursion here. timer callbacks are async */
6027 		env->subprog_info[subprog].is_async_cb = true;
6028 		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6029 					 *insn_idx, subprog);
6030 		if (!async_cb)
6031 			return -EFAULT;
6032 		callee = async_cb->frame[0];
6033 		callee->async_entry_cnt = caller->async_entry_cnt + 1;
6034 
6035 		/* Convert bpf_timer_set_callback() args into timer callback args */
6036 		err = set_callee_state_cb(env, caller, callee, *insn_idx);
6037 		if (err)
6038 			return err;
6039 
6040 		clear_caller_saved_regs(env, caller->regs);
6041 		mark_reg_unknown(env, caller->regs, BPF_REG_0);
6042 		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6043 		/* continue with next insn after call */
6044 		return 0;
6045 	}
6046 
6047 	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6048 	if (!callee)
6049 		return -ENOMEM;
6050 	state->frame[state->curframe + 1] = callee;
6051 
6052 	/* callee cannot access r0, r6 - r9 for reading and has to write
6053 	 * into its own stack before reading from it.
6054 	 * callee can read/write into caller's stack
6055 	 */
6056 	init_func_state(env, callee,
6057 			/* remember the callsite, it will be used by bpf_exit */
6058 			*insn_idx /* callsite */,
6059 			state->curframe + 1 /* frameno within this callchain */,
6060 			subprog /* subprog number within this prog */);
6061 
6062 	/* Transfer references to the callee */
6063 	err = copy_reference_state(callee, caller);
6064 	if (err)
6065 		goto err_out;
6066 
6067 	err = set_callee_state_cb(env, caller, callee, *insn_idx);
6068 	if (err)
6069 		goto err_out;
6070 
6071 	clear_caller_saved_regs(env, caller->regs);
6072 
6073 	/* only increment it after check_reg_arg() finished */
6074 	state->curframe++;
6075 
6076 	/* and go analyze first insn of the callee */
6077 	*insn_idx = env->subprog_info[subprog].start - 1;
6078 
6079 	if (env->log.level & BPF_LOG_LEVEL) {
6080 		verbose(env, "caller:\n");
6081 		print_verifier_state(env, caller);
6082 		verbose(env, "callee:\n");
6083 		print_verifier_state(env, callee);
6084 	}
6085 	return 0;
6086 
6087 err_out:
6088 	free_func_state(callee);
6089 	state->frame[state->curframe + 1] = NULL;
6090 	return err;
6091 }
6092 
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)6093 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6094 				   struct bpf_func_state *caller,
6095 				   struct bpf_func_state *callee)
6096 {
6097 	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6098 	 *      void *callback_ctx, u64 flags);
6099 	 * callback_fn(struct bpf_map *map, void *key, void *value,
6100 	 *      void *callback_ctx);
6101 	 */
6102 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6103 
6104 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6105 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6106 	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6107 
6108 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6109 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6110 	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6111 
6112 	/* pointer to stack or null */
6113 	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6114 
6115 	/* unused */
6116 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6117 	return 0;
6118 }
6119 
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6120 static int set_callee_state(struct bpf_verifier_env *env,
6121 			    struct bpf_func_state *caller,
6122 			    struct bpf_func_state *callee, int insn_idx)
6123 {
6124 	int i;
6125 
6126 	/* copy r1 - r5 args that callee can access.  The copy includes parent
6127 	 * pointers, which connects us up to the liveness chain
6128 	 */
6129 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6130 		callee->regs[i] = caller->regs[i];
6131 	return 0;
6132 }
6133 
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)6134 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6135 			   int *insn_idx)
6136 {
6137 	int subprog, target_insn;
6138 
6139 	target_insn = *insn_idx + insn->imm + 1;
6140 	subprog = find_subprog(env, target_insn);
6141 	if (subprog < 0) {
6142 		verbose(env, "verifier bug. No program starts at insn %d\n",
6143 			target_insn);
6144 		return -EFAULT;
6145 	}
6146 
6147 	return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6148 }
6149 
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6150 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6151 				       struct bpf_func_state *caller,
6152 				       struct bpf_func_state *callee,
6153 				       int insn_idx)
6154 {
6155 	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6156 	struct bpf_map *map;
6157 	int err;
6158 
6159 	if (bpf_map_ptr_poisoned(insn_aux)) {
6160 		verbose(env, "tail_call abusing map_ptr\n");
6161 		return -EINVAL;
6162 	}
6163 
6164 	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6165 	if (!map->ops->map_set_for_each_callback_args ||
6166 	    !map->ops->map_for_each_callback) {
6167 		verbose(env, "callback function not allowed for map\n");
6168 		return -ENOTSUPP;
6169 	}
6170 
6171 	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6172 	if (err)
6173 		return err;
6174 
6175 	callee->in_callback_fn = true;
6176 	return 0;
6177 }
6178 
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)6179 static int set_timer_callback_state(struct bpf_verifier_env *env,
6180 				    struct bpf_func_state *caller,
6181 				    struct bpf_func_state *callee,
6182 				    int insn_idx)
6183 {
6184 	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6185 
6186 	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6187 	 * callback_fn(struct bpf_map *map, void *key, void *value);
6188 	 */
6189 	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6190 	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6191 	callee->regs[BPF_REG_1].map_ptr = map_ptr;
6192 
6193 	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6194 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6195 	callee->regs[BPF_REG_2].map_ptr = map_ptr;
6196 
6197 	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6198 	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6199 	callee->regs[BPF_REG_3].map_ptr = map_ptr;
6200 
6201 	/* unused */
6202 	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6203 	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6204 	callee->in_async_callback_fn = true;
6205 	return 0;
6206 }
6207 
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)6208 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6209 {
6210 	struct bpf_verifier_state *state = env->cur_state;
6211 	struct bpf_func_state *caller, *callee;
6212 	struct bpf_reg_state *r0;
6213 	int err;
6214 
6215 	callee = state->frame[state->curframe];
6216 	r0 = &callee->regs[BPF_REG_0];
6217 	if (r0->type == PTR_TO_STACK) {
6218 		/* technically it's ok to return caller's stack pointer
6219 		 * (or caller's caller's pointer) back to the caller,
6220 		 * since these pointers are valid. Only current stack
6221 		 * pointer will be invalid as soon as function exits,
6222 		 * but let's be conservative
6223 		 */
6224 		verbose(env, "cannot return stack pointer to the caller\n");
6225 		return -EINVAL;
6226 	}
6227 
6228 	caller = state->frame[state->curframe - 1];
6229 	if (callee->in_callback_fn) {
6230 		/* enforce R0 return value range [0, 1]. */
6231 		struct tnum range = tnum_range(0, 1);
6232 
6233 		if (r0->type != SCALAR_VALUE) {
6234 			verbose(env, "R0 not a scalar value\n");
6235 			return -EACCES;
6236 		}
6237 
6238 		/* we are going to rely on register's precise value */
6239 		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
6240 		err = err ?: mark_chain_precision(env, BPF_REG_0);
6241 		if (err)
6242 			return err;
6243 
6244 		if (!tnum_in(range, r0->var_off)) {
6245 			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6246 			return -EINVAL;
6247 		}
6248 	} else {
6249 		/* return to the caller whatever r0 had in the callee */
6250 		caller->regs[BPF_REG_0] = *r0;
6251 	}
6252 
6253 	/* Transfer references to the caller */
6254 	err = copy_reference_state(caller, callee);
6255 	if (err)
6256 		return err;
6257 
6258 	*insn_idx = callee->callsite + 1;
6259 	if (env->log.level & BPF_LOG_LEVEL) {
6260 		verbose(env, "returning from callee:\n");
6261 		print_verifier_state(env, callee);
6262 		verbose(env, "to caller at %d:\n", *insn_idx);
6263 		print_verifier_state(env, caller);
6264 	}
6265 	/* clear everything in the callee */
6266 	free_func_state(callee);
6267 	state->frame[state->curframe--] = NULL;
6268 	return 0;
6269 }
6270 
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)6271 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6272 				   int func_id,
6273 				   struct bpf_call_arg_meta *meta)
6274 {
6275 	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6276 
6277 	if (ret_type != RET_INTEGER ||
6278 	    (func_id != BPF_FUNC_get_stack &&
6279 	     func_id != BPF_FUNC_get_task_stack &&
6280 	     func_id != BPF_FUNC_probe_read_str &&
6281 	     func_id != BPF_FUNC_probe_read_kernel_str &&
6282 	     func_id != BPF_FUNC_probe_read_user_str))
6283 		return;
6284 
6285 	ret_reg->smax_value = meta->msize_max_value;
6286 	ret_reg->s32_max_value = meta->msize_max_value;
6287 	ret_reg->smin_value = -MAX_ERRNO;
6288 	ret_reg->s32_min_value = -MAX_ERRNO;
6289 	reg_bounds_sync(ret_reg);
6290 }
6291 
6292 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)6293 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6294 		int func_id, int insn_idx)
6295 {
6296 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6297 	struct bpf_map *map = meta->map_ptr;
6298 
6299 	if (func_id != BPF_FUNC_tail_call &&
6300 	    func_id != BPF_FUNC_map_lookup_elem &&
6301 	    func_id != BPF_FUNC_map_update_elem &&
6302 	    func_id != BPF_FUNC_map_delete_elem &&
6303 	    func_id != BPF_FUNC_map_push_elem &&
6304 	    func_id != BPF_FUNC_map_pop_elem &&
6305 	    func_id != BPF_FUNC_map_peek_elem &&
6306 	    func_id != BPF_FUNC_for_each_map_elem &&
6307 	    func_id != BPF_FUNC_redirect_map)
6308 		return 0;
6309 
6310 	if (map == NULL) {
6311 		verbose(env, "kernel subsystem misconfigured verifier\n");
6312 		return -EINVAL;
6313 	}
6314 
6315 	/* In case of read-only, some additional restrictions
6316 	 * need to be applied in order to prevent altering the
6317 	 * state of the map from program side.
6318 	 */
6319 	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6320 	    (func_id == BPF_FUNC_map_delete_elem ||
6321 	     func_id == BPF_FUNC_map_update_elem ||
6322 	     func_id == BPF_FUNC_map_push_elem ||
6323 	     func_id == BPF_FUNC_map_pop_elem)) {
6324 		verbose(env, "write into map forbidden\n");
6325 		return -EACCES;
6326 	}
6327 
6328 	if (!BPF_MAP_PTR(aux->map_ptr_state))
6329 		bpf_map_ptr_store(aux, meta->map_ptr,
6330 				  !meta->map_ptr->bypass_spec_v1);
6331 	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6332 		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6333 				  !meta->map_ptr->bypass_spec_v1);
6334 	return 0;
6335 }
6336 
6337 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)6338 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6339 		int func_id, int insn_idx)
6340 {
6341 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6342 	struct bpf_reg_state *regs = cur_regs(env), *reg;
6343 	struct bpf_map *map = meta->map_ptr;
6344 	u64 val, max;
6345 	int err;
6346 
6347 	if (func_id != BPF_FUNC_tail_call)
6348 		return 0;
6349 	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6350 		verbose(env, "kernel subsystem misconfigured verifier\n");
6351 		return -EINVAL;
6352 	}
6353 
6354 	reg = &regs[BPF_REG_3];
6355 	val = reg->var_off.value;
6356 	max = map->max_entries;
6357 
6358 	if (!(register_is_const(reg) && val < max)) {
6359 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6360 		return 0;
6361 	}
6362 
6363 	err = mark_chain_precision(env, BPF_REG_3);
6364 	if (err)
6365 		return err;
6366 	if (bpf_map_key_unseen(aux))
6367 		bpf_map_key_store(aux, val);
6368 	else if (!bpf_map_key_poisoned(aux) &&
6369 		  bpf_map_key_immediate(aux) != val)
6370 		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6371 	return 0;
6372 }
6373 
check_reference_leak(struct bpf_verifier_env * env)6374 static int check_reference_leak(struct bpf_verifier_env *env)
6375 {
6376 	struct bpf_func_state *state = cur_func(env);
6377 	int i;
6378 
6379 	for (i = 0; i < state->acquired_refs; i++) {
6380 		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6381 			state->refs[i].id, state->refs[i].insn_idx);
6382 	}
6383 	return state->acquired_refs ? -EINVAL : 0;
6384 }
6385 
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)6386 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6387 				   struct bpf_reg_state *regs)
6388 {
6389 	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6390 	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6391 	struct bpf_map *fmt_map = fmt_reg->map_ptr;
6392 	int err, fmt_map_off, num_args;
6393 	u64 fmt_addr;
6394 	char *fmt;
6395 
6396 	/* data must be an array of u64 */
6397 	if (data_len_reg->var_off.value % 8)
6398 		return -EINVAL;
6399 	num_args = data_len_reg->var_off.value / 8;
6400 
6401 	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6402 	 * and map_direct_value_addr is set.
6403 	 */
6404 	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6405 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6406 						  fmt_map_off);
6407 	if (err) {
6408 		verbose(env, "verifier bug\n");
6409 		return -EFAULT;
6410 	}
6411 	fmt = (char *)(long)fmt_addr + fmt_map_off;
6412 
6413 	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6414 	 * can focus on validating the format specifiers.
6415 	 */
6416 	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6417 	if (err < 0)
6418 		verbose(env, "Invalid format string\n");
6419 
6420 	return err;
6421 }
6422 
check_get_func_ip(struct bpf_verifier_env * env)6423 static int check_get_func_ip(struct bpf_verifier_env *env)
6424 {
6425 	enum bpf_attach_type eatype = env->prog->expected_attach_type;
6426 	enum bpf_prog_type type = resolve_prog_type(env->prog);
6427 	int func_id = BPF_FUNC_get_func_ip;
6428 
6429 	if (type == BPF_PROG_TYPE_TRACING) {
6430 		if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6431 		    eatype != BPF_MODIFY_RETURN) {
6432 			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6433 				func_id_name(func_id), func_id);
6434 			return -ENOTSUPP;
6435 		}
6436 		return 0;
6437 	} else if (type == BPF_PROG_TYPE_KPROBE) {
6438 		return 0;
6439 	}
6440 
6441 	verbose(env, "func %s#%d not supported for program type %d\n",
6442 		func_id_name(func_id), func_id, type);
6443 	return -ENOTSUPP;
6444 }
6445 
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)6446 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6447 			     int *insn_idx_p)
6448 {
6449 	const struct bpf_func_proto *fn = NULL;
6450 	enum bpf_return_type ret_type;
6451 	enum bpf_type_flag ret_flag;
6452 	struct bpf_reg_state *regs;
6453 	struct bpf_call_arg_meta meta;
6454 	int insn_idx = *insn_idx_p;
6455 	bool changes_data;
6456 	int i, err, func_id;
6457 
6458 	/* find function prototype */
6459 	func_id = insn->imm;
6460 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6461 		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6462 			func_id);
6463 		return -EINVAL;
6464 	}
6465 
6466 	if (env->ops->get_func_proto)
6467 		fn = env->ops->get_func_proto(func_id, env->prog);
6468 	if (!fn) {
6469 		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6470 			func_id);
6471 		return -EINVAL;
6472 	}
6473 
6474 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
6475 	if (!env->prog->gpl_compatible && fn->gpl_only) {
6476 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6477 		return -EINVAL;
6478 	}
6479 
6480 	if (fn->allowed && !fn->allowed(env->prog)) {
6481 		verbose(env, "helper call is not allowed in probe\n");
6482 		return -EINVAL;
6483 	}
6484 
6485 	/* With LD_ABS/IND some JITs save/restore skb from r1. */
6486 	changes_data = bpf_helper_changes_pkt_data(fn->func);
6487 	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6488 		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6489 			func_id_name(func_id), func_id);
6490 		return -EINVAL;
6491 	}
6492 
6493 	memset(&meta, 0, sizeof(meta));
6494 	meta.pkt_access = fn->pkt_access;
6495 
6496 	err = check_func_proto(fn, func_id);
6497 	if (err) {
6498 		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6499 			func_id_name(func_id), func_id);
6500 		return err;
6501 	}
6502 
6503 	meta.func_id = func_id;
6504 	/* check args */
6505 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6506 		err = check_func_arg(env, i, &meta, fn);
6507 		if (err)
6508 			return err;
6509 	}
6510 
6511 	err = record_func_map(env, &meta, func_id, insn_idx);
6512 	if (err)
6513 		return err;
6514 
6515 	err = record_func_key(env, &meta, func_id, insn_idx);
6516 	if (err)
6517 		return err;
6518 
6519 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
6520 	 * is inferred from register state.
6521 	 */
6522 	for (i = 0; i < meta.access_size; i++) {
6523 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6524 				       BPF_WRITE, -1, false);
6525 		if (err)
6526 			return err;
6527 	}
6528 
6529 	if (func_id == BPF_FUNC_tail_call) {
6530 		err = check_reference_leak(env);
6531 		if (err) {
6532 			verbose(env, "tail_call would lead to reference leak\n");
6533 			return err;
6534 		}
6535 	} else if (is_release_function(func_id)) {
6536 		err = release_reference(env, meta.ref_obj_id);
6537 		if (err) {
6538 			verbose(env, "func %s#%d reference has not been acquired before\n",
6539 				func_id_name(func_id), func_id);
6540 			return err;
6541 		}
6542 	}
6543 
6544 	regs = cur_regs(env);
6545 
6546 	/* check that flags argument in get_local_storage(map, flags) is 0,
6547 	 * this is required because get_local_storage() can't return an error.
6548 	 */
6549 	if (func_id == BPF_FUNC_get_local_storage &&
6550 	    !register_is_null(&regs[BPF_REG_2])) {
6551 		verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6552 		return -EINVAL;
6553 	}
6554 
6555 	if (func_id == BPF_FUNC_for_each_map_elem) {
6556 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6557 					set_map_elem_callback_state);
6558 		if (err < 0)
6559 			return -EINVAL;
6560 	}
6561 
6562 	if (func_id == BPF_FUNC_timer_set_callback) {
6563 		err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6564 					set_timer_callback_state);
6565 		if (err < 0)
6566 			return -EINVAL;
6567 	}
6568 
6569 	if (func_id == BPF_FUNC_snprintf) {
6570 		err = check_bpf_snprintf_call(env, regs);
6571 		if (err < 0)
6572 			return err;
6573 	}
6574 
6575 	/* reset caller saved regs */
6576 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
6577 		mark_reg_not_init(env, regs, caller_saved[i]);
6578 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6579 	}
6580 
6581 	/* helper call returns 64-bit value. */
6582 	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6583 
6584 	/* update return register (already marked as written above) */
6585 	ret_type = fn->ret_type;
6586 	ret_flag = type_flag(fn->ret_type);
6587 	if (ret_type == RET_INTEGER) {
6588 		/* sets type to SCALAR_VALUE */
6589 		mark_reg_unknown(env, regs, BPF_REG_0);
6590 	} else if (ret_type == RET_VOID) {
6591 		regs[BPF_REG_0].type = NOT_INIT;
6592 	} else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
6593 		/* There is no offset yet applied, variable or fixed */
6594 		mark_reg_known_zero(env, regs, BPF_REG_0);
6595 		/* remember map_ptr, so that check_map_access()
6596 		 * can check 'value_size' boundary of memory access
6597 		 * to map element returned from bpf_map_lookup_elem()
6598 		 */
6599 		if (meta.map_ptr == NULL) {
6600 			verbose(env,
6601 				"kernel subsystem misconfigured verifier\n");
6602 			return -EINVAL;
6603 		}
6604 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
6605 		regs[BPF_REG_0].map_uid = meta.map_uid;
6606 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
6607 		if (!type_may_be_null(ret_type) &&
6608 		    map_value_has_spin_lock(meta.map_ptr)) {
6609 			regs[BPF_REG_0].id = ++env->id_gen;
6610 		}
6611 	} else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
6612 		mark_reg_known_zero(env, regs, BPF_REG_0);
6613 		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
6614 	} else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
6615 		mark_reg_known_zero(env, regs, BPF_REG_0);
6616 		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
6617 	} else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
6618 		mark_reg_known_zero(env, regs, BPF_REG_0);
6619 		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
6620 	} else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
6621 		mark_reg_known_zero(env, regs, BPF_REG_0);
6622 		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6623 		regs[BPF_REG_0].mem_size = meta.mem_size;
6624 	} else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
6625 		const struct btf_type *t;
6626 
6627 		mark_reg_known_zero(env, regs, BPF_REG_0);
6628 		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6629 		if (!btf_type_is_struct(t)) {
6630 			u32 tsize;
6631 			const struct btf_type *ret;
6632 			const char *tname;
6633 
6634 			/* resolve the type size of ksym. */
6635 			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6636 			if (IS_ERR(ret)) {
6637 				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6638 				verbose(env, "unable to resolve the size of type '%s': %ld\n",
6639 					tname, PTR_ERR(ret));
6640 				return -EINVAL;
6641 			}
6642 			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
6643 			regs[BPF_REG_0].mem_size = tsize;
6644 		} else {
6645 			/* MEM_RDONLY may be carried from ret_flag, but it
6646 			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
6647 			 * it will confuse the check of PTR_TO_BTF_ID in
6648 			 * check_mem_access().
6649 			 */
6650 			ret_flag &= ~MEM_RDONLY;
6651 
6652 			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6653 			regs[BPF_REG_0].btf = meta.ret_btf;
6654 			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6655 		}
6656 	} else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
6657 		int ret_btf_id;
6658 
6659 		mark_reg_known_zero(env, regs, BPF_REG_0);
6660 		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
6661 		ret_btf_id = *fn->ret_btf_id;
6662 		if (ret_btf_id == 0) {
6663 			verbose(env, "invalid return type %u of func %s#%d\n",
6664 				base_type(ret_type), func_id_name(func_id),
6665 				func_id);
6666 			return -EINVAL;
6667 		}
6668 		/* current BPF helper definitions are only coming from
6669 		 * built-in code with type IDs from  vmlinux BTF
6670 		 */
6671 		regs[BPF_REG_0].btf = btf_vmlinux;
6672 		regs[BPF_REG_0].btf_id = ret_btf_id;
6673 	} else {
6674 		verbose(env, "unknown return type %u of func %s#%d\n",
6675 			base_type(ret_type), func_id_name(func_id), func_id);
6676 		return -EINVAL;
6677 	}
6678 
6679 	if (type_may_be_null(regs[BPF_REG_0].type))
6680 		regs[BPF_REG_0].id = ++env->id_gen;
6681 
6682 	if (is_ptr_cast_function(func_id)) {
6683 		/* For release_reference() */
6684 		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6685 	} else if (is_acquire_function(func_id, meta.map_ptr)) {
6686 		int id = acquire_reference_state(env, insn_idx);
6687 
6688 		if (id < 0)
6689 			return id;
6690 		/* For mark_ptr_or_null_reg() */
6691 		regs[BPF_REG_0].id = id;
6692 		/* For release_reference() */
6693 		regs[BPF_REG_0].ref_obj_id = id;
6694 	}
6695 
6696 	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6697 
6698 	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6699 	if (err)
6700 		return err;
6701 
6702 	if ((func_id == BPF_FUNC_get_stack ||
6703 	     func_id == BPF_FUNC_get_task_stack) &&
6704 	    !env->prog->has_callchain_buf) {
6705 		const char *err_str;
6706 
6707 #ifdef CONFIG_PERF_EVENTS
6708 		err = get_callchain_buffers(sysctl_perf_event_max_stack);
6709 		err_str = "cannot get callchain buffer for func %s#%d\n";
6710 #else
6711 		err = -ENOTSUPP;
6712 		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6713 #endif
6714 		if (err) {
6715 			verbose(env, err_str, func_id_name(func_id), func_id);
6716 			return err;
6717 		}
6718 
6719 		env->prog->has_callchain_buf = true;
6720 	}
6721 
6722 	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6723 		env->prog->call_get_stack = true;
6724 
6725 	if (func_id == BPF_FUNC_get_func_ip) {
6726 		if (check_get_func_ip(env))
6727 			return -ENOTSUPP;
6728 		env->prog->call_get_func_ip = true;
6729 	}
6730 
6731 	if (changes_data)
6732 		clear_all_pkt_pointers(env);
6733 	return 0;
6734 }
6735 
6736 /* mark_btf_func_reg_size() is used when the reg size is determined by
6737  * the BTF func_proto's return value size and argument.
6738  */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)6739 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6740 				   size_t reg_size)
6741 {
6742 	struct bpf_reg_state *reg = &cur_regs(env)[regno];
6743 
6744 	if (regno == BPF_REG_0) {
6745 		/* Function return value */
6746 		reg->live |= REG_LIVE_WRITTEN;
6747 		reg->subreg_def = reg_size == sizeof(u64) ?
6748 			DEF_NOT_SUBREG : env->insn_idx + 1;
6749 	} else {
6750 		/* Function argument */
6751 		if (reg_size == sizeof(u64)) {
6752 			mark_insn_zext(env, reg);
6753 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6754 		} else {
6755 			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6756 		}
6757 	}
6758 }
6759 
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn)6760 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6761 {
6762 	const struct btf_type *t, *func, *func_proto, *ptr_type;
6763 	struct bpf_reg_state *regs = cur_regs(env);
6764 	const char *func_name, *ptr_type_name;
6765 	u32 i, nargs, func_id, ptr_type_id;
6766 	const struct btf_param *args;
6767 	int err;
6768 
6769 	func_id = insn->imm;
6770 	func = btf_type_by_id(btf_vmlinux, func_id);
6771 	func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6772 	func_proto = btf_type_by_id(btf_vmlinux, func->type);
6773 
6774 	if (!env->ops->check_kfunc_call ||
6775 	    !env->ops->check_kfunc_call(func_id)) {
6776 		verbose(env, "calling kernel function %s is not allowed\n",
6777 			func_name);
6778 		return -EACCES;
6779 	}
6780 
6781 	/* Check the arguments */
6782 	err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6783 	if (err)
6784 		return err;
6785 
6786 	for (i = 0; i < CALLER_SAVED_REGS; i++)
6787 		mark_reg_not_init(env, regs, caller_saved[i]);
6788 
6789 	/* Check return type */
6790 	t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6791 	if (btf_type_is_scalar(t)) {
6792 		mark_reg_unknown(env, regs, BPF_REG_0);
6793 		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6794 	} else if (btf_type_is_ptr(t)) {
6795 		ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6796 						   &ptr_type_id);
6797 		if (!btf_type_is_struct(ptr_type)) {
6798 			ptr_type_name = btf_name_by_offset(btf_vmlinux,
6799 							   ptr_type->name_off);
6800 			verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6801 				func_name, btf_type_str(ptr_type),
6802 				ptr_type_name);
6803 			return -EINVAL;
6804 		}
6805 		mark_reg_known_zero(env, regs, BPF_REG_0);
6806 		regs[BPF_REG_0].btf = btf_vmlinux;
6807 		regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6808 		regs[BPF_REG_0].btf_id = ptr_type_id;
6809 		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6810 	} /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6811 
6812 	nargs = btf_type_vlen(func_proto);
6813 	args = (const struct btf_param *)(func_proto + 1);
6814 	for (i = 0; i < nargs; i++) {
6815 		u32 regno = i + 1;
6816 
6817 		t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6818 		if (btf_type_is_ptr(t))
6819 			mark_btf_func_reg_size(env, regno, sizeof(void *));
6820 		else
6821 			/* scalar. ensured by btf_check_kfunc_arg_match() */
6822 			mark_btf_func_reg_size(env, regno, t->size);
6823 	}
6824 
6825 	return 0;
6826 }
6827 
signed_add_overflows(s64 a,s64 b)6828 static bool signed_add_overflows(s64 a, s64 b)
6829 {
6830 	/* Do the add in u64, where overflow is well-defined */
6831 	s64 res = (s64)((u64)a + (u64)b);
6832 
6833 	if (b < 0)
6834 		return res > a;
6835 	return res < a;
6836 }
6837 
signed_add32_overflows(s32 a,s32 b)6838 static bool signed_add32_overflows(s32 a, s32 b)
6839 {
6840 	/* Do the add in u32, where overflow is well-defined */
6841 	s32 res = (s32)((u32)a + (u32)b);
6842 
6843 	if (b < 0)
6844 		return res > a;
6845 	return res < a;
6846 }
6847 
signed_sub_overflows(s64 a,s64 b)6848 static bool signed_sub_overflows(s64 a, s64 b)
6849 {
6850 	/* Do the sub in u64, where overflow is well-defined */
6851 	s64 res = (s64)((u64)a - (u64)b);
6852 
6853 	if (b < 0)
6854 		return res < a;
6855 	return res > a;
6856 }
6857 
signed_sub32_overflows(s32 a,s32 b)6858 static bool signed_sub32_overflows(s32 a, s32 b)
6859 {
6860 	/* Do the sub in u32, where overflow is well-defined */
6861 	s32 res = (s32)((u32)a - (u32)b);
6862 
6863 	if (b < 0)
6864 		return res < a;
6865 	return res > a;
6866 }
6867 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)6868 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6869 				  const struct bpf_reg_state *reg,
6870 				  enum bpf_reg_type type)
6871 {
6872 	bool known = tnum_is_const(reg->var_off);
6873 	s64 val = reg->var_off.value;
6874 	s64 smin = reg->smin_value;
6875 
6876 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6877 		verbose(env, "math between %s pointer and %lld is not allowed\n",
6878 			reg_type_str(env, type), val);
6879 		return false;
6880 	}
6881 
6882 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6883 		verbose(env, "%s pointer offset %d is not allowed\n",
6884 			reg_type_str(env, type), reg->off);
6885 		return false;
6886 	}
6887 
6888 	if (smin == S64_MIN) {
6889 		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6890 			reg_type_str(env, type));
6891 		return false;
6892 	}
6893 
6894 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6895 		verbose(env, "value %lld makes %s pointer be out of bounds\n",
6896 			smin, reg_type_str(env, type));
6897 		return false;
6898 	}
6899 
6900 	return true;
6901 }
6902 
cur_aux(struct bpf_verifier_env * env)6903 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6904 {
6905 	return &env->insn_aux_data[env->insn_idx];
6906 }
6907 
6908 enum {
6909 	REASON_BOUNDS	= -1,
6910 	REASON_TYPE	= -2,
6911 	REASON_PATHS	= -3,
6912 	REASON_LIMIT	= -4,
6913 	REASON_STACK	= -5,
6914 };
6915 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)6916 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6917 			      u32 *alu_limit, bool mask_to_left)
6918 {
6919 	u32 max = 0, ptr_limit = 0;
6920 
6921 	switch (ptr_reg->type) {
6922 	case PTR_TO_STACK:
6923 		/* Offset 0 is out-of-bounds, but acceptable start for the
6924 		 * left direction, see BPF_REG_FP. Also, unknown scalar
6925 		 * offset where we would need to deal with min/max bounds is
6926 		 * currently prohibited for unprivileged.
6927 		 */
6928 		max = MAX_BPF_STACK + mask_to_left;
6929 		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6930 		break;
6931 	case PTR_TO_MAP_VALUE:
6932 		max = ptr_reg->map_ptr->value_size;
6933 		ptr_limit = (mask_to_left ?
6934 			     ptr_reg->smin_value :
6935 			     ptr_reg->umax_value) + ptr_reg->off;
6936 		break;
6937 	default:
6938 		return REASON_TYPE;
6939 	}
6940 
6941 	if (ptr_limit >= max)
6942 		return REASON_LIMIT;
6943 	*alu_limit = ptr_limit;
6944 	return 0;
6945 }
6946 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)6947 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6948 				    const struct bpf_insn *insn)
6949 {
6950 	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6951 }
6952 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)6953 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6954 				       u32 alu_state, u32 alu_limit)
6955 {
6956 	/* If we arrived here from different branches with different
6957 	 * state or limits to sanitize, then this won't work.
6958 	 */
6959 	if (aux->alu_state &&
6960 	    (aux->alu_state != alu_state ||
6961 	     aux->alu_limit != alu_limit))
6962 		return REASON_PATHS;
6963 
6964 	/* Corresponding fixup done in do_misc_fixups(). */
6965 	aux->alu_state = alu_state;
6966 	aux->alu_limit = alu_limit;
6967 	return 0;
6968 }
6969 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)6970 static int sanitize_val_alu(struct bpf_verifier_env *env,
6971 			    struct bpf_insn *insn)
6972 {
6973 	struct bpf_insn_aux_data *aux = cur_aux(env);
6974 
6975 	if (can_skip_alu_sanitation(env, insn))
6976 		return 0;
6977 
6978 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6979 }
6980 
sanitize_needed(u8 opcode)6981 static bool sanitize_needed(u8 opcode)
6982 {
6983 	return opcode == BPF_ADD || opcode == BPF_SUB;
6984 }
6985 
6986 struct bpf_sanitize_info {
6987 	struct bpf_insn_aux_data aux;
6988 	bool mask_to_left;
6989 };
6990 
6991 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)6992 sanitize_speculative_path(struct bpf_verifier_env *env,
6993 			  const struct bpf_insn *insn,
6994 			  u32 next_idx, u32 curr_idx)
6995 {
6996 	struct bpf_verifier_state *branch;
6997 	struct bpf_reg_state *regs;
6998 
6999 	branch = push_stack(env, next_idx, curr_idx, true);
7000 	if (branch && insn) {
7001 		regs = branch->frame[branch->curframe]->regs;
7002 		if (BPF_SRC(insn->code) == BPF_K) {
7003 			mark_reg_unknown(env, regs, insn->dst_reg);
7004 		} else if (BPF_SRC(insn->code) == BPF_X) {
7005 			mark_reg_unknown(env, regs, insn->dst_reg);
7006 			mark_reg_unknown(env, regs, insn->src_reg);
7007 		}
7008 	}
7009 	return branch;
7010 }
7011 
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)7012 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7013 			    struct bpf_insn *insn,
7014 			    const struct bpf_reg_state *ptr_reg,
7015 			    const struct bpf_reg_state *off_reg,
7016 			    struct bpf_reg_state *dst_reg,
7017 			    struct bpf_sanitize_info *info,
7018 			    const bool commit_window)
7019 {
7020 	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7021 	struct bpf_verifier_state *vstate = env->cur_state;
7022 	bool off_is_imm = tnum_is_const(off_reg->var_off);
7023 	bool off_is_neg = off_reg->smin_value < 0;
7024 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
7025 	u8 opcode = BPF_OP(insn->code);
7026 	u32 alu_state, alu_limit;
7027 	struct bpf_reg_state tmp;
7028 	bool ret;
7029 	int err;
7030 
7031 	if (can_skip_alu_sanitation(env, insn))
7032 		return 0;
7033 
7034 	/* We already marked aux for masking from non-speculative
7035 	 * paths, thus we got here in the first place. We only care
7036 	 * to explore bad access from here.
7037 	 */
7038 	if (vstate->speculative)
7039 		goto do_sim;
7040 
7041 	if (!commit_window) {
7042 		if (!tnum_is_const(off_reg->var_off) &&
7043 		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7044 			return REASON_BOUNDS;
7045 
7046 		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7047 				     (opcode == BPF_SUB && !off_is_neg);
7048 	}
7049 
7050 	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7051 	if (err < 0)
7052 		return err;
7053 
7054 	if (commit_window) {
7055 		/* In commit phase we narrow the masking window based on
7056 		 * the observed pointer move after the simulated operation.
7057 		 */
7058 		alu_state = info->aux.alu_state;
7059 		alu_limit = abs(info->aux.alu_limit - alu_limit);
7060 	} else {
7061 		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7062 		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7063 		alu_state |= ptr_is_dst_reg ?
7064 			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7065 
7066 		/* Limit pruning on unknown scalars to enable deep search for
7067 		 * potential masking differences from other program paths.
7068 		 */
7069 		if (!off_is_imm)
7070 			env->explore_alu_limits = true;
7071 	}
7072 
7073 	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7074 	if (err < 0)
7075 		return err;
7076 do_sim:
7077 	/* If we're in commit phase, we're done here given we already
7078 	 * pushed the truncated dst_reg into the speculative verification
7079 	 * stack.
7080 	 *
7081 	 * Also, when register is a known constant, we rewrite register-based
7082 	 * operation to immediate-based, and thus do not need masking (and as
7083 	 * a consequence, do not need to simulate the zero-truncation either).
7084 	 */
7085 	if (commit_window || off_is_imm)
7086 		return 0;
7087 
7088 	/* Simulate and find potential out-of-bounds access under
7089 	 * speculative execution from truncation as a result of
7090 	 * masking when off was not within expected range. If off
7091 	 * sits in dst, then we temporarily need to move ptr there
7092 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7093 	 * for cases where we use K-based arithmetic in one direction
7094 	 * and truncated reg-based in the other in order to explore
7095 	 * bad access.
7096 	 */
7097 	if (!ptr_is_dst_reg) {
7098 		tmp = *dst_reg;
7099 		copy_register_state(dst_reg, ptr_reg);
7100 	}
7101 	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7102 					env->insn_idx);
7103 	if (!ptr_is_dst_reg && ret)
7104 		*dst_reg = tmp;
7105 	return !ret ? REASON_STACK : 0;
7106 }
7107 
sanitize_mark_insn_seen(struct bpf_verifier_env * env)7108 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7109 {
7110 	struct bpf_verifier_state *vstate = env->cur_state;
7111 
7112 	/* If we simulate paths under speculation, we don't update the
7113 	 * insn as 'seen' such that when we verify unreachable paths in
7114 	 * the non-speculative domain, sanitize_dead_code() can still
7115 	 * rewrite/sanitize them.
7116 	 */
7117 	if (!vstate->speculative)
7118 		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7119 }
7120 
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)7121 static int sanitize_err(struct bpf_verifier_env *env,
7122 			const struct bpf_insn *insn, int reason,
7123 			const struct bpf_reg_state *off_reg,
7124 			const struct bpf_reg_state *dst_reg)
7125 {
7126 	static const char *err = "pointer arithmetic with it prohibited for !root";
7127 	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7128 	u32 dst = insn->dst_reg, src = insn->src_reg;
7129 
7130 	switch (reason) {
7131 	case REASON_BOUNDS:
7132 		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7133 			off_reg == dst_reg ? dst : src, err);
7134 		break;
7135 	case REASON_TYPE:
7136 		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7137 			off_reg == dst_reg ? src : dst, err);
7138 		break;
7139 	case REASON_PATHS:
7140 		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7141 			dst, op, err);
7142 		break;
7143 	case REASON_LIMIT:
7144 		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7145 			dst, op, err);
7146 		break;
7147 	case REASON_STACK:
7148 		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7149 			dst, err);
7150 		break;
7151 	default:
7152 		verbose(env, "verifier internal error: unknown reason (%d)\n",
7153 			reason);
7154 		break;
7155 	}
7156 
7157 	return -EACCES;
7158 }
7159 
7160 /* check that stack access falls within stack limits and that 'reg' doesn't
7161  * have a variable offset.
7162  *
7163  * Variable offset is prohibited for unprivileged mode for simplicity since it
7164  * requires corresponding support in Spectre masking for stack ALU.  See also
7165  * retrieve_ptr_limit().
7166  *
7167  *
7168  * 'off' includes 'reg->off'.
7169  */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)7170 static int check_stack_access_for_ptr_arithmetic(
7171 				struct bpf_verifier_env *env,
7172 				int regno,
7173 				const struct bpf_reg_state *reg,
7174 				int off)
7175 {
7176 	if (!tnum_is_const(reg->var_off)) {
7177 		char tn_buf[48];
7178 
7179 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7180 		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7181 			regno, tn_buf, off);
7182 		return -EACCES;
7183 	}
7184 
7185 	if (off >= 0 || off < -MAX_BPF_STACK) {
7186 		verbose(env, "R%d stack pointer arithmetic goes out of range, "
7187 			"prohibited for !root; off=%d\n", regno, off);
7188 		return -EACCES;
7189 	}
7190 
7191 	return 0;
7192 }
7193 
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)7194 static int sanitize_check_bounds(struct bpf_verifier_env *env,
7195 				 const struct bpf_insn *insn,
7196 				 const struct bpf_reg_state *dst_reg)
7197 {
7198 	u32 dst = insn->dst_reg;
7199 
7200 	/* For unprivileged we require that resulting offset must be in bounds
7201 	 * in order to be able to sanitize access later on.
7202 	 */
7203 	if (env->bypass_spec_v1)
7204 		return 0;
7205 
7206 	switch (dst_reg->type) {
7207 	case PTR_TO_STACK:
7208 		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7209 					dst_reg->off + dst_reg->var_off.value))
7210 			return -EACCES;
7211 		break;
7212 	case PTR_TO_MAP_VALUE:
7213 		if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7214 			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7215 				"prohibited for !root\n", dst);
7216 			return -EACCES;
7217 		}
7218 		break;
7219 	default:
7220 		break;
7221 	}
7222 
7223 	return 0;
7224 }
7225 
7226 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
7227  * Caller should also handle BPF_MOV case separately.
7228  * If we return -EACCES, caller may want to try again treating pointer as a
7229  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
7230  */
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)7231 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7232 				   struct bpf_insn *insn,
7233 				   const struct bpf_reg_state *ptr_reg,
7234 				   const struct bpf_reg_state *off_reg)
7235 {
7236 	struct bpf_verifier_state *vstate = env->cur_state;
7237 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
7238 	struct bpf_reg_state *regs = state->regs, *dst_reg;
7239 	bool known = tnum_is_const(off_reg->var_off);
7240 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7241 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7242 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7243 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7244 	struct bpf_sanitize_info info = {};
7245 	u8 opcode = BPF_OP(insn->code);
7246 	u32 dst = insn->dst_reg;
7247 	int ret;
7248 
7249 	dst_reg = &regs[dst];
7250 
7251 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7252 	    smin_val > smax_val || umin_val > umax_val) {
7253 		/* Taint dst register if offset had invalid bounds derived from
7254 		 * e.g. dead branches.
7255 		 */
7256 		__mark_reg_unknown(env, dst_reg);
7257 		return 0;
7258 	}
7259 
7260 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
7261 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
7262 		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7263 			__mark_reg_unknown(env, dst_reg);
7264 			return 0;
7265 		}
7266 
7267 		verbose(env,
7268 			"R%d 32-bit pointer arithmetic prohibited\n",
7269 			dst);
7270 		return -EACCES;
7271 	}
7272 
7273 	if (ptr_reg->type & PTR_MAYBE_NULL) {
7274 		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7275 			dst, reg_type_str(env, ptr_reg->type));
7276 		return -EACCES;
7277 	}
7278 
7279 	switch (base_type(ptr_reg->type)) {
7280 	case PTR_TO_FLOW_KEYS:
7281 		if (known)
7282 			break;
7283 		fallthrough;
7284 	case CONST_PTR_TO_MAP:
7285 		/* smin_val represents the known value */
7286 		if (known && smin_val == 0 && opcode == BPF_ADD)
7287 			break;
7288 		fallthrough;
7289 	case PTR_TO_PACKET_END:
7290 	case PTR_TO_SOCKET:
7291 	case PTR_TO_SOCK_COMMON:
7292 	case PTR_TO_TCP_SOCK:
7293 	case PTR_TO_XDP_SOCK:
7294 reject:
7295 		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7296 			dst, reg_type_str(env, ptr_reg->type));
7297 		return -EACCES;
7298 	default:
7299 		if (type_may_be_null(ptr_reg->type))
7300 			goto reject;
7301 		break;
7302 	}
7303 
7304 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7305 	 * The id may be overwritten later if we create a new variable offset.
7306 	 */
7307 	dst_reg->type = ptr_reg->type;
7308 	dst_reg->id = ptr_reg->id;
7309 
7310 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7311 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7312 		return -EINVAL;
7313 
7314 	/* pointer types do not carry 32-bit bounds at the moment. */
7315 	__mark_reg32_unbounded(dst_reg);
7316 
7317 	if (sanitize_needed(opcode)) {
7318 		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7319 				       &info, false);
7320 		if (ret < 0)
7321 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7322 	}
7323 
7324 	switch (opcode) {
7325 	case BPF_ADD:
7326 		/* We can take a fixed offset as long as it doesn't overflow
7327 		 * the s32 'off' field
7328 		 */
7329 		if (known && (ptr_reg->off + smin_val ==
7330 			      (s64)(s32)(ptr_reg->off + smin_val))) {
7331 			/* pointer += K.  Accumulate it into fixed offset */
7332 			dst_reg->smin_value = smin_ptr;
7333 			dst_reg->smax_value = smax_ptr;
7334 			dst_reg->umin_value = umin_ptr;
7335 			dst_reg->umax_value = umax_ptr;
7336 			dst_reg->var_off = ptr_reg->var_off;
7337 			dst_reg->off = ptr_reg->off + smin_val;
7338 			dst_reg->raw = ptr_reg->raw;
7339 			break;
7340 		}
7341 		/* A new variable offset is created.  Note that off_reg->off
7342 		 * == 0, since it's a scalar.
7343 		 * dst_reg gets the pointer type and since some positive
7344 		 * integer value was added to the pointer, give it a new 'id'
7345 		 * if it's a PTR_TO_PACKET.
7346 		 * this creates a new 'base' pointer, off_reg (variable) gets
7347 		 * added into the variable offset, and we copy the fixed offset
7348 		 * from ptr_reg.
7349 		 */
7350 		if (signed_add_overflows(smin_ptr, smin_val) ||
7351 		    signed_add_overflows(smax_ptr, smax_val)) {
7352 			dst_reg->smin_value = S64_MIN;
7353 			dst_reg->smax_value = S64_MAX;
7354 		} else {
7355 			dst_reg->smin_value = smin_ptr + smin_val;
7356 			dst_reg->smax_value = smax_ptr + smax_val;
7357 		}
7358 		if (umin_ptr + umin_val < umin_ptr ||
7359 		    umax_ptr + umax_val < umax_ptr) {
7360 			dst_reg->umin_value = 0;
7361 			dst_reg->umax_value = U64_MAX;
7362 		} else {
7363 			dst_reg->umin_value = umin_ptr + umin_val;
7364 			dst_reg->umax_value = umax_ptr + umax_val;
7365 		}
7366 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7367 		dst_reg->off = ptr_reg->off;
7368 		dst_reg->raw = ptr_reg->raw;
7369 		if (reg_is_pkt_pointer(ptr_reg)) {
7370 			dst_reg->id = ++env->id_gen;
7371 			/* something was added to pkt_ptr, set range to zero */
7372 			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7373 		}
7374 		break;
7375 	case BPF_SUB:
7376 		if (dst_reg == off_reg) {
7377 			/* scalar -= pointer.  Creates an unknown scalar */
7378 			verbose(env, "R%d tried to subtract pointer from scalar\n",
7379 				dst);
7380 			return -EACCES;
7381 		}
7382 		/* We don't allow subtraction from FP, because (according to
7383 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
7384 		 * be able to deal with it.
7385 		 */
7386 		if (ptr_reg->type == PTR_TO_STACK) {
7387 			verbose(env, "R%d subtraction from stack pointer prohibited\n",
7388 				dst);
7389 			return -EACCES;
7390 		}
7391 		if (known && (ptr_reg->off - smin_val ==
7392 			      (s64)(s32)(ptr_reg->off - smin_val))) {
7393 			/* pointer -= K.  Subtract it from fixed offset */
7394 			dst_reg->smin_value = smin_ptr;
7395 			dst_reg->smax_value = smax_ptr;
7396 			dst_reg->umin_value = umin_ptr;
7397 			dst_reg->umax_value = umax_ptr;
7398 			dst_reg->var_off = ptr_reg->var_off;
7399 			dst_reg->id = ptr_reg->id;
7400 			dst_reg->off = ptr_reg->off - smin_val;
7401 			dst_reg->raw = ptr_reg->raw;
7402 			break;
7403 		}
7404 		/* A new variable offset is created.  If the subtrahend is known
7405 		 * nonnegative, then any reg->range we had before is still good.
7406 		 */
7407 		if (signed_sub_overflows(smin_ptr, smax_val) ||
7408 		    signed_sub_overflows(smax_ptr, smin_val)) {
7409 			/* Overflow possible, we know nothing */
7410 			dst_reg->smin_value = S64_MIN;
7411 			dst_reg->smax_value = S64_MAX;
7412 		} else {
7413 			dst_reg->smin_value = smin_ptr - smax_val;
7414 			dst_reg->smax_value = smax_ptr - smin_val;
7415 		}
7416 		if (umin_ptr < umax_val) {
7417 			/* Overflow possible, we know nothing */
7418 			dst_reg->umin_value = 0;
7419 			dst_reg->umax_value = U64_MAX;
7420 		} else {
7421 			/* Cannot overflow (as long as bounds are consistent) */
7422 			dst_reg->umin_value = umin_ptr - umax_val;
7423 			dst_reg->umax_value = umax_ptr - umin_val;
7424 		}
7425 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7426 		dst_reg->off = ptr_reg->off;
7427 		dst_reg->raw = ptr_reg->raw;
7428 		if (reg_is_pkt_pointer(ptr_reg)) {
7429 			dst_reg->id = ++env->id_gen;
7430 			/* something was added to pkt_ptr, set range to zero */
7431 			if (smin_val < 0)
7432 				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7433 		}
7434 		break;
7435 	case BPF_AND:
7436 	case BPF_OR:
7437 	case BPF_XOR:
7438 		/* bitwise ops on pointers are troublesome, prohibit. */
7439 		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7440 			dst, bpf_alu_string[opcode >> 4]);
7441 		return -EACCES;
7442 	default:
7443 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
7444 		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7445 			dst, bpf_alu_string[opcode >> 4]);
7446 		return -EACCES;
7447 	}
7448 
7449 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7450 		return -EINVAL;
7451 	reg_bounds_sync(dst_reg);
7452 	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7453 		return -EACCES;
7454 	if (sanitize_needed(opcode)) {
7455 		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7456 				       &info, true);
7457 		if (ret < 0)
7458 			return sanitize_err(env, insn, ret, off_reg, dst_reg);
7459 	}
7460 
7461 	return 0;
7462 }
7463 
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7464 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7465 				 struct bpf_reg_state *src_reg)
7466 {
7467 	s32 smin_val = src_reg->s32_min_value;
7468 	s32 smax_val = src_reg->s32_max_value;
7469 	u32 umin_val = src_reg->u32_min_value;
7470 	u32 umax_val = src_reg->u32_max_value;
7471 
7472 	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7473 	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7474 		dst_reg->s32_min_value = S32_MIN;
7475 		dst_reg->s32_max_value = S32_MAX;
7476 	} else {
7477 		dst_reg->s32_min_value += smin_val;
7478 		dst_reg->s32_max_value += smax_val;
7479 	}
7480 	if (dst_reg->u32_min_value + umin_val < umin_val ||
7481 	    dst_reg->u32_max_value + umax_val < umax_val) {
7482 		dst_reg->u32_min_value = 0;
7483 		dst_reg->u32_max_value = U32_MAX;
7484 	} else {
7485 		dst_reg->u32_min_value += umin_val;
7486 		dst_reg->u32_max_value += umax_val;
7487 	}
7488 }
7489 
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7490 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7491 			       struct bpf_reg_state *src_reg)
7492 {
7493 	s64 smin_val = src_reg->smin_value;
7494 	s64 smax_val = src_reg->smax_value;
7495 	u64 umin_val = src_reg->umin_value;
7496 	u64 umax_val = src_reg->umax_value;
7497 
7498 	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7499 	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
7500 		dst_reg->smin_value = S64_MIN;
7501 		dst_reg->smax_value = S64_MAX;
7502 	} else {
7503 		dst_reg->smin_value += smin_val;
7504 		dst_reg->smax_value += smax_val;
7505 	}
7506 	if (dst_reg->umin_value + umin_val < umin_val ||
7507 	    dst_reg->umax_value + umax_val < umax_val) {
7508 		dst_reg->umin_value = 0;
7509 		dst_reg->umax_value = U64_MAX;
7510 	} else {
7511 		dst_reg->umin_value += umin_val;
7512 		dst_reg->umax_value += umax_val;
7513 	}
7514 }
7515 
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7516 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7517 				 struct bpf_reg_state *src_reg)
7518 {
7519 	s32 smin_val = src_reg->s32_min_value;
7520 	s32 smax_val = src_reg->s32_max_value;
7521 	u32 umin_val = src_reg->u32_min_value;
7522 	u32 umax_val = src_reg->u32_max_value;
7523 
7524 	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7525 	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7526 		/* Overflow possible, we know nothing */
7527 		dst_reg->s32_min_value = S32_MIN;
7528 		dst_reg->s32_max_value = S32_MAX;
7529 	} else {
7530 		dst_reg->s32_min_value -= smax_val;
7531 		dst_reg->s32_max_value -= smin_val;
7532 	}
7533 	if (dst_reg->u32_min_value < umax_val) {
7534 		/* Overflow possible, we know nothing */
7535 		dst_reg->u32_min_value = 0;
7536 		dst_reg->u32_max_value = U32_MAX;
7537 	} else {
7538 		/* Cannot overflow (as long as bounds are consistent) */
7539 		dst_reg->u32_min_value -= umax_val;
7540 		dst_reg->u32_max_value -= umin_val;
7541 	}
7542 }
7543 
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7544 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7545 			       struct bpf_reg_state *src_reg)
7546 {
7547 	s64 smin_val = src_reg->smin_value;
7548 	s64 smax_val = src_reg->smax_value;
7549 	u64 umin_val = src_reg->umin_value;
7550 	u64 umax_val = src_reg->umax_value;
7551 
7552 	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7553 	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7554 		/* Overflow possible, we know nothing */
7555 		dst_reg->smin_value = S64_MIN;
7556 		dst_reg->smax_value = S64_MAX;
7557 	} else {
7558 		dst_reg->smin_value -= smax_val;
7559 		dst_reg->smax_value -= smin_val;
7560 	}
7561 	if (dst_reg->umin_value < umax_val) {
7562 		/* Overflow possible, we know nothing */
7563 		dst_reg->umin_value = 0;
7564 		dst_reg->umax_value = U64_MAX;
7565 	} else {
7566 		/* Cannot overflow (as long as bounds are consistent) */
7567 		dst_reg->umin_value -= umax_val;
7568 		dst_reg->umax_value -= umin_val;
7569 	}
7570 }
7571 
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7572 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7573 				 struct bpf_reg_state *src_reg)
7574 {
7575 	s32 smin_val = src_reg->s32_min_value;
7576 	u32 umin_val = src_reg->u32_min_value;
7577 	u32 umax_val = src_reg->u32_max_value;
7578 
7579 	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7580 		/* Ain't nobody got time to multiply that sign */
7581 		__mark_reg32_unbounded(dst_reg);
7582 		return;
7583 	}
7584 	/* Both values are positive, so we can work with unsigned and
7585 	 * copy the result to signed (unless it exceeds S32_MAX).
7586 	 */
7587 	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7588 		/* Potential overflow, we know nothing */
7589 		__mark_reg32_unbounded(dst_reg);
7590 		return;
7591 	}
7592 	dst_reg->u32_min_value *= umin_val;
7593 	dst_reg->u32_max_value *= umax_val;
7594 	if (dst_reg->u32_max_value > S32_MAX) {
7595 		/* Overflow possible, we know nothing */
7596 		dst_reg->s32_min_value = S32_MIN;
7597 		dst_reg->s32_max_value = S32_MAX;
7598 	} else {
7599 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7600 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7601 	}
7602 }
7603 
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7604 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7605 			       struct bpf_reg_state *src_reg)
7606 {
7607 	s64 smin_val = src_reg->smin_value;
7608 	u64 umin_val = src_reg->umin_value;
7609 	u64 umax_val = src_reg->umax_value;
7610 
7611 	if (smin_val < 0 || dst_reg->smin_value < 0) {
7612 		/* Ain't nobody got time to multiply that sign */
7613 		__mark_reg64_unbounded(dst_reg);
7614 		return;
7615 	}
7616 	/* Both values are positive, so we can work with unsigned and
7617 	 * copy the result to signed (unless it exceeds S64_MAX).
7618 	 */
7619 	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7620 		/* Potential overflow, we know nothing */
7621 		__mark_reg64_unbounded(dst_reg);
7622 		return;
7623 	}
7624 	dst_reg->umin_value *= umin_val;
7625 	dst_reg->umax_value *= umax_val;
7626 	if (dst_reg->umax_value > S64_MAX) {
7627 		/* Overflow possible, we know nothing */
7628 		dst_reg->smin_value = S64_MIN;
7629 		dst_reg->smax_value = S64_MAX;
7630 	} else {
7631 		dst_reg->smin_value = dst_reg->umin_value;
7632 		dst_reg->smax_value = dst_reg->umax_value;
7633 	}
7634 }
7635 
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7636 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7637 				 struct bpf_reg_state *src_reg)
7638 {
7639 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7640 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7641 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7642 	s32 smin_val = src_reg->s32_min_value;
7643 	u32 umax_val = src_reg->u32_max_value;
7644 
7645 	if (src_known && dst_known) {
7646 		__mark_reg32_known(dst_reg, var32_off.value);
7647 		return;
7648 	}
7649 
7650 	/* We get our minimum from the var_off, since that's inherently
7651 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7652 	 */
7653 	dst_reg->u32_min_value = var32_off.value;
7654 	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7655 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7656 		/* Lose signed bounds when ANDing negative numbers,
7657 		 * ain't nobody got time for that.
7658 		 */
7659 		dst_reg->s32_min_value = S32_MIN;
7660 		dst_reg->s32_max_value = S32_MAX;
7661 	} else {
7662 		/* ANDing two positives gives a positive, so safe to
7663 		 * cast result into s64.
7664 		 */
7665 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7666 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7667 	}
7668 }
7669 
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7670 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7671 			       struct bpf_reg_state *src_reg)
7672 {
7673 	bool src_known = tnum_is_const(src_reg->var_off);
7674 	bool dst_known = tnum_is_const(dst_reg->var_off);
7675 	s64 smin_val = src_reg->smin_value;
7676 	u64 umax_val = src_reg->umax_value;
7677 
7678 	if (src_known && dst_known) {
7679 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7680 		return;
7681 	}
7682 
7683 	/* We get our minimum from the var_off, since that's inherently
7684 	 * bitwise.  Our maximum is the minimum of the operands' maxima.
7685 	 */
7686 	dst_reg->umin_value = dst_reg->var_off.value;
7687 	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7688 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7689 		/* Lose signed bounds when ANDing negative numbers,
7690 		 * ain't nobody got time for that.
7691 		 */
7692 		dst_reg->smin_value = S64_MIN;
7693 		dst_reg->smax_value = S64_MAX;
7694 	} else {
7695 		/* ANDing two positives gives a positive, so safe to
7696 		 * cast result into s64.
7697 		 */
7698 		dst_reg->smin_value = dst_reg->umin_value;
7699 		dst_reg->smax_value = dst_reg->umax_value;
7700 	}
7701 	/* We may learn something more from the var_off */
7702 	__update_reg_bounds(dst_reg);
7703 }
7704 
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7705 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7706 				struct bpf_reg_state *src_reg)
7707 {
7708 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7709 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7710 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7711 	s32 smin_val = src_reg->s32_min_value;
7712 	u32 umin_val = src_reg->u32_min_value;
7713 
7714 	if (src_known && dst_known) {
7715 		__mark_reg32_known(dst_reg, var32_off.value);
7716 		return;
7717 	}
7718 
7719 	/* We get our maximum from the var_off, and our minimum is the
7720 	 * maximum of the operands' minima
7721 	 */
7722 	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7723 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7724 	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7725 		/* Lose signed bounds when ORing negative numbers,
7726 		 * ain't nobody got time for that.
7727 		 */
7728 		dst_reg->s32_min_value = S32_MIN;
7729 		dst_reg->s32_max_value = S32_MAX;
7730 	} else {
7731 		/* ORing two positives gives a positive, so safe to
7732 		 * cast result into s64.
7733 		 */
7734 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7735 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7736 	}
7737 }
7738 
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7739 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7740 			      struct bpf_reg_state *src_reg)
7741 {
7742 	bool src_known = tnum_is_const(src_reg->var_off);
7743 	bool dst_known = tnum_is_const(dst_reg->var_off);
7744 	s64 smin_val = src_reg->smin_value;
7745 	u64 umin_val = src_reg->umin_value;
7746 
7747 	if (src_known && dst_known) {
7748 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7749 		return;
7750 	}
7751 
7752 	/* We get our maximum from the var_off, and our minimum is the
7753 	 * maximum of the operands' minima
7754 	 */
7755 	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7756 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7757 	if (dst_reg->smin_value < 0 || smin_val < 0) {
7758 		/* Lose signed bounds when ORing negative numbers,
7759 		 * ain't nobody got time for that.
7760 		 */
7761 		dst_reg->smin_value = S64_MIN;
7762 		dst_reg->smax_value = S64_MAX;
7763 	} else {
7764 		/* ORing two positives gives a positive, so safe to
7765 		 * cast result into s64.
7766 		 */
7767 		dst_reg->smin_value = dst_reg->umin_value;
7768 		dst_reg->smax_value = dst_reg->umax_value;
7769 	}
7770 	/* We may learn something more from the var_off */
7771 	__update_reg_bounds(dst_reg);
7772 }
7773 
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7774 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7775 				 struct bpf_reg_state *src_reg)
7776 {
7777 	bool src_known = tnum_subreg_is_const(src_reg->var_off);
7778 	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7779 	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7780 	s32 smin_val = src_reg->s32_min_value;
7781 
7782 	if (src_known && dst_known) {
7783 		__mark_reg32_known(dst_reg, var32_off.value);
7784 		return;
7785 	}
7786 
7787 	/* We get both minimum and maximum from the var32_off. */
7788 	dst_reg->u32_min_value = var32_off.value;
7789 	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7790 
7791 	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7792 		/* XORing two positive sign numbers gives a positive,
7793 		 * so safe to cast u32 result into s32.
7794 		 */
7795 		dst_reg->s32_min_value = dst_reg->u32_min_value;
7796 		dst_reg->s32_max_value = dst_reg->u32_max_value;
7797 	} else {
7798 		dst_reg->s32_min_value = S32_MIN;
7799 		dst_reg->s32_max_value = S32_MAX;
7800 	}
7801 }
7802 
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7803 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7804 			       struct bpf_reg_state *src_reg)
7805 {
7806 	bool src_known = tnum_is_const(src_reg->var_off);
7807 	bool dst_known = tnum_is_const(dst_reg->var_off);
7808 	s64 smin_val = src_reg->smin_value;
7809 
7810 	if (src_known && dst_known) {
7811 		/* dst_reg->var_off.value has been updated earlier */
7812 		__mark_reg_known(dst_reg, dst_reg->var_off.value);
7813 		return;
7814 	}
7815 
7816 	/* We get both minimum and maximum from the var_off. */
7817 	dst_reg->umin_value = dst_reg->var_off.value;
7818 	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7819 
7820 	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7821 		/* XORing two positive sign numbers gives a positive,
7822 		 * so safe to cast u64 result into s64.
7823 		 */
7824 		dst_reg->smin_value = dst_reg->umin_value;
7825 		dst_reg->smax_value = dst_reg->umax_value;
7826 	} else {
7827 		dst_reg->smin_value = S64_MIN;
7828 		dst_reg->smax_value = S64_MAX;
7829 	}
7830 
7831 	__update_reg_bounds(dst_reg);
7832 }
7833 
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)7834 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7835 				   u64 umin_val, u64 umax_val)
7836 {
7837 	/* We lose all sign bit information (except what we can pick
7838 	 * up from var_off)
7839 	 */
7840 	dst_reg->s32_min_value = S32_MIN;
7841 	dst_reg->s32_max_value = S32_MAX;
7842 	/* If we might shift our top bit out, then we know nothing */
7843 	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7844 		dst_reg->u32_min_value = 0;
7845 		dst_reg->u32_max_value = U32_MAX;
7846 	} else {
7847 		dst_reg->u32_min_value <<= umin_val;
7848 		dst_reg->u32_max_value <<= umax_val;
7849 	}
7850 }
7851 
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7852 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7853 				 struct bpf_reg_state *src_reg)
7854 {
7855 	u32 umax_val = src_reg->u32_max_value;
7856 	u32 umin_val = src_reg->u32_min_value;
7857 	/* u32 alu operation will zext upper bits */
7858 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7859 
7860 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7861 	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7862 	/* Not required but being careful mark reg64 bounds as unknown so
7863 	 * that we are forced to pick them up from tnum and zext later and
7864 	 * if some path skips this step we are still safe.
7865 	 */
7866 	__mark_reg64_unbounded(dst_reg);
7867 	__update_reg32_bounds(dst_reg);
7868 }
7869 
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)7870 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7871 				   u64 umin_val, u64 umax_val)
7872 {
7873 	/* Special case <<32 because it is a common compiler pattern to sign
7874 	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7875 	 * positive we know this shift will also be positive so we can track
7876 	 * bounds correctly. Otherwise we lose all sign bit information except
7877 	 * what we can pick up from var_off. Perhaps we can generalize this
7878 	 * later to shifts of any length.
7879 	 */
7880 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7881 		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7882 	else
7883 		dst_reg->smax_value = S64_MAX;
7884 
7885 	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7886 		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7887 	else
7888 		dst_reg->smin_value = S64_MIN;
7889 
7890 	/* If we might shift our top bit out, then we know nothing */
7891 	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7892 		dst_reg->umin_value = 0;
7893 		dst_reg->umax_value = U64_MAX;
7894 	} else {
7895 		dst_reg->umin_value <<= umin_val;
7896 		dst_reg->umax_value <<= umax_val;
7897 	}
7898 }
7899 
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7900 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7901 			       struct bpf_reg_state *src_reg)
7902 {
7903 	u64 umax_val = src_reg->umax_value;
7904 	u64 umin_val = src_reg->umin_value;
7905 
7906 	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
7907 	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7908 	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7909 
7910 	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7911 	/* We may learn something more from the var_off */
7912 	__update_reg_bounds(dst_reg);
7913 }
7914 
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7915 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7916 				 struct bpf_reg_state *src_reg)
7917 {
7918 	struct tnum subreg = tnum_subreg(dst_reg->var_off);
7919 	u32 umax_val = src_reg->u32_max_value;
7920 	u32 umin_val = src_reg->u32_min_value;
7921 
7922 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7923 	 * be negative, then either:
7924 	 * 1) src_reg might be zero, so the sign bit of the result is
7925 	 *    unknown, so we lose our signed bounds
7926 	 * 2) it's known negative, thus the unsigned bounds capture the
7927 	 *    signed bounds
7928 	 * 3) the signed bounds cross zero, so they tell us nothing
7929 	 *    about the result
7930 	 * If the value in dst_reg is known nonnegative, then again the
7931 	 * unsigned bounds capture the signed bounds.
7932 	 * Thus, in all cases it suffices to blow away our signed bounds
7933 	 * and rely on inferring new ones from the unsigned bounds and
7934 	 * var_off of the result.
7935 	 */
7936 	dst_reg->s32_min_value = S32_MIN;
7937 	dst_reg->s32_max_value = S32_MAX;
7938 
7939 	dst_reg->var_off = tnum_rshift(subreg, umin_val);
7940 	dst_reg->u32_min_value >>= umax_val;
7941 	dst_reg->u32_max_value >>= umin_val;
7942 
7943 	__mark_reg64_unbounded(dst_reg);
7944 	__update_reg32_bounds(dst_reg);
7945 }
7946 
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7947 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7948 			       struct bpf_reg_state *src_reg)
7949 {
7950 	u64 umax_val = src_reg->umax_value;
7951 	u64 umin_val = src_reg->umin_value;
7952 
7953 	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
7954 	 * be negative, then either:
7955 	 * 1) src_reg might be zero, so the sign bit of the result is
7956 	 *    unknown, so we lose our signed bounds
7957 	 * 2) it's known negative, thus the unsigned bounds capture the
7958 	 *    signed bounds
7959 	 * 3) the signed bounds cross zero, so they tell us nothing
7960 	 *    about the result
7961 	 * If the value in dst_reg is known nonnegative, then again the
7962 	 * unsigned bounds capture the signed bounds.
7963 	 * Thus, in all cases it suffices to blow away our signed bounds
7964 	 * and rely on inferring new ones from the unsigned bounds and
7965 	 * var_off of the result.
7966 	 */
7967 	dst_reg->smin_value = S64_MIN;
7968 	dst_reg->smax_value = S64_MAX;
7969 	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7970 	dst_reg->umin_value >>= umax_val;
7971 	dst_reg->umax_value >>= umin_val;
7972 
7973 	/* Its not easy to operate on alu32 bounds here because it depends
7974 	 * on bits being shifted in. Take easy way out and mark unbounded
7975 	 * so we can recalculate later from tnum.
7976 	 */
7977 	__mark_reg32_unbounded(dst_reg);
7978 	__update_reg_bounds(dst_reg);
7979 }
7980 
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)7981 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7982 				  struct bpf_reg_state *src_reg)
7983 {
7984 	u64 umin_val = src_reg->u32_min_value;
7985 
7986 	/* Upon reaching here, src_known is true and
7987 	 * umax_val is equal to umin_val.
7988 	 */
7989 	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7990 	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7991 
7992 	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7993 
7994 	/* blow away the dst_reg umin_value/umax_value and rely on
7995 	 * dst_reg var_off to refine the result.
7996 	 */
7997 	dst_reg->u32_min_value = 0;
7998 	dst_reg->u32_max_value = U32_MAX;
7999 
8000 	__mark_reg64_unbounded(dst_reg);
8001 	__update_reg32_bounds(dst_reg);
8002 }
8003 
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8004 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8005 				struct bpf_reg_state *src_reg)
8006 {
8007 	u64 umin_val = src_reg->umin_value;
8008 
8009 	/* Upon reaching here, src_known is true and umax_val is equal
8010 	 * to umin_val.
8011 	 */
8012 	dst_reg->smin_value >>= umin_val;
8013 	dst_reg->smax_value >>= umin_val;
8014 
8015 	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8016 
8017 	/* blow away the dst_reg umin_value/umax_value and rely on
8018 	 * dst_reg var_off to refine the result.
8019 	 */
8020 	dst_reg->umin_value = 0;
8021 	dst_reg->umax_value = U64_MAX;
8022 
8023 	/* Its not easy to operate on alu32 bounds here because it depends
8024 	 * on bits being shifted in from upper 32-bits. Take easy way out
8025 	 * and mark unbounded so we can recalculate later from tnum.
8026 	 */
8027 	__mark_reg32_unbounded(dst_reg);
8028 	__update_reg_bounds(dst_reg);
8029 }
8030 
8031 /* WARNING: This function does calculations on 64-bit values, but the actual
8032  * execution may occur on 32-bit values. Therefore, things like bitshifts
8033  * need extra checks in the 32-bit case.
8034  */
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)8035 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8036 				      struct bpf_insn *insn,
8037 				      struct bpf_reg_state *dst_reg,
8038 				      struct bpf_reg_state src_reg)
8039 {
8040 	struct bpf_reg_state *regs = cur_regs(env);
8041 	u8 opcode = BPF_OP(insn->code);
8042 	bool src_known;
8043 	s64 smin_val, smax_val;
8044 	u64 umin_val, umax_val;
8045 	s32 s32_min_val, s32_max_val;
8046 	u32 u32_min_val, u32_max_val;
8047 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8048 	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8049 	int ret;
8050 
8051 	smin_val = src_reg.smin_value;
8052 	smax_val = src_reg.smax_value;
8053 	umin_val = src_reg.umin_value;
8054 	umax_val = src_reg.umax_value;
8055 
8056 	s32_min_val = src_reg.s32_min_value;
8057 	s32_max_val = src_reg.s32_max_value;
8058 	u32_min_val = src_reg.u32_min_value;
8059 	u32_max_val = src_reg.u32_max_value;
8060 
8061 	if (alu32) {
8062 		src_known = tnum_subreg_is_const(src_reg.var_off);
8063 		if ((src_known &&
8064 		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8065 		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8066 			/* Taint dst register if offset had invalid bounds
8067 			 * derived from e.g. dead branches.
8068 			 */
8069 			__mark_reg_unknown(env, dst_reg);
8070 			return 0;
8071 		}
8072 	} else {
8073 		src_known = tnum_is_const(src_reg.var_off);
8074 		if ((src_known &&
8075 		     (smin_val != smax_val || umin_val != umax_val)) ||
8076 		    smin_val > smax_val || umin_val > umax_val) {
8077 			/* Taint dst register if offset had invalid bounds
8078 			 * derived from e.g. dead branches.
8079 			 */
8080 			__mark_reg_unknown(env, dst_reg);
8081 			return 0;
8082 		}
8083 	}
8084 
8085 	if (!src_known &&
8086 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8087 		__mark_reg_unknown(env, dst_reg);
8088 		return 0;
8089 	}
8090 
8091 	if (sanitize_needed(opcode)) {
8092 		ret = sanitize_val_alu(env, insn);
8093 		if (ret < 0)
8094 			return sanitize_err(env, insn, ret, NULL, NULL);
8095 	}
8096 
8097 	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8098 	 * There are two classes of instructions: The first class we track both
8099 	 * alu32 and alu64 sign/unsigned bounds independently this provides the
8100 	 * greatest amount of precision when alu operations are mixed with jmp32
8101 	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8102 	 * and BPF_OR. This is possible because these ops have fairly easy to
8103 	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8104 	 * See alu32 verifier tests for examples. The second class of
8105 	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8106 	 * with regards to tracking sign/unsigned bounds because the bits may
8107 	 * cross subreg boundaries in the alu64 case. When this happens we mark
8108 	 * the reg unbounded in the subreg bound space and use the resulting
8109 	 * tnum to calculate an approximation of the sign/unsigned bounds.
8110 	 */
8111 	switch (opcode) {
8112 	case BPF_ADD:
8113 		scalar32_min_max_add(dst_reg, &src_reg);
8114 		scalar_min_max_add(dst_reg, &src_reg);
8115 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8116 		break;
8117 	case BPF_SUB:
8118 		scalar32_min_max_sub(dst_reg, &src_reg);
8119 		scalar_min_max_sub(dst_reg, &src_reg);
8120 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8121 		break;
8122 	case BPF_MUL:
8123 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8124 		scalar32_min_max_mul(dst_reg, &src_reg);
8125 		scalar_min_max_mul(dst_reg, &src_reg);
8126 		break;
8127 	case BPF_AND:
8128 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8129 		scalar32_min_max_and(dst_reg, &src_reg);
8130 		scalar_min_max_and(dst_reg, &src_reg);
8131 		break;
8132 	case BPF_OR:
8133 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8134 		scalar32_min_max_or(dst_reg, &src_reg);
8135 		scalar_min_max_or(dst_reg, &src_reg);
8136 		break;
8137 	case BPF_XOR:
8138 		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8139 		scalar32_min_max_xor(dst_reg, &src_reg);
8140 		scalar_min_max_xor(dst_reg, &src_reg);
8141 		break;
8142 	case BPF_LSH:
8143 		if (umax_val >= insn_bitness) {
8144 			/* Shifts greater than 31 or 63 are undefined.
8145 			 * This includes shifts by a negative number.
8146 			 */
8147 			mark_reg_unknown(env, regs, insn->dst_reg);
8148 			break;
8149 		}
8150 		if (alu32)
8151 			scalar32_min_max_lsh(dst_reg, &src_reg);
8152 		else
8153 			scalar_min_max_lsh(dst_reg, &src_reg);
8154 		break;
8155 	case BPF_RSH:
8156 		if (umax_val >= insn_bitness) {
8157 			/* Shifts greater than 31 or 63 are undefined.
8158 			 * This includes shifts by a negative number.
8159 			 */
8160 			mark_reg_unknown(env, regs, insn->dst_reg);
8161 			break;
8162 		}
8163 		if (alu32)
8164 			scalar32_min_max_rsh(dst_reg, &src_reg);
8165 		else
8166 			scalar_min_max_rsh(dst_reg, &src_reg);
8167 		break;
8168 	case BPF_ARSH:
8169 		if (umax_val >= insn_bitness) {
8170 			/* Shifts greater than 31 or 63 are undefined.
8171 			 * This includes shifts by a negative number.
8172 			 */
8173 			mark_reg_unknown(env, regs, insn->dst_reg);
8174 			break;
8175 		}
8176 		if (alu32)
8177 			scalar32_min_max_arsh(dst_reg, &src_reg);
8178 		else
8179 			scalar_min_max_arsh(dst_reg, &src_reg);
8180 		break;
8181 	default:
8182 		mark_reg_unknown(env, regs, insn->dst_reg);
8183 		break;
8184 	}
8185 
8186 	/* ALU32 ops are zero extended into 64bit register */
8187 	if (alu32)
8188 		zext_32_to_64(dst_reg);
8189 	reg_bounds_sync(dst_reg);
8190 	return 0;
8191 }
8192 
8193 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8194  * and var_off.
8195  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)8196 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8197 				   struct bpf_insn *insn)
8198 {
8199 	struct bpf_verifier_state *vstate = env->cur_state;
8200 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
8201 	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
8202 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8203 	u8 opcode = BPF_OP(insn->code);
8204 	int err;
8205 
8206 	dst_reg = &regs[insn->dst_reg];
8207 	src_reg = NULL;
8208 	if (dst_reg->type != SCALAR_VALUE)
8209 		ptr_reg = dst_reg;
8210 	else
8211 		/* Make sure ID is cleared otherwise dst_reg min/max could be
8212 		 * incorrectly propagated into other registers by find_equal_scalars()
8213 		 */
8214 		dst_reg->id = 0;
8215 	if (BPF_SRC(insn->code) == BPF_X) {
8216 		src_reg = &regs[insn->src_reg];
8217 		if (src_reg->type != SCALAR_VALUE) {
8218 			if (dst_reg->type != SCALAR_VALUE) {
8219 				/* Combining two pointers by any ALU op yields
8220 				 * an arbitrary scalar. Disallow all math except
8221 				 * pointer subtraction
8222 				 */
8223 				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8224 					mark_reg_unknown(env, regs, insn->dst_reg);
8225 					return 0;
8226 				}
8227 				verbose(env, "R%d pointer %s pointer prohibited\n",
8228 					insn->dst_reg,
8229 					bpf_alu_string[opcode >> 4]);
8230 				return -EACCES;
8231 			} else {
8232 				/* scalar += pointer
8233 				 * This is legal, but we have to reverse our
8234 				 * src/dest handling in computing the range
8235 				 */
8236 				err = mark_chain_precision(env, insn->dst_reg);
8237 				if (err)
8238 					return err;
8239 				return adjust_ptr_min_max_vals(env, insn,
8240 							       src_reg, dst_reg);
8241 			}
8242 		} else if (ptr_reg) {
8243 			/* pointer += scalar */
8244 			err = mark_chain_precision(env, insn->src_reg);
8245 			if (err)
8246 				return err;
8247 			return adjust_ptr_min_max_vals(env, insn,
8248 						       dst_reg, src_reg);
8249 		} else if (dst_reg->precise) {
8250 			/* if dst_reg is precise, src_reg should be precise as well */
8251 			err = mark_chain_precision(env, insn->src_reg);
8252 			if (err)
8253 				return err;
8254 		}
8255 	} else {
8256 		/* Pretend the src is a reg with a known value, since we only
8257 		 * need to be able to read from this state.
8258 		 */
8259 		off_reg.type = SCALAR_VALUE;
8260 		__mark_reg_known(&off_reg, insn->imm);
8261 		src_reg = &off_reg;
8262 		if (ptr_reg) /* pointer += K */
8263 			return adjust_ptr_min_max_vals(env, insn,
8264 						       ptr_reg, src_reg);
8265 	}
8266 
8267 	/* Got here implies adding two SCALAR_VALUEs */
8268 	if (WARN_ON_ONCE(ptr_reg)) {
8269 		print_verifier_state(env, state);
8270 		verbose(env, "verifier internal error: unexpected ptr_reg\n");
8271 		return -EINVAL;
8272 	}
8273 	if (WARN_ON(!src_reg)) {
8274 		print_verifier_state(env, state);
8275 		verbose(env, "verifier internal error: no src_reg\n");
8276 		return -EINVAL;
8277 	}
8278 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8279 }
8280 
8281 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)8282 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8283 {
8284 	struct bpf_reg_state *regs = cur_regs(env);
8285 	u8 opcode = BPF_OP(insn->code);
8286 	int err;
8287 
8288 	if (opcode == BPF_END || opcode == BPF_NEG) {
8289 		if (opcode == BPF_NEG) {
8290 			if (BPF_SRC(insn->code) != 0 ||
8291 			    insn->src_reg != BPF_REG_0 ||
8292 			    insn->off != 0 || insn->imm != 0) {
8293 				verbose(env, "BPF_NEG uses reserved fields\n");
8294 				return -EINVAL;
8295 			}
8296 		} else {
8297 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8298 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8299 			    BPF_CLASS(insn->code) == BPF_ALU64) {
8300 				verbose(env, "BPF_END uses reserved fields\n");
8301 				return -EINVAL;
8302 			}
8303 		}
8304 
8305 		/* check src operand */
8306 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8307 		if (err)
8308 			return err;
8309 
8310 		if (is_pointer_value(env, insn->dst_reg)) {
8311 			verbose(env, "R%d pointer arithmetic prohibited\n",
8312 				insn->dst_reg);
8313 			return -EACCES;
8314 		}
8315 
8316 		/* check dest operand */
8317 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
8318 		if (err)
8319 			return err;
8320 
8321 	} else if (opcode == BPF_MOV) {
8322 
8323 		if (BPF_SRC(insn->code) == BPF_X) {
8324 			if (insn->imm != 0 || insn->off != 0) {
8325 				verbose(env, "BPF_MOV uses reserved fields\n");
8326 				return -EINVAL;
8327 			}
8328 
8329 			/* check src operand */
8330 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8331 			if (err)
8332 				return err;
8333 		} else {
8334 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8335 				verbose(env, "BPF_MOV uses reserved fields\n");
8336 				return -EINVAL;
8337 			}
8338 		}
8339 
8340 		/* check dest operand, mark as required later */
8341 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8342 		if (err)
8343 			return err;
8344 
8345 		if (BPF_SRC(insn->code) == BPF_X) {
8346 			struct bpf_reg_state *src_reg = regs + insn->src_reg;
8347 			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8348 
8349 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8350 				/* case: R1 = R2
8351 				 * copy register state to dest reg
8352 				 */
8353 				if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8354 					/* Assign src and dst registers the same ID
8355 					 * that will be used by find_equal_scalars()
8356 					 * to propagate min/max range.
8357 					 */
8358 					src_reg->id = ++env->id_gen;
8359 				copy_register_state(dst_reg, src_reg);
8360 				dst_reg->live |= REG_LIVE_WRITTEN;
8361 				dst_reg->subreg_def = DEF_NOT_SUBREG;
8362 			} else {
8363 				/* R1 = (u32) R2 */
8364 				if (is_pointer_value(env, insn->src_reg)) {
8365 					verbose(env,
8366 						"R%d partial copy of pointer\n",
8367 						insn->src_reg);
8368 					return -EACCES;
8369 				} else if (src_reg->type == SCALAR_VALUE) {
8370 					copy_register_state(dst_reg, src_reg);
8371 					/* Make sure ID is cleared otherwise
8372 					 * dst_reg min/max could be incorrectly
8373 					 * propagated into src_reg by find_equal_scalars()
8374 					 */
8375 					dst_reg->id = 0;
8376 					dst_reg->live |= REG_LIVE_WRITTEN;
8377 					dst_reg->subreg_def = env->insn_idx + 1;
8378 				} else {
8379 					mark_reg_unknown(env, regs,
8380 							 insn->dst_reg);
8381 				}
8382 				zext_32_to_64(dst_reg);
8383 				reg_bounds_sync(dst_reg);
8384 			}
8385 		} else {
8386 			/* case: R = imm
8387 			 * remember the value we stored into this reg
8388 			 */
8389 			/* clear any state __mark_reg_known doesn't set */
8390 			mark_reg_unknown(env, regs, insn->dst_reg);
8391 			regs[insn->dst_reg].type = SCALAR_VALUE;
8392 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
8393 				__mark_reg_known(regs + insn->dst_reg,
8394 						 insn->imm);
8395 			} else {
8396 				__mark_reg_known(regs + insn->dst_reg,
8397 						 (u32)insn->imm);
8398 			}
8399 		}
8400 
8401 	} else if (opcode > BPF_END) {
8402 		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8403 		return -EINVAL;
8404 
8405 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
8406 
8407 		if (BPF_SRC(insn->code) == BPF_X) {
8408 			if (insn->imm != 0 || insn->off != 0) {
8409 				verbose(env, "BPF_ALU uses reserved fields\n");
8410 				return -EINVAL;
8411 			}
8412 			/* check src1 operand */
8413 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
8414 			if (err)
8415 				return err;
8416 		} else {
8417 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8418 				verbose(env, "BPF_ALU uses reserved fields\n");
8419 				return -EINVAL;
8420 			}
8421 		}
8422 
8423 		/* check src2 operand */
8424 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8425 		if (err)
8426 			return err;
8427 
8428 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8429 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8430 			verbose(env, "div by zero\n");
8431 			return -EINVAL;
8432 		}
8433 
8434 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8435 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8436 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8437 
8438 			if (insn->imm < 0 || insn->imm >= size) {
8439 				verbose(env, "invalid shift %d\n", insn->imm);
8440 				return -EINVAL;
8441 			}
8442 		}
8443 
8444 		/* check dest operand */
8445 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8446 		if (err)
8447 			return err;
8448 
8449 		return adjust_reg_min_max_vals(env, insn);
8450 	}
8451 
8452 	return 0;
8453 }
8454 
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)8455 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8456 				   struct bpf_reg_state *dst_reg,
8457 				   enum bpf_reg_type type,
8458 				   bool range_right_open)
8459 {
8460 	struct bpf_func_state *state;
8461 	struct bpf_reg_state *reg;
8462 	int new_range;
8463 
8464 	if (dst_reg->off < 0 ||
8465 	    (dst_reg->off == 0 && range_right_open))
8466 		/* This doesn't give us any range */
8467 		return;
8468 
8469 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
8470 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8471 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
8472 		 * than pkt_end, but that's because it's also less than pkt.
8473 		 */
8474 		return;
8475 
8476 	new_range = dst_reg->off;
8477 	if (range_right_open)
8478 		new_range++;
8479 
8480 	/* Examples for register markings:
8481 	 *
8482 	 * pkt_data in dst register:
8483 	 *
8484 	 *   r2 = r3;
8485 	 *   r2 += 8;
8486 	 *   if (r2 > pkt_end) goto <handle exception>
8487 	 *   <access okay>
8488 	 *
8489 	 *   r2 = r3;
8490 	 *   r2 += 8;
8491 	 *   if (r2 < pkt_end) goto <access okay>
8492 	 *   <handle exception>
8493 	 *
8494 	 *   Where:
8495 	 *     r2 == dst_reg, pkt_end == src_reg
8496 	 *     r2=pkt(id=n,off=8,r=0)
8497 	 *     r3=pkt(id=n,off=0,r=0)
8498 	 *
8499 	 * pkt_data in src register:
8500 	 *
8501 	 *   r2 = r3;
8502 	 *   r2 += 8;
8503 	 *   if (pkt_end >= r2) goto <access okay>
8504 	 *   <handle exception>
8505 	 *
8506 	 *   r2 = r3;
8507 	 *   r2 += 8;
8508 	 *   if (pkt_end <= r2) goto <handle exception>
8509 	 *   <access okay>
8510 	 *
8511 	 *   Where:
8512 	 *     pkt_end == dst_reg, r2 == src_reg
8513 	 *     r2=pkt(id=n,off=8,r=0)
8514 	 *     r3=pkt(id=n,off=0,r=0)
8515 	 *
8516 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8517 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8518 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
8519 	 * the check.
8520 	 */
8521 
8522 	/* If our ids match, then we must have the same max_value.  And we
8523 	 * don't care about the other reg's fixed offset, since if it's too big
8524 	 * the range won't allow anything.
8525 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8526 	 */
8527 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8528 		if (reg->type == type && reg->id == dst_reg->id)
8529 			/* keep the maximum range already checked */
8530 			reg->range = max(reg->range, new_range);
8531 	}));
8532 }
8533 
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)8534 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8535 {
8536 	struct tnum subreg = tnum_subreg(reg->var_off);
8537 	s32 sval = (s32)val;
8538 
8539 	switch (opcode) {
8540 	case BPF_JEQ:
8541 		if (tnum_is_const(subreg))
8542 			return !!tnum_equals_const(subreg, val);
8543 		break;
8544 	case BPF_JNE:
8545 		if (tnum_is_const(subreg))
8546 			return !tnum_equals_const(subreg, val);
8547 		break;
8548 	case BPF_JSET:
8549 		if ((~subreg.mask & subreg.value) & val)
8550 			return 1;
8551 		if (!((subreg.mask | subreg.value) & val))
8552 			return 0;
8553 		break;
8554 	case BPF_JGT:
8555 		if (reg->u32_min_value > val)
8556 			return 1;
8557 		else if (reg->u32_max_value <= val)
8558 			return 0;
8559 		break;
8560 	case BPF_JSGT:
8561 		if (reg->s32_min_value > sval)
8562 			return 1;
8563 		else if (reg->s32_max_value <= sval)
8564 			return 0;
8565 		break;
8566 	case BPF_JLT:
8567 		if (reg->u32_max_value < val)
8568 			return 1;
8569 		else if (reg->u32_min_value >= val)
8570 			return 0;
8571 		break;
8572 	case BPF_JSLT:
8573 		if (reg->s32_max_value < sval)
8574 			return 1;
8575 		else if (reg->s32_min_value >= sval)
8576 			return 0;
8577 		break;
8578 	case BPF_JGE:
8579 		if (reg->u32_min_value >= val)
8580 			return 1;
8581 		else if (reg->u32_max_value < val)
8582 			return 0;
8583 		break;
8584 	case BPF_JSGE:
8585 		if (reg->s32_min_value >= sval)
8586 			return 1;
8587 		else if (reg->s32_max_value < sval)
8588 			return 0;
8589 		break;
8590 	case BPF_JLE:
8591 		if (reg->u32_max_value <= val)
8592 			return 1;
8593 		else if (reg->u32_min_value > val)
8594 			return 0;
8595 		break;
8596 	case BPF_JSLE:
8597 		if (reg->s32_max_value <= sval)
8598 			return 1;
8599 		else if (reg->s32_min_value > sval)
8600 			return 0;
8601 		break;
8602 	}
8603 
8604 	return -1;
8605 }
8606 
8607 
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)8608 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8609 {
8610 	s64 sval = (s64)val;
8611 
8612 	switch (opcode) {
8613 	case BPF_JEQ:
8614 		if (tnum_is_const(reg->var_off))
8615 			return !!tnum_equals_const(reg->var_off, val);
8616 		break;
8617 	case BPF_JNE:
8618 		if (tnum_is_const(reg->var_off))
8619 			return !tnum_equals_const(reg->var_off, val);
8620 		break;
8621 	case BPF_JSET:
8622 		if ((~reg->var_off.mask & reg->var_off.value) & val)
8623 			return 1;
8624 		if (!((reg->var_off.mask | reg->var_off.value) & val))
8625 			return 0;
8626 		break;
8627 	case BPF_JGT:
8628 		if (reg->umin_value > val)
8629 			return 1;
8630 		else if (reg->umax_value <= val)
8631 			return 0;
8632 		break;
8633 	case BPF_JSGT:
8634 		if (reg->smin_value > sval)
8635 			return 1;
8636 		else if (reg->smax_value <= sval)
8637 			return 0;
8638 		break;
8639 	case BPF_JLT:
8640 		if (reg->umax_value < val)
8641 			return 1;
8642 		else if (reg->umin_value >= val)
8643 			return 0;
8644 		break;
8645 	case BPF_JSLT:
8646 		if (reg->smax_value < sval)
8647 			return 1;
8648 		else if (reg->smin_value >= sval)
8649 			return 0;
8650 		break;
8651 	case BPF_JGE:
8652 		if (reg->umin_value >= val)
8653 			return 1;
8654 		else if (reg->umax_value < val)
8655 			return 0;
8656 		break;
8657 	case BPF_JSGE:
8658 		if (reg->smin_value >= sval)
8659 			return 1;
8660 		else if (reg->smax_value < sval)
8661 			return 0;
8662 		break;
8663 	case BPF_JLE:
8664 		if (reg->umax_value <= val)
8665 			return 1;
8666 		else if (reg->umin_value > val)
8667 			return 0;
8668 		break;
8669 	case BPF_JSLE:
8670 		if (reg->smax_value <= sval)
8671 			return 1;
8672 		else if (reg->smin_value > sval)
8673 			return 0;
8674 		break;
8675 	}
8676 
8677 	return -1;
8678 }
8679 
8680 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8681  * and return:
8682  *  1 - branch will be taken and "goto target" will be executed
8683  *  0 - branch will not be taken and fall-through to next insn
8684  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8685  *      range [0,10]
8686  */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)8687 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8688 			   bool is_jmp32)
8689 {
8690 	if (__is_pointer_value(false, reg)) {
8691 		if (!reg_type_not_null(reg->type))
8692 			return -1;
8693 
8694 		/* If pointer is valid tests against zero will fail so we can
8695 		 * use this to direct branch taken.
8696 		 */
8697 		if (val != 0)
8698 			return -1;
8699 
8700 		switch (opcode) {
8701 		case BPF_JEQ:
8702 			return 0;
8703 		case BPF_JNE:
8704 			return 1;
8705 		default:
8706 			return -1;
8707 		}
8708 	}
8709 
8710 	if (is_jmp32)
8711 		return is_branch32_taken(reg, val, opcode);
8712 	return is_branch64_taken(reg, val, opcode);
8713 }
8714 
flip_opcode(u32 opcode)8715 static int flip_opcode(u32 opcode)
8716 {
8717 	/* How can we transform "a <op> b" into "b <op> a"? */
8718 	static const u8 opcode_flip[16] = {
8719 		/* these stay the same */
8720 		[BPF_JEQ  >> 4] = BPF_JEQ,
8721 		[BPF_JNE  >> 4] = BPF_JNE,
8722 		[BPF_JSET >> 4] = BPF_JSET,
8723 		/* these swap "lesser" and "greater" (L and G in the opcodes) */
8724 		[BPF_JGE  >> 4] = BPF_JLE,
8725 		[BPF_JGT  >> 4] = BPF_JLT,
8726 		[BPF_JLE  >> 4] = BPF_JGE,
8727 		[BPF_JLT  >> 4] = BPF_JGT,
8728 		[BPF_JSGE >> 4] = BPF_JSLE,
8729 		[BPF_JSGT >> 4] = BPF_JSLT,
8730 		[BPF_JSLE >> 4] = BPF_JSGE,
8731 		[BPF_JSLT >> 4] = BPF_JSGT
8732 	};
8733 	return opcode_flip[opcode >> 4];
8734 }
8735 
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)8736 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8737 				   struct bpf_reg_state *src_reg,
8738 				   u8 opcode)
8739 {
8740 	struct bpf_reg_state *pkt;
8741 
8742 	if (src_reg->type == PTR_TO_PACKET_END) {
8743 		pkt = dst_reg;
8744 	} else if (dst_reg->type == PTR_TO_PACKET_END) {
8745 		pkt = src_reg;
8746 		opcode = flip_opcode(opcode);
8747 	} else {
8748 		return -1;
8749 	}
8750 
8751 	if (pkt->range >= 0)
8752 		return -1;
8753 
8754 	switch (opcode) {
8755 	case BPF_JLE:
8756 		/* pkt <= pkt_end */
8757 		fallthrough;
8758 	case BPF_JGT:
8759 		/* pkt > pkt_end */
8760 		if (pkt->range == BEYOND_PKT_END)
8761 			/* pkt has at last one extra byte beyond pkt_end */
8762 			return opcode == BPF_JGT;
8763 		break;
8764 	case BPF_JLT:
8765 		/* pkt < pkt_end */
8766 		fallthrough;
8767 	case BPF_JGE:
8768 		/* pkt >= pkt_end */
8769 		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8770 			return opcode == BPF_JGE;
8771 		break;
8772 	}
8773 	return -1;
8774 }
8775 
8776 /* Adjusts the register min/max values in the case that the dst_reg is the
8777  * variable register that we are working on, and src_reg is a constant or we're
8778  * simply doing a BPF_K check.
8779  * In JEQ/JNE cases we also adjust the var_off values.
8780  */
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)8781 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8782 			    struct bpf_reg_state *false_reg,
8783 			    u64 val, u32 val32,
8784 			    u8 opcode, bool is_jmp32)
8785 {
8786 	struct tnum false_32off = tnum_subreg(false_reg->var_off);
8787 	struct tnum false_64off = false_reg->var_off;
8788 	struct tnum true_32off = tnum_subreg(true_reg->var_off);
8789 	struct tnum true_64off = true_reg->var_off;
8790 	s64 sval = (s64)val;
8791 	s32 sval32 = (s32)val32;
8792 
8793 	/* If the dst_reg is a pointer, we can't learn anything about its
8794 	 * variable offset from the compare (unless src_reg were a pointer into
8795 	 * the same object, but we don't bother with that.
8796 	 * Since false_reg and true_reg have the same type by construction, we
8797 	 * only need to check one of them for pointerness.
8798 	 */
8799 	if (__is_pointer_value(false, false_reg))
8800 		return;
8801 
8802 	switch (opcode) {
8803 	/* JEQ/JNE comparison doesn't change the register equivalence.
8804 	 *
8805 	 * r1 = r2;
8806 	 * if (r1 == 42) goto label;
8807 	 * ...
8808 	 * label: // here both r1 and r2 are known to be 42.
8809 	 *
8810 	 * Hence when marking register as known preserve it's ID.
8811 	 */
8812 	case BPF_JEQ:
8813 		if (is_jmp32) {
8814 			__mark_reg32_known(true_reg, val32);
8815 			true_32off = tnum_subreg(true_reg->var_off);
8816 		} else {
8817 			___mark_reg_known(true_reg, val);
8818 			true_64off = true_reg->var_off;
8819 		}
8820 		break;
8821 	case BPF_JNE:
8822 		if (is_jmp32) {
8823 			__mark_reg32_known(false_reg, val32);
8824 			false_32off = tnum_subreg(false_reg->var_off);
8825 		} else {
8826 			___mark_reg_known(false_reg, val);
8827 			false_64off = false_reg->var_off;
8828 		}
8829 		break;
8830 	case BPF_JSET:
8831 		if (is_jmp32) {
8832 			false_32off = tnum_and(false_32off, tnum_const(~val32));
8833 			if (is_power_of_2(val32))
8834 				true_32off = tnum_or(true_32off,
8835 						     tnum_const(val32));
8836 		} else {
8837 			false_64off = tnum_and(false_64off, tnum_const(~val));
8838 			if (is_power_of_2(val))
8839 				true_64off = tnum_or(true_64off,
8840 						     tnum_const(val));
8841 		}
8842 		break;
8843 	case BPF_JGE:
8844 	case BPF_JGT:
8845 	{
8846 		if (is_jmp32) {
8847 			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
8848 			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8849 
8850 			false_reg->u32_max_value = min(false_reg->u32_max_value,
8851 						       false_umax);
8852 			true_reg->u32_min_value = max(true_reg->u32_min_value,
8853 						      true_umin);
8854 		} else {
8855 			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
8856 			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8857 
8858 			false_reg->umax_value = min(false_reg->umax_value, false_umax);
8859 			true_reg->umin_value = max(true_reg->umin_value, true_umin);
8860 		}
8861 		break;
8862 	}
8863 	case BPF_JSGE:
8864 	case BPF_JSGT:
8865 	{
8866 		if (is_jmp32) {
8867 			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
8868 			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8869 
8870 			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8871 			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8872 		} else {
8873 			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
8874 			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8875 
8876 			false_reg->smax_value = min(false_reg->smax_value, false_smax);
8877 			true_reg->smin_value = max(true_reg->smin_value, true_smin);
8878 		}
8879 		break;
8880 	}
8881 	case BPF_JLE:
8882 	case BPF_JLT:
8883 	{
8884 		if (is_jmp32) {
8885 			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
8886 			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8887 
8888 			false_reg->u32_min_value = max(false_reg->u32_min_value,
8889 						       false_umin);
8890 			true_reg->u32_max_value = min(true_reg->u32_max_value,
8891 						      true_umax);
8892 		} else {
8893 			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
8894 			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8895 
8896 			false_reg->umin_value = max(false_reg->umin_value, false_umin);
8897 			true_reg->umax_value = min(true_reg->umax_value, true_umax);
8898 		}
8899 		break;
8900 	}
8901 	case BPF_JSLE:
8902 	case BPF_JSLT:
8903 	{
8904 		if (is_jmp32) {
8905 			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
8906 			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8907 
8908 			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8909 			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8910 		} else {
8911 			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
8912 			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8913 
8914 			false_reg->smin_value = max(false_reg->smin_value, false_smin);
8915 			true_reg->smax_value = min(true_reg->smax_value, true_smax);
8916 		}
8917 		break;
8918 	}
8919 	default:
8920 		return;
8921 	}
8922 
8923 	if (is_jmp32) {
8924 		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8925 					     tnum_subreg(false_32off));
8926 		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8927 					    tnum_subreg(true_32off));
8928 		__reg_combine_32_into_64(false_reg);
8929 		__reg_combine_32_into_64(true_reg);
8930 	} else {
8931 		false_reg->var_off = false_64off;
8932 		true_reg->var_off = true_64off;
8933 		__reg_combine_64_into_32(false_reg);
8934 		__reg_combine_64_into_32(true_reg);
8935 	}
8936 }
8937 
8938 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8939  * the variable reg.
8940  */
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)8941 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8942 				struct bpf_reg_state *false_reg,
8943 				u64 val, u32 val32,
8944 				u8 opcode, bool is_jmp32)
8945 {
8946 	opcode = flip_opcode(opcode);
8947 	/* This uses zero as "not present in table"; luckily the zero opcode,
8948 	 * BPF_JA, can't get here.
8949 	 */
8950 	if (opcode)
8951 		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8952 }
8953 
8954 /* 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)8955 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8956 				  struct bpf_reg_state *dst_reg)
8957 {
8958 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8959 							dst_reg->umin_value);
8960 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8961 							dst_reg->umax_value);
8962 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8963 							dst_reg->smin_value);
8964 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8965 							dst_reg->smax_value);
8966 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8967 							     dst_reg->var_off);
8968 	reg_bounds_sync(src_reg);
8969 	reg_bounds_sync(dst_reg);
8970 }
8971 
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)8972 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8973 				struct bpf_reg_state *true_dst,
8974 				struct bpf_reg_state *false_src,
8975 				struct bpf_reg_state *false_dst,
8976 				u8 opcode)
8977 {
8978 	switch (opcode) {
8979 	case BPF_JEQ:
8980 		__reg_combine_min_max(true_src, true_dst);
8981 		break;
8982 	case BPF_JNE:
8983 		__reg_combine_min_max(false_src, false_dst);
8984 		break;
8985 	}
8986 }
8987 
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)8988 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8989 				 struct bpf_reg_state *reg, u32 id,
8990 				 bool is_null)
8991 {
8992 	if (type_may_be_null(reg->type) && reg->id == id &&
8993 	    !WARN_ON_ONCE(!reg->id)) {
8994 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8995 				 !tnum_equals_const(reg->var_off, 0) ||
8996 				 reg->off)) {
8997 			/* Old offset (both fixed and variable parts) should
8998 			 * have been known-zero, because we don't allow pointer
8999 			 * arithmetic on pointers that might be NULL. If we
9000 			 * see this happening, don't convert the register.
9001 			 */
9002 			return;
9003 		}
9004 		if (is_null) {
9005 			reg->type = SCALAR_VALUE;
9006 			/* We don't need id and ref_obj_id from this point
9007 			 * onwards anymore, thus we should better reset it,
9008 			 * so that state pruning has chances to take effect.
9009 			 */
9010 			reg->id = 0;
9011 			reg->ref_obj_id = 0;
9012 
9013 			return;
9014 		}
9015 
9016 		mark_ptr_not_null_reg(reg);
9017 
9018 		if (!reg_may_point_to_spin_lock(reg)) {
9019 			/* For not-NULL ptr, reg->ref_obj_id will be reset
9020 			 * in release_reference().
9021 			 *
9022 			 * reg->id is still used by spin_lock ptr. Other
9023 			 * than spin_lock ptr type, reg->id can be reset.
9024 			 */
9025 			reg->id = 0;
9026 		}
9027 	}
9028 }
9029 
9030 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9031  * be folded together at some point.
9032  */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)9033 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9034 				  bool is_null)
9035 {
9036 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9037 	struct bpf_reg_state *regs = state->regs, *reg;
9038 	u32 ref_obj_id = regs[regno].ref_obj_id;
9039 	u32 id = regs[regno].id;
9040 
9041 	if (ref_obj_id && ref_obj_id == id && is_null)
9042 		/* regs[regno] is in the " == NULL" branch.
9043 		 * No one could have freed the reference state before
9044 		 * doing the NULL check.
9045 		 */
9046 		WARN_ON_ONCE(release_reference_state(state, id));
9047 
9048 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9049 		mark_ptr_or_null_reg(state, reg, id, is_null);
9050 	}));
9051 }
9052 
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)9053 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9054 				   struct bpf_reg_state *dst_reg,
9055 				   struct bpf_reg_state *src_reg,
9056 				   struct bpf_verifier_state *this_branch,
9057 				   struct bpf_verifier_state *other_branch)
9058 {
9059 	if (BPF_SRC(insn->code) != BPF_X)
9060 		return false;
9061 
9062 	/* Pointers are always 64-bit. */
9063 	if (BPF_CLASS(insn->code) == BPF_JMP32)
9064 		return false;
9065 
9066 	switch (BPF_OP(insn->code)) {
9067 	case BPF_JGT:
9068 		if ((dst_reg->type == PTR_TO_PACKET &&
9069 		     src_reg->type == PTR_TO_PACKET_END) ||
9070 		    (dst_reg->type == PTR_TO_PACKET_META &&
9071 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9072 			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9073 			find_good_pkt_pointers(this_branch, dst_reg,
9074 					       dst_reg->type, false);
9075 			mark_pkt_end(other_branch, insn->dst_reg, true);
9076 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9077 			    src_reg->type == PTR_TO_PACKET) ||
9078 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9079 			    src_reg->type == PTR_TO_PACKET_META)) {
9080 			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
9081 			find_good_pkt_pointers(other_branch, src_reg,
9082 					       src_reg->type, true);
9083 			mark_pkt_end(this_branch, insn->src_reg, false);
9084 		} else {
9085 			return false;
9086 		}
9087 		break;
9088 	case BPF_JLT:
9089 		if ((dst_reg->type == PTR_TO_PACKET &&
9090 		     src_reg->type == PTR_TO_PACKET_END) ||
9091 		    (dst_reg->type == PTR_TO_PACKET_META &&
9092 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9093 			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9094 			find_good_pkt_pointers(other_branch, dst_reg,
9095 					       dst_reg->type, true);
9096 			mark_pkt_end(this_branch, insn->dst_reg, false);
9097 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9098 			    src_reg->type == PTR_TO_PACKET) ||
9099 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9100 			    src_reg->type == PTR_TO_PACKET_META)) {
9101 			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
9102 			find_good_pkt_pointers(this_branch, src_reg,
9103 					       src_reg->type, false);
9104 			mark_pkt_end(other_branch, insn->src_reg, true);
9105 		} else {
9106 			return false;
9107 		}
9108 		break;
9109 	case BPF_JGE:
9110 		if ((dst_reg->type == PTR_TO_PACKET &&
9111 		     src_reg->type == PTR_TO_PACKET_END) ||
9112 		    (dst_reg->type == PTR_TO_PACKET_META &&
9113 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9114 			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9115 			find_good_pkt_pointers(this_branch, dst_reg,
9116 					       dst_reg->type, true);
9117 			mark_pkt_end(other_branch, insn->dst_reg, false);
9118 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9119 			    src_reg->type == PTR_TO_PACKET) ||
9120 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9121 			    src_reg->type == PTR_TO_PACKET_META)) {
9122 			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9123 			find_good_pkt_pointers(other_branch, src_reg,
9124 					       src_reg->type, false);
9125 			mark_pkt_end(this_branch, insn->src_reg, true);
9126 		} else {
9127 			return false;
9128 		}
9129 		break;
9130 	case BPF_JLE:
9131 		if ((dst_reg->type == PTR_TO_PACKET &&
9132 		     src_reg->type == PTR_TO_PACKET_END) ||
9133 		    (dst_reg->type == PTR_TO_PACKET_META &&
9134 		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9135 			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9136 			find_good_pkt_pointers(other_branch, dst_reg,
9137 					       dst_reg->type, false);
9138 			mark_pkt_end(this_branch, insn->dst_reg, true);
9139 		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
9140 			    src_reg->type == PTR_TO_PACKET) ||
9141 			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9142 			    src_reg->type == PTR_TO_PACKET_META)) {
9143 			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9144 			find_good_pkt_pointers(this_branch, src_reg,
9145 					       src_reg->type, true);
9146 			mark_pkt_end(other_branch, insn->src_reg, false);
9147 		} else {
9148 			return false;
9149 		}
9150 		break;
9151 	default:
9152 		return false;
9153 	}
9154 
9155 	return true;
9156 }
9157 
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)9158 static void find_equal_scalars(struct bpf_verifier_state *vstate,
9159 			       struct bpf_reg_state *known_reg)
9160 {
9161 	struct bpf_func_state *state;
9162 	struct bpf_reg_state *reg;
9163 
9164 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9165 		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9166 			copy_register_state(reg, known_reg);
9167 	}));
9168 }
9169 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)9170 static int check_cond_jmp_op(struct bpf_verifier_env *env,
9171 			     struct bpf_insn *insn, int *insn_idx)
9172 {
9173 	struct bpf_verifier_state *this_branch = env->cur_state;
9174 	struct bpf_verifier_state *other_branch;
9175 	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
9176 	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
9177 	u8 opcode = BPF_OP(insn->code);
9178 	bool is_jmp32;
9179 	int pred = -1;
9180 	int err;
9181 
9182 	/* Only conditional jumps are expected to reach here. */
9183 	if (opcode == BPF_JA || opcode > BPF_JSLE) {
9184 		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9185 		return -EINVAL;
9186 	}
9187 
9188 	if (BPF_SRC(insn->code) == BPF_X) {
9189 		if (insn->imm != 0) {
9190 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9191 			return -EINVAL;
9192 		}
9193 
9194 		/* check src1 operand */
9195 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9196 		if (err)
9197 			return err;
9198 
9199 		if (is_pointer_value(env, insn->src_reg)) {
9200 			verbose(env, "R%d pointer comparison prohibited\n",
9201 				insn->src_reg);
9202 			return -EACCES;
9203 		}
9204 		src_reg = &regs[insn->src_reg];
9205 	} else {
9206 		if (insn->src_reg != BPF_REG_0) {
9207 			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9208 			return -EINVAL;
9209 		}
9210 	}
9211 
9212 	/* check src2 operand */
9213 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9214 	if (err)
9215 		return err;
9216 
9217 	dst_reg = &regs[insn->dst_reg];
9218 	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9219 
9220 	if (BPF_SRC(insn->code) == BPF_K) {
9221 		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9222 	} else if (src_reg->type == SCALAR_VALUE &&
9223 		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9224 		pred = is_branch_taken(dst_reg,
9225 				       tnum_subreg(src_reg->var_off).value,
9226 				       opcode,
9227 				       is_jmp32);
9228 	} else if (src_reg->type == SCALAR_VALUE &&
9229 		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9230 		pred = is_branch_taken(dst_reg,
9231 				       src_reg->var_off.value,
9232 				       opcode,
9233 				       is_jmp32);
9234 	} else if (reg_is_pkt_pointer_any(dst_reg) &&
9235 		   reg_is_pkt_pointer_any(src_reg) &&
9236 		   !is_jmp32) {
9237 		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9238 	}
9239 
9240 	if (pred >= 0) {
9241 		/* If we get here with a dst_reg pointer type it is because
9242 		 * above is_branch_taken() special cased the 0 comparison.
9243 		 */
9244 		if (!__is_pointer_value(false, dst_reg))
9245 			err = mark_chain_precision(env, insn->dst_reg);
9246 		if (BPF_SRC(insn->code) == BPF_X && !err &&
9247 		    !__is_pointer_value(false, src_reg))
9248 			err = mark_chain_precision(env, insn->src_reg);
9249 		if (err)
9250 			return err;
9251 	}
9252 
9253 	if (pred == 1) {
9254 		/* Only follow the goto, ignore fall-through. If needed, push
9255 		 * the fall-through branch for simulation under speculative
9256 		 * execution.
9257 		 */
9258 		if (!env->bypass_spec_v1 &&
9259 		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
9260 					       *insn_idx))
9261 			return -EFAULT;
9262 		*insn_idx += insn->off;
9263 		return 0;
9264 	} else if (pred == 0) {
9265 		/* Only follow the fall-through branch, since that's where the
9266 		 * program will go. If needed, push the goto branch for
9267 		 * simulation under speculative execution.
9268 		 */
9269 		if (!env->bypass_spec_v1 &&
9270 		    !sanitize_speculative_path(env, insn,
9271 					       *insn_idx + insn->off + 1,
9272 					       *insn_idx))
9273 			return -EFAULT;
9274 		return 0;
9275 	}
9276 
9277 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9278 				  false);
9279 	if (!other_branch)
9280 		return -EFAULT;
9281 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9282 
9283 	/* detect if we are comparing against a constant value so we can adjust
9284 	 * our min/max values for our dst register.
9285 	 * this is only legit if both are scalars (or pointers to the same
9286 	 * object, I suppose, but we don't support that right now), because
9287 	 * otherwise the different base pointers mean the offsets aren't
9288 	 * comparable.
9289 	 */
9290 	if (BPF_SRC(insn->code) == BPF_X) {
9291 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9292 
9293 		if (dst_reg->type == SCALAR_VALUE &&
9294 		    src_reg->type == SCALAR_VALUE) {
9295 			if (tnum_is_const(src_reg->var_off) ||
9296 			    (is_jmp32 &&
9297 			     tnum_is_const(tnum_subreg(src_reg->var_off))))
9298 				reg_set_min_max(&other_branch_regs[insn->dst_reg],
9299 						dst_reg,
9300 						src_reg->var_off.value,
9301 						tnum_subreg(src_reg->var_off).value,
9302 						opcode, is_jmp32);
9303 			else if (tnum_is_const(dst_reg->var_off) ||
9304 				 (is_jmp32 &&
9305 				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
9306 				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9307 						    src_reg,
9308 						    dst_reg->var_off.value,
9309 						    tnum_subreg(dst_reg->var_off).value,
9310 						    opcode, is_jmp32);
9311 			else if (!is_jmp32 &&
9312 				 (opcode == BPF_JEQ || opcode == BPF_JNE))
9313 				/* Comparing for equality, we can combine knowledge */
9314 				reg_combine_min_max(&other_branch_regs[insn->src_reg],
9315 						    &other_branch_regs[insn->dst_reg],
9316 						    src_reg, dst_reg, opcode);
9317 			if (src_reg->id &&
9318 			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9319 				find_equal_scalars(this_branch, src_reg);
9320 				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9321 			}
9322 
9323 		}
9324 	} else if (dst_reg->type == SCALAR_VALUE) {
9325 		reg_set_min_max(&other_branch_regs[insn->dst_reg],
9326 					dst_reg, insn->imm, (u32)insn->imm,
9327 					opcode, is_jmp32);
9328 	}
9329 
9330 	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9331 	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9332 		find_equal_scalars(this_branch, dst_reg);
9333 		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9334 	}
9335 
9336 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9337 	 * NOTE: these optimizations below are related with pointer comparison
9338 	 *       which will never be JMP32.
9339 	 */
9340 	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9341 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9342 	    type_may_be_null(dst_reg->type)) {
9343 		/* Mark all identical registers in each branch as either
9344 		 * safe or unknown depending R == 0 or R != 0 conditional.
9345 		 */
9346 		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9347 				      opcode == BPF_JNE);
9348 		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9349 				      opcode == BPF_JEQ);
9350 	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9351 					   this_branch, other_branch) &&
9352 		   is_pointer_value(env, insn->dst_reg)) {
9353 		verbose(env, "R%d pointer comparison prohibited\n",
9354 			insn->dst_reg);
9355 		return -EACCES;
9356 	}
9357 	if (env->log.level & BPF_LOG_LEVEL)
9358 		print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9359 	return 0;
9360 }
9361 
9362 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)9363 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9364 {
9365 	struct bpf_insn_aux_data *aux = cur_aux(env);
9366 	struct bpf_reg_state *regs = cur_regs(env);
9367 	struct bpf_reg_state *dst_reg;
9368 	struct bpf_map *map;
9369 	int err;
9370 
9371 	if (BPF_SIZE(insn->code) != BPF_DW) {
9372 		verbose(env, "invalid BPF_LD_IMM insn\n");
9373 		return -EINVAL;
9374 	}
9375 	if (insn->off != 0) {
9376 		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9377 		return -EINVAL;
9378 	}
9379 
9380 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
9381 	if (err)
9382 		return err;
9383 
9384 	dst_reg = &regs[insn->dst_reg];
9385 	if (insn->src_reg == 0) {
9386 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9387 
9388 		dst_reg->type = SCALAR_VALUE;
9389 		__mark_reg_known(&regs[insn->dst_reg], imm);
9390 		return 0;
9391 	}
9392 
9393 	/* All special src_reg cases are listed below. From this point onwards
9394 	 * we either succeed and assign a corresponding dst_reg->type after
9395 	 * zeroing the offset, or fail and reject the program.
9396 	 */
9397 	mark_reg_known_zero(env, regs, insn->dst_reg);
9398 
9399 	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9400 		dst_reg->type = aux->btf_var.reg_type;
9401 		switch (base_type(dst_reg->type)) {
9402 		case PTR_TO_MEM:
9403 			dst_reg->mem_size = aux->btf_var.mem_size;
9404 			break;
9405 		case PTR_TO_BTF_ID:
9406 		case PTR_TO_PERCPU_BTF_ID:
9407 			dst_reg->btf = aux->btf_var.btf;
9408 			dst_reg->btf_id = aux->btf_var.btf_id;
9409 			break;
9410 		default:
9411 			verbose(env, "bpf verifier is misconfigured\n");
9412 			return -EFAULT;
9413 		}
9414 		return 0;
9415 	}
9416 
9417 	if (insn->src_reg == BPF_PSEUDO_FUNC) {
9418 		struct bpf_prog_aux *aux = env->prog->aux;
9419 		u32 subprogno = find_subprog(env,
9420 					     env->insn_idx + insn->imm + 1);
9421 
9422 		if (!aux->func_info) {
9423 			verbose(env, "missing btf func_info\n");
9424 			return -EINVAL;
9425 		}
9426 		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9427 			verbose(env, "callback function not static\n");
9428 			return -EINVAL;
9429 		}
9430 
9431 		dst_reg->type = PTR_TO_FUNC;
9432 		dst_reg->subprogno = subprogno;
9433 		return 0;
9434 	}
9435 
9436 	map = env->used_maps[aux->map_index];
9437 	dst_reg->map_ptr = map;
9438 
9439 	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9440 	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9441 		dst_reg->type = PTR_TO_MAP_VALUE;
9442 		dst_reg->off = aux->map_off;
9443 		if (map_value_has_spin_lock(map))
9444 			dst_reg->id = ++env->id_gen;
9445 	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9446 		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9447 		dst_reg->type = CONST_PTR_TO_MAP;
9448 	} else {
9449 		verbose(env, "bpf verifier is misconfigured\n");
9450 		return -EINVAL;
9451 	}
9452 
9453 	return 0;
9454 }
9455 
may_access_skb(enum bpf_prog_type type)9456 static bool may_access_skb(enum bpf_prog_type type)
9457 {
9458 	switch (type) {
9459 	case BPF_PROG_TYPE_SOCKET_FILTER:
9460 	case BPF_PROG_TYPE_SCHED_CLS:
9461 	case BPF_PROG_TYPE_SCHED_ACT:
9462 		return true;
9463 	default:
9464 		return false;
9465 	}
9466 }
9467 
9468 /* verify safety of LD_ABS|LD_IND instructions:
9469  * - they can only appear in the programs where ctx == skb
9470  * - since they are wrappers of function calls, they scratch R1-R5 registers,
9471  *   preserve R6-R9, and store return value into R0
9472  *
9473  * Implicit input:
9474  *   ctx == skb == R6 == CTX
9475  *
9476  * Explicit input:
9477  *   SRC == any register
9478  *   IMM == 32-bit immediate
9479  *
9480  * Output:
9481  *   R0 - 8/16/32-bit skb data converted to cpu endianness
9482  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)9483 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9484 {
9485 	struct bpf_reg_state *regs = cur_regs(env);
9486 	static const int ctx_reg = BPF_REG_6;
9487 	u8 mode = BPF_MODE(insn->code);
9488 	int i, err;
9489 
9490 	if (!may_access_skb(resolve_prog_type(env->prog))) {
9491 		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9492 		return -EINVAL;
9493 	}
9494 
9495 	if (!env->ops->gen_ld_abs) {
9496 		verbose(env, "bpf verifier is misconfigured\n");
9497 		return -EINVAL;
9498 	}
9499 
9500 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9501 	    BPF_SIZE(insn->code) == BPF_DW ||
9502 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9503 		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9504 		return -EINVAL;
9505 	}
9506 
9507 	/* check whether implicit source operand (register R6) is readable */
9508 	err = check_reg_arg(env, ctx_reg, SRC_OP);
9509 	if (err)
9510 		return err;
9511 
9512 	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9513 	 * gen_ld_abs() may terminate the program at runtime, leading to
9514 	 * reference leak.
9515 	 */
9516 	err = check_reference_leak(env);
9517 	if (err) {
9518 		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9519 		return err;
9520 	}
9521 
9522 	if (env->cur_state->active_spin_lock) {
9523 		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9524 		return -EINVAL;
9525 	}
9526 
9527 	if (regs[ctx_reg].type != PTR_TO_CTX) {
9528 		verbose(env,
9529 			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9530 		return -EINVAL;
9531 	}
9532 
9533 	if (mode == BPF_IND) {
9534 		/* check explicit source operand */
9535 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
9536 		if (err)
9537 			return err;
9538 	}
9539 
9540 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9541 	if (err < 0)
9542 		return err;
9543 
9544 	/* reset caller saved regs to unreadable */
9545 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9546 		mark_reg_not_init(env, regs, caller_saved[i]);
9547 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9548 	}
9549 
9550 	/* mark destination R0 register as readable, since it contains
9551 	 * the value fetched from the packet.
9552 	 * Already marked as written above.
9553 	 */
9554 	mark_reg_unknown(env, regs, BPF_REG_0);
9555 	/* ld_abs load up to 32-bit skb data. */
9556 	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9557 	return 0;
9558 }
9559 
check_return_code(struct bpf_verifier_env * env)9560 static int check_return_code(struct bpf_verifier_env *env)
9561 {
9562 	struct tnum enforce_attach_type_range = tnum_unknown;
9563 	const struct bpf_prog *prog = env->prog;
9564 	struct bpf_reg_state *reg;
9565 	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
9566 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9567 	int err;
9568 	struct bpf_func_state *frame = env->cur_state->frame[0];
9569 	const bool is_subprog = frame->subprogno;
9570 
9571 	/* LSM and struct_ops func-ptr's return type could be "void" */
9572 	if (!is_subprog &&
9573 	    (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9574 	     prog_type == BPF_PROG_TYPE_LSM) &&
9575 	    !prog->aux->attach_func_proto->type)
9576 		return 0;
9577 
9578 	/* eBPF calling convention is such that R0 is used
9579 	 * to return the value from eBPF program.
9580 	 * Make sure that it's readable at this time
9581 	 * of bpf_exit, which means that program wrote
9582 	 * something into it earlier
9583 	 */
9584 	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9585 	if (err)
9586 		return err;
9587 
9588 	if (is_pointer_value(env, BPF_REG_0)) {
9589 		verbose(env, "R0 leaks addr as return value\n");
9590 		return -EACCES;
9591 	}
9592 
9593 	reg = cur_regs(env) + BPF_REG_0;
9594 
9595 	if (frame->in_async_callback_fn) {
9596 		/* enforce return zero from async callbacks like timer */
9597 		if (reg->type != SCALAR_VALUE) {
9598 			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9599 				reg_type_str(env, reg->type));
9600 			return -EINVAL;
9601 		}
9602 
9603 		if (!tnum_in(const_0, reg->var_off)) {
9604 			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
9605 			return -EINVAL;
9606 		}
9607 		return 0;
9608 	}
9609 
9610 	if (is_subprog) {
9611 		if (reg->type != SCALAR_VALUE) {
9612 			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9613 				reg_type_str(env, reg->type));
9614 			return -EINVAL;
9615 		}
9616 		return 0;
9617 	}
9618 
9619 	switch (prog_type) {
9620 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9621 		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9622 		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9623 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9624 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9625 		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9626 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9627 			range = tnum_range(1, 1);
9628 		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9629 		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9630 			range = tnum_range(0, 3);
9631 		break;
9632 	case BPF_PROG_TYPE_CGROUP_SKB:
9633 		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9634 			range = tnum_range(0, 3);
9635 			enforce_attach_type_range = tnum_range(2, 3);
9636 		}
9637 		break;
9638 	case BPF_PROG_TYPE_CGROUP_SOCK:
9639 	case BPF_PROG_TYPE_SOCK_OPS:
9640 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9641 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9642 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9643 		break;
9644 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9645 		if (!env->prog->aux->attach_btf_id)
9646 			return 0;
9647 		range = tnum_const(0);
9648 		break;
9649 	case BPF_PROG_TYPE_TRACING:
9650 		switch (env->prog->expected_attach_type) {
9651 		case BPF_TRACE_FENTRY:
9652 		case BPF_TRACE_FEXIT:
9653 			range = tnum_const(0);
9654 			break;
9655 		case BPF_TRACE_RAW_TP:
9656 		case BPF_MODIFY_RETURN:
9657 			return 0;
9658 		case BPF_TRACE_ITER:
9659 			break;
9660 		default:
9661 			return -ENOTSUPP;
9662 		}
9663 		break;
9664 	case BPF_PROG_TYPE_SK_LOOKUP:
9665 		range = tnum_range(SK_DROP, SK_PASS);
9666 		break;
9667 	case BPF_PROG_TYPE_EXT:
9668 		/* freplace program can return anything as its return value
9669 		 * depends on the to-be-replaced kernel func or bpf program.
9670 		 */
9671 	default:
9672 		return 0;
9673 	}
9674 
9675 	if (reg->type != SCALAR_VALUE) {
9676 		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9677 			reg_type_str(env, reg->type));
9678 		return -EINVAL;
9679 	}
9680 
9681 	if (!tnum_in(range, reg->var_off)) {
9682 		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9683 		return -EINVAL;
9684 	}
9685 
9686 	if (!tnum_is_unknown(enforce_attach_type_range) &&
9687 	    tnum_in(enforce_attach_type_range, reg->var_off))
9688 		env->prog->enforce_expected_attach_type = 1;
9689 	return 0;
9690 }
9691 
9692 /* non-recursive DFS pseudo code
9693  * 1  procedure DFS-iterative(G,v):
9694  * 2      label v as discovered
9695  * 3      let S be a stack
9696  * 4      S.push(v)
9697  * 5      while S is not empty
9698  * 6            t <- S.pop()
9699  * 7            if t is what we're looking for:
9700  * 8                return t
9701  * 9            for all edges e in G.adjacentEdges(t) do
9702  * 10               if edge e is already labelled
9703  * 11                   continue with the next edge
9704  * 12               w <- G.adjacentVertex(t,e)
9705  * 13               if vertex w is not discovered and not explored
9706  * 14                   label e as tree-edge
9707  * 15                   label w as discovered
9708  * 16                   S.push(w)
9709  * 17                   continue at 5
9710  * 18               else if vertex w is discovered
9711  * 19                   label e as back-edge
9712  * 20               else
9713  * 21                   // vertex w is explored
9714  * 22                   label e as forward- or cross-edge
9715  * 23           label t as explored
9716  * 24           S.pop()
9717  *
9718  * convention:
9719  * 0x10 - discovered
9720  * 0x11 - discovered and fall-through edge labelled
9721  * 0x12 - discovered and fall-through and branch edges labelled
9722  * 0x20 - explored
9723  */
9724 
9725 enum {
9726 	DISCOVERED = 0x10,
9727 	EXPLORED = 0x20,
9728 	FALLTHROUGH = 1,
9729 	BRANCH = 2,
9730 };
9731 
state_htab_size(struct bpf_verifier_env * env)9732 static u32 state_htab_size(struct bpf_verifier_env *env)
9733 {
9734 	return env->prog->len;
9735 }
9736 
explored_state(struct bpf_verifier_env * env,int idx)9737 static struct bpf_verifier_state_list **explored_state(
9738 					struct bpf_verifier_env *env,
9739 					int idx)
9740 {
9741 	struct bpf_verifier_state *cur = env->cur_state;
9742 	struct bpf_func_state *state = cur->frame[cur->curframe];
9743 
9744 	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9745 }
9746 
init_explored_state(struct bpf_verifier_env * env,int idx)9747 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9748 {
9749 	env->insn_aux_data[idx].prune_point = true;
9750 }
9751 
9752 enum {
9753 	DONE_EXPLORING = 0,
9754 	KEEP_EXPLORING = 1,
9755 };
9756 
9757 /* t, w, e - match pseudo-code above:
9758  * t - index of current instruction
9759  * w - next instruction
9760  * e - edge
9761  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)9762 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9763 		     bool loop_ok)
9764 {
9765 	int *insn_stack = env->cfg.insn_stack;
9766 	int *insn_state = env->cfg.insn_state;
9767 
9768 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9769 		return DONE_EXPLORING;
9770 
9771 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9772 		return DONE_EXPLORING;
9773 
9774 	if (w < 0 || w >= env->prog->len) {
9775 		verbose_linfo(env, t, "%d: ", t);
9776 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
9777 		return -EINVAL;
9778 	}
9779 
9780 	if (e == BRANCH)
9781 		/* mark branch target for state pruning */
9782 		init_explored_state(env, w);
9783 
9784 	if (insn_state[w] == 0) {
9785 		/* tree-edge */
9786 		insn_state[t] = DISCOVERED | e;
9787 		insn_state[w] = DISCOVERED;
9788 		if (env->cfg.cur_stack >= env->prog->len)
9789 			return -E2BIG;
9790 		insn_stack[env->cfg.cur_stack++] = w;
9791 		return KEEP_EXPLORING;
9792 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9793 		if (loop_ok && env->bpf_capable)
9794 			return DONE_EXPLORING;
9795 		verbose_linfo(env, t, "%d: ", t);
9796 		verbose_linfo(env, w, "%d: ", w);
9797 		verbose(env, "back-edge from insn %d to %d\n", t, w);
9798 		return -EINVAL;
9799 	} else if (insn_state[w] == EXPLORED) {
9800 		/* forward- or cross-edge */
9801 		insn_state[t] = DISCOVERED | e;
9802 	} else {
9803 		verbose(env, "insn state internal bug\n");
9804 		return -EFAULT;
9805 	}
9806 	return DONE_EXPLORING;
9807 }
9808 
visit_func_call_insn(int t,int insn_cnt,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)9809 static int visit_func_call_insn(int t, int insn_cnt,
9810 				struct bpf_insn *insns,
9811 				struct bpf_verifier_env *env,
9812 				bool visit_callee)
9813 {
9814 	int ret;
9815 
9816 	ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9817 	if (ret)
9818 		return ret;
9819 
9820 	if (t + 1 < insn_cnt)
9821 		init_explored_state(env, t + 1);
9822 	if (visit_callee) {
9823 		init_explored_state(env, t);
9824 		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9825 				/* It's ok to allow recursion from CFG point of
9826 				 * view. __check_func_call() will do the actual
9827 				 * check.
9828 				 */
9829 				bpf_pseudo_func(insns + t));
9830 	}
9831 	return ret;
9832 }
9833 
9834 /* Visits the instruction at index t and returns one of the following:
9835  *  < 0 - an error occurred
9836  *  DONE_EXPLORING - the instruction was fully explored
9837  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
9838  */
visit_insn(int t,int insn_cnt,struct bpf_verifier_env * env)9839 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9840 {
9841 	struct bpf_insn *insns = env->prog->insnsi;
9842 	int ret;
9843 
9844 	if (bpf_pseudo_func(insns + t))
9845 		return visit_func_call_insn(t, insn_cnt, insns, env, true);
9846 
9847 	/* All non-branch instructions have a single fall-through edge. */
9848 	if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9849 	    BPF_CLASS(insns[t].code) != BPF_JMP32)
9850 		return push_insn(t, t + 1, FALLTHROUGH, env, false);
9851 
9852 	switch (BPF_OP(insns[t].code)) {
9853 	case BPF_EXIT:
9854 		return DONE_EXPLORING;
9855 
9856 	case BPF_CALL:
9857 		if (insns[t].imm == BPF_FUNC_timer_set_callback)
9858 			/* Mark this call insn to trigger is_state_visited() check
9859 			 * before call itself is processed by __check_func_call().
9860 			 * Otherwise new async state will be pushed for further
9861 			 * exploration.
9862 			 */
9863 			init_explored_state(env, t);
9864 		return visit_func_call_insn(t, insn_cnt, insns, env,
9865 					    insns[t].src_reg == BPF_PSEUDO_CALL);
9866 
9867 	case BPF_JA:
9868 		if (BPF_SRC(insns[t].code) != BPF_K)
9869 			return -EINVAL;
9870 
9871 		/* unconditional jump with single edge */
9872 		ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9873 				true);
9874 		if (ret)
9875 			return ret;
9876 
9877 		/* unconditional jmp is not a good pruning point,
9878 		 * but it's marked, since backtracking needs
9879 		 * to record jmp history in is_state_visited().
9880 		 */
9881 		init_explored_state(env, t + insns[t].off + 1);
9882 		/* tell verifier to check for equivalent states
9883 		 * after every call and jump
9884 		 */
9885 		if (t + 1 < insn_cnt)
9886 			init_explored_state(env, t + 1);
9887 
9888 		return ret;
9889 
9890 	default:
9891 		/* conditional jump with two edges */
9892 		init_explored_state(env, t);
9893 		ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9894 		if (ret)
9895 			return ret;
9896 
9897 		return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9898 	}
9899 }
9900 
9901 /* non-recursive depth-first-search to detect loops in BPF program
9902  * loop == back-edge in directed graph
9903  */
check_cfg(struct bpf_verifier_env * env)9904 static int check_cfg(struct bpf_verifier_env *env)
9905 {
9906 	int insn_cnt = env->prog->len;
9907 	int *insn_stack, *insn_state;
9908 	int ret = 0;
9909 	int i;
9910 
9911 	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9912 	if (!insn_state)
9913 		return -ENOMEM;
9914 
9915 	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9916 	if (!insn_stack) {
9917 		kvfree(insn_state);
9918 		return -ENOMEM;
9919 	}
9920 
9921 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9922 	insn_stack[0] = 0; /* 0 is the first instruction */
9923 	env->cfg.cur_stack = 1;
9924 
9925 	while (env->cfg.cur_stack > 0) {
9926 		int t = insn_stack[env->cfg.cur_stack - 1];
9927 
9928 		ret = visit_insn(t, insn_cnt, env);
9929 		switch (ret) {
9930 		case DONE_EXPLORING:
9931 			insn_state[t] = EXPLORED;
9932 			env->cfg.cur_stack--;
9933 			break;
9934 		case KEEP_EXPLORING:
9935 			break;
9936 		default:
9937 			if (ret > 0) {
9938 				verbose(env, "visit_insn internal bug\n");
9939 				ret = -EFAULT;
9940 			}
9941 			goto err_free;
9942 		}
9943 	}
9944 
9945 	if (env->cfg.cur_stack < 0) {
9946 		verbose(env, "pop stack internal bug\n");
9947 		ret = -EFAULT;
9948 		goto err_free;
9949 	}
9950 
9951 	for (i = 0; i < insn_cnt; i++) {
9952 		if (insn_state[i] != EXPLORED) {
9953 			verbose(env, "unreachable insn %d\n", i);
9954 			ret = -EINVAL;
9955 			goto err_free;
9956 		}
9957 	}
9958 	ret = 0; /* cfg looks good */
9959 
9960 err_free:
9961 	kvfree(insn_state);
9962 	kvfree(insn_stack);
9963 	env->cfg.insn_state = env->cfg.insn_stack = NULL;
9964 	return ret;
9965 }
9966 
check_abnormal_return(struct bpf_verifier_env * env)9967 static int check_abnormal_return(struct bpf_verifier_env *env)
9968 {
9969 	int i;
9970 
9971 	for (i = 1; i < env->subprog_cnt; i++) {
9972 		if (env->subprog_info[i].has_ld_abs) {
9973 			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9974 			return -EINVAL;
9975 		}
9976 		if (env->subprog_info[i].has_tail_call) {
9977 			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9978 			return -EINVAL;
9979 		}
9980 	}
9981 	return 0;
9982 }
9983 
9984 /* The minimum supported BTF func info size */
9985 #define MIN_BPF_FUNCINFO_SIZE	8
9986 #define MAX_FUNCINFO_REC_SIZE	252
9987 
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)9988 static int check_btf_func(struct bpf_verifier_env *env,
9989 			  const union bpf_attr *attr,
9990 			  bpfptr_t uattr)
9991 {
9992 	const struct btf_type *type, *func_proto, *ret_type;
9993 	u32 i, nfuncs, urec_size, min_size;
9994 	u32 krec_size = sizeof(struct bpf_func_info);
9995 	struct bpf_func_info *krecord;
9996 	struct bpf_func_info_aux *info_aux = NULL;
9997 	struct bpf_prog *prog;
9998 	const struct btf *btf;
9999 	bpfptr_t urecord;
10000 	u32 prev_offset = 0;
10001 	bool scalar_return;
10002 	int ret = -ENOMEM;
10003 
10004 	nfuncs = attr->func_info_cnt;
10005 	if (!nfuncs) {
10006 		if (check_abnormal_return(env))
10007 			return -EINVAL;
10008 		return 0;
10009 	}
10010 
10011 	if (nfuncs != env->subprog_cnt) {
10012 		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10013 		return -EINVAL;
10014 	}
10015 
10016 	urec_size = attr->func_info_rec_size;
10017 	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10018 	    urec_size > MAX_FUNCINFO_REC_SIZE ||
10019 	    urec_size % sizeof(u32)) {
10020 		verbose(env, "invalid func info rec size %u\n", urec_size);
10021 		return -EINVAL;
10022 	}
10023 
10024 	prog = env->prog;
10025 	btf = prog->aux->btf;
10026 
10027 	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10028 	min_size = min_t(u32, krec_size, urec_size);
10029 
10030 	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10031 	if (!krecord)
10032 		return -ENOMEM;
10033 	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10034 	if (!info_aux)
10035 		goto err_free;
10036 
10037 	for (i = 0; i < nfuncs; i++) {
10038 		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10039 		if (ret) {
10040 			if (ret == -E2BIG) {
10041 				verbose(env, "nonzero tailing record in func info");
10042 				/* set the size kernel expects so loader can zero
10043 				 * out the rest of the record.
10044 				 */
10045 				if (copy_to_bpfptr_offset(uattr,
10046 							  offsetof(union bpf_attr, func_info_rec_size),
10047 							  &min_size, sizeof(min_size)))
10048 					ret = -EFAULT;
10049 			}
10050 			goto err_free;
10051 		}
10052 
10053 		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10054 			ret = -EFAULT;
10055 			goto err_free;
10056 		}
10057 
10058 		/* check insn_off */
10059 		ret = -EINVAL;
10060 		if (i == 0) {
10061 			if (krecord[i].insn_off) {
10062 				verbose(env,
10063 					"nonzero insn_off %u for the first func info record",
10064 					krecord[i].insn_off);
10065 				goto err_free;
10066 			}
10067 		} else if (krecord[i].insn_off <= prev_offset) {
10068 			verbose(env,
10069 				"same or smaller insn offset (%u) than previous func info record (%u)",
10070 				krecord[i].insn_off, prev_offset);
10071 			goto err_free;
10072 		}
10073 
10074 		if (env->subprog_info[i].start != krecord[i].insn_off) {
10075 			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10076 			goto err_free;
10077 		}
10078 
10079 		/* check type_id */
10080 		type = btf_type_by_id(btf, krecord[i].type_id);
10081 		if (!type || !btf_type_is_func(type)) {
10082 			verbose(env, "invalid type id %d in func info",
10083 				krecord[i].type_id);
10084 			goto err_free;
10085 		}
10086 		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10087 
10088 		func_proto = btf_type_by_id(btf, type->type);
10089 		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10090 			/* btf_func_check() already verified it during BTF load */
10091 			goto err_free;
10092 		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10093 		scalar_return =
10094 			btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10095 		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10096 			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10097 			goto err_free;
10098 		}
10099 		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10100 			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10101 			goto err_free;
10102 		}
10103 
10104 		prev_offset = krecord[i].insn_off;
10105 		bpfptr_add(&urecord, urec_size);
10106 	}
10107 
10108 	prog->aux->func_info = krecord;
10109 	prog->aux->func_info_cnt = nfuncs;
10110 	prog->aux->func_info_aux = info_aux;
10111 	return 0;
10112 
10113 err_free:
10114 	kvfree(krecord);
10115 	kfree(info_aux);
10116 	return ret;
10117 }
10118 
adjust_btf_func(struct bpf_verifier_env * env)10119 static void adjust_btf_func(struct bpf_verifier_env *env)
10120 {
10121 	struct bpf_prog_aux *aux = env->prog->aux;
10122 	int i;
10123 
10124 	if (!aux->func_info)
10125 		return;
10126 
10127 	for (i = 0; i < env->subprog_cnt; i++)
10128 		aux->func_info[i].insn_off = env->subprog_info[i].start;
10129 }
10130 
10131 #define MIN_BPF_LINEINFO_SIZE	(offsetof(struct bpf_line_info, line_col) + \
10132 		sizeof(((struct bpf_line_info *)(0))->line_col))
10133 #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
10134 
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)10135 static int check_btf_line(struct bpf_verifier_env *env,
10136 			  const union bpf_attr *attr,
10137 			  bpfptr_t uattr)
10138 {
10139 	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10140 	struct bpf_subprog_info *sub;
10141 	struct bpf_line_info *linfo;
10142 	struct bpf_prog *prog;
10143 	const struct btf *btf;
10144 	bpfptr_t ulinfo;
10145 	int err;
10146 
10147 	nr_linfo = attr->line_info_cnt;
10148 	if (!nr_linfo)
10149 		return 0;
10150 	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10151 		return -EINVAL;
10152 
10153 	rec_size = attr->line_info_rec_size;
10154 	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10155 	    rec_size > MAX_LINEINFO_REC_SIZE ||
10156 	    rec_size & (sizeof(u32) - 1))
10157 		return -EINVAL;
10158 
10159 	/* Need to zero it in case the userspace may
10160 	 * pass in a smaller bpf_line_info object.
10161 	 */
10162 	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10163 			 GFP_KERNEL | __GFP_NOWARN);
10164 	if (!linfo)
10165 		return -ENOMEM;
10166 
10167 	prog = env->prog;
10168 	btf = prog->aux->btf;
10169 
10170 	s = 0;
10171 	sub = env->subprog_info;
10172 	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
10173 	expected_size = sizeof(struct bpf_line_info);
10174 	ncopy = min_t(u32, expected_size, rec_size);
10175 	for (i = 0; i < nr_linfo; i++) {
10176 		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10177 		if (err) {
10178 			if (err == -E2BIG) {
10179 				verbose(env, "nonzero tailing record in line_info");
10180 				if (copy_to_bpfptr_offset(uattr,
10181 							  offsetof(union bpf_attr, line_info_rec_size),
10182 							  &expected_size, sizeof(expected_size)))
10183 					err = -EFAULT;
10184 			}
10185 			goto err_free;
10186 		}
10187 
10188 		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10189 			err = -EFAULT;
10190 			goto err_free;
10191 		}
10192 
10193 		/*
10194 		 * Check insn_off to ensure
10195 		 * 1) strictly increasing AND
10196 		 * 2) bounded by prog->len
10197 		 *
10198 		 * The linfo[0].insn_off == 0 check logically falls into
10199 		 * the later "missing bpf_line_info for func..." case
10200 		 * because the first linfo[0].insn_off must be the
10201 		 * first sub also and the first sub must have
10202 		 * subprog_info[0].start == 0.
10203 		 */
10204 		if ((i && linfo[i].insn_off <= prev_offset) ||
10205 		    linfo[i].insn_off >= prog->len) {
10206 			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10207 				i, linfo[i].insn_off, prev_offset,
10208 				prog->len);
10209 			err = -EINVAL;
10210 			goto err_free;
10211 		}
10212 
10213 		if (!prog->insnsi[linfo[i].insn_off].code) {
10214 			verbose(env,
10215 				"Invalid insn code at line_info[%u].insn_off\n",
10216 				i);
10217 			err = -EINVAL;
10218 			goto err_free;
10219 		}
10220 
10221 		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10222 		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10223 			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10224 			err = -EINVAL;
10225 			goto err_free;
10226 		}
10227 
10228 		if (s != env->subprog_cnt) {
10229 			if (linfo[i].insn_off == sub[s].start) {
10230 				sub[s].linfo_idx = i;
10231 				s++;
10232 			} else if (sub[s].start < linfo[i].insn_off) {
10233 				verbose(env, "missing bpf_line_info for func#%u\n", s);
10234 				err = -EINVAL;
10235 				goto err_free;
10236 			}
10237 		}
10238 
10239 		prev_offset = linfo[i].insn_off;
10240 		bpfptr_add(&ulinfo, rec_size);
10241 	}
10242 
10243 	if (s != env->subprog_cnt) {
10244 		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10245 			env->subprog_cnt - s, s);
10246 		err = -EINVAL;
10247 		goto err_free;
10248 	}
10249 
10250 	prog->aux->linfo = linfo;
10251 	prog->aux->nr_linfo = nr_linfo;
10252 
10253 	return 0;
10254 
10255 err_free:
10256 	kvfree(linfo);
10257 	return err;
10258 }
10259 
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)10260 static int check_btf_info(struct bpf_verifier_env *env,
10261 			  const union bpf_attr *attr,
10262 			  bpfptr_t uattr)
10263 {
10264 	struct btf *btf;
10265 	int err;
10266 
10267 	if (!attr->func_info_cnt && !attr->line_info_cnt) {
10268 		if (check_abnormal_return(env))
10269 			return -EINVAL;
10270 		return 0;
10271 	}
10272 
10273 	btf = btf_get_by_fd(attr->prog_btf_fd);
10274 	if (IS_ERR(btf))
10275 		return PTR_ERR(btf);
10276 	if (btf_is_kernel(btf)) {
10277 		btf_put(btf);
10278 		return -EACCES;
10279 	}
10280 	env->prog->aux->btf = btf;
10281 
10282 	err = check_btf_func(env, attr, uattr);
10283 	if (err)
10284 		return err;
10285 
10286 	err = check_btf_line(env, attr, uattr);
10287 	if (err)
10288 		return err;
10289 
10290 	return 0;
10291 }
10292 
10293 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)10294 static bool range_within(struct bpf_reg_state *old,
10295 			 struct bpf_reg_state *cur)
10296 {
10297 	return old->umin_value <= cur->umin_value &&
10298 	       old->umax_value >= cur->umax_value &&
10299 	       old->smin_value <= cur->smin_value &&
10300 	       old->smax_value >= cur->smax_value &&
10301 	       old->u32_min_value <= cur->u32_min_value &&
10302 	       old->u32_max_value >= cur->u32_max_value &&
10303 	       old->s32_min_value <= cur->s32_min_value &&
10304 	       old->s32_max_value >= cur->s32_max_value;
10305 }
10306 
10307 /* If in the old state two registers had the same id, then they need to have
10308  * the same id in the new state as well.  But that id could be different from
10309  * the old state, so we need to track the mapping from old to new ids.
10310  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10311  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
10312  * regs with a different old id could still have new id 9, we don't care about
10313  * that.
10314  * So we look through our idmap to see if this old id has been seen before.  If
10315  * so, we require the new id to match; otherwise, we add the id pair to the map.
10316  */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)10317 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10318 {
10319 	unsigned int i;
10320 
10321 	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10322 		if (!idmap[i].old) {
10323 			/* Reached an empty slot; haven't seen this id before */
10324 			idmap[i].old = old_id;
10325 			idmap[i].cur = cur_id;
10326 			return true;
10327 		}
10328 		if (idmap[i].old == old_id)
10329 			return idmap[i].cur == cur_id;
10330 	}
10331 	/* We ran out of idmap slots, which should be impossible */
10332 	WARN_ON_ONCE(1);
10333 	return false;
10334 }
10335 
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)10336 static void clean_func_state(struct bpf_verifier_env *env,
10337 			     struct bpf_func_state *st)
10338 {
10339 	enum bpf_reg_liveness live;
10340 	int i, j;
10341 
10342 	for (i = 0; i < BPF_REG_FP; i++) {
10343 		live = st->regs[i].live;
10344 		/* liveness must not touch this register anymore */
10345 		st->regs[i].live |= REG_LIVE_DONE;
10346 		if (!(live & REG_LIVE_READ))
10347 			/* since the register is unused, clear its state
10348 			 * to make further comparison simpler
10349 			 */
10350 			__mark_reg_not_init(env, &st->regs[i]);
10351 	}
10352 
10353 	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10354 		live = st->stack[i].spilled_ptr.live;
10355 		/* liveness must not touch this stack slot anymore */
10356 		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10357 		if (!(live & REG_LIVE_READ)) {
10358 			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10359 			for (j = 0; j < BPF_REG_SIZE; j++)
10360 				st->stack[i].slot_type[j] = STACK_INVALID;
10361 		}
10362 	}
10363 }
10364 
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)10365 static void clean_verifier_state(struct bpf_verifier_env *env,
10366 				 struct bpf_verifier_state *st)
10367 {
10368 	int i;
10369 
10370 	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10371 		/* all regs in this state in all frames were already marked */
10372 		return;
10373 
10374 	for (i = 0; i <= st->curframe; i++)
10375 		clean_func_state(env, st->frame[i]);
10376 }
10377 
10378 /* the parentage chains form a tree.
10379  * the verifier states are added to state lists at given insn and
10380  * pushed into state stack for future exploration.
10381  * when the verifier reaches bpf_exit insn some of the verifer states
10382  * stored in the state lists have their final liveness state already,
10383  * but a lot of states will get revised from liveness point of view when
10384  * the verifier explores other branches.
10385  * Example:
10386  * 1: r0 = 1
10387  * 2: if r1 == 100 goto pc+1
10388  * 3: r0 = 2
10389  * 4: exit
10390  * when the verifier reaches exit insn the register r0 in the state list of
10391  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10392  * of insn 2 and goes exploring further. At the insn 4 it will walk the
10393  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10394  *
10395  * Since the verifier pushes the branch states as it sees them while exploring
10396  * the program the condition of walking the branch instruction for the second
10397  * time means that all states below this branch were already explored and
10398  * their final liveness marks are already propagated.
10399  * Hence when the verifier completes the search of state list in is_state_visited()
10400  * we can call this clean_live_states() function to mark all liveness states
10401  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10402  * will not be used.
10403  * This function also clears the registers and stack for states that !READ
10404  * to simplify state merging.
10405  *
10406  * Important note here that walking the same branch instruction in the callee
10407  * doesn't meant that the states are DONE. The verifier has to compare
10408  * the callsites
10409  */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)10410 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10411 			      struct bpf_verifier_state *cur)
10412 {
10413 	struct bpf_verifier_state_list *sl;
10414 	int i;
10415 
10416 	sl = *explored_state(env, insn);
10417 	while (sl) {
10418 		if (sl->state.branches)
10419 			goto next;
10420 		if (sl->state.insn_idx != insn ||
10421 		    sl->state.curframe != cur->curframe)
10422 			goto next;
10423 		for (i = 0; i <= cur->curframe; i++)
10424 			if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10425 				goto next;
10426 		clean_verifier_state(env, &sl->state);
10427 next:
10428 		sl = sl->next;
10429 	}
10430 }
10431 
10432 /* 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)10433 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10434 		    struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10435 {
10436 	bool equal;
10437 
10438 	if (!(rold->live & REG_LIVE_READ))
10439 		/* explored state didn't use this */
10440 		return true;
10441 
10442 	equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10443 
10444 	if (rold->type == PTR_TO_STACK)
10445 		/* two stack pointers are equal only if they're pointing to
10446 		 * the same stack frame, since fp-8 in foo != fp-8 in bar
10447 		 */
10448 		return equal && rold->frameno == rcur->frameno;
10449 
10450 	if (equal)
10451 		return true;
10452 
10453 	if (rold->type == NOT_INIT)
10454 		/* explored state can't have used this */
10455 		return true;
10456 	if (rcur->type == NOT_INIT)
10457 		return false;
10458 	switch (base_type(rold->type)) {
10459 	case SCALAR_VALUE:
10460 		if (env->explore_alu_limits)
10461 			return false;
10462 		if (rcur->type == SCALAR_VALUE) {
10463 			if (!rold->precise)
10464 				return true;
10465 			/* new val must satisfy old val knowledge */
10466 			return range_within(rold, rcur) &&
10467 			       tnum_in(rold->var_off, rcur->var_off);
10468 		} else {
10469 			/* We're trying to use a pointer in place of a scalar.
10470 			 * Even if the scalar was unbounded, this could lead to
10471 			 * pointer leaks because scalars are allowed to leak
10472 			 * while pointers are not. We could make this safe in
10473 			 * special cases if root is calling us, but it's
10474 			 * probably not worth the hassle.
10475 			 */
10476 			return false;
10477 		}
10478 	case PTR_TO_MAP_KEY:
10479 	case PTR_TO_MAP_VALUE:
10480 		/* a PTR_TO_MAP_VALUE could be safe to use as a
10481 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10482 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10483 		 * checked, doing so could have affected others with the same
10484 		 * id, and we can't check for that because we lost the id when
10485 		 * we converted to a PTR_TO_MAP_VALUE.
10486 		 */
10487 		if (type_may_be_null(rold->type)) {
10488 			if (!type_may_be_null(rcur->type))
10489 				return false;
10490 			if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10491 				return false;
10492 			/* Check our ids match any regs they're supposed to */
10493 			return check_ids(rold->id, rcur->id, idmap);
10494 		}
10495 
10496 		/* If the new min/max/var_off satisfy the old ones and
10497 		 * everything else matches, we are OK.
10498 		 * 'id' is not compared, since it's only used for maps with
10499 		 * bpf_spin_lock inside map element and in such cases if
10500 		 * the rest of the prog is valid for one map element then
10501 		 * it's valid for all map elements regardless of the key
10502 		 * used in bpf_map_lookup()
10503 		 */
10504 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10505 		       range_within(rold, rcur) &&
10506 		       tnum_in(rold->var_off, rcur->var_off);
10507 	case PTR_TO_PACKET_META:
10508 	case PTR_TO_PACKET:
10509 		if (rcur->type != rold->type)
10510 			return false;
10511 		/* We must have at least as much range as the old ptr
10512 		 * did, so that any accesses which were safe before are
10513 		 * still safe.  This is true even if old range < old off,
10514 		 * since someone could have accessed through (ptr - k), or
10515 		 * even done ptr -= k in a register, to get a safe access.
10516 		 */
10517 		if (rold->range > rcur->range)
10518 			return false;
10519 		/* If the offsets don't match, we can't trust our alignment;
10520 		 * nor can we be sure that we won't fall out of range.
10521 		 */
10522 		if (rold->off != rcur->off)
10523 			return false;
10524 		/* id relations must be preserved */
10525 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10526 			return false;
10527 		/* new val must satisfy old val knowledge */
10528 		return range_within(rold, rcur) &&
10529 		       tnum_in(rold->var_off, rcur->var_off);
10530 	case PTR_TO_CTX:
10531 	case CONST_PTR_TO_MAP:
10532 	case PTR_TO_PACKET_END:
10533 	case PTR_TO_FLOW_KEYS:
10534 	case PTR_TO_SOCKET:
10535 	case PTR_TO_SOCK_COMMON:
10536 	case PTR_TO_TCP_SOCK:
10537 	case PTR_TO_XDP_SOCK:
10538 		/* Only valid matches are exact, which memcmp() above
10539 		 * would have accepted
10540 		 */
10541 	default:
10542 		/* Don't know what's going on, just say it's not safe */
10543 		return false;
10544 	}
10545 
10546 	/* Shouldn't get here; if we do, say it's not safe */
10547 	WARN_ON_ONCE(1);
10548 	return false;
10549 }
10550 
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)10551 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10552 		      struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10553 {
10554 	int i, spi;
10555 
10556 	/* walk slots of the explored stack and ignore any additional
10557 	 * slots in the current stack, since explored(safe) state
10558 	 * didn't use them
10559 	 */
10560 	for (i = 0; i < old->allocated_stack; i++) {
10561 		spi = i / BPF_REG_SIZE;
10562 
10563 		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10564 			i += BPF_REG_SIZE - 1;
10565 			/* explored state didn't use this */
10566 			continue;
10567 		}
10568 
10569 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10570 			continue;
10571 
10572 		/* explored stack has more populated slots than current stack
10573 		 * and these slots were used
10574 		 */
10575 		if (i >= cur->allocated_stack)
10576 			return false;
10577 
10578 		/* if old state was safe with misc data in the stack
10579 		 * it will be safe with zero-initialized stack.
10580 		 * The opposite is not true
10581 		 */
10582 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10583 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10584 			continue;
10585 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10586 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10587 			/* Ex: old explored (safe) state has STACK_SPILL in
10588 			 * this stack slot, but current has STACK_MISC ->
10589 			 * this verifier states are not equivalent,
10590 			 * return false to continue verification of this path
10591 			 */
10592 			return false;
10593 		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
10594 			continue;
10595 		if (!is_spilled_reg(&old->stack[spi]))
10596 			continue;
10597 		if (!regsafe(env, &old->stack[spi].spilled_ptr,
10598 			     &cur->stack[spi].spilled_ptr, idmap))
10599 			/* when explored and current stack slot are both storing
10600 			 * spilled registers, check that stored pointers types
10601 			 * are the same as well.
10602 			 * Ex: explored safe path could have stored
10603 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10604 			 * but current path has stored:
10605 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10606 			 * such verifier states are not equivalent.
10607 			 * return false to continue verification of this path
10608 			 */
10609 			return false;
10610 	}
10611 	return true;
10612 }
10613 
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)10614 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10615 {
10616 	if (old->acquired_refs != cur->acquired_refs)
10617 		return false;
10618 	return !memcmp(old->refs, cur->refs,
10619 		       sizeof(*old->refs) * old->acquired_refs);
10620 }
10621 
10622 /* compare two verifier states
10623  *
10624  * all states stored in state_list are known to be valid, since
10625  * verifier reached 'bpf_exit' instruction through them
10626  *
10627  * this function is called when verifier exploring different branches of
10628  * execution popped from the state stack. If it sees an old state that has
10629  * more strict register state and more strict stack state then this execution
10630  * branch doesn't need to be explored further, since verifier already
10631  * concluded that more strict state leads to valid finish.
10632  *
10633  * Therefore two states are equivalent if register state is more conservative
10634  * and explored stack state is more conservative than the current one.
10635  * Example:
10636  *       explored                   current
10637  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10638  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10639  *
10640  * In other words if current stack state (one being explored) has more
10641  * valid slots than old one that already passed validation, it means
10642  * the verifier can stop exploring and conclude that current state is valid too
10643  *
10644  * Similarly with registers. If explored state has register type as invalid
10645  * whereas register type in current state is meaningful, it means that
10646  * the current state will reach 'bpf_exit' instruction safely
10647  */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)10648 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10649 			      struct bpf_func_state *cur)
10650 {
10651 	int i;
10652 
10653 	memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10654 	for (i = 0; i < MAX_BPF_REG; i++)
10655 		if (!regsafe(env, &old->regs[i], &cur->regs[i],
10656 			     env->idmap_scratch))
10657 			return false;
10658 
10659 	if (!stacksafe(env, old, cur, env->idmap_scratch))
10660 		return false;
10661 
10662 	if (!refsafe(old, cur))
10663 		return false;
10664 
10665 	return true;
10666 }
10667 
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)10668 static bool states_equal(struct bpf_verifier_env *env,
10669 			 struct bpf_verifier_state *old,
10670 			 struct bpf_verifier_state *cur)
10671 {
10672 	int i;
10673 
10674 	if (old->curframe != cur->curframe)
10675 		return false;
10676 
10677 	/* Verification state from speculative execution simulation
10678 	 * must never prune a non-speculative execution one.
10679 	 */
10680 	if (old->speculative && !cur->speculative)
10681 		return false;
10682 
10683 	if (old->active_spin_lock != cur->active_spin_lock)
10684 		return false;
10685 
10686 	/* for states to be equal callsites have to be the same
10687 	 * and all frame states need to be equivalent
10688 	 */
10689 	for (i = 0; i <= old->curframe; i++) {
10690 		if (old->frame[i]->callsite != cur->frame[i]->callsite)
10691 			return false;
10692 		if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10693 			return false;
10694 	}
10695 	return true;
10696 }
10697 
10698 /* Return 0 if no propagation happened. Return negative error code if error
10699  * happened. Otherwise, return the propagated bit.
10700  */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)10701 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10702 				  struct bpf_reg_state *reg,
10703 				  struct bpf_reg_state *parent_reg)
10704 {
10705 	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10706 	u8 flag = reg->live & REG_LIVE_READ;
10707 	int err;
10708 
10709 	/* When comes here, read flags of PARENT_REG or REG could be any of
10710 	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10711 	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10712 	 */
10713 	if (parent_flag == REG_LIVE_READ64 ||
10714 	    /* Or if there is no read flag from REG. */
10715 	    !flag ||
10716 	    /* Or if the read flag from REG is the same as PARENT_REG. */
10717 	    parent_flag == flag)
10718 		return 0;
10719 
10720 	err = mark_reg_read(env, reg, parent_reg, flag);
10721 	if (err)
10722 		return err;
10723 
10724 	return flag;
10725 }
10726 
10727 /* A write screens off any subsequent reads; but write marks come from the
10728  * straight-line code between a state and its parent.  When we arrive at an
10729  * equivalent state (jump target or such) we didn't arrive by the straight-line
10730  * code, so read marks in the state must propagate to the parent regardless
10731  * of the state's write marks. That's what 'parent == state->parent' comparison
10732  * in mark_reg_read() is for.
10733  */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)10734 static int propagate_liveness(struct bpf_verifier_env *env,
10735 			      const struct bpf_verifier_state *vstate,
10736 			      struct bpf_verifier_state *vparent)
10737 {
10738 	struct bpf_reg_state *state_reg, *parent_reg;
10739 	struct bpf_func_state *state, *parent;
10740 	int i, frame, err = 0;
10741 
10742 	if (vparent->curframe != vstate->curframe) {
10743 		WARN(1, "propagate_live: parent frame %d current frame %d\n",
10744 		     vparent->curframe, vstate->curframe);
10745 		return -EFAULT;
10746 	}
10747 	/* Propagate read liveness of registers... */
10748 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10749 	for (frame = 0; frame <= vstate->curframe; frame++) {
10750 		parent = vparent->frame[frame];
10751 		state = vstate->frame[frame];
10752 		parent_reg = parent->regs;
10753 		state_reg = state->regs;
10754 		/* We don't need to worry about FP liveness, it's read-only */
10755 		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10756 			err = propagate_liveness_reg(env, &state_reg[i],
10757 						     &parent_reg[i]);
10758 			if (err < 0)
10759 				return err;
10760 			if (err == REG_LIVE_READ64)
10761 				mark_insn_zext(env, &parent_reg[i]);
10762 		}
10763 
10764 		/* Propagate stack slots. */
10765 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10766 			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10767 			parent_reg = &parent->stack[i].spilled_ptr;
10768 			state_reg = &state->stack[i].spilled_ptr;
10769 			err = propagate_liveness_reg(env, state_reg,
10770 						     parent_reg);
10771 			if (err < 0)
10772 				return err;
10773 		}
10774 	}
10775 	return 0;
10776 }
10777 
10778 /* find precise scalars in the previous equivalent state and
10779  * propagate them into the current state
10780  */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)10781 static int propagate_precision(struct bpf_verifier_env *env,
10782 			       const struct bpf_verifier_state *old)
10783 {
10784 	struct bpf_reg_state *state_reg;
10785 	struct bpf_func_state *state;
10786 	int i, err = 0, fr;
10787 
10788 	for (fr = old->curframe; fr >= 0; fr--) {
10789 		state = old->frame[fr];
10790 		state_reg = state->regs;
10791 		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10792 			if (state_reg->type != SCALAR_VALUE ||
10793 			    !state_reg->precise ||
10794 			    !(state_reg->live & REG_LIVE_READ))
10795 				continue;
10796 			if (env->log.level & BPF_LOG_LEVEL2)
10797 				verbose(env, "frame %d: propagating r%d\n", fr, i);
10798 			err = mark_chain_precision_frame(env, fr, i);
10799 			if (err < 0)
10800 				return err;
10801 		}
10802 
10803 		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10804 			if (!is_spilled_reg(&state->stack[i]))
10805 				continue;
10806 			state_reg = &state->stack[i].spilled_ptr;
10807 			if (state_reg->type != SCALAR_VALUE ||
10808 			    !state_reg->precise ||
10809 			    !(state_reg->live & REG_LIVE_READ))
10810 				continue;
10811 			if (env->log.level & BPF_LOG_LEVEL2)
10812 				verbose(env, "frame %d: propagating fp%d\n",
10813 					fr, (-i - 1) * BPF_REG_SIZE);
10814 			err = mark_chain_precision_stack_frame(env, fr, i);
10815 			if (err < 0)
10816 				return err;
10817 		}
10818 	}
10819 	return 0;
10820 }
10821 
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)10822 static bool states_maybe_looping(struct bpf_verifier_state *old,
10823 				 struct bpf_verifier_state *cur)
10824 {
10825 	struct bpf_func_state *fold, *fcur;
10826 	int i, fr = cur->curframe;
10827 
10828 	if (old->curframe != fr)
10829 		return false;
10830 
10831 	fold = old->frame[fr];
10832 	fcur = cur->frame[fr];
10833 	for (i = 0; i < MAX_BPF_REG; i++)
10834 		if (memcmp(&fold->regs[i], &fcur->regs[i],
10835 			   offsetof(struct bpf_reg_state, parent)))
10836 			return false;
10837 	return true;
10838 }
10839 
10840 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)10841 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10842 {
10843 	struct bpf_verifier_state_list *new_sl;
10844 	struct bpf_verifier_state_list *sl, **pprev;
10845 	struct bpf_verifier_state *cur = env->cur_state, *new;
10846 	int i, j, err, states_cnt = 0;
10847 	bool add_new_state = env->test_state_freq ? true : false;
10848 
10849 	cur->last_insn_idx = env->prev_insn_idx;
10850 	if (!env->insn_aux_data[insn_idx].prune_point)
10851 		/* this 'insn_idx' instruction wasn't marked, so we will not
10852 		 * be doing state search here
10853 		 */
10854 		return 0;
10855 
10856 	/* bpf progs typically have pruning point every 4 instructions
10857 	 * http://vger.kernel.org/bpfconf2019.html#session-1
10858 	 * Do not add new state for future pruning if the verifier hasn't seen
10859 	 * at least 2 jumps and at least 8 instructions.
10860 	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10861 	 * In tests that amounts to up to 50% reduction into total verifier
10862 	 * memory consumption and 20% verifier time speedup.
10863 	 */
10864 	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10865 	    env->insn_processed - env->prev_insn_processed >= 8)
10866 		add_new_state = true;
10867 
10868 	pprev = explored_state(env, insn_idx);
10869 	sl = *pprev;
10870 
10871 	clean_live_states(env, insn_idx, cur);
10872 
10873 	while (sl) {
10874 		states_cnt++;
10875 		if (sl->state.insn_idx != insn_idx)
10876 			goto next;
10877 
10878 		if (sl->state.branches) {
10879 			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10880 
10881 			if (frame->in_async_callback_fn &&
10882 			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10883 				/* Different async_entry_cnt means that the verifier is
10884 				 * processing another entry into async callback.
10885 				 * Seeing the same state is not an indication of infinite
10886 				 * loop or infinite recursion.
10887 				 * But finding the same state doesn't mean that it's safe
10888 				 * to stop processing the current state. The previous state
10889 				 * hasn't yet reached bpf_exit, since state.branches > 0.
10890 				 * Checking in_async_callback_fn alone is not enough either.
10891 				 * Since the verifier still needs to catch infinite loops
10892 				 * inside async callbacks.
10893 				 */
10894 			} else if (states_maybe_looping(&sl->state, cur) &&
10895 				   states_equal(env, &sl->state, cur)) {
10896 				verbose_linfo(env, insn_idx, "; ");
10897 				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10898 				return -EINVAL;
10899 			}
10900 			/* if the verifier is processing a loop, avoid adding new state
10901 			 * too often, since different loop iterations have distinct
10902 			 * states and may not help future pruning.
10903 			 * This threshold shouldn't be too low to make sure that
10904 			 * a loop with large bound will be rejected quickly.
10905 			 * The most abusive loop will be:
10906 			 * r1 += 1
10907 			 * if r1 < 1000000 goto pc-2
10908 			 * 1M insn_procssed limit / 100 == 10k peak states.
10909 			 * This threshold shouldn't be too high either, since states
10910 			 * at the end of the loop are likely to be useful in pruning.
10911 			 */
10912 			if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10913 			    env->insn_processed - env->prev_insn_processed < 100)
10914 				add_new_state = false;
10915 			goto miss;
10916 		}
10917 		if (states_equal(env, &sl->state, cur)) {
10918 			sl->hit_cnt++;
10919 			/* reached equivalent register/stack state,
10920 			 * prune the search.
10921 			 * Registers read by the continuation are read by us.
10922 			 * If we have any write marks in env->cur_state, they
10923 			 * will prevent corresponding reads in the continuation
10924 			 * from reaching our parent (an explored_state).  Our
10925 			 * own state will get the read marks recorded, but
10926 			 * they'll be immediately forgotten as we're pruning
10927 			 * this state and will pop a new one.
10928 			 */
10929 			err = propagate_liveness(env, &sl->state, cur);
10930 
10931 			/* if previous state reached the exit with precision and
10932 			 * current state is equivalent to it (except precsion marks)
10933 			 * the precision needs to be propagated back in
10934 			 * the current state.
10935 			 */
10936 			err = err ? : push_jmp_history(env, cur);
10937 			err = err ? : propagate_precision(env, &sl->state);
10938 			if (err)
10939 				return err;
10940 			return 1;
10941 		}
10942 miss:
10943 		/* when new state is not going to be added do not increase miss count.
10944 		 * Otherwise several loop iterations will remove the state
10945 		 * recorded earlier. The goal of these heuristics is to have
10946 		 * states from some iterations of the loop (some in the beginning
10947 		 * and some at the end) to help pruning.
10948 		 */
10949 		if (add_new_state)
10950 			sl->miss_cnt++;
10951 		/* heuristic to determine whether this state is beneficial
10952 		 * to keep checking from state equivalence point of view.
10953 		 * Higher numbers increase max_states_per_insn and verification time,
10954 		 * but do not meaningfully decrease insn_processed.
10955 		 */
10956 		if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10957 			/* the state is unlikely to be useful. Remove it to
10958 			 * speed up verification
10959 			 */
10960 			*pprev = sl->next;
10961 			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10962 				u32 br = sl->state.branches;
10963 
10964 				WARN_ONCE(br,
10965 					  "BUG live_done but branches_to_explore %d\n",
10966 					  br);
10967 				free_verifier_state(&sl->state, false);
10968 				kfree(sl);
10969 				env->peak_states--;
10970 			} else {
10971 				/* cannot free this state, since parentage chain may
10972 				 * walk it later. Add it for free_list instead to
10973 				 * be freed at the end of verification
10974 				 */
10975 				sl->next = env->free_list;
10976 				env->free_list = sl;
10977 			}
10978 			sl = *pprev;
10979 			continue;
10980 		}
10981 next:
10982 		pprev = &sl->next;
10983 		sl = *pprev;
10984 	}
10985 
10986 	if (env->max_states_per_insn < states_cnt)
10987 		env->max_states_per_insn = states_cnt;
10988 
10989 	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10990 		return push_jmp_history(env, cur);
10991 
10992 	if (!add_new_state)
10993 		return push_jmp_history(env, cur);
10994 
10995 	/* There were no equivalent states, remember the current one.
10996 	 * Technically the current state is not proven to be safe yet,
10997 	 * but it will either reach outer most bpf_exit (which means it's safe)
10998 	 * or it will be rejected. When there are no loops the verifier won't be
10999 	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11000 	 * again on the way to bpf_exit.
11001 	 * When looping the sl->state.branches will be > 0 and this state
11002 	 * will not be considered for equivalence until branches == 0.
11003 	 */
11004 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11005 	if (!new_sl)
11006 		return -ENOMEM;
11007 	env->total_states++;
11008 	env->peak_states++;
11009 	env->prev_jmps_processed = env->jmps_processed;
11010 	env->prev_insn_processed = env->insn_processed;
11011 
11012 	/* forget precise markings we inherited, see __mark_chain_precision */
11013 	if (env->bpf_capable)
11014 		mark_all_scalars_imprecise(env, cur);
11015 
11016 	/* add new state to the head of linked list */
11017 	new = &new_sl->state;
11018 	err = copy_verifier_state(new, cur);
11019 	if (err) {
11020 		free_verifier_state(new, false);
11021 		kfree(new_sl);
11022 		return err;
11023 	}
11024 	new->insn_idx = insn_idx;
11025 	WARN_ONCE(new->branches != 1,
11026 		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11027 
11028 	cur->parent = new;
11029 	cur->first_insn_idx = insn_idx;
11030 	clear_jmp_history(cur);
11031 	new_sl->next = *explored_state(env, insn_idx);
11032 	*explored_state(env, insn_idx) = new_sl;
11033 	/* connect new state to parentage chain. Current frame needs all
11034 	 * registers connected. Only r6 - r9 of the callers are alive (pushed
11035 	 * to the stack implicitly by JITs) so in callers' frames connect just
11036 	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11037 	 * the state of the call instruction (with WRITTEN set), and r0 comes
11038 	 * from callee with its full parentage chain, anyway.
11039 	 */
11040 	/* clear write marks in current state: the writes we did are not writes
11041 	 * our child did, so they don't screen off its reads from us.
11042 	 * (There are no read marks in current state, because reads always mark
11043 	 * their parent and current state never has children yet.  Only
11044 	 * explored_states can get read marks.)
11045 	 */
11046 	for (j = 0; j <= cur->curframe; j++) {
11047 		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11048 			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11049 		for (i = 0; i < BPF_REG_FP; i++)
11050 			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11051 	}
11052 
11053 	/* all stack frames are accessible from callee, clear them all */
11054 	for (j = 0; j <= cur->curframe; j++) {
11055 		struct bpf_func_state *frame = cur->frame[j];
11056 		struct bpf_func_state *newframe = new->frame[j];
11057 
11058 		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
11059 			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
11060 			frame->stack[i].spilled_ptr.parent =
11061 						&newframe->stack[i].spilled_ptr;
11062 		}
11063 	}
11064 	return 0;
11065 }
11066 
11067 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)11068 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11069 {
11070 	switch (base_type(type)) {
11071 	case PTR_TO_CTX:
11072 	case PTR_TO_SOCKET:
11073 	case PTR_TO_SOCK_COMMON:
11074 	case PTR_TO_TCP_SOCK:
11075 	case PTR_TO_XDP_SOCK:
11076 	case PTR_TO_BTF_ID:
11077 		return false;
11078 	default:
11079 		return true;
11080 	}
11081 }
11082 
11083 /* If an instruction was previously used with particular pointer types, then we
11084  * need to be careful to avoid cases such as the below, where it may be ok
11085  * for one branch accessing the pointer, but not ok for the other branch:
11086  *
11087  * R1 = sock_ptr
11088  * goto X;
11089  * ...
11090  * R1 = some_other_valid_ptr;
11091  * goto X;
11092  * ...
11093  * R2 = *(u32 *)(R1 + 0);
11094  */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)11095 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11096 {
11097 	return src != prev && (!reg_type_mismatch_ok(src) ||
11098 			       !reg_type_mismatch_ok(prev));
11099 }
11100 
do_check(struct bpf_verifier_env * env)11101 static int do_check(struct bpf_verifier_env *env)
11102 {
11103 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11104 	struct bpf_verifier_state *state = env->cur_state;
11105 	struct bpf_insn *insns = env->prog->insnsi;
11106 	struct bpf_reg_state *regs;
11107 	int insn_cnt = env->prog->len;
11108 	bool do_print_state = false;
11109 	int prev_insn_idx = -1;
11110 
11111 	for (;;) {
11112 		struct bpf_insn *insn;
11113 		u8 class;
11114 		int err;
11115 
11116 		env->prev_insn_idx = prev_insn_idx;
11117 		if (env->insn_idx >= insn_cnt) {
11118 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
11119 				env->insn_idx, insn_cnt);
11120 			return -EFAULT;
11121 		}
11122 
11123 		insn = &insns[env->insn_idx];
11124 		class = BPF_CLASS(insn->code);
11125 
11126 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
11127 			verbose(env,
11128 				"BPF program is too large. Processed %d insn\n",
11129 				env->insn_processed);
11130 			return -E2BIG;
11131 		}
11132 
11133 		err = is_state_visited(env, env->insn_idx);
11134 		if (err < 0)
11135 			return err;
11136 		if (err == 1) {
11137 			/* found equivalent state, can prune the search */
11138 			if (env->log.level & BPF_LOG_LEVEL) {
11139 				if (do_print_state)
11140 					verbose(env, "\nfrom %d to %d%s: safe\n",
11141 						env->prev_insn_idx, env->insn_idx,
11142 						env->cur_state->speculative ?
11143 						" (speculative execution)" : "");
11144 				else
11145 					verbose(env, "%d: safe\n", env->insn_idx);
11146 			}
11147 			goto process_bpf_exit;
11148 		}
11149 
11150 		if (signal_pending(current))
11151 			return -EAGAIN;
11152 
11153 		if (need_resched())
11154 			cond_resched();
11155 
11156 		if (env->log.level & BPF_LOG_LEVEL2 ||
11157 		    (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
11158 			if (env->log.level & BPF_LOG_LEVEL2)
11159 				verbose(env, "%d:", env->insn_idx);
11160 			else
11161 				verbose(env, "\nfrom %d to %d%s:",
11162 					env->prev_insn_idx, env->insn_idx,
11163 					env->cur_state->speculative ?
11164 					" (speculative execution)" : "");
11165 			print_verifier_state(env, state->frame[state->curframe]);
11166 			do_print_state = false;
11167 		}
11168 
11169 		if (env->log.level & BPF_LOG_LEVEL) {
11170 			const struct bpf_insn_cbs cbs = {
11171 				.cb_call	= disasm_kfunc_name,
11172 				.cb_print	= verbose,
11173 				.private_data	= env,
11174 			};
11175 
11176 			verbose_linfo(env, env->insn_idx, "; ");
11177 			verbose(env, "%d: ", env->insn_idx);
11178 			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
11179 		}
11180 
11181 		if (bpf_prog_is_dev_bound(env->prog->aux)) {
11182 			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11183 							   env->prev_insn_idx);
11184 			if (err)
11185 				return err;
11186 		}
11187 
11188 		regs = cur_regs(env);
11189 		sanitize_mark_insn_seen(env);
11190 		prev_insn_idx = env->insn_idx;
11191 
11192 		if (class == BPF_ALU || class == BPF_ALU64) {
11193 			err = check_alu_op(env, insn);
11194 			if (err)
11195 				return err;
11196 
11197 		} else if (class == BPF_LDX) {
11198 			enum bpf_reg_type *prev_src_type, src_reg_type;
11199 
11200 			/* check for reserved fields is already done */
11201 
11202 			/* check src operand */
11203 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11204 			if (err)
11205 				return err;
11206 
11207 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11208 			if (err)
11209 				return err;
11210 
11211 			src_reg_type = regs[insn->src_reg].type;
11212 
11213 			/* check that memory (src_reg + off) is readable,
11214 			 * the state of dst_reg will be updated by this func
11215 			 */
11216 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
11217 					       insn->off, BPF_SIZE(insn->code),
11218 					       BPF_READ, insn->dst_reg, false);
11219 			if (err)
11220 				return err;
11221 
11222 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11223 
11224 			if (*prev_src_type == NOT_INIT) {
11225 				/* saw a valid insn
11226 				 * dst_reg = *(u32 *)(src_reg + off)
11227 				 * save type to validate intersecting paths
11228 				 */
11229 				*prev_src_type = src_reg_type;
11230 
11231 			} else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11232 				/* ABuser program is trying to use the same insn
11233 				 * dst_reg = *(u32*) (src_reg + off)
11234 				 * with different pointer types:
11235 				 * src_reg == ctx in one branch and
11236 				 * src_reg == stack|map in some other branch.
11237 				 * Reject it.
11238 				 */
11239 				verbose(env, "same insn cannot be used with different pointers\n");
11240 				return -EINVAL;
11241 			}
11242 
11243 		} else if (class == BPF_STX) {
11244 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
11245 
11246 			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11247 				err = check_atomic(env, env->insn_idx, insn);
11248 				if (err)
11249 					return err;
11250 				env->insn_idx++;
11251 				continue;
11252 			}
11253 
11254 			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11255 				verbose(env, "BPF_STX uses reserved fields\n");
11256 				return -EINVAL;
11257 			}
11258 
11259 			/* check src1 operand */
11260 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
11261 			if (err)
11262 				return err;
11263 			/* check src2 operand */
11264 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11265 			if (err)
11266 				return err;
11267 
11268 			dst_reg_type = regs[insn->dst_reg].type;
11269 
11270 			/* check that memory (dst_reg + off) is writeable */
11271 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11272 					       insn->off, BPF_SIZE(insn->code),
11273 					       BPF_WRITE, insn->src_reg, false);
11274 			if (err)
11275 				return err;
11276 
11277 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11278 
11279 			if (*prev_dst_type == NOT_INIT) {
11280 				*prev_dst_type = dst_reg_type;
11281 			} else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11282 				verbose(env, "same insn cannot be used with different pointers\n");
11283 				return -EINVAL;
11284 			}
11285 
11286 		} else if (class == BPF_ST) {
11287 			if (BPF_MODE(insn->code) != BPF_MEM ||
11288 			    insn->src_reg != BPF_REG_0) {
11289 				verbose(env, "BPF_ST uses reserved fields\n");
11290 				return -EINVAL;
11291 			}
11292 			/* check src operand */
11293 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11294 			if (err)
11295 				return err;
11296 
11297 			if (is_ctx_reg(env, insn->dst_reg)) {
11298 				verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11299 					insn->dst_reg,
11300 					reg_type_str(env, reg_state(env, insn->dst_reg)->type));
11301 				return -EACCES;
11302 			}
11303 
11304 			/* check that memory (dst_reg + off) is writeable */
11305 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11306 					       insn->off, BPF_SIZE(insn->code),
11307 					       BPF_WRITE, -1, false);
11308 			if (err)
11309 				return err;
11310 
11311 		} else if (class == BPF_JMP || class == BPF_JMP32) {
11312 			u8 opcode = BPF_OP(insn->code);
11313 
11314 			env->jmps_processed++;
11315 			if (opcode == BPF_CALL) {
11316 				if (BPF_SRC(insn->code) != BPF_K ||
11317 				    insn->off != 0 ||
11318 				    (insn->src_reg != BPF_REG_0 &&
11319 				     insn->src_reg != BPF_PSEUDO_CALL &&
11320 				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11321 				    insn->dst_reg != BPF_REG_0 ||
11322 				    class == BPF_JMP32) {
11323 					verbose(env, "BPF_CALL uses reserved fields\n");
11324 					return -EINVAL;
11325 				}
11326 
11327 				if (env->cur_state->active_spin_lock &&
11328 				    (insn->src_reg == BPF_PSEUDO_CALL ||
11329 				     insn->imm != BPF_FUNC_spin_unlock)) {
11330 					verbose(env, "function calls are not allowed while holding a lock\n");
11331 					return -EINVAL;
11332 				}
11333 				if (insn->src_reg == BPF_PSEUDO_CALL)
11334 					err = check_func_call(env, insn, &env->insn_idx);
11335 				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11336 					err = check_kfunc_call(env, insn);
11337 				else
11338 					err = check_helper_call(env, insn, &env->insn_idx);
11339 				if (err)
11340 					return err;
11341 			} else if (opcode == BPF_JA) {
11342 				if (BPF_SRC(insn->code) != BPF_K ||
11343 				    insn->imm != 0 ||
11344 				    insn->src_reg != BPF_REG_0 ||
11345 				    insn->dst_reg != BPF_REG_0 ||
11346 				    class == BPF_JMP32) {
11347 					verbose(env, "BPF_JA uses reserved fields\n");
11348 					return -EINVAL;
11349 				}
11350 
11351 				env->insn_idx += insn->off + 1;
11352 				continue;
11353 
11354 			} else if (opcode == BPF_EXIT) {
11355 				if (BPF_SRC(insn->code) != BPF_K ||
11356 				    insn->imm != 0 ||
11357 				    insn->src_reg != BPF_REG_0 ||
11358 				    insn->dst_reg != BPF_REG_0 ||
11359 				    class == BPF_JMP32) {
11360 					verbose(env, "BPF_EXIT uses reserved fields\n");
11361 					return -EINVAL;
11362 				}
11363 
11364 				if (env->cur_state->active_spin_lock) {
11365 					verbose(env, "bpf_spin_unlock is missing\n");
11366 					return -EINVAL;
11367 				}
11368 
11369 				if (state->curframe) {
11370 					/* exit from nested function */
11371 					err = prepare_func_exit(env, &env->insn_idx);
11372 					if (err)
11373 						return err;
11374 					do_print_state = true;
11375 					continue;
11376 				}
11377 
11378 				err = check_reference_leak(env);
11379 				if (err)
11380 					return err;
11381 
11382 				err = check_return_code(env);
11383 				if (err)
11384 					return err;
11385 process_bpf_exit:
11386 				update_branch_counts(env, env->cur_state);
11387 				err = pop_stack(env, &prev_insn_idx,
11388 						&env->insn_idx, pop_log);
11389 				if (err < 0) {
11390 					if (err != -ENOENT)
11391 						return err;
11392 					break;
11393 				} else {
11394 					do_print_state = true;
11395 					continue;
11396 				}
11397 			} else {
11398 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
11399 				if (err)
11400 					return err;
11401 			}
11402 		} else if (class == BPF_LD) {
11403 			u8 mode = BPF_MODE(insn->code);
11404 
11405 			if (mode == BPF_ABS || mode == BPF_IND) {
11406 				err = check_ld_abs(env, insn);
11407 				if (err)
11408 					return err;
11409 
11410 			} else if (mode == BPF_IMM) {
11411 				err = check_ld_imm(env, insn);
11412 				if (err)
11413 					return err;
11414 
11415 				env->insn_idx++;
11416 				sanitize_mark_insn_seen(env);
11417 			} else {
11418 				verbose(env, "invalid BPF_LD mode\n");
11419 				return -EINVAL;
11420 			}
11421 		} else {
11422 			verbose(env, "unknown insn class %d\n", class);
11423 			return -EINVAL;
11424 		}
11425 
11426 		env->insn_idx++;
11427 	}
11428 
11429 	return 0;
11430 }
11431 
find_btf_percpu_datasec(struct btf * btf)11432 static int find_btf_percpu_datasec(struct btf *btf)
11433 {
11434 	const struct btf_type *t;
11435 	const char *tname;
11436 	int i, n;
11437 
11438 	/*
11439 	 * Both vmlinux and module each have their own ".data..percpu"
11440 	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11441 	 * types to look at only module's own BTF types.
11442 	 */
11443 	n = btf_nr_types(btf);
11444 	if (btf_is_module(btf))
11445 		i = btf_nr_types(btf_vmlinux);
11446 	else
11447 		i = 1;
11448 
11449 	for(; i < n; i++) {
11450 		t = btf_type_by_id(btf, i);
11451 		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11452 			continue;
11453 
11454 		tname = btf_name_by_offset(btf, t->name_off);
11455 		if (!strcmp(tname, ".data..percpu"))
11456 			return i;
11457 	}
11458 
11459 	return -ENOENT;
11460 }
11461 
11462 /* 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)11463 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11464 			       struct bpf_insn *insn,
11465 			       struct bpf_insn_aux_data *aux)
11466 {
11467 	const struct btf_var_secinfo *vsi;
11468 	const struct btf_type *datasec;
11469 	struct btf_mod_pair *btf_mod;
11470 	const struct btf_type *t;
11471 	const char *sym_name;
11472 	bool percpu = false;
11473 	u32 type, id = insn->imm;
11474 	struct btf *btf;
11475 	s32 datasec_id;
11476 	u64 addr;
11477 	int i, btf_fd, err;
11478 
11479 	btf_fd = insn[1].imm;
11480 	if (btf_fd) {
11481 		btf = btf_get_by_fd(btf_fd);
11482 		if (IS_ERR(btf)) {
11483 			verbose(env, "invalid module BTF object FD specified.\n");
11484 			return -EINVAL;
11485 		}
11486 	} else {
11487 		if (!btf_vmlinux) {
11488 			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11489 			return -EINVAL;
11490 		}
11491 		btf = btf_vmlinux;
11492 		btf_get(btf);
11493 	}
11494 
11495 	t = btf_type_by_id(btf, id);
11496 	if (!t) {
11497 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11498 		err = -ENOENT;
11499 		goto err_put;
11500 	}
11501 
11502 	if (!btf_type_is_var(t)) {
11503 		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11504 		err = -EINVAL;
11505 		goto err_put;
11506 	}
11507 
11508 	sym_name = btf_name_by_offset(btf, t->name_off);
11509 	addr = kallsyms_lookup_name(sym_name);
11510 	if (!addr) {
11511 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11512 			sym_name);
11513 		err = -ENOENT;
11514 		goto err_put;
11515 	}
11516 
11517 	datasec_id = find_btf_percpu_datasec(btf);
11518 	if (datasec_id > 0) {
11519 		datasec = btf_type_by_id(btf, datasec_id);
11520 		for_each_vsi(i, datasec, vsi) {
11521 			if (vsi->type == id) {
11522 				percpu = true;
11523 				break;
11524 			}
11525 		}
11526 	}
11527 
11528 	insn[0].imm = (u32)addr;
11529 	insn[1].imm = addr >> 32;
11530 
11531 	type = t->type;
11532 	t = btf_type_skip_modifiers(btf, type, NULL);
11533 	if (percpu) {
11534 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11535 		aux->btf_var.btf = btf;
11536 		aux->btf_var.btf_id = type;
11537 	} else if (!btf_type_is_struct(t)) {
11538 		const struct btf_type *ret;
11539 		const char *tname;
11540 		u32 tsize;
11541 
11542 		/* resolve the type size of ksym. */
11543 		ret = btf_resolve_size(btf, t, &tsize);
11544 		if (IS_ERR(ret)) {
11545 			tname = btf_name_by_offset(btf, t->name_off);
11546 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11547 				tname, PTR_ERR(ret));
11548 			err = -EINVAL;
11549 			goto err_put;
11550 		}
11551 		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
11552 		aux->btf_var.mem_size = tsize;
11553 	} else {
11554 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
11555 		aux->btf_var.btf = btf;
11556 		aux->btf_var.btf_id = type;
11557 	}
11558 
11559 	/* check whether we recorded this BTF (and maybe module) already */
11560 	for (i = 0; i < env->used_btf_cnt; i++) {
11561 		if (env->used_btfs[i].btf == btf) {
11562 			btf_put(btf);
11563 			return 0;
11564 		}
11565 	}
11566 
11567 	if (env->used_btf_cnt >= MAX_USED_BTFS) {
11568 		err = -E2BIG;
11569 		goto err_put;
11570 	}
11571 
11572 	btf_mod = &env->used_btfs[env->used_btf_cnt];
11573 	btf_mod->btf = btf;
11574 	btf_mod->module = NULL;
11575 
11576 	/* if we reference variables from kernel module, bump its refcount */
11577 	if (btf_is_module(btf)) {
11578 		btf_mod->module = btf_try_get_module(btf);
11579 		if (!btf_mod->module) {
11580 			err = -ENXIO;
11581 			goto err_put;
11582 		}
11583 	}
11584 
11585 	env->used_btf_cnt++;
11586 
11587 	return 0;
11588 err_put:
11589 	btf_put(btf);
11590 	return err;
11591 }
11592 
check_map_prealloc(struct bpf_map * map)11593 static int check_map_prealloc(struct bpf_map *map)
11594 {
11595 	return (map->map_type != BPF_MAP_TYPE_HASH &&
11596 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11597 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11598 		!(map->map_flags & BPF_F_NO_PREALLOC);
11599 }
11600 
is_tracing_prog_type(enum bpf_prog_type type)11601 static bool is_tracing_prog_type(enum bpf_prog_type type)
11602 {
11603 	switch (type) {
11604 	case BPF_PROG_TYPE_KPROBE:
11605 	case BPF_PROG_TYPE_TRACEPOINT:
11606 	case BPF_PROG_TYPE_PERF_EVENT:
11607 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
11608 		return true;
11609 	default:
11610 		return false;
11611 	}
11612 }
11613 
is_preallocated_map(struct bpf_map * map)11614 static bool is_preallocated_map(struct bpf_map *map)
11615 {
11616 	if (!check_map_prealloc(map))
11617 		return false;
11618 	if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11619 		return false;
11620 	return true;
11621 }
11622 
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)11623 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11624 					struct bpf_map *map,
11625 					struct bpf_prog *prog)
11626 
11627 {
11628 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
11629 	/*
11630 	 * Validate that trace type programs use preallocated hash maps.
11631 	 *
11632 	 * For programs attached to PERF events this is mandatory as the
11633 	 * perf NMI can hit any arbitrary code sequence.
11634 	 *
11635 	 * All other trace types using preallocated hash maps are unsafe as
11636 	 * well because tracepoint or kprobes can be inside locked regions
11637 	 * of the memory allocator or at a place where a recursion into the
11638 	 * memory allocator would see inconsistent state.
11639 	 *
11640 	 * On RT enabled kernels run-time allocation of all trace type
11641 	 * programs is strictly prohibited due to lock type constraints. On
11642 	 * !RT kernels it is allowed for backwards compatibility reasons for
11643 	 * now, but warnings are emitted so developers are made aware of
11644 	 * the unsafety and can fix their programs before this is enforced.
11645 	 */
11646 	if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11647 		if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11648 			verbose(env, "perf_event programs can only use preallocated hash map\n");
11649 			return -EINVAL;
11650 		}
11651 		if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11652 			verbose(env, "trace type programs can only use preallocated hash map\n");
11653 			return -EINVAL;
11654 		}
11655 		WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11656 		verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11657 	}
11658 
11659 	if (map_value_has_spin_lock(map)) {
11660 		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11661 			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11662 			return -EINVAL;
11663 		}
11664 
11665 		if (is_tracing_prog_type(prog_type)) {
11666 			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11667 			return -EINVAL;
11668 		}
11669 
11670 		if (prog->aux->sleepable) {
11671 			verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11672 			return -EINVAL;
11673 		}
11674 	}
11675 
11676 	if (map_value_has_timer(map)) {
11677 		if (is_tracing_prog_type(prog_type)) {
11678 			verbose(env, "tracing progs cannot use bpf_timer yet\n");
11679 			return -EINVAL;
11680 		}
11681 	}
11682 
11683 	if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11684 	    !bpf_offload_prog_map_match(prog, map)) {
11685 		verbose(env, "offload device mismatch between prog and map\n");
11686 		return -EINVAL;
11687 	}
11688 
11689 	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11690 		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11691 		return -EINVAL;
11692 	}
11693 
11694 	if (prog->aux->sleepable)
11695 		switch (map->map_type) {
11696 		case BPF_MAP_TYPE_HASH:
11697 		case BPF_MAP_TYPE_LRU_HASH:
11698 		case BPF_MAP_TYPE_ARRAY:
11699 		case BPF_MAP_TYPE_PERCPU_HASH:
11700 		case BPF_MAP_TYPE_PERCPU_ARRAY:
11701 		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11702 		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11703 		case BPF_MAP_TYPE_HASH_OF_MAPS:
11704 			if (!is_preallocated_map(map)) {
11705 				verbose(env,
11706 					"Sleepable programs can only use preallocated maps\n");
11707 				return -EINVAL;
11708 			}
11709 			break;
11710 		case BPF_MAP_TYPE_RINGBUF:
11711 			break;
11712 		default:
11713 			verbose(env,
11714 				"Sleepable programs can only use array, hash, and ringbuf maps\n");
11715 			return -EINVAL;
11716 		}
11717 
11718 	return 0;
11719 }
11720 
bpf_map_is_cgroup_storage(struct bpf_map * map)11721 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11722 {
11723 	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11724 		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11725 }
11726 
11727 /* find and rewrite pseudo imm in ld_imm64 instructions:
11728  *
11729  * 1. if it accesses map FD, replace it with actual map pointer.
11730  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11731  *
11732  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11733  */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)11734 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11735 {
11736 	struct bpf_insn *insn = env->prog->insnsi;
11737 	int insn_cnt = env->prog->len;
11738 	int i, j, err;
11739 
11740 	err = bpf_prog_calc_tag(env->prog);
11741 	if (err)
11742 		return err;
11743 
11744 	for (i = 0; i < insn_cnt; i++, insn++) {
11745 		if (BPF_CLASS(insn->code) == BPF_LDX &&
11746 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11747 			verbose(env, "BPF_LDX uses reserved fields\n");
11748 			return -EINVAL;
11749 		}
11750 
11751 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11752 			struct bpf_insn_aux_data *aux;
11753 			struct bpf_map *map;
11754 			struct fd f;
11755 			u64 addr;
11756 			u32 fd;
11757 
11758 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
11759 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11760 			    insn[1].off != 0) {
11761 				verbose(env, "invalid bpf_ld_imm64 insn\n");
11762 				return -EINVAL;
11763 			}
11764 
11765 			if (insn[0].src_reg == 0)
11766 				/* valid generic load 64-bit imm */
11767 				goto next_insn;
11768 
11769 			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11770 				aux = &env->insn_aux_data[i];
11771 				err = check_pseudo_btf_id(env, insn, aux);
11772 				if (err)
11773 					return err;
11774 				goto next_insn;
11775 			}
11776 
11777 			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11778 				aux = &env->insn_aux_data[i];
11779 				aux->ptr_type = PTR_TO_FUNC;
11780 				goto next_insn;
11781 			}
11782 
11783 			/* In final convert_pseudo_ld_imm64() step, this is
11784 			 * converted into regular 64-bit imm load insn.
11785 			 */
11786 			switch (insn[0].src_reg) {
11787 			case BPF_PSEUDO_MAP_VALUE:
11788 			case BPF_PSEUDO_MAP_IDX_VALUE:
11789 				break;
11790 			case BPF_PSEUDO_MAP_FD:
11791 			case BPF_PSEUDO_MAP_IDX:
11792 				if (insn[1].imm == 0)
11793 					break;
11794 				fallthrough;
11795 			default:
11796 				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11797 				return -EINVAL;
11798 			}
11799 
11800 			switch (insn[0].src_reg) {
11801 			case BPF_PSEUDO_MAP_IDX_VALUE:
11802 			case BPF_PSEUDO_MAP_IDX:
11803 				if (bpfptr_is_null(env->fd_array)) {
11804 					verbose(env, "fd_idx without fd_array is invalid\n");
11805 					return -EPROTO;
11806 				}
11807 				if (copy_from_bpfptr_offset(&fd, env->fd_array,
11808 							    insn[0].imm * sizeof(fd),
11809 							    sizeof(fd)))
11810 					return -EFAULT;
11811 				break;
11812 			default:
11813 				fd = insn[0].imm;
11814 				break;
11815 			}
11816 
11817 			f = fdget(fd);
11818 			map = __bpf_map_get(f);
11819 			if (IS_ERR(map)) {
11820 				verbose(env, "fd %d is not pointing to valid bpf_map\n",
11821 					insn[0].imm);
11822 				return PTR_ERR(map);
11823 			}
11824 
11825 			err = check_map_prog_compatibility(env, map, env->prog);
11826 			if (err) {
11827 				fdput(f);
11828 				return err;
11829 			}
11830 
11831 			aux = &env->insn_aux_data[i];
11832 			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11833 			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11834 				addr = (unsigned long)map;
11835 			} else {
11836 				u32 off = insn[1].imm;
11837 
11838 				if (off >= BPF_MAX_VAR_OFF) {
11839 					verbose(env, "direct value offset of %u is not allowed\n", off);
11840 					fdput(f);
11841 					return -EINVAL;
11842 				}
11843 
11844 				if (!map->ops->map_direct_value_addr) {
11845 					verbose(env, "no direct value access support for this map type\n");
11846 					fdput(f);
11847 					return -EINVAL;
11848 				}
11849 
11850 				err = map->ops->map_direct_value_addr(map, &addr, off);
11851 				if (err) {
11852 					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11853 						map->value_size, off);
11854 					fdput(f);
11855 					return err;
11856 				}
11857 
11858 				aux->map_off = off;
11859 				addr += off;
11860 			}
11861 
11862 			insn[0].imm = (u32)addr;
11863 			insn[1].imm = addr >> 32;
11864 
11865 			/* check whether we recorded this map already */
11866 			for (j = 0; j < env->used_map_cnt; j++) {
11867 				if (env->used_maps[j] == map) {
11868 					aux->map_index = j;
11869 					fdput(f);
11870 					goto next_insn;
11871 				}
11872 			}
11873 
11874 			if (env->used_map_cnt >= MAX_USED_MAPS) {
11875 				fdput(f);
11876 				return -E2BIG;
11877 			}
11878 
11879 			/* hold the map. If the program is rejected by verifier,
11880 			 * the map will be released by release_maps() or it
11881 			 * will be used by the valid program until it's unloaded
11882 			 * and all maps are released in free_used_maps()
11883 			 */
11884 			bpf_map_inc(map);
11885 
11886 			aux->map_index = env->used_map_cnt;
11887 			env->used_maps[env->used_map_cnt++] = map;
11888 
11889 			if (bpf_map_is_cgroup_storage(map) &&
11890 			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
11891 				verbose(env, "only one cgroup storage of each type is allowed\n");
11892 				fdput(f);
11893 				return -EBUSY;
11894 			}
11895 
11896 			fdput(f);
11897 next_insn:
11898 			insn++;
11899 			i++;
11900 			continue;
11901 		}
11902 
11903 		/* Basic sanity check before we invest more work here. */
11904 		if (!bpf_opcode_in_insntable(insn->code)) {
11905 			verbose(env, "unknown opcode %02x\n", insn->code);
11906 			return -EINVAL;
11907 		}
11908 	}
11909 
11910 	/* now all pseudo BPF_LD_IMM64 instructions load valid
11911 	 * 'struct bpf_map *' into a register instead of user map_fd.
11912 	 * These pointers will be used later by verifier to validate map access.
11913 	 */
11914 	return 0;
11915 }
11916 
11917 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)11918 static void release_maps(struct bpf_verifier_env *env)
11919 {
11920 	__bpf_free_used_maps(env->prog->aux, env->used_maps,
11921 			     env->used_map_cnt);
11922 }
11923 
11924 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)11925 static void release_btfs(struct bpf_verifier_env *env)
11926 {
11927 	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11928 			     env->used_btf_cnt);
11929 }
11930 
11931 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)11932 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11933 {
11934 	struct bpf_insn *insn = env->prog->insnsi;
11935 	int insn_cnt = env->prog->len;
11936 	int i;
11937 
11938 	for (i = 0; i < insn_cnt; i++, insn++) {
11939 		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11940 			continue;
11941 		if (insn->src_reg == BPF_PSEUDO_FUNC)
11942 			continue;
11943 		insn->src_reg = 0;
11944 	}
11945 }
11946 
11947 /* single env->prog->insni[off] instruction was replaced with the range
11948  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
11949  * [0, off) and [off, end) to new locations, so the patched range stays zero
11950  */
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)11951 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11952 				 struct bpf_insn_aux_data *new_data,
11953 				 struct bpf_prog *new_prog, u32 off, u32 cnt)
11954 {
11955 	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11956 	struct bpf_insn *insn = new_prog->insnsi;
11957 	u32 old_seen = old_data[off].seen;
11958 	u32 prog_len;
11959 	int i;
11960 
11961 	/* aux info at OFF always needs adjustment, no matter fast path
11962 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11963 	 * original insn at old prog.
11964 	 */
11965 	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11966 
11967 	if (cnt == 1)
11968 		return;
11969 	prog_len = new_prog->len;
11970 
11971 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11972 	memcpy(new_data + off + cnt - 1, old_data + off,
11973 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11974 	for (i = off; i < off + cnt - 1; i++) {
11975 		/* Expand insni[off]'s seen count to the patched range. */
11976 		new_data[i].seen = old_seen;
11977 		new_data[i].zext_dst = insn_has_def32(env, insn + i);
11978 	}
11979 	env->insn_aux_data = new_data;
11980 	vfree(old_data);
11981 }
11982 
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)11983 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11984 {
11985 	int i;
11986 
11987 	if (len == 1)
11988 		return;
11989 	/* NOTE: fake 'exit' subprog should be updated as well. */
11990 	for (i = 0; i <= env->subprog_cnt; i++) {
11991 		if (env->subprog_info[i].start <= off)
11992 			continue;
11993 		env->subprog_info[i].start += len - 1;
11994 	}
11995 }
11996 
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)11997 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11998 {
11999 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12000 	int i, sz = prog->aux->size_poke_tab;
12001 	struct bpf_jit_poke_descriptor *desc;
12002 
12003 	for (i = 0; i < sz; i++) {
12004 		desc = &tab[i];
12005 		if (desc->insn_idx <= off)
12006 			continue;
12007 		desc->insn_idx += len - 1;
12008 	}
12009 }
12010 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)12011 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12012 					    const struct bpf_insn *patch, u32 len)
12013 {
12014 	struct bpf_prog *new_prog;
12015 	struct bpf_insn_aux_data *new_data = NULL;
12016 
12017 	if (len > 1) {
12018 		new_data = vzalloc(array_size(env->prog->len + len - 1,
12019 					      sizeof(struct bpf_insn_aux_data)));
12020 		if (!new_data)
12021 			return NULL;
12022 	}
12023 
12024 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12025 	if (IS_ERR(new_prog)) {
12026 		if (PTR_ERR(new_prog) == -ERANGE)
12027 			verbose(env,
12028 				"insn %d cannot be patched due to 16-bit range\n",
12029 				env->insn_aux_data[off].orig_idx);
12030 		vfree(new_data);
12031 		return NULL;
12032 	}
12033 	adjust_insn_aux_data(env, new_data, new_prog, off, len);
12034 	adjust_subprog_starts(env, off, len);
12035 	adjust_poke_descs(new_prog, off, len);
12036 	return new_prog;
12037 }
12038 
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)12039 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12040 					      u32 off, u32 cnt)
12041 {
12042 	int i, j;
12043 
12044 	/* find first prog starting at or after off (first to remove) */
12045 	for (i = 0; i < env->subprog_cnt; i++)
12046 		if (env->subprog_info[i].start >= off)
12047 			break;
12048 	/* find first prog starting at or after off + cnt (first to stay) */
12049 	for (j = i; j < env->subprog_cnt; j++)
12050 		if (env->subprog_info[j].start >= off + cnt)
12051 			break;
12052 	/* if j doesn't start exactly at off + cnt, we are just removing
12053 	 * the front of previous prog
12054 	 */
12055 	if (env->subprog_info[j].start != off + cnt)
12056 		j--;
12057 
12058 	if (j > i) {
12059 		struct bpf_prog_aux *aux = env->prog->aux;
12060 		int move;
12061 
12062 		/* move fake 'exit' subprog as well */
12063 		move = env->subprog_cnt + 1 - j;
12064 
12065 		memmove(env->subprog_info + i,
12066 			env->subprog_info + j,
12067 			sizeof(*env->subprog_info) * move);
12068 		env->subprog_cnt -= j - i;
12069 
12070 		/* remove func_info */
12071 		if (aux->func_info) {
12072 			move = aux->func_info_cnt - j;
12073 
12074 			memmove(aux->func_info + i,
12075 				aux->func_info + j,
12076 				sizeof(*aux->func_info) * move);
12077 			aux->func_info_cnt -= j - i;
12078 			/* func_info->insn_off is set after all code rewrites,
12079 			 * in adjust_btf_func() - no need to adjust
12080 			 */
12081 		}
12082 	} else {
12083 		/* convert i from "first prog to remove" to "first to adjust" */
12084 		if (env->subprog_info[i].start == off)
12085 			i++;
12086 	}
12087 
12088 	/* update fake 'exit' subprog as well */
12089 	for (; i <= env->subprog_cnt; i++)
12090 		env->subprog_info[i].start -= cnt;
12091 
12092 	return 0;
12093 }
12094 
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)12095 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12096 				      u32 cnt)
12097 {
12098 	struct bpf_prog *prog = env->prog;
12099 	u32 i, l_off, l_cnt, nr_linfo;
12100 	struct bpf_line_info *linfo;
12101 
12102 	nr_linfo = prog->aux->nr_linfo;
12103 	if (!nr_linfo)
12104 		return 0;
12105 
12106 	linfo = prog->aux->linfo;
12107 
12108 	/* find first line info to remove, count lines to be removed */
12109 	for (i = 0; i < nr_linfo; i++)
12110 		if (linfo[i].insn_off >= off)
12111 			break;
12112 
12113 	l_off = i;
12114 	l_cnt = 0;
12115 	for (; i < nr_linfo; i++)
12116 		if (linfo[i].insn_off < off + cnt)
12117 			l_cnt++;
12118 		else
12119 			break;
12120 
12121 	/* First live insn doesn't match first live linfo, it needs to "inherit"
12122 	 * last removed linfo.  prog is already modified, so prog->len == off
12123 	 * means no live instructions after (tail of the program was removed).
12124 	 */
12125 	if (prog->len != off && l_cnt &&
12126 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12127 		l_cnt--;
12128 		linfo[--i].insn_off = off + cnt;
12129 	}
12130 
12131 	/* remove the line info which refer to the removed instructions */
12132 	if (l_cnt) {
12133 		memmove(linfo + l_off, linfo + i,
12134 			sizeof(*linfo) * (nr_linfo - i));
12135 
12136 		prog->aux->nr_linfo -= l_cnt;
12137 		nr_linfo = prog->aux->nr_linfo;
12138 	}
12139 
12140 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
12141 	for (i = l_off; i < nr_linfo; i++)
12142 		linfo[i].insn_off -= cnt;
12143 
12144 	/* fix up all subprogs (incl. 'exit') which start >= off */
12145 	for (i = 0; i <= env->subprog_cnt; i++)
12146 		if (env->subprog_info[i].linfo_idx > l_off) {
12147 			/* program may have started in the removed region but
12148 			 * may not be fully removed
12149 			 */
12150 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12151 				env->subprog_info[i].linfo_idx -= l_cnt;
12152 			else
12153 				env->subprog_info[i].linfo_idx = l_off;
12154 		}
12155 
12156 	return 0;
12157 }
12158 
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)12159 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12160 {
12161 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12162 	unsigned int orig_prog_len = env->prog->len;
12163 	int err;
12164 
12165 	if (bpf_prog_is_dev_bound(env->prog->aux))
12166 		bpf_prog_offload_remove_insns(env, off, cnt);
12167 
12168 	err = bpf_remove_insns(env->prog, off, cnt);
12169 	if (err)
12170 		return err;
12171 
12172 	err = adjust_subprog_starts_after_remove(env, off, cnt);
12173 	if (err)
12174 		return err;
12175 
12176 	err = bpf_adj_linfo_after_remove(env, off, cnt);
12177 	if (err)
12178 		return err;
12179 
12180 	memmove(aux_data + off,	aux_data + off + cnt,
12181 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
12182 
12183 	return 0;
12184 }
12185 
12186 /* The verifier does more data flow analysis than llvm and will not
12187  * explore branches that are dead at run time. Malicious programs can
12188  * have dead code too. Therefore replace all dead at-run-time code
12189  * with 'ja -1'.
12190  *
12191  * Just nops are not optimal, e.g. if they would sit at the end of the
12192  * program and through another bug we would manage to jump there, then
12193  * we'd execute beyond program memory otherwise. Returning exception
12194  * code also wouldn't work since we can have subprogs where the dead
12195  * code could be located.
12196  */
sanitize_dead_code(struct bpf_verifier_env * env)12197 static void sanitize_dead_code(struct bpf_verifier_env *env)
12198 {
12199 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12200 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12201 	struct bpf_insn *insn = env->prog->insnsi;
12202 	const int insn_cnt = env->prog->len;
12203 	int i;
12204 
12205 	for (i = 0; i < insn_cnt; i++) {
12206 		if (aux_data[i].seen)
12207 			continue;
12208 		memcpy(insn + i, &trap, sizeof(trap));
12209 		aux_data[i].zext_dst = false;
12210 	}
12211 }
12212 
insn_is_cond_jump(u8 code)12213 static bool insn_is_cond_jump(u8 code)
12214 {
12215 	u8 op;
12216 
12217 	if (BPF_CLASS(code) == BPF_JMP32)
12218 		return true;
12219 
12220 	if (BPF_CLASS(code) != BPF_JMP)
12221 		return false;
12222 
12223 	op = BPF_OP(code);
12224 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12225 }
12226 
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)12227 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12228 {
12229 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12230 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12231 	struct bpf_insn *insn = env->prog->insnsi;
12232 	const int insn_cnt = env->prog->len;
12233 	int i;
12234 
12235 	for (i = 0; i < insn_cnt; i++, insn++) {
12236 		if (!insn_is_cond_jump(insn->code))
12237 			continue;
12238 
12239 		if (!aux_data[i + 1].seen)
12240 			ja.off = insn->off;
12241 		else if (!aux_data[i + 1 + insn->off].seen)
12242 			ja.off = 0;
12243 		else
12244 			continue;
12245 
12246 		if (bpf_prog_is_dev_bound(env->prog->aux))
12247 			bpf_prog_offload_replace_insn(env, i, &ja);
12248 
12249 		memcpy(insn, &ja, sizeof(ja));
12250 	}
12251 }
12252 
opt_remove_dead_code(struct bpf_verifier_env * env)12253 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12254 {
12255 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12256 	int insn_cnt = env->prog->len;
12257 	int i, err;
12258 
12259 	for (i = 0; i < insn_cnt; i++) {
12260 		int j;
12261 
12262 		j = 0;
12263 		while (i + j < insn_cnt && !aux_data[i + j].seen)
12264 			j++;
12265 		if (!j)
12266 			continue;
12267 
12268 		err = verifier_remove_insns(env, i, j);
12269 		if (err)
12270 			return err;
12271 		insn_cnt = env->prog->len;
12272 	}
12273 
12274 	return 0;
12275 }
12276 
opt_remove_nops(struct bpf_verifier_env * env)12277 static int opt_remove_nops(struct bpf_verifier_env *env)
12278 {
12279 	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12280 	struct bpf_insn *insn = env->prog->insnsi;
12281 	int insn_cnt = env->prog->len;
12282 	int i, err;
12283 
12284 	for (i = 0; i < insn_cnt; i++) {
12285 		if (memcmp(&insn[i], &ja, sizeof(ja)))
12286 			continue;
12287 
12288 		err = verifier_remove_insns(env, i, 1);
12289 		if (err)
12290 			return err;
12291 		insn_cnt--;
12292 		i--;
12293 	}
12294 
12295 	return 0;
12296 }
12297 
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)12298 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12299 					 const union bpf_attr *attr)
12300 {
12301 	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12302 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
12303 	int i, patch_len, delta = 0, len = env->prog->len;
12304 	struct bpf_insn *insns = env->prog->insnsi;
12305 	struct bpf_prog *new_prog;
12306 	bool rnd_hi32;
12307 
12308 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12309 	zext_patch[1] = BPF_ZEXT_REG(0);
12310 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12311 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12312 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12313 	for (i = 0; i < len; i++) {
12314 		int adj_idx = i + delta;
12315 		struct bpf_insn insn;
12316 		int load_reg;
12317 
12318 		insn = insns[adj_idx];
12319 		load_reg = insn_def_regno(&insn);
12320 		if (!aux[adj_idx].zext_dst) {
12321 			u8 code, class;
12322 			u32 imm_rnd;
12323 
12324 			if (!rnd_hi32)
12325 				continue;
12326 
12327 			code = insn.code;
12328 			class = BPF_CLASS(code);
12329 			if (load_reg == -1)
12330 				continue;
12331 
12332 			/* NOTE: arg "reg" (the fourth one) is only used for
12333 			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
12334 			 *       here.
12335 			 */
12336 			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12337 				if (class == BPF_LD &&
12338 				    BPF_MODE(code) == BPF_IMM)
12339 					i++;
12340 				continue;
12341 			}
12342 
12343 			/* ctx load could be transformed into wider load. */
12344 			if (class == BPF_LDX &&
12345 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
12346 				continue;
12347 
12348 			imm_rnd = get_random_int();
12349 			rnd_hi32_patch[0] = insn;
12350 			rnd_hi32_patch[1].imm = imm_rnd;
12351 			rnd_hi32_patch[3].dst_reg = load_reg;
12352 			patch = rnd_hi32_patch;
12353 			patch_len = 4;
12354 			goto apply_patch_buffer;
12355 		}
12356 
12357 		/* Add in an zero-extend instruction if a) the JIT has requested
12358 		 * it or b) it's a CMPXCHG.
12359 		 *
12360 		 * The latter is because: BPF_CMPXCHG always loads a value into
12361 		 * R0, therefore always zero-extends. However some archs'
12362 		 * equivalent instruction only does this load when the
12363 		 * comparison is successful. This detail of CMPXCHG is
12364 		 * orthogonal to the general zero-extension behaviour of the
12365 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
12366 		 */
12367 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12368 			continue;
12369 
12370 		/* Zero-extension is done by the caller. */
12371 		if (bpf_pseudo_kfunc_call(&insn))
12372 			continue;
12373 
12374 		if (WARN_ON(load_reg == -1)) {
12375 			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12376 			return -EFAULT;
12377 		}
12378 
12379 		zext_patch[0] = insn;
12380 		zext_patch[1].dst_reg = load_reg;
12381 		zext_patch[1].src_reg = load_reg;
12382 		patch = zext_patch;
12383 		patch_len = 2;
12384 apply_patch_buffer:
12385 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12386 		if (!new_prog)
12387 			return -ENOMEM;
12388 		env->prog = new_prog;
12389 		insns = new_prog->insnsi;
12390 		aux = env->insn_aux_data;
12391 		delta += patch_len - 1;
12392 	}
12393 
12394 	return 0;
12395 }
12396 
12397 /* convert load instructions that access fields of a context type into a
12398  * sequence of instructions that access fields of the underlying structure:
12399  *     struct __sk_buff    -> struct sk_buff
12400  *     struct bpf_sock_ops -> struct sock
12401  */
convert_ctx_accesses(struct bpf_verifier_env * env)12402 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12403 {
12404 	const struct bpf_verifier_ops *ops = env->ops;
12405 	int i, cnt, size, ctx_field_size, delta = 0;
12406 	const int insn_cnt = env->prog->len;
12407 	struct bpf_insn insn_buf[16], *insn;
12408 	u32 target_size, size_default, off;
12409 	struct bpf_prog *new_prog;
12410 	enum bpf_access_type type;
12411 	bool is_narrower_load;
12412 
12413 	if (ops->gen_prologue || env->seen_direct_write) {
12414 		if (!ops->gen_prologue) {
12415 			verbose(env, "bpf verifier is misconfigured\n");
12416 			return -EINVAL;
12417 		}
12418 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12419 					env->prog);
12420 		if (cnt >= ARRAY_SIZE(insn_buf)) {
12421 			verbose(env, "bpf verifier is misconfigured\n");
12422 			return -EINVAL;
12423 		} else if (cnt) {
12424 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12425 			if (!new_prog)
12426 				return -ENOMEM;
12427 
12428 			env->prog = new_prog;
12429 			delta += cnt - 1;
12430 		}
12431 	}
12432 
12433 	if (bpf_prog_is_dev_bound(env->prog->aux))
12434 		return 0;
12435 
12436 	insn = env->prog->insnsi + delta;
12437 
12438 	for (i = 0; i < insn_cnt; i++, insn++) {
12439 		bpf_convert_ctx_access_t convert_ctx_access;
12440 		bool ctx_access;
12441 
12442 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12443 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12444 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12445 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12446 			type = BPF_READ;
12447 			ctx_access = true;
12448 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12449 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12450 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12451 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12452 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12453 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12454 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12455 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12456 			type = BPF_WRITE;
12457 			ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12458 		} else {
12459 			continue;
12460 		}
12461 
12462 		if (type == BPF_WRITE &&
12463 		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
12464 			struct bpf_insn patch[] = {
12465 				*insn,
12466 				BPF_ST_NOSPEC(),
12467 			};
12468 
12469 			cnt = ARRAY_SIZE(patch);
12470 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12471 			if (!new_prog)
12472 				return -ENOMEM;
12473 
12474 			delta    += cnt - 1;
12475 			env->prog = new_prog;
12476 			insn      = new_prog->insnsi + i + delta;
12477 			continue;
12478 		}
12479 
12480 		if (!ctx_access)
12481 			continue;
12482 
12483 		switch (env->insn_aux_data[i + delta].ptr_type) {
12484 		case PTR_TO_CTX:
12485 			if (!ops->convert_ctx_access)
12486 				continue;
12487 			convert_ctx_access = ops->convert_ctx_access;
12488 			break;
12489 		case PTR_TO_SOCKET:
12490 		case PTR_TO_SOCK_COMMON:
12491 			convert_ctx_access = bpf_sock_convert_ctx_access;
12492 			break;
12493 		case PTR_TO_TCP_SOCK:
12494 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12495 			break;
12496 		case PTR_TO_XDP_SOCK:
12497 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12498 			break;
12499 		case PTR_TO_BTF_ID:
12500 			if (type == BPF_READ) {
12501 				insn->code = BPF_LDX | BPF_PROBE_MEM |
12502 					BPF_SIZE((insn)->code);
12503 				env->prog->aux->num_exentries++;
12504 			} else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12505 				verbose(env, "Writes through BTF pointers are not allowed\n");
12506 				return -EINVAL;
12507 			}
12508 			continue;
12509 		default:
12510 			continue;
12511 		}
12512 
12513 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12514 		size = BPF_LDST_BYTES(insn);
12515 
12516 		/* If the read access is a narrower load of the field,
12517 		 * convert to a 4/8-byte load, to minimum program type specific
12518 		 * convert_ctx_access changes. If conversion is successful,
12519 		 * we will apply proper mask to the result.
12520 		 */
12521 		is_narrower_load = size < ctx_field_size;
12522 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12523 		off = insn->off;
12524 		if (is_narrower_load) {
12525 			u8 size_code;
12526 
12527 			if (type == BPF_WRITE) {
12528 				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12529 				return -EINVAL;
12530 			}
12531 
12532 			size_code = BPF_H;
12533 			if (ctx_field_size == 4)
12534 				size_code = BPF_W;
12535 			else if (ctx_field_size == 8)
12536 				size_code = BPF_DW;
12537 
12538 			insn->off = off & ~(size_default - 1);
12539 			insn->code = BPF_LDX | BPF_MEM | size_code;
12540 		}
12541 
12542 		target_size = 0;
12543 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12544 					 &target_size);
12545 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12546 		    (ctx_field_size && !target_size)) {
12547 			verbose(env, "bpf verifier is misconfigured\n");
12548 			return -EINVAL;
12549 		}
12550 
12551 		if (is_narrower_load && size < target_size) {
12552 			u8 shift = bpf_ctx_narrow_access_offset(
12553 				off, size, size_default) * 8;
12554 			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12555 				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12556 				return -EINVAL;
12557 			}
12558 			if (ctx_field_size <= 4) {
12559 				if (shift)
12560 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12561 									insn->dst_reg,
12562 									shift);
12563 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12564 								(1 << size * 8) - 1);
12565 			} else {
12566 				if (shift)
12567 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12568 									insn->dst_reg,
12569 									shift);
12570 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12571 								(1ULL << size * 8) - 1);
12572 			}
12573 		}
12574 
12575 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12576 		if (!new_prog)
12577 			return -ENOMEM;
12578 
12579 		delta += cnt - 1;
12580 
12581 		/* keep walking new program and skip insns we just inserted */
12582 		env->prog = new_prog;
12583 		insn      = new_prog->insnsi + i + delta;
12584 	}
12585 
12586 	return 0;
12587 }
12588 
jit_subprogs(struct bpf_verifier_env * env)12589 static int jit_subprogs(struct bpf_verifier_env *env)
12590 {
12591 	struct bpf_prog *prog = env->prog, **func, *tmp;
12592 	int i, j, subprog_start, subprog_end = 0, len, subprog;
12593 	struct bpf_map *map_ptr;
12594 	struct bpf_insn *insn;
12595 	void *old_bpf_func;
12596 	int err, num_exentries;
12597 
12598 	if (env->subprog_cnt <= 1)
12599 		return 0;
12600 
12601 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12602 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
12603 			continue;
12604 
12605 		/* Upon error here we cannot fall back to interpreter but
12606 		 * need a hard reject of the program. Thus -EFAULT is
12607 		 * propagated in any case.
12608 		 */
12609 		subprog = find_subprog(env, i + insn->imm + 1);
12610 		if (subprog < 0) {
12611 			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12612 				  i + insn->imm + 1);
12613 			return -EFAULT;
12614 		}
12615 		/* temporarily remember subprog id inside insn instead of
12616 		 * aux_data, since next loop will split up all insns into funcs
12617 		 */
12618 		insn->off = subprog;
12619 		/* remember original imm in case JIT fails and fallback
12620 		 * to interpreter will be needed
12621 		 */
12622 		env->insn_aux_data[i].call_imm = insn->imm;
12623 		/* point imm to __bpf_call_base+1 from JITs point of view */
12624 		insn->imm = 1;
12625 		if (bpf_pseudo_func(insn))
12626 			/* jit (e.g. x86_64) may emit fewer instructions
12627 			 * if it learns a u32 imm is the same as a u64 imm.
12628 			 * Force a non zero here.
12629 			 */
12630 			insn[1].imm = 1;
12631 	}
12632 
12633 	err = bpf_prog_alloc_jited_linfo(prog);
12634 	if (err)
12635 		goto out_undo_insn;
12636 
12637 	err = -ENOMEM;
12638 	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12639 	if (!func)
12640 		goto out_undo_insn;
12641 
12642 	for (i = 0; i < env->subprog_cnt; i++) {
12643 		subprog_start = subprog_end;
12644 		subprog_end = env->subprog_info[i + 1].start;
12645 
12646 		len = subprog_end - subprog_start;
12647 		/* bpf_prog_run() doesn't call subprogs directly,
12648 		 * hence main prog stats include the runtime of subprogs.
12649 		 * subprogs don't have IDs and not reachable via prog_get_next_id
12650 		 * func[i]->stats will never be accessed and stays NULL
12651 		 */
12652 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12653 		if (!func[i])
12654 			goto out_free;
12655 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12656 		       len * sizeof(struct bpf_insn));
12657 		func[i]->type = prog->type;
12658 		func[i]->len = len;
12659 		if (bpf_prog_calc_tag(func[i]))
12660 			goto out_free;
12661 		func[i]->is_func = 1;
12662 		func[i]->aux->func_idx = i;
12663 		/* Below members will be freed only at prog->aux */
12664 		func[i]->aux->btf = prog->aux->btf;
12665 		func[i]->aux->func_info = prog->aux->func_info;
12666 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
12667 		func[i]->aux->poke_tab = prog->aux->poke_tab;
12668 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12669 
12670 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
12671 			struct bpf_jit_poke_descriptor *poke;
12672 
12673 			poke = &prog->aux->poke_tab[j];
12674 			if (poke->insn_idx < subprog_end &&
12675 			    poke->insn_idx >= subprog_start)
12676 				poke->aux = func[i]->aux;
12677 		}
12678 
12679 		func[i]->aux->name[0] = 'F';
12680 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12681 		func[i]->jit_requested = 1;
12682 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12683 		func[i]->aux->linfo = prog->aux->linfo;
12684 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12685 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12686 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12687 		num_exentries = 0;
12688 		insn = func[i]->insnsi;
12689 		for (j = 0; j < func[i]->len; j++, insn++) {
12690 			if (BPF_CLASS(insn->code) == BPF_LDX &&
12691 			    BPF_MODE(insn->code) == BPF_PROBE_MEM)
12692 				num_exentries++;
12693 		}
12694 		func[i]->aux->num_exentries = num_exentries;
12695 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12696 		func[i] = bpf_int_jit_compile(func[i]);
12697 		if (!func[i]->jited) {
12698 			err = -ENOTSUPP;
12699 			goto out_free;
12700 		}
12701 		cond_resched();
12702 	}
12703 
12704 	/* at this point all bpf functions were successfully JITed
12705 	 * now populate all bpf_calls with correct addresses and
12706 	 * run last pass of JIT
12707 	 */
12708 	for (i = 0; i < env->subprog_cnt; i++) {
12709 		insn = func[i]->insnsi;
12710 		for (j = 0; j < func[i]->len; j++, insn++) {
12711 			if (bpf_pseudo_func(insn)) {
12712 				subprog = insn->off;
12713 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12714 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12715 				continue;
12716 			}
12717 			if (!bpf_pseudo_call(insn))
12718 				continue;
12719 			subprog = insn->off;
12720 			insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12721 				    __bpf_call_base;
12722 		}
12723 
12724 		/* we use the aux data to keep a list of the start addresses
12725 		 * of the JITed images for each function in the program
12726 		 *
12727 		 * for some architectures, such as powerpc64, the imm field
12728 		 * might not be large enough to hold the offset of the start
12729 		 * address of the callee's JITed image from __bpf_call_base
12730 		 *
12731 		 * in such cases, we can lookup the start address of a callee
12732 		 * by using its subprog id, available from the off field of
12733 		 * the call instruction, as an index for this list
12734 		 */
12735 		func[i]->aux->func = func;
12736 		func[i]->aux->func_cnt = env->subprog_cnt;
12737 	}
12738 	for (i = 0; i < env->subprog_cnt; i++) {
12739 		old_bpf_func = func[i]->bpf_func;
12740 		tmp = bpf_int_jit_compile(func[i]);
12741 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12742 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12743 			err = -ENOTSUPP;
12744 			goto out_free;
12745 		}
12746 		cond_resched();
12747 	}
12748 
12749 	/* finally lock prog and jit images for all functions and
12750 	 * populate kallsysm. Begin at the first subprogram, since
12751 	 * bpf_prog_load will add the kallsyms for the main program.
12752 	 */
12753 	for (i = 1; i < env->subprog_cnt; i++) {
12754 		bpf_prog_lock_ro(func[i]);
12755 		bpf_prog_kallsyms_add(func[i]);
12756 	}
12757 
12758 	/* Last step: make now unused interpreter insns from main
12759 	 * prog consistent for later dump requests, so they can
12760 	 * later look the same as if they were interpreted only.
12761 	 */
12762 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12763 		if (bpf_pseudo_func(insn)) {
12764 			insn[0].imm = env->insn_aux_data[i].call_imm;
12765 			insn[1].imm = insn->off;
12766 			insn->off = 0;
12767 			continue;
12768 		}
12769 		if (!bpf_pseudo_call(insn))
12770 			continue;
12771 		insn->off = env->insn_aux_data[i].call_imm;
12772 		subprog = find_subprog(env, i + insn->off + 1);
12773 		insn->imm = subprog;
12774 	}
12775 
12776 	prog->jited = 1;
12777 	prog->bpf_func = func[0]->bpf_func;
12778 	prog->aux->extable = func[0]->aux->extable;
12779 	prog->aux->num_exentries = func[0]->aux->num_exentries;
12780 	prog->aux->func = func;
12781 	prog->aux->func_cnt = env->subprog_cnt;
12782 	bpf_prog_jit_attempt_done(prog);
12783 	return 0;
12784 out_free:
12785 	/* We failed JIT'ing, so at this point we need to unregister poke
12786 	 * descriptors from subprogs, so that kernel is not attempting to
12787 	 * patch it anymore as we're freeing the subprog JIT memory.
12788 	 */
12789 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
12790 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
12791 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12792 	}
12793 	/* At this point we're guaranteed that poke descriptors are not
12794 	 * live anymore. We can just unlink its descriptor table as it's
12795 	 * released with the main prog.
12796 	 */
12797 	for (i = 0; i < env->subprog_cnt; i++) {
12798 		if (!func[i])
12799 			continue;
12800 		func[i]->aux->poke_tab = NULL;
12801 		bpf_jit_free(func[i]);
12802 	}
12803 	kfree(func);
12804 out_undo_insn:
12805 	/* cleanup main prog to be interpreted */
12806 	prog->jit_requested = 0;
12807 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12808 		if (!bpf_pseudo_call(insn))
12809 			continue;
12810 		insn->off = 0;
12811 		insn->imm = env->insn_aux_data[i].call_imm;
12812 	}
12813 	bpf_prog_jit_attempt_done(prog);
12814 	return err;
12815 }
12816 
fixup_call_args(struct bpf_verifier_env * env)12817 static int fixup_call_args(struct bpf_verifier_env *env)
12818 {
12819 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12820 	struct bpf_prog *prog = env->prog;
12821 	struct bpf_insn *insn = prog->insnsi;
12822 	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12823 	int i, depth;
12824 #endif
12825 	int err = 0;
12826 
12827 	if (env->prog->jit_requested &&
12828 	    !bpf_prog_is_dev_bound(env->prog->aux)) {
12829 		err = jit_subprogs(env);
12830 		if (err == 0)
12831 			return 0;
12832 		if (err == -EFAULT)
12833 			return err;
12834 	}
12835 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12836 	if (has_kfunc_call) {
12837 		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12838 		return -EINVAL;
12839 	}
12840 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12841 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
12842 		 * have to be rejected, since interpreter doesn't support them yet.
12843 		 */
12844 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12845 		return -EINVAL;
12846 	}
12847 	for (i = 0; i < prog->len; i++, insn++) {
12848 		if (bpf_pseudo_func(insn)) {
12849 			/* When JIT fails the progs with callback calls
12850 			 * have to be rejected, since interpreter doesn't support them yet.
12851 			 */
12852 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
12853 			return -EINVAL;
12854 		}
12855 
12856 		if (!bpf_pseudo_call(insn))
12857 			continue;
12858 		depth = get_callee_stack_depth(env, insn, i);
12859 		if (depth < 0)
12860 			return depth;
12861 		bpf_patch_call_args(insn, depth);
12862 	}
12863 	err = 0;
12864 #endif
12865 	return err;
12866 }
12867 
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn)12868 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12869 			    struct bpf_insn *insn)
12870 {
12871 	const struct bpf_kfunc_desc *desc;
12872 
12873 	/* insn->imm has the btf func_id. Replace it with
12874 	 * an address (relative to __bpf_base_call).
12875 	 */
12876 	desc = find_kfunc_desc(env->prog, insn->imm);
12877 	if (!desc) {
12878 		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12879 			insn->imm);
12880 		return -EFAULT;
12881 	}
12882 
12883 	insn->imm = desc->imm;
12884 
12885 	return 0;
12886 }
12887 
12888 /* Do various post-verification rewrites in a single program pass.
12889  * These rewrites simplify JIT and interpreter implementations.
12890  */
do_misc_fixups(struct bpf_verifier_env * env)12891 static int do_misc_fixups(struct bpf_verifier_env *env)
12892 {
12893 	struct bpf_prog *prog = env->prog;
12894 	bool expect_blinding = bpf_jit_blinding_enabled(prog);
12895 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
12896 	struct bpf_insn *insn = prog->insnsi;
12897 	const struct bpf_func_proto *fn;
12898 	const int insn_cnt = prog->len;
12899 	const struct bpf_map_ops *ops;
12900 	struct bpf_insn_aux_data *aux;
12901 	struct bpf_insn insn_buf[16];
12902 	struct bpf_prog *new_prog;
12903 	struct bpf_map *map_ptr;
12904 	int i, ret, cnt, delta = 0;
12905 
12906 	for (i = 0; i < insn_cnt; i++, insn++) {
12907 		/* Make divide-by-zero exceptions impossible. */
12908 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12909 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12910 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12911 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12912 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12913 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12914 			struct bpf_insn *patchlet;
12915 			struct bpf_insn chk_and_div[] = {
12916 				/* [R,W]x div 0 -> 0 */
12917 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12918 					     BPF_JNE | BPF_K, insn->src_reg,
12919 					     0, 2, 0),
12920 				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12921 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12922 				*insn,
12923 			};
12924 			struct bpf_insn chk_and_mod[] = {
12925 				/* [R,W]x mod 0 -> [R,W]x */
12926 				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12927 					     BPF_JEQ | BPF_K, insn->src_reg,
12928 					     0, 1 + (is64 ? 0 : 1), 0),
12929 				*insn,
12930 				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12931 				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12932 			};
12933 
12934 			patchlet = isdiv ? chk_and_div : chk_and_mod;
12935 			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12936 				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12937 
12938 			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12939 			if (!new_prog)
12940 				return -ENOMEM;
12941 
12942 			delta    += cnt - 1;
12943 			env->prog = prog = new_prog;
12944 			insn      = new_prog->insnsi + i + delta;
12945 			continue;
12946 		}
12947 
12948 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12949 		if (BPF_CLASS(insn->code) == BPF_LD &&
12950 		    (BPF_MODE(insn->code) == BPF_ABS ||
12951 		     BPF_MODE(insn->code) == BPF_IND)) {
12952 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
12953 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12954 				verbose(env, "bpf verifier is misconfigured\n");
12955 				return -EINVAL;
12956 			}
12957 
12958 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12959 			if (!new_prog)
12960 				return -ENOMEM;
12961 
12962 			delta    += cnt - 1;
12963 			env->prog = prog = new_prog;
12964 			insn      = new_prog->insnsi + i + delta;
12965 			continue;
12966 		}
12967 
12968 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
12969 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12970 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12971 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12972 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12973 			struct bpf_insn *patch = &insn_buf[0];
12974 			bool issrc, isneg, isimm;
12975 			u32 off_reg;
12976 
12977 			aux = &env->insn_aux_data[i + delta];
12978 			if (!aux->alu_state ||
12979 			    aux->alu_state == BPF_ALU_NON_POINTER)
12980 				continue;
12981 
12982 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12983 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12984 				BPF_ALU_SANITIZE_SRC;
12985 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12986 
12987 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
12988 			if (isimm) {
12989 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12990 			} else {
12991 				if (isneg)
12992 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12993 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12994 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12995 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12996 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12997 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12998 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12999 			}
13000 			if (!issrc)
13001 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13002 			insn->src_reg = BPF_REG_AX;
13003 			if (isneg)
13004 				insn->code = insn->code == code_add ?
13005 					     code_sub : code_add;
13006 			*patch++ = *insn;
13007 			if (issrc && isneg && !isimm)
13008 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13009 			cnt = patch - insn_buf;
13010 
13011 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13012 			if (!new_prog)
13013 				return -ENOMEM;
13014 
13015 			delta    += cnt - 1;
13016 			env->prog = prog = new_prog;
13017 			insn      = new_prog->insnsi + i + delta;
13018 			continue;
13019 		}
13020 
13021 		if (insn->code != (BPF_JMP | BPF_CALL))
13022 			continue;
13023 		if (insn->src_reg == BPF_PSEUDO_CALL)
13024 			continue;
13025 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13026 			ret = fixup_kfunc_call(env, insn);
13027 			if (ret)
13028 				return ret;
13029 			continue;
13030 		}
13031 
13032 		if (insn->imm == BPF_FUNC_get_route_realm)
13033 			prog->dst_needed = 1;
13034 		if (insn->imm == BPF_FUNC_get_prandom_u32)
13035 			bpf_user_rnd_init_once();
13036 		if (insn->imm == BPF_FUNC_override_return)
13037 			prog->kprobe_override = 1;
13038 		if (insn->imm == BPF_FUNC_tail_call) {
13039 			/* If we tail call into other programs, we
13040 			 * cannot make any assumptions since they can
13041 			 * be replaced dynamically during runtime in
13042 			 * the program array.
13043 			 */
13044 			prog->cb_access = 1;
13045 			if (!allow_tail_call_in_subprogs(env))
13046 				prog->aux->stack_depth = MAX_BPF_STACK;
13047 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
13048 
13049 			/* mark bpf_tail_call as different opcode to avoid
13050 			 * conditional branch in the interpreter for every normal
13051 			 * call and to prevent accidental JITing by JIT compiler
13052 			 * that doesn't support bpf_tail_call yet
13053 			 */
13054 			insn->imm = 0;
13055 			insn->code = BPF_JMP | BPF_TAIL_CALL;
13056 
13057 			aux = &env->insn_aux_data[i + delta];
13058 			if (env->bpf_capable && !expect_blinding &&
13059 			    prog->jit_requested &&
13060 			    !bpf_map_key_poisoned(aux) &&
13061 			    !bpf_map_ptr_poisoned(aux) &&
13062 			    !bpf_map_ptr_unpriv(aux)) {
13063 				struct bpf_jit_poke_descriptor desc = {
13064 					.reason = BPF_POKE_REASON_TAIL_CALL,
13065 					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13066 					.tail_call.key = bpf_map_key_immediate(aux),
13067 					.insn_idx = i + delta,
13068 				};
13069 
13070 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
13071 				if (ret < 0) {
13072 					verbose(env, "adding tail call poke descriptor failed\n");
13073 					return ret;
13074 				}
13075 
13076 				insn->imm = ret + 1;
13077 				continue;
13078 			}
13079 
13080 			if (!bpf_map_ptr_unpriv(aux))
13081 				continue;
13082 
13083 			/* instead of changing every JIT dealing with tail_call
13084 			 * emit two extra insns:
13085 			 * if (index >= max_entries) goto out;
13086 			 * index &= array->index_mask;
13087 			 * to avoid out-of-bounds cpu speculation
13088 			 */
13089 			if (bpf_map_ptr_poisoned(aux)) {
13090 				verbose(env, "tail_call abusing map_ptr\n");
13091 				return -EINVAL;
13092 			}
13093 
13094 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13095 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13096 						  map_ptr->max_entries, 2);
13097 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13098 						    container_of(map_ptr,
13099 								 struct bpf_array,
13100 								 map)->index_mask);
13101 			insn_buf[2] = *insn;
13102 			cnt = 3;
13103 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13104 			if (!new_prog)
13105 				return -ENOMEM;
13106 
13107 			delta    += cnt - 1;
13108 			env->prog = prog = new_prog;
13109 			insn      = new_prog->insnsi + i + delta;
13110 			continue;
13111 		}
13112 
13113 		if (insn->imm == BPF_FUNC_timer_set_callback) {
13114 			/* The verifier will process callback_fn as many times as necessary
13115 			 * with different maps and the register states prepared by
13116 			 * set_timer_callback_state will be accurate.
13117 			 *
13118 			 * The following use case is valid:
13119 			 *   map1 is shared by prog1, prog2, prog3.
13120 			 *   prog1 calls bpf_timer_init for some map1 elements
13121 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
13122 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
13123 			 *   prog3 calls bpf_timer_start for some map1 elements.
13124 			 *     Those that were not both bpf_timer_init-ed and
13125 			 *     bpf_timer_set_callback-ed will return -EINVAL.
13126 			 */
13127 			struct bpf_insn ld_addrs[2] = {
13128 				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13129 			};
13130 
13131 			insn_buf[0] = ld_addrs[0];
13132 			insn_buf[1] = ld_addrs[1];
13133 			insn_buf[2] = *insn;
13134 			cnt = 3;
13135 
13136 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13137 			if (!new_prog)
13138 				return -ENOMEM;
13139 
13140 			delta    += cnt - 1;
13141 			env->prog = prog = new_prog;
13142 			insn      = new_prog->insnsi + i + delta;
13143 			goto patch_call_imm;
13144 		}
13145 
13146 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
13147 		 * and other inlining handlers are currently limited to 64 bit
13148 		 * only.
13149 		 */
13150 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13151 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
13152 		     insn->imm == BPF_FUNC_map_update_elem ||
13153 		     insn->imm == BPF_FUNC_map_delete_elem ||
13154 		     insn->imm == BPF_FUNC_map_push_elem   ||
13155 		     insn->imm == BPF_FUNC_map_pop_elem    ||
13156 		     insn->imm == BPF_FUNC_map_peek_elem   ||
13157 		     insn->imm == BPF_FUNC_redirect_map)) {
13158 			aux = &env->insn_aux_data[i + delta];
13159 			if (bpf_map_ptr_poisoned(aux))
13160 				goto patch_call_imm;
13161 
13162 			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
13163 			ops = map_ptr->ops;
13164 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
13165 			    ops->map_gen_lookup) {
13166 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
13167 				if (cnt == -EOPNOTSUPP)
13168 					goto patch_map_ops_generic;
13169 				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13170 					verbose(env, "bpf verifier is misconfigured\n");
13171 					return -EINVAL;
13172 				}
13173 
13174 				new_prog = bpf_patch_insn_data(env, i + delta,
13175 							       insn_buf, cnt);
13176 				if (!new_prog)
13177 					return -ENOMEM;
13178 
13179 				delta    += cnt - 1;
13180 				env->prog = prog = new_prog;
13181 				insn      = new_prog->insnsi + i + delta;
13182 				continue;
13183 			}
13184 
13185 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13186 				     (void *(*)(struct bpf_map *map, void *key))NULL));
13187 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13188 				     (int (*)(struct bpf_map *map, void *key))NULL));
13189 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13190 				     (int (*)(struct bpf_map *map, void *key, void *value,
13191 					      u64 flags))NULL));
13192 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13193 				     (int (*)(struct bpf_map *map, void *value,
13194 					      u64 flags))NULL));
13195 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13196 				     (int (*)(struct bpf_map *map, void *value))NULL));
13197 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13198 				     (int (*)(struct bpf_map *map, void *value))NULL));
13199 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
13200 				     (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13201 
13202 patch_map_ops_generic:
13203 			switch (insn->imm) {
13204 			case BPF_FUNC_map_lookup_elem:
13205 				insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
13206 					    __bpf_call_base;
13207 				continue;
13208 			case BPF_FUNC_map_update_elem:
13209 				insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
13210 					    __bpf_call_base;
13211 				continue;
13212 			case BPF_FUNC_map_delete_elem:
13213 				insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
13214 					    __bpf_call_base;
13215 				continue;
13216 			case BPF_FUNC_map_push_elem:
13217 				insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
13218 					    __bpf_call_base;
13219 				continue;
13220 			case BPF_FUNC_map_pop_elem:
13221 				insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
13222 					    __bpf_call_base;
13223 				continue;
13224 			case BPF_FUNC_map_peek_elem:
13225 				insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
13226 					    __bpf_call_base;
13227 				continue;
13228 			case BPF_FUNC_redirect_map:
13229 				insn->imm = BPF_CAST_CALL(ops->map_redirect) -
13230 					    __bpf_call_base;
13231 				continue;
13232 			}
13233 
13234 			goto patch_call_imm;
13235 		}
13236 
13237 		/* Implement bpf_jiffies64 inline. */
13238 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
13239 		    insn->imm == BPF_FUNC_jiffies64) {
13240 			struct bpf_insn ld_jiffies_addr[2] = {
13241 				BPF_LD_IMM64(BPF_REG_0,
13242 					     (unsigned long)&jiffies),
13243 			};
13244 
13245 			insn_buf[0] = ld_jiffies_addr[0];
13246 			insn_buf[1] = ld_jiffies_addr[1];
13247 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13248 						  BPF_REG_0, 0);
13249 			cnt = 3;
13250 
13251 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13252 						       cnt);
13253 			if (!new_prog)
13254 				return -ENOMEM;
13255 
13256 			delta    += cnt - 1;
13257 			env->prog = prog = new_prog;
13258 			insn      = new_prog->insnsi + i + delta;
13259 			continue;
13260 		}
13261 
13262 		/* Implement bpf_get_func_ip inline. */
13263 		if (prog_type == BPF_PROG_TYPE_TRACING &&
13264 		    insn->imm == BPF_FUNC_get_func_ip) {
13265 			/* Load IP address from ctx - 8 */
13266 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13267 
13268 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13269 			if (!new_prog)
13270 				return -ENOMEM;
13271 
13272 			env->prog = prog = new_prog;
13273 			insn      = new_prog->insnsi + i + delta;
13274 			continue;
13275 		}
13276 
13277 patch_call_imm:
13278 		fn = env->ops->get_func_proto(insn->imm, env->prog);
13279 		/* all functions that have prototype and verifier allowed
13280 		 * programs to call them, must be real in-kernel functions
13281 		 */
13282 		if (!fn->func) {
13283 			verbose(env,
13284 				"kernel subsystem misconfigured func %s#%d\n",
13285 				func_id_name(insn->imm), insn->imm);
13286 			return -EFAULT;
13287 		}
13288 		insn->imm = fn->func - __bpf_call_base;
13289 	}
13290 
13291 	/* Since poke tab is now finalized, publish aux to tracker. */
13292 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
13293 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
13294 		if (!map_ptr->ops->map_poke_track ||
13295 		    !map_ptr->ops->map_poke_untrack ||
13296 		    !map_ptr->ops->map_poke_run) {
13297 			verbose(env, "bpf verifier is misconfigured\n");
13298 			return -EINVAL;
13299 		}
13300 
13301 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13302 		if (ret < 0) {
13303 			verbose(env, "tracking tail call prog failed\n");
13304 			return ret;
13305 		}
13306 	}
13307 
13308 	sort_kfunc_descs_by_imm(env->prog);
13309 
13310 	return 0;
13311 }
13312 
free_states(struct bpf_verifier_env * env)13313 static void free_states(struct bpf_verifier_env *env)
13314 {
13315 	struct bpf_verifier_state_list *sl, *sln;
13316 	int i;
13317 
13318 	sl = env->free_list;
13319 	while (sl) {
13320 		sln = sl->next;
13321 		free_verifier_state(&sl->state, false);
13322 		kfree(sl);
13323 		sl = sln;
13324 	}
13325 	env->free_list = NULL;
13326 
13327 	if (!env->explored_states)
13328 		return;
13329 
13330 	for (i = 0; i < state_htab_size(env); i++) {
13331 		sl = env->explored_states[i];
13332 
13333 		while (sl) {
13334 			sln = sl->next;
13335 			free_verifier_state(&sl->state, false);
13336 			kfree(sl);
13337 			sl = sln;
13338 		}
13339 		env->explored_states[i] = NULL;
13340 	}
13341 }
13342 
do_check_common(struct bpf_verifier_env * env,int subprog)13343 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13344 {
13345 	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13346 	struct bpf_verifier_state *state;
13347 	struct bpf_reg_state *regs;
13348 	int ret, i;
13349 
13350 	env->prev_linfo = NULL;
13351 	env->pass_cnt++;
13352 
13353 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13354 	if (!state)
13355 		return -ENOMEM;
13356 	state->curframe = 0;
13357 	state->speculative = false;
13358 	state->branches = 1;
13359 	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13360 	if (!state->frame[0]) {
13361 		kfree(state);
13362 		return -ENOMEM;
13363 	}
13364 	env->cur_state = state;
13365 	init_func_state(env, state->frame[0],
13366 			BPF_MAIN_FUNC /* callsite */,
13367 			0 /* frameno */,
13368 			subprog);
13369 	state->first_insn_idx = env->subprog_info[subprog].start;
13370 	state->last_insn_idx = -1;
13371 
13372 	regs = state->frame[state->curframe]->regs;
13373 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13374 		ret = btf_prepare_func_args(env, subprog, regs);
13375 		if (ret)
13376 			goto out;
13377 		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13378 			if (regs[i].type == PTR_TO_CTX)
13379 				mark_reg_known_zero(env, regs, i);
13380 			else if (regs[i].type == SCALAR_VALUE)
13381 				mark_reg_unknown(env, regs, i);
13382 			else if (base_type(regs[i].type) == PTR_TO_MEM) {
13383 				const u32 mem_size = regs[i].mem_size;
13384 
13385 				mark_reg_known_zero(env, regs, i);
13386 				regs[i].mem_size = mem_size;
13387 				regs[i].id = ++env->id_gen;
13388 			}
13389 		}
13390 	} else {
13391 		/* 1st arg to a function */
13392 		regs[BPF_REG_1].type = PTR_TO_CTX;
13393 		mark_reg_known_zero(env, regs, BPF_REG_1);
13394 		ret = btf_check_subprog_arg_match(env, subprog, regs);
13395 		if (ret == -EFAULT)
13396 			/* unlikely verifier bug. abort.
13397 			 * ret == 0 and ret < 0 are sadly acceptable for
13398 			 * main() function due to backward compatibility.
13399 			 * Like socket filter program may be written as:
13400 			 * int bpf_prog(struct pt_regs *ctx)
13401 			 * and never dereference that ctx in the program.
13402 			 * 'struct pt_regs' is a type mismatch for socket
13403 			 * filter that should be using 'struct __sk_buff'.
13404 			 */
13405 			goto out;
13406 	}
13407 
13408 	ret = do_check(env);
13409 out:
13410 	/* check for NULL is necessary, since cur_state can be freed inside
13411 	 * do_check() under memory pressure.
13412 	 */
13413 	if (env->cur_state) {
13414 		free_verifier_state(env->cur_state, true);
13415 		env->cur_state = NULL;
13416 	}
13417 	while (!pop_stack(env, NULL, NULL, false));
13418 	if (!ret && pop_log)
13419 		bpf_vlog_reset(&env->log, 0);
13420 	free_states(env);
13421 	return ret;
13422 }
13423 
13424 /* Verify all global functions in a BPF program one by one based on their BTF.
13425  * All global functions must pass verification. Otherwise the whole program is rejected.
13426  * Consider:
13427  * int bar(int);
13428  * int foo(int f)
13429  * {
13430  *    return bar(f);
13431  * }
13432  * int bar(int b)
13433  * {
13434  *    ...
13435  * }
13436  * foo() will be verified first for R1=any_scalar_value. During verification it
13437  * will be assumed that bar() already verified successfully and call to bar()
13438  * from foo() will be checked for type match only. Later bar() will be verified
13439  * independently to check that it's safe for R1=any_scalar_value.
13440  */
do_check_subprogs(struct bpf_verifier_env * env)13441 static int do_check_subprogs(struct bpf_verifier_env *env)
13442 {
13443 	struct bpf_prog_aux *aux = env->prog->aux;
13444 	int i, ret;
13445 
13446 	if (!aux->func_info)
13447 		return 0;
13448 
13449 	for (i = 1; i < env->subprog_cnt; i++) {
13450 		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13451 			continue;
13452 		env->insn_idx = env->subprog_info[i].start;
13453 		WARN_ON_ONCE(env->insn_idx == 0);
13454 		ret = do_check_common(env, i);
13455 		if (ret) {
13456 			return ret;
13457 		} else if (env->log.level & BPF_LOG_LEVEL) {
13458 			verbose(env,
13459 				"Func#%d is safe for any args that match its prototype\n",
13460 				i);
13461 		}
13462 	}
13463 	return 0;
13464 }
13465 
do_check_main(struct bpf_verifier_env * env)13466 static int do_check_main(struct bpf_verifier_env *env)
13467 {
13468 	int ret;
13469 
13470 	env->insn_idx = 0;
13471 	ret = do_check_common(env, 0);
13472 	if (!ret)
13473 		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13474 	return ret;
13475 }
13476 
13477 
print_verification_stats(struct bpf_verifier_env * env)13478 static void print_verification_stats(struct bpf_verifier_env *env)
13479 {
13480 	int i;
13481 
13482 	if (env->log.level & BPF_LOG_STATS) {
13483 		verbose(env, "verification time %lld usec\n",
13484 			div_u64(env->verification_time, 1000));
13485 		verbose(env, "stack depth ");
13486 		for (i = 0; i < env->subprog_cnt; i++) {
13487 			u32 depth = env->subprog_info[i].stack_depth;
13488 
13489 			verbose(env, "%d", depth);
13490 			if (i + 1 < env->subprog_cnt)
13491 				verbose(env, "+");
13492 		}
13493 		verbose(env, "\n");
13494 	}
13495 	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13496 		"total_states %d peak_states %d mark_read %d\n",
13497 		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13498 		env->max_states_per_insn, env->total_states,
13499 		env->peak_states, env->longest_mark_read_walk);
13500 }
13501 
check_struct_ops_btf_id(struct bpf_verifier_env * env)13502 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13503 {
13504 	const struct btf_type *t, *func_proto;
13505 	const struct bpf_struct_ops *st_ops;
13506 	const struct btf_member *member;
13507 	struct bpf_prog *prog = env->prog;
13508 	u32 btf_id, member_idx;
13509 	const char *mname;
13510 
13511 	if (!prog->gpl_compatible) {
13512 		verbose(env, "struct ops programs must have a GPL compatible license\n");
13513 		return -EINVAL;
13514 	}
13515 
13516 	btf_id = prog->aux->attach_btf_id;
13517 	st_ops = bpf_struct_ops_find(btf_id);
13518 	if (!st_ops) {
13519 		verbose(env, "attach_btf_id %u is not a supported struct\n",
13520 			btf_id);
13521 		return -ENOTSUPP;
13522 	}
13523 
13524 	t = st_ops->type;
13525 	member_idx = prog->expected_attach_type;
13526 	if (member_idx >= btf_type_vlen(t)) {
13527 		verbose(env, "attach to invalid member idx %u of struct %s\n",
13528 			member_idx, st_ops->name);
13529 		return -EINVAL;
13530 	}
13531 
13532 	member = &btf_type_member(t)[member_idx];
13533 	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13534 	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13535 					       NULL);
13536 	if (!func_proto) {
13537 		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13538 			mname, member_idx, st_ops->name);
13539 		return -EINVAL;
13540 	}
13541 
13542 	if (st_ops->check_member) {
13543 		int err = st_ops->check_member(t, member);
13544 
13545 		if (err) {
13546 			verbose(env, "attach to unsupported member %s of struct %s\n",
13547 				mname, st_ops->name);
13548 			return err;
13549 		}
13550 	}
13551 
13552 	prog->aux->attach_func_proto = func_proto;
13553 	prog->aux->attach_func_name = mname;
13554 	env->ops = st_ops->verifier_ops;
13555 
13556 	return 0;
13557 }
13558 #define SECURITY_PREFIX "security_"
13559 
check_attach_modify_return(unsigned long addr,const char * func_name)13560 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13561 {
13562 	if (within_error_injection_list(addr) ||
13563 	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13564 		return 0;
13565 
13566 	return -EINVAL;
13567 }
13568 
13569 /* list of non-sleepable functions that are otherwise on
13570  * ALLOW_ERROR_INJECTION list
13571  */
13572 BTF_SET_START(btf_non_sleepable_error_inject)
13573 /* Three functions below can be called from sleepable and non-sleepable context.
13574  * Assume non-sleepable from bpf safety point of view.
13575  */
BTF_ID(func,__add_to_page_cache_locked)13576 BTF_ID(func, __add_to_page_cache_locked)
13577 BTF_ID(func, should_fail_alloc_page)
13578 BTF_ID(func, should_failslab)
13579 BTF_SET_END(btf_non_sleepable_error_inject)
13580 
13581 static int check_non_sleepable_error_inject(u32 btf_id)
13582 {
13583 	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13584 }
13585 
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)13586 int bpf_check_attach_target(struct bpf_verifier_log *log,
13587 			    const struct bpf_prog *prog,
13588 			    const struct bpf_prog *tgt_prog,
13589 			    u32 btf_id,
13590 			    struct bpf_attach_target_info *tgt_info)
13591 {
13592 	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13593 	const char prefix[] = "btf_trace_";
13594 	int ret = 0, subprog = -1, i;
13595 	const struct btf_type *t;
13596 	bool conservative = true;
13597 	const char *tname;
13598 	struct btf *btf;
13599 	long addr = 0;
13600 
13601 	if (!btf_id) {
13602 		bpf_log(log, "Tracing programs must provide btf_id\n");
13603 		return -EINVAL;
13604 	}
13605 	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13606 	if (!btf) {
13607 		bpf_log(log,
13608 			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13609 		return -EINVAL;
13610 	}
13611 	t = btf_type_by_id(btf, btf_id);
13612 	if (!t) {
13613 		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13614 		return -EINVAL;
13615 	}
13616 	tname = btf_name_by_offset(btf, t->name_off);
13617 	if (!tname) {
13618 		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13619 		return -EINVAL;
13620 	}
13621 	if (tgt_prog) {
13622 		struct bpf_prog_aux *aux = tgt_prog->aux;
13623 
13624 		for (i = 0; i < aux->func_info_cnt; i++)
13625 			if (aux->func_info[i].type_id == btf_id) {
13626 				subprog = i;
13627 				break;
13628 			}
13629 		if (subprog == -1) {
13630 			bpf_log(log, "Subprog %s doesn't exist\n", tname);
13631 			return -EINVAL;
13632 		}
13633 		conservative = aux->func_info_aux[subprog].unreliable;
13634 		if (prog_extension) {
13635 			if (conservative) {
13636 				bpf_log(log,
13637 					"Cannot replace static functions\n");
13638 				return -EINVAL;
13639 			}
13640 			if (!prog->jit_requested) {
13641 				bpf_log(log,
13642 					"Extension programs should be JITed\n");
13643 				return -EINVAL;
13644 			}
13645 		}
13646 		if (!tgt_prog->jited) {
13647 			bpf_log(log, "Can attach to only JITed progs\n");
13648 			return -EINVAL;
13649 		}
13650 		if (tgt_prog->type == prog->type) {
13651 			/* Cannot fentry/fexit another fentry/fexit program.
13652 			 * Cannot attach program extension to another extension.
13653 			 * It's ok to attach fentry/fexit to extension program.
13654 			 */
13655 			bpf_log(log, "Cannot recursively attach\n");
13656 			return -EINVAL;
13657 		}
13658 		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13659 		    prog_extension &&
13660 		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13661 		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13662 			/* Program extensions can extend all program types
13663 			 * except fentry/fexit. The reason is the following.
13664 			 * The fentry/fexit programs are used for performance
13665 			 * analysis, stats and can be attached to any program
13666 			 * type except themselves. When extension program is
13667 			 * replacing XDP function it is necessary to allow
13668 			 * performance analysis of all functions. Both original
13669 			 * XDP program and its program extension. Hence
13670 			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13671 			 * allowed. If extending of fentry/fexit was allowed it
13672 			 * would be possible to create long call chain
13673 			 * fentry->extension->fentry->extension beyond
13674 			 * reasonable stack size. Hence extending fentry is not
13675 			 * allowed.
13676 			 */
13677 			bpf_log(log, "Cannot extend fentry/fexit\n");
13678 			return -EINVAL;
13679 		}
13680 	} else {
13681 		if (prog_extension) {
13682 			bpf_log(log, "Cannot replace kernel functions\n");
13683 			return -EINVAL;
13684 		}
13685 	}
13686 
13687 	switch (prog->expected_attach_type) {
13688 	case BPF_TRACE_RAW_TP:
13689 		if (tgt_prog) {
13690 			bpf_log(log,
13691 				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13692 			return -EINVAL;
13693 		}
13694 		if (!btf_type_is_typedef(t)) {
13695 			bpf_log(log, "attach_btf_id %u is not a typedef\n",
13696 				btf_id);
13697 			return -EINVAL;
13698 		}
13699 		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13700 			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13701 				btf_id, tname);
13702 			return -EINVAL;
13703 		}
13704 		tname += sizeof(prefix) - 1;
13705 		t = btf_type_by_id(btf, t->type);
13706 		if (!btf_type_is_ptr(t))
13707 			/* should never happen in valid vmlinux build */
13708 			return -EINVAL;
13709 		t = btf_type_by_id(btf, t->type);
13710 		if (!btf_type_is_func_proto(t))
13711 			/* should never happen in valid vmlinux build */
13712 			return -EINVAL;
13713 
13714 		break;
13715 	case BPF_TRACE_ITER:
13716 		if (!btf_type_is_func(t)) {
13717 			bpf_log(log, "attach_btf_id %u is not a function\n",
13718 				btf_id);
13719 			return -EINVAL;
13720 		}
13721 		t = btf_type_by_id(btf, t->type);
13722 		if (!btf_type_is_func_proto(t))
13723 			return -EINVAL;
13724 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13725 		if (ret)
13726 			return ret;
13727 		break;
13728 	default:
13729 		if (!prog_extension)
13730 			return -EINVAL;
13731 		fallthrough;
13732 	case BPF_MODIFY_RETURN:
13733 	case BPF_LSM_MAC:
13734 	case BPF_TRACE_FENTRY:
13735 	case BPF_TRACE_FEXIT:
13736 		if (!btf_type_is_func(t)) {
13737 			bpf_log(log, "attach_btf_id %u is not a function\n",
13738 				btf_id);
13739 			return -EINVAL;
13740 		}
13741 		if (prog_extension &&
13742 		    btf_check_type_match(log, prog, btf, t))
13743 			return -EINVAL;
13744 		t = btf_type_by_id(btf, t->type);
13745 		if (!btf_type_is_func_proto(t))
13746 			return -EINVAL;
13747 
13748 		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13749 		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13750 		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13751 			return -EINVAL;
13752 
13753 		if (tgt_prog && conservative)
13754 			t = NULL;
13755 
13756 		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13757 		if (ret < 0)
13758 			return ret;
13759 
13760 		if (tgt_prog) {
13761 			if (subprog == 0)
13762 				addr = (long) tgt_prog->bpf_func;
13763 			else
13764 				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13765 		} else {
13766 			addr = kallsyms_lookup_name(tname);
13767 			if (!addr) {
13768 				bpf_log(log,
13769 					"The address of function %s cannot be found\n",
13770 					tname);
13771 				return -ENOENT;
13772 			}
13773 		}
13774 
13775 		if (prog->aux->sleepable) {
13776 			ret = -EINVAL;
13777 			switch (prog->type) {
13778 			case BPF_PROG_TYPE_TRACING:
13779 				/* fentry/fexit/fmod_ret progs can be sleepable only if they are
13780 				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13781 				 */
13782 				if (!check_non_sleepable_error_inject(btf_id) &&
13783 				    within_error_injection_list(addr))
13784 					ret = 0;
13785 				break;
13786 			case BPF_PROG_TYPE_LSM:
13787 				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
13788 				 * Only some of them are sleepable.
13789 				 */
13790 				if (bpf_lsm_is_sleepable_hook(btf_id))
13791 					ret = 0;
13792 				break;
13793 			default:
13794 				break;
13795 			}
13796 			if (ret) {
13797 				bpf_log(log, "%s is not sleepable\n", tname);
13798 				return ret;
13799 			}
13800 		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13801 			if (tgt_prog) {
13802 				bpf_log(log, "can't modify return codes of BPF programs\n");
13803 				return -EINVAL;
13804 			}
13805 			ret = check_attach_modify_return(addr, tname);
13806 			if (ret) {
13807 				bpf_log(log, "%s() is not modifiable\n", tname);
13808 				return ret;
13809 			}
13810 		}
13811 
13812 		break;
13813 	}
13814 	tgt_info->tgt_addr = addr;
13815 	tgt_info->tgt_name = tname;
13816 	tgt_info->tgt_type = t;
13817 	return 0;
13818 }
13819 
BTF_SET_START(btf_id_deny)13820 BTF_SET_START(btf_id_deny)
13821 BTF_ID_UNUSED
13822 #ifdef CONFIG_SMP
13823 BTF_ID(func, migrate_disable)
13824 BTF_ID(func, migrate_enable)
13825 #endif
13826 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13827 BTF_ID(func, rcu_read_unlock_strict)
13828 #endif
13829 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
13830 BTF_ID(func, preempt_count_add)
13831 BTF_ID(func, preempt_count_sub)
13832 #endif
13833 BTF_SET_END(btf_id_deny)
13834 
13835 static int check_attach_btf_id(struct bpf_verifier_env *env)
13836 {
13837 	struct bpf_prog *prog = env->prog;
13838 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13839 	struct bpf_attach_target_info tgt_info = {};
13840 	u32 btf_id = prog->aux->attach_btf_id;
13841 	struct bpf_trampoline *tr;
13842 	int ret;
13843 	u64 key;
13844 
13845 	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13846 		if (prog->aux->sleepable)
13847 			/* attach_btf_id checked to be zero already */
13848 			return 0;
13849 		verbose(env, "Syscall programs can only be sleepable\n");
13850 		return -EINVAL;
13851 	}
13852 
13853 	if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13854 	    prog->type != BPF_PROG_TYPE_LSM) {
13855 		verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13856 		return -EINVAL;
13857 	}
13858 
13859 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13860 		return check_struct_ops_btf_id(env);
13861 
13862 	if (prog->type != BPF_PROG_TYPE_TRACING &&
13863 	    prog->type != BPF_PROG_TYPE_LSM &&
13864 	    prog->type != BPF_PROG_TYPE_EXT)
13865 		return 0;
13866 
13867 	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13868 	if (ret)
13869 		return ret;
13870 
13871 	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13872 		/* to make freplace equivalent to their targets, they need to
13873 		 * inherit env->ops and expected_attach_type for the rest of the
13874 		 * verification
13875 		 */
13876 		env->ops = bpf_verifier_ops[tgt_prog->type];
13877 		prog->expected_attach_type = tgt_prog->expected_attach_type;
13878 	}
13879 
13880 	/* store info about the attachment target that will be used later */
13881 	prog->aux->attach_func_proto = tgt_info.tgt_type;
13882 	prog->aux->attach_func_name = tgt_info.tgt_name;
13883 
13884 	if (tgt_prog) {
13885 		prog->aux->saved_dst_prog_type = tgt_prog->type;
13886 		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13887 	}
13888 
13889 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13890 		prog->aux->attach_btf_trace = true;
13891 		return 0;
13892 	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13893 		if (!bpf_iter_prog_supported(prog))
13894 			return -EINVAL;
13895 		return 0;
13896 	}
13897 
13898 	if (prog->type == BPF_PROG_TYPE_LSM) {
13899 		ret = bpf_lsm_verify_prog(&env->log, prog);
13900 		if (ret < 0)
13901 			return ret;
13902 	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
13903 		   btf_id_set_contains(&btf_id_deny, btf_id)) {
13904 		return -EINVAL;
13905 	}
13906 
13907 	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13908 	tr = bpf_trampoline_get(key, &tgt_info);
13909 	if (!tr)
13910 		return -ENOMEM;
13911 
13912 	prog->aux->dst_trampoline = tr;
13913 	return 0;
13914 }
13915 
bpf_get_btf_vmlinux(void)13916 struct btf *bpf_get_btf_vmlinux(void)
13917 {
13918 	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13919 		mutex_lock(&bpf_verifier_lock);
13920 		if (!btf_vmlinux)
13921 			btf_vmlinux = btf_parse_vmlinux();
13922 		mutex_unlock(&bpf_verifier_lock);
13923 	}
13924 	return btf_vmlinux;
13925 }
13926 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr)13927 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13928 {
13929 	u64 start_time = ktime_get_ns();
13930 	struct bpf_verifier_env *env;
13931 	struct bpf_verifier_log *log;
13932 	int i, len, ret = -EINVAL;
13933 	bool is_priv;
13934 
13935 	/* no program is valid */
13936 	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13937 		return -EINVAL;
13938 
13939 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
13940 	 * allocate/free it every time bpf_check() is called
13941 	 */
13942 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13943 	if (!env)
13944 		return -ENOMEM;
13945 	log = &env->log;
13946 
13947 	len = (*prog)->len;
13948 	env->insn_aux_data =
13949 		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13950 	ret = -ENOMEM;
13951 	if (!env->insn_aux_data)
13952 		goto err_free_env;
13953 	for (i = 0; i < len; i++)
13954 		env->insn_aux_data[i].orig_idx = i;
13955 	env->prog = *prog;
13956 	env->ops = bpf_verifier_ops[env->prog->type];
13957 	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13958 	is_priv = bpf_capable();
13959 
13960 	bpf_get_btf_vmlinux();
13961 
13962 	/* grab the mutex to protect few globals used by verifier */
13963 	if (!is_priv)
13964 		mutex_lock(&bpf_verifier_lock);
13965 
13966 	if (attr->log_level || attr->log_buf || attr->log_size) {
13967 		/* user requested verbose verifier output
13968 		 * and supplied buffer to store the verification trace
13969 		 */
13970 		log->level = attr->log_level;
13971 		log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13972 		log->len_total = attr->log_size;
13973 
13974 		/* log attributes have to be sane */
13975 		if (!bpf_verifier_log_attr_valid(log)) {
13976 			ret = -EINVAL;
13977 			goto err_unlock;
13978 		}
13979 	}
13980 
13981 	if (IS_ERR(btf_vmlinux)) {
13982 		/* Either gcc or pahole or kernel are broken. */
13983 		verbose(env, "in-kernel BTF is malformed\n");
13984 		ret = PTR_ERR(btf_vmlinux);
13985 		goto skip_full_check;
13986 	}
13987 
13988 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13989 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13990 		env->strict_alignment = true;
13991 	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13992 		env->strict_alignment = false;
13993 
13994 	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13995 	env->allow_uninit_stack = bpf_allow_uninit_stack();
13996 	env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13997 	env->bypass_spec_v1 = bpf_bypass_spec_v1();
13998 	env->bypass_spec_v4 = bpf_bypass_spec_v4();
13999 	env->bpf_capable = bpf_capable();
14000 
14001 	if (is_priv)
14002 		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14003 
14004 	env->explored_states = kvcalloc(state_htab_size(env),
14005 				       sizeof(struct bpf_verifier_state_list *),
14006 				       GFP_USER);
14007 	ret = -ENOMEM;
14008 	if (!env->explored_states)
14009 		goto skip_full_check;
14010 
14011 	ret = add_subprog_and_kfunc(env);
14012 	if (ret < 0)
14013 		goto skip_full_check;
14014 
14015 	ret = check_subprogs(env);
14016 	if (ret < 0)
14017 		goto skip_full_check;
14018 
14019 	ret = check_btf_info(env, attr, uattr);
14020 	if (ret < 0)
14021 		goto skip_full_check;
14022 
14023 	ret = check_attach_btf_id(env);
14024 	if (ret)
14025 		goto skip_full_check;
14026 
14027 	ret = resolve_pseudo_ldimm64(env);
14028 	if (ret < 0)
14029 		goto skip_full_check;
14030 
14031 	if (bpf_prog_is_dev_bound(env->prog->aux)) {
14032 		ret = bpf_prog_offload_verifier_prep(env->prog);
14033 		if (ret)
14034 			goto skip_full_check;
14035 	}
14036 
14037 	ret = check_cfg(env);
14038 	if (ret < 0)
14039 		goto skip_full_check;
14040 
14041 	ret = do_check_subprogs(env);
14042 	ret = ret ?: do_check_main(env);
14043 
14044 	if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14045 		ret = bpf_prog_offload_finalize(env);
14046 
14047 skip_full_check:
14048 	kvfree(env->explored_states);
14049 
14050 	if (ret == 0)
14051 		ret = check_max_stack_depth(env);
14052 
14053 	/* instruction rewrites happen after this point */
14054 	if (is_priv) {
14055 		if (ret == 0)
14056 			opt_hard_wire_dead_code_branches(env);
14057 		if (ret == 0)
14058 			ret = opt_remove_dead_code(env);
14059 		if (ret == 0)
14060 			ret = opt_remove_nops(env);
14061 	} else {
14062 		if (ret == 0)
14063 			sanitize_dead_code(env);
14064 	}
14065 
14066 	if (ret == 0)
14067 		/* program is valid, convert *(u32*)(ctx + off) accesses */
14068 		ret = convert_ctx_accesses(env);
14069 
14070 	if (ret == 0)
14071 		ret = do_misc_fixups(env);
14072 
14073 	/* do 32-bit optimization after insn patching has done so those patched
14074 	 * insns could be handled correctly.
14075 	 */
14076 	if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14077 		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14078 		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14079 								     : false;
14080 	}
14081 
14082 	if (ret == 0)
14083 		ret = fixup_call_args(env);
14084 
14085 	env->verification_time = ktime_get_ns() - start_time;
14086 	print_verification_stats(env);
14087 
14088 	if (log->level && bpf_verifier_log_full(log))
14089 		ret = -ENOSPC;
14090 	if (log->level && !log->ubuf) {
14091 		ret = -EFAULT;
14092 		goto err_release_maps;
14093 	}
14094 
14095 	if (ret)
14096 		goto err_release_maps;
14097 
14098 	if (env->used_map_cnt) {
14099 		/* if program passed verifier, update used_maps in bpf_prog_info */
14100 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14101 							  sizeof(env->used_maps[0]),
14102 							  GFP_KERNEL);
14103 
14104 		if (!env->prog->aux->used_maps) {
14105 			ret = -ENOMEM;
14106 			goto err_release_maps;
14107 		}
14108 
14109 		memcpy(env->prog->aux->used_maps, env->used_maps,
14110 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
14111 		env->prog->aux->used_map_cnt = env->used_map_cnt;
14112 	}
14113 	if (env->used_btf_cnt) {
14114 		/* if program passed verifier, update used_btfs in bpf_prog_aux */
14115 		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14116 							  sizeof(env->used_btfs[0]),
14117 							  GFP_KERNEL);
14118 		if (!env->prog->aux->used_btfs) {
14119 			ret = -ENOMEM;
14120 			goto err_release_maps;
14121 		}
14122 
14123 		memcpy(env->prog->aux->used_btfs, env->used_btfs,
14124 		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14125 		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14126 	}
14127 	if (env->used_map_cnt || env->used_btf_cnt) {
14128 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
14129 		 * bpf_ld_imm64 instructions
14130 		 */
14131 		convert_pseudo_ld_imm64(env);
14132 	}
14133 
14134 	adjust_btf_func(env);
14135 
14136 err_release_maps:
14137 	if (!env->prog->aux->used_maps)
14138 		/* if we didn't copy map pointers into bpf_prog_info, release
14139 		 * them now. Otherwise free_used_maps() will release them.
14140 		 */
14141 		release_maps(env);
14142 	if (!env->prog->aux->used_btfs)
14143 		release_btfs(env);
14144 
14145 	/* extension progs temporarily inherit the attach_type of their targets
14146 	   for verification purposes, so set it back to zero before returning
14147 	 */
14148 	if (env->prog->type == BPF_PROG_TYPE_EXT)
14149 		env->prog->expected_attach_type = 0;
14150 
14151 	*prog = env->prog;
14152 err_unlock:
14153 	if (!is_priv)
14154 		mutex_unlock(&bpf_verifier_lock);
14155 	vfree(env->insn_aux_data);
14156 err_free_env:
14157 	kfree(env);
14158 	return ret;
14159 }
14160