xref: /linux/include/linux/bpf_verifier.h (revision 02f8ca3d49055788f112c17052a3da65feb01835)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #ifndef _LINUX_BPF_VERIFIER_H
5 #define _LINUX_BPF_VERIFIER_H 1
6 
7 #include <linux/bpf.h> /* for enum bpf_reg_type */
8 #include <linux/btf.h> /* for struct btf and btf_id() */
9 #include <linux/filter.h> /* for MAX_BPF_STACK */
10 #include <linux/tnum.h>
11 
12 /* Maximum variable offset umax_value permitted when resolving memory accesses.
13  * In practice this is far bigger than any realistic pointer offset; this limit
14  * ensures that umax_value + (int)off + (int)size cannot overflow a u64.
15  */
16 #define BPF_MAX_VAR_OFF	(1 << 29)
17 /* Maximum variable size permitted for ARG_CONST_SIZE[_OR_ZERO].  This ensures
18  * that converting umax_value to int cannot overflow.
19  */
20 #define BPF_MAX_VAR_SIZ	(1 << 29)
21 /* size of tmp_str_buf in bpf_verifier.
22  * we need at least 306 bytes to fit full stack mask representation
23  * (in the "-8,-16,...,-512" form)
24  */
25 #define TMP_STR_BUF_LEN 320
26 
27 /* Liveness marks, used for registers and spilled-regs (in stack slots).
28  * Read marks propagate upwards until they find a write mark; they record that
29  * "one of this state's descendants read this reg" (and therefore the reg is
30  * relevant for states_equal() checks).
31  * Write marks collect downwards and do not propagate; they record that "the
32  * straight-line code that reached this state (from its parent) wrote this reg"
33  * (and therefore that reads propagated from this state or its descendants
34  * should not propagate to its parent).
35  * A state with a write mark can receive read marks; it just won't propagate
36  * them to its parent, since the write mark is a property, not of the state,
37  * but of the link between it and its parent.  See mark_reg_read() and
38  * mark_stack_slot_read() in kernel/bpf/verifier.c.
39  */
40 enum bpf_reg_liveness {
41 	REG_LIVE_NONE = 0, /* reg hasn't been read or written this branch */
42 	REG_LIVE_READ32 = 0x1, /* reg was read, so we're sensitive to initial value */
43 	REG_LIVE_READ64 = 0x2, /* likewise, but full 64-bit content matters */
44 	REG_LIVE_READ = REG_LIVE_READ32 | REG_LIVE_READ64,
45 	REG_LIVE_WRITTEN = 0x4, /* reg was written first, screening off later reads */
46 	REG_LIVE_DONE = 0x8, /* liveness won't be updating this register anymore */
47 };
48 
49 /* For every reg representing a map value or allocated object pointer,
50  * we consider the tuple of (ptr, id) for them to be unique in verifier
51  * context and conside them to not alias each other for the purposes of
52  * tracking lock state.
53  */
54 struct bpf_active_lock {
55 	/* This can either be reg->map_ptr or reg->btf. If ptr is NULL,
56 	 * there's no active lock held, and other fields have no
57 	 * meaning. If non-NULL, it indicates that a lock is held and
58 	 * id member has the reg->id of the register which can be >= 0.
59 	 */
60 	void *ptr;
61 	/* This will be reg->id */
62 	u32 id;
63 };
64 
65 #define ITER_PREFIX "bpf_iter_"
66 
67 enum bpf_iter_state {
68 	BPF_ITER_STATE_INVALID, /* for non-first slot */
69 	BPF_ITER_STATE_ACTIVE,
70 	BPF_ITER_STATE_DRAINED,
71 };
72 
73 struct bpf_reg_state {
74 	/* Ordering of fields matters.  See states_equal() */
75 	enum bpf_reg_type type;
76 	/*
77 	 * Fixed part of pointer offset, pointer types only.
78 	 * Or constant delta between "linked" scalars with the same ID.
79 	 */
80 	s32 off;
81 	union {
82 		/* valid when type == PTR_TO_PACKET */
83 		int range;
84 
85 		/* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
86 		 *   PTR_TO_MAP_VALUE_OR_NULL
87 		 */
88 		struct {
89 			struct bpf_map *map_ptr;
90 			/* To distinguish map lookups from outer map
91 			 * the map_uid is non-zero for registers
92 			 * pointing to inner maps.
93 			 */
94 			u32 map_uid;
95 		};
96 
97 		/* for PTR_TO_BTF_ID */
98 		struct {
99 			struct btf *btf;
100 			u32 btf_id;
101 		};
102 
103 		struct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */
104 			u32 mem_size;
105 			u32 dynptr_id; /* for dynptr slices */
106 		};
107 
108 		/* For dynptr stack slots */
109 		struct {
110 			enum bpf_dynptr_type type;
111 			/* A dynptr is 16 bytes so it takes up 2 stack slots.
112 			 * We need to track which slot is the first slot
113 			 * to protect against cases where the user may try to
114 			 * pass in an address starting at the second slot of the
115 			 * dynptr.
116 			 */
117 			bool first_slot;
118 		} dynptr;
119 
120 		/* For bpf_iter stack slots */
121 		struct {
122 			/* BTF container and BTF type ID describing
123 			 * struct bpf_iter_<type> of an iterator state
124 			 */
125 			struct btf *btf;
126 			u32 btf_id;
127 			/* packing following two fields to fit iter state into 16 bytes */
128 			enum bpf_iter_state state:2;
129 			int depth:30;
130 		} iter;
131 
132 		/* Max size from any of the above. */
133 		struct {
134 			unsigned long raw1;
135 			unsigned long raw2;
136 		} raw;
137 
138 		u32 subprogno; /* for PTR_TO_FUNC */
139 	};
140 	/* For scalar types (SCALAR_VALUE), this represents our knowledge of
141 	 * the actual value.
142 	 * For pointer types, this represents the variable part of the offset
143 	 * from the pointed-to object, and is shared with all bpf_reg_states
144 	 * with the same id as us.
145 	 */
146 	struct tnum var_off;
147 	/* Used to determine if any memory access using this register will
148 	 * result in a bad access.
149 	 * These refer to the same value as var_off, not necessarily the actual
150 	 * contents of the register.
151 	 */
152 	s64 smin_value; /* minimum possible (s64)value */
153 	s64 smax_value; /* maximum possible (s64)value */
154 	u64 umin_value; /* minimum possible (u64)value */
155 	u64 umax_value; /* maximum possible (u64)value */
156 	s32 s32_min_value; /* minimum possible (s32)value */
157 	s32 s32_max_value; /* maximum possible (s32)value */
158 	u32 u32_min_value; /* minimum possible (u32)value */
159 	u32 u32_max_value; /* maximum possible (u32)value */
160 	/* For PTR_TO_PACKET, used to find other pointers with the same variable
161 	 * offset, so they can share range knowledge.
162 	 * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we
163 	 * came from, when one is tested for != NULL.
164 	 * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation
165 	 * for the purpose of tracking that it's freed.
166 	 * For PTR_TO_SOCKET this is used to share which pointers retain the
167 	 * same reference to the socket, to determine proper reference freeing.
168 	 * For stack slots that are dynptrs, this is used to track references to
169 	 * the dynptr to determine proper reference freeing.
170 	 * Similarly to dynptrs, we use ID to track "belonging" of a reference
171 	 * to a specific instance of bpf_iter.
172 	 */
173 	/*
174 	 * Upper bit of ID is used to remember relationship between "linked"
175 	 * registers. Example:
176 	 * r1 = r2;    both will have r1->id == r2->id == N
177 	 * r1 += 10;   r1->id == N | BPF_ADD_CONST and r1->off == 10
178 	 */
179 #define BPF_ADD_CONST (1U << 31)
180 	u32 id;
181 	/* PTR_TO_SOCKET and PTR_TO_TCP_SOCK could be a ptr returned
182 	 * from a pointer-cast helper, bpf_sk_fullsock() and
183 	 * bpf_tcp_sock().
184 	 *
185 	 * Consider the following where "sk" is a reference counted
186 	 * pointer returned from "sk = bpf_sk_lookup_tcp();":
187 	 *
188 	 * 1: sk = bpf_sk_lookup_tcp();
189 	 * 2: if (!sk) { return 0; }
190 	 * 3: fullsock = bpf_sk_fullsock(sk);
191 	 * 4: if (!fullsock) { bpf_sk_release(sk); return 0; }
192 	 * 5: tp = bpf_tcp_sock(fullsock);
193 	 * 6: if (!tp) { bpf_sk_release(sk); return 0; }
194 	 * 7: bpf_sk_release(sk);
195 	 * 8: snd_cwnd = tp->snd_cwnd;  // verifier will complain
196 	 *
197 	 * After bpf_sk_release(sk) at line 7, both "fullsock" ptr and
198 	 * "tp" ptr should be invalidated also.  In order to do that,
199 	 * the reg holding "fullsock" and "sk" need to remember
200 	 * the original refcounted ptr id (i.e. sk_reg->id) in ref_obj_id
201 	 * such that the verifier can reset all regs which have
202 	 * ref_obj_id matching the sk_reg->id.
203 	 *
204 	 * sk_reg->ref_obj_id is set to sk_reg->id at line 1.
205 	 * sk_reg->id will stay as NULL-marking purpose only.
206 	 * After NULL-marking is done, sk_reg->id can be reset to 0.
207 	 *
208 	 * After "fullsock = bpf_sk_fullsock(sk);" at line 3,
209 	 * fullsock_reg->ref_obj_id is set to sk_reg->ref_obj_id.
210 	 *
211 	 * After "tp = bpf_tcp_sock(fullsock);" at line 5,
212 	 * tp_reg->ref_obj_id is set to fullsock_reg->ref_obj_id
213 	 * which is the same as sk_reg->ref_obj_id.
214 	 *
215 	 * From the verifier perspective, if sk, fullsock and tp
216 	 * are not NULL, they are the same ptr with different
217 	 * reg->type.  In particular, bpf_sk_release(tp) is also
218 	 * allowed and has the same effect as bpf_sk_release(sk).
219 	 */
220 	u32 ref_obj_id;
221 	/* parentage chain for liveness checking */
222 	struct bpf_reg_state *parent;
223 	/* Inside the callee two registers can be both PTR_TO_STACK like
224 	 * R1=fp-8 and R2=fp-8, but one of them points to this function stack
225 	 * while another to the caller's stack. To differentiate them 'frameno'
226 	 * is used which is an index in bpf_verifier_state->frame[] array
227 	 * pointing to bpf_func_state.
228 	 */
229 	u32 frameno;
230 	/* Tracks subreg definition. The stored value is the insn_idx of the
231 	 * writing insn. This is safe because subreg_def is used before any insn
232 	 * patching which only happens after main verification finished.
233 	 */
234 	s32 subreg_def;
235 	enum bpf_reg_liveness live;
236 	/* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
237 	bool precise;
238 };
239 
240 enum bpf_stack_slot_type {
241 	STACK_INVALID,    /* nothing was stored in this stack slot */
242 	STACK_SPILL,      /* register spilled into stack */
243 	STACK_MISC,	  /* BPF program wrote some data into this slot */
244 	STACK_ZERO,	  /* BPF program wrote constant zero */
245 	/* A dynptr is stored in this stack slot. The type of dynptr
246 	 * is stored in bpf_stack_state->spilled_ptr.dynptr.type
247 	 */
248 	STACK_DYNPTR,
249 	STACK_ITER,
250 };
251 
252 #define BPF_REG_SIZE 8	/* size of eBPF register in bytes */
253 
254 #define BPF_REGMASK_ARGS ((1 << BPF_REG_1) | (1 << BPF_REG_2) | \
255 			  (1 << BPF_REG_3) | (1 << BPF_REG_4) | \
256 			  (1 << BPF_REG_5))
257 
258 #define BPF_DYNPTR_SIZE		sizeof(struct bpf_dynptr_kern)
259 #define BPF_DYNPTR_NR_SLOTS		(BPF_DYNPTR_SIZE / BPF_REG_SIZE)
260 
261 struct bpf_stack_state {
262 	struct bpf_reg_state spilled_ptr;
263 	u8 slot_type[BPF_REG_SIZE];
264 };
265 
266 struct bpf_reference_state {
267 	/* Track each reference created with a unique id, even if the same
268 	 * instruction creates the reference multiple times (eg, via CALL).
269 	 */
270 	int id;
271 	/* Instruction where the allocation of this reference occurred. This
272 	 * is used purely to inform the user of a reference leak.
273 	 */
274 	int insn_idx;
275 	/* There can be a case like:
276 	 * main (frame 0)
277 	 *  cb (frame 1)
278 	 *   func (frame 3)
279 	 *    cb (frame 4)
280 	 * Hence for frame 4, if callback_ref just stored boolean, it would be
281 	 * impossible to distinguish nested callback refs. Hence store the
282 	 * frameno and compare that to callback_ref in check_reference_leak when
283 	 * exiting a callback function.
284 	 */
285 	int callback_ref;
286 };
287 
288 struct bpf_retval_range {
289 	s32 minval;
290 	s32 maxval;
291 };
292 
293 /* state of the program:
294  * type of all registers and stack info
295  */
296 struct bpf_func_state {
297 	struct bpf_reg_state regs[MAX_BPF_REG];
298 	/* index of call instruction that called into this func */
299 	int callsite;
300 	/* stack frame number of this function state from pov of
301 	 * enclosing bpf_verifier_state.
302 	 * 0 = main function, 1 = first callee.
303 	 */
304 	u32 frameno;
305 	/* subprog number == index within subprog_info
306 	 * zero == main subprog
307 	 */
308 	u32 subprogno;
309 	/* Every bpf_timer_start will increment async_entry_cnt.
310 	 * It's used to distinguish:
311 	 * void foo(void) { for(;;); }
312 	 * void foo(void) { bpf_timer_set_callback(,foo); }
313 	 */
314 	u32 async_entry_cnt;
315 	struct bpf_retval_range callback_ret_range;
316 	bool in_callback_fn;
317 	bool in_async_callback_fn;
318 	bool in_exception_callback_fn;
319 	/* For callback calling functions that limit number of possible
320 	 * callback executions (e.g. bpf_loop) keeps track of current
321 	 * simulated iteration number.
322 	 * Value in frame N refers to number of times callback with frame
323 	 * N+1 was simulated, e.g. for the following call:
324 	 *
325 	 *   bpf_loop(..., fn, ...); | suppose current frame is N
326 	 *                           | fn would be simulated in frame N+1
327 	 *                           | number of simulations is tracked in frame N
328 	 */
329 	u32 callback_depth;
330 
331 	/* The following fields should be last. See copy_func_state() */
332 	int acquired_refs;
333 	struct bpf_reference_state *refs;
334 	/* The state of the stack. Each element of the array describes BPF_REG_SIZE
335 	 * (i.e. 8) bytes worth of stack memory.
336 	 * stack[0] represents bytes [*(r10-8)..*(r10-1)]
337 	 * stack[1] represents bytes [*(r10-16)..*(r10-9)]
338 	 * ...
339 	 * stack[allocated_stack/8 - 1] represents [*(r10-allocated_stack)..*(r10-allocated_stack+7)]
340 	 */
341 	struct bpf_stack_state *stack;
342 	/* Size of the current stack, in bytes. The stack state is tracked below, in
343 	 * `stack`. allocated_stack is always a multiple of BPF_REG_SIZE.
344 	 */
345 	int allocated_stack;
346 };
347 
348 #define MAX_CALL_FRAMES 8
349 
350 /* instruction history flags, used in bpf_jmp_history_entry.flags field */
351 enum {
352 	/* instruction references stack slot through PTR_TO_STACK register;
353 	 * we also store stack's frame number in lower 3 bits (MAX_CALL_FRAMES is 8)
354 	 * and accessed stack slot's index in next 6 bits (MAX_BPF_STACK is 512,
355 	 * 8 bytes per slot, so slot index (spi) is [0, 63])
356 	 */
357 	INSN_F_FRAMENO_MASK = 0x7, /* 3 bits */
358 
359 	INSN_F_SPI_MASK = 0x3f, /* 6 bits */
360 	INSN_F_SPI_SHIFT = 3, /* shifted 3 bits to the left */
361 
362 	INSN_F_STACK_ACCESS = BIT(9), /* we need 10 bits total */
363 };
364 
365 static_assert(INSN_F_FRAMENO_MASK + 1 >= MAX_CALL_FRAMES);
366 static_assert(INSN_F_SPI_MASK + 1 >= MAX_BPF_STACK / 8);
367 
368 struct bpf_jmp_history_entry {
369 	u32 idx;
370 	/* insn idx can't be bigger than 1 million */
371 	u32 prev_idx : 22;
372 	/* special flags, e.g., whether insn is doing register stack spill/load */
373 	u32 flags : 10;
374 };
375 
376 /* Maximum number of register states that can exist at once */
377 #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) * MAX_CALL_FRAMES)
378 struct bpf_verifier_state {
379 	/* call stack tracking */
380 	struct bpf_func_state *frame[MAX_CALL_FRAMES];
381 	struct bpf_verifier_state *parent;
382 	/*
383 	 * 'branches' field is the number of branches left to explore:
384 	 * 0 - all possible paths from this state reached bpf_exit or
385 	 * were safely pruned
386 	 * 1 - at least one path is being explored.
387 	 * This state hasn't reached bpf_exit
388 	 * 2 - at least two paths are being explored.
389 	 * This state is an immediate parent of two children.
390 	 * One is fallthrough branch with branches==1 and another
391 	 * state is pushed into stack (to be explored later) also with
392 	 * branches==1. The parent of this state has branches==1.
393 	 * The verifier state tree connected via 'parent' pointer looks like:
394 	 * 1
395 	 * 1
396 	 * 2 -> 1 (first 'if' pushed into stack)
397 	 * 1
398 	 * 2 -> 1 (second 'if' pushed into stack)
399 	 * 1
400 	 * 1
401 	 * 1 bpf_exit.
402 	 *
403 	 * Once do_check() reaches bpf_exit, it calls update_branch_counts()
404 	 * and the verifier state tree will look:
405 	 * 1
406 	 * 1
407 	 * 2 -> 1 (first 'if' pushed into stack)
408 	 * 1
409 	 * 1 -> 1 (second 'if' pushed into stack)
410 	 * 0
411 	 * 0
412 	 * 0 bpf_exit.
413 	 * After pop_stack() the do_check() will resume at second 'if'.
414 	 *
415 	 * If is_state_visited() sees a state with branches > 0 it means
416 	 * there is a loop. If such state is exactly equal to the current state
417 	 * it's an infinite loop. Note states_equal() checks for states
418 	 * equivalency, so two states being 'states_equal' does not mean
419 	 * infinite loop. The exact comparison is provided by
420 	 * states_maybe_looping() function. It's a stronger pre-check and
421 	 * much faster than states_equal().
422 	 *
423 	 * This algorithm may not find all possible infinite loops or
424 	 * loop iteration count may be too high.
425 	 * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in.
426 	 */
427 	u32 branches;
428 	u32 insn_idx;
429 	u32 curframe;
430 
431 	struct bpf_active_lock active_lock;
432 	bool speculative;
433 	bool active_rcu_lock;
434 	u32 active_preempt_lock;
435 	/* If this state was ever pointed-to by other state's loop_entry field
436 	 * this flag would be set to true. Used to avoid freeing such states
437 	 * while they are still in use.
438 	 */
439 	bool used_as_loop_entry;
440 	bool in_sleepable;
441 
442 	/* first and last insn idx of this verifier state */
443 	u32 first_insn_idx;
444 	u32 last_insn_idx;
445 	/* If this state is a part of states loop this field points to some
446 	 * parent of this state such that:
447 	 * - it is also a member of the same states loop;
448 	 * - DFS states traversal starting from initial state visits loop_entry
449 	 *   state before this state.
450 	 * Used to compute topmost loop entry for state loops.
451 	 * State loops might appear because of open coded iterators logic.
452 	 * See get_loop_entry() for more information.
453 	 */
454 	struct bpf_verifier_state *loop_entry;
455 	/* jmp history recorded from first to last.
456 	 * backtracking is using it to go from last to first.
457 	 * For most states jmp_history_cnt is [0-3].
458 	 * For loops can go up to ~40.
459 	 */
460 	struct bpf_jmp_history_entry *jmp_history;
461 	u32 jmp_history_cnt;
462 	u32 dfs_depth;
463 	u32 callback_unroll_depth;
464 	u32 may_goto_depth;
465 };
466 
467 #define bpf_get_spilled_reg(slot, frame, mask)				\
468 	(((slot < frame->allocated_stack / BPF_REG_SIZE) &&		\
469 	  ((1 << frame->stack[slot].slot_type[BPF_REG_SIZE - 1]) & (mask))) \
470 	 ? &frame->stack[slot].spilled_ptr : NULL)
471 
472 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */
473 #define bpf_for_each_spilled_reg(iter, frame, reg, mask)			\
474 	for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask);		\
475 	     iter < frame->allocated_stack / BPF_REG_SIZE;		\
476 	     iter++, reg = bpf_get_spilled_reg(iter, frame, mask))
477 
478 #define bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, __mask, __expr)   \
479 	({                                                               \
480 		struct bpf_verifier_state *___vstate = __vst;            \
481 		int ___i, ___j;                                          \
482 		for (___i = 0; ___i <= ___vstate->curframe; ___i++) {    \
483 			struct bpf_reg_state *___regs;                   \
484 			__state = ___vstate->frame[___i];                \
485 			___regs = __state->regs;                         \
486 			for (___j = 0; ___j < MAX_BPF_REG; ___j++) {     \
487 				__reg = &___regs[___j];                  \
488 				(void)(__expr);                          \
489 			}                                                \
490 			bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \
491 				if (!__reg)                              \
492 					continue;                        \
493 				(void)(__expr);                          \
494 			}                                                \
495 		}                                                        \
496 	})
497 
498 /* Invoke __expr over regsiters in __vst, setting __state and __reg */
499 #define bpf_for_each_reg_in_vstate(__vst, __state, __reg, __expr) \
500 	bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, 1 << STACK_SPILL, __expr)
501 
502 /* linked list of verifier states used to prune search */
503 struct bpf_verifier_state_list {
504 	struct bpf_verifier_state state;
505 	struct bpf_verifier_state_list *next;
506 	int miss_cnt, hit_cnt;
507 };
508 
509 struct bpf_loop_inline_state {
510 	unsigned int initialized:1; /* set to true upon first entry */
511 	unsigned int fit_for_inline:1; /* true if callback function is the same
512 					* at each call and flags are always zero
513 					*/
514 	u32 callback_subprogno; /* valid when fit_for_inline is true */
515 };
516 
517 /* pointer and state for maps */
518 struct bpf_map_ptr_state {
519 	struct bpf_map *map_ptr;
520 	bool poison;
521 	bool unpriv;
522 };
523 
524 /* Possible states for alu_state member. */
525 #define BPF_ALU_SANITIZE_SRC		(1U << 0)
526 #define BPF_ALU_SANITIZE_DST		(1U << 1)
527 #define BPF_ALU_NEG_VALUE		(1U << 2)
528 #define BPF_ALU_NON_POINTER		(1U << 3)
529 #define BPF_ALU_IMMEDIATE		(1U << 4)
530 #define BPF_ALU_SANITIZE		(BPF_ALU_SANITIZE_SRC | \
531 					 BPF_ALU_SANITIZE_DST)
532 
533 struct bpf_insn_aux_data {
534 	union {
535 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
536 		struct bpf_map_ptr_state map_ptr_state;
537 		s32 call_imm;			/* saved imm field of call insn */
538 		u32 alu_limit;			/* limit for add/sub register with pointer */
539 		struct {
540 			u32 map_index;		/* index into used_maps[] */
541 			u32 map_off;		/* offset from value base address */
542 		};
543 		struct {
544 			enum bpf_reg_type reg_type;	/* type of pseudo_btf_id */
545 			union {
546 				struct {
547 					struct btf *btf;
548 					u32 btf_id;	/* btf_id for struct typed var */
549 				};
550 				u32 mem_size;	/* mem_size for non-struct typed var */
551 			};
552 		} btf_var;
553 		/* if instruction is a call to bpf_loop this field tracks
554 		 * the state of the relevant registers to make decision about inlining
555 		 */
556 		struct bpf_loop_inline_state loop_inline_state;
557 	};
558 	union {
559 		/* remember the size of type passed to bpf_obj_new to rewrite R1 */
560 		u64 obj_new_size;
561 		/* remember the offset of node field within type to rewrite */
562 		u64 insert_off;
563 	};
564 	struct btf_struct_meta *kptr_struct_meta;
565 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
566 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
567 	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
568 	bool sanitize_stack_spill; /* subject to Spectre v4 sanitation */
569 	bool zext_dst; /* this insn zero extends dst reg */
570 	bool needs_zext; /* alu op needs to clear upper bits */
571 	bool storage_get_func_atomic; /* bpf_*_storage_get() with atomic memory alloc */
572 	bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */
573 	bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */
574 	u8 alu_state; /* used in combination with alu_limit */
575 
576 	/* below fields are initialized once */
577 	unsigned int orig_idx; /* original instruction index */
578 	bool jmp_point;
579 	bool prune_point;
580 	/* ensure we check state equivalence and save state checkpoint and
581 	 * this instruction, regardless of any heuristics
582 	 */
583 	bool force_checkpoint;
584 	/* true if instruction is a call to a helper function that
585 	 * accepts callback function as a parameter.
586 	 */
587 	bool calls_callback;
588 };
589 
590 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
591 #define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */
592 
593 #define BPF_VERIFIER_TMP_LOG_SIZE	1024
594 
595 struct bpf_verifier_log {
596 	/* Logical start and end positions of a "log window" of the verifier log.
597 	 * start_pos == 0 means we haven't truncated anything.
598 	 * Once truncation starts to happen, start_pos + len_total == end_pos,
599 	 * except during log reset situations, in which (end_pos - start_pos)
600 	 * might get smaller than len_total (see bpf_vlog_reset()).
601 	 * Generally, (end_pos - start_pos) gives number of useful data in
602 	 * user log buffer.
603 	 */
604 	u64 start_pos;
605 	u64 end_pos;
606 	char __user *ubuf;
607 	u32 level;
608 	u32 len_total;
609 	u32 len_max;
610 	char kbuf[BPF_VERIFIER_TMP_LOG_SIZE];
611 };
612 
613 #define BPF_LOG_LEVEL1	1
614 #define BPF_LOG_LEVEL2	2
615 #define BPF_LOG_STATS	4
616 #define BPF_LOG_FIXED	8
617 #define BPF_LOG_LEVEL	(BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2)
618 #define BPF_LOG_MASK	(BPF_LOG_LEVEL | BPF_LOG_STATS | BPF_LOG_FIXED)
619 #define BPF_LOG_KERNEL	(BPF_LOG_MASK + 1) /* kernel internal flag */
620 #define BPF_LOG_MIN_ALIGNMENT 8U
621 #define BPF_LOG_ALIGNMENT 40U
622 
bpf_verifier_log_needed(const struct bpf_verifier_log * log)623 static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log)
624 {
625 	return log && log->level;
626 }
627 
628 #define BPF_MAX_SUBPROGS 256
629 
630 struct bpf_subprog_arg_info {
631 	enum bpf_arg_type arg_type;
632 	union {
633 		u32 mem_size;
634 		u32 btf_id;
635 	};
636 };
637 
638 struct bpf_subprog_info {
639 	/* 'start' has to be the first field otherwise find_subprog() won't work */
640 	u32 start; /* insn idx of function entry point */
641 	u32 linfo_idx; /* The idx to the main_prog->aux->linfo */
642 	u16 stack_depth; /* max. stack depth used by this function */
643 	u16 stack_extra;
644 	bool has_tail_call: 1;
645 	bool tail_call_reachable: 1;
646 	bool has_ld_abs: 1;
647 	bool is_cb: 1;
648 	bool is_async_cb: 1;
649 	bool is_exception_cb: 1;
650 	bool args_cached: 1;
651 
652 	u8 arg_cnt;
653 	struct bpf_subprog_arg_info args[MAX_BPF_FUNC_REG_ARGS];
654 };
655 
656 struct bpf_verifier_env;
657 
658 struct backtrack_state {
659 	struct bpf_verifier_env *env;
660 	u32 frame;
661 	u32 reg_masks[MAX_CALL_FRAMES];
662 	u64 stack_masks[MAX_CALL_FRAMES];
663 };
664 
665 struct bpf_id_pair {
666 	u32 old;
667 	u32 cur;
668 };
669 
670 struct bpf_idmap {
671 	u32 tmp_id_gen;
672 	struct bpf_id_pair map[BPF_ID_MAP_SIZE];
673 };
674 
675 struct bpf_idset {
676 	u32 count;
677 	u32 ids[BPF_ID_MAP_SIZE];
678 };
679 
680 /* single container for all structs
681  * one verifier_env per bpf_check() call
682  */
683 struct bpf_verifier_env {
684 	u32 insn_idx;
685 	u32 prev_insn_idx;
686 	struct bpf_prog *prog;		/* eBPF program being verified */
687 	const struct bpf_verifier_ops *ops;
688 	struct module *attach_btf_mod;	/* The owner module of prog->aux->attach_btf */
689 	struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */
690 	int stack_size;			/* number of states to be processed */
691 	bool strict_alignment;		/* perform strict pointer alignment checks */
692 	bool test_state_freq;		/* test verifier with different pruning frequency */
693 	bool test_reg_invariants;	/* fail verification on register invariants violations */
694 	struct bpf_verifier_state *cur_state; /* current verifier state */
695 	struct bpf_verifier_state_list **explored_states; /* search pruning optimization */
696 	struct bpf_verifier_state_list *free_list;
697 	struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
698 	struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */
699 	u32 used_map_cnt;		/* number of used maps */
700 	u32 used_btf_cnt;		/* number of used BTF objects */
701 	u32 id_gen;			/* used to generate unique reg IDs */
702 	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
703 	int exception_callback_subprog;
704 	bool explore_alu_limits;
705 	bool allow_ptr_leaks;
706 	/* Allow access to uninitialized stack memory. Writes with fixed offset are
707 	 * always allowed, so this refers to reads (with fixed or variable offset),
708 	 * to writes with variable offset and to indirect (helper) accesses.
709 	 */
710 	bool allow_uninit_stack;
711 	bool bpf_capable;
712 	bool bypass_spec_v1;
713 	bool bypass_spec_v4;
714 	bool seen_direct_write;
715 	bool seen_exception;
716 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
717 	const struct bpf_line_info *prev_linfo;
718 	struct bpf_verifier_log log;
719 	struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
720 	union {
721 		struct bpf_idmap idmap_scratch;
722 		struct bpf_idset idset_scratch;
723 	};
724 	struct {
725 		int *insn_state;
726 		int *insn_stack;
727 		int cur_stack;
728 	} cfg;
729 	struct backtrack_state bt;
730 	struct bpf_jmp_history_entry *cur_hist_ent;
731 	u32 pass_cnt; /* number of times do_check() was called */
732 	u32 subprog_cnt;
733 	/* number of instructions analyzed by the verifier */
734 	u32 prev_insn_processed, insn_processed;
735 	/* number of jmps, calls, exits analyzed so far */
736 	u32 prev_jmps_processed, jmps_processed;
737 	/* total verification time */
738 	u64 verification_time;
739 	/* maximum number of verifier states kept in 'branching' instructions */
740 	u32 max_states_per_insn;
741 	/* total number of allocated verifier states */
742 	u32 total_states;
743 	/* some states are freed during program analysis.
744 	 * this is peak number of states. this number dominates kernel
745 	 * memory consumption during verification
746 	 */
747 	u32 peak_states;
748 	/* longest register parentage chain walked for liveness marking */
749 	u32 longest_mark_read_walk;
750 	bpfptr_t fd_array;
751 
752 	/* bit mask to keep track of whether a register has been accessed
753 	 * since the last time the function state was printed
754 	 */
755 	u32 scratched_regs;
756 	/* Same as scratched_regs but for stack slots */
757 	u64 scratched_stack_slots;
758 	u64 prev_log_pos, prev_insn_print_pos;
759 	/* buffer used to temporary hold constants as scalar registers */
760 	struct bpf_reg_state fake_reg[2];
761 	/* buffer used to generate temporary string representations,
762 	 * e.g., in reg_type_str() to generate reg_type string
763 	 */
764 	char tmp_str_buf[TMP_STR_BUF_LEN];
765 };
766 
subprog_aux(struct bpf_verifier_env * env,int subprog)767 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
768 {
769 	return &env->prog->aux->func_info_aux[subprog];
770 }
771 
subprog_info(struct bpf_verifier_env * env,int subprog)772 static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env, int subprog)
773 {
774 	return &env->subprog_info[subprog];
775 }
776 
777 __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,
778 				      const char *fmt, va_list args);
779 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
780 					   const char *fmt, ...);
781 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
782 			    const char *fmt, ...);
783 int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level,
784 		  char __user *log_buf, u32 log_size);
785 void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos);
786 int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual);
787 
788 __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
789 				  u32 insn_off,
790 				  const char *prefix_fmt, ...);
791 
cur_func(struct bpf_verifier_env * env)792 static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env)
793 {
794 	struct bpf_verifier_state *cur = env->cur_state;
795 
796 	return cur->frame[cur->curframe];
797 }
798 
cur_regs(struct bpf_verifier_env * env)799 static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env)
800 {
801 	return cur_func(env)->regs;
802 }
803 
804 int bpf_prog_offload_verifier_prep(struct bpf_prog *prog);
805 int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env,
806 				 int insn_idx, int prev_insn_idx);
807 int bpf_prog_offload_finalize(struct bpf_verifier_env *env);
808 void
809 bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off,
810 			      struct bpf_insn *insn);
811 void
812 bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt);
813 
814 /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */
bpf_trampoline_compute_key(const struct bpf_prog * tgt_prog,struct btf * btf,u32 btf_id)815 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
816 					     struct btf *btf, u32 btf_id)
817 {
818 	if (tgt_prog)
819 		return ((u64)tgt_prog->aux->id << 32) | btf_id;
820 	else
821 		return ((u64)btf_obj_id(btf) << 32) | 0x80000000 | btf_id;
822 }
823 
824 /* unpack the IDs from the key as constructed above */
bpf_trampoline_unpack_key(u64 key,u32 * obj_id,u32 * btf_id)825 static inline void bpf_trampoline_unpack_key(u64 key, u32 *obj_id, u32 *btf_id)
826 {
827 	if (obj_id)
828 		*obj_id = key >> 32;
829 	if (btf_id)
830 		*btf_id = key & 0x7FFFFFFF;
831 }
832 
833 int bpf_check_attach_target(struct bpf_verifier_log *log,
834 			    const struct bpf_prog *prog,
835 			    const struct bpf_prog *tgt_prog,
836 			    u32 btf_id,
837 			    struct bpf_attach_target_info *tgt_info);
838 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
839 
840 int mark_chain_precision(struct bpf_verifier_env *env, int regno);
841 
842 #define BPF_BASE_TYPE_MASK	GENMASK(BPF_BASE_TYPE_BITS - 1, 0)
843 
844 /* extract base type from bpf_{arg, return, reg}_type. */
base_type(u32 type)845 static inline u32 base_type(u32 type)
846 {
847 	return type & BPF_BASE_TYPE_MASK;
848 }
849 
850 /* extract flags from an extended type. See bpf_type_flag in bpf.h. */
type_flag(u32 type)851 static inline u32 type_flag(u32 type)
852 {
853 	return type & ~BPF_BASE_TYPE_MASK;
854 }
855 
856 /* only use after check_attach_btf_id() */
resolve_prog_type(const struct bpf_prog * prog)857 static inline enum bpf_prog_type resolve_prog_type(const struct bpf_prog *prog)
858 {
859 	return (prog->type == BPF_PROG_TYPE_EXT && prog->aux->saved_dst_prog_type) ?
860 		prog->aux->saved_dst_prog_type : prog->type;
861 }
862 
bpf_prog_check_recur(const struct bpf_prog * prog)863 static inline bool bpf_prog_check_recur(const struct bpf_prog *prog)
864 {
865 	switch (resolve_prog_type(prog)) {
866 	case BPF_PROG_TYPE_TRACING:
867 		return prog->expected_attach_type != BPF_TRACE_ITER;
868 	case BPF_PROG_TYPE_STRUCT_OPS:
869 	case BPF_PROG_TYPE_LSM:
870 		return false;
871 	default:
872 		return true;
873 	}
874 }
875 
876 #define BPF_REG_TRUSTED_MODIFIERS (MEM_ALLOC | PTR_TRUSTED | NON_OWN_REF)
877 
bpf_type_has_unsafe_modifiers(u32 type)878 static inline bool bpf_type_has_unsafe_modifiers(u32 type)
879 {
880 	return type_flag(type) & ~BPF_REG_TRUSTED_MODIFIERS;
881 }
882 
type_is_ptr_alloc_obj(u32 type)883 static inline bool type_is_ptr_alloc_obj(u32 type)
884 {
885 	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
886 }
887 
type_is_non_owning_ref(u32 type)888 static inline bool type_is_non_owning_ref(u32 type)
889 {
890 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
891 }
892 
type_is_pkt_pointer(enum bpf_reg_type type)893 static inline bool type_is_pkt_pointer(enum bpf_reg_type type)
894 {
895 	type = base_type(type);
896 	return type == PTR_TO_PACKET ||
897 	       type == PTR_TO_PACKET_META;
898 }
899 
type_is_sk_pointer(enum bpf_reg_type type)900 static inline bool type_is_sk_pointer(enum bpf_reg_type type)
901 {
902 	return type == PTR_TO_SOCKET ||
903 		type == PTR_TO_SOCK_COMMON ||
904 		type == PTR_TO_TCP_SOCK ||
905 		type == PTR_TO_XDP_SOCK;
906 }
907 
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)908 static inline void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
909 {
910 	env->scratched_regs |= 1U << regno;
911 }
912 
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)913 static inline void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
914 {
915 	env->scratched_stack_slots |= 1ULL << spi;
916 }
917 
reg_scratched(const struct bpf_verifier_env * env,u32 regno)918 static inline bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
919 {
920 	return (env->scratched_regs >> regno) & 1;
921 }
922 
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)923 static inline bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
924 {
925 	return (env->scratched_stack_slots >> regno) & 1;
926 }
927 
verifier_state_scratched(const struct bpf_verifier_env * env)928 static inline bool verifier_state_scratched(const struct bpf_verifier_env *env)
929 {
930 	return env->scratched_regs || env->scratched_stack_slots;
931 }
932 
mark_verifier_state_clean(struct bpf_verifier_env * env)933 static inline void mark_verifier_state_clean(struct bpf_verifier_env *env)
934 {
935 	env->scratched_regs = 0U;
936 	env->scratched_stack_slots = 0ULL;
937 }
938 
939 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)940 static inline void mark_verifier_state_scratched(struct bpf_verifier_env *env)
941 {
942 	env->scratched_regs = ~0U;
943 	env->scratched_stack_slots = ~0ULL;
944 }
945 
bpf_stack_narrow_access_ok(int off,int fill_size,int spill_size)946 static inline bool bpf_stack_narrow_access_ok(int off, int fill_size, int spill_size)
947 {
948 #ifdef __BIG_ENDIAN
949 	off -= spill_size - fill_size;
950 #endif
951 
952 	return !(off % BPF_REG_SIZE);
953 }
954 
955 const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type);
956 const char *dynptr_type_str(enum bpf_dynptr_type type);
957 const char *iter_type_str(const struct btf *btf, u32 btf_id);
958 const char *iter_state_str(enum bpf_iter_state state);
959 
960 void print_verifier_state(struct bpf_verifier_env *env,
961 			  const struct bpf_func_state *state, bool print_all);
962 void print_insn_state(struct bpf_verifier_env *env, const struct bpf_func_state *state);
963 
964 #endif /* _LINUX_BPF_VERIFIER_H */
965