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 22/* Liveness marks, used for registers and spilled-regs (in stack slots). 23 * Read marks propagate upwards until they find a write mark; they record that 24 * "one of this state's descendants read this reg" (and therefore the reg is 25 * relevant for states_equal() checks). 26 * Write marks collect downwards and do not propagate; they record that "the 27 * straight-line code that reached this state (from its parent) wrote this reg" 28 * (and therefore that reads propagated from this state or its descendants 29 * should not propagate to its parent). 30 * A state with a write mark can receive read marks; it just won't propagate 31 * them to its parent, since the write mark is a property, not of the state, 32 * but of the link between it and its parent. See mark_reg_read() and 33 * mark_stack_slot_read() in kernel/bpf/verifier.c. 34 */ 35enum bpf_reg_liveness { 36 REG_LIVE_NONE = 0, /* reg hasn't been read or written this branch */ 37 REG_LIVE_READ32 = 0x1, /* reg was read, so we're sensitive to initial value */ 38 REG_LIVE_READ64 = 0x2, /* likewise, but full 64-bit content matters */ 39 REG_LIVE_READ = REG_LIVE_READ32 | REG_LIVE_READ64, 40 REG_LIVE_WRITTEN = 0x4, /* reg was written first, screening off later reads */ 41 REG_LIVE_DONE = 0x8, /* liveness won't be updating this register anymore */ 42}; 43 44struct bpf_reg_state { 45 /* Ordering of fields matters. See states_equal() */ 46 enum bpf_reg_type type; 47 /* Fixed part of pointer offset, pointer types only */ 48 s32 off; 49 union { 50 /* valid when type == PTR_TO_PACKET */ 51 int range; 52 53 /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE | 54 * PTR_TO_MAP_VALUE_OR_NULL 55 */ 56 struct bpf_map *map_ptr; 57 58 /* for PTR_TO_BTF_ID */ 59 struct { 60 struct btf *btf; 61 u32 btf_id; 62 }; 63 64 u32 mem_size; /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */ 65 66 /* Max size from any of the above. */ 67 struct { 68 unsigned long raw1; 69 unsigned long raw2; 70 } raw; 71 72 u32 subprogno; /* for PTR_TO_FUNC */ 73 }; 74 /* For PTR_TO_PACKET, used to find other pointers with the same variable 75 * offset, so they can share range knowledge. 76 * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we 77 * came from, when one is tested for != NULL. 78 * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation 79 * for the purpose of tracking that it's freed. 80 * For PTR_TO_SOCKET this is used to share which pointers retain the 81 * same reference to the socket, to determine proper reference freeing. 82 */ 83 u32 id; 84 /* PTR_TO_SOCKET and PTR_TO_TCP_SOCK could be a ptr returned 85 * from a pointer-cast helper, bpf_sk_fullsock() and 86 * bpf_tcp_sock(). 87 * 88 * Consider the following where "sk" is a reference counted 89 * pointer returned from "sk = bpf_sk_lookup_tcp();": 90 * 91 * 1: sk = bpf_sk_lookup_tcp(); 92 * 2: if (!sk) { return 0; } 93 * 3: fullsock = bpf_sk_fullsock(sk); 94 * 4: if (!fullsock) { bpf_sk_release(sk); return 0; } 95 * 5: tp = bpf_tcp_sock(fullsock); 96 * 6: if (!tp) { bpf_sk_release(sk); return 0; } 97 * 7: bpf_sk_release(sk); 98 * 8: snd_cwnd = tp->snd_cwnd; // verifier will complain 99 * 100 * After bpf_sk_release(sk) at line 7, both "fullsock" ptr and 101 * "tp" ptr should be invalidated also. In order to do that, 102 * the reg holding "fullsock" and "sk" need to remember 103 * the original refcounted ptr id (i.e. sk_reg->id) in ref_obj_id 104 * such that the verifier can reset all regs which have 105 * ref_obj_id matching the sk_reg->id. 106 * 107 * sk_reg->ref_obj_id is set to sk_reg->id at line 1. 108 * sk_reg->id will stay as NULL-marking purpose only. 109 * After NULL-marking is done, sk_reg->id can be reset to 0. 110 * 111 * After "fullsock = bpf_sk_fullsock(sk);" at line 3, 112 * fullsock_reg->ref_obj_id is set to sk_reg->ref_obj_id. 113 * 114 * After "tp = bpf_tcp_sock(fullsock);" at line 5, 115 * tp_reg->ref_obj_id is set to fullsock_reg->ref_obj_id 116 * which is the same as sk_reg->ref_obj_id. 117 * 118 * From the verifier perspective, if sk, fullsock and tp 119 * are not NULL, they are the same ptr with different 120 * reg->type. In particular, bpf_sk_release(tp) is also 121 * allowed and has the same effect as bpf_sk_release(sk). 122 */ 123 u32 ref_obj_id; 124 /* For scalar types (SCALAR_VALUE), this represents our knowledge of 125 * the actual value. 126 * For pointer types, this represents the variable part of the offset 127 * from the pointed-to object, and is shared with all bpf_reg_states 128 * with the same id as us. 129 */ 130 struct tnum var_off; 131 /* Used to determine if any memory access using this register will 132 * result in a bad access. 133 * These refer to the same value as var_off, not necessarily the actual 134 * contents of the register. 135 */ 136 s64 smin_value; /* minimum possible (s64)value */ 137 s64 smax_value; /* maximum possible (s64)value */ 138 u64 umin_value; /* minimum possible (u64)value */ 139 u64 umax_value; /* maximum possible (u64)value */ 140 s32 s32_min_value; /* minimum possible (s32)value */ 141 s32 s32_max_value; /* maximum possible (s32)value */ 142 u32 u32_min_value; /* minimum possible (u32)value */ 143 u32 u32_max_value; /* maximum possible (u32)value */ 144 /* parentage chain for liveness checking */ 145 struct bpf_reg_state *parent; 146 /* Inside the callee two registers can be both PTR_TO_STACK like 147 * R1=fp-8 and R2=fp-8, but one of them points to this function stack 148 * while another to the caller's stack. To differentiate them 'frameno' 149 * is used which is an index in bpf_verifier_state->frame[] array 150 * pointing to bpf_func_state. 151 */ 152 u32 frameno; 153 /* Tracks subreg definition. The stored value is the insn_idx of the 154 * writing insn. This is safe because subreg_def is used before any insn 155 * patching which only happens after main verification finished. 156 */ 157 s32 subreg_def; 158 enum bpf_reg_liveness live; 159 /* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */ 160 bool precise; 161}; 162 163enum bpf_stack_slot_type { 164 STACK_INVALID, /* nothing was stored in this stack slot */ 165 STACK_SPILL, /* register spilled into stack */ 166 STACK_MISC, /* BPF program wrote some data into this slot */ 167 STACK_ZERO, /* BPF program wrote constant zero */ 168}; 169 170#define BPF_REG_SIZE 8 /* size of eBPF register in bytes */ 171 172struct bpf_stack_state { 173 struct bpf_reg_state spilled_ptr; 174 u8 slot_type[BPF_REG_SIZE]; 175}; 176 177struct bpf_reference_state { 178 /* Track each reference created with a unique id, even if the same 179 * instruction creates the reference multiple times (eg, via CALL). 180 */ 181 int id; 182 /* Instruction where the allocation of this reference occurred. This 183 * is used purely to inform the user of a reference leak. 184 */ 185 int insn_idx; 186}; 187 188/* state of the program: 189 * type of all registers and stack info 190 */ 191struct bpf_func_state { 192 struct bpf_reg_state regs[MAX_BPF_REG]; 193 /* index of call instruction that called into this func */ 194 int callsite; 195 /* stack frame number of this function state from pov of 196 * enclosing bpf_verifier_state. 197 * 0 = main function, 1 = first callee. 198 */ 199 u32 frameno; 200 /* subprog number == index within subprog_info 201 * zero == main subprog 202 */ 203 u32 subprogno; 204 205 /* The following fields should be last. See copy_func_state() */ 206 int acquired_refs; 207 struct bpf_reference_state *refs; 208 int allocated_stack; 209 bool in_callback_fn; 210 struct bpf_stack_state *stack; 211}; 212 213struct bpf_idx_pair { 214 u32 prev_idx; 215 u32 idx; 216}; 217 218struct bpf_id_pair { 219 u32 old; 220 u32 cur; 221}; 222 223/* Maximum number of register states that can exist at once */ 224#define BPF_ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 225#define MAX_CALL_FRAMES 8 226struct bpf_verifier_state { 227 /* call stack tracking */ 228 struct bpf_func_state *frame[MAX_CALL_FRAMES]; 229 struct bpf_verifier_state *parent; 230 /* 231 * 'branches' field is the number of branches left to explore: 232 * 0 - all possible paths from this state reached bpf_exit or 233 * were safely pruned 234 * 1 - at least one path is being explored. 235 * This state hasn't reached bpf_exit 236 * 2 - at least two paths are being explored. 237 * This state is an immediate parent of two children. 238 * One is fallthrough branch with branches==1 and another 239 * state is pushed into stack (to be explored later) also with 240 * branches==1. The parent of this state has branches==1. 241 * The verifier state tree connected via 'parent' pointer looks like: 242 * 1 243 * 1 244 * 2 -> 1 (first 'if' pushed into stack) 245 * 1 246 * 2 -> 1 (second 'if' pushed into stack) 247 * 1 248 * 1 249 * 1 bpf_exit. 250 * 251 * Once do_check() reaches bpf_exit, it calls update_branch_counts() 252 * and the verifier state tree will look: 253 * 1 254 * 1 255 * 2 -> 1 (first 'if' pushed into stack) 256 * 1 257 * 1 -> 1 (second 'if' pushed into stack) 258 * 0 259 * 0 260 * 0 bpf_exit. 261 * After pop_stack() the do_check() will resume at second 'if'. 262 * 263 * If is_state_visited() sees a state with branches > 0 it means 264 * there is a loop. If such state is exactly equal to the current state 265 * it's an infinite loop. Note states_equal() checks for states 266 * equvalency, so two states being 'states_equal' does not mean 267 * infinite loop. The exact comparison is provided by 268 * states_maybe_looping() function. It's a stronger pre-check and 269 * much faster than states_equal(). 270 * 271 * This algorithm may not find all possible infinite loops or 272 * loop iteration count may be too high. 273 * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in. 274 */ 275 u32 branches; 276 u32 insn_idx; 277 u32 curframe; 278 u32 active_spin_lock; 279 bool speculative; 280 281 /* first and last insn idx of this verifier state */ 282 u32 first_insn_idx; 283 u32 last_insn_idx; 284 /* jmp history recorded from first to last. 285 * backtracking is using it to go from last to first. 286 * For most states jmp_history_cnt is [0-3]. 287 * For loops can go up to ~40. 288 */ 289 struct bpf_idx_pair *jmp_history; 290 u32 jmp_history_cnt; 291}; 292 293#define bpf_get_spilled_reg(slot, frame) \ 294 (((slot < frame->allocated_stack / BPF_REG_SIZE) && \ 295 (frame->stack[slot].slot_type[0] == STACK_SPILL)) \ 296 ? &frame->stack[slot].spilled_ptr : NULL) 297 298/* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */ 299#define bpf_for_each_spilled_reg(iter, frame, reg) \ 300 for (iter = 0, reg = bpf_get_spilled_reg(iter, frame); \ 301 iter < frame->allocated_stack / BPF_REG_SIZE; \ 302 iter++, reg = bpf_get_spilled_reg(iter, frame)) 303 304/* linked list of verifier states used to prune search */ 305struct bpf_verifier_state_list { 306 struct bpf_verifier_state state; 307 struct bpf_verifier_state_list *next; 308 int miss_cnt, hit_cnt; 309}; 310 311/* Possible states for alu_state member. */ 312#define BPF_ALU_SANITIZE_SRC (1U << 0) 313#define BPF_ALU_SANITIZE_DST (1U << 1) 314#define BPF_ALU_NEG_VALUE (1U << 2) 315#define BPF_ALU_NON_POINTER (1U << 3) 316#define BPF_ALU_IMMEDIATE (1U << 4) 317#define BPF_ALU_SANITIZE (BPF_ALU_SANITIZE_SRC | \ 318 BPF_ALU_SANITIZE_DST) 319 320struct bpf_insn_aux_data { 321 union { 322 enum bpf_reg_type ptr_type; /* pointer type for load/store insns */ 323 unsigned long map_ptr_state; /* pointer/poison value for maps */ 324 s32 call_imm; /* saved imm field of call insn */ 325 u32 alu_limit; /* limit for add/sub register with pointer */ 326 struct { 327 u32 map_index; /* index into used_maps[] */ 328 u32 map_off; /* offset from value base address */ 329 }; 330 struct { 331 enum bpf_reg_type reg_type; /* type of pseudo_btf_id */ 332 union { 333 struct { 334 struct btf *btf; 335 u32 btf_id; /* btf_id for struct typed var */ 336 }; 337 u32 mem_size; /* mem_size for non-struct typed var */ 338 }; 339 } btf_var; 340 }; 341 u64 map_key_state; /* constant (32 bit) key tracking for maps */ 342 int ctx_field_size; /* the ctx field size for load insn, maybe 0 */ 343 u32 seen; /* this insn was processed by the verifier at env->pass_cnt */ 344 bool sanitize_stack_spill; /* subject to Spectre v4 sanitation */ 345 bool zext_dst; /* this insn zero extends dst reg */ 346 u8 alu_state; /* used in combination with alu_limit */ 347 348 /* below fields are initialized once */ 349 unsigned int orig_idx; /* original instruction index */ 350 bool prune_point; 351}; 352 353#define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */ 354#define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */ 355 356#define BPF_VERIFIER_TMP_LOG_SIZE 1024 357 358struct bpf_verifier_log { 359 u32 level; 360 char kbuf[BPF_VERIFIER_TMP_LOG_SIZE]; 361 char __user *ubuf; 362 u32 len_used; 363 u32 len_total; 364}; 365 366static inline bool bpf_verifier_log_full(const struct bpf_verifier_log *log) 367{ 368 return log->len_used >= log->len_total - 1; 369} 370 371#define BPF_LOG_LEVEL1 1 372#define BPF_LOG_LEVEL2 2 373#define BPF_LOG_STATS 4 374#define BPF_LOG_LEVEL (BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2) 375#define BPF_LOG_MASK (BPF_LOG_LEVEL | BPF_LOG_STATS) 376#define BPF_LOG_KERNEL (BPF_LOG_MASK + 1) /* kernel internal flag */ 377 378static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log) 379{ 380 return log && 381 ((log->level && log->ubuf && !bpf_verifier_log_full(log)) || 382 log->level == BPF_LOG_KERNEL); 383} 384 385#define BPF_MAX_SUBPROGS 256 386 387struct bpf_subprog_info { 388 /* 'start' has to be the first field otherwise find_subprog() won't work */ 389 u32 start; /* insn idx of function entry point */ 390 u32 linfo_idx; /* The idx to the main_prog->aux->linfo */ 391 u16 stack_depth; /* max. stack depth used by this function */ 392 bool has_tail_call; 393 bool tail_call_reachable; 394 bool has_ld_abs; 395}; 396 397/* single container for all structs 398 * one verifier_env per bpf_check() call 399 */ 400struct bpf_verifier_env { 401 u32 insn_idx; 402 u32 prev_insn_idx; 403 struct bpf_prog *prog; /* eBPF program being verified */ 404 const struct bpf_verifier_ops *ops; 405 struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */ 406 int stack_size; /* number of states to be processed */ 407 bool strict_alignment; /* perform strict pointer alignment checks */ 408 bool test_state_freq; /* test verifier with different pruning frequency */ 409 struct bpf_verifier_state *cur_state; /* current verifier state */ 410 struct bpf_verifier_state_list **explored_states; /* search pruning optimization */ 411 struct bpf_verifier_state_list *free_list; 412 struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */ 413 struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */ 414 u32 used_map_cnt; /* number of used maps */ 415 u32 used_btf_cnt; /* number of used BTF objects */ 416 u32 id_gen; /* used to generate unique reg IDs */ 417 bool explore_alu_limits; 418 bool allow_ptr_leaks; 419 bool allow_uninit_stack; 420 bool allow_ptr_to_map_access; 421 bool bpf_capable; 422 bool bypass_spec_v1; 423 bool bypass_spec_v4; 424 bool seen_direct_write; 425 struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */ 426 const struct bpf_line_info *prev_linfo; 427 struct bpf_verifier_log log; 428 struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 1]; 429 struct bpf_id_pair idmap_scratch[BPF_ID_MAP_SIZE]; 430 struct { 431 int *insn_state; 432 int *insn_stack; 433 int cur_stack; 434 } cfg; 435 u32 pass_cnt; /* number of times do_check() was called */ 436 u32 subprog_cnt; 437 /* number of instructions analyzed by the verifier */ 438 u32 prev_insn_processed, insn_processed; 439 /* number of jmps, calls, exits analyzed so far */ 440 u32 prev_jmps_processed, jmps_processed; 441 /* total verification time */ 442 u64 verification_time; 443 /* maximum number of verifier states kept in 'branching' instructions */ 444 u32 max_states_per_insn; 445 /* total number of allocated verifier states */ 446 u32 total_states; 447 /* some states are freed during program analysis. 448 * this is peak number of states. this number dominates kernel 449 * memory consumption during verification 450 */ 451 u32 peak_states; 452 /* longest register parentage chain walked for liveness marking */ 453 u32 longest_mark_read_walk; 454 bpfptr_t fd_array; 455}; 456 457__printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log, 458 const char *fmt, va_list args); 459__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 460 const char *fmt, ...); 461__printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 462 const char *fmt, ...); 463 464static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env) 465{ 466 struct bpf_verifier_state *cur = env->cur_state; 467 468 return cur->frame[cur->curframe]; 469} 470 471static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env) 472{ 473 return cur_func(env)->regs; 474} 475 476int bpf_prog_offload_verifier_prep(struct bpf_prog *prog); 477int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env, 478 int insn_idx, int prev_insn_idx); 479int bpf_prog_offload_finalize(struct bpf_verifier_env *env); 480void 481bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off, 482 struct bpf_insn *insn); 483void 484bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt); 485 486int check_ctx_reg(struct bpf_verifier_env *env, 487 const struct bpf_reg_state *reg, int regno); 488int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 489 u32 regno, u32 mem_size); 490 491/* this lives here instead of in bpf.h because it needs to dereference tgt_prog */ 492static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog, 493 struct btf *btf, u32 btf_id) 494{ 495 if (tgt_prog) 496 return ((u64)tgt_prog->aux->id << 32) | btf_id; 497 else 498 return ((u64)btf_obj_id(btf) << 32) | 0x80000000 | btf_id; 499} 500 501/* unpack the IDs from the key as constructed above */ 502static inline void bpf_trampoline_unpack_key(u64 key, u32 *obj_id, u32 *btf_id) 503{ 504 if (obj_id) 505 *obj_id = key >> 32; 506 if (btf_id) 507 *btf_id = key & 0x7FFFFFFF; 508} 509 510int bpf_check_attach_target(struct bpf_verifier_log *log, 511 const struct bpf_prog *prog, 512 const struct bpf_prog *tgt_prog, 513 u32 btf_id, 514 struct bpf_attach_target_info *tgt_info); 515 516#endif /* _LINUX_BPF_VERIFIER_H */ 517