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/bpf-cgroup.h> 8 #include <linux/count_zeros.h> 9 #include <linux/kernel.h> 10 #include <linux/types.h> 11 #include <linux/slab.h> 12 #include <linux/bpf.h> 13 #include <linux/btf.h> 14 #include <linux/bpf_verifier.h> 15 #include <linux/filter.h> 16 #include <net/netlink.h> 17 #include <linux/file.h> 18 #include <linux/vmalloc.h> 19 #include <linux/stringify.h> 20 #include <linux/bsearch.h> 21 #include <linux/sort.h> 22 #include <linux/perf_event.h> 23 #include <linux/ctype.h> 24 #include <linux/error-injection.h> 25 #include <linux/bpf_lsm.h> 26 #include <linux/security.h> 27 #include <linux/verification.h> 28 #include <linux/keyctl.h> 29 #include <linux/btf_ids.h> 30 #include <linux/poison.h> 31 #include <linux/module.h> 32 #include <linux/cpumask.h> 33 #include <linux/cnum.h> 34 #include <linux/gcd.h> 35 #include <linux/bpf_mem_alloc.h> 36 #include <net/xdp.h> 37 #include <linux/trace_events.h> 38 #include <linux/kallsyms.h> 39 40 #include "diagnostics.h" 41 #include "disasm.h" 42 43 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 44 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 45 [_id] = & _name ## _verifier_ops, 46 #define BPF_MAP_TYPE(_id, _ops) 47 #define BPF_LINK_TYPE(_id, _name) 48 #include <linux/bpf_types.h> 49 #undef BPF_PROG_TYPE 50 #undef BPF_MAP_TYPE 51 #undef BPF_LINK_TYPE 52 }; 53 54 enum bpf_features { 55 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 56 BPF_FEAT_STREAMS = 1, 57 __MAX_BPF_FEAT, 58 }; 59 60 struct bpf_mem_alloc bpf_global_percpu_ma; 61 static bool bpf_global_percpu_ma_set; 62 63 /* bpf_check() is a static code analyzer that walks eBPF program 64 * instruction by instruction and updates register/stack state. 65 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 66 * 67 * The first pass is depth-first-search to check that the program is a DAG. 68 * It rejects the following programs: 69 * - larger than BPF_MAXINSNS insns 70 * - if loop is present (detected via back-edge) 71 * - unreachable insns exist (shouldn't be a forest. program = one function) 72 * - out of bounds or malformed jumps 73 * The second pass is all possible path descent from the 1st insn. 74 * Since it's analyzing all paths through the program, the length of the 75 * analysis is limited to 64k insn, which may be hit even if total number of 76 * insn is less then 4K, but there are too many branches that change stack/regs. 77 * Number of 'branches to be analyzed' is limited to 1k 78 * 79 * On entry to each instruction, each register has a type, and the instruction 80 * changes the types of the registers depending on instruction semantics. 81 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 82 * copied to R1. 83 * 84 * All registers are 64-bit. 85 * R0 - return register 86 * R1-R5 argument passing registers 87 * R6-R9 callee saved registers 88 * R10 - frame pointer read-only 89 * 90 * At the start of BPF program the register R1 contains a pointer to bpf_context 91 * and has type PTR_TO_CTX. 92 * 93 * Verifier tracks arithmetic operations on pointers in case: 94 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 95 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 96 * 1st insn copies R10 (which has FRAME_PTR) type into R1 97 * and 2nd arithmetic instruction is pattern matched to recognize 98 * that it wants to construct a pointer to some element within stack. 99 * So after 2nd insn, the register R1 has type PTR_TO_STACK 100 * (and -20 constant is saved for further stack bounds checking). 101 * Meaning that this reg is a pointer to stack plus known immediate constant. 102 * 103 * Most of the time the registers have SCALAR_VALUE type, which 104 * means the register has some value, but it's not a valid pointer. 105 * (like pointer plus pointer becomes SCALAR_VALUE type) 106 * 107 * When verifier sees load or store instructions the type of base register 108 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 109 * four pointer types recognized by check_mem_access() function. 110 * 111 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 112 * and the range of [ptr, ptr + map's value_size) is accessible. 113 * 114 * registers used to pass values to function calls are checked against 115 * function argument constraints. 116 * 117 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 118 * It means that the register type passed to this function must be 119 * PTR_TO_STACK and it will be used inside the function as 120 * 'pointer to map element key' 121 * 122 * For example the argument constraints for bpf_map_lookup_elem(): 123 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 124 * .arg1_type = ARG_CONST_MAP_PTR, 125 * .arg2_type = ARG_PTR_TO_MAP_KEY, 126 * 127 * ret_type says that this function returns 'pointer to map elem value or null' 128 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 129 * 2nd argument should be a pointer to stack, which will be used inside 130 * the helper function as a pointer to map element key. 131 * 132 * On the kernel side the helper function looks like: 133 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 134 * { 135 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 136 * void *key = (void *) (unsigned long) r2; 137 * void *value; 138 * 139 * here kernel can access 'key' and 'map' pointers safely, knowing that 140 * [key, key + map->key_size) bytes are valid and were initialized on 141 * the stack of eBPF program. 142 * } 143 * 144 * Corresponding eBPF program may look like: 145 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 146 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 147 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 148 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 149 * here verifier looks at prototype of map_lookup_elem() and sees: 150 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 151 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 152 * 153 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 154 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 155 * and were initialized prior to this call. 156 * If it's ok, then verifier allows this BPF_CALL insn and looks at 157 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 158 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 159 * returns either pointer to map value or NULL. 160 * 161 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 162 * insn, the register holding that pointer in the true branch changes state to 163 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 164 * branch. See check_cond_jmp_op(). 165 * 166 * After the call R0 is set to return type of the function and registers R1-R5 167 * are set to NOT_INIT to indicate that they are no longer readable. 168 * 169 * The following reference types represent a potential reference to a kernel 170 * resource which, after first being allocated, must be checked and freed by 171 * the BPF program: 172 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 173 * 174 * When the verifier sees a helper call return a reference type, it allocates a 175 * pointer id for the reference and stores it in the current function state. 176 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 177 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 178 * passes through a NULL-check conditional. For the branch wherein the state is 179 * changed to CONST_IMM, the verifier releases the reference. 180 * 181 * For each helper function that allocates a reference, such as 182 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 183 * bpf_sk_release(). When a reference type passes into the release function, 184 * the verifier also releases the reference. If any unchecked or unreleased 185 * reference remains at the end of the program, the verifier rejects it. 186 */ 187 188 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 189 struct bpf_verifier_stack_elem { 190 /* verifier state is 'st' 191 * before processing instruction 'insn_idx' 192 * and after processing instruction 'prev_insn_idx' 193 */ 194 struct bpf_verifier_state st; 195 int insn_idx; 196 int prev_insn_idx; 197 struct bpf_verifier_stack_elem *next; 198 /* length of verifier log at the time this state was pushed on stack */ 199 u32 log_pos; 200 u64 diag_log_pos; 201 }; 202 203 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 204 #define BPF_COMPLEXITY_LIMIT_STATES 64 205 206 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 207 208 #define BPF_PRIV_STACK_MIN_SIZE 64 209 210 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id); 211 static int __release_reference_nomark(struct bpf_verifier_state *state, int id); 212 static int release_reference_nomark(struct bpf_verifier_env *env, int id); 213 static int release_reference(struct bpf_verifier_env *env, int id); 214 static int invalidate_reference(struct bpf_verifier_env *env, int id); 215 static u32 reg_lifetime_id(struct bpf_verifier_env *env, 216 const struct bpf_reg_state *reg); 217 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 218 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env); 219 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 220 static bool is_tracing_prog_type(enum bpf_prog_type type); 221 static int ref_set_non_owning(struct bpf_verifier_env *env, 222 struct bpf_reg_state *reg); 223 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); 224 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 225 static bool in_rcu_callback(struct bpf_verifier_env *env); 226 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 227 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 228 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 229 230 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 231 struct bpf_map *map, 232 bool unpriv, bool poison) 233 { 234 unpriv |= bpf_map_ptr_unpriv(aux); 235 aux->map_ptr_state.unpriv = unpriv; 236 aux->map_ptr_state.poison = poison; 237 aux->map_ptr_state.map_ptr = map; 238 } 239 240 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 241 { 242 bool poisoned = bpf_map_key_poisoned(aux); 243 244 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 245 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 246 } 247 248 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg) 249 { 250 ref_obj->id = reg->id; 251 ref_obj->parent_id = reg->parent_id; 252 ref_obj->cnt++; 253 } 254 255 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj) 256 { 257 if (ref_obj->cnt > 1) { 258 verifier_bug(env, "function expects only one referenced object but got %d\n", 259 ref_obj->cnt); 260 return -EFAULT; 261 } 262 263 return 0; 264 } 265 266 struct bpf_kfunc_meta { 267 struct btf *btf; 268 const struct btf_type *proto; 269 const char *name; 270 const u32 *flags; 271 s32 id; 272 }; 273 274 struct btf *btf_vmlinux; 275 276 typedef struct argno { 277 int argno; 278 } argno_t; 279 280 static argno_t argno_from_reg(u32 regno) 281 { 282 return (argno_t){ .argno = regno }; 283 } 284 285 static argno_t argno_from_arg(u32 arg) 286 { 287 return (argno_t){ .argno = -arg }; 288 } 289 290 static int reg_from_argno(argno_t a) 291 { 292 if (a.argno >= 0) 293 return a.argno; 294 if (a.argno >= -MAX_BPF_FUNC_REG_ARGS) 295 return -a.argno; 296 return -1; 297 } 298 299 static int arg_from_argno(argno_t a) 300 { 301 if (a.argno < 0) 302 return -a.argno; 303 return -1; 304 } 305 306 static int arg_idx_from_argno(argno_t a) 307 { 308 return arg_from_argno(a) - 1; 309 } 310 311 /* Normalize helper register numbers and kfunc argument numbers to ABI slots. */ 312 static u32 arg_slot_from_argno(argno_t a) 313 { 314 return abs(a.argno) - 1; 315 } 316 317 static const char *btf_type_name(const struct btf *btf, u32 id) 318 { 319 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 320 } 321 322 static DEFINE_MUTEX(bpf_verifier_lock); 323 static DEFINE_MUTEX(btf_vmlinux_lock); 324 static DEFINE_MUTEX(bpf_percpu_ma_lock); 325 326 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 327 { 328 struct bpf_verifier_env *env = private_data; 329 va_list args; 330 331 if (!bpf_verifier_log_needed(&env->log)) 332 return; 333 334 va_start(args, fmt); 335 bpf_verifier_vlog(&env->log, fmt, args); 336 va_end(args); 337 } 338 339 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 340 struct bpf_reg_state *reg, 341 struct bpf_retval_range range, const char *ctx, 342 const char *reg_name) 343 { 344 bool unknown = true; 345 346 verbose(env, "%s the register %s has", ctx, reg_name); 347 if (reg_smin(reg) > S64_MIN) { 348 verbose(env, " smin=%lld", reg_smin(reg)); 349 unknown = false; 350 } 351 if (reg_smax(reg) < S64_MAX) { 352 verbose(env, " smax=%lld", reg_smax(reg)); 353 unknown = false; 354 } 355 if (unknown) 356 verbose(env, " unknown scalar value"); 357 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 358 } 359 360 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 361 { 362 enum bpf_reg_type type; 363 364 type = reg->type; 365 if (type_may_be_null(type)) 366 return false; 367 368 /* 369 * The types below guarantee a non-NULL base, an unbounded offset can 370 * still wrap base + offset to zero. 371 */ 372 if (reg_smin(reg) <= -BPF_MAX_VAR_OFF || reg_smax(reg) >= BPF_MAX_VAR_OFF) 373 return false; 374 375 type = base_type(type); 376 return type == PTR_TO_SOCKET || 377 type == PTR_TO_TCP_SOCK || 378 type == PTR_TO_XDP_SOCK || 379 type == PTR_TO_BUF || 380 type == PTR_TO_MAP_VALUE || 381 type == PTR_TO_MAP_KEY || 382 type == PTR_TO_SOCK_COMMON || 383 (type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) || 384 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 385 type == CONST_PTR_TO_MAP; 386 } 387 388 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 389 { 390 struct btf_record *rec = NULL; 391 struct btf_struct_meta *meta; 392 393 if (reg->type == PTR_TO_MAP_VALUE) { 394 rec = reg->map_ptr->record; 395 } else if (type_is_ptr_alloc_obj(reg->type)) { 396 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 397 if (meta) 398 rec = meta->record; 399 } 400 return rec; 401 } 402 403 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 404 { 405 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 406 407 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 408 } 409 410 static const struct btf_type *subprog_ret_type(struct bpf_verifier_env *env, int subprog) 411 { 412 const struct btf_type *func, *func_proto; 413 const struct btf *btf = env->prog->aux->btf; 414 u32 btf_id; 415 416 if (!btf || !env->prog->aux->func_info) 417 return NULL; 418 419 btf_id = env->prog->aux->func_info[subprog].type_id; 420 421 /* Both already validated by prepare_btf_func() at prog load. */ 422 func = btf_type_by_id(btf, btf_id); 423 func_proto = btf_type_by_id(btf, func->type); 424 425 return btf_type_skip_modifiers(btf, func_proto->type, NULL); 426 } 427 428 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 429 { 430 const struct btf_type *type = subprog_ret_type(env, subprog); 431 432 return type && btf_type_is_void(type); 433 } 434 435 static u32 ret_regs_cnt(u32 size) 436 { 437 return size > 8 && size <= 16 ? 2 : 1; 438 } 439 440 /* Registers holding a function return value, in order. See ret_regs_cnt(). */ 441 static const int ret_regs[] = { BPF_REG_0, BPF_REG_2 }; 442 443 static int bpf_compute_subprog_ret_regs(struct bpf_verifier_env *env) 444 { 445 const struct btf *btf = env->prog->aux->btf; 446 const struct btf_type *type; 447 int subprog; 448 u32 size; 449 450 if (!env->prog->jit_requested || bpf_prog_is_offloaded(env->prog->aux)) 451 return 0; 452 453 /* 454 * Skip the main program: its return value is the program's exit code, 455 * read out of R0, so it never uses the register pair. An extension does 456 * have a real prototype for subprog 0, but btf_check_func_type_match() 457 * refuses to replace a function returning more than 8 bytes. 458 */ 459 for (subprog = 1; subprog < env->subprog_cnt; subprog++) { 460 type = subprog_ret_type(env, subprog); 461 if (!type || btf_type_is_void(type)) 462 continue; 463 if (verifier_bug_if(IS_ERR(btf_resolve_size(btf, type, &size)), env, 464 "cannot size return type of subprog %d", subprog)) 465 return -EFAULT; 466 if (ret_regs_cnt(size) > 1) { 467 subprog_info(env, subprog)->ret_reg_pair = true; 468 env->prog->jit_required = 1; 469 } 470 } 471 472 return 0; 473 } 474 475 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog) 476 { 477 struct bpf_func_info *info; 478 479 if (!env->prog->aux->func_info) 480 return ""; 481 482 info = &env->prog->aux->func_info[subprog]; 483 return btf_type_name(env->prog->aux->btf, info->type_id); 484 } 485 486 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 487 { 488 struct bpf_subprog_info *info = subprog_info(env, subprog); 489 490 info->is_cb = true; 491 info->is_async_cb = true; 492 info->is_exception_cb = true; 493 } 494 495 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 496 { 497 return subprog_info(env, subprog)->is_exception_cb; 498 } 499 500 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 501 { 502 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 503 } 504 505 static bool type_is_rdonly_mem(u32 type) 506 { 507 return type & MEM_RDONLY; 508 } 509 510 static bool is_acquire_function(enum bpf_func_id func_id, 511 const struct bpf_map *map) 512 { 513 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 514 515 if (func_id == BPF_FUNC_sk_lookup_tcp || 516 func_id == BPF_FUNC_sk_lookup_udp || 517 func_id == BPF_FUNC_skc_lookup_tcp || 518 func_id == BPF_FUNC_ringbuf_reserve || 519 func_id == BPF_FUNC_kptr_xchg) 520 return true; 521 522 if (func_id == BPF_FUNC_map_lookup_elem && 523 (map_type == BPF_MAP_TYPE_SOCKMAP || 524 map_type == BPF_MAP_TYPE_SOCKHASH)) 525 return true; 526 527 return false; 528 } 529 530 static bool is_ptr_cast_function(enum bpf_func_id func_id) 531 { 532 return func_id == BPF_FUNC_tcp_sock || 533 func_id == BPF_FUNC_sk_fullsock || 534 func_id == BPF_FUNC_skc_to_tcp_sock || 535 func_id == BPF_FUNC_skc_to_tcp6_sock || 536 func_id == BPF_FUNC_skc_to_udp6_sock || 537 func_id == BPF_FUNC_skc_to_mptcp_sock || 538 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 539 func_id == BPF_FUNC_skc_to_tcp_request_sock; 540 } 541 542 static bool is_sync_callback_calling_kfunc(u32 btf_id); 543 static bool is_async_callback_calling_kfunc(u32 btf_id); 544 static bool is_call_rcu_kfunc(u32 btf_id); 545 static bool is_callback_calling_kfunc(u32 btf_id); 546 547 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 548 static bool is_task_work_add_kfunc(u32 func_id); 549 550 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 551 { 552 return func_id == BPF_FUNC_for_each_map_elem || 553 func_id == BPF_FUNC_find_vma || 554 func_id == BPF_FUNC_loop || 555 func_id == BPF_FUNC_user_ringbuf_drain; 556 } 557 558 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 559 { 560 return func_id == BPF_FUNC_timer_set_callback; 561 } 562 563 static bool is_callback_calling_function(enum bpf_func_id func_id) 564 { 565 return is_sync_callback_calling_function(func_id) || 566 is_async_callback_calling_function(func_id); 567 } 568 569 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 570 { 571 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 572 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 573 } 574 575 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 576 { 577 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 578 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 579 } 580 581 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 582 { 583 /* bpf_timer callbacks are never sleepable. */ 584 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 585 return false; 586 587 /* bpf_call_rcu and bpf_call_rcu_tasks_trace callbacks are never sleepable. */ 588 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && is_call_rcu_kfunc(insn->imm)) 589 return false; 590 591 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 592 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 593 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 594 return true; 595 596 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 597 return false; 598 } 599 600 /* From here on the maps of the program count it as a sleepable user. */ 601 static void mark_sleepable_async_cb(struct bpf_verifier_env *env) 602 { 603 int i; 604 605 if (bpf_prog_runs_sleepable(env->prog)) 606 return; 607 608 env->prog->aux->sleepable_async_cb = true; 609 for (i = 0; i < env->used_map_cnt; i++) 610 atomic64_inc(&env->used_maps[i]->sleepable_refcnt); 611 } 612 613 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 614 { 615 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 616 } 617 618 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 619 { 620 int allocated_slots = bpf_stack_nr_slots(state); 621 622 /* 623 * We need to check that slots between [spi - nr_slots + 1, spi] are 624 * within [0, allocated_stack). 625 * 626 * Please note that the spi grows downwards. For example, a dynptr 627 * takes the size of two stack slots; the first slot will be at 628 * spi and the second slot will be at spi - 1. 629 */ 630 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 631 } 632 633 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 634 const char *obj_kind, int nr_slots) 635 { 636 int off, spi; 637 638 if (!tnum_is_const(reg->var_off)) { 639 verbose(env, "%s has to be at a constant offset\n", obj_kind); 640 return -EINVAL; 641 } 642 643 off = reg->var_off.value; 644 if (off >= 0 || off % BPF_REG_SIZE) { 645 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 646 return -EINVAL; 647 } 648 649 spi = bpf_get_spi(off); 650 if (spi + 1 < nr_slots) { 651 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 652 return -EINVAL; 653 } 654 655 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 656 return -ERANGE; 657 return spi; 658 } 659 660 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 661 { 662 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 663 } 664 665 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 666 { 667 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 668 } 669 670 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 671 { 672 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 673 } 674 675 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 676 { 677 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 678 case DYNPTR_TYPE_LOCAL: 679 return BPF_DYNPTR_TYPE_LOCAL; 680 case DYNPTR_TYPE_RINGBUF: 681 return BPF_DYNPTR_TYPE_RINGBUF; 682 case DYNPTR_TYPE_SKB: 683 return BPF_DYNPTR_TYPE_SKB; 684 case DYNPTR_TYPE_XDP: 685 return BPF_DYNPTR_TYPE_XDP; 686 case DYNPTR_TYPE_SKB_META: 687 return BPF_DYNPTR_TYPE_SKB_META; 688 case DYNPTR_TYPE_FILE: 689 return BPF_DYNPTR_TYPE_FILE; 690 default: 691 return BPF_DYNPTR_TYPE_INVALID; 692 } 693 } 694 695 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 696 { 697 switch (type) { 698 case BPF_DYNPTR_TYPE_LOCAL: 699 return DYNPTR_TYPE_LOCAL; 700 case BPF_DYNPTR_TYPE_RINGBUF: 701 return DYNPTR_TYPE_RINGBUF; 702 case BPF_DYNPTR_TYPE_SKB: 703 return DYNPTR_TYPE_SKB; 704 case BPF_DYNPTR_TYPE_XDP: 705 return DYNPTR_TYPE_XDP; 706 case BPF_DYNPTR_TYPE_SKB_META: 707 return DYNPTR_TYPE_SKB_META; 708 case BPF_DYNPTR_TYPE_FILE: 709 return DYNPTR_TYPE_FILE; 710 default: 711 return 0; 712 } 713 } 714 715 static bool dynptr_type_referenced(enum bpf_dynptr_type type) 716 { 717 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 718 } 719 720 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 721 enum bpf_dynptr_type type, 722 bool first_slot, int id, int parent_id); 723 724 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 725 struct bpf_reg_state *sreg1, 726 struct bpf_reg_state *sreg2, 727 enum bpf_dynptr_type type, int parent_id) 728 { 729 int id = ++env->id_gen; 730 731 __mark_dynptr_reg(sreg1, type, true, id, parent_id); 732 __mark_dynptr_reg(sreg2, type, false, id, parent_id); 733 } 734 735 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 736 struct bpf_reg_state *reg, 737 enum bpf_dynptr_type type) 738 { 739 __mark_dynptr_reg(reg, type, true, ++env->id_gen, 0); 740 } 741 742 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 743 struct bpf_func_state *state, int spi); 744 745 static int destroy_dynptrs_in_stack_slots(struct bpf_verifier_env *env, 746 struct bpf_func_state *state, 747 int first_spi, int last_spi) 748 { 749 int spi, err; 750 751 for (spi = first_spi; spi <= last_spi; spi++) { 752 err = destroy_if_dynptr_stack_slot(env, state, spi); 753 if (err) 754 return err; 755 } 756 757 return 0; 758 } 759 760 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 761 enum bpf_arg_type arg_type, int insn_idx, 762 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 763 { 764 struct bpf_func_state *state = bpf_func(env, reg); 765 int spi, i, err, parent_id = 0; 766 enum bpf_dynptr_type type; 767 768 spi = dynptr_get_spi(env, reg); 769 if (spi < 0) 770 return spi; 771 772 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 773 * hence we need to destroy dynptrs in both slots, 774 * to ensure that for the following example: 775 * [d1][d1][d2][d2] 776 * spi 3 2 1 0 777 * So marking spi = 2 should lead to destruction of both d1 and d2. In 778 * case they do belong to same dynptr, second call won't see slot_type 779 * as STACK_DYNPTR and will simply skip destruction. 780 */ 781 err = destroy_dynptrs_in_stack_slots(env, state, spi - 1, spi); 782 if (err) 783 return err; 784 785 for (i = 0; i < BPF_REG_SIZE; i++) { 786 bpf_stack_slot(state, spi)->slot_type[i] = STACK_DYNPTR; 787 bpf_stack_slot(state, spi - 1)->slot_type[i] = STACK_DYNPTR; 788 } 789 790 type = arg_to_dynptr_type(arg_type); 791 if (type == BPF_DYNPTR_TYPE_INVALID) 792 return -EINVAL; 793 794 if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */ 795 err = validate_ref_obj(env, ref_obj); 796 if (err) 797 return err; 798 799 /* All non-clone constructors take their backing object in R1. */ 800 parent_id = reg_lifetime_id(env, &cur_regs(env)[BPF_REG_1]); 801 802 if (dynptr_type_referenced(type)) { 803 int id; 804 805 /* 806 * Create an intermediate reference that tracks the referenced 807 * object for the referenced dynptr. Freeing a referenced dynptr 808 * through helpers/kfuncs will invalidate all clones. 809 */ 810 id = acquire_reference(env, insn_idx, parent_id); 811 if (id < 0) 812 return id; 813 814 parent_id = id; 815 } 816 } else { /* bpf_dynptr_clone() */ 817 parent_id = dynptr->parent_id; 818 } 819 820 mark_dynptr_stack_regs(env, &bpf_stack_slot(state, spi)->spilled_ptr, 821 &bpf_stack_slot(state, spi - 1)->spilled_ptr, type, parent_id); 822 823 return 0; 824 } 825 826 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack) 827 { 828 int i; 829 830 for (i = 0; i < BPF_REG_SIZE; i++) { 831 stack[0].slot_type[i] = STACK_INVALID; 832 stack[1].slot_type[i] = STACK_INVALID; 833 } 834 835 bpf_mark_reg_not_init(env, &stack[0].spilled_ptr); 836 bpf_mark_reg_not_init(env, &stack[1].spilled_ptr); 837 } 838 839 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 840 { 841 struct bpf_func_state *state = bpf_func(env, reg); 842 int spi; 843 844 spi = dynptr_get_spi(env, reg); 845 if (spi < 0) 846 return spi; 847 848 /* 849 * For referenced dynptr, release the parent ref which cascades to 850 * all clones and derived slices. For non-referenced dynptr, only 851 * the dynptr and slices derived from it will be invalidated. 852 */ 853 reg = &bpf_stack_slot(state, spi)->spilled_ptr; 854 return release_reference(env, dynptr_type_referenced(reg->dynptr.type) 855 ? reg->parent_id 856 : reg->id); 857 } 858 859 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 860 struct bpf_reg_state *reg); 861 862 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 863 { 864 if (!env->allow_ptr_leaks) 865 bpf_mark_reg_not_init(env, reg); 866 else 867 __mark_reg_unknown(env, reg); 868 } 869 870 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id) 871 { 872 struct bpf_stack_state *stack; 873 struct bpf_func_state *state; 874 struct bpf_reg_state *reg; 875 int ref_cnt = 0; 876 877 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ 878 if (!stack || stack->slot_type[0] != STACK_DYNPTR) 879 continue; 880 if (!stack->spilled_ptr.dynptr.first_slot) 881 continue; 882 if (stack->spilled_ptr.parent_id == v_parent_id) 883 ref_cnt++; 884 })); 885 886 return ref_cnt; 887 } 888 889 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 890 struct bpf_func_state *state, int spi) 891 { 892 struct bpf_stack_state *slot = bpf_stack_slot(state, spi); 893 int err = 0; 894 895 /* We always ensure that STACK_DYNPTR is never set partially, 896 * hence just checking for slot_type[0] is enough. This is 897 * different for STACK_SPILL, where it may be only set for 898 * 1 byte, so code has to use is_spilled_reg. 899 */ 900 if (slot->slot_type[0] != STACK_DYNPTR) 901 return 0; 902 903 /* Reposition spi to first slot */ 904 if (!slot->spilled_ptr.dynptr.first_slot) { 905 spi = spi + 1; 906 slot = bpf_stack_slot(state, spi); 907 } 908 909 /* 910 * A referenced dynptr can be overwritten only if there is at 911 * least one other dynptr sharing the same virtual ref parent, 912 * ensuring the reference can still be properly released. 913 */ 914 if (dynptr_type_referenced(slot->spilled_ptr.dynptr.type) && 915 dynptr_ref_cnt(env, slot->spilled_ptr.parent_id) <= 1) { 916 verbose(env, "cannot overwrite referenced dynptr\n"); 917 bpf_diag_res( 918 env, env->insn_idx, "referenced dynptr overwrite", 919 "This stack slot contains a dynptr that owns or protects a referenced resource. Overwriting the last dynptr for that resource would lose the verifier-tracked release path.", 920 "Release or clone the dynptr so another live dynptr still tracks the referenced resource before overwriting this stack slot."); 921 return -EINVAL; 922 } 923 924 /* Invalidate the dynptr and any derived slices */ 925 err = release_reference(env, slot->spilled_ptr.id); 926 if (!err) { 927 mark_stack_slot_scratched(env, spi); 928 mark_stack_slot_scratched(env, spi - 1); 929 } 930 931 return err; 932 } 933 934 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 935 { 936 int spi; 937 938 if (reg->type == CONST_PTR_TO_DYNPTR) 939 return false; 940 941 spi = dynptr_get_spi(env, reg); 942 943 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 944 * error because this just means the stack state hasn't been updated yet. 945 * We will do check_mem_access to check and update stack bounds later. 946 */ 947 if (spi < 0 && spi != -ERANGE) 948 return false; 949 950 /* We don't need to check if the stack slots are marked by previous 951 * dynptr initializations because we allow overwriting existing unreferenced 952 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 953 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 954 * touching are completely destructed before we reinitialize them for a new 955 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 956 * instead of delaying it until the end where the user will get "Unreleased 957 * reference" error. 958 */ 959 return true; 960 } 961 962 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 963 { 964 struct bpf_func_state *state = bpf_func(env, reg); 965 struct bpf_stack_state *slot; 966 int i, spi; 967 968 /* This already represents first slot of initialized bpf_dynptr. 969 * 970 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 971 * check_func_arg_reg_off's logic, so we don't need to check its 972 * offset and alignment. 973 */ 974 if (reg->type == CONST_PTR_TO_DYNPTR) 975 return true; 976 977 spi = dynptr_get_spi(env, reg); 978 if (spi < 0) 979 return false; 980 slot = bpf_stack_slot(state, spi); 981 if (!slot->spilled_ptr.dynptr.first_slot) 982 return false; 983 984 for (i = 0; i < BPF_REG_SIZE; i++) { 985 if (slot->slot_type[i] != STACK_DYNPTR || 986 bpf_stack_slot(state, spi - 1)->slot_type[i] != STACK_DYNPTR) 987 return false; 988 } 989 990 return true; 991 } 992 993 static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 994 { 995 struct bpf_func_state *state; 996 int spi; 997 998 if (reg->type == CONST_PTR_TO_DYNPTR) 999 return reg->dynptr.type; 1000 1001 spi = dynptr_get_spi(env, reg); 1002 if (spi < 0) 1003 return BPF_DYNPTR_TYPE_INVALID; 1004 state = bpf_func(env, reg); 1005 return bpf_stack_slot(state, spi)->spilled_ptr.dynptr.type; 1006 } 1007 1008 static bool dynptr_write_changes_pkt_data(enum bpf_dynptr_type type) 1009 { 1010 return type == BPF_DYNPTR_TYPE_SKB || type == BPF_DYNPTR_TYPE_SKB_META; 1011 } 1012 1013 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1014 enum bpf_arg_type arg_type) 1015 { 1016 /* 1017 * ARG_PTR_TO_DYNPTR without a type flag takes any type of dynptr. 1018 * Test the flags rather than the whole arg_type, which may carry 1019 * unrelated ones such as PTR_MAYBE_NULL. 1020 */ 1021 if (!(arg_type & DYNPTR_TYPE_FLAG_MASK)) 1022 return true; 1023 1024 return dynptr_reg_type(env, reg) == arg_to_dynptr_type(arg_type); 1025 } 1026 1027 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1028 1029 static bool in_rcu_cs(struct bpf_verifier_env *env); 1030 1031 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta); 1032 1033 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1034 struct bpf_call_arg_meta *meta, 1035 struct bpf_reg_state *reg, int insn_idx, 1036 struct btf *btf, u32 btf_id, int nr_slots) 1037 { 1038 struct bpf_func_state *state = bpf_func(env, reg); 1039 int spi, i, j, id; 1040 1041 spi = iter_get_spi(env, reg, nr_slots); 1042 if (spi < 0) 1043 return spi; 1044 1045 id = acquire_reference(env, insn_idx, 0); 1046 if (id < 0) 1047 return id; 1048 1049 for (i = 0; i < nr_slots; i++) { 1050 struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); 1051 struct bpf_reg_state *st = &slot->spilled_ptr; 1052 1053 __mark_reg_known_zero(st); 1054 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1055 if (is_kfunc_rcu_protected(meta)) { 1056 if (in_rcu_cs(env)) 1057 st->type |= MEM_RCU; 1058 else 1059 st->type |= PTR_UNTRUSTED; 1060 } 1061 st->id = i == 0 ? id : 0; 1062 st->iter.btf = btf; 1063 st->iter.btf_id = btf_id; 1064 st->iter.state = BPF_ITER_STATE_ACTIVE; 1065 st->iter.depth = 0; 1066 1067 for (j = 0; j < BPF_REG_SIZE; j++) 1068 slot->slot_type[j] = STACK_ITER; 1069 1070 mark_stack_slot_scratched(env, spi - i); 1071 } 1072 1073 return 0; 1074 } 1075 1076 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1077 struct bpf_reg_state *reg, int nr_slots) 1078 { 1079 struct bpf_func_state *state = bpf_func(env, reg); 1080 int spi, i, j, err; 1081 1082 spi = iter_get_spi(env, reg, nr_slots); 1083 if (spi < 0) 1084 return spi; 1085 1086 for (i = 0; i < nr_slots; i++) { 1087 struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); 1088 struct bpf_reg_state *st = &slot->spilled_ptr; 1089 1090 if (i == 0) { 1091 err = release_reference(env, st->id); 1092 if (err) 1093 return err; 1094 } 1095 1096 bpf_mark_reg_not_init(env, st); 1097 1098 for (j = 0; j < BPF_REG_SIZE; j++) 1099 slot->slot_type[j] = STACK_INVALID; 1100 1101 mark_stack_slot_scratched(env, spi - i); 1102 } 1103 1104 return 0; 1105 } 1106 1107 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1108 struct bpf_reg_state *reg, int nr_slots) 1109 { 1110 struct bpf_func_state *state = bpf_func(env, reg); 1111 int spi, i, j; 1112 1113 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1114 * will do check_mem_access to check and update stack bounds later, so 1115 * return true for that case. 1116 */ 1117 spi = iter_get_spi(env, reg, nr_slots); 1118 if (spi == -ERANGE) 1119 return true; 1120 if (spi < 0) 1121 return false; 1122 1123 for (i = 0; i < nr_slots; i++) { 1124 struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); 1125 1126 for (j = 0; j < BPF_REG_SIZE; j++) 1127 if (slot->slot_type[j] == STACK_ITER) 1128 return false; 1129 } 1130 1131 return true; 1132 } 1133 1134 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1135 struct btf *btf, u32 btf_id, int nr_slots) 1136 { 1137 struct bpf_func_state *state = bpf_func(env, reg); 1138 int spi, i, j; 1139 1140 spi = iter_get_spi(env, reg, nr_slots); 1141 if (spi < 0) 1142 return -EINVAL; 1143 1144 for (i = 0; i < nr_slots; i++) { 1145 struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); 1146 struct bpf_reg_state *st = &slot->spilled_ptr; 1147 1148 if (st->type & PTR_UNTRUSTED) 1149 return -EPROTO; 1150 /* only main (first) slot has id set */ 1151 if (i == 0 && !st->id) 1152 return -EINVAL; 1153 if (i != 0 && st->id) 1154 return -EINVAL; 1155 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1156 return -EINVAL; 1157 1158 for (j = 0; j < BPF_REG_SIZE; j++) 1159 if (slot->slot_type[j] != STACK_ITER) 1160 return -EINVAL; 1161 } 1162 1163 return 0; 1164 } 1165 1166 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1167 static int release_irq_state(struct bpf_verifier_env *env, int id); 1168 1169 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1170 struct bpf_call_arg_meta *meta, 1171 struct bpf_reg_state *reg, int insn_idx, 1172 int kfunc_class) 1173 { 1174 struct bpf_func_state *state = bpf_func(env, reg); 1175 struct bpf_stack_state *slot; 1176 struct bpf_reg_state *st; 1177 int spi, i, id; 1178 1179 spi = irq_flag_get_spi(env, reg); 1180 if (spi < 0) 1181 return spi; 1182 1183 id = acquire_irq_state(env, insn_idx); 1184 if (id < 0) 1185 return id; 1186 1187 slot = bpf_stack_slot(state, spi); 1188 st = &slot->spilled_ptr; 1189 1190 __mark_reg_known_zero(st); 1191 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1192 st->id = id; 1193 st->irq.kfunc_class = kfunc_class; 1194 1195 for (i = 0; i < BPF_REG_SIZE; i++) 1196 slot->slot_type[i] = STACK_IRQ_FLAG; 1197 1198 mark_stack_slot_scratched(env, spi); 1199 return 0; 1200 } 1201 1202 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1203 int kfunc_class) 1204 { 1205 struct bpf_func_state *state = bpf_func(env, reg); 1206 struct bpf_stack_state *slot; 1207 struct bpf_reg_state *st; 1208 int spi, i, err; 1209 1210 spi = irq_flag_get_spi(env, reg); 1211 if (spi < 0) 1212 return spi; 1213 1214 slot = bpf_stack_slot(state, spi); 1215 st = &slot->spilled_ptr; 1216 1217 if (st->irq.kfunc_class != kfunc_class) { 1218 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1219 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1220 const char *reason; 1221 1222 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1223 flag_kfunc, used_kfunc); 1224 reason = bpf_diag_fmt(env, 1225 "This IRQ flag was saved by %s IRQ kfuncs, but the restore call " 1226 "belongs to the %s IRQ kfunc family. Save and restore operations " 1227 "must use the same family.", 1228 flag_kfunc, used_kfunc); 1229 bpf_diag_irq(env, env->insn_idx, "IRQ flag restore mismatch", reason, 1230 "Restore the flag with the matching IRQ restore kfunc for the save " 1231 "operation that created it.", 1232 bpf_diag_irq_depth(env->cur_state)); 1233 return -EINVAL; 1234 } 1235 1236 err = release_irq_state(env, st->id); 1237 WARN_ON_ONCE(err && err != -EACCES); 1238 if (err) { 1239 int insn_idx = 0; 1240 1241 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1242 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1243 insn_idx = env->cur_state->refs[i].insn_idx; 1244 break; 1245 } 1246 } 1247 1248 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1249 env->cur_state->active_irq_id, insn_idx); 1250 bpf_diag_irq(env, env->insn_idx, "IRQ flag restore out of order", 1251 "IRQ-disabled regions must be restored in last-in, first-out order, " 1252 "but this restore does not match the currently active IRQ flag.", 1253 "Restore nested IRQ flags in the reverse order they were saved.", 1254 bpf_diag_irq_depth(env->cur_state)); 1255 return err; 1256 } 1257 1258 bpf_mark_reg_not_init(env, st); 1259 1260 for (i = 0; i < BPF_REG_SIZE; i++) 1261 slot->slot_type[i] = STACK_INVALID; 1262 1263 mark_stack_slot_scratched(env, spi); 1264 return 0; 1265 } 1266 1267 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1268 { 1269 struct bpf_func_state *state = bpf_func(env, reg); 1270 struct bpf_stack_state *slot; 1271 int spi, i; 1272 1273 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1274 * will do check_mem_access to check and update stack bounds later, so 1275 * return true for that case. 1276 */ 1277 spi = irq_flag_get_spi(env, reg); 1278 if (spi == -ERANGE) 1279 return true; 1280 if (spi < 0) 1281 return false; 1282 1283 slot = bpf_stack_slot(state, spi); 1284 1285 for (i = 0; i < BPF_REG_SIZE; i++) 1286 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1287 return false; 1288 return true; 1289 } 1290 1291 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1292 { 1293 struct bpf_func_state *state = bpf_func(env, reg); 1294 struct bpf_stack_state *slot; 1295 struct bpf_reg_state *st; 1296 int spi, i; 1297 1298 spi = irq_flag_get_spi(env, reg); 1299 if (spi < 0) 1300 return -EINVAL; 1301 1302 slot = bpf_stack_slot(state, spi); 1303 st = &slot->spilled_ptr; 1304 1305 if (!st->id) 1306 return -EINVAL; 1307 1308 for (i = 0; i < BPF_REG_SIZE; i++) 1309 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1310 return -EINVAL; 1311 return 0; 1312 } 1313 1314 /* Check if given stack slot is "special": 1315 * - spilled register state (STACK_SPILL); 1316 * - dynptr state (STACK_DYNPTR); 1317 * - iter state (STACK_ITER). 1318 * - irq flag state (STACK_IRQ_FLAG) 1319 */ 1320 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1321 { 1322 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1323 1324 switch (type) { 1325 case STACK_SPILL: 1326 case STACK_DYNPTR: 1327 case STACK_ITER: 1328 case STACK_IRQ_FLAG: 1329 return true; 1330 case STACK_INVALID: 1331 case STACK_POISON: 1332 case STACK_MISC: 1333 case STACK_ZERO: 1334 return false; 1335 default: 1336 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1337 return true; 1338 } 1339 } 1340 1341 /* The reg state of a pointer or a bounded scalar was saved when 1342 * it was spilled to the stack. 1343 */ 1344 1345 /* 1346 * Mark stack slot as STACK_MISC, unless it is already: 1347 * - STACK_INVALID, in which case they are equivalent. 1348 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1349 * - STACK_POISON, which truly forbids access to the slot. 1350 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1351 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1352 * unnecessary as both are considered equivalent when loading data and pruning, 1353 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1354 * slots. 1355 */ 1356 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1357 { 1358 if (*stype == STACK_ZERO) 1359 return; 1360 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1361 return; 1362 *stype = STACK_MISC; 1363 } 1364 1365 static void scrub_spilled_slot(u8 *stype) 1366 { 1367 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1368 *stype = STACK_MISC; 1369 } 1370 1371 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1372 * small to hold src. This is different from krealloc since we don't want to preserve 1373 * the contents of dst. 1374 * 1375 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1376 * not be allocated. 1377 */ 1378 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1379 { 1380 size_t alloc_bytes; 1381 void *orig = dst; 1382 size_t bytes; 1383 1384 if (ZERO_OR_NULL_PTR(src)) 1385 goto out; 1386 1387 if (unlikely(check_mul_overflow(n, size, &bytes))) 1388 return NULL; 1389 1390 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1391 dst = krealloc(orig, alloc_bytes, flags); 1392 if (!dst) { 1393 kfree(orig); 1394 return NULL; 1395 } 1396 1397 memcpy(dst, src, bytes); 1398 out: 1399 return dst ? dst : ZERO_SIZE_PTR; 1400 } 1401 1402 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1403 * small to hold new_n items. new items are zeroed out if the array grows. 1404 * 1405 * Contrary to krealloc_array, does not free arr if new_n is zero. 1406 */ 1407 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1408 { 1409 size_t alloc_size; 1410 void *new_arr; 1411 1412 if (!new_n || old_n == new_n) 1413 goto out; 1414 1415 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1416 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1417 if (!new_arr) { 1418 kfree(arr); 1419 return NULL; 1420 } 1421 arr = new_arr; 1422 1423 if (new_n > old_n) 1424 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1425 1426 out: 1427 return arr ? arr : ZERO_SIZE_PTR; 1428 } 1429 1430 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1431 { 1432 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1433 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1434 if (!dst->refs) 1435 return -ENOMEM; 1436 1437 dst->acquired_refs = src->acquired_refs; 1438 dst->active_locks = src->active_locks; 1439 dst->active_preempt_locks = src->active_preempt_locks; 1440 dst->active_rcu_locks = src->active_rcu_locks; 1441 dst->active_irq_id = src->active_irq_id; 1442 dst->active_lock_id = src->active_lock_id; 1443 dst->active_lock_ptr = src->active_lock_ptr; 1444 return 0; 1445 } 1446 1447 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1448 { 1449 size_t n = bpf_stack_nr_slots(src); 1450 1451 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1452 GFP_KERNEL_ACCOUNT); 1453 if (!dst->stack) 1454 return -ENOMEM; 1455 1456 dst->allocated_stack = src->allocated_stack; 1457 1458 /* copy stack args state */ 1459 n = src->out_stack_arg_cnt; 1460 if (n) { 1461 dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n, 1462 sizeof(struct bpf_reg_state), 1463 GFP_KERNEL_ACCOUNT); 1464 if (!dst->stack_arg_regs) 1465 return -ENOMEM; 1466 } 1467 1468 dst->out_stack_arg_cnt = src->out_stack_arg_cnt; 1469 return 0; 1470 } 1471 1472 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1473 { 1474 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1475 sizeof(struct bpf_reference_state)); 1476 if (!state->refs) 1477 return -ENOMEM; 1478 1479 state->acquired_refs = n; 1480 return 0; 1481 } 1482 1483 /* Possibly update state->allocated_stack to be at least size bytes. Also 1484 * possibly update the function's high-water mark in its bpf_subprog_info. 1485 */ 1486 int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1487 { 1488 size_t old_n = bpf_stack_nr_slots(state), n; 1489 1490 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1491 size = round_up(size, BPF_REG_SIZE); 1492 n = size / BPF_REG_SIZE; 1493 1494 if (old_n >= n) 1495 return 0; 1496 1497 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1498 if (!state->stack) 1499 return -ENOMEM; 1500 1501 state->allocated_stack = size; 1502 1503 /* update known max for given subprogram */ 1504 if (env->subprog_info[state->subprogno].stack_depth < size) 1505 env->subprog_info[state->subprogno].stack_depth = size; 1506 1507 return 0; 1508 } 1509 1510 static int grow_stack_arg_slots(struct bpf_verifier_env *env, 1511 struct bpf_func_state *state, int cnt) 1512 { 1513 size_t old_n = state->out_stack_arg_cnt; 1514 1515 if (old_n >= cnt) 1516 return 0; 1517 1518 state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt, 1519 sizeof(struct bpf_reg_state)); 1520 if (!state->stack_arg_regs) 1521 return -ENOMEM; 1522 1523 state->out_stack_arg_cnt = cnt; 1524 return 0; 1525 } 1526 1527 /* Acquire a pointer id from the env and update the state->refs to include 1528 * this new pointer reference. 1529 * On success, returns a valid pointer id to associate with the register 1530 * On failure, returns a negative errno. 1531 */ 1532 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1533 { 1534 struct bpf_verifier_state *state = env->cur_state; 1535 int new_ofs = state->acquired_refs; 1536 int err; 1537 1538 err = resize_reference_state(state, state->acquired_refs + 1); 1539 if (err) 1540 return NULL; 1541 state->refs[new_ofs].insn_idx = insn_idx; 1542 1543 return &state->refs[new_ofs]; 1544 } 1545 1546 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id) 1547 { 1548 struct bpf_reference_state *s; 1549 1550 s = acquire_reference_state(env, insn_idx); 1551 if (!s) 1552 return -ENOMEM; 1553 s->type = REF_TYPE_PTR; 1554 s->id = ++env->id_gen; 1555 s->parent_id = parent_id; 1556 bpf_diag_record_ref_acquire(env, insn_idx, s->id); 1557 return s->id; 1558 } 1559 1560 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1561 int id, void *ptr) 1562 { 1563 struct bpf_verifier_state *state = env->cur_state; 1564 struct bpf_reference_state *s; 1565 1566 s = acquire_reference_state(env, insn_idx); 1567 if (!s) 1568 return -ENOMEM; 1569 s->type = type; 1570 s->id = id; 1571 s->ptr = ptr; 1572 1573 state->active_locks++; 1574 state->active_lock_id = id; 1575 state->active_lock_ptr = ptr; 1576 bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_LOCK, true, 1577 state->active_locks); 1578 return 0; 1579 } 1580 1581 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1582 { 1583 struct bpf_verifier_state *state = env->cur_state; 1584 struct bpf_reference_state *s; 1585 1586 s = acquire_reference_state(env, insn_idx); 1587 if (!s) 1588 return -ENOMEM; 1589 s->type = REF_TYPE_IRQ; 1590 s->id = ++env->id_gen; 1591 1592 state->active_irq_id = s->id; 1593 bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_IRQ, true, 1594 bpf_diag_irq_depth(state)); 1595 return s->id; 1596 } 1597 1598 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1599 { 1600 int last_idx; 1601 size_t rem; 1602 1603 /* IRQ state requires the relative ordering of elements remaining the 1604 * same, since it relies on the refs array to behave as a stack, so that 1605 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1606 * the array instead of swapping the final element into the deleted idx. 1607 */ 1608 last_idx = state->acquired_refs - 1; 1609 rem = state->acquired_refs - idx - 1; 1610 if (last_idx && idx != last_idx) 1611 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1612 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1613 state->acquired_refs--; 1614 return; 1615 } 1616 1617 static bool find_reference_state(struct bpf_verifier_state *state, int id) 1618 { 1619 int i; 1620 1621 for (i = 0; i < state->acquired_refs; i++) { 1622 if (state->refs[i].type != REF_TYPE_PTR) 1623 continue; 1624 if (state->refs[i].id == id) 1625 return true; 1626 } 1627 1628 return false; 1629 } 1630 1631 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 1632 { 1633 return find_reference_state(env->cur_state, reg->id); 1634 } 1635 1636 static u32 reg_lifetime_id(struct bpf_verifier_env *env, 1637 const struct bpf_reg_state *reg) 1638 { 1639 return reg_is_referenced(env, reg) ? reg->id : reg->parent_id; 1640 } 1641 1642 static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr) 1643 { 1644 struct bpf_verifier_state *state = env->cur_state; 1645 void *prev_ptr = NULL; 1646 u32 prev_id = 0; 1647 int i; 1648 1649 for (i = 0; i < state->acquired_refs; i++) { 1650 if (state->refs[i].type == type && state->refs[i].id == id && 1651 state->refs[i].ptr == ptr) { 1652 release_reference_state(state, i); 1653 state->active_locks--; 1654 /* Reassign active lock (id, ptr). */ 1655 state->active_lock_id = prev_id; 1656 state->active_lock_ptr = prev_ptr; 1657 bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_LOCK, 1658 false, state->active_locks); 1659 return 0; 1660 } 1661 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1662 prev_id = state->refs[i].id; 1663 prev_ptr = state->refs[i].ptr; 1664 } 1665 } 1666 return -EINVAL; 1667 } 1668 1669 static int release_irq_state(struct bpf_verifier_env *env, int id) 1670 { 1671 struct bpf_verifier_state *state = env->cur_state; 1672 u32 prev_id = 0; 1673 int i; 1674 1675 if (id != state->active_irq_id) 1676 return -EACCES; 1677 1678 for (i = 0; i < state->acquired_refs; i++) { 1679 if (state->refs[i].type != REF_TYPE_IRQ) 1680 continue; 1681 if (state->refs[i].id == id) { 1682 release_reference_state(state, i); 1683 state->active_irq_id = prev_id; 1684 bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_IRQ, 1685 false, bpf_diag_irq_depth(state)); 1686 return 0; 1687 } else { 1688 prev_id = state->refs[i].id; 1689 } 1690 } 1691 return -EINVAL; 1692 } 1693 1694 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1695 int id, void *ptr) 1696 { 1697 int i; 1698 1699 for (i = 0; i < state->acquired_refs; i++) { 1700 struct bpf_reference_state *s = &state->refs[i]; 1701 1702 if (!(s->type & type)) 1703 continue; 1704 1705 if (s->id == id && s->ptr == ptr) 1706 return s; 1707 } 1708 return NULL; 1709 } 1710 1711 static void free_func_state(struct bpf_func_state *state) 1712 { 1713 if (!state) 1714 return; 1715 kfree(state->loop_stack); 1716 kfree(state->stack_arg_regs); 1717 kfree(state->stack); 1718 kfree(state); 1719 } 1720 1721 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1722 { 1723 kfree(state->jmp_history); 1724 state->jmp_history = NULL; 1725 state->jmp_history_cnt = 0; 1726 } 1727 1728 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1729 bool free_self) 1730 { 1731 int i; 1732 1733 for (i = 0; i <= state->curframe; i++) { 1734 free_func_state(state->frame[i]); 1735 state->frame[i] = NULL; 1736 } 1737 kfree(state->refs); 1738 bpf_clear_jmp_history(state); 1739 if (free_self) 1740 kfree(state); 1741 } 1742 1743 /* copy verifier state from src to dst growing dst stack space 1744 * when necessary to accommodate larger src stack 1745 */ 1746 static int copy_func_state(struct bpf_func_state *dst, 1747 const struct bpf_func_state *src) 1748 { 1749 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1750 /* Instruction accounting is path-local, not part of verifier state. */ 1751 dst->insns_subtotal = 0; 1752 dst->loop_stack = copy_array(dst->loop_stack, src->loop_stack, src->loop_stack_cnt, 1753 sizeof(*src->loop_stack), GFP_KERNEL_ACCOUNT); 1754 if (!dst->loop_stack) 1755 return -ENOMEM; 1756 return copy_stack_state(dst, src); 1757 } 1758 1759 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1760 const struct bpf_verifier_state *src) 1761 { 1762 struct bpf_func_state *dst; 1763 int i, err; 1764 1765 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1766 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1767 GFP_KERNEL_ACCOUNT); 1768 if (!dst_state->jmp_history) 1769 return -ENOMEM; 1770 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1771 1772 /* if dst has more stack frames then src frame, free them, this is also 1773 * necessary in case of exceptional exits using bpf_throw. 1774 */ 1775 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1776 free_func_state(dst_state->frame[i]); 1777 dst_state->frame[i] = NULL; 1778 } 1779 err = copy_reference_state(dst_state, src); 1780 if (err) 1781 return err; 1782 dst_state->speculative = src->speculative; 1783 dst_state->in_sleepable = src->in_sleepable; 1784 dst_state->unwound = src->unwound; 1785 dst_state->curframe = src->curframe; 1786 dst_state->branches = src->branches; 1787 dst_state->parent = src->parent; 1788 dst_state->first_insn_idx = src->first_insn_idx; 1789 dst_state->last_insn_idx = src->last_insn_idx; 1790 dst_state->dfs_depth = src->dfs_depth; 1791 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1792 dst_state->may_goto_depth = src->may_goto_depth; 1793 dst_state->equal_state = src->equal_state; 1794 for (i = 0; i <= src->curframe; i++) { 1795 dst = dst_state->frame[i]; 1796 if (!dst) { 1797 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1798 if (!dst) 1799 return -ENOMEM; 1800 dst_state->frame[i] = dst; 1801 } 1802 err = copy_func_state(dst, src->frame[i]); 1803 if (err) 1804 return err; 1805 } 1806 return 0; 1807 } 1808 1809 static u32 state_htab_size(struct bpf_verifier_env *env) 1810 { 1811 return env->prog->len; 1812 } 1813 1814 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1815 { 1816 struct bpf_verifier_state *cur = env->cur_state; 1817 struct bpf_func_state *state = cur->frame[cur->curframe]; 1818 1819 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1820 } 1821 1822 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1823 { 1824 int fr; 1825 1826 if (a->curframe != b->curframe) 1827 return false; 1828 1829 for (fr = a->curframe; fr >= 0; fr--) 1830 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1831 return false; 1832 1833 return true; 1834 } 1835 1836 void bpf_free_backedges(struct bpf_scc_visit *visit) 1837 { 1838 struct bpf_scc_backedge *backedge, *next; 1839 1840 for (backedge = visit->backedges; backedge; backedge = next) { 1841 bpf_free_verifier_state(&backedge->state, false); 1842 next = backedge->next; 1843 kfree(backedge); 1844 } 1845 visit->backedges = NULL; 1846 } 1847 1848 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1849 int *insn_idx, bool pop_log) 1850 { 1851 struct bpf_verifier_state *cur = env->cur_state; 1852 struct bpf_verifier_stack_elem *elem, *head = env->head; 1853 int err; 1854 1855 if (env->head == NULL) 1856 return -ENOENT; 1857 1858 if (cur) { 1859 err = bpf_copy_verifier_state(cur, &head->st); 1860 if (err) 1861 return err; 1862 bpf_diag_event_log_restore(env, head->diag_log_pos); 1863 } 1864 if (pop_log) 1865 bpf_vlog_reset(&env->log, head->log_pos); 1866 if (insn_idx) 1867 *insn_idx = head->insn_idx; 1868 if (prev_insn_idx) 1869 *prev_insn_idx = head->prev_insn_idx; 1870 elem = head->next; 1871 bpf_free_verifier_state(&head->st, false); 1872 kfree(head); 1873 env->head = elem; 1874 env->stack_size--; 1875 return 0; 1876 } 1877 1878 static bool error_recoverable_with_nospec(int err) 1879 { 1880 /* Should only return true for non-fatal errors that are allowed to 1881 * occur during speculative verification. For these we can insert a 1882 * nospec and the program might still be accepted. Do not include 1883 * something like ENOMEM because it is likely to re-occur for the next 1884 * architectural path once it has been recovered-from in all speculative 1885 * paths. 1886 */ 1887 return err == -EPERM || err == -EACCES || err == -EINVAL; 1888 } 1889 1890 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1891 int insn_idx, int prev_insn_idx, 1892 bool speculative) 1893 { 1894 struct bpf_verifier_state *cur = env->cur_state; 1895 struct bpf_verifier_stack_elem *elem; 1896 int err; 1897 1898 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1899 if (!elem) 1900 return ERR_PTR(-ENOMEM); 1901 1902 elem->insn_idx = insn_idx; 1903 elem->prev_insn_idx = prev_insn_idx; 1904 elem->next = env->head; 1905 elem->log_pos = env->log.end_pos; 1906 elem->diag_log_pos = bpf_diag_event_log_save(env); 1907 env->head = elem; 1908 env->stack_size++; 1909 err = bpf_copy_verifier_state(&elem->st, cur); 1910 if (err) 1911 return ERR_PTR(-ENOMEM); 1912 elem->st.speculative |= speculative; 1913 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1914 verbose(env, "The sequence of %d jumps is too complex.\n", 1915 env->stack_size); 1916 return ERR_PTR(-E2BIG); 1917 } 1918 if (elem->st.parent) { 1919 ++elem->st.parent->branches; 1920 /* WARN_ON(branches > 2) technically makes sense here, 1921 * but 1922 * 1. speculative states will bump 'branches' for non-branch 1923 * instructions 1924 * 2. is_state_visited() heuristics may decide not to create 1925 * a new state for a sequence of branches and all such current 1926 * and cloned states will be pointing to a single parent state 1927 * which might have large 'branches' count. 1928 */ 1929 } 1930 return &elem->st; 1931 } 1932 1933 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno) 1934 { 1935 char *buf = env->tmp_arg_name; 1936 int len = sizeof(env->tmp_arg_name); 1937 int arg, regno = reg_from_argno(argno); 1938 1939 if (regno >= 0) { 1940 snprintf(buf, len, "R%d", regno); 1941 } else { 1942 arg = arg_from_argno(argno); 1943 snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE); 1944 } 1945 1946 return buf; 1947 } 1948 1949 static const int caller_saved[CALLER_SAVED_REGS] = { 1950 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1951 }; 1952 1953 static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env, 1954 struct bpf_reg_state *regs) 1955 { 1956 int i; 1957 1958 for (i = 1; i < CALLER_SAVED_REGS; i++) { 1959 bpf_diag_record_scrub(env, ®s[caller_saved[i]], 1960 BPF_DIAG_MOD_CALLER_SAVED); 1961 } 1962 } 1963 1964 static void reg_step_reset(struct bpf_reg_state *reg) 1965 { 1966 reg->base = 0; 1967 reg->step = 1; 1968 } 1969 1970 static void scalar_step_add(struct bpf_reg_state *dst_reg, 1971 const struct bpf_reg_state *a, 1972 const struct bpf_reg_state *b) 1973 { 1974 const struct bpf_reg_state *reg; 1975 s64 amount, tmp; 1976 1977 if (tnum_is_const(b->var_off)) { 1978 reg = a; 1979 amount = (s64)b->var_off.value; 1980 } else if (tnum_is_const(a->var_off)) { 1981 reg = b; 1982 amount = (s64)a->var_off.value; 1983 } else { 1984 reg_step_reset(dst_reg); 1985 return; 1986 } 1987 1988 /* 1989 * Let x be a possible signed value of the register, 1990 * d = amount, s = reg->step, and b = reg->base. 1991 * Then x mod s = b, with s > 0 and 0 <= b < s. 1992 * If the addition causes signed underflow, the resulting value 1993 * is x + d + 2**64. 1994 * 1995 * Taking the result modulo s and substituting x mod s = b gives: 1996 * (x + d + 2**64) mod s = (b + d + (2**64 mod s)) mod s (1) 1997 * Keeping reg->step = s and updating reg->base to (b + d) mod s 1998 * requires (1) to equal (b + d) mod s, which holds if and only 1999 * if 2**64 mod s = 0. 2000 * Signed overflow subtracts 2**64 and has the same requirement. 2001 * 2002 * Conservatively reset the stride if either wrap is possible. 2003 */ 2004 if (check_add_overflow(reg_smin(reg), amount, &tmp) || 2005 check_add_overflow(reg_smax(reg), amount, &tmp)) { 2006 reg_step_reset(dst_reg); 2007 return; 2008 } 2009 2010 dst_reg->base = (reg->base + imod(amount, reg->step)) % reg->step; 2011 dst_reg->step = reg->step; 2012 } 2013 2014 static void scalar_step_scale(struct bpf_reg_state *dst_reg, u64 amount) 2015 { 2016 u16 step; 2017 s64 tmp; 2018 2019 /* 2020 * Using the same notation as scalar_step_add(), with d > 0, 2021 * the scaled value satisfies (x * d) mod (s * d) = b * d. 2022 * If the multiplication wraps, its signed result can be represented 2023 * as x * d - n * 2**64 for some nonzero integer n. 2024 * 2025 * Taking the result modulo s * d gives: 2026 * (x * d - n * 2**64) mod (s * d) = 2027 * (b * d - (n * 2**64 mod (s * d))) mod (s * d) (1) 2028 * Updating dst_reg->base to b * d and dst_reg->step to s * d 2029 * requires (1) to equal b * d, which holds if and only if 2030 * n * 2**64 mod (s * d) = 0. 2031 * 2032 * Conservatively reset the stride if a wrap is possible. 2033 */ 2034 if (amount == 0 || check_mul_overflow(dst_reg->step, amount, &step) || 2035 check_mul_overflow(reg_smin(dst_reg), (s64)amount, &tmp) || 2036 check_mul_overflow(reg_smax(dst_reg), (s64)amount, &tmp)) { 2037 reg_step_reset(dst_reg); 2038 return; 2039 } 2040 /* 2041 * The above established that `step = dst_reg->step * amount` 2042 * does not overflow, therefore the base < step invariant holds 2043 * after assignments below. 2044 */ 2045 dst_reg->base = dst_reg->base * amount; 2046 dst_reg->step = step; 2047 } 2048 2049 /* 2050 * Let x be a possible signed value of the register, 2051 * s = reg->step, and b = reg->base. 2052 * Then x mod s = b, with s > 0 and 0 <= b < s. 2053 * Truncating to N bits and then zero- or sign-extending x 2054 * is equivalent to computing x + k * 2**N for some integer k. 2055 * For example, sign-extending the low 8 bits of x = 255 can 2056 * be expressed as 255 - 2**8 = -1. 2057 * 2058 * Taking the result modulo s and substituting x mod s = b gives: 2059 * (x + k * 2**N) mod s = (b + (k * 2**N mod s)) mod s 2060 * Keeping reg->base = b and reg->step = s requires this to equal b, 2061 * which holds if and only if k * 2**N mod s = 0. 2062 * Continuing the example with s = 3 and b = 0, we have 255 mod 3 = 0, 2063 * but (-1) mod 3 = 2, so the original base and step no longer hold. 2064 * 2065 * Conservatively reset the stride unless all possible values fit in 2066 * the range where the conversion leaves them unchanged. 2067 * Call before updating the register's bounds. Requires 0 < bits < 64. 2068 */ 2069 static void reg_step_check_unsigned(struct bpf_reg_state *reg, u32 bits) 2070 { 2071 if (reg_umax(reg) >= (1ULL << bits)) 2072 reg_step_reset(reg); 2073 } 2074 2075 /* This helper doesn't clear reg->id */ 2076 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2077 { 2078 reg->var_off = tnum_const(imm); 2079 reg->r64 = cnum64_from_urange(imm, imm); 2080 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 2081 reg_step_reset(reg); 2082 } 2083 2084 /* Mark the unknown part of a register (variable offset or scalar value) as 2085 * known to have the value @imm. 2086 */ 2087 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2088 { 2089 /* Clear off and union(map_ptr, range) */ 2090 memset(((u8 *)reg) + sizeof(reg->type), 0, 2091 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2092 reg->id = 0; 2093 reg->parent_id = 0; 2094 reg->map_uid = 0; 2095 ___mark_reg_known(reg, imm); 2096 } 2097 2098 void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm) 2099 { 2100 __mark_reg_known(reg, imm); 2101 reg->type = SCALAR_VALUE; 2102 } 2103 2104 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2105 { 2106 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2107 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 2108 } 2109 2110 /* Mark the 'variable offset' part of a register as zero. This should be 2111 * used only on registers holding a pointer type. 2112 */ 2113 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2114 { 2115 __mark_reg_known(reg, 0); 2116 } 2117 2118 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2119 { 2120 __mark_reg_known(reg, 0); 2121 reg->type = SCALAR_VALUE; 2122 /* all scalars are assumed imprecise initially (unless unprivileged, 2123 * in which case everything is forced to be precise) 2124 */ 2125 reg->precise = !env->bpf_capable; 2126 } 2127 2128 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2129 struct bpf_reg_state *regs, u32 regno) 2130 { 2131 __mark_reg_known_zero(regs + regno); 2132 } 2133 2134 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2135 bool first_slot, int id, int parent_id) 2136 { 2137 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2138 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2139 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2140 */ 2141 __mark_reg_known_zero(reg); 2142 reg->type = CONST_PTR_TO_DYNPTR; 2143 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2144 reg->id = id; 2145 reg->parent_id = parent_id; 2146 reg->dynptr.type = type; 2147 reg->dynptr.first_slot = first_slot; 2148 } 2149 2150 /* 2151 * Refine the return type of the bpf_map_lookup_elem() for special map types: 2152 * map-in-map, xskmap, sockmap and sockhash. 2153 */ 2154 static void refine_map_lookup_value(struct bpf_reg_state *reg) 2155 { 2156 enum bpf_type_flag maybe_null = reg->type & PTR_MAYBE_NULL; 2157 const struct bpf_map *map = reg->map_ptr; 2158 2159 if (map->inner_map_meta) { 2160 reg->type = CONST_PTR_TO_MAP | maybe_null; 2161 reg->map_ptr = map->inner_map_meta; 2162 /* 2163 * transfer reg's id which is unique for every map_lookup_elem 2164 * as UID of the inner map. 2165 */ 2166 reg->map_uid = reg->id; 2167 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2168 reg->type = PTR_TO_XDP_SOCK | maybe_null; 2169 reg->map_uid = 0; 2170 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2171 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2172 reg->type = PTR_TO_SOCKET | maybe_null; 2173 reg->map_uid = 0; 2174 } 2175 } 2176 2177 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2178 { 2179 reg->type &= ~PTR_MAYBE_NULL; 2180 } 2181 2182 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2183 struct btf_field_graph_root *ds_head) 2184 { 2185 __mark_reg_known(®s[regno], ds_head->node_offset); 2186 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2187 regs[regno].btf = ds_head->btf; 2188 regs[regno].btf_id = ds_head->value_btf_id; 2189 } 2190 2191 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2192 { 2193 return type_is_pkt_pointer(reg->type); 2194 } 2195 2196 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2197 { 2198 return reg_is_pkt_pointer(reg) || 2199 reg->type == PTR_TO_PACKET_END; 2200 } 2201 2202 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2203 { 2204 return base_type(reg->type) == PTR_TO_MEM && 2205 (reg->type & 2206 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 2207 } 2208 2209 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2210 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2211 enum bpf_reg_type which) 2212 { 2213 /* The register can already have a range from prior markings. 2214 * This is fine as long as it hasn't been advanced from its 2215 * origin. 2216 */ 2217 return reg->type == which && 2218 reg->id == 0 && 2219 tnum_equals_const(reg->var_off, 0); 2220 } 2221 2222 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2223 { 2224 reg->r32 = CNUM32_UNBOUNDED; 2225 } 2226 2227 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2228 { 2229 reg->r64 = CNUM64_UNBOUNDED; 2230 } 2231 2232 /* Reset the min/max bounds of a register */ 2233 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2234 { 2235 __mark_reg64_unbounded(reg); 2236 __mark_reg32_unbounded(reg); 2237 } 2238 2239 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 2240 { 2241 __mark_reg64_unbounded(reg); 2242 reg->var_off = tnum_unknown; 2243 } 2244 2245 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 2246 { 2247 __mark_reg32_unbounded(reg); 2248 reg->var_off = tnum_unknown; 2249 } 2250 2251 static struct cnum32 cnum32_from_tnum(struct tnum tnum) 2252 { 2253 tnum = tnum_subreg(tnum); 2254 if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN)) 2255 /* min signed is max(sign bit) | min(other bits) */ 2256 /* max signed is min(sign bit) | max(other bits) */ 2257 return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN), 2258 tnum.value | (tnum.mask & S32_MAX)); 2259 else 2260 return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask)); 2261 } 2262 2263 static struct cnum64 cnum64_from_tnum(struct tnum tnum) 2264 { 2265 if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN)) 2266 /* min signed is max(sign bit) | min(other bits) */ 2267 /* max signed is min(sign bit) | max(other bits) */ 2268 return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN), 2269 tnum.value | (tnum.mask & S64_MAX)); 2270 else 2271 return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask)); 2272 } 2273 2274 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2275 { 2276 cnum32_intersect_with(®->r32, cnum32_from_tnum(reg->var_off)); 2277 } 2278 2279 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2280 { 2281 u64 tnum_next, tmax; 2282 bool umin_in_tnum; 2283 2284 cnum64_intersect_with(®->r64, cnum64_from_tnum(reg->var_off)); 2285 2286 /* Check if u64 and tnum overlap in a single value */ 2287 tnum_next = tnum_step(reg->var_off, reg_umin(reg)); 2288 umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value; 2289 tmax = reg->var_off.value | reg->var_off.mask; 2290 if (umin_in_tnum && tnum_next > reg_umax(reg)) { 2291 /* The u64 range and the tnum only overlap in umin. 2292 * u64: ---[xxxxxx]----- 2293 * tnum: --xx----------x- 2294 */ 2295 ___mark_reg_known(reg, reg_umin(reg)); 2296 } else if (!umin_in_tnum && tnum_next == tmax) { 2297 /* The u64 range and the tnum only overlap in the maximum value 2298 * represented by the tnum, called tmax. 2299 * u64: ---[xxxxxx]----- 2300 * tnum: xx-----x-------- 2301 */ 2302 ___mark_reg_known(reg, tmax); 2303 } else if (!umin_in_tnum && tnum_next <= reg_umax(reg) && 2304 tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) { 2305 /* The u64 range and the tnum only overlap in between umin 2306 * (excluded) and umax. 2307 * u64: ---[xxxxxx]----- 2308 * tnum: xx----x-------x- 2309 */ 2310 ___mark_reg_known(reg, tnum_next); 2311 } 2312 } 2313 2314 static void __update_reg_bounds(struct bpf_reg_state *reg) 2315 { 2316 __update_reg32_bounds(reg); 2317 __update_reg64_bounds(reg); 2318 } 2319 2320 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2321 { 2322 cnum32_intersect_with(®->r32, cnum32_from_cnum64(reg->r64)); 2323 } 2324 2325 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2326 { 2327 reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32); 2328 } 2329 2330 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2331 { 2332 deduce_bounds_32_from_64(reg); 2333 deduce_bounds_64_from_32(reg); 2334 } 2335 2336 /* Attempts to improve var_off based on unsigned min/max information */ 2337 static void __reg_bound_offset(struct bpf_reg_state *reg) 2338 { 2339 struct tnum var64_off = tnum_intersect(reg->var_off, 2340 tnum_range(reg_umin(reg), 2341 reg_umax(reg))); 2342 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2343 tnum_range(reg_u32_min(reg), 2344 reg_u32_max(reg))); 2345 u32 trailing_zero_bits; 2346 u16 base = reg->base; 2347 u16 step = reg->step; 2348 2349 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2350 2351 if (base == 0) 2352 trailing_zero_bits = count_trailing_zeros(step); 2353 else 2354 trailing_zero_bits = min(count_trailing_zeros(base), 2355 count_trailing_zeros(step)); 2356 reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits)); 2357 } 2358 2359 static void __update_bounds_from_step(struct bpf_reg_state *reg) 2360 { 2361 reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step); 2362 deduce_bounds_32_from_64(reg); 2363 } 2364 2365 static bool range_bounds_violation(struct bpf_reg_state *reg); 2366 2367 static void reg_bounds_sync(struct bpf_reg_state *reg) 2368 { 2369 /* If the input reg_state is invalid, we can exit early */ 2370 if (range_bounds_violation(reg)) 2371 return; 2372 /* We might have learned new bounds from the var_off. */ 2373 __update_reg_bounds(reg); 2374 /* We might have learned something about the sign bit. */ 2375 __reg_deduce_bounds(reg); 2376 __reg_deduce_bounds(reg); 2377 /* We might have learned some bits from the bounds. */ 2378 __reg_bound_offset(reg); 2379 /* Intersecting with the old var_off might have improved our bounds 2380 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2381 * then new var_off is (0; 0x7f...fc) which improves our umax. 2382 */ 2383 __update_reg_bounds(reg); 2384 /* 2385 * Both tnum and base+step define a sequence of points, 2386 * potentially w/o intersection, or intersecting after N 2387 * tnum_step()'s, where N can be large. On the other hand, 2388 * step+base *must* be in sync with r64 in order for 2389 * array traversal logic starting at reg_smin() to be sound. 2390 * Hence, place this as a final step in the reg_bounds_sync(). 2391 */ 2392 __update_bounds_from_step(reg); 2393 } 2394 2395 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2396 { 2397 if (!tnum_is_const(reg->var_off)) 2398 return false; 2399 2400 return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value; 2401 } 2402 2403 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2404 { 2405 if (!tnum_subreg_is_const(reg->var_off)) 2406 return false; 2407 2408 return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value; 2409 } 2410 2411 static bool range_bounds_violation(struct bpf_reg_state *reg) 2412 { 2413 return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64); 2414 } 2415 2416 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2417 struct bpf_reg_state *reg, const char *ctx) 2418 { 2419 const char *msg; 2420 2421 if (range_bounds_violation(reg)) { 2422 msg = "range bounds violation"; 2423 goto out; 2424 } 2425 2426 if (const_tnum_range_mismatch(reg)) { 2427 msg = "const tnum out of sync with range bounds"; 2428 goto out; 2429 } 2430 2431 if (const_tnum_range_mismatch_32(reg)) { 2432 msg = "const subreg tnum out of sync with range bounds"; 2433 goto out; 2434 } 2435 2436 if (reg->step == 0 || reg->base >= reg->step) { 2437 msg = "invalid base/step"; 2438 goto out; 2439 } 2440 2441 return 0; 2442 out: 2443 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} " 2444 "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx) step=%u+%u", 2445 ctx, msg, 2446 reg->r64.base, reg->r64.size, 2447 reg->r32.base, reg->r32.size, 2448 reg->var_off.value, reg->var_off.mask, 2449 reg->base, reg->step); 2450 if (env->test_reg_invariants) 2451 return -EFAULT; 2452 __mark_reg_unbounded(reg); 2453 reg_step_reset(reg); 2454 return 0; 2455 } 2456 2457 /* Mark a register as having a completely unknown (scalar) value. */ 2458 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2459 { 2460 memset(reg, 0, sizeof(*reg)); 2461 reg->type = SCALAR_VALUE; 2462 reg->var_off = tnum_unknown; 2463 __mark_reg_unbounded(reg); 2464 reg_step_reset(reg); 2465 } 2466 2467 /* Mark a register as having a completely unknown (scalar) value, 2468 * initialize .precise as true when not bpf capable. 2469 */ 2470 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2471 struct bpf_reg_state *reg) 2472 { 2473 bpf_mark_reg_unknown_imprecise(reg); 2474 reg->precise = !env->bpf_capable; 2475 } 2476 2477 static void mark_reg_unknown(struct bpf_verifier_env *env, 2478 struct bpf_reg_state *regs, u32 regno) 2479 { 2480 __mark_reg_unknown(env, regs + regno); 2481 } 2482 2483 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2484 struct bpf_reg_state *regs, 2485 u32 regno, 2486 s32 s32_min, 2487 s32 s32_max) 2488 { 2489 struct bpf_reg_state *reg = regs + regno; 2490 2491 reg_set_srange32(reg, 2492 max_t(s32, reg_s32_min(reg), s32_min), 2493 min_t(s32, reg_s32_max(reg), s32_max)); 2494 reg_set_srange64(reg, 2495 max_t(s64, reg_smin(reg), s32_min), 2496 min_t(s64, reg_smax(reg), s32_max)); 2497 2498 reg_bounds_sync(reg); 2499 2500 return reg_bounds_sanity_check(env, reg, "s32_range"); 2501 } 2502 2503 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 2504 struct bpf_reg_state *reg) 2505 { 2506 __mark_reg_unknown(env, reg); 2507 reg->type = NOT_INIT; 2508 } 2509 2510 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2511 struct bpf_reg_state *regs, u32 regno, 2512 enum bpf_reg_type reg_type, 2513 struct btf *btf, u32 btf_id, 2514 enum bpf_type_flag flag) 2515 { 2516 switch (reg_type) { 2517 case SCALAR_VALUE: 2518 mark_reg_unknown(env, regs, regno); 2519 return 0; 2520 case PTR_TO_BTF_ID: 2521 mark_reg_known_zero(env, regs, regno); 2522 regs[regno].type = PTR_TO_BTF_ID | flag; 2523 regs[regno].btf = btf; 2524 regs[regno].btf_id = btf_id; 2525 if (type_may_be_null(flag)) 2526 regs[regno].id = ++env->id_gen; 2527 return 0; 2528 case PTR_TO_MEM: 2529 mark_reg_known_zero(env, regs, regno); 2530 regs[regno].type = PTR_TO_MEM | flag; 2531 regs[regno].mem_size = 0; 2532 return 0; 2533 default: 2534 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2535 return -EFAULT; 2536 } 2537 } 2538 2539 static void init_reg_state(struct bpf_verifier_env *env, 2540 struct bpf_func_state *state) 2541 { 2542 struct bpf_reg_state *regs = state->regs; 2543 int i; 2544 2545 for (i = 0; i < MAX_BPF_REG; i++) { 2546 bpf_mark_reg_not_init(env, ®s[i]); 2547 } 2548 2549 /* frame pointer */ 2550 regs[BPF_REG_FP].type = PTR_TO_STACK; 2551 mark_reg_known_zero(env, regs, BPF_REG_FP); 2552 regs[BPF_REG_FP].frameno = state->frameno; 2553 } 2554 2555 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2556 { 2557 /* 2558 * return_32bit is set to false by default and set explicitly 2559 * by the caller when necessary. 2560 */ 2561 return (struct bpf_retval_range){ minval, maxval, false }; 2562 } 2563 2564 static void init_func_state(struct bpf_verifier_env *env, 2565 struct bpf_func_state *state, 2566 int callsite, int frameno, int subprogno) 2567 { 2568 state->callsite = callsite; 2569 state->frameno = frameno; 2570 bpf_diag_init_frame(env, state); 2571 state->subprogno = subprogno; 2572 state->callback_ret_range = retval_range(0, 0); 2573 init_reg_state(env, state); 2574 mark_verifier_state_scratched(env); 2575 } 2576 2577 /* Similar to push_stack(), but for async callbacks */ 2578 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2579 int insn_idx, int prev_insn_idx, 2580 int subprog, bool is_sleepable) 2581 { 2582 struct bpf_verifier_stack_elem *elem; 2583 struct bpf_func_state *frame; 2584 2585 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2586 if (!elem) 2587 return ERR_PTR(-ENOMEM); 2588 2589 elem->insn_idx = insn_idx; 2590 elem->prev_insn_idx = prev_insn_idx; 2591 elem->next = env->head; 2592 elem->log_pos = env->log.end_pos; 2593 elem->diag_log_pos = bpf_diag_event_log_save(env); 2594 env->head = elem; 2595 env->stack_size++; 2596 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2597 verbose(env, 2598 "The sequence of %d jumps is too complex for async cb.\n", 2599 env->stack_size); 2600 return ERR_PTR(-E2BIG); 2601 } 2602 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2603 * The caller state doesn't matter. 2604 * This is async callback. It starts in a fresh stack. 2605 * Initialize it similar to do_check_common(). 2606 */ 2607 elem->st.branches = 1; 2608 elem->st.in_sleepable = is_sleepable; 2609 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2610 if (!frame) 2611 return ERR_PTR(-ENOMEM); 2612 init_func_state(env, frame, 2613 BPF_MAIN_FUNC /* callsite */, 2614 0 /* frameno within this callchain */, 2615 subprog /* subprog number within this prog */); 2616 elem->st.frame[0] = frame; 2617 return &elem->st; 2618 } 2619 2620 /* Find subprogram that contains instruction at 'off' */ 2621 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2622 { 2623 struct bpf_subprog_info *vals = env->subprog_info; 2624 int l, r, m; 2625 2626 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2627 return NULL; 2628 2629 l = 0; 2630 r = env->subprog_cnt - 1; 2631 while (l < r) { 2632 m = l + (r - l + 1) / 2; 2633 if (vals[m].start <= off) 2634 l = m; 2635 else 2636 r = m - 1; 2637 } 2638 return &vals[l]; 2639 } 2640 2641 /* Find subprogram that starts exactly at 'off' */ 2642 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2643 { 2644 struct bpf_subprog_info *p; 2645 2646 p = bpf_find_containing_subprog(env, off); 2647 if (!p || p->start != off) 2648 return -ENOENT; 2649 return p - env->subprog_info; 2650 } 2651 2652 static int add_subprog(struct bpf_verifier_env *env, int off) 2653 { 2654 struct bpf_subprog_info *subprog = env->subprog_info; 2655 int insn_cnt = env->prog->len; 2656 int i; 2657 2658 if (off >= insn_cnt || off < 0) { 2659 verbose(env, "call to invalid destination\n"); 2660 return -EINVAL; 2661 } 2662 i = bpf_find_subprog(env, off); 2663 if (i >= 0) 2664 return i; 2665 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2666 verbose(env, "too many subprograms\n"); 2667 return -E2BIG; 2668 } 2669 /* 2670 * Determine subprog starts. The end is one before the next starts. 2671 * The array stays sorted: subprogs that start after 'off' move up. 2672 */ 2673 for (i = env->subprog_cnt++; i > 0 && subprog[i - 1].start > off; i--) 2674 subprog[i] = subprog[i - 1]; 2675 subprog[i] = (struct bpf_subprog_info){ .start = off, .exit_idx = U32_MAX }; 2676 return i; 2677 } 2678 2679 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2680 { 2681 struct bpf_prog_aux *aux = env->prog->aux; 2682 struct btf *btf = aux->btf; 2683 const struct btf_type *t; 2684 u32 main_btf_id, id; 2685 const char *name; 2686 int ret, i; 2687 2688 /* Non-zero func_info_cnt implies valid btf */ 2689 if (!aux->func_info_cnt) 2690 return 0; 2691 main_btf_id = aux->func_info[0].type_id; 2692 2693 t = btf_type_by_id(btf, main_btf_id); 2694 if (!t) { 2695 verbose(env, "invalid btf id for main subprog in func_info\n"); 2696 return -EINVAL; 2697 } 2698 2699 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2700 if (IS_ERR(name)) { 2701 ret = PTR_ERR(name); 2702 /* If there is no tag present, there is no exception callback */ 2703 if (ret == -ENOENT) 2704 ret = 0; 2705 else if (ret == -EEXIST) 2706 verbose(env, "multiple exception callback tags for main subprog\n"); 2707 return ret; 2708 } 2709 2710 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2711 if (ret < 0) { 2712 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2713 return ret; 2714 } 2715 id = ret; 2716 t = btf_type_by_id(btf, id); 2717 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2718 verbose(env, "exception callback '%s' must have global linkage\n", name); 2719 return -EINVAL; 2720 } 2721 ret = 0; 2722 for (i = 0; i < aux->func_info_cnt; i++) { 2723 if (aux->func_info[i].type_id != id) 2724 continue; 2725 ret = aux->func_info[i].insn_off; 2726 /* Further func_info and subprog checks will also happen 2727 * later, so assume this is the right insn_off for now. 2728 */ 2729 if (!ret) { 2730 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2731 ret = -EINVAL; 2732 } 2733 } 2734 if (!ret) { 2735 verbose(env, "exception callback type id not found in func_info\n"); 2736 ret = -EINVAL; 2737 } 2738 return ret; 2739 } 2740 2741 #define MAX_KFUNC_BTFS 256 2742 2743 struct bpf_kfunc_btf { 2744 struct btf *btf; 2745 struct module *module; 2746 u16 offset; 2747 }; 2748 2749 struct bpf_kfunc_btf_tab { 2750 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2751 u32 nr_descs; 2752 }; 2753 2754 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2755 { 2756 const struct bpf_kfunc_desc *d0 = a; 2757 const struct bpf_kfunc_desc *d1 = b; 2758 2759 /* func_id is not greater than BTF_MAX_TYPE */ 2760 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2761 } 2762 2763 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2764 { 2765 const struct bpf_kfunc_btf *d0 = a; 2766 const struct bpf_kfunc_btf *d1 = b; 2767 2768 return d0->offset - d1->offset; 2769 } 2770 2771 static struct bpf_kfunc_desc * 2772 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2773 { 2774 struct bpf_kfunc_desc desc = { 2775 .func_id = func_id, 2776 .offset = offset, 2777 }; 2778 struct bpf_kfunc_desc_tab *tab; 2779 2780 tab = prog->aux->kfunc_tab; 2781 return bsearch(&desc, tab->descs, tab->nr_base_descs, 2782 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2783 } 2784 2785 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2786 u16 desc_idx, u8 **func_addr) 2787 { 2788 struct bpf_kfunc_desc_tab *tab; 2789 const struct bpf_kfunc_desc *desc; 2790 2791 tab = prog->aux->kfunc_tab; 2792 if (desc_idx >= tab->nr_descs) 2793 return -EFAULT; 2794 desc = &tab->descs[desc_idx]; 2795 if (desc->func_id != func_id) 2796 return -EFAULT; 2797 2798 *func_addr = (u8 *)desc->addr; 2799 return 0; 2800 } 2801 2802 #define BPF_FD_SLOT_BTF 1UL 2803 2804 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map) 2805 { 2806 slot->val = (unsigned long)map; 2807 } 2808 2809 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf) 2810 { 2811 slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF; 2812 } 2813 2814 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot) 2815 { 2816 if (slot.val & BPF_FD_SLOT_BTF) 2817 return NULL; 2818 return (struct bpf_map *)slot.val; 2819 } 2820 2821 static struct btf *fd_slot_btf(struct bpf_fd_array slot) 2822 { 2823 if (!(slot.val & BPF_FD_SLOT_BTF)) 2824 return NULL; 2825 return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF); 2826 } 2827 2828 static struct btf * 2829 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx) 2830 { 2831 struct btf *btf; 2832 2833 if (idx >= env->fd_array_cnt) { 2834 verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n", 2835 idx, env->fd_array_cnt); 2836 return ERR_PTR(-EINVAL); 2837 } 2838 btf = fd_slot_btf(env->fd_array[idx]); 2839 if (!btf) { 2840 verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx); 2841 return ERR_PTR(-EINVAL); 2842 } 2843 btf_get(btf); 2844 return btf; 2845 } 2846 2847 static struct btf * 2848 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx) 2849 { 2850 struct btf *btf; 2851 int btf_fd; 2852 2853 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw, 2854 (size_t)idx * sizeof(btf_fd), sizeof(btf_fd))) 2855 return ERR_PTR(-EFAULT); 2856 btf = btf_get_by_fd(btf_fd); 2857 if (IS_ERR(btf)) { 2858 verbose(env, "invalid module BTF fd specified\n"); 2859 return btf; 2860 } 2861 return btf; 2862 } 2863 2864 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx) 2865 { 2866 if (env->signature) { 2867 verbose(env, "signed program cannot bind any BTF\n"); 2868 return ERR_PTR(-EACCES); 2869 } 2870 if (env->fd_array) 2871 return fd_array_get_btf_continuous(env, idx); 2872 if (!bpfptr_is_null(env->fd_array_raw)) 2873 return fd_array_get_btf_sparse(env, idx); 2874 2875 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2876 return ERR_PTR(-EPROTO); 2877 } 2878 2879 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2880 s16 offset) 2881 { 2882 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2883 struct bpf_kfunc_btf_tab *tab; 2884 struct bpf_kfunc_btf *b; 2885 struct module *mod; 2886 struct btf *btf; 2887 2888 tab = env->prog->aux->kfunc_btf_tab; 2889 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2890 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2891 if (!b) { 2892 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2893 verbose(env, "too many different module BTFs\n"); 2894 return ERR_PTR(-E2BIG); 2895 } 2896 2897 btf = fd_array_get_btf(env, offset); 2898 if (IS_ERR(btf)) 2899 return btf; 2900 if (!btf_is_module(btf)) { 2901 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2902 btf_put(btf); 2903 return ERR_PTR(-EINVAL); 2904 } 2905 2906 mod = btf_try_get_module(btf); 2907 if (!mod) { 2908 btf_put(btf); 2909 return ERR_PTR(-ENXIO); 2910 } 2911 2912 b = &tab->descs[tab->nr_descs++]; 2913 b->btf = btf; 2914 b->module = mod; 2915 b->offset = offset; 2916 2917 /* sort() reorders entries by value, so b may no longer point 2918 * to the right entry after this 2919 */ 2920 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2921 kfunc_btf_cmp_by_off, NULL); 2922 } else { 2923 btf = b->btf; 2924 } 2925 2926 return btf; 2927 } 2928 2929 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2930 { 2931 if (!tab) 2932 return; 2933 2934 while (tab->nr_descs--) { 2935 module_put(tab->descs[tab->nr_descs].module); 2936 btf_put(tab->descs[tab->nr_descs].btf); 2937 } 2938 kfree(tab); 2939 } 2940 2941 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2942 { 2943 if (offset) { 2944 if (offset < 0) { 2945 /* In the future, this can be allowed to increase limit 2946 * of fd index into fd_array, interpreted as u16. 2947 */ 2948 verbose(env, "negative offset disallowed for kernel module function call\n"); 2949 return ERR_PTR(-EINVAL); 2950 } 2951 2952 return __find_kfunc_desc_btf(env, offset); 2953 } 2954 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2955 } 2956 2957 static struct btf *find_kfunc_desc_btf_cached(struct bpf_verifier_env *env, s16 offset) 2958 { 2959 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2960 struct bpf_kfunc_btf_tab *tab; 2961 struct bpf_kfunc_btf *b; 2962 2963 if (!offset) 2964 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2965 if (offset < 0) 2966 return ERR_PTR(-EINVAL); 2967 2968 tab = env->prog->aux->kfunc_btf_tab; 2969 if (!tab) 2970 return ERR_PTR(-ENOENT); 2971 2972 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2973 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2974 return b ? b->btf : ERR_PTR(-ENOENT); 2975 } 2976 2977 #define KF_IMPL_SUFFIX "_impl" 2978 2979 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log, 2980 struct btf *btf, 2981 const char *func_name) 2982 { 2983 const struct btf_type *func; 2984 char buf[KSYM_NAME_LEN]; 2985 s32 impl_id; 2986 int len; 2987 2988 len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX); 2989 if (len < 0 || len >= sizeof(buf)) { 2990 bpf_log(log, "function name %s%s is too long\n", 2991 func_name, KF_IMPL_SUFFIX); 2992 return NULL; 2993 } 2994 2995 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2996 if (impl_id <= 0) { 2997 bpf_log(log, "cannot find function %s in BTF\n", buf); 2998 return NULL; 2999 } 3000 3001 func = btf_type_by_id(btf, impl_id); 3002 3003 return btf_type_by_id(btf, func->type); 3004 } 3005 3006 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 3007 s32 func_id, 3008 s16 offset, 3009 struct bpf_kfunc_meta *kfunc) 3010 { 3011 const struct btf_type *func, *func_proto; 3012 const char *func_name; 3013 u32 *kfunc_flags; 3014 struct btf *btf; 3015 3016 if (func_id <= 0) { 3017 verbose(env, "invalid kernel function btf_id %d\n", func_id); 3018 return -EINVAL; 3019 } 3020 3021 btf = find_kfunc_desc_btf(env, offset); 3022 if (IS_ERR(btf)) { 3023 verbose(env, "failed to find BTF for kernel function\n"); 3024 return PTR_ERR(btf); 3025 } 3026 3027 /* 3028 * Note that kfunc_flags may be NULL at this point, which 3029 * means that we couldn't find func_id in any relevant 3030 * kfunc_id_set. This most likely indicates an invalid kfunc 3031 * call. However we don't fail with an error here, 3032 * and let the caller decide what to do with NULL kfunc->flags. 3033 */ 3034 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 3035 3036 func = btf_type_by_id(btf, func_id); 3037 if (!func || !btf_type_is_func(func)) { 3038 verbose(env, "kernel btf_id %d is not a function\n", func_id); 3039 return -EINVAL; 3040 } 3041 3042 func_name = btf_name_by_offset(btf, func->name_off); 3043 3044 /* 3045 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 3046 * can be found through the counterpart _impl kfunc. 3047 */ 3048 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 3049 func_proto = find_kfunc_impl_proto(&env->log, btf, func_name); 3050 else 3051 func_proto = btf_type_by_id(btf, func->type); 3052 3053 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 3054 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 3055 func_id); 3056 return -EINVAL; 3057 } 3058 3059 memset(kfunc, 0, sizeof(*kfunc)); 3060 kfunc->btf = btf; 3061 kfunc->id = func_id; 3062 kfunc->name = func_name; 3063 kfunc->proto = func_proto; 3064 kfunc->flags = kfunc_flags; 3065 3066 return 0; 3067 } 3068 3069 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 3070 const struct btf_func_model *fm, struct bpf_func_proto *proto); 3071 3072 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 3073 { 3074 struct bpf_call_arg_meta meta; 3075 struct bpf_kfunc_btf_tab *btf_tab; 3076 struct btf_func_model func_model; 3077 struct bpf_kfunc_desc_tab *tab; 3078 struct bpf_prog_aux *prog_aux; 3079 struct bpf_kfunc_meta kfunc; 3080 struct bpf_kfunc_desc *desc; 3081 unsigned long addr; 3082 int err; 3083 3084 prog_aux = env->prog->aux; 3085 tab = prog_aux->kfunc_tab; 3086 btf_tab = prog_aux->kfunc_btf_tab; 3087 if (!tab) { 3088 if (!btf_vmlinux) { 3089 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 3090 return -ENOTSUPP; 3091 } 3092 3093 if (!env->prog->jit_requested) { 3094 verbose(env, "JIT is required for calling kernel function\n"); 3095 return -ENOTSUPP; 3096 } 3097 3098 if (!bpf_jit_supports_kfunc_call()) { 3099 verbose(env, "JIT does not support calling kernel function\n"); 3100 return -ENOTSUPP; 3101 } 3102 3103 if (!env->prog->gpl_compatible) { 3104 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 3105 return -EINVAL; 3106 } 3107 3108 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 3109 if (!tab) 3110 return -ENOMEM; 3111 prog_aux->kfunc_tab = tab; 3112 } 3113 3114 env->prog->jit_required = 1; 3115 3116 /* func_id == 0 is always invalid, but instead of returning an error, be 3117 * conservative and wait until the code elimination pass before returning 3118 * error, so that invalid calls that get pruned out can be in BPF programs 3119 * loaded from userspace. It is also required that offset be untouched 3120 * for such calls. 3121 */ 3122 if (!func_id && !offset) 3123 return 0; 3124 3125 if (!btf_tab && offset) { 3126 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 3127 if (!btf_tab) 3128 return -ENOMEM; 3129 prog_aux->kfunc_btf_tab = btf_tab; 3130 } 3131 3132 if (find_kfunc_desc(env->prog, func_id, offset)) 3133 return 0; 3134 3135 if (tab->nr_base_descs == MAX_KFUNC_DESCS) { 3136 verbose(env, "too many different kernel function calls\n"); 3137 return -E2BIG; 3138 } 3139 if (tab->nr_descs != tab->nr_base_descs) { 3140 verifier_bug(env, "unexpected specialized func desc found (%d descs, %d base descs)", 3141 tab->nr_descs, tab->nr_base_descs); 3142 return -EFAULT; 3143 } 3144 3145 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 3146 if (err) 3147 return err; 3148 3149 addr = kallsyms_lookup_name(kfunc.name); 3150 if (!addr) { 3151 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 3152 return -EINVAL; 3153 } 3154 3155 if (bpf_dev_bound_kfunc_id(func_id)) { 3156 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 3157 if (err) 3158 return err; 3159 } 3160 3161 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 3162 if (err) 3163 return err; 3164 if (func_model.ret_size > 8) { 3165 if (kfunc.flags && (*kfunc.flags & KF_FASTCALL)) { 3166 verbose(env, "kfunc %s with >8-byte return is not supported with KF_FASTCALL\n", 3167 kfunc.name); 3168 return -EOPNOTSUPP; 3169 } 3170 if (!bpf_jit_supports_kfunc_ret_reg_pair()) { 3171 verbose(env, "kfunc %s with >8-byte return is not supported by JIT\n", 3172 kfunc.name); 3173 return -EOPNOTSUPP; 3174 } 3175 } 3176 3177 memset(&meta, 0, sizeof(meta)); 3178 meta.btf = kfunc.btf; 3179 meta.func_id = kfunc.id; 3180 meta.func_proto = kfunc.proto; 3181 meta.func_name = kfunc.name; 3182 meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0; 3183 3184 tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT); 3185 if (!tab) 3186 return -ENOMEM; 3187 prog_aux->kfunc_tab = tab; 3188 3189 desc = &tab->descs[tab->nr_descs]; 3190 memset(desc, 0, sizeof(*desc)); 3191 3192 err = gen_kfunc_arg_proto(env, &meta, &func_model, &desc->proto); 3193 if (err) 3194 return err; 3195 3196 desc->func_id = func_id; 3197 desc->offset = offset; 3198 desc->addr = addr; 3199 desc->func_model = func_model; 3200 tab->nr_descs++; 3201 tab->nr_base_descs++; 3202 sort(tab->descs, tab->nr_base_descs, sizeof(tab->descs[0]), 3203 kfunc_desc_cmp_by_id_off, NULL); 3204 return 0; 3205 } 3206 3207 static int add_subprogs(struct bpf_verifier_env *env) 3208 { 3209 struct bpf_subprog_info *subprog = env->subprog_info; 3210 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3211 struct bpf_insn *insn = env->prog->insnsi; 3212 const char *operation, *suggestion; 3213 3214 /* Add entry function. */ 3215 ret = add_subprog(env, 0); 3216 if (ret) 3217 return ret; 3218 3219 for (i = 0; i < insn_cnt; i++, insn++) { 3220 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 3221 continue; 3222 3223 if (!env->bpf_capable) { 3224 if (bpf_pseudo_func(insn)) { 3225 operation = "BPF function reference"; 3226 suggestion = "Load this program with the required capability, or avoid BPF function references in unprivileged programs."; 3227 } else { 3228 operation = "BPF-to-BPF function call"; 3229 suggestion = "Load this program with the required capability, or avoid BPF-to-BPF function calls in unprivileged programs."; 3230 } 3231 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3232 bpf_diag_policy( 3233 env, i, operation, 3234 "loading or calling other BPF functions requires CAP_BPF or CAP_SYS_ADMIN", 3235 suggestion); 3236 return -EPERM; 3237 } 3238 3239 ret = add_subprog(env, i + insn->imm + 1); 3240 if (ret < 0) 3241 return ret; 3242 } 3243 3244 /* 3245 * func_info describes all functions of the program. Those that are 3246 * referenced only from data, e.g. from a table of functions to be 3247 * called via callx, are not seen by the loop above. They are possible 3248 * callees that have to be known upfront as well. 3249 */ 3250 if (env->bpf_capable) { 3251 struct bpf_prog_aux *aux = env->prog->aux; 3252 3253 for (i = 1; i < aux->func_info_cnt; i++) { 3254 ret = add_subprog(env, aux->func_info[i].insn_off); 3255 if (ret < 0) 3256 return ret; 3257 } 3258 } 3259 3260 ret = bpf_find_exception_callback_insn_off(env); 3261 if (ret < 0) 3262 return ret; 3263 ex_cb_insn = ret; 3264 3265 /* If ex_cb_insn > 0, this means that the main program has a subprog 3266 * marked using BTF decl tag to serve as the exception callback. 3267 */ 3268 if (ex_cb_insn) { 3269 ret = add_subprog(env, ex_cb_insn); 3270 if (ret < 0) 3271 return ret; 3272 for (i = 1; i < env->subprog_cnt; i++) { 3273 if (env->subprog_info[i].start != ex_cb_insn) 3274 continue; 3275 env->exception_callback_subprog = i; 3276 bpf_mark_subprog_exc_cb(env, i); 3277 break; 3278 } 3279 } 3280 3281 /* Add a fake 'exit' subprog which could simplify subprog iteration 3282 * logic. 'subprog_cnt' should not be increased. 3283 */ 3284 subprog[env->subprog_cnt].start = insn_cnt; 3285 3286 if (env->log.level & BPF_LOG_LEVEL2) 3287 for (i = 0; i < env->subprog_cnt; i++) 3288 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3289 3290 return 0; 3291 } 3292 3293 static int add_kfuncs(struct bpf_verifier_env *env) 3294 { 3295 struct bpf_insn *insn = env->prog->insnsi; 3296 int i, ret, insn_cnt = env->prog->len; 3297 3298 for (i = 0; i < insn_cnt; i++, insn++) { 3299 if (!bpf_pseudo_kfunc_call(insn)) 3300 continue; 3301 3302 if (!env->bpf_capable) { 3303 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3304 bpf_diag_policy( 3305 env, i, "kernel function call", 3306 "calling kernel functions requires CAP_BPF or CAP_SYS_ADMIN", 3307 "Load this program with the required capability, or avoid kernel function calls in unprivileged programs."); 3308 return -EPERM; 3309 } 3310 3311 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 3312 if (ret < 0) 3313 return ret; 3314 } 3315 3316 return 0; 3317 } 3318 3319 static void find_subprog_properties(struct bpf_verifier_env *env) 3320 { 3321 struct bpf_subprog_info *subprog = env->subprog_info; 3322 struct bpf_insn *insn = env->prog->insnsi; 3323 int cur_subprog; 3324 3325 for (cur_subprog = 0; cur_subprog < env->subprog_cnt; cur_subprog++) { 3326 int i; 3327 3328 for (i = subprog[cur_subprog].start; 3329 i < subprog[cur_subprog + 1].start; i++) { 3330 u8 code = insn[i].code; 3331 3332 if (code == (BPF_JMP | BPF_CALL) && 3333 insn[i].src_reg == 0 && 3334 insn[i].imm == BPF_FUNC_tail_call) { 3335 subprog[cur_subprog].has_tail_call = true; 3336 subprog[cur_subprog].tail_call_reachable = true; 3337 } 3338 if (BPF_CLASS(code) == BPF_LD && 3339 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3340 subprog[cur_subprog].has_ld_abs = true; 3341 if (bpf_is_callx(&insn[i])) 3342 env->has_callx = true; 3343 } 3344 } 3345 } 3346 3347 static int check_subprogs(struct bpf_verifier_env *env) 3348 { 3349 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3350 struct bpf_subprog_info *subprog = env->subprog_info; 3351 struct bpf_insn *insn = env->prog->insnsi; 3352 int insn_cnt = env->prog->len; 3353 3354 /* now check that all jumps are within the same subprog */ 3355 subprog_start = subprog[cur_subprog].start; 3356 subprog_end = subprog[cur_subprog + 1].start; 3357 for (i = 0; i < insn_cnt; i++) { 3358 u8 code = insn[i].code; 3359 3360 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3361 goto next; 3362 if (BPF_OP(code) == BPF_CALL) 3363 goto next; 3364 if (BPF_OP(code) == BPF_EXIT) { 3365 subprog[cur_subprog].exit_idx = i; 3366 goto next; 3367 } 3368 if (insn_is_gotox(&insn[i])) 3369 goto next; 3370 off = i + bpf_jmp_offset(&insn[i]) + 1; 3371 if (off < subprog_start || off >= subprog_end) { 3372 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3373 bpf_diag_program_structure( 3374 env, i, "jump out of range", 3375 "Keep branch targets within the same subprogram, or use an explicit subprogram call.", 3376 "Instruction %d jumps to instruction %d, but subprogram %d only contains instructions %d through %d. " 3377 "A branch target must stay inside the same subprogram.", 3378 i, off, cur_subprog, subprog_start, subprog_end - 1); 3379 return -EINVAL; 3380 } 3381 next: 3382 if (i == subprog_end - 1) { 3383 /* 3384 * To avoid fall-through from one subprog into another, 3385 * the last insn of the subprog should be either exit 3386 * or unconditional jump back or bpf_throw call. 3387 */ 3388 if (code != (BPF_JMP | BPF_EXIT) && 3389 code != (BPF_JMP32 | BPF_JA) && 3390 code != (BPF_JMP | BPF_JA) && 3391 !insn_is_gotox(&insn[i])) { 3392 verbose(env, "last insn is not an exit or jmp\n"); 3393 bpf_diag_program_structure( 3394 env, i, "subprogram can fall through", 3395 "End each subprogram with an exit or an explicit jump that keeps control flow inside the subprogram.", 3396 "Subprogram %d reaches its last instruction %d without an exit or jump, so control could continue into the next subprogram.", 3397 cur_subprog, i); 3398 return -EINVAL; 3399 } 3400 subprog_start = subprog_end; 3401 cur_subprog++; 3402 if (cur_subprog < env->subprog_cnt) 3403 subprog_end = subprog[cur_subprog + 1].start; 3404 } 3405 } 3406 return 0; 3407 } 3408 3409 /* 3410 * The callee of callx is known to the main verification pass only, which 3411 * records the 'caller' -> 'callee' edge of the call graph for the checks 3412 * that follow it: absence of recursion and the maximum stack depth. 3413 */ 3414 static int record_callx_edge(struct bpf_verifier_env *env, int caller, int callee) 3415 { 3416 u32 cnt = env->subprog_cnt; 3417 3418 if (!env->callx_edges) { 3419 env->callx_edges = kvcalloc(BITS_TO_LONGS(cnt * cnt), sizeof(long), 3420 GFP_KERNEL_ACCOUNT); 3421 if (!env->callx_edges) 3422 return -ENOMEM; 3423 } 3424 __set_bit(caller * cnt + callee, env->callx_edges); 3425 return 0; 3426 } 3427 3428 /* 3429 * Return the first subprog with the number >= 'from' that 'caller' calls 3430 * via callx, or -1 when there is none. 3431 */ 3432 static int next_callx_callee(struct bpf_verifier_env *env, int caller, int from) 3433 { 3434 u32 cnt = env->subprog_cnt; 3435 unsigned long bit, end = (caller + 1) * cnt; 3436 3437 if (!env->callx_edges || from >= cnt) 3438 return -1; 3439 bit = find_next_bit(env->callx_edges, end, caller * cnt + from); 3440 return bit < end ? bit - caller * cnt : -1; 3441 } 3442 3443 /* 3444 * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit. 3445 * JITs don't emit a branch for it. unwind_exit finds the pad by its return 3446 * address. So unwind_goto has to follow the call and nothing may jump to it. 3447 */ 3448 static int check_unwind_insns(struct bpf_verifier_env *env) 3449 { 3450 struct bpf_insn *insn = env->prog->insnsi; 3451 bool seen = false; 3452 int i; 3453 3454 for (i = 0; i < env->prog->len; i++, insn++) { 3455 if (bpf_is_unwind_exit(insn)) { 3456 bpf_find_containing_subprog(env, i)->can_unwind = true; 3457 seen = true; 3458 } 3459 if (!bpf_is_unwind_goto(insn)) 3460 continue; 3461 seen = true; 3462 if (!i || !(bpf_pseudo_call(insn - 1) || bpf_is_callx(insn - 1))) { 3463 verbose(env, "unwind_goto at insn %d doesn't follow a call of a subprog\n", 3464 i); 3465 return -EINVAL; 3466 } 3467 if (bpf_is_jump_target(env, i)) { 3468 verbose(env, "jump to unwind_goto at insn %d\n", i); 3469 return -EINVAL; 3470 } 3471 } 3472 if (!seen) 3473 return 0; 3474 if (!bpf_jit_supports_unwind() || bpf_prog_is_offloaded(env->prog->aux)) { 3475 verbose(env, "JIT does not support unwinding\n"); 3476 return -ENOTSUPP; 3477 } 3478 env->prog->jit_required = 1; 3479 env->prog->aux->can_unwind = env->subprog_info[0].can_unwind; 3480 return 0; 3481 } 3482 3483 /* 3484 * Sort subprogs in topological order so that leaf subprogs come first and 3485 * their callers come later. This is a DFS post-order traversal of the call 3486 * graph. Scan only reachable instructions (those in the computed postorder) of 3487 * the current subprog to discover callees (direct subprogs and sync 3488 * callbacks). 3489 * 3490 * The callees of callx are not known before the main verification pass. 3491 * When callx is used the sort is repeated after it with the recorded callx 3492 * edges added to the call graph to reject recursion through indirect calls. 3493 */ 3494 static int sort_subprogs_topo(struct bpf_verifier_env *env) 3495 { 3496 struct bpf_subprog_info *si = env->subprog_info; 3497 int *insn_postorder = env->cfg.insn_postorder; 3498 struct bpf_insn *insn = env->prog->insnsi; 3499 int cnt = env->subprog_cnt; 3500 int *dfs_stack = NULL; 3501 int top = 0, order = 0; 3502 int i, ret = 0; 3503 u8 *color = NULL; 3504 3505 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 3506 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 3507 if (!color || !dfs_stack) { 3508 ret = -ENOMEM; 3509 goto out; 3510 } 3511 3512 /* 3513 * DFS post-order traversal. 3514 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 3515 */ 3516 for (i = 0; i < cnt; i++) { 3517 if (color[i]) 3518 continue; 3519 color[i] = 1; 3520 dfs_stack[top++] = i; 3521 3522 while (top > 0) { 3523 int cur = dfs_stack[top - 1]; 3524 int po_start = si[cur].postorder_start; 3525 int po_end = si[cur + 1].postorder_start; 3526 bool pushed = false; 3527 int j; 3528 3529 for (j = po_start; j < po_end; j++) { 3530 int idx = insn_postorder[j]; 3531 int callee; 3532 3533 if (bpf_is_callx(&insn[idx])) { 3534 /* find a callee that is not explored yet */ 3535 callee = -1; 3536 do { 3537 callee = next_callx_callee(env, cur, callee + 1); 3538 } while (callee >= 0 && color[callee] == 2); 3539 if (callee < 0) 3540 continue; 3541 } else if (bpf_pseudo_call(&insn[idx]) || bpf_pseudo_func(&insn[idx])) { 3542 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 3543 if (callee < 0) { 3544 ret = -EFAULT; 3545 goto out; 3546 } 3547 } else { 3548 continue; 3549 } 3550 if (color[callee] == 2) 3551 continue; 3552 if (color[callee] == 1) { 3553 if (bpf_pseudo_func(&insn[idx])) 3554 continue; 3555 verbose(env, "recursive call from %s() to %s()\n", 3556 bpf_subprog_name(env, cur), 3557 bpf_subprog_name(env, callee)); 3558 bpf_diag_program_structure( 3559 env, idx, "recursive subprogram call", 3560 "Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.", 3561 "This bpf2bpf call would make the subprogram call graph recursive. " 3562 "The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis."); 3563 ret = -EINVAL; 3564 goto out; 3565 } 3566 color[callee] = 1; 3567 dfs_stack[top++] = callee; 3568 pushed = true; 3569 break; 3570 } 3571 3572 if (!pushed) { 3573 color[cur] = 2; 3574 env->subprog_topo_order[order++] = cur; 3575 top--; 3576 } 3577 } 3578 } 3579 3580 if (env->log.level & BPF_LOG_LEVEL2) 3581 for (i = 0; i < cnt; i++) 3582 verbose(env, "topo_order[%d] = %s\n", 3583 i, bpf_subprog_name(env, env->subprog_topo_order[i])); 3584 out: 3585 kvfree(dfs_stack); 3586 kvfree(color); 3587 return ret; 3588 } 3589 3590 static void mark_stack_slots_scratched(struct bpf_verifier_env *env, 3591 int spi, int nr_slots) 3592 { 3593 int i; 3594 3595 for (i = 0; i < nr_slots; i++) 3596 mark_stack_slot_scratched(env, spi - i); 3597 } 3598 3599 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3600 enum bpf_reg_arg_type t) 3601 { 3602 struct bpf_reg_state *reg; 3603 3604 mark_reg_scratched(env, regno); 3605 3606 reg = ®s[regno]; 3607 if (t == SRC_OP) { 3608 /* check whether register used as source operand can be read */ 3609 if (reg->type == NOT_INIT) { 3610 verbose(env, "R%d !read_ok\n", regno); 3611 bpf_diag_unreadable_reg(env, env->insn_idx, regno); 3612 return -EACCES; 3613 } 3614 /* We don't need to worry about FP liveness because it's read-only */ 3615 if (regno == BPF_REG_FP) 3616 return 0; 3617 3618 return 0; 3619 } else { 3620 /* check whether register used as dest operand can be written to */ 3621 if (regno == BPF_REG_FP) { 3622 verbose(env, "frame pointer is read only\n"); 3623 return -EACCES; 3624 } 3625 if (t == DST_OP) 3626 mark_reg_unknown(env, regs, regno); 3627 } 3628 return 0; 3629 } 3630 3631 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3632 enum bpf_reg_arg_type t) 3633 { 3634 struct bpf_verifier_state *vstate = env->cur_state; 3635 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3636 3637 return __check_reg_arg(env, state->regs, regno, t); 3638 } 3639 3640 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3641 { 3642 env->insn_aux_data[idx].indirect_target = true; 3643 } 3644 3645 static void mark_non_stack_access(struct bpf_verifier_env *env, int idx) 3646 { 3647 env->insn_aux_data[idx].non_stack_access = true; 3648 } 3649 3650 /* Layout of one packed linked register in the jump history, see linked_regs_pack() */ 3651 #define LR_FRAMENO_BITS 4 3652 #define LR_INDEX_BITS 11 3653 #define LR_FRAMENO_MASK ((1u << LR_FRAMENO_BITS) - 1) 3654 #define LR_IS_REG BIT(LR_FRAMENO_BITS) 3655 #define LR_INDEX_OFF (LR_FRAMENO_BITS + 1) 3656 #define LR_INDEX_MASK ((1u << LR_INDEX_BITS) - 1) 3657 #define LINKED_REGS_MAX BPF_LINKED_REGS_MAX 3658 3659 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS)); 3660 static_assert(MAX_BPF_REG <= (1 << LR_INDEX_BITS)); 3661 static_assert(MAX_BPF_STACK_SLOTS <= (1 << LR_INDEX_BITS)); 3662 static_assert(LR_INDEX_OFF + LR_INDEX_BITS <= 16); 3663 3664 struct linked_reg { 3665 u8 frameno; 3666 union { 3667 u16 spi; 3668 u16 regno; 3669 }; 3670 bool is_reg; 3671 }; 3672 3673 struct linked_regs { 3674 int cnt; 3675 struct linked_reg entries[LINKED_REGS_MAX]; 3676 }; 3677 3678 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3679 { 3680 if (s->cnt < LINKED_REGS_MAX) 3681 return &s->entries[s->cnt++]; 3682 3683 return NULL; 3684 } 3685 3686 /* 3687 * Pack linked registers for a jump history entry, one u16 each: 3688 * - 4 bits frameno 3689 * - 1 bit is_reg 3690 * - 11 bits register or stack slot index 3691 */ 3692 static void linked_regs_pack(const struct linked_regs *s, u16 *packed) 3693 { 3694 int i; 3695 3696 for (i = 0; i < s->cnt; ++i) { 3697 const struct linked_reg *e = &s->entries[i]; 3698 3699 packed[i] = e->frameno | (e->is_reg ? LR_IS_REG : 0) | (e->spi << LR_INDEX_OFF); 3700 } 3701 } 3702 3703 static void linked_regs_unpack(const struct bpf_jmp_history_entry *hist, struct linked_regs *s) 3704 { 3705 int i; 3706 3707 s->cnt = hist->linked_regs_cnt; 3708 for (i = 0; i < s->cnt; ++i) { 3709 struct linked_reg *e = &s->entries[i]; 3710 u16 packed = hist->linked_regs[i]; 3711 3712 e->frameno = packed & LR_FRAMENO_MASK; 3713 e->is_reg = packed & LR_IS_REG; 3714 e->spi = (packed >> LR_INDEX_OFF) & LR_INDEX_MASK; 3715 } 3716 } 3717 3718 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3719 { 3720 const struct btf_type *func; 3721 struct btf *desc_btf; 3722 3723 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3724 return NULL; 3725 3726 desc_btf = find_kfunc_desc_btf_cached(data, insn->off); 3727 if (IS_ERR(desc_btf)) 3728 return "<error>"; 3729 3730 func = btf_type_by_id(desc_btf, insn->imm); 3731 if (!func || !btf_type_is_func(func)) 3732 return "<error>"; 3733 return btf_name_by_offset(desc_btf, func->name_off); 3734 } 3735 3736 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3737 { 3738 const struct bpf_insn_cbs cbs = { 3739 .cb_call = bpf_disasm_kfunc_name, 3740 .cb_print = verbose, 3741 .private_data = env, 3742 }; 3743 3744 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3745 } 3746 3747 /* If any register R in hist->linked_regs is marked as precise in bt, 3748 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3749 */ 3750 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3751 { 3752 struct linked_regs linked_regs; 3753 bool some_precise = false; 3754 int i; 3755 3756 if (!hist || !hist->linked_regs_cnt) 3757 return; 3758 3759 linked_regs_unpack(hist, &linked_regs); 3760 for (i = 0; i < linked_regs.cnt; ++i) { 3761 struct linked_reg *e = &linked_regs.entries[i]; 3762 3763 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3764 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3765 some_precise = true; 3766 break; 3767 } 3768 } 3769 3770 if (!some_precise) 3771 return; 3772 3773 for (i = 0; i < linked_regs.cnt; ++i) { 3774 struct linked_reg *e = &linked_regs.entries[i]; 3775 3776 if (e->is_reg) 3777 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3778 else 3779 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3780 } 3781 } 3782 3783 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3784 { 3785 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3786 } 3787 3788 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3789 * desired reg and stack masks across all relevant frames 3790 */ 3791 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3792 struct bpf_verifier_state *starting_state) 3793 { 3794 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3795 } 3796 3797 /* check if register is a constant scalar value */ 3798 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3799 { 3800 return reg->type == SCALAR_VALUE && 3801 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3802 } 3803 3804 /* assuming is_reg_const() is true, return constant value of a register */ 3805 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3806 { 3807 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3808 } 3809 3810 static bool is_pointer_regtype(enum bpf_reg_type type) 3811 { 3812 return type != SCALAR_VALUE && type != NOT_INIT; 3813 } 3814 3815 static bool __is_pointer_value(bool allow_ptr_leaks, 3816 const struct bpf_reg_state *reg) 3817 { 3818 if (allow_ptr_leaks) 3819 return false; 3820 3821 return is_pointer_regtype(reg->type); 3822 } 3823 3824 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3825 struct bpf_reg_state *src_reg) 3826 { 3827 if (src_reg->type != SCALAR_VALUE) 3828 return; 3829 /* 3830 * The verifier is processing rX = rY insn and 3831 * rY->id has special linked register already. 3832 * Cleared it, since multiple rX += const are not supported. 3833 */ 3834 if (src_reg->id & BPF_ADD_CONST) 3835 clear_scalar_id(src_reg); 3836 /* 3837 * Ensure that src_reg has a valid ID that will be copied to 3838 * dst_reg and then will be used by sync_linked_regs() to 3839 * propagate min/max range. 3840 */ 3841 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3842 src_reg->id = ++env->id_gen; 3843 } 3844 3845 static void save_register_state(struct bpf_verifier_env *env, 3846 struct bpf_func_state *state, 3847 int spi, struct bpf_reg_state *reg, 3848 int size) 3849 { 3850 struct bpf_stack_state *slot = bpf_stack_slot(state, spi); 3851 int i; 3852 3853 bpf_diag_mod_begin(env, &slot->spilled_ptr, reg, BPF_DIAG_MOD_SPILL); 3854 slot->spilled_ptr = *reg; 3855 3856 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3857 slot->slot_type[i - 1] = STACK_SPILL; 3858 3859 /* size < 8 bytes spill */ 3860 for (; i; i--) 3861 mark_stack_slot_misc(env, &slot->slot_type[i - 1]); 3862 3863 bpf_diag_mod_end(env); 3864 } 3865 3866 static bool is_bpf_st_mem(struct bpf_insn *insn) 3867 { 3868 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3869 } 3870 3871 static int get_reg_width(struct bpf_reg_state *reg) 3872 { 3873 return fls64(reg_umax(reg)); 3874 } 3875 3876 /* See comment for mark_fastcall_pattern_for_call() */ 3877 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3878 struct bpf_func_state *state, int insn_idx, int off) 3879 { 3880 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3881 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3882 int i; 3883 3884 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3885 return; 3886 /* access to the region [max_stack_depth .. fastcall_stack_off) 3887 * from something that is not a part of the fastcall pattern, 3888 * disable fastcall rewrites for current subprogram by setting 3889 * fastcall_stack_off to a value smaller than any possible offset. 3890 */ 3891 subprog->fastcall_stack_off = S16_MIN; 3892 /* reset fastcall aux flags within subprogram, 3893 * happens at most once per subprogram 3894 */ 3895 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3896 aux[i].fastcall_spills_num = 0; 3897 aux[i].fastcall_pattern = 0; 3898 } 3899 } 3900 3901 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3902 { 3903 struct bpf_stack_state *slot = bpf_stack_slot(state, spi); 3904 int i; 3905 3906 /* regular write of data into stack destroys any spilled ptr */ 3907 slot->spilled_ptr.type = NOT_INIT; 3908 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3909 if (is_stack_slot_special(slot)) 3910 for (i = 0; i < BPF_REG_SIZE; i++) 3911 scrub_spilled_slot(&slot->slot_type[i]); 3912 } 3913 3914 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3915 * stack boundary and alignment are checked in check_mem_access() 3916 */ 3917 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3918 /* stack frame we're writing to */ 3919 struct bpf_func_state *state, 3920 int off, int size, int value_regno, 3921 int insn_idx) 3922 { 3923 struct bpf_func_state *cur; /* state of the current function */ 3924 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3925 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3926 struct bpf_reg_state *reg = NULL; 3927 int insn_flags = INSN_F_STACK_ACCESS; 3928 int hist_spi = spi, hist_frame = state->frameno; 3929 struct bpf_stack_state *ss = bpf_stack_slot(state, spi); 3930 3931 /* 3932 * caller checked that off % size == 0 and -env->stack_limit <= off < 0, 3933 * so it's aligned access and [off, off + size) are within stack limits 3934 */ 3935 if (!env->allow_ptr_leaks && 3936 bpf_is_spilled_reg(ss) && 3937 !bpf_is_spilled_scalar_reg(ss) && 3938 size != BPF_REG_SIZE) { 3939 const char *reason; 3940 3941 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3942 reason = bpf_diag_fmt(env, 3943 "This store writes %d bytes at stack offset %d into a stack slot that currently holds a spilled pointer. " 3944 "Partial writes to spilled pointers are rejected because they can corrupt pointer metadata and leak kernel pointers.", 3945 size, off); 3946 bpf_diag_memory( 3947 env, insn_idx, "stack spill corruption", reason, 3948 "Write the full 8-byte spilled pointer slot, or use a separate stack slot for scalar data before overwriting only part of it."); 3949 return -EACCES; 3950 } 3951 3952 cur = env->cur_state->frame[env->cur_state->curframe]; 3953 if (value_regno >= 0) 3954 reg = &cur->regs[value_regno]; 3955 if (!env->bypass_spec_v4) { 3956 bool sanitize = reg && is_pointer_regtype(reg->type); 3957 3958 for (i = 0; i < size; i++) { 3959 u8 type = ss->slot_type[(slot - i) % 3960 BPF_REG_SIZE]; 3961 3962 if (type != STACK_MISC && type != STACK_ZERO) { 3963 sanitize = true; 3964 break; 3965 } 3966 } 3967 3968 if (sanitize) 3969 env->insn_aux_data[insn_idx].nospec_result = true; 3970 } 3971 3972 err = destroy_if_dynptr_stack_slot(env, state, spi); 3973 if (err) 3974 return err; 3975 3976 mark_stack_slot_scratched(env, spi); 3977 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3978 bool reg_value_fits; 3979 3980 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3981 /* Make sure that reg had an ID to build a relation on spill. */ 3982 if (reg_value_fits) 3983 assign_scalar_id_before_mov(env, reg); 3984 save_register_state(env, state, spi, reg, size); 3985 /* Break the relation on a narrowing spill. */ 3986 if (!reg_value_fits) 3987 clear_scalar_id(&ss->spilled_ptr); 3988 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3989 env->bpf_capable) { 3990 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3991 3992 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3993 __mark_reg_known(tmp_reg, insn->imm); 3994 tmp_reg->type = SCALAR_VALUE; 3995 save_register_state(env, state, spi, tmp_reg, size); 3996 } else if (reg && is_pointer_regtype(reg->type)) { 3997 /* register containing pointer is being spilled into stack */ 3998 if (size != BPF_REG_SIZE) { 3999 verbose_linfo(env, insn_idx, "; "); 4000 verbose(env, "invalid size of register spill\n"); 4001 return -EACCES; 4002 } 4003 if (state != cur && reg->type == PTR_TO_STACK) { 4004 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4005 return -EINVAL; 4006 } 4007 save_register_state(env, state, spi, reg, size); 4008 } else { 4009 u8 type = STACK_MISC; 4010 4011 if (bpf_is_spilled_reg(ss)) 4012 bpf_diag_record_scrub(env, &ss->spilled_ptr, 4013 BPF_DIAG_MOD_WRITE); 4014 scrub_special_slot(state, spi); 4015 4016 /* when we zero initialize stack slots mark them as such */ 4017 if ((reg && bpf_register_is_null(reg)) || 4018 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4019 /* STACK_ZERO case happened because register spill 4020 * wasn't properly aligned at the stack slot boundary, 4021 * so it's not a register spill anymore; force 4022 * originating register to be precise to make 4023 * STACK_ZERO correct for subsequent states 4024 */ 4025 err = mark_chain_precision(env, value_regno); 4026 if (err) 4027 return err; 4028 type = STACK_ZERO; 4029 } 4030 4031 /* Mark slots affected by this stack write. */ 4032 for (i = 0; i < size; i++) 4033 ss->slot_type[(slot - i) % BPF_REG_SIZE] = type; 4034 insn_flags = 0; /* not a register spill */ 4035 } 4036 4037 if (insn_flags) 4038 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 4039 hist_spi, hist_frame, NULL, 0); 4040 return 0; 4041 } 4042 4043 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 4044 * known to contain a variable offset. 4045 * This function checks whether the write is permitted and conservatively 4046 * tracks the effects of the write, considering that each stack slot in the 4047 * dynamic range is potentially written to. 4048 * 4049 * 'value_regno' can be -1, meaning that an unknown value is being written to 4050 * the stack. 4051 * 4052 * Spilled pointers in range are not marked as written because we don't know 4053 * what's going to be actually written. This means that read propagation for 4054 * future reads cannot be terminated by this write. 4055 * 4056 * For privileged programs, uninitialized stack slots are considered 4057 * initialized by this write (even though we don't know exactly what offsets 4058 * are going to be written to). The idea is that we don't want the verifier to 4059 * reject future reads that access slots written to through variable offsets. 4060 */ 4061 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4062 /* func where register points to */ 4063 struct bpf_func_state *state, 4064 struct bpf_reg_state *ptr_reg, int off, int size, 4065 int value_regno, int insn_idx) 4066 { 4067 struct bpf_func_state *cur; /* state of the current function */ 4068 int min_off, max_off; 4069 int i, err; 4070 struct bpf_reg_state *value_reg = NULL; 4071 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4072 bool writing_zero = false; 4073 /* set if the fact that we're writing a zero is used to let any 4074 * stack slots remain STACK_ZERO 4075 */ 4076 bool zero_used = false; 4077 4078 cur = env->cur_state->frame[env->cur_state->curframe]; 4079 min_off = reg_smin(ptr_reg) + off; 4080 max_off = reg_smax(ptr_reg) + off + size; 4081 if (value_regno >= 0) 4082 value_reg = &cur->regs[value_regno]; 4083 if ((value_reg && bpf_register_is_null(value_reg)) || 4084 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4085 writing_zero = true; 4086 4087 err = destroy_dynptrs_in_stack_slots(env, state, bpf_get_spi(max_off - 1), 4088 bpf_get_spi(min_off)); 4089 if (err) 4090 return err; 4091 4092 /* Variable offset writes destroy any spilled pointers in range. */ 4093 for (i = min_off; i < max_off; i++) { 4094 struct bpf_stack_state *ss; 4095 u8 new_type, *stype; 4096 int slot, spi; 4097 4098 slot = -i - 1; 4099 spi = slot / BPF_REG_SIZE; 4100 ss = bpf_stack_slot(state, spi); 4101 stype = &ss->slot_type[slot % BPF_REG_SIZE]; 4102 mark_stack_slot_scratched(env, spi); 4103 4104 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4105 /* Reject the write if range we may write to has not 4106 * been initialized beforehand. If we didn't reject 4107 * here, the ptr status would be erased below (even 4108 * though not all slots are actually overwritten), 4109 * possibly opening the door to leaks. 4110 * 4111 * We do however catch STACK_INVALID case below, and 4112 * only allow reading possibly uninitialized memory 4113 * later for CAP_PERFMON, as the write may not happen to 4114 * that slot. 4115 */ 4116 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4117 insn_idx, i); 4118 return -EINVAL; 4119 } 4120 4121 /* If writing_zero and the spi slot contains a spill of value 0, 4122 * maintain the spill type. 4123 */ 4124 if (writing_zero && *stype == STACK_SPILL && bpf_is_spilled_scalar_reg(ss)) { 4125 struct bpf_reg_state *spill_reg = &ss->spilled_ptr; 4126 4127 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4128 zero_used = true; 4129 continue; 4130 } 4131 } 4132 4133 /* 4134 * Scrub slots if variable-offset stack write goes over spilled pointers. 4135 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 4136 * and valid program is rejected by check_stack_read_fixed_off() 4137 * with obscure "invalid size of register fill" message. 4138 */ 4139 scrub_special_slot(state, spi); 4140 4141 /* Update the slot type. */ 4142 new_type = STACK_MISC; 4143 if (writing_zero && *stype == STACK_ZERO) { 4144 new_type = STACK_ZERO; 4145 zero_used = true; 4146 } 4147 /* If the slot is STACK_INVALID, we check whether it's OK to 4148 * pretend that it will be initialized by this write. The slot 4149 * might not actually be written to, and so if we mark it as 4150 * initialized future reads might leak uninitialized memory. 4151 * For privileged programs, we will accept such reads to slots 4152 * that may or may not be written because, if we're reject 4153 * them, the error would be too confusing. 4154 * Conservatively, treat STACK_POISON in a similar way. 4155 */ 4156 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 4157 !env->allow_uninit_stack) { 4158 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4159 insn_idx, i); 4160 return -EINVAL; 4161 } 4162 *stype = new_type; 4163 } 4164 if (zero_used) { 4165 /* backtracking doesn't work for STACK_ZERO yet. */ 4166 err = mark_chain_precision(env, value_regno); 4167 if (err) 4168 return err; 4169 } 4170 bpf_diag_record_scrub_stack(env, state, min_off, max_off, 4171 BPF_DIAG_MOD_VAR_WRITE); 4172 return 0; 4173 } 4174 4175 /* When register 'dst_regno' is assigned some values from stack[min_off, 4176 * max_off), we set the register's type according to the types of the 4177 * respective stack slots. If all the stack values are known to be zeros, then 4178 * so is the destination reg. Otherwise, the register is considered to be 4179 * SCALAR. This function does not deal with register filling; the caller must 4180 * ensure that all spilled registers in the stack range have been marked as 4181 * read. 4182 * 4183 * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered 4184 * zero bytes. In that case, mark the contributing stack slots precise so 4185 * pruning cannot reuse a zero-spill state for a later non-zero spill state. 4186 * 4187 * Returns an error if precision backtracking fails. 4188 */ 4189 static int mark_reg_stack_read(struct bpf_verifier_env *env, 4190 /* func where src register points to */ 4191 struct bpf_func_state *ptr_state, 4192 int min_off, int max_off, int dst_regno) 4193 { 4194 struct bpf_verifier_state *vstate = env->cur_state; 4195 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4196 int i, slot, spi; 4197 u8 *stype; 4198 int zeros = 0, zero_spills = 0; 4199 4200 for (i = min_off; i < max_off; i++) { 4201 slot = -i - 1; 4202 spi = slot / BPF_REG_SIZE; 4203 mark_stack_slot_scratched(env, spi); 4204 stype = bpf_stack_slot(ptr_state, spi)->slot_type; 4205 if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) { 4206 zeros++; 4207 continue; 4208 } 4209 if (stype[slot % BPF_REG_SIZE] == STACK_SPILL && 4210 bpf_register_is_null(&bpf_stack_slot(ptr_state, spi)->spilled_ptr)) { 4211 zero_spills++; 4212 zeros++; 4213 continue; 4214 } 4215 break; 4216 } 4217 if (zeros == max_off - min_off) { 4218 /* Any access_size read into register is zero extended, 4219 * so the whole register == const_zero. 4220 */ 4221 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4222 if (zero_spills) { 4223 for (i = min_off; i < max_off; i++) { 4224 slot = -i - 1; 4225 spi = slot / BPF_REG_SIZE; 4226 stype = bpf_stack_slot(ptr_state, spi)->slot_type; 4227 if (stype[slot % BPF_REG_SIZE] == STACK_SPILL) 4228 bpf_bt_set_frame_slot(&env->bt, ptr_state->frameno, spi); 4229 } 4230 return mark_chain_precision_batch(env, env->cur_state); 4231 } 4232 } else { 4233 /* have read misc data from the stack */ 4234 mark_reg_unknown(env, state->regs, dst_regno); 4235 } 4236 4237 return 0; 4238 } 4239 4240 static void bpf_diag_stack_read_invalid(struct bpf_verifier_env *env, int off, int i, int size, 4241 enum bpf_stack_slot_type type) 4242 { 4243 const char *problem, *reason, *suggestion, *kind; 4244 4245 if (type == STACK_INVALID) { 4246 reason = bpf_diag_fmt( 4247 env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range is uninitialized on this path. " 4248 "Programs loaded with CAP_PERFMON can be allowed to read uninitialized stack bytes, but this program is being rejected without that allowance.", 4249 size, off, i); 4250 bpf_diag_memory( 4251 env, env->insn_idx, "uninitialized stack read", reason, 4252 "Initialize every byte in the stack range before reading it, adjust the offset and size so the read covers only initialized bytes, " 4253 "or load with CAP_PERFMON if uninitialized stack reads are intended."); 4254 return; 4255 } 4256 4257 switch (type) { 4258 case STACK_DYNPTR: 4259 kind = "dynptr"; 4260 suggestion = "Use dynptr helpers or kfuncs to access the object represented by the dynptr instead of reading the dynptr state directly."; 4261 break; 4262 case STACK_ITER: 4263 kind = "iterator"; 4264 suggestion = "Use iterator kfuncs to advance or destroy the iterator instead of reading its state directly."; 4265 break; 4266 case STACK_IRQ_FLAG: 4267 kind = "IRQ flag"; 4268 suggestion = "Pass the saved IRQ flag to the matching restore kfunc instead of reading its state directly."; 4269 break; 4270 default: 4271 return; 4272 } 4273 4274 problem = bpf_diag_fmt(env, "direct read of %s stack state", kind); 4275 reason = bpf_diag_fmt( 4276 env, "This rejected read uses %d bytes at stack offset %d, but byte %d in that range belongs to verifier-managed %s state. " 4277 "This state has an opaque representation that BPF programs cannot read directly.", 4278 size, off, i, kind); 4279 bpf_diag_memory(env, env->insn_idx, problem, reason, suggestion); 4280 } 4281 4282 /* Read the stack at 'off' and put the results into the register indicated by 4283 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4284 * spilled reg. 4285 * 4286 * 'dst_regno' can be -1, meaning that the read value is not going to a 4287 * register. 4288 * 4289 * The access is assumed to be within the current stack bounds. 4290 */ 4291 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4292 /* func where src register points to */ 4293 struct bpf_func_state *reg_state, 4294 int off, int size, int dst_regno) 4295 { 4296 struct bpf_verifier_state *vstate = env->cur_state; 4297 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4298 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4299 struct bpf_reg_state *reg; 4300 u8 *stype, type; 4301 int err; 4302 int insn_flags = INSN_F_STACK_ACCESS; 4303 int hist_spi = spi, hist_frame = reg_state->frameno; 4304 struct bpf_stack_state *ss = bpf_stack_slot(reg_state, spi); 4305 4306 stype = ss->slot_type; 4307 reg = &ss->spilled_ptr; 4308 4309 mark_stack_slot_scratched(env, spi); 4310 4311 /* 4312 * Refine the in-progress load record's origin to the source stack slot. 4313 */ 4314 if (dst_regno >= 0) 4315 bpf_diag_mod_begin(env, &state->regs[dst_regno], reg, BPF_DIAG_MOD_WRITE); 4316 4317 if (bpf_is_spilled_reg(ss)) { 4318 u8 spill_size = bpf_spill_size(ss); 4319 4320 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4321 if (reg->type != SCALAR_VALUE) { 4322 verbose_linfo(env, env->insn_idx, "; "); 4323 verbose(env, "invalid size of register fill\n"); 4324 return -EACCES; 4325 } 4326 4327 if (size <= spill_size && 4328 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4329 if (dst_regno < 0) 4330 return 0; 4331 4332 if (env->bpf_capable && size == 4 && spill_size == 4 && 4333 get_reg_width(reg) <= 32) 4334 /* Ensure stack slot has an ID to build a relation 4335 * with the destination register on fill. 4336 */ 4337 assign_scalar_id_before_mov(env, reg); 4338 state->regs[dst_regno] = *reg; 4339 4340 /* Break the relation on a narrowing fill. 4341 * coerce_reg_to_size will adjust the boundaries. 4342 */ 4343 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4344 clear_scalar_id(&state->regs[dst_regno]); 4345 } else { 4346 int spill_cnt = 0, zero_cnt = 0; 4347 4348 for (i = 0; i < size; i++) { 4349 type = stype[(slot - i) % BPF_REG_SIZE]; 4350 if (type == STACK_SPILL) { 4351 spill_cnt++; 4352 continue; 4353 } 4354 if (type == STACK_MISC) 4355 continue; 4356 if (type == STACK_ZERO) { 4357 zero_cnt++; 4358 continue; 4359 } 4360 if (type == STACK_INVALID && env->allow_uninit_stack) 4361 continue; 4362 if (type == STACK_POISON) { 4363 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 4364 off, i, size); 4365 } else { 4366 verbose(env, "invalid read from stack off %d+%d size %d\n", 4367 off, i, size); 4368 bpf_diag_stack_read_invalid(env, off, i, size, type); 4369 } 4370 return -EACCES; 4371 } 4372 4373 if (dst_regno < 0) 4374 return 0; 4375 4376 if (spill_cnt == size && 4377 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4378 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4379 /* this IS register fill, so keep insn_flags */ 4380 } else if (zero_cnt == size) { 4381 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4382 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4383 insn_flags = 0; /* not restoring original register state */ 4384 } else { 4385 err = mark_reg_stack_read(env, reg_state, off, off + size, 4386 dst_regno); 4387 if (err) 4388 return err; 4389 insn_flags = 0; /* not restoring original register state */ 4390 } 4391 } 4392 } else if (dst_regno >= 0) { 4393 /* restore register state from stack */ 4394 if (env->bpf_capable) 4395 /* Ensure stack slot has an ID to build a relation 4396 * with the destination register on fill. 4397 */ 4398 assign_scalar_id_before_mov(env, reg); 4399 state->regs[dst_regno] = *reg; 4400 /* mark reg as written since spilled pointer state likely 4401 * has its liveness marks cleared by is_state_visited() 4402 * which resets stack/reg liveness for state transitions 4403 */ 4404 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4405 /* If dst_regno==-1, the caller is asking us whether 4406 * it is acceptable to use this value as a SCALAR_VALUE 4407 * (e.g. for XADD). 4408 * We must not allow unprivileged callers to do that 4409 * with spilled pointers. 4410 */ 4411 verbose(env, "leaking pointer from stack off %d\n", 4412 off); 4413 return -EACCES; 4414 } 4415 } else { 4416 for (i = 0; i < size; i++) { 4417 type = stype[(slot - i) % BPF_REG_SIZE]; 4418 if (type == STACK_MISC) 4419 continue; 4420 if (type == STACK_ZERO) 4421 continue; 4422 if (type == STACK_INVALID && env->allow_uninit_stack) 4423 continue; 4424 if (type == STACK_POISON) { 4425 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 4426 off, i, size); 4427 } else { 4428 verbose(env, "invalid read from stack off %d+%d size %d\n", 4429 off, i, size); 4430 bpf_diag_stack_read_invalid(env, off, i, size, type); 4431 } 4432 return -EACCES; 4433 } 4434 if (dst_regno >= 0) { 4435 err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4436 if (err) 4437 return err; 4438 } 4439 insn_flags = 0; /* we are not restoring spilled register */ 4440 } 4441 if (insn_flags) 4442 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 4443 hist_spi, hist_frame, NULL, 0); 4444 return 0; 4445 } 4446 4447 enum bpf_access_src { 4448 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4449 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4450 }; 4451 4452 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4453 argno_t argno, int off, int access_size, 4454 bool zero_size_allowed, 4455 enum bpf_access_type type, 4456 struct bpf_call_arg_meta *meta); 4457 4458 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4459 { 4460 return cur_regs(env) + regno; 4461 } 4462 4463 /* Read the stack at 'reg + off' and put the result into the register 4464 * 'dst_regno'. 4465 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 4466 * but not its variable offset. 4467 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4468 * 4469 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4470 * filling registers (i.e. reads of spilled register cannot be detected when 4471 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4472 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 4473 * offset; for a fixed offset check_stack_read_fixed_off should be used 4474 * instead. 4475 */ 4476 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4477 argno_t ptr_argno, int off, int size, int dst_regno) 4478 { 4479 struct bpf_func_state *ptr_state = bpf_func(env, reg); 4480 int err; 4481 int min_off, max_off; 4482 4483 /* Note that we pass a NULL meta, so raw access will not be permitted. 4484 */ 4485 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 4486 false, BPF_READ, NULL); 4487 if (err) 4488 return err; 4489 4490 min_off = reg_smin(reg) + off; 4491 max_off = reg_smax(reg) + off; 4492 err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size, 4493 dst_regno); 4494 if (err) 4495 return err; 4496 return 0; 4497 } 4498 4499 /* check_stack_read dispatches to check_stack_read_fixed_off or 4500 * check_stack_read_var_off. 4501 * 4502 * The caller must ensure that the offset falls within the allocated stack 4503 * bounds. 4504 * 4505 * 'dst_regno' is a register which will receive the value from the stack. It 4506 * can be -1, meaning that the read value is not going to a register. 4507 */ 4508 static int check_stack_read(struct bpf_verifier_env *env, 4509 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 4510 int dst_regno) 4511 { 4512 struct bpf_func_state *state = bpf_func(env, reg); 4513 int err; 4514 /* Some accesses are only permitted with a static offset. */ 4515 bool var_off = !tnum_is_const(reg->var_off); 4516 4517 /* The offset is required to be static when reads don't go to a 4518 * register, in order to not leak pointers (see 4519 * check_stack_read_fixed_off). 4520 */ 4521 if (dst_regno < 0 && var_off) { 4522 const char *reason; 4523 char tn_buf[48]; 4524 4525 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4526 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4527 tn_buf, off, size); 4528 reason = bpf_diag_fmt( 4529 env, "The instruction would access the stack through variable offset %s plus fixed offset %d and size %d. " 4530 "This stack access requires a constant stack offset and a precise initialized range.", 4531 tn_buf, off, size); 4532 bpf_diag_memory( 4533 env, env->insn_idx, "variable-offset stack access", reason, 4534 "Use a fixed stack offset for the instruction, selecting the target stack slot on separate control-flow paths if necessary."); 4535 return -EACCES; 4536 } 4537 /* Variable offset is prohibited for unprivileged mode for simplicity 4538 * since it requires corresponding support in Spectre masking for stack 4539 * ALU. See also retrieve_ptr_limit(). The check in 4540 * check_stack_access_for_ptr_arithmetic() called by 4541 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4542 * with variable offsets, therefore no check is required here. Further, 4543 * just checking it here would be insufficient as speculative stack 4544 * writes could still lead to unsafe speculative behaviour. 4545 */ 4546 if (!var_off) { 4547 off += reg->var_off.value; 4548 err = check_stack_read_fixed_off(env, state, off, size, 4549 dst_regno); 4550 } else { 4551 /* Variable offset stack reads need more conservative handling 4552 * than fixed offset ones. Note that dst_regno >= 0 on this 4553 * branch. 4554 */ 4555 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 4556 dst_regno); 4557 } 4558 return err; 4559 } 4560 4561 /* check_stack_write dispatches to check_stack_write_fixed_off or 4562 * check_stack_write_var_off. 4563 * 4564 * 'reg' is the register used as a pointer into the stack. 4565 * 'value_regno' is the register whose value we're writing to the stack. It can 4566 * be -1, meaning that we're not writing from a register. 4567 * 4568 * The caller must ensure that the offset falls within the maximum stack size. 4569 */ 4570 static int check_stack_write(struct bpf_verifier_env *env, 4571 struct bpf_reg_state *reg, int off, int size, 4572 int value_regno, int insn_idx) 4573 { 4574 struct bpf_func_state *state = bpf_func(env, reg); 4575 int err; 4576 4577 if (tnum_is_const(reg->var_off)) { 4578 off += reg->var_off.value; 4579 err = check_stack_write_fixed_off(env, state, off, size, 4580 value_regno, insn_idx); 4581 } else { 4582 /* Variable offset stack reads need more conservative handling 4583 * than fixed offset ones. 4584 */ 4585 err = check_stack_write_var_off(env, state, 4586 reg, off, size, 4587 value_regno, insn_idx); 4588 } 4589 return err; 4590 } 4591 4592 /* 4593 * Write a value to the outgoing stack arg area. 4594 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4595 */ 4596 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4597 int off, struct bpf_reg_state *value_reg) 4598 { 4599 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4600 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4601 int spi = -off / BPF_REG_SIZE - 1; 4602 struct bpf_reg_state *arg; 4603 int err; 4604 4605 if (spi >= max_stack_arg_regs) { 4606 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4607 off, max_stack_arg_regs); 4608 return -EINVAL; 4609 } 4610 4611 err = grow_stack_arg_slots(env, state, spi + 1); 4612 if (err) 4613 return err; 4614 4615 /* Track the max outgoing stack arg slot count. */ 4616 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4617 subprog->max_out_stack_arg_cnt = spi + 1; 4618 4619 arg = &state->stack_arg_regs[spi]; 4620 bpf_diag_mod_begin(env, arg, value_reg, BPF_DIAG_MOD_WRITE); 4621 4622 if (value_reg) { 4623 state->stack_arg_regs[spi] = *value_reg; 4624 } else { 4625 /* BPF_ST: store immediate, treat as scalar */ 4626 arg->type = SCALAR_VALUE; 4627 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4628 } 4629 bpf_diag_mod_end(env); 4630 state->no_stack_arg_load = true; 4631 return bpf_push_jmp_history(env, env->cur_state, 4632 INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0); 4633 } 4634 4635 /* 4636 * Read a value from the incoming stack arg area. 4637 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4638 */ 4639 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4640 int off, int dst_regno) 4641 { 4642 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4643 struct bpf_verifier_state *vstate = env->cur_state; 4644 int spi = off / BPF_REG_SIZE - 1; 4645 struct bpf_func_state *caller, *cur; 4646 struct bpf_reg_state *arg; 4647 4648 if (state->no_stack_arg_load) { 4649 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4650 return -EINVAL; 4651 } 4652 4653 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4654 verbose(env, "invalid read from stack arg off %d depth %d\n", 4655 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4656 return -EACCES; 4657 } 4658 4659 caller = vstate->frame[vstate->curframe - 1]; 4660 arg = bpf_get_spilled_stack_arg(spi, caller); 4661 if (!arg) { 4662 verbose(env, "invalid read from uninitialized stack arg off %d\n", off); 4663 return -EACCES; 4664 } 4665 4666 cur = vstate->frame[vstate->curframe]; 4667 bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE); 4668 cur->regs[dst_regno] = *arg; 4669 bpf_diag_mod_end(env); 4670 return bpf_push_jmp_history(env, env->cur_state, 4671 INSN_F_STACK_ARG_ACCESS, spi, 0, NULL, 0); 4672 } 4673 4674 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4675 { 4676 struct bpf_func_state *caller = cur_func(env); 4677 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4678 4679 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4680 return mark_chain_precision_batch(env, env->cur_state); 4681 } 4682 4683 static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno) 4684 { 4685 int regno = reg_from_argno(argno); 4686 4687 if (regno >= 0) 4688 return mark_chain_precision(env, regno); 4689 return mark_stack_arg_precision(env, arg_idx_from_argno(argno)); 4690 } 4691 4692 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4693 int nargs, const char *callee_name, const struct btf *btf, 4694 const struct btf_param *args) 4695 { 4696 int i, spi; 4697 4698 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4699 spi = i - MAX_BPF_FUNC_REG_ARGS; 4700 if (spi >= caller->out_stack_arg_cnt || 4701 caller->stack_arg_regs[spi].type == NOT_INIT) { 4702 const char *arg_name = NULL; 4703 4704 if (args && args[i].name_off) 4705 arg_name = btf_name_by_offset(btf, args[i].name_off); 4706 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4707 nargs, spi + 1); 4708 bpf_diag_stack_arg_uninit(env, env->insn_idx, nargs, spi, 4709 callee_name, arg_name); 4710 return -EFAULT; 4711 } 4712 } 4713 4714 return 0; 4715 } 4716 4717 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4718 struct bpf_reg_state *regs, int arg) 4719 { 4720 if (arg < MAX_BPF_FUNC_REG_ARGS) 4721 return ®s[arg + 1]; 4722 4723 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4724 } 4725 4726 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4727 int off, int size, enum bpf_access_type type) 4728 { 4729 struct bpf_map *map = reg->map_ptr; 4730 u32 cap = bpf_map_flags_to_cap(map); 4731 4732 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4733 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4734 map->value_size, reg_smin(reg) + off, size); 4735 return -EACCES; 4736 } 4737 4738 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4739 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4740 map->value_size, reg_smin(reg) + off, size); 4741 return -EACCES; 4742 } 4743 4744 return 0; 4745 } 4746 4747 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4748 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4749 int off, int size, u32 mem_size, 4750 bool zero_size_allowed) 4751 { 4752 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4753 4754 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4755 return 0; 4756 4757 switch (reg->type) { 4758 case PTR_TO_MAP_KEY: 4759 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4760 mem_size, off, size); 4761 break; 4762 case PTR_TO_MAP_VALUE: 4763 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4764 mem_size, off, size); 4765 break; 4766 case PTR_TO_PACKET: 4767 case PTR_TO_PACKET_META: 4768 case PTR_TO_PACKET_END: 4769 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4770 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4771 break; 4772 case PTR_TO_CTX: 4773 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4774 mem_size, off, size); 4775 break; 4776 case PTR_TO_MEM: 4777 default: 4778 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4779 mem_size, off, size); 4780 } 4781 4782 return -EACCES; 4783 } 4784 4785 /* check read/write into a memory region with possible variable offset */ 4786 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4787 int off, int size, u32 mem_size, 4788 bool zero_size_allowed) 4789 { 4790 const char *proof = ""; 4791 const char *start; 4792 s64 max_start, max_end; 4793 int err; 4794 4795 /* We may have adjusted the register pointing to memory region, so we 4796 * need to try adding each of min_value and max_value to off 4797 * to make sure our theoretical access will be safe. 4798 * 4799 * The minimum value is only important with signed 4800 * comparisons where we can't assume the floor of a 4801 * value is 0. If we are using signed variables for our 4802 * index'es we need to make sure that whatever we use 4803 * will have a set floor within our range. 4804 */ 4805 if (reg_smin(reg) < 0 && 4806 (reg_smin(reg) == S64_MIN || 4807 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4808 reg_smin(reg) + off < 0)) { 4809 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4810 reg_arg_name(env, argno)); 4811 err = -EACCES; 4812 if (bpf_diag_enabled(env)) { 4813 start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off); 4814 proof = bpf_diag_fmt( 4815 env, "the minimal bound for a memory access is a negative value: %s", 4816 start); 4817 } 4818 goto report_error; 4819 } 4820 4821 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4822 mem_size, zero_size_allowed); 4823 if (err) { 4824 verbose(env, "%s min value is outside of the allowed memory range\n", 4825 reg_arg_name(env, argno)); 4826 if (bpf_diag_enabled(env)) { 4827 start = bpf_diag_fmt_s64_sum(env, reg_smin(reg), off); 4828 proof = bpf_diag_fmt( 4829 env, "the minimal bound for a memory access is %s and is outside of the object of size %u", 4830 start, mem_size); 4831 } 4832 goto report_error; 4833 } 4834 4835 /* If we haven't set a max value then we need to bail since we can't be 4836 * sure we won't do bad things. 4837 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4838 */ 4839 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4840 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4841 reg_arg_name(env, argno)); 4842 err = -EACCES; 4843 if (bpf_diag_enabled(env)) 4844 proof = bpf_diag_fmt( 4845 env, "the maximal bound for a memory access is %llu and exceeds maximum allowed offset of %u", 4846 reg_umax(reg), BPF_MAX_VAR_OFF); 4847 goto report_error; 4848 } 4849 4850 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4851 mem_size, zero_size_allowed); 4852 if (err) { 4853 verbose(env, "%s max value is outside of the allowed memory range\n", 4854 reg_arg_name(env, argno)); 4855 if (bpf_diag_enabled(env)) { 4856 max_start = (s64)reg_umax(reg) + off; 4857 max_end = max_start + size; 4858 proof = bpf_diag_fmt( 4859 env, "the maximal bound for a memory access is %lld: start %lld + access_size %d, beyond object_size %u", 4860 max_end, max_start, size, mem_size); 4861 } 4862 goto report_error; 4863 } 4864 4865 return 0; 4866 4867 report_error: 4868 bpf_diag_mem_bounds(env, env->insn_idx, reg_from_argno(argno), 4869 reg_arg_name(env, argno), reg_type_str(env, reg->type), proof, 4870 off, size, mem_size, reg); 4871 return err; 4872 } 4873 4874 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4875 const struct bpf_reg_state *reg, argno_t argno, 4876 bool fixed_off_ok) 4877 { 4878 /* Access to this pointer-typed register or passing it to a helper 4879 * is only allowed in its original, unmodified form. 4880 */ 4881 4882 if (!tnum_is_const(reg->var_off)) { 4883 char tn_buf[48]; 4884 4885 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4886 verbose(env, "variable %s access var_off=%s disallowed\n", 4887 reg_type_str(env, reg->type), tn_buf); 4888 return -EACCES; 4889 } 4890 4891 if (reg_smin(reg) < 0) { 4892 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4893 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4894 return -EACCES; 4895 } 4896 4897 if (!fixed_off_ok && reg->var_off.value != 0) { 4898 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4899 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4900 bpf_diag_invalid_deref(env, env->insn_idx, reg_from_argno(argno), 4901 reg_arg_name(env, argno), reg, 4902 BPF_DIAG_DEREF_MODIFIED_PTR, reg->var_off.value); 4903 return -EACCES; 4904 } 4905 4906 return 0; 4907 } 4908 4909 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4910 const struct bpf_reg_state *reg, int regno) 4911 { 4912 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4913 } 4914 4915 static int map_kptr_match_type(struct bpf_verifier_env *env, 4916 struct btf_field *kptr_field, 4917 struct bpf_reg_state *reg, u32 regno) 4918 { 4919 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4920 int perm_flags; 4921 const char *reg_name = ""; 4922 4923 if (base_type(reg->type) != PTR_TO_BTF_ID) 4924 goto bad_type; 4925 4926 if (btf_is_kernel(reg->btf)) { 4927 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4928 4929 /* Only unreferenced case accepts untrusted pointers */ 4930 if (kptr_field->type == BPF_KPTR_UNREF) 4931 perm_flags |= PTR_UNTRUSTED; 4932 } else { 4933 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4934 if (kptr_field->type == BPF_KPTR_PERCPU) 4935 perm_flags |= MEM_PERCPU; 4936 } 4937 4938 if (type_flag(reg->type) & ~perm_flags) 4939 goto bad_type; 4940 4941 /* 4942 * A BPF_KPTR_PERCPU field is read back as MEM_PERCPU, so the value 4943 * stored in it must carry the same flag. 4944 */ 4945 if ((kptr_field->type == BPF_KPTR_PERCPU) != !!(reg->type & MEM_PERCPU)) 4946 goto bad_type; 4947 4948 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4949 reg_name = btf_type_name(reg->btf, reg->btf_id); 4950 4951 /* For ref_ptr case, release function check should ensure we get one 4952 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4953 * normal store of unreferenced kptr, we must ensure var_off is zero. 4954 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4955 * reg->id is not needed here. 4956 */ 4957 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4958 return -EACCES; 4959 4960 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4961 * we also need to take into account the reg->var_off. 4962 * 4963 * We want to support cases like: 4964 * 4965 * struct foo { 4966 * struct bar br; 4967 * struct baz bz; 4968 * }; 4969 * 4970 * struct foo *v; 4971 * v = func(); // PTR_TO_BTF_ID 4972 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4973 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4974 * // first member type of struct after comparison fails 4975 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4976 * // to match type 4977 * 4978 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4979 * is zero. We must also ensure that btf_struct_ids_match does not walk 4980 * the struct to match type against first member of struct, i.e. reject 4981 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4982 * strict mode to true for type match. 4983 */ 4984 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4985 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4986 kptr_field->type != BPF_KPTR_UNREF, 4987 !type_is_alloc(reg->type))) 4988 goto bad_type; 4989 return 0; 4990 bad_type: 4991 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4992 reg_type_str(env, reg->type), reg_name); 4993 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4994 if (kptr_field->type == BPF_KPTR_UNREF) 4995 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4996 targ_name); 4997 else 4998 verbose(env, "\n"); 4999 return -EINVAL; 5000 } 5001 5002 static bool in_sleepable(struct bpf_verifier_env *env) 5003 { 5004 return env->cur_state->in_sleepable; 5005 } 5006 5007 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5008 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5009 */ 5010 static bool in_rcu_cs(struct bpf_verifier_env *env) 5011 { 5012 return env->cur_state->active_rcu_locks || 5013 env->cur_state->active_preempt_locks || 5014 env->cur_state->active_locks || 5015 env->cur_state->active_irq_id || 5016 !in_sleepable(env); 5017 } 5018 5019 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5020 BTF_SET_START(rcu_protected_types) 5021 #ifdef CONFIG_NET 5022 BTF_ID(struct, prog_test_ref_kfunc) 5023 #endif 5024 #ifdef CONFIG_CGROUPS 5025 BTF_ID(struct, cgroup) 5026 #endif 5027 #ifdef CONFIG_BPF_JIT 5028 BTF_ID(struct, bpf_cpumask) 5029 #endif 5030 BTF_ID(struct, task_struct) 5031 #ifdef CONFIG_BPF_CRYPTO 5032 BTF_ID(struct, bpf_crypto_ctx) 5033 #endif 5034 #ifdef CONFIG_INET 5035 BTF_ID(struct, bpf_ksock) 5036 #endif 5037 BTF_SET_END(rcu_protected_types) 5038 5039 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5040 { 5041 if (!btf_is_kernel(btf)) 5042 return true; 5043 return btf_id_set_contains(&rcu_protected_types, btf_id); 5044 } 5045 5046 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5047 { 5048 struct btf_struct_meta *meta; 5049 5050 if (btf_is_kernel(kptr_field->kptr.btf)) 5051 return NULL; 5052 5053 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5054 kptr_field->kptr.btf_id); 5055 5056 return meta ? meta->record : NULL; 5057 } 5058 5059 static bool rcu_safe_kptr(const struct btf_field *field) 5060 { 5061 const struct btf_field_kptr *kptr = &field->kptr; 5062 5063 return field->type == BPF_KPTR_PERCPU || 5064 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5065 } 5066 5067 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5068 { 5069 struct btf_record *rec; 5070 u32 ret; 5071 5072 ret = PTR_MAYBE_NULL; 5073 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5074 ret |= MEM_RCU; 5075 if (kptr_field->type == BPF_KPTR_PERCPU) 5076 ret |= MEM_PERCPU; 5077 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5078 ret |= MEM_ALLOC; 5079 5080 rec = kptr_pointee_btf_record(kptr_field); 5081 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5082 ret |= NON_OWN_REF; 5083 } else { 5084 ret |= PTR_UNTRUSTED; 5085 } 5086 5087 return ret; 5088 } 5089 5090 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 5091 struct btf_field *field) 5092 { 5093 struct bpf_reg_state *reg; 5094 const struct btf_type *t; 5095 5096 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 5097 mark_reg_known_zero(env, cur_regs(env), regno); 5098 reg = reg_state(env, regno); 5099 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 5100 reg->mem_size = t->size; 5101 reg->id = ++env->id_gen; 5102 5103 return 0; 5104 } 5105 5106 static int check_map_kptr_access(struct bpf_verifier_env *env, 5107 int value_regno, int insn_idx, 5108 struct btf_field *kptr_field) 5109 { 5110 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5111 int class = BPF_CLASS(insn->code); 5112 struct bpf_reg_state *val_reg; 5113 int ret; 5114 5115 /* Things we already checked for in check_map_access and caller: 5116 * - Reject cases where variable offset may touch kptr 5117 * - size of access (must be BPF_DW) 5118 * - tnum_is_const(reg->var_off) 5119 * - kptr_field->offset == off + reg->var_off.value 5120 */ 5121 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5122 if (BPF_MODE(insn->code) != BPF_MEM) { 5123 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5124 return -EACCES; 5125 } 5126 5127 /* We only allow loading referenced kptr, since it will be marked as 5128 * untrusted, similar to unreferenced kptr. 5129 */ 5130 if (class != BPF_LDX && 5131 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5132 verbose(env, "store to referenced kptr disallowed\n"); 5133 return -EACCES; 5134 } 5135 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 5136 verbose(env, "store to uptr disallowed\n"); 5137 return -EACCES; 5138 } 5139 5140 if (class == BPF_LDX) { 5141 if (kptr_field->type == BPF_UPTR) 5142 return mark_uptr_ld_reg(env, value_regno, kptr_field); 5143 5144 /* We can simply mark the value_regno receiving the pointer 5145 * value from map as PTR_TO_BTF_ID, with the correct type. 5146 */ 5147 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 5148 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5149 btf_ld_kptr_type(env, kptr_field)); 5150 if (ret < 0) 5151 return ret; 5152 } else if (class == BPF_STX) { 5153 val_reg = reg_state(env, value_regno); 5154 if (bpf_register_is_null(val_reg)) { 5155 /* 5156 * This store is valid only because the scalar is known to be 5157 * zero. Mark it precise so another scalar cannot be pruned 5158 * against this state. 5159 */ 5160 return mark_chain_precision(env, value_regno); 5161 } 5162 if (map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5163 return -EACCES; 5164 } else if (class == BPF_ST) { 5165 if (insn->imm) { 5166 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5167 kptr_field->offset); 5168 return -EACCES; 5169 } 5170 } else { 5171 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5172 return -EACCES; 5173 } 5174 return 0; 5175 } 5176 5177 /* 5178 * Return the size of the memory region accessible from a pointer to map value. 5179 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 5180 */ 5181 static u32 map_mem_size(const struct bpf_map *map) 5182 { 5183 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5184 return map->max_entries * sizeof(long); 5185 5186 return map->value_size; 5187 } 5188 5189 /* check read/write into a map element with possible variable offset */ 5190 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 5191 int off, int size, bool zero_size_allowed, 5192 enum bpf_access_src src) 5193 { 5194 struct bpf_map *map = reg->map_ptr; 5195 u32 mem_size = map_mem_size(map); 5196 struct btf_record *rec; 5197 int err, i; 5198 5199 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 5200 if (err) 5201 return err; 5202 5203 if (IS_ERR_OR_NULL(map->record)) 5204 return 0; 5205 rec = map->record; 5206 for (i = 0; i < rec->cnt; i++) { 5207 struct btf_field *field = &rec->fields[i]; 5208 u32 p = field->offset; 5209 5210 /* If any part of a field can be touched by load/store, reject 5211 * this program. To check that [x1, x2) overlaps with [y1, y2), 5212 * it is sufficient to check x1 < y2 && y1 < x2. 5213 */ 5214 if (reg_smin(reg) + off < p + field->size && 5215 p < reg_umax(reg) + off + size) { 5216 switch (field->type) { 5217 case BPF_KPTR_UNREF: 5218 case BPF_KPTR_REF: 5219 case BPF_KPTR_PERCPU: 5220 case BPF_UPTR: 5221 if (src != ACCESS_DIRECT) { 5222 verbose(env, "%s cannot be accessed indirectly by helper\n", 5223 btf_field_type_name(field->type)); 5224 return -EACCES; 5225 } 5226 if (!tnum_is_const(reg->var_off)) { 5227 verbose(env, "%s access cannot have variable offset\n", 5228 btf_field_type_name(field->type)); 5229 return -EACCES; 5230 } 5231 if (p != off + reg->var_off.value) { 5232 verbose(env, "%s access misaligned expected=%u off=%llu\n", 5233 btf_field_type_name(field->type), 5234 p, off + reg->var_off.value); 5235 return -EACCES; 5236 } 5237 if (size != bpf_size_to_bytes(BPF_DW)) { 5238 verbose(env, "%s access size must be BPF_DW\n", 5239 btf_field_type_name(field->type)); 5240 return -EACCES; 5241 } 5242 break; 5243 default: 5244 verbose(env, "%s cannot be accessed directly by load/store\n", 5245 btf_field_type_name(field->type)); 5246 return -EACCES; 5247 } 5248 } 5249 } 5250 return 0; 5251 } 5252 5253 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5254 const struct bpf_call_arg_meta *meta, 5255 enum bpf_access_type t) 5256 { 5257 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5258 5259 switch (prog_type) { 5260 /* Program types only with direct read access go here! */ 5261 case BPF_PROG_TYPE_LWT_IN: 5262 case BPF_PROG_TYPE_LWT_OUT: 5263 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5264 case BPF_PROG_TYPE_SK_REUSEPORT: 5265 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5266 case BPF_PROG_TYPE_CGROUP_SKB: 5267 if (t == BPF_WRITE) 5268 return false; 5269 fallthrough; 5270 5271 /* Program types with direct read + write access go here! */ 5272 case BPF_PROG_TYPE_SCHED_CLS: 5273 case BPF_PROG_TYPE_SCHED_ACT: 5274 case BPF_PROG_TYPE_XDP: 5275 case BPF_PROG_TYPE_LWT_XMIT: 5276 case BPF_PROG_TYPE_SK_SKB: 5277 case BPF_PROG_TYPE_SK_MSG: 5278 if (meta && !meta->btf && meta->func_id) 5279 return meta->fn->pkt_access; 5280 5281 if (t == BPF_WRITE) 5282 env->seen_direct_write = true; 5283 return true; 5284 5285 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5286 if (t == BPF_WRITE) 5287 env->seen_direct_write = true; 5288 5289 return true; 5290 5291 default: 5292 return false; 5293 } 5294 } 5295 5296 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 5297 int size, bool zero_size_allowed) 5298 { 5299 int err; 5300 5301 if (reg->range < 0) { 5302 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 5303 return -EINVAL; 5304 } 5305 5306 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 5307 if (err) 5308 return err; 5309 5310 /* __check_mem_access has made sure "off + size - 1" is within u16. 5311 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 5312 * otherwise find_good_pkt_pointers would have refused to set range info 5313 * that __check_mem_access would have rejected this pkt access. 5314 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 5315 */ 5316 env->prog->aux->max_pkt_offset = 5317 max_t(u32, env->prog->aux->max_pkt_offset, 5318 off + reg_umax(reg) + size - 1); 5319 5320 return 0; 5321 } 5322 5323 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 5324 { 5325 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 5326 } 5327 5328 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5329 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5330 enum bpf_access_type t, struct bpf_insn_access_aux *info) 5331 { 5332 if (env->ops->is_valid_access && 5333 env->ops->is_valid_access(off, size, t, env->prog, info)) { 5334 /* A non zero info.ctx_field_size indicates that this field is a 5335 * candidate for later verifier transformation to load the whole 5336 * field and then apply a mask when accessed with a narrower 5337 * access than actual ctx access size. A zero info.ctx_field_size 5338 * will only allow for whole field access and rejects any other 5339 * type of narrower access. 5340 */ 5341 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 5342 if (info->ref_id && 5343 !find_reference_state(env->cur_state, info->ref_id)) { 5344 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 5345 off); 5346 return -EACCES; 5347 } 5348 } else { 5349 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 5350 } 5351 /* remember the offset of last byte accessed in ctx */ 5352 if (env->prog->aux->max_ctx_offset < off + size) 5353 env->prog->aux->max_ctx_offset = off + size; 5354 return 0; 5355 } 5356 5357 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5358 return -EACCES; 5359 } 5360 5361 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 5362 int off, int access_size, enum bpf_access_type t, 5363 struct bpf_insn_access_aux *info) 5364 { 5365 /* 5366 * Program types that don't rewrite ctx accesses can safely 5367 * dereference ctx pointers with fixed offsets. 5368 */ 5369 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 5370 bool fixed_off_ok = !env->ops->convert_ctx_access; 5371 int err; 5372 5373 if (var_off_ok) 5374 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 5375 else 5376 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 5377 if (err) 5378 return err; 5379 off += reg_umax(reg); 5380 5381 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 5382 if (err) 5383 verbose_linfo(env, insn_idx, "; "); 5384 return err; 5385 } 5386 5387 static int check_flow_keys_access(struct bpf_verifier_env *env, 5388 struct bpf_reg_state *reg, argno_t argno, 5389 int off, int size) 5390 { 5391 /* Only a constant offset is allowed here; fold it into off. */ 5392 if (!tnum_is_const(reg->var_off)) { 5393 char tn_buf[48]; 5394 5395 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5396 verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n", 5397 reg_arg_name(env, argno), off, tn_buf); 5398 return -EACCES; 5399 } 5400 off += reg->var_off.value; 5401 5402 if (size < 0 || off < 0 || 5403 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5404 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5405 off, size); 5406 return -EACCES; 5407 } 5408 return 0; 5409 } 5410 5411 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5412 struct bpf_reg_state *reg, argno_t argno, int off, int size, 5413 enum bpf_access_type t) 5414 { 5415 struct bpf_insn_access_aux info = {}; 5416 bool valid; 5417 5418 if (reg_smin(reg) < 0) { 5419 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5420 reg_arg_name(env, argno)); 5421 return -EACCES; 5422 } 5423 5424 switch (reg->type) { 5425 case PTR_TO_SOCK_COMMON: 5426 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5427 break; 5428 case PTR_TO_SOCKET: 5429 valid = bpf_sock_is_valid_access(off, size, t, &info); 5430 break; 5431 case PTR_TO_TCP_SOCK: 5432 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5433 break; 5434 case PTR_TO_XDP_SOCK: 5435 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5436 break; 5437 default: 5438 valid = false; 5439 } 5440 5441 if (valid) { 5442 env->insn_aux_data[insn_idx].ctx_field_size = 5443 info.ctx_field_size; 5444 return 0; 5445 } 5446 5447 verbose(env, "%s invalid %s access off=%d size=%d\n", 5448 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 5449 5450 return -EACCES; 5451 } 5452 5453 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5454 { 5455 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5456 } 5457 5458 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5459 { 5460 const struct bpf_reg_state *reg = reg_state(env, regno); 5461 5462 return reg->type == PTR_TO_CTX; 5463 } 5464 5465 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5466 { 5467 const struct bpf_reg_state *reg = reg_state(env, regno); 5468 5469 return type_is_sk_pointer(reg->type); 5470 } 5471 5472 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5473 { 5474 const struct bpf_reg_state *reg = reg_state(env, regno); 5475 5476 return type_is_pkt_pointer(reg->type); 5477 } 5478 5479 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5480 { 5481 const struct bpf_reg_state *reg = reg_state(env, regno); 5482 5483 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5484 return reg->type == PTR_TO_FLOW_KEYS; 5485 } 5486 5487 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5488 { 5489 const struct bpf_reg_state *reg = reg_state(env, regno); 5490 5491 return reg->type == PTR_TO_ARENA; 5492 } 5493 5494 static bool is_load_acq_unsafe(struct bpf_verifier_env *env, int regno, 5495 struct bpf_insn *insn) 5496 { 5497 const struct bpf_reg_state *reg = reg_state(env, regno); 5498 5499 /* 5500 * A BPF_LOAD_ACQ is not rewritten to a BPF_PROBE_MEM load by the 5501 * verifier, unlike a regular BPF_LDX. The JIT would emit a plain load 5502 * with no exception table entry, so a fault (e.g. NULL deref) crashes 5503 * the kernel instead of being handled. Reject the source pointer types 5504 * that would have needed that protection, the remaining ones stay 5505 * allowed. 5506 */ 5507 return insn->imm == BPF_LOAD_ACQ && bpf_may_fault_on_deref(reg->type); 5508 } 5509 5510 /* Return false if @regno contains a pointer whose type isn't supported for 5511 * atomic instruction @insn. 5512 */ 5513 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 5514 struct bpf_insn *insn) 5515 { 5516 if (is_ctx_reg(env, regno)) 5517 return false; 5518 if (is_pkt_reg(env, regno)) 5519 return false; 5520 if (is_flow_key_reg(env, regno)) 5521 return false; 5522 if (is_sk_reg(env, regno)) 5523 return false; 5524 if (is_arena_reg(env, regno)) 5525 return bpf_jit_supports_insn(insn, true); 5526 if (is_load_acq_unsafe(env, regno, insn)) 5527 return false; 5528 return true; 5529 } 5530 5531 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5532 #ifdef CONFIG_NET 5533 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5534 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5535 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5536 #endif 5537 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5538 }; 5539 5540 static bool is_trusted_reg_type(struct bpf_verifier_env *env, 5541 const struct bpf_reg_state *reg, 5542 enum bpf_reg_type type) 5543 { 5544 /* A referenced register is always trusted. */ 5545 if (reg_is_referenced(env, reg)) 5546 return true; 5547 5548 /* Types listed in the reg2btf_ids are always trusted */ 5549 if (reg2btf_ids[base_type(type)] && 5550 !bpf_type_has_unsafe_modifiers(type)) 5551 return true; 5552 5553 /* If a register is not referenced, it is trusted if it has the 5554 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5555 * other type modifiers may be safe, but we elect to take an opt-in 5556 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5557 * not. 5558 * 5559 * Eventually, we should make PTR_TRUSTED the single source of truth 5560 * for whether a register is trusted. 5561 */ 5562 return type_flag(type) & BPF_REG_TRUSTED_MODIFIERS && 5563 !bpf_type_has_unsafe_modifiers(type); 5564 } 5565 5566 static bool is_trusted_reg(struct bpf_verifier_env *env, 5567 const struct bpf_reg_state *reg) 5568 { 5569 return is_trusted_reg_type(env, reg, reg->type); 5570 } 5571 5572 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5573 { 5574 return reg->type & MEM_RCU; 5575 } 5576 5577 static void clear_trusted_flags(enum bpf_type_flag *flag) 5578 { 5579 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5580 } 5581 5582 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5583 const struct bpf_reg_state *reg, 5584 int off, int size, bool strict) 5585 { 5586 struct tnum reg_off; 5587 int ip_align; 5588 5589 /* Byte size accesses are always allowed. */ 5590 if (!strict || size == 1) 5591 return 0; 5592 5593 /* For platforms that do not have a Kconfig enabling 5594 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5595 * NET_IP_ALIGN is universally set to '2'. And on platforms 5596 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5597 * to this code only in strict mode where we want to emulate 5598 * the NET_IP_ALIGN==2 checking. Therefore use an 5599 * unconditional IP align value of '2'. 5600 */ 5601 ip_align = 2; 5602 5603 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 5604 if (!tnum_is_aligned(reg_off, size)) { 5605 char tn_buf[48]; 5606 5607 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5608 verbose(env, 5609 "misaligned packet access off %d+%s+%d size %d\n", 5610 ip_align, tn_buf, off, size); 5611 return -EACCES; 5612 } 5613 5614 return 0; 5615 } 5616 5617 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5618 const struct bpf_reg_state *reg, 5619 const char *pointer_desc, 5620 int off, int size, bool strict) 5621 { 5622 struct tnum reg_off; 5623 5624 /* Byte size accesses are always allowed. */ 5625 if (!strict || size == 1) 5626 return 0; 5627 5628 reg_off = tnum_add(reg->var_off, tnum_const(off)); 5629 if (!tnum_is_aligned(reg_off, size)) { 5630 char tn_buf[48]; 5631 5632 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5633 verbose(env, "misaligned %saccess off %s+%d size %d\n", 5634 pointer_desc, tn_buf, off, size); 5635 return -EACCES; 5636 } 5637 5638 return 0; 5639 } 5640 5641 static int check_ptr_alignment(struct bpf_verifier_env *env, 5642 const struct bpf_reg_state *reg, int off, 5643 int size, bool strict_alignment_once) 5644 { 5645 bool strict = env->strict_alignment || strict_alignment_once; 5646 const char *pointer_desc = ""; 5647 5648 switch (reg->type) { 5649 case PTR_TO_PACKET: 5650 case PTR_TO_PACKET_META: 5651 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5652 * right in front, treat it the very same way. 5653 */ 5654 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5655 case PTR_TO_FLOW_KEYS: 5656 pointer_desc = "flow keys "; 5657 break; 5658 case PTR_TO_MAP_KEY: 5659 pointer_desc = "key "; 5660 break; 5661 case PTR_TO_MAP_VALUE: 5662 pointer_desc = "value "; 5663 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5664 strict = true; 5665 break; 5666 case PTR_TO_CTX: 5667 pointer_desc = "context "; 5668 break; 5669 case PTR_TO_STACK: 5670 pointer_desc = "stack "; 5671 /* The stack spill tracking logic in check_stack_write_fixed_off() 5672 * and check_stack_read_fixed_off() relies on stack accesses being 5673 * aligned. 5674 */ 5675 strict = true; 5676 break; 5677 case PTR_TO_SOCKET: 5678 pointer_desc = "sock "; 5679 break; 5680 case PTR_TO_SOCK_COMMON: 5681 pointer_desc = "sock_common "; 5682 break; 5683 case PTR_TO_TCP_SOCK: 5684 pointer_desc = "tcp_sock "; 5685 break; 5686 case PTR_TO_XDP_SOCK: 5687 pointer_desc = "xdp_sock "; 5688 break; 5689 case PTR_TO_ARENA: 5690 return 0; 5691 default: 5692 break; 5693 } 5694 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5695 strict); 5696 } 5697 5698 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5699 { 5700 if (!bpf_jit_supports_private_stack()) 5701 return NO_PRIV_STACK; 5702 5703 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5704 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5705 * explicitly. 5706 */ 5707 switch (prog->type) { 5708 case BPF_PROG_TYPE_KPROBE: 5709 case BPF_PROG_TYPE_TRACEPOINT: 5710 case BPF_PROG_TYPE_PERF_EVENT: 5711 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5712 return PRIV_STACK_ADAPTIVE; 5713 case BPF_PROG_TYPE_TRACING: 5714 case BPF_PROG_TYPE_LSM: 5715 case BPF_PROG_TYPE_STRUCT_OPS: 5716 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5717 return PRIV_STACK_ADAPTIVE; 5718 fallthrough; 5719 default: 5720 break; 5721 } 5722 5723 return NO_PRIV_STACK; 5724 } 5725 5726 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5727 { 5728 if (env->prog->jit_requested) 5729 return round_up(stack_depth, 16); 5730 5731 /* round up to 32-bytes, since this is granularity 5732 * of interpreter stack size 5733 */ 5734 return round_up(max_t(u32, stack_depth, 1), 32); 5735 } 5736 5737 /* temporary state used for call frame depth calculation */ 5738 struct bpf_subprog_call_depth_info { 5739 int ret_insn; /* caller instruction where we return to. */ 5740 int caller; /* caller subprogram idx */ 5741 int frame; /* # of consecutive static call stack frames on top of stack */ 5742 int callx_insn; /* callx instruction whose callees are being walked */ 5743 int callx_next; /* next callee of callx_insn to walk */ 5744 bool via_callx; /* the subprogram is entered via callx */ 5745 }; 5746 5747 /* starting from main bpf function walk all instructions of the function 5748 * and recursively walk all callees that given function can call. 5749 * Ignore jump and exit insns. 5750 */ 5751 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5752 struct bpf_subprog_call_depth_info *dinfo, 5753 bool priv_stack_supported) 5754 { 5755 struct bpf_subprog_info *subprog = env->subprog_info; 5756 struct bpf_insn *insn = env->prog->insnsi; 5757 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5758 bool tail_call_reachable = false; 5759 int total; 5760 int tmp; 5761 5762 /* no caller idx */ 5763 dinfo[idx].caller = -1; 5764 dinfo[idx].via_callx = false; 5765 5766 i = subprog[idx].start; 5767 if (!priv_stack_supported) 5768 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5769 process_func: 5770 dinfo[idx].callx_insn = -1; 5771 if (subprog[idx].has_ld_abs) { 5772 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5773 if (subprog[tmp].is_cb) { 5774 verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n"); 5775 return -EINVAL; 5776 } 5777 } 5778 } 5779 5780 /* protect against potential stack overflow that might happen when 5781 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5782 * depth for such case down to 256 so that the worst case scenario 5783 * would result in 8k stack size (32 which is tailcall limit * 256 = 5784 * 8k). 5785 * 5786 * To get the idea what might happen, see an example: 5787 * func1 -> sub rsp, 128 5788 * subfunc1 -> sub rsp, 256 5789 * tailcall1 -> add rsp, 256 5790 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5791 * subfunc2 -> sub rsp, 64 5792 * subfunc22 -> sub rsp, 128 5793 * tailcall2 -> add rsp, 128 5794 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5795 * 5796 * tailcall will unwind the current stack frame but it will not get rid 5797 * of caller's stack as shown on the example above. 5798 */ 5799 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5800 verbose(env, 5801 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5802 depth); 5803 return -EACCES; 5804 } 5805 5806 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5807 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5808 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5809 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5810 } else if (priv_stack_supported) { 5811 /* Request private stack support only if the subprog stack 5812 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5813 * avoid jit penalty if the stack usage is small. 5814 */ 5815 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5816 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5817 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5818 } 5819 5820 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5821 if (subprog_depth > env->max_stack_depth) 5822 env->max_stack_depth = subprog_depth; 5823 if (subprog_depth > env->stack_limit) { 5824 verbose(env, "stack size of subprog %d is %d. Too large\n", 5825 idx, subprog_depth); 5826 return -EACCES; 5827 } 5828 } else { 5829 depth += subprog_depth; 5830 if (depth > env->max_stack_depth) 5831 env->max_stack_depth = depth; 5832 if (depth > env->stack_limit) { 5833 total = 0; 5834 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5835 total++; 5836 5837 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5838 total, depth); 5839 return -EACCES; 5840 } 5841 } 5842 continue_func: 5843 subprog_end = subprog[idx + 1].start; 5844 for (; i < subprog_end; i++) { 5845 int next_insn, sidx; 5846 5847 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off && 5848 bpf_is_throw_kfunc(insn + i)) { 5849 bool err = false; 5850 5851 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5852 if (subprog[tmp].is_cb) { 5853 err = true; 5854 break; 5855 } 5856 } 5857 if (!err) 5858 continue; 5859 verbose(env, 5860 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5861 i, idx); 5862 return -EINVAL; 5863 } 5864 5865 if (bpf_is_callx(insn + i) || bpf_calls_callback(env, i)) { 5866 /* 5867 * Walk the callees and the callbacks recorded by 5868 * the main verification pass one by one, returning to 5869 * this insn after each. 5870 */ 5871 if (dinfo[idx].callx_insn != i) { 5872 dinfo[idx].callx_insn = i; 5873 dinfo[idx].callx_next = 0; 5874 } 5875 sidx = next_callx_callee(env, idx, dinfo[idx].callx_next); 5876 if (sidx < 0) 5877 continue; 5878 dinfo[idx].callx_next = sidx + 1; 5879 dinfo[idx].ret_insn = i; 5880 next_insn = subprog[sidx].start; 5881 } else if (bpf_pseudo_call(insn + i) || bpf_pseudo_func(insn + i)) { 5882 /* find the callee */ 5883 next_insn = i + insn[i].imm + 1; 5884 sidx = bpf_find_subprog(env, next_insn); 5885 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5886 return -EFAULT; 5887 if (subprog[sidx].is_async_cb) { 5888 /* async callbacks don't increase bpf prog stack size unless called directly */ 5889 if (!bpf_pseudo_call(insn + i)) 5890 continue; 5891 if (subprog[sidx].is_exception_cb) { 5892 verbose(env, "insn %d cannot call exception cb directly", i); 5893 return -EINVAL; 5894 } 5895 } 5896 /* remember insn to return to */ 5897 dinfo[idx].ret_insn = i + 1; 5898 } else { 5899 continue; 5900 } 5901 5902 /* 5903 * sort_subprogs_topo() tolerates cycles in the call graph that 5904 * go through the address of a function being taken, since it 5905 * doesn't know what it is taken for. Such cycle is a recursion 5906 * unless it's an async callback, which are skipped above. 5907 * The main verification pass limits the depth of the recursion, 5908 * but it doesn't follow calls of global functions. 5909 */ 5910 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5911 if (tmp != sidx) 5912 continue; 5913 verbose(env, "recursive call from %s() to %s()\n", 5914 bpf_subprog_name(env, idx), bpf_subprog_name(env, sidx)); 5915 bpf_diag_program_structure( 5916 env, i, "recursive subprogram call", 5917 "Rewrite the recursion as an explicit bounded loop, or split the logic so subprogram calls do not form a cycle.", 5918 "This call or callback would make the subprogram call graph recursive. " 5919 "The verifier requires a finite, acyclic call graph so it can bound stack depth and analysis."); 5920 return -EINVAL; 5921 } 5922 5923 /* store caller info for after we return from callee */ 5924 dinfo[idx].frame = frame; 5925 5926 /* push caller idx into callee's dinfo */ 5927 dinfo[sidx].caller = idx; 5928 dinfo[sidx].via_callx = bpf_is_callx(insn + i); 5929 5930 i = next_insn; 5931 5932 idx = sidx; 5933 if (!priv_stack_supported) 5934 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5935 5936 /* sync tail_call_reachable with callee state on entry */ 5937 tail_call_reachable = subprog[idx].has_tail_call; 5938 5939 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5940 if (frame >= MAX_CALL_FRAMES) { 5941 verbose(env, "the call stack of %d frames is too deep !\n", 5942 frame); 5943 return -E2BIG; 5944 } 5945 goto process_func; 5946 } 5947 /* if tail call got detected across bpf2bpf calls then mark each of the 5948 * currently present subprog frames as tail call reachable subprogs; 5949 * this info will be utilized by JIT so that we will be preserving the 5950 * tail call counter throughout bpf2bpf calls combined with tailcalls 5951 */ 5952 if (tail_call_reachable) { 5953 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5954 if (subprog[tmp].is_cb) { 5955 verbose(env, "cannot tail call within callback\n"); 5956 return -EINVAL; 5957 } 5958 if (subprog[tmp].stack_arg_cnt) { 5959 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5960 return -EINVAL; 5961 } 5962 /* 5963 * JITs pass tail call counter in a register that is 5964 * not available when the callee is called via callx. 5965 */ 5966 if (dinfo[tmp].via_callx) { 5967 verbose(env, "tail_calls are not allowed in functions called via callx\n"); 5968 return -EINVAL; 5969 } 5970 subprog[tmp].tail_call_reachable = true; 5971 } 5972 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5973 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5974 return -EINVAL; 5975 } 5976 5977 if (subprog[0].tail_call_reachable) 5978 env->prog->aux->tail_call_reachable = true; 5979 5980 /* end of for() loop means the last insn of the 'subprog' 5981 * was reached. Doesn't matter whether it was JA or EXIT 5982 */ 5983 if (frame == 0 && dinfo[idx].caller < 0) 5984 return 0; 5985 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5986 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5987 5988 /* pop caller idx from callee */ 5989 idx = dinfo[idx].caller; 5990 5991 /* retrieve caller state from its frame */ 5992 frame = dinfo[idx].frame; 5993 i = dinfo[idx].ret_insn; 5994 5995 /* reset tail_call_reachable to the parent's actual state */ 5996 tail_call_reachable = subprog[idx].tail_call_reachable; 5997 5998 goto continue_func; 5999 } 6000 6001 static int check_max_stack_depth(struct bpf_verifier_env *env) 6002 { 6003 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 6004 struct bpf_subprog_call_depth_info *dinfo; 6005 struct bpf_subprog_info *si = env->subprog_info; 6006 bool priv_stack_supported; 6007 int ret; 6008 6009 dinfo = kvzalloc_objs(*dinfo, env->subprog_cnt, GFP_KERNEL_ACCOUNT); 6010 if (!dinfo) 6011 return -ENOMEM; 6012 6013 for (int i = 0; i < env->subprog_cnt; i++) { 6014 if (si[i].has_tail_call) { 6015 priv_stack_mode = NO_PRIV_STACK; 6016 break; 6017 } 6018 } 6019 6020 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 6021 priv_stack_mode = bpf_enable_priv_stack(env->prog); 6022 6023 /* All async_cb subprogs use normal kernel stack. If a particular 6024 * subprog appears in both main prog and async_cb subtree, that 6025 * subprog will use normal kernel stack to avoid potential nesting. 6026 * The reverse subprog traversal ensures when main prog subtree is 6027 * checked, the subprogs appearing in async_cb subtrees are already 6028 * marked as using normal kernel stack, so stack size checking can 6029 * be done properly. 6030 */ 6031 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 6032 if (!i || si[i].is_async_cb) { 6033 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 6034 ret = check_max_stack_depth_subprog(env, i, dinfo, 6035 priv_stack_supported); 6036 if (ret < 0) { 6037 kvfree(dinfo); 6038 return ret; 6039 } 6040 } 6041 } 6042 6043 for (int i = 0; i < env->subprog_cnt; i++) { 6044 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6045 env->prog->aux->jits_use_priv_stack = true; 6046 break; 6047 } 6048 } 6049 6050 kvfree(dinfo); 6051 6052 return 0; 6053 } 6054 6055 static int __check_buffer_access(struct bpf_verifier_env *env, 6056 const char *buf_info, 6057 const struct bpf_reg_state *reg, 6058 argno_t argno, int off, int size, 6059 u32 *access_end) 6060 { 6061 s64 start; 6062 6063 if (!tnum_is_const(reg->var_off)) { 6064 char tn_buf[48]; 6065 6066 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6067 verbose(env, 6068 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 6069 reg_arg_name(env, argno), off, tn_buf); 6070 return -EACCES; 6071 } 6072 6073 start = (s64)reg->var_off.value + off; 6074 if (start < 0) { 6075 verbose(env, 6076 "%s invalid negative %s buffer offset: off=%d, var_off=%lld\n", 6077 reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value); 6078 return -EACCES; 6079 } 6080 6081 *access_end = start + size; 6082 return 0; 6083 } 6084 6085 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6086 const struct bpf_reg_state *reg, 6087 argno_t argno, int off, int size) 6088 { 6089 u32 access_end; 6090 int err; 6091 6092 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end); 6093 if (err) 6094 return err; 6095 6096 env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access); 6097 6098 return 0; 6099 } 6100 6101 static int check_buffer_access(struct bpf_verifier_env *env, 6102 const struct bpf_reg_state *reg, 6103 argno_t argno, int off, int size, 6104 bool zero_size_allowed, 6105 u32 *max_access, bool write) 6106 { 6107 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6108 struct bpf_prog_aux *aux = env->prog->aux; 6109 u32 access_end; 6110 int err; 6111 6112 err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end); 6113 if (err) 6114 return err; 6115 6116 *max_access = max(access_end, *max_access); 6117 if (write && size) { 6118 if (!aux->max_rdwr_write || access_end - size < aux->min_rdwr_write) 6119 aux->min_rdwr_write = access_end - size; 6120 aux->max_rdwr_write = max(access_end, aux->max_rdwr_write); 6121 } 6122 6123 return 0; 6124 } 6125 6126 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6127 static void zext_32_to_64(struct bpf_reg_state *reg) 6128 { 6129 reg_step_check_unsigned(reg, 32); 6130 reg->var_off = tnum_subreg(reg->var_off); 6131 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 6132 } 6133 6134 /* truncate register to smaller size (in bytes) 6135 * must be called with size < BPF_REG_SIZE 6136 */ 6137 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6138 { 6139 u64 mask = (1ULL << (size * 8)) - 1; 6140 6141 reg_step_check_unsigned(reg, size * 8); 6142 6143 /* clear high bits in bit representation */ 6144 reg->var_off = tnum_cast(reg->var_off, size); 6145 6146 /* fix arithmetic bounds */ 6147 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 6148 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 6149 else 6150 reg_set_urange64(reg, 0, mask); 6151 6152 /* If size is smaller than 32bit register the 32bit register 6153 * values are also truncated so we push 64-bit bounds into 6154 * 32-bit bounds. Above were truncated < 32-bits already. 6155 */ 6156 if (size < 4) 6157 __mark_reg32_unbounded(reg); 6158 6159 reg_bounds_sync(reg); 6160 } 6161 6162 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6163 { 6164 if (size == 1) { 6165 reg_set_srange64(reg, S8_MIN, S8_MAX); 6166 reg_set_srange32(reg, S8_MIN, S8_MAX); 6167 } else if (size == 2) { 6168 reg_set_srange64(reg, S16_MIN, S16_MAX); 6169 reg_set_srange32(reg, S16_MIN, S16_MAX); 6170 } else { 6171 /* size == 4 */ 6172 reg_set_srange64(reg, S32_MIN, S32_MAX); 6173 reg_set_srange32(reg, S32_MIN, S32_MAX); 6174 } 6175 reg->var_off = tnum_unknown; 6176 } 6177 6178 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6179 { 6180 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6181 u64 top_smax_value, top_smin_value; 6182 u64 num_bits = size * 8; 6183 s64 limit = 1LL << (num_bits - 1); 6184 6185 /* If every value fits the signed N-bit range sign extension is a noop. */ 6186 if (reg_smin(reg) >= -limit && reg_smax(reg) < limit) 6187 return; 6188 6189 /* See commen at reg_step_check_unsigned(). */ 6190 reg_step_reset(reg); 6191 6192 if (tnum_is_const(reg->var_off)) { 6193 u64_cval = reg->var_off.value; 6194 if (size == 1) 6195 reg->var_off = tnum_const((s8)u64_cval); 6196 else if (size == 2) 6197 reg->var_off = tnum_const((s16)u64_cval); 6198 else 6199 /* size == 4 */ 6200 reg->var_off = tnum_const((s32)u64_cval); 6201 6202 u64_cval = reg->var_off.value; 6203 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 6204 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 6205 return; 6206 } 6207 6208 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 6209 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 6210 6211 if (top_smax_value != top_smin_value) 6212 goto out; 6213 6214 /* find the s64_min and s64_min after sign extension */ 6215 if (size == 1) { 6216 init_s64_max = (s8)reg_smax(reg); 6217 init_s64_min = (s8)reg_smin(reg); 6218 } else if (size == 2) { 6219 init_s64_max = (s16)reg_smax(reg); 6220 init_s64_min = (s16)reg_smin(reg); 6221 } else { 6222 init_s64_max = (s32)reg_smax(reg); 6223 init_s64_min = (s32)reg_smin(reg); 6224 } 6225 6226 s64_max = max(init_s64_max, init_s64_min); 6227 s64_min = min(init_s64_max, init_s64_min); 6228 6229 /* both of s64_max/s64_min positive or negative */ 6230 if ((s64_max >= 0) == (s64_min >= 0)) { 6231 reg_set_srange64(reg, s64_min, s64_max); 6232 reg_set_srange32(reg, s64_min, s64_max); 6233 reg->var_off = tnum_range(s64_min, s64_max); 6234 return; 6235 } 6236 6237 out: 6238 set_sext64_default_val(reg, size); 6239 } 6240 6241 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6242 { 6243 if (size == 1) 6244 reg_set_srange32(reg, S8_MIN, S8_MAX); 6245 else 6246 /* size == 2 */ 6247 reg_set_srange32(reg, S16_MIN, S16_MAX); 6248 reg->var_off = tnum_subreg(tnum_unknown); 6249 } 6250 6251 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6252 { 6253 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6254 u32 top_smax_value, top_smin_value; 6255 u32 num_bits = size * 8; 6256 6257 /* 6258 * If value fits the non-negative half of the signed N-bit range, 6259 * sign extension is a noop. 6260 */ 6261 if (reg_umax(reg) < (1ULL << (num_bits - 1))) 6262 return; 6263 6264 /* See comment at reg_step_check_unsigned(). */ 6265 reg_step_reset(reg); 6266 6267 if (tnum_is_const(reg->var_off)) { 6268 u32_val = reg->var_off.value; 6269 if (size == 1) 6270 reg->var_off = tnum_const((s8)u32_val); 6271 else 6272 reg->var_off = tnum_const((s16)u32_val); 6273 6274 u32_val = reg->var_off.value; 6275 reg_set_srange32(reg, u32_val, u32_val); 6276 return; 6277 } 6278 6279 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 6280 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 6281 6282 if (top_smax_value != top_smin_value) 6283 goto out; 6284 6285 /* find the s32_min and s32_min after sign extension */ 6286 if (size == 1) { 6287 init_s32_max = (s8)reg_s32_max(reg); 6288 init_s32_min = (s8)reg_s32_min(reg); 6289 } else { 6290 /* size == 2 */ 6291 init_s32_max = (s16)reg_s32_max(reg); 6292 init_s32_min = (s16)reg_s32_min(reg); 6293 } 6294 s32_max = max(init_s32_max, init_s32_min); 6295 s32_min = min(init_s32_max, init_s32_min); 6296 6297 if ((s32_min >= 0) == (s32_max >= 0)) { 6298 reg_set_srange32(reg, s32_min, s32_max); 6299 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6300 return; 6301 } 6302 6303 out: 6304 set_sext32_default_val(reg, size); 6305 } 6306 6307 bool bpf_map_is_rdonly(const struct bpf_map *map) 6308 { 6309 /* A map is considered read-only if the following condition are true: 6310 * 6311 * 1) BPF program side cannot change any of the map content. The 6312 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6313 * and was set at map creation time. 6314 * 2) The map value(s) have been initialized from user space by a 6315 * loader and then "frozen", such that no new map update/delete 6316 * operations from syscall side are possible for the rest of 6317 * the map's lifetime from that point onwards. 6318 * 3) Any parallel/pending map update/delete operations from syscall 6319 * side have been completed. Only after that point, it's safe to 6320 * assume that map value(s) are immutable. 6321 */ 6322 return (map->map_flags & BPF_F_RDONLY_PROG) && 6323 READ_ONCE(map->frozen) && 6324 !bpf_map_write_active(map); 6325 } 6326 6327 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6328 bool is_ldsx) 6329 { 6330 void *ptr; 6331 u64 addr; 6332 int err; 6333 6334 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY || map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) 6335 return -EINVAL; 6336 err = map->ops->map_direct_value_addr(map, &addr, off); 6337 if (err) 6338 return err; 6339 ptr = (void *)(long)addr + off; 6340 6341 switch (size) { 6342 case sizeof(u8): 6343 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6344 break; 6345 case sizeof(u16): 6346 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6347 break; 6348 case sizeof(u32): 6349 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6350 break; 6351 case sizeof(u64): 6352 *val = *(u64 *)ptr; 6353 break; 6354 default: 6355 return -EINVAL; 6356 } 6357 return 0; 6358 } 6359 6360 static int cmp_func_ptrs(const void *_a, const void *_b) 6361 { 6362 const struct bpf_func_ptr *a = _a, *b = _b; 6363 6364 if (a->map != b->map) 6365 return a->map < b->map ? -1 : 1; 6366 if (a->map_off != b->map_off) 6367 return a->map_off < b->map_off ? -1 : 1; 6368 return 0; 6369 } 6370 6371 /* Find the first pointer to a function at or after 'off' in the value of 'map' */ 6372 static u32 func_ptr_lower_bound(struct bpf_verifier_env *env, const struct bpf_map *map, u64 off) 6373 { 6374 u32 l = 0, r = env->func_ptr_cnt, m; 6375 struct bpf_func_ptr *p; 6376 6377 while (l < r) { 6378 m = l + (r - l) / 2; 6379 p = &env->func_ptrs[m]; 6380 if (p->map < map || (p->map == map && p->map_off < off)) 6381 l = m + 1; 6382 else 6383 r = m; 6384 } 6385 return l; 6386 } 6387 6388 /* 6389 * Return pointers to functions that overlap with 'size' bytes at offset 'off' 6390 * of the value of 'map' and their number in 'cnt'. 6391 */ 6392 struct bpf_func_ptr *bpf_map_range_func_ptrs(struct bpf_verifier_env *env, 6393 const struct bpf_map *map, 6394 u64 off, u64 size, u32 *cnt) 6395 { 6396 u32 first, last; 6397 6398 *cnt = 0; 6399 if (!env->func_ptr_cnt || !size) 6400 return NULL; 6401 6402 /* a pointer that starts up to 7 bytes before 'off' overlaps too */ 6403 first = func_ptr_lower_bound(env, map, off >= sizeof(u64) ? off - sizeof(u64) + 1 : 0); 6404 last = func_ptr_lower_bound(env, map, off + size); 6405 if (first >= last) 6406 return NULL; 6407 6408 *cnt = last - first; 6409 return &env->func_ptrs[first]; 6410 } 6411 6412 /* Return all pointers to functions in the value of 'map' */ 6413 struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env, 6414 const struct bpf_map *map, u32 *cnt) 6415 { 6416 return bpf_map_range_func_ptrs(env, map, 0, (u64)map->value_size, cnt); 6417 } 6418 6419 /* instructions [off, off + len) replaced the instruction at 'off' */ 6420 void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len) 6421 { 6422 struct bpf_func_ptr *p; 6423 u32 i; 6424 6425 if (len <= 1) 6426 return; 6427 6428 for (i = 0; i < env->func_ptr_cnt; i++) { 6429 p = &env->func_ptrs[i]; 6430 if (p->xlated_off <= off || p->xlated_off == BPF_FUNC_PTR_DELETED) 6431 continue; 6432 p->xlated_off += len - 1; 6433 } 6434 } 6435 6436 /* 6437 * Instructions [off, off + len) are about to be removed. It's called before 6438 * the starts of subprogs are adjusted. A subprog is gone when all of its 6439 * instructions are. Otherwise, e.g. when its first instruction is a nop, 6440 * it starts where the removed instructions did. 6441 */ 6442 void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len) 6443 { 6444 struct bpf_func_ptr *p; 6445 int subprog; 6446 u32 i; 6447 6448 for (i = 0; i < env->func_ptr_cnt; i++) { 6449 p = &env->func_ptrs[i]; 6450 if (p->xlated_off < off || p->xlated_off == BPF_FUNC_PTR_DELETED) 6451 continue; 6452 if (p->xlated_off >= off + len) { 6453 p->xlated_off -= len; 6454 continue; 6455 } 6456 subprog = bpf_find_subprog(env, p->xlated_off); 6457 if (subprog > 0 && env->subprog_info[subprog + 1].start > off + len) 6458 p->xlated_off = off; 6459 else 6460 p->xlated_off = BPF_FUNC_PTR_DELETED; 6461 } 6462 } 6463 6464 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6465 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6466 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6467 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6468 6469 /* 6470 * Allow list few fields as RCU trusted or full trusted. 6471 * This logic doesn't allow mix tagging and will be removed once GCC supports 6472 * btf_type_tag. 6473 */ 6474 6475 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6476 BTF_TYPE_SAFE_RCU(struct task_struct) { 6477 const cpumask_t *cpus_ptr; 6478 struct css_set __rcu *cgroups; 6479 struct task_struct __rcu *real_parent; 6480 struct task_struct *group_leader; 6481 }; 6482 6483 BTF_TYPE_SAFE_RCU(struct cgroup) { 6484 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6485 struct kernfs_node *kn; 6486 }; 6487 6488 BTF_TYPE_SAFE_RCU(struct css_set) { 6489 struct cgroup *dfl_cgrp; 6490 }; 6491 6492 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 6493 struct cgroup *cgroup; 6494 }; 6495 6496 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6497 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6498 struct file __rcu *exe_file; 6499 #ifdef CONFIG_MEMCG 6500 struct task_struct __rcu *owner; 6501 #endif 6502 }; 6503 6504 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6505 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6506 */ 6507 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6508 struct sock *sk; 6509 }; 6510 6511 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6512 struct sock *sk; 6513 }; 6514 6515 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6516 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6517 struct seq_file *seq; 6518 }; 6519 6520 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6521 struct bpf_iter_meta *meta; 6522 struct task_struct *task; 6523 }; 6524 6525 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6526 struct file *file; 6527 }; 6528 6529 BTF_TYPE_SAFE_TRUSTED(struct file) { 6530 struct inode *f_inode; 6531 }; 6532 6533 /* 6534 * The pointer fields in the sched_ext ops argument containers are pinned by the 6535 * callers for the duration of the ops calls and are never NULL. 6536 */ 6537 BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args) { 6538 #ifdef CONFIG_EXT_GROUP_SCHED 6539 struct cgroup *cgroup; 6540 #endif 6541 }; 6542 6543 BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args) { 6544 struct task_struct *task; 6545 }; 6546 6547 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args) { 6548 struct sched_ext_ops *ops; 6549 }; 6550 6551 BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args) { 6552 struct sched_ext_ops *ops; 6553 }; 6554 6555 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 6556 struct inode *d_inode; 6557 }; 6558 6559 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm) { 6560 struct mm_struct *mm; 6561 }; 6562 6563 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6564 struct sock *sk; 6565 }; 6566 6567 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 6568 struct mm_struct *vm_mm; 6569 struct file *vm_file; 6570 }; 6571 6572 static bool type_is_rcu(struct bpf_verifier_env *env, 6573 struct bpf_reg_state *reg, 6574 const char *field_name, u32 btf_id) 6575 { 6576 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6577 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6578 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6579 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 6580 6581 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6582 } 6583 6584 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6585 struct bpf_reg_state *reg, 6586 const char *field_name, u32 btf_id) 6587 { 6588 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6589 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6590 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6591 6592 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6593 } 6594 6595 static bool type_is_trusted(struct bpf_verifier_env *env, 6596 struct bpf_reg_state *reg, 6597 const char *field_name, u32 btf_id) 6598 { 6599 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6600 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6601 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6602 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6603 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args)); 6604 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args)); 6605 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args)); 6606 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args)); 6607 6608 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6609 } 6610 6611 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6612 struct bpf_reg_state *reg, 6613 const char *field_name, u32 btf_id) 6614 { 6615 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6616 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 6617 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct linux_binprm)); 6618 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 6619 6620 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6621 "__safe_trusted_or_null"); 6622 } 6623 6624 /* 6625 * The member holds the kernel address of arena memory, which the rewritten 6626 * load turns into an arena pointer, see arena_member_fixup(). NULL needs no 6627 * tracking, PTR_TO_ARENA covers it. 6628 */ 6629 static int check_arena_member_load(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 6630 int value_regno, enum bpf_type_flag flag, const char *tname, 6631 const char *field_name) 6632 { 6633 struct bpf_insn_aux_data *aux = &env->insn_aux_data[env->insn_idx]; 6634 struct bpf_insn *insn; 6635 6636 /* a helper reading the member as bytes needs no rewrite */ 6637 if (value_regno < 0) 6638 return 0; 6639 if (!env->prog->aux->arena) { 6640 verbose(env, 6641 "arena pointer member %s of struct %s requires a program with an associated arena\n", 6642 field_name, tname); 6643 return -EINVAL; 6644 } 6645 /* only a plain load or an acquire load is rewritten */ 6646 insn = &env->prog->insnsi[env->insn_idx]; 6647 if (BPF_CLASS(insn->code) != BPF_LDX && 6648 !(insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW) && insn->imm == BPF_LOAD_ACQ)) { 6649 verbose(env, 6650 "arena pointer member %s of struct %s can only be read with a plain or an acquire load\n", 6651 field_name, tname); 6652 return -EACCES; 6653 } 6654 6655 aux->arena_member = true; 6656 if (flag & PTR_MAYBE_NULL) 6657 aux->arena_member_nullable = true; 6658 mark_reg_unknown(env, regs, value_regno); 6659 regs[value_regno].type = PTR_TO_ARENA; 6660 return 0; 6661 } 6662 6663 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6664 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 6665 argno_t argno, int off, int size, 6666 enum bpf_access_type atype, 6667 int value_regno) 6668 { 6669 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6670 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6671 const char *field_name = NULL; 6672 enum bpf_type_flag flag = 0; 6673 u32 btf_id = 0; 6674 s64 min_off; 6675 int ret; 6676 6677 if (!env->allow_ptr_leaks) { 6678 verbose(env, 6679 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6680 tname); 6681 return -EPERM; 6682 } 6683 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6684 verbose(env, 6685 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6686 tname); 6687 return -EINVAL; 6688 } 6689 6690 if (check_add_overflow(reg_smin(reg), off, &min_off)) { 6691 verbose(env, 6692 "%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\n", 6693 reg_arg_name(env, argno), tname, reg_smin(reg), off); 6694 return -EACCES; 6695 } 6696 6697 if (min_off < 0) { 6698 verbose(env, 6699 "%s is ptr_%s invalid negative access: off=%lld\n", 6700 reg_arg_name(env, argno), tname, min_off); 6701 return -EACCES; 6702 } 6703 6704 if (reg->type & MEM_USER) { 6705 verbose(env, 6706 "%s is ptr_%s access user memory\n", 6707 reg_arg_name(env, argno), tname); 6708 return -EACCES; 6709 } 6710 6711 if (reg->type & MEM_PERCPU) { 6712 verbose(env, 6713 "%s is ptr_%s access percpu memory\n", 6714 reg_arg_name(env, argno), tname); 6715 return -EACCES; 6716 } 6717 6718 if (atype != BPF_READ && bpf_may_fault_on_deref(reg->type)) { 6719 verbose(env, "only read is supported\n"); 6720 return -EACCES; 6721 } 6722 6723 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6724 if (!tnum_is_const(reg->var_off)) { 6725 char tn_buf[48]; 6726 6727 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6728 verbose(env, 6729 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6730 reg_arg_name(env, argno), tname, off, tn_buf); 6731 return -EACCES; 6732 } 6733 6734 off += reg->var_off.value; 6735 6736 if (!btf_is_kernel(reg->btf)) { 6737 verifier_bug(env, "reg->btf must be kernel btf"); 6738 return -EFAULT; 6739 } 6740 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6741 if (ret < 0) 6742 verbose(env, 6743 "%s cannot write into ptr_%s at off=%d size=%d\n", 6744 reg_arg_name(env, argno), tname, off, size); 6745 } else { 6746 /* Writes are permitted with default btf_struct_access for 6747 * program allocated objects (which always have id > 0). 6748 */ 6749 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6750 verbose(env, "only read is supported\n"); 6751 return -EACCES; 6752 } 6753 6754 /* 6755 * A fault-prone allocated object may still be read through a 6756 * BPF_PROBE_MEM load after its lifetime protection ends. Writes 6757 * through such pointers were rejected above. 6758 */ 6759 if (type_is_alloc(reg->type) && !bpf_may_fault_on_deref(reg->type) && 6760 !type_is_non_owning_ref(reg->type) && 6761 !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) { 6762 verifier_bug(env, "allocated object must have a referenced id"); 6763 return -EFAULT; 6764 } 6765 6766 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6767 } 6768 6769 if (ret < 0) 6770 return ret; 6771 6772 if (ret == PTR_TO_ARENA) 6773 return check_arena_member_load(env, regs, value_regno, flag, tname, field_name); 6774 6775 if (ret != PTR_TO_BTF_ID) { 6776 /* just mark; */ 6777 6778 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6779 /* If this is an untrusted pointer, all pointers formed by walking it 6780 * also inherit the untrusted flag. 6781 */ 6782 flag = PTR_UNTRUSTED; 6783 6784 } else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) { 6785 /* By default any pointer obtained from walking a trusted pointer is no 6786 * longer trusted, unless the field being accessed has explicitly been 6787 * marked as inheriting its parent's state of trust (either full or RCU). 6788 * For example: 6789 * 'cgroups' pointer is untrusted if task->cgroups dereference 6790 * happened in a sleepable program outside of bpf_rcu_read_lock() 6791 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6792 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6793 * 6794 * A regular RCU-protected pointer with __rcu tag can also be deemed 6795 * trusted if we are in an RCU CS. Such pointer can be NULL. 6796 */ 6797 if (type_is_trusted(env, reg, field_name, btf_id)) { 6798 flag |= PTR_TRUSTED; 6799 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6800 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6801 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6802 if (type_is_rcu(env, reg, field_name, btf_id)) { 6803 /* ignore __rcu tag and mark it MEM_RCU */ 6804 flag |= MEM_RCU; 6805 } else if (flag & MEM_RCU || 6806 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6807 /* __rcu tagged pointers can be NULL */ 6808 flag |= MEM_RCU | PTR_MAYBE_NULL; 6809 6810 /* We always trust them */ 6811 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6812 flag & PTR_UNTRUSTED) 6813 flag &= ~PTR_UNTRUSTED; 6814 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6815 /* keep as-is */ 6816 } else { 6817 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6818 clear_trusted_flags(&flag); 6819 } 6820 } else { 6821 /* 6822 * If not in RCU CS or MEM_RCU pointer can be NULL then 6823 * aggressively mark as untrusted otherwise such 6824 * pointers will be plain PTR_TO_BTF_ID without flags 6825 * and will be allowed to be passed into helpers for 6826 * compat reasons. 6827 */ 6828 flag = PTR_UNTRUSTED; 6829 } 6830 } else { 6831 /* Old compat. Deprecated */ 6832 clear_trusted_flags(&flag); 6833 } 6834 6835 /* 6836 * A __nullable member only matters where NULL would otherwise be 6837 * assumed away, which is anywhere but on a plain or an untrusted 6838 * pointer: those are probed on a dereference, which tolerates NULL, and 6839 * the BTF_TYPE_SAFE_*_OR_NULL lists never applied to them either. A 6840 * per-CPU pointer counts, per_cpu_ptr() does not check for NULL. 6841 */ 6842 if (bpf_may_fault_on_deref(PTR_TO_BTF_ID | (flag & ~PTR_MAYBE_NULL))) 6843 flag &= ~PTR_MAYBE_NULL; 6844 6845 if (atype == BPF_READ && value_regno >= 0) { 6846 u32 parent_id = reg_lifetime_id(env, reg); 6847 6848 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6849 if (ret < 0) 6850 return ret; 6851 if ((regs[value_regno].type & PTR_TRUSTED) && 6852 !(regs[value_regno].type & (MEM_RCU | MEM_PERCPU | MEM_USER))) 6853 regs[value_regno].parent_id = parent_id; 6854 } 6855 6856 return 0; 6857 } 6858 6859 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6860 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 6861 argno_t argno, int off, int size, 6862 enum bpf_access_type atype, 6863 int value_regno) 6864 { 6865 struct bpf_map *map = reg->map_ptr; 6866 struct bpf_reg_state map_reg; 6867 enum bpf_type_flag flag = 0; 6868 const struct btf_type *t; 6869 const char *tname; 6870 u32 btf_id; 6871 int ret; 6872 6873 if (!btf_vmlinux) { 6874 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6875 return -ENOTSUPP; 6876 } 6877 6878 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6879 verbose(env, "map_ptr access not supported for map type %d\n", 6880 map->map_type); 6881 return -ENOTSUPP; 6882 } 6883 6884 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6885 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6886 6887 if (!env->allow_ptr_leaks) { 6888 verbose(env, 6889 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6890 tname); 6891 return -EPERM; 6892 } 6893 6894 if (off < 0) { 6895 verbose(env, "%s is %s invalid negative access: off=%d\n", 6896 reg_arg_name(env, argno), tname, off); 6897 return -EACCES; 6898 } 6899 6900 if (atype != BPF_READ) { 6901 verbose(env, "only read from %s is supported\n", tname); 6902 return -EACCES; 6903 } 6904 6905 /* Simulate access to a PTR_TO_BTF_ID */ 6906 memset(&map_reg, 0, sizeof(map_reg)); 6907 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 6908 btf_vmlinux, *map->ops->map_btf_id, 0); 6909 if (ret < 0) 6910 return ret; 6911 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6912 if (ret < 0) 6913 return ret; 6914 6915 if (value_regno >= 0) { 6916 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6917 if (ret < 0) 6918 return ret; 6919 } 6920 6921 return 0; 6922 } 6923 6924 /* 6925 * Check that the stack access at the given offset is within bounds. The 6926 * maximum valid offset is -1. 6927 * 6928 * The minimum valid offset is -env->stack_limit for writes, and 6929 * -state->allocated_stack for reads. 6930 */ 6931 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6932 s64 off, 6933 struct bpf_func_state *state, 6934 enum bpf_access_type t) 6935 { 6936 int min_valid_off; 6937 6938 if (t == BPF_WRITE || env->allow_uninit_stack) 6939 min_valid_off = -(int)env->stack_limit; 6940 else 6941 min_valid_off = -state->allocated_stack; 6942 6943 if (off < min_valid_off || off > -1) 6944 return -EACCES; 6945 return 0; 6946 } 6947 6948 /* Check that the stack access at 'regno + off' falls within the maximum stack 6949 * bounds. 6950 * 6951 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6952 */ 6953 static int check_stack_access_within_bounds( 6954 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6955 argno_t argno, int off, int access_size, 6956 enum bpf_access_type type) 6957 { 6958 struct bpf_func_state *state = bpf_func(env, reg); 6959 s64 min_off, max_off; 6960 int err; 6961 char *err_extra; 6962 6963 if (type == BPF_READ) 6964 err_extra = " read from"; 6965 else 6966 err_extra = " write to"; 6967 6968 if (tnum_is_const(reg->var_off)) { 6969 min_off = (s64)reg->var_off.value + off; 6970 max_off = min_off + access_size; 6971 } else { 6972 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 6973 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 6974 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 6975 err_extra, reg_arg_name(env, argno)); 6976 return -EACCES; 6977 } 6978 min_off = reg_smin(reg) + off; 6979 max_off = reg_smax(reg) + off + access_size; 6980 } 6981 6982 err = check_stack_slot_within_bounds(env, min_off, state, type); 6983 if (!err && max_off > 0) 6984 err = -EINVAL; /* out of stack access into non-negative offsets */ 6985 if (!err && access_size < 0) 6986 /* access_size should not be negative (or overflow an int); others checks 6987 * along the way should have prevented such an access. 6988 */ 6989 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6990 6991 if (err) { 6992 if (tnum_is_const(reg->var_off)) { 6993 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 6994 err_extra, reg_arg_name(env, argno), min_off, access_size); 6995 } else { 6996 char tn_buf[48]; 6997 6998 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6999 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 7000 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 7001 } 7002 return err; 7003 } 7004 7005 /* 7006 * Every stack access passes through here, including buffers passed to 7007 * helpers and kfuncs and accesses into a caller's frame, so check the 7008 * fastcall contract of the frame that owns the slots once for all of 7009 * them. Zero-sized accesses touch no stack and keep the rewrite enabled. 7010 */ 7011 if (access_size) 7012 check_fastcall_stack_contract(env, state, env->insn_idx, min_off); 7013 7014 /* Note that there is no stack access with offset zero, so the needed stack 7015 * size is -min_off, not -min_off+1. 7016 */ 7017 return bpf_grow_stack_state(env, state, -min_off /* size */); 7018 } 7019 7020 static bool get_func_retval_range(struct bpf_prog *prog, 7021 struct bpf_retval_range *range) 7022 { 7023 if (prog->type == BPF_PROG_TYPE_LSM && 7024 prog->expected_attach_type == BPF_LSM_MAC && 7025 !bpf_lsm_get_retval_range(prog, range)) { 7026 return true; 7027 } 7028 return false; 7029 } 7030 7031 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 7032 { 7033 struct bpf_reg_state fake_reg; 7034 7035 if (!val) 7036 return; 7037 7038 fake_reg.type = SCALAR_VALUE; 7039 __mark_reg_known(&fake_reg, val); 7040 7041 scalar_step_add(dst_reg, dst_reg, &fake_reg); 7042 scalar32_min_max_add(dst_reg, &fake_reg); 7043 scalar_min_max_add(dst_reg, &fake_reg); 7044 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 7045 7046 reg_bounds_sync(dst_reg); 7047 } 7048 7049 /* there is no support for callx in the interpreter */ 7050 static int require_callx_jit(struct bpf_verifier_env *env) 7051 { 7052 if (!env->prog->jit_requested) { 7053 verbose(env, "JIT is required to use callx\n"); 7054 return -EOPNOTSUPP; 7055 } 7056 if (!bpf_jit_supports_callx()) { 7057 verbose(env, "JIT doesn't support callx\n"); 7058 return -EOPNOTSUPP; 7059 } 7060 env->prog->jit_required = true; 7061 return 0; 7062 } 7063 7064 static void mark_reg_func_ptr(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 7065 int regno, int subprog) 7066 { 7067 mark_reg_known_zero(env, regs, regno); 7068 regs[regno].type = PTR_TO_FUNC; 7069 regs[regno].subprogno = subprog; 7070 } 7071 7072 /* a read from a table of functions branches into that many states at most */ 7073 #define BPF_MAX_FUNC_PTR_TARGETS 64 7074 /* and that many pointers at most are next to what is read at variable offset */ 7075 #define BPF_MAX_FUNC_PTR_RANGE 4096 7076 7077 /* Count up to 'limit' offsets in [min_off, max_off] that the read is possible at */ 7078 static u32 count_read_offsets(struct tnum offs, u64 min_off, u64 max_off, u32 limit) 7079 { 7080 u64 o = min_off, next; 7081 u32 cnt = 0; 7082 7083 if (!tnum_in(offs, tnum_const(o))) { 7084 next = tnum_step(offs, o); 7085 if (next <= o) 7086 return 0; 7087 o = next; 7088 } 7089 while (o <= max_off && cnt < limit) { 7090 cnt++; 7091 next = tnum_step(offs, o); 7092 if (next <= o) 7093 break; 7094 o = next; 7095 } 7096 return cnt; 7097 } 7098 7099 /* 7100 * A read from a frozen read-only map that has pointers to functions, see 7101 * resolve_func_ptrs(). The bounds and var_off of the offset tell where the read 7102 * is possible at, e.g. var_off is the stride of the elements of an array. 7103 * A read of exactly one pointer yields PTR_TO_FUNC. When the offset is variable 7104 * and only pointers can be read, which is how an element of a table of 7105 * functions is loaded, the verification continues with each of them. Other 7106 * reads that overlap with a pointer are rejected, because their result is not 7107 * known until the program is jitted. 7108 * 7109 * Return -ENOENT if there are no pointers to functions in the bytes that are read. 7110 */ 7111 static int check_func_ptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off, 7112 int size, int value_regno) 7113 { 7114 u64 min_off = reg_umin(reg) + off, max_off = reg_umax(reg) + off; 7115 struct tnum offs = tnum_add(reg->var_off, tnum_const(off)); 7116 struct bpf_reg_state *regs = cur_regs(env); 7117 struct bpf_map *map = reg->map_ptr; 7118 struct bpf_verifier_state *branch; 7119 int subprog, targets[BPF_MAX_FUNC_PTR_TARGETS]; 7120 struct bpf_func_ptr *ptrs; 7121 u32 i, cnt, n = 0; 7122 u64 o, lo, hi; 7123 int err; 7124 7125 ptrs = bpf_map_range_func_ptrs(env, map, min_off, max_off - min_off + size, &cnt); 7126 if (!ptrs) 7127 return -ENOENT; 7128 if (cnt > BPF_MAX_FUNC_PTR_RANGE) 7129 goto overlap; 7130 7131 for (i = 0; i < cnt; i++) { 7132 /* the offsets at which the read overlaps with the pointer */ 7133 lo = ptrs[i].map_off >= size ? ptrs[i].map_off - size + 1 : 0; 7134 lo = max(lo, min_off); 7135 hi = min(ptrs[i].map_off + sizeof(u64) - 1, max_off); 7136 for (o = lo; o <= hi; o++) { 7137 if (!tnum_in(offs, tnum_const(o))) 7138 continue; 7139 if (o != ptrs[i].map_off || size != sizeof(u64) || value_regno < 0) 7140 goto overlap; 7141 if (n == BPF_MAX_FUNC_PTR_TARGETS) { 7142 verbose(env, "read from map '%s' may yield more than %d pointers to functions\n", 7143 map->name, BPF_MAX_FUNC_PTR_TARGETS); 7144 return -E2BIG; 7145 } 7146 subprog = bpf_find_subprog(env, ptrs[i].xlated_off); 7147 if (verifier_bug_if(subprog <= 0, env, 7148 "no function at insn %u for map '%s' offset %u", 7149 ptrs[i].xlated_off, map->name, ptrs[i].map_off)) 7150 return -EFAULT; 7151 targets[n++] = subprog; 7152 } 7153 } 7154 /* pointers are next to what is read, e.g. the data of an array of vtables */ 7155 if (!n) 7156 return -ENOENT; 7157 /* either every offset that the read is possible at is a pointer or none */ 7158 if (count_read_offsets(offs, min_off, max_off, n + 1) != n) 7159 goto overlap; 7160 7161 /* the map has the offset of the function until the program is jitted */ 7162 err = require_callx_jit(env); 7163 if (err) 7164 return err; 7165 7166 for (i = 0; i < n - 1; i++) { 7167 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, 7168 env->cur_state->speculative); 7169 if (IS_ERR(branch)) 7170 return PTR_ERR(branch); 7171 mark_reg_func_ptr(env, branch->frame[branch->curframe]->regs, value_regno, 7172 targets[i]); 7173 } 7174 mark_reg_func_ptr(env, regs, value_regno, targets[n - 1]); 7175 return 0; 7176 7177 overlap: 7178 verbose(env, "read of %d bytes at offset [%llu,%llu] of map '%s' overlaps with a pointer to a function\n", 7179 size, min_off, max_off, map->name); 7180 return -EACCES; 7181 } 7182 7183 static int check_map_mem_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int off, 7184 int bpf_size, int value_regno, bool is_ldsx) 7185 { 7186 struct bpf_reg_state *regs = cur_regs(env); 7187 int size = bpf_size_to_bytes(bpf_size); 7188 struct bpf_map *map = reg->map_ptr; 7189 int err; 7190 7191 switch (map->map_type) { 7192 case BPF_MAP_TYPE_INSN_ARRAY: 7193 if (bpf_size != BPF_DW) { 7194 verbose(env, "Invalid read of %d bytes from insn_array\n", size); 7195 return -EACCES; 7196 } 7197 regs[value_regno] = *reg; 7198 add_scalar_to_reg(®s[value_regno], off); 7199 regs[value_regno].type = PTR_TO_INSN; 7200 return 0; 7201 case BPF_MAP_TYPE_PERCPU_ARRAY: 7202 goto reg_unknown; 7203 default: 7204 break; 7205 } 7206 7207 if (env->func_ptr_cnt) { 7208 err = check_func_ptr_read(env, reg, off, size, value_regno); 7209 if (err != -ENOENT) 7210 return err; 7211 } 7212 7213 /* If map is read-only, track its contents as scalars. */ 7214 if (tnum_is_const(reg->var_off) && 7215 bpf_map_is_rdonly(map) && 7216 map->ops->map_direct_value_addr) { 7217 int map_off = off + reg->var_off.value; 7218 u64 val = 0; 7219 7220 err = bpf_map_direct_read(map, map_off, size, &val, is_ldsx); 7221 if (err) 7222 return err; 7223 7224 regs[value_regno].type = SCALAR_VALUE; 7225 __mark_reg_known(®s[value_regno], val); 7226 return 0; 7227 } 7228 7229 reg_unknown: 7230 mark_reg_unknown(env, regs, value_regno); 7231 return 0; 7232 } 7233 7234 /* check whether memory at (regno + off) is accessible for t = (read | write) 7235 * if t==write, value_regno is a register which value is stored into memory 7236 * if t==read, value_regno is a register which will receive the value from memory 7237 * if t==write && value_regno==-1, some unknown value is stored into memory 7238 * if t==read && value_regno==-1, don't care what we read from memory 7239 */ 7240 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 7241 int off, int bpf_size, enum bpf_access_type t, 7242 int value_regno, bool strict_alignment_once, bool is_ldsx) 7243 { 7244 struct bpf_reg_state *regs = cur_regs(env); 7245 enum bpf_reg_type ptr_type = reg->type; 7246 int size, err = 0; 7247 7248 size = bpf_size_to_bytes(bpf_size); 7249 if (size < 0) 7250 return size; 7251 7252 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 7253 if (err) 7254 return err; 7255 7256 if (reg->type == PTR_TO_MAP_KEY) { 7257 if (t == BPF_WRITE) { 7258 verbose(env, "write to change key %s not allowed\n", 7259 reg_arg_name(env, argno)); 7260 return -EACCES; 7261 } 7262 7263 err = check_mem_region_access(env, reg, argno, off, size, 7264 reg->map_ptr->key_size, false); 7265 if (err) 7266 return err; 7267 if (value_regno >= 0) 7268 mark_reg_unknown(env, regs, value_regno); 7269 } else if (reg->type == PTR_TO_MAP_VALUE) { 7270 struct btf_field *kptr_field = NULL; 7271 7272 if (t == BPF_WRITE && value_regno >= 0 && 7273 is_pointer_value(env, value_regno)) { 7274 verbose(env, "R%d leaks addr into map\n", value_regno); 7275 return -EACCES; 7276 } 7277 err = check_map_access_type(env, reg, off, size, t); 7278 if (err) 7279 return err; 7280 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 7281 if (err) 7282 return err; 7283 if (tnum_is_const(reg->var_off)) 7284 kptr_field = btf_record_find(reg->map_ptr->record, 7285 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 7286 if (kptr_field) { 7287 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 7288 } else if (t == BPF_READ && value_regno >= 0) { 7289 err = check_map_mem_read(env, reg, off, bpf_size, value_regno, is_ldsx); 7290 } 7291 } else if (base_type(reg->type) == PTR_TO_MEM) { 7292 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7293 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 7294 7295 if (type_may_be_null(reg->type)) { 7296 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 7297 reg_type_str(env, reg->type)); 7298 bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno), 7299 reg_arg_name(env, argno), reg, 7300 BPF_DIAG_DEREF_NULLABLE_PTR, 0); 7301 return -EACCES; 7302 } 7303 7304 if (t == BPF_WRITE && rdonly_mem) { 7305 verbose(env, "%s cannot write into %s\n", 7306 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7307 return -EACCES; 7308 } 7309 7310 if (t == BPF_WRITE && value_regno >= 0 && 7311 is_pointer_value(env, value_regno)) { 7312 verbose(env, "R%d leaks addr into mem\n", value_regno); 7313 return -EACCES; 7314 } 7315 7316 if (rdonly_untrusted && !env->allow_ptr_leaks) { 7317 verbose(env, "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7318 reg_type_str(env, reg->type)); 7319 bpf_diag_policy(env, insn_idx, "read from untrusted read-only memory", 7320 "the access requires CAP_PERFMON", 7321 "Load the program with CAP_PERFMON, or avoid dereferencing untrusted pointers."); 7322 return -EPERM; 7323 } 7324 7325 /* 7326 * Accesses to untrusted PTR_TO_MEM are done through probe 7327 * instructions, hence no need to check bounds in that case. 7328 */ 7329 if (!rdonly_untrusted) 7330 err = check_mem_region_access(env, reg, argno, off, size, 7331 reg->mem_size, false); 7332 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7333 mark_reg_unknown(env, regs, value_regno); 7334 } else if (reg->type == PTR_TO_CTX) { 7335 struct bpf_insn_access_aux info = { 7336 .reg_type = SCALAR_VALUE, 7337 .is_ldsx = is_ldsx, 7338 .log = &env->log, 7339 }; 7340 struct bpf_retval_range range; 7341 7342 if (t == BPF_WRITE && value_regno >= 0 && 7343 is_pointer_value(env, value_regno)) { 7344 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7345 return -EACCES; 7346 } 7347 7348 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 7349 if (!err && t == BPF_READ && value_regno >= 0) { 7350 /* ctx access returns either a scalar, or a 7351 * PTR_TO_PACKET[_META,_END]. In the latter 7352 * case, we know the offset is zero. 7353 */ 7354 if (info.reg_type == SCALAR_VALUE) { 7355 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 7356 mark_reg_unknown(env, regs, value_regno); 7357 err = __mark_reg_s32_range(env, regs, value_regno, 7358 range.minval, range.maxval); 7359 if (err) 7360 return err; 7361 } else { 7362 mark_reg_unknown(env, regs, value_regno); 7363 } 7364 } else { 7365 mark_reg_known_zero(env, regs, 7366 value_regno); 7367 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 7368 regs[value_regno].btf = info.btf; 7369 regs[value_regno].btf_id = info.btf_id; 7370 regs[value_regno].id = info.ref_id; 7371 } else if (base_type(info.reg_type) == PTR_TO_MEM) { 7372 regs[value_regno].mem_size = info.mem_size; 7373 } 7374 if (type_may_be_null(info.reg_type) && !regs[value_regno].id) 7375 regs[value_regno].id = ++env->id_gen; 7376 } 7377 regs[value_regno].type = info.reg_type; 7378 } 7379 7380 } else if (reg->type == PTR_TO_STACK) { 7381 /* Basic bounds checks. */ 7382 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 7383 if (err) 7384 return err; 7385 7386 if (t == BPF_READ) 7387 err = check_stack_read(env, reg, argno, off, size, 7388 value_regno); 7389 else 7390 err = check_stack_write(env, reg, off, size, 7391 value_regno, insn_idx); 7392 } else if (reg_is_pkt_pointer(reg)) { 7393 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7394 verbose(env, "cannot write into packet\n"); 7395 return -EACCES; 7396 } 7397 if (t == BPF_WRITE && value_regno >= 0 && 7398 is_pointer_value(env, value_regno)) { 7399 verbose(env, "R%d leaks addr into packet\n", 7400 value_regno); 7401 return -EACCES; 7402 } 7403 err = check_packet_access(env, reg, argno, off, size, false); 7404 if (!err && t == BPF_READ && value_regno >= 0) 7405 mark_reg_unknown(env, regs, value_regno); 7406 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7407 if (t == BPF_WRITE && value_regno >= 0 && 7408 is_pointer_value(env, value_regno)) { 7409 verbose(env, "R%d leaks addr into flow keys\n", 7410 value_regno); 7411 return -EACCES; 7412 } 7413 7414 err = check_flow_keys_access(env, reg, argno, off, size); 7415 if (!err && t == BPF_READ && value_regno >= 0) 7416 mark_reg_unknown(env, regs, value_regno); 7417 } else if (type_is_sk_pointer(reg->type)) { 7418 if (t == BPF_WRITE) { 7419 verbose(env, "%s cannot write into %s\n", 7420 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7421 return -EACCES; 7422 } 7423 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 7424 if (!err && value_regno >= 0) 7425 mark_reg_unknown(env, regs, value_regno); 7426 } else if (reg->type == PTR_TO_TP_BUFFER) { 7427 err = check_tp_buffer_access(env, reg, argno, off, size); 7428 if (!err && t == BPF_READ && value_regno >= 0) 7429 mark_reg_unknown(env, regs, value_regno); 7430 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7431 !type_may_be_null(reg->type)) { 7432 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 7433 value_regno); 7434 } else if (reg->type == CONST_PTR_TO_MAP) { 7435 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 7436 value_regno); 7437 } else if (base_type(reg->type) == PTR_TO_BUF && 7438 !type_may_be_null(reg->type)) { 7439 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7440 u32 *max_access; 7441 7442 if (rdonly_mem) { 7443 if (t == BPF_WRITE) { 7444 verbose(env, "%s cannot write into %s\n", 7445 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7446 return -EACCES; 7447 } 7448 max_access = &env->prog->aux->max_rdonly_access; 7449 } else { 7450 max_access = &env->prog->aux->max_rdwr_access; 7451 } 7452 7453 err = check_buffer_access(env, reg, argno, off, size, false, 7454 max_access, t == BPF_WRITE); 7455 7456 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7457 mark_reg_unknown(env, regs, value_regno); 7458 } else if (reg->type == PTR_TO_ARENA) { 7459 if (t == BPF_READ && value_regno >= 0) 7460 mark_reg_unknown(env, regs, value_regno); 7461 } else { 7462 enum bpf_diag_invalid_deref_kind kind = BPF_DIAG_DEREF_INVALID_PTR; 7463 7464 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 7465 reg_type_str(env, reg->type)); 7466 if (reg->type == SCALAR_VALUE) 7467 kind = BPF_DIAG_DEREF_SCALAR; 7468 else if (type_may_be_null(reg->type)) 7469 kind = BPF_DIAG_DEREF_NULLABLE_PTR; 7470 bpf_diag_invalid_deref(env, insn_idx, reg_from_argno(argno), 7471 reg_arg_name(env, argno), reg, kind, 0); 7472 return -EACCES; 7473 } 7474 7475 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7476 regs[value_regno].type == SCALAR_VALUE) { 7477 if (!is_ldsx) { 7478 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7479 coerce_reg_to_size(®s[value_regno], size); 7480 } else { 7481 /* 7482 * Sign-extension can change the register value relative 7483 * to a scalar it is linked with by id (e.g. a zero- 7484 * extending fill of the same spilled stack slot), thus 7485 * drop the shared id in that case. 7486 */ 7487 bool no_sext = reg_umax(®s[value_regno]) < 7488 (1ULL << (size * BITS_PER_BYTE - 1)); 7489 7490 coerce_reg_to_size_sx(®s[value_regno], size); 7491 if (!no_sext) 7492 clear_scalar_id(®s[value_regno]); 7493 } 7494 } 7495 7496 if (!err && bpf_is_mem_insn(&env->prog->insnsi[insn_idx]) && ptr_type != PTR_TO_STACK) 7497 mark_non_stack_access(env, insn_idx); 7498 7499 return err; 7500 } 7501 7502 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7503 bool allow_trust_mismatch); 7504 7505 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 7506 bool strict_alignment_once, bool is_ldsx, 7507 bool allow_trust_mismatch, const char *ctx) 7508 { 7509 struct bpf_verifier_state *vstate = env->cur_state; 7510 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7511 struct bpf_reg_state *regs = cur_regs(env); 7512 enum bpf_reg_type src_reg_type; 7513 int err; 7514 7515 /* Handle stack arg read */ 7516 if (is_stack_arg_ldx(insn)) { 7517 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7518 if (err) 7519 return err; 7520 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 7521 } 7522 7523 /* check src operand */ 7524 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7525 if (err) 7526 return err; 7527 7528 /* check dst operand */ 7529 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7530 if (err) 7531 return err; 7532 7533 src_reg_type = regs[insn->src_reg].type; 7534 7535 /* 7536 * check_stack_read_fixed_off() may refine the modification's origin to 7537 * the source stack slot. 7538 */ 7539 bpf_diag_mod_begin(env, ®s[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE); 7540 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, 7541 argno_from_reg(insn->src_reg), insn->off, 7542 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 7543 strict_alignment_once, is_ldsx); 7544 /* 7545 * Paths through a kernel struct pointer and through other pointers 7546 * may share the insn, see save_aux_ptr_type(). Record a load that did 7547 * not produce an arena pointer from an __arena member, the only load 7548 * through a kernel struct pointer that does, next to the one 7549 * check_arena_member_load() records, so that arena_member_fixup() can 7550 * tell when the paths disagree. 7551 */ 7552 if (!err && !(base_type(src_reg_type) == PTR_TO_BTF_ID && 7553 regs[insn->dst_reg].type == PTR_TO_ARENA)) 7554 env->insn_aux_data[env->insn_idx].non_arena_load = true; 7555 err = err ?: save_aux_ptr_type(env, src_reg_type, 7556 allow_trust_mismatch); 7557 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 7558 if (!err) 7559 bpf_diag_mod_end(env); 7560 7561 return err; 7562 } 7563 7564 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 7565 bool strict_alignment_once) 7566 { 7567 struct bpf_verifier_state *vstate = env->cur_state; 7568 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7569 struct bpf_reg_state *regs = cur_regs(env); 7570 enum bpf_reg_type dst_reg_type; 7571 int err; 7572 7573 /* Handle stack arg write */ 7574 if (is_stack_arg_stx(insn)) { 7575 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7576 if (err) 7577 return err; 7578 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 7579 } 7580 7581 /* check src1 operand */ 7582 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7583 if (err) 7584 return err; 7585 7586 /* check src2 operand */ 7587 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7588 if (err) 7589 return err; 7590 7591 dst_reg_type = regs[insn->dst_reg].type; 7592 7593 /* Check if (dst_reg + off) is writeable. */ 7594 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, 7595 argno_from_reg(insn->dst_reg), insn->off, 7596 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 7597 strict_alignment_once, false); 7598 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 7599 7600 return err; 7601 } 7602 7603 static int check_atomic_rmw(struct bpf_verifier_env *env, 7604 struct bpf_insn *insn) 7605 { 7606 struct bpf_reg_state *dst_reg; 7607 int load_reg; 7608 int err; 7609 7610 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7611 verbose(env, "invalid atomic operand size\n"); 7612 return -EINVAL; 7613 } 7614 7615 /* check src1 operand */ 7616 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7617 if (err) 7618 return err; 7619 7620 /* check src2 operand */ 7621 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7622 if (err) 7623 return err; 7624 7625 if (insn->imm == BPF_CMPXCHG) { 7626 /* Check comparison of R0 with memory location */ 7627 const u32 aux_reg = BPF_REG_0; 7628 7629 err = check_reg_arg(env, aux_reg, SRC_OP); 7630 if (err) 7631 return err; 7632 7633 if (is_pointer_value(env, aux_reg)) { 7634 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7635 return -EACCES; 7636 } 7637 } 7638 7639 if (is_pointer_value(env, insn->src_reg)) { 7640 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7641 return -EACCES; 7642 } 7643 7644 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7645 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7646 insn->dst_reg, 7647 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7648 return -EACCES; 7649 } 7650 7651 load_reg = bpf_atomic_load_reg(insn); 7652 if (load_reg >= 0) { 7653 /* check and record load of old value */ 7654 err = check_reg_arg(env, load_reg, DST_OP); 7655 if (err) 7656 return err; 7657 } 7658 7659 dst_reg = cur_regs(env) + insn->dst_reg; 7660 7661 /* Check whether we can read the memory, with second call for fetch 7662 * case to simulate the register fill. 7663 */ 7664 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 7665 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7666 if (!err && load_reg >= 0) { 7667 bpf_diag_mod_begin(env, cur_regs(env) + load_reg, NULL, BPF_DIAG_MOD_WRITE); 7668 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 7669 insn->off, BPF_SIZE(insn->code), 7670 BPF_READ, load_reg, true, false); 7671 if (!err) 7672 bpf_diag_mod_end(env); 7673 } 7674 if (err) 7675 return err; 7676 7677 err = save_aux_ptr_type(env, dst_reg->type, false); 7678 if (err) 7679 return err; 7680 /* Check whether we can write into the same memory. */ 7681 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 7682 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7683 if (err) 7684 return err; 7685 return 0; 7686 } 7687 7688 static int check_atomic_load(struct bpf_verifier_env *env, 7689 struct bpf_insn *insn) 7690 { 7691 int err; 7692 7693 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7694 if (err) 7695 return err; 7696 7697 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 7698 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 7699 insn->src_reg, 7700 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 7701 return -EACCES; 7702 } 7703 7704 return check_load_mem(env, insn, true, false, false, "atomic_load"); 7705 } 7706 7707 static int check_atomic_store(struct bpf_verifier_env *env, 7708 struct bpf_insn *insn) 7709 { 7710 int err; 7711 7712 err = check_store_reg(env, insn, true); 7713 if (err) 7714 return err; 7715 7716 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7717 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7718 insn->dst_reg, 7719 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7720 return -EACCES; 7721 } 7722 7723 return 0; 7724 } 7725 7726 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 7727 { 7728 switch (insn->imm) { 7729 case BPF_ADD: 7730 case BPF_ADD | BPF_FETCH: 7731 case BPF_AND: 7732 case BPF_AND | BPF_FETCH: 7733 case BPF_OR: 7734 case BPF_OR | BPF_FETCH: 7735 case BPF_XOR: 7736 case BPF_XOR | BPF_FETCH: 7737 case BPF_XCHG: 7738 case BPF_CMPXCHG: 7739 return check_atomic_rmw(env, insn); 7740 case BPF_LOAD_ACQ: 7741 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 7742 verbose(env, 7743 "64-bit load-acquires are only supported on 64-bit arches\n"); 7744 return -EOPNOTSUPP; 7745 } 7746 return check_atomic_load(env, insn); 7747 case BPF_STORE_REL: 7748 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 7749 verbose(env, 7750 "64-bit store-releases are only supported on 64-bit arches\n"); 7751 return -EOPNOTSUPP; 7752 } 7753 return check_atomic_store(env, insn); 7754 default: 7755 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 7756 insn->imm); 7757 return -EINVAL; 7758 } 7759 } 7760 7761 /* When register 'regno' is used to read the stack (either directly or through 7762 * a helper function) make sure that it's within stack boundary and, depending 7763 * on the access type and privileges, that all elements of the stack are 7764 * initialized. 7765 * 7766 * All registers that have been spilled on the stack in the slots within the 7767 * read offsets are marked as read. 7768 */ 7769 static int check_stack_range_initialized( 7770 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 7771 int access_size, bool zero_size_allowed, 7772 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 7773 { 7774 struct bpf_func_state *state = bpf_func(env, reg); 7775 int err, min_off, max_off, i, j, slot, spi; 7776 /* Some accesses can write anything into the stack, others are 7777 * read-only. 7778 */ 7779 bool clobber = type == BPF_WRITE; 7780 /* 7781 * Negative access_size signals global subprog arg check where 7782 * STACK_POISON slots are acceptable. static stack liveness 7783 * might have determined that subprog doesn't read them, 7784 * but BTF based global subprog validation isn't accurate enough. 7785 */ 7786 bool allow_poison = access_size < 0 || clobber; 7787 u32 arg_slot = arg_slot_from_argno(argno); 7788 bool uninit = clobber && meta && arg_slot < MAX_BPF_FUNC_ARGS && 7789 (meta->arg_raw_mem.mask & BIT(arg_slot)); 7790 bool raw_mode = uninit && env->allow_uninit_stack && 7791 !(meta->arg_raw_mem.var_size_mask & BIT(arg_slot)); 7792 7793 access_size = abs(access_size); 7794 7795 if (access_size == 0 && !zero_size_allowed) { 7796 verbose(env, "invalid zero-sized read\n"); 7797 return -EACCES; 7798 } 7799 7800 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 7801 if (err) 7802 return err; 7803 7804 if (tnum_is_const(reg->var_off)) { 7805 min_off = max_off = reg->var_off.value + off; 7806 } else { 7807 /* Variable offset is prohibited for unprivileged mode for 7808 * simplicity since it requires corresponding support in 7809 * Spectre masking for stack ALU. 7810 * See also retrieve_ptr_limit(). 7811 */ 7812 if (!env->bypass_spec_v1) { 7813 char tn_buf[48]; 7814 7815 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7816 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 7817 reg_arg_name(env, argno), tn_buf); 7818 return -EACCES; 7819 } 7820 /* 7821 * The call may touch any byte in the possible range, but does not 7822 * definitely initialize all of it. Fall back to ordinary stack checks. 7823 */ 7824 raw_mode = false; 7825 7826 min_off = reg_smin(reg) + off; 7827 max_off = reg_smax(reg) + off; 7828 } 7829 7830 /* Unprivileged outputs retain each byte's initialization state. */ 7831 if (raw_mode) { 7832 meta->arg_raw_mem.size[arg_slot] = access_size; 7833 return 0; 7834 } 7835 7836 for (i = min_off; i < max_off + access_size; i++) { 7837 struct bpf_stack_state *ss; 7838 u8 *stype; 7839 7840 slot = -i - 1; 7841 spi = slot / BPF_REG_SIZE; 7842 if (state->allocated_stack <= slot) { 7843 verbose(env, "allocated_stack too small\n"); 7844 return -EFAULT; 7845 } 7846 7847 ss = bpf_stack_slot(state, spi); 7848 stype = &ss->slot_type[slot % BPF_REG_SIZE]; 7849 if (*stype == STACK_MISC) 7850 goto mark; 7851 if ((*stype == STACK_ZERO) || 7852 (*stype == STACK_INVALID && (uninit || env->allow_uninit_stack))) { 7853 if (clobber && (*stype != STACK_INVALID || env->allow_uninit_stack)) { 7854 /* helper can write anything into the stack */ 7855 *stype = STACK_MISC; 7856 } 7857 goto mark; 7858 } 7859 7860 /* 7861 * Only the bytes marked STACK_SPILL hold the spilled register. 7862 * The rest of a narrowly spilled slot keeps its previous type 7863 * and must be initialized on its own. 7864 */ 7865 if (*stype == STACK_SPILL && 7866 (ss->spilled_ptr.type == SCALAR_VALUE || 7867 env->allow_ptr_leaks)) { 7868 if (clobber) { 7869 __mark_reg_unknown(env, &ss->spilled_ptr); 7870 for (j = 0; j < BPF_REG_SIZE; j++) 7871 scrub_spilled_slot(&ss->slot_type[j]); 7872 } 7873 goto mark; 7874 } 7875 7876 if (*stype == STACK_POISON) { 7877 if (allow_poison) { 7878 if (uninit && env->allow_uninit_stack) 7879 *stype = STACK_MISC; 7880 goto mark; 7881 } 7882 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 7883 reg_arg_name(env, argno), min_off, i - min_off, access_size); 7884 } else if (tnum_is_const(reg->var_off)) { 7885 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 7886 reg_arg_name(env, argno), min_off, i - min_off, access_size); 7887 } else { 7888 char tn_buf[48]; 7889 7890 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7891 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 7892 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 7893 } 7894 return -EACCES; 7895 mark: 7896 ; 7897 } 7898 return 0; 7899 } 7900 7901 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7902 argno_t argno, int access_size, 7903 enum bpf_access_type access_type, bool zero_size_allowed, 7904 struct bpf_call_arg_meta *meta, bool *known_memory) 7905 { 7906 struct bpf_reg_state *regs = cur_regs(env); 7907 u32 *max_access; 7908 7909 if (known_memory) 7910 *known_memory = true; 7911 7912 switch (base_type(reg->type)) { 7913 case PTR_TO_PACKET: 7914 case PTR_TO_PACKET_META: 7915 if (!may_access_direct_pkt_data(env, meta, access_type)) { 7916 verbose(env, "function access to the packet is not allowed\n"); 7917 return -EACCES; 7918 } 7919 return check_packet_access(env, reg, argno, 0, access_size, 7920 zero_size_allowed); 7921 case PTR_TO_MAP_KEY: 7922 if (access_type == BPF_WRITE) { 7923 verbose(env, "%s cannot write into %s\n", 7924 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7925 return -EACCES; 7926 } 7927 return check_mem_region_access(env, reg, argno, 0, access_size, 7928 reg->map_ptr->key_size, false); 7929 case PTR_TO_MAP_VALUE: 7930 if (check_map_access_type(env, reg, 0, access_size, access_type)) 7931 return -EACCES; 7932 return check_map_access(env, reg, argno, 0, access_size, 7933 zero_size_allowed, ACCESS_HELPER); 7934 case PTR_TO_MEM: 7935 if (type_is_rdonly_mem(reg->type)) { 7936 if (access_type == BPF_WRITE) { 7937 verbose(env, "%s cannot write into %s\n", 7938 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7939 return -EACCES; 7940 } 7941 } 7942 return check_mem_region_access(env, reg, argno, 0, 7943 access_size, reg->mem_size, 7944 zero_size_allowed); 7945 case PTR_TO_BUF: 7946 if (type_is_rdonly_mem(reg->type)) { 7947 if (access_type == BPF_WRITE) { 7948 verbose(env, "%s cannot write into %s\n", 7949 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7950 return -EACCES; 7951 } 7952 7953 max_access = &env->prog->aux->max_rdonly_access; 7954 } else { 7955 max_access = &env->prog->aux->max_rdwr_access; 7956 } 7957 return check_buffer_access(env, reg, argno, 0, 7958 access_size, zero_size_allowed, 7959 max_access, access_type == BPF_WRITE); 7960 case PTR_TO_STACK: 7961 return check_stack_range_initialized( 7962 env, reg, 7963 argno, 0, access_size, 7964 zero_size_allowed, access_type, meta); 7965 case PTR_TO_BTF_ID: 7966 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 7967 access_size, access_type, -1); 7968 case PTR_TO_CTX: 7969 /* Only permit reading or writing syscall context using helper calls. */ 7970 if (is_var_ctx_off_allowed(env->prog)) { 7971 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 7972 zero_size_allowed); 7973 if (err) 7974 return err; 7975 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 7976 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 7977 return 0; 7978 } 7979 fallthrough; 7980 default: /* scalar_value or invalid ptr */ 7981 /* Allow zero-byte read from NULL, regardless of pointer type */ 7982 if (zero_size_allowed && access_size == 0 && 7983 bpf_register_is_null(reg)) 7984 return 0; 7985 if (known_memory && base_type(reg->type) != PTR_TO_CTX) 7986 *known_memory = false; 7987 7988 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 7989 reg_type_str(env, reg->type)); 7990 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7991 return -EACCES; 7992 } 7993 } 7994 7995 enum bpf_mem_size_failure { 7996 BPF_MEM_SIZE_FAIL_NONE, 7997 BPF_MEM_SIZE_FAIL_MEMORY, 7998 BPF_MEM_SIZE_FAIL_SIZE, 7999 }; 8000 8001 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 8002 * size. 8003 * 8004 * @mem_reg contains the pointer, @size_reg contains the access size. 8005 */ 8006 static int check_mem_size_reg(struct bpf_verifier_env *env, 8007 struct bpf_reg_state *mem_reg, 8008 struct bpf_reg_state *size_reg, argno_t mem_argno, 8009 argno_t size_argno, u32 access_type, 8010 bool zero_size_allowed, 8011 struct bpf_call_arg_meta *meta, 8012 enum bpf_mem_size_failure *failure) 8013 { 8014 int err = 0; 8015 8016 if (failure) 8017 *failure = BPF_MEM_SIZE_FAIL_NONE; 8018 8019 /* This is used to refine r0 return value bounds for helpers 8020 * that enforce this value as an upper bound on return values. 8021 * See do_refine_retval_range() for helpers that can refine 8022 * the return value. C type of helper is u32 so we pull register 8023 * bound from umax_value however, if negative verifier errors 8024 * out. Only upper bounds can be learned because retval is an 8025 * int type and negative retvals are allowed. 8026 */ 8027 meta->msize_max_value = reg_umax(size_reg); 8028 8029 /* 8030 * Check variable ranges byte by byte instead of using raw mode. Keep the 8031 * MEM_UNINIT annotation so invalid bytes are accepted without marking them 8032 * initialized when the caller cannot read uninitialized stack memory. 8033 */ 8034 if (!tnum_is_const(size_reg->var_off)) 8035 meta->arg_raw_mem.var_size_mask |= BIT(arg_slot_from_argno(mem_argno)); 8036 8037 if (reg_smin(size_reg) < 0) { 8038 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 8039 reg_arg_name(env, size_argno)); 8040 err = -EACCES; 8041 goto size_error; 8042 } 8043 8044 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 8045 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 8046 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 8047 err = -EACCES; 8048 goto size_error; 8049 } 8050 8051 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 8052 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 8053 reg_arg_name(env, size_argno)); 8054 err = -EACCES; 8055 goto size_error; 8056 } 8057 8058 if (access_type & BPF_READ) 8059 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 8060 BPF_READ, zero_size_allowed, meta, NULL); 8061 if (!err && access_type & BPF_WRITE) 8062 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 8063 BPF_WRITE, zero_size_allowed, meta, NULL); 8064 if (err && failure) 8065 *failure = BPF_MEM_SIZE_FAIL_MEMORY; 8066 8067 if (!err) 8068 err = mark_arg_precision(env, size_argno); 8069 8070 return err; 8071 8072 size_error: 8073 if (failure) 8074 *failure = BPF_MEM_SIZE_FAIL_SIZE; 8075 return err; 8076 } 8077 8078 static bool is_subprog(const struct bpf_call_arg_meta *meta) 8079 { 8080 return meta->btf && !meta->func_id; 8081 } 8082 8083 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8084 argno_t argno, u32 mem_size, enum bpf_access_type access_type, 8085 struct bpf_call_arg_meta *meta, bool *known_memory) 8086 { 8087 int size, err = 0; 8088 8089 if (bpf_register_is_null(reg)) 8090 return mark_arg_precision(env, argno); 8091 if (known_memory) 8092 *known_memory = true; 8093 8094 if (mem_size > S32_MAX) { 8095 verbose(env, "%s memory size %u is too large\n", 8096 reg_arg_name(env, argno), mem_size); 8097 return -EACCES; 8098 } 8099 8100 /* 8101 * Only a global subprog may read poisoned stack slots: 8102 * its static stack liveness proved the callee body skips them. 8103 */ 8104 size = (is_subprog(meta) && 8105 base_type(reg->type) == PTR_TO_STACK) ? -(int)mem_size : mem_size; 8106 8107 if (access_type & BPF_READ) 8108 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta, 8109 known_memory); 8110 if (!err && (access_type & BPF_WRITE)) 8111 err = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta, 8112 known_memory); 8113 8114 return err; 8115 } 8116 8117 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8118 argno_t argno, struct ret_mem_desc *ret_mem) 8119 { 8120 int regno = reg_from_argno(argno); 8121 int err; 8122 8123 if (ret_mem->found) { 8124 verifier_bug(env, "only one allocation size argument permitted"); 8125 return -EFAULT; 8126 } 8127 8128 if (!tnum_is_const(reg->var_off)) { 8129 verbose(env, "%s is not a const\n", reg_arg_name(env, argno)); 8130 return -EINVAL; 8131 } 8132 8133 if (reg->var_off.value > U32_MAX) { 8134 verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno)); 8135 return -EINVAL; 8136 } 8137 8138 if (regno >= 0) 8139 err = mark_chain_precision(env, regno); 8140 else 8141 err = mark_stack_arg_precision(env, arg_idx_from_argno(argno)); 8142 if (err) 8143 return err; 8144 8145 ret_mem->size = reg->var_off.value; 8146 ret_mem->found = true; 8147 8148 return 0; 8149 } 8150 8151 static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8152 argno_t argno, struct bpf_call_arg_meta *meta) 8153 { 8154 int regno = reg_from_argno(argno); 8155 int err; 8156 8157 if (meta->arg_constant.found) { 8158 verifier_bug(env, "only one constant argument permitted"); 8159 return -EFAULT; 8160 } 8161 8162 if (!tnum_is_const(reg->var_off)) { 8163 verbose(env, "%s must be a known constant\n", reg_arg_name(env, argno)); 8164 return -EINVAL; 8165 } 8166 8167 if (regno >= 0) 8168 err = mark_chain_precision(env, regno); 8169 else 8170 err = mark_stack_arg_precision(env, arg_idx_from_argno(argno)); 8171 if (err < 0) 8172 return err; 8173 8174 meta->arg_constant.found = true; 8175 meta->arg_constant.value = reg->var_off.value; 8176 8177 return 0; 8178 } 8179 8180 enum { 8181 PROCESS_SPIN_LOCK = (1 << 0), 8182 PROCESS_RES_LOCK = (1 << 1), 8183 PROCESS_LOCK_IRQ = (1 << 2), 8184 }; 8185 8186 /* Implementation details: 8187 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 8188 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 8189 * Two bpf_map_lookups (even with the same key) will have different reg->id. 8190 * Two separate bpf_obj_new will also have different reg->id. 8191 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 8192 * clears reg->id after value_or_null->value transition, since the verifier only 8193 * cares about the range of access to valid map value pointer and doesn't care 8194 * about actual address of the map element. 8195 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 8196 * reg->id > 0 after value_or_null->value transition. By doing so 8197 * two bpf_map_lookups will be considered two different pointers that 8198 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 8199 * returned from bpf_obj_new. 8200 * The verifier allows taking only one bpf_spin_lock at a time to avoid 8201 * dead-locks. 8202 * Since only one bpf_spin_lock is allowed the checks are simpler than 8203 * reg_is_refcounted() logic. The verifier needs to remember only 8204 * one spin_lock instead of array of acquired_refs. 8205 * env->cur_state->active_locks remembers which map value element or allocated 8206 * object got locked and clears it after bpf_spin_unlock. 8207 */ 8208 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 8209 { 8210 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 8211 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 8212 struct bpf_verifier_state *cur = env->cur_state; 8213 struct bpf_reference_state *lock; 8214 bool is_const = tnum_is_const(reg->var_off); 8215 bool is_irq = flags & PROCESS_LOCK_IRQ; 8216 u64 val = reg->var_off.value; 8217 struct bpf_map *map = NULL; 8218 struct btf *btf = NULL; 8219 struct btf_record *rec; 8220 u32 spin_lock_off; 8221 int err; 8222 8223 if (!is_const) { 8224 verbose(env, 8225 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 8226 reg_arg_name(env, argno), lock_str); 8227 return -EINVAL; 8228 } 8229 if (reg->type == PTR_TO_MAP_VALUE) { 8230 map = reg->map_ptr; 8231 if (!map->btf) { 8232 verbose(env, 8233 "map '%s' has to have BTF in order to use %s_lock\n", 8234 map->name, lock_str); 8235 return -EINVAL; 8236 } 8237 } else { 8238 btf = reg->btf; 8239 } 8240 8241 rec = reg_btf_record(reg); 8242 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 8243 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 8244 map ? map->name : "kptr", lock_str); 8245 return -EINVAL; 8246 } 8247 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 8248 if (spin_lock_off != val) { 8249 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 8250 val, lock_str, spin_lock_off); 8251 return -EINVAL; 8252 } 8253 if (is_lock) { 8254 void *ptr; 8255 int type; 8256 8257 if (map) 8258 ptr = map; 8259 else 8260 ptr = btf; 8261 8262 if (!is_res_lock && cur->active_locks) { 8263 lock = find_lock_state(cur, REF_TYPE_LOCK, 0, NULL); 8264 if (lock) { 8265 verbose(env, 8266 "Locking two bpf_spin_locks are not allowed\n"); 8267 bpf_diag_lock( 8268 env, env->insn_idx, "nested spin lock", 8269 "This path already holds a bpf_spin_lock. The verifier allows only one regular BPF spin lock at a time.", 8270 "Unlock the current bpf_spin_lock before taking another one.", lock); 8271 return -EINVAL; 8272 } 8273 } else if (is_res_lock && cur->active_locks) { 8274 lock = find_lock_state(cur, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, 8275 reg->id, ptr); 8276 if (lock) { 8277 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 8278 bpf_diag_lock( 8279 env, env->insn_idx, "recursive resource spin lock", 8280 "This path already holds the same resource spin lock. Taking it again would deadlock.", 8281 "Avoid reacquiring the same resource spin lock before it is unlocked.", lock); 8282 return -EINVAL; 8283 } 8284 } 8285 8286 if (is_res_lock && is_irq) 8287 type = REF_TYPE_RES_LOCK_IRQ; 8288 else if (is_res_lock) 8289 type = REF_TYPE_RES_LOCK; 8290 else 8291 type = REF_TYPE_LOCK; 8292 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 8293 if (err < 0) { 8294 verbose(env, "Failed to acquire lock state\n"); 8295 return err; 8296 } 8297 } else { 8298 void *ptr; 8299 int type; 8300 8301 if (map) 8302 ptr = map; 8303 else 8304 ptr = btf; 8305 8306 if (!cur->active_locks) { 8307 verbose(env, "%s_unlock without taking a lock\n", lock_str); 8308 bpf_diag_res( 8309 env, env->insn_idx, "unlock without lock", 8310 "This unlock operation has no matching active lock on the current path.", 8311 "Take the matching lock before this unlock, or remove the unmatched unlock path."); 8312 return -EINVAL; 8313 } 8314 8315 if (is_res_lock && is_irq) 8316 type = REF_TYPE_RES_LOCK_IRQ; 8317 else if (is_res_lock) 8318 type = REF_TYPE_RES_LOCK; 8319 else 8320 type = REF_TYPE_LOCK; 8321 8322 lock = find_lock_state(cur, type, reg->id, ptr); 8323 if (!lock) { 8324 verbose(env, "%s_unlock of different lock\n", lock_str); 8325 lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id, 8326 cur->active_lock_ptr); 8327 bpf_diag_lock( 8328 env, env->insn_idx, "unlock of a different lock", 8329 "This unlock does not match any active lock with the same tracked identity on the current path.", 8330 "Unlock the same lock object that was most recently acquired.", lock); 8331 return -EINVAL; 8332 } 8333 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 8334 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 8335 lock = find_lock_state(cur, REF_TYPE_LOCK_MASK, cur->active_lock_id, 8336 cur->active_lock_ptr); 8337 bpf_diag_lock( 8338 env, env->insn_idx, "unlock out of order", 8339 "Locks must be released in last-in, first-out order, but this unlock does not match the currently active lock.", 8340 "Release nested locks in the reverse order they were acquired.", lock); 8341 return -EINVAL; 8342 } 8343 if (release_lock_state(env, type, reg->id, ptr)) { 8344 verbose(env, "%s_unlock of different lock\n", lock_str); 8345 bpf_diag_lock( 8346 env, env->insn_idx, "unlock of a different lock", 8347 "The verifier could not release a lock state matching this unlock operation.", 8348 "Pass the same lock object and lock kind that were used for the matching lock operation.", 8349 lock); 8350 return -EINVAL; 8351 } 8352 /* 8353 * Invalidate non-owning refs before RCU demotion clears their 8354 * NON_OWN_REF flag. 8355 */ 8356 invalidate_non_owning_refs(env); 8357 8358 if (!in_rcu_cs(env)) 8359 invalidate_rcu_protected_refs(env); 8360 } 8361 return 0; 8362 } 8363 8364 /* Check if @regno is a pointer to a specific field in a map value */ 8365 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 8366 enum btf_field_type field_type, 8367 struct bpf_map_desc *map_desc) 8368 { 8369 bool is_const = tnum_is_const(reg->var_off); 8370 struct bpf_map *map = reg->map_ptr; 8371 u64 val = reg->var_off.value; 8372 const char *struct_name = btf_field_type_name(field_type); 8373 int field_off = -1; 8374 8375 if (!is_const) { 8376 verbose(env, 8377 "%s doesn't have constant offset. %s has to be at the constant offset\n", 8378 reg_arg_name(env, argno), struct_name); 8379 return -EINVAL; 8380 } 8381 if (!map->btf) { 8382 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 8383 struct_name); 8384 return -EINVAL; 8385 } 8386 if (!btf_record_has_field(map->record, field_type)) { 8387 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 8388 return -EINVAL; 8389 } 8390 switch (field_type) { 8391 case BPF_TIMER: 8392 field_off = map->record->timer_off; 8393 break; 8394 case BPF_TASK_WORK: 8395 field_off = map->record->task_work_off; 8396 break; 8397 case BPF_RCU_HEAD: 8398 field_off = map->record->rcu_head_off; 8399 break; 8400 case BPF_WORKQUEUE: 8401 field_off = map->record->wq_off; 8402 break; 8403 default: 8404 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 8405 return -EINVAL; 8406 } 8407 if (field_off != val) { 8408 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 8409 val, struct_name, field_off); 8410 return -EINVAL; 8411 } 8412 if (map_desc->ptr) { 8413 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 8414 return -EFAULT; 8415 } 8416 map_desc->uid = reg->map_uid; 8417 map_desc->ptr = map; 8418 return 0; 8419 } 8420 8421 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 8422 struct bpf_map_desc *map) 8423 { 8424 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 8425 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 8426 return -EOPNOTSUPP; 8427 } 8428 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 8429 } 8430 8431 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 8432 struct bpf_call_arg_meta *meta) 8433 { 8434 struct bpf_reg_state *reg = reg_state(env, regno); 8435 struct btf_field *kptr_field; 8436 struct bpf_map *map_ptr; 8437 struct btf_record *rec; 8438 u32 kptr_off; 8439 8440 if (type_is_ptr_alloc_obj(reg->type)) { 8441 rec = reg_btf_record(reg); 8442 } else { /* PTR_TO_MAP_VALUE */ 8443 map_ptr = reg->map_ptr; 8444 if (!map_ptr->btf) { 8445 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 8446 map_ptr->name); 8447 return -EINVAL; 8448 } 8449 rec = map_ptr->record; 8450 meta->map.ptr = map_ptr; 8451 } 8452 8453 if (!tnum_is_const(reg->var_off)) { 8454 verbose(env, 8455 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 8456 regno); 8457 return -EINVAL; 8458 } 8459 8460 if (!btf_record_has_field(rec, BPF_KPTR)) { 8461 verbose(env, "R%d has no valid kptr\n", regno); 8462 return -EINVAL; 8463 } 8464 8465 kptr_off = reg->var_off.value; 8466 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 8467 if (!kptr_field) { 8468 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 8469 return -EACCES; 8470 } 8471 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 8472 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 8473 return -EACCES; 8474 } 8475 meta->kptr_field = kptr_field; 8476 return 0; 8477 } 8478 8479 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno, 8480 const char *call_name, const char *reason, const char *suggestion); 8481 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx, 8482 argno_t argno, const char *call_name, 8483 const char *suggestion, const char *fmt, ...); 8484 8485 /* 8486 * Validate dynptr arguments for helper, kfunc and subprog. 8487 * 8488 * @meta carries the dynptr and referenced-object state. The dynptr is populated 8489 * when the argument is tagged with MEM_UNINIT (i.e., the dynptr argument that 8490 * will be constructed) and consumed when the argument is expected to be an 8491 * initialized dynptr. The reference tracks the parent object (e.g., file or skb 8492 * in qdisc program) when constructing a dynptr. 8493 * 8494 * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 8495 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 8496 * 8497 * In both cases we deal with the first 8 bytes, but need to mark the next 8 8498 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 8499 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 8500 * 8501 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 8502 * dynptr points to. At the first level, the verifier will make sure a 8503 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 8504 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 8505 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 8506 * and checked dynamically during runtime. 8507 */ 8508 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8509 argno_t argno, int insn_idx, enum bpf_arg_type arg_type, 8510 struct bpf_call_arg_meta *meta) 8511 { 8512 int spi, err = 0; 8513 8514 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 8515 * constructing a mutable bpf_dynptr object. 8516 * 8517 * Currently, this is only possible with PTR_TO_STACK 8518 * pointing to a region of at least 16 bytes which doesn't 8519 * contain an existing bpf_dynptr. 8520 * 8521 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 8522 * destroyed. 8523 * 8524 * None - Points to a initialized dynptr that cannot be 8525 * reinitialized or destroyed. However, the view of the 8526 * dynptr and the memory it points to may be mutated. 8527 */ 8528 if (arg_type & MEM_UNINIT) { 8529 int i; 8530 8531 if (!is_dynptr_reg_valid_uninit(env, reg)) { 8532 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 8533 bpf_diag_res( 8534 env, insn_idx, "dynptr is already initialized", 8535 "This function constructs a dynptr and requires an uninitialized dynptr stack slot, but the selected slot already holds dynptr state.", 8536 "Use a fresh stack dynptr slot, or release/destroy the existing dynptr before reusing the slot."); 8537 return -EINVAL; 8538 } 8539 8540 /* we write BPF_DW bits (8 bytes) at a time */ 8541 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8542 err = check_mem_access(env, insn_idx, reg, argno, 8543 i, BPF_DW, BPF_WRITE, -1, false, false); 8544 if (err) 8545 return err; 8546 } 8547 8548 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, 8549 &meta->ref_obj, &meta->dynptr); 8550 } else /* OBJ_RELEASE and None case from above */ { 8551 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 8552 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 8553 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 8554 bpf_diag_res( 8555 env, insn_idx, "const dynptr release", 8556 "This release operation was given a const dynptr. Const dynptr values are verifier-provided views and cannot be released by the program.", 8557 "Release only mutable dynptrs that the program initialized or reserved."); 8558 return -EINVAL; 8559 } 8560 8561 if (!is_dynptr_reg_valid_init(env, reg)) { 8562 verbose(env, "Expected an initialized dynptr as %s\n", 8563 reg_arg_name(env, argno)); 8564 bpf_diag_res( 8565 env, insn_idx, "uninitialized dynptr use", 8566 "This operation requires an initialized dynptr, but the stack slot does not currently hold a valid dynptr on this path.", 8567 "Initialize the dynptr on every path before this call, and avoid overwriting or releasing it before this use."); 8568 return -EINVAL; 8569 } 8570 8571 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 8572 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 8573 enum bpf_dynptr_type expected_type = arg_to_dynptr_type(arg_type); 8574 enum bpf_dynptr_type actual_type = dynptr_reg_type(env, reg); 8575 8576 verbose(env, "Expected a dynptr of type %s as %s\n", 8577 dynptr_type_str(expected_type), reg_arg_name(env, argno)); 8578 bpf_diag_call_arg_fmt( 8579 env, insn_idx, argno, meta->func_name, 8580 "Use a dynptr constructor that matches this operation, or call an operation that accepts the dynptr's current type.", 8581 "the dynptr is initialized with backing object type %s, but this operation expects dynptr type %s", 8582 dynptr_type_str(actual_type), dynptr_type_str(expected_type)); 8583 return -EINVAL; 8584 } 8585 8586 if (reg->type != CONST_PTR_TO_DYNPTR) { 8587 struct bpf_func_state *state = bpf_func(env, reg); 8588 8589 spi = dynptr_get_spi(env, reg); 8590 if (spi < 0) 8591 return spi; 8592 8593 mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); 8594 8595 reg = &bpf_stack_slot(state, spi)->spilled_ptr; 8596 } 8597 8598 meta->dynptr.type = reg->dynptr.type; 8599 meta->dynptr.id = reg->id; 8600 meta->dynptr.parent_id = reg->parent_id; 8601 } 8602 return err; 8603 } 8604 8605 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta) 8606 { 8607 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 8608 } 8609 8610 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta) 8611 { 8612 return meta->kfunc_flags & KF_ITER_NEW; 8613 } 8614 8615 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta) 8616 { 8617 return meta->kfunc_flags & KF_ITER_DESTROY; 8618 } 8619 8620 static bool iter_next_borrows_struct(struct bpf_call_arg_meta *meta) 8621 { 8622 const struct btf_type *t; 8623 8624 if (!(meta->kfunc_flags & KF_ITER_NEXT) || 8625 (meta->kfunc_flags & (KF_ITER_RET_INDEPENDENT | KF_ACQUIRE))) 8626 return false; 8627 8628 t = btf_type_skip_modifiers(meta->btf, meta->func_proto->type, NULL); 8629 if (!t || !btf_type_is_ptr(t)) 8630 return false; 8631 t = btf_type_skip_modifiers(meta->btf, t->type, NULL); 8632 return t && __btf_type_is_struct(t); 8633 } 8634 8635 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx, 8636 const struct btf_param *arg) 8637 { 8638 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 8639 * kfunc is iter state pointer 8640 */ 8641 if (is_iter_kfunc(meta)) 8642 return arg_idx == 0; 8643 8644 /* iter passed as an argument to a generic kfunc */ 8645 return btf_param_match_suffix(meta->btf, arg, "__iter"); 8646 } 8647 8648 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8649 u32 arg, argno_t argno, int insn_idx, 8650 struct bpf_call_arg_meta *meta) 8651 { 8652 struct bpf_func_state *state = bpf_func(env, reg); 8653 const struct btf_type *t; 8654 int spi, err, i, nr_slots, btf_id; 8655 8656 if (reg->type != PTR_TO_STACK) { 8657 verbose(env, "%s expected pointer to an iterator on stack\n", 8658 reg_arg_name(env, argno)); 8659 bpf_diag_call_arg_fmt( 8660 env, insn_idx, argno, meta->func_name, 8661 "Pass the address of a stack iterator object for iterator new, next, and destroy calls.", 8662 "iterator state must live in verifier-tracked stack memory, but %s is %s", 8663 reg_arg_name(env, argno), bpf_diag_reg_type_plain(env, reg->type)); 8664 return -EINVAL; 8665 } 8666 8667 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8668 * ensures struct convention, so we wouldn't need to do any BTF 8669 * validation here. But given iter state can be passed as a parameter 8670 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8671 * conservative here. 8672 */ 8673 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg); 8674 if (btf_id < 0) { 8675 verbose(env, "expected valid iter pointer as %s\n", 8676 reg_arg_name(env, argno)); 8677 bpf_diag_call_arg( 8678 env, insn_idx, argno, meta->func_name, 8679 "the function expects a recognized iterator state pointer, but this argument does not match a valid iterator type", 8680 "Pass the exact iterator state type expected by this function."); 8681 return -EINVAL; 8682 } 8683 t = btf_type_by_id(meta->btf, btf_id); 8684 nr_slots = t->size / BPF_REG_SIZE; 8685 8686 if (is_iter_new_kfunc(meta)) { 8687 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8688 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8689 verbose(env, "expected uninitialized iter_%s as %s\n", 8690 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 8691 bpf_diag_res( 8692 env, insn_idx, "iterator is already initialized", 8693 "Iterator creation requires an uninitialized iterator stack object, but this stack range already contains iterator state.", 8694 "Use a fresh iterator stack slot, or destroy the existing iterator before reusing the slot."); 8695 return -EINVAL; 8696 } 8697 8698 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8699 err = check_mem_access(env, insn_idx, reg, argno, 8700 i, BPF_DW, BPF_WRITE, -1, false, false); 8701 if (err) 8702 return err; 8703 } 8704 8705 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8706 if (err) 8707 return err; 8708 } else { 8709 /* iter_next() or iter_destroy(), as well as any kfunc 8710 * accepting iter argument, expect initialized iter state 8711 */ 8712 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8713 switch (err) { 8714 case 0: 8715 break; 8716 case -EINVAL: 8717 verbose(env, "expected an initialized iter_%s as %s\n", 8718 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 8719 bpf_diag_res( 8720 env, insn_idx, "uninitialized iterator use", 8721 "This iterator operation requires an initialized iterator state object, but the stack range does not contain a live iterator on this path.", 8722 "Call the matching iterator new kfunc on every path before calling next or destroy, and do not destroy the iterator before this use."); 8723 return err; 8724 case -EPROTO: 8725 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8726 bpf_diag_ctx_required( 8727 env, insn_idx, meta->func_name, BPF_DIAG_CONTEXT_RCU, 8728 "Wrap iterator use in bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced."); 8729 return err; 8730 default: 8731 return err; 8732 } 8733 8734 spi = iter_get_spi(env, reg, nr_slots); 8735 if (spi < 0) 8736 return spi; 8737 8738 mark_stack_slots_scratched(env, spi, nr_slots); 8739 8740 /* remember meta->iter info for process_iter_next_call() */ 8741 meta->iter.spi = spi; 8742 meta->iter.frameno = reg->frameno; 8743 update_ref_obj(&meta->ref_obj, &bpf_stack_slot(state, spi)->spilled_ptr); 8744 8745 /* The iterator stays. What was borrowed from the previous element goes. */ 8746 if (iter_next_borrows_struct(meta)) { 8747 err = invalidate_reference(env, meta->ref_obj.id); 8748 if (err) 8749 return err; 8750 } 8751 8752 if (is_iter_destroy_kfunc(meta)) { 8753 err = unmark_stack_slots_iter(env, reg, nr_slots); 8754 if (err) 8755 return err; 8756 } 8757 } 8758 8759 return 0; 8760 } 8761 8762 /* Look for a previous loop entry at insn_idx: nearest parent state 8763 * stopped at insn_idx with callsites matching those in cur->frame. 8764 */ 8765 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8766 struct bpf_verifier_state *cur, 8767 int insn_idx) 8768 { 8769 struct bpf_verifier_state_list *sl; 8770 struct bpf_verifier_state *st; 8771 struct list_head *pos, *head; 8772 8773 /* Explored states are pushed in stack order, most recent states come first */ 8774 head = bpf_explored_state(env, insn_idx); 8775 list_for_each(pos, head) { 8776 sl = container_of(pos, struct bpf_verifier_state_list, node); 8777 /* If st->branches != 0 state is a part of current DFS verification path, 8778 * hence cur & st for a loop. 8779 */ 8780 st = &sl->state; 8781 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8782 st->dfs_depth < cur->dfs_depth) 8783 return st; 8784 } 8785 8786 return NULL; 8787 } 8788 8789 /* 8790 * Check if scalar registers are exact for the purpose of not widening. 8791 * More lenient than regs_exact() 8792 */ 8793 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 8794 const struct bpf_reg_state *rcur) 8795 { 8796 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 8797 } 8798 8799 static void maybe_widen_reg(struct bpf_verifier_env *env, 8800 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 8801 { 8802 if (rold->type != SCALAR_VALUE) 8803 return; 8804 if (rold->type != rcur->type) 8805 return; 8806 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 8807 return; 8808 __mark_reg_unknown(env, rcur); 8809 } 8810 8811 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8812 struct bpf_verifier_state *old, 8813 struct bpf_verifier_state *cur) 8814 { 8815 struct bpf_func_state *fold, *fcur; 8816 int i, fr, num_slots; 8817 8818 for (fr = old->curframe; fr >= 0; fr--) { 8819 fold = old->frame[fr]; 8820 fcur = cur->frame[fr]; 8821 8822 for (i = 0; i < MAX_BPF_REG; i++) 8823 maybe_widen_reg(env, 8824 &fold->regs[i], 8825 &fcur->regs[i]); 8826 8827 num_slots = min(bpf_stack_nr_slots(fold), bpf_stack_nr_slots(fcur)); 8828 for (i = 0; i < num_slots; i++) { 8829 struct bpf_stack_state *old_ss = bpf_stack_slot(fold, i); 8830 struct bpf_stack_state *cur_ss = bpf_stack_slot(fcur, i); 8831 8832 if (!bpf_is_spilled_reg(old_ss) || !bpf_is_spilled_reg(cur_ss)) 8833 continue; 8834 8835 maybe_widen_reg(env, &old_ss->spilled_ptr, &cur_ss->spilled_ptr); 8836 } 8837 } 8838 return 0; 8839 } 8840 8841 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8842 struct bpf_call_arg_meta *meta) 8843 { 8844 int iter_frameno = meta->iter.frameno; 8845 int iter_spi = meta->iter.spi; 8846 8847 return &bpf_stack_slot(cur_st->frame[iter_frameno], iter_spi)->spilled_ptr; 8848 } 8849 8850 /* process_iter_next_call() is called when verifier gets to iterator's next 8851 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8852 * to it as just "iter_next()" in comments below. 8853 * 8854 * BPF verifier relies on a crucial contract for any iter_next() 8855 * implementation: it should *eventually* return NULL, and once that happens 8856 * it should keep returning NULL. That is, once iterator exhausts elements to 8857 * iterate, it should never reset or spuriously return new elements. 8858 * 8859 * With the assumption of such contract, process_iter_next_call() simulates 8860 * a fork in the verifier state to validate loop logic correctness and safety 8861 * without having to simulate infinite amount of iterations. 8862 * 8863 * In current state, we first assume that iter_next() returned NULL and 8864 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8865 * conditions we should not form an infinite loop and should eventually reach 8866 * exit. 8867 * 8868 * Besides that, we also fork current state and enqueue it for later 8869 * verification. In a forked state we keep iterator state as ACTIVE 8870 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8871 * also bump iteration depth to prevent erroneous infinite loop detection 8872 * later on (see iter_active_depths_differ() comment for details). In this 8873 * state we assume that we'll eventually loop back to another iter_next() 8874 * calls (it could be in exactly same location or in some other instruction, 8875 * it doesn't matter, we don't make any unnecessary assumptions about this, 8876 * everything revolves around iterator state in a stack slot, not which 8877 * instruction is calling iter_next()). When that happens, we either will come 8878 * to iter_next() with equivalent state and can conclude that next iteration 8879 * will proceed in exactly the same way as we just verified, so it's safe to 8880 * assume that loop converges. If not, we'll go on another iteration 8881 * simulation with a different input state, until all possible starting states 8882 * are validated or we reach maximum number of instructions limit. 8883 * 8884 * This way, we will either exhaustively discover all possible input states 8885 * that iterator loop can start with and eventually will converge, or we'll 8886 * effectively regress into bounded loop simulation logic and either reach 8887 * maximum number of instructions if loop is not provably convergent, or there 8888 * is some statically known limit on number of iterations (e.g., if there is 8889 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8890 * 8891 * Iteration convergence logic in is_state_visited() relies on exact 8892 * states comparison, which ignores read and precision marks. 8893 * This is necessary because read and precision marks are not finalized 8894 * while in the loop. Exact comparison might preclude convergence for 8895 * simple programs like below: 8896 * 8897 * i = 0; 8898 * while(iter_next(&it)) 8899 * i++; 8900 * 8901 * At each iteration step i++ would produce a new distinct state and 8902 * eventually instruction processing limit would be reached. 8903 * 8904 * To avoid such behavior speculatively forget (widen) range for 8905 * imprecise scalar registers, if those registers were not precise at the 8906 * end of the previous iteration and do not match exactly. 8907 * 8908 * This is a conservative heuristic that allows to verify wide range of programs, 8909 * however it precludes verification of programs that conjure an 8910 * imprecise value on the first loop iteration and use it as precise on a second. 8911 * For example, the following safe program would fail to verify: 8912 * 8913 * struct bpf_num_iter it; 8914 * int arr[10]; 8915 * int i = 0, a = 0; 8916 * bpf_iter_num_new(&it, 0, 10); 8917 * while (bpf_iter_num_next(&it)) { 8918 * if (a == 0) { 8919 * a = 1; 8920 * i = 7; // Because i changed verifier would forget 8921 * // it's range on second loop entry. 8922 * } else { 8923 * arr[i] = 42; // This would fail to verify. 8924 * } 8925 * } 8926 * bpf_iter_num_destroy(&it); 8927 */ 8928 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8929 struct bpf_call_arg_meta *meta) 8930 { 8931 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8932 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8933 struct bpf_reg_state *cur_iter, *queued_iter; 8934 8935 BTF_TYPE_EMIT(struct bpf_iter); 8936 8937 cur_iter = get_iter_from_state(cur_st, meta); 8938 8939 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8940 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8941 verifier_bug(env, "unexpected iterator state %d (%s)", 8942 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8943 return -EFAULT; 8944 } 8945 8946 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8947 /* Because iter_next() call is a checkpoint is_state_visitied() 8948 * should guarantee parent state with same call sites and insn_idx. 8949 */ 8950 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8951 !same_callsites(cur_st->parent, cur_st)) { 8952 verifier_bug(env, "bad parent state for iter next call"); 8953 return -EFAULT; 8954 } 8955 /* Note cur_st->parent in the call below, it is necessary to skip 8956 * checkpoint created for cur_st by is_state_visited() 8957 * right at this instruction. 8958 */ 8959 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8960 /* branch out active iter state */ 8961 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8962 if (IS_ERR(queued_st)) 8963 return PTR_ERR(queued_st); 8964 8965 queued_iter = get_iter_from_state(queued_st, meta); 8966 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8967 queued_iter->iter.depth++; 8968 if (prev_st) 8969 widen_imprecise_scalars(env, prev_st, queued_st); 8970 8971 queued_fr = queued_st->frame[queued_st->curframe]; 8972 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8973 } 8974 8975 /* switch to DRAINED state, but keep the depth unchanged */ 8976 /* mark current iter state as drained and assume returned NULL */ 8977 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8978 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8979 8980 return 0; 8981 } 8982 8983 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8984 { 8985 return type == ARG_MEM_SIZE || type == ARG_MEM_SIZE_OR_ZERO; 8986 } 8987 8988 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8989 { 8990 /* 8991 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw 8992 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be 8993 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized(). 8994 */ 8995 return (base_type(type) == ARG_PTR_TO_MEM || 8996 base_type(type) == ARG_PTR_TO_MAP_VALUE) && 8997 type & MEM_UNINIT; 8998 } 8999 9000 static bool arg_type_is_release(enum bpf_arg_type type) 9001 { 9002 return type & OBJ_RELEASE; 9003 } 9004 9005 static bool arg_type_is_dynptr(enum bpf_arg_type type) 9006 { 9007 return base_type(type) == ARG_PTR_TO_DYNPTR; 9008 } 9009 9010 /* 9011 * An argument that only ever takes a scalar, so a zero register passed to it 9012 * is a value rather than a NULL pointer. 9013 */ 9014 static bool arg_type_is_scalar(enum bpf_arg_type type) 9015 { 9016 switch (base_type(type)) { 9017 case ARG_SCALAR: 9018 case ARG_CONST_SCALAR: 9019 case ARG_MEM_SIZE: 9020 case ARG_MEM_SIZE_OR_ZERO: 9021 case ARG_CONST_MEM_SIZE: 9022 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9023 return true; 9024 default: 9025 return false; 9026 } 9027 } 9028 9029 /* 9030 * A helper has no BTF and a nonzero function ID. A kfunc has both, while a 9031 * BPF subprogram has BTF and a zero function ID. 9032 */ 9033 static bool is_helper(const struct bpf_call_arg_meta *meta) 9034 { 9035 return !meta->btf && meta->func_id; 9036 } 9037 9038 static bool is_helper_call(const struct bpf_call_arg_meta *meta, enum bpf_func_id func_id) 9039 { 9040 return is_helper(meta) && meta->func_id == func_id; 9041 } 9042 9043 static bool is_kfunc(const struct bpf_call_arg_meta *meta) 9044 { 9045 return meta->btf && meta->func_id; 9046 } 9047 9048 static bool is_kfunc_call(const struct bpf_call_arg_meta *meta, u32 btf_id) 9049 { 9050 return is_kfunc(meta) && meta->func_id == btf_id; 9051 } 9052 9053 static int resolve_map_arg_type(struct bpf_verifier_env *env, 9054 const struct bpf_call_arg_meta *meta, 9055 enum bpf_arg_type *arg_type) 9056 { 9057 if (!meta->map.ptr) { 9058 /* kernel subsystem misconfigured verifier */ 9059 verifier_bug(env, "invalid map_ptr to access map->type"); 9060 return -EFAULT; 9061 } 9062 9063 switch (meta->map.ptr->map_type) { 9064 case BPF_MAP_TYPE_SOCKMAP: 9065 case BPF_MAP_TYPE_SOCKHASH: 9066 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 9067 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 9068 } else { 9069 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 9070 return -EINVAL; 9071 } 9072 break; 9073 case BPF_MAP_TYPE_BLOOM_FILTER: 9074 if (is_helper_call(meta, BPF_FUNC_map_peek_elem)) 9075 *arg_type = ARG_PTR_TO_MAP_VALUE; 9076 break; 9077 default: 9078 break; 9079 } 9080 return 0; 9081 } 9082 9083 static int resolve_func_arg_type(struct bpf_verifier_env *env, 9084 struct bpf_reg_state *reg, u32 arg, argno_t argno, 9085 struct bpf_call_arg_meta *meta, 9086 enum bpf_arg_type *arg_type, u32 *arg_size); 9087 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 9088 argno_t argno, enum bpf_arg_type arg_type, 9089 const struct btf *arg_btf, u32 arg_btf_id, 9090 struct bpf_call_arg_meta *meta, int insn_idx); 9091 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, 9092 const struct btf_param *arg); 9093 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 9094 const struct btf_param *arg, 9095 const char *name); 9096 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta); 9097 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta); 9098 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta); 9099 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta); 9100 static bool is_bpf_obj_drop_kfunc(u32 func_id); 9101 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id); 9102 static bool is_bpf_rbtree_add_kfunc(u32 func_id); 9103 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta); 9104 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env); 9105 static int process_irq_flag(struct bpf_verifier_env *env, 9106 struct bpf_reg_state *reg, argno_t argno, 9107 struct bpf_call_arg_meta *meta); 9108 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 9109 struct bpf_reg_state *reg, 9110 argno_t argno, 9111 struct bpf_call_arg_meta *meta); 9112 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 9113 struct bpf_reg_state *reg, 9114 argno_t argno, 9115 struct bpf_call_arg_meta *meta); 9116 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 9117 struct bpf_reg_state *reg, 9118 argno_t argno, 9119 struct bpf_call_arg_meta *meta); 9120 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 9121 struct bpf_reg_state *reg, 9122 argno_t argno, 9123 struct bpf_call_arg_meta *meta); 9124 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env); 9125 9126 struct bpf_reg_types { 9127 const enum bpf_reg_type types[10]; 9128 u32 *btf_id; 9129 }; 9130 9131 static const struct bpf_reg_types sock_types = { 9132 .types = { 9133 PTR_TO_SOCK_COMMON, 9134 PTR_TO_SOCKET, 9135 PTR_TO_TCP_SOCK, 9136 PTR_TO_XDP_SOCK, 9137 }, 9138 }; 9139 9140 #ifdef CONFIG_NET 9141 static const struct bpf_reg_types btf_id_sock_common_types = { 9142 .types = { 9143 PTR_TO_SOCK_COMMON, 9144 PTR_TO_SOCKET, 9145 PTR_TO_TCP_SOCK, 9146 PTR_TO_XDP_SOCK, 9147 PTR_TO_BTF_ID, 9148 PTR_TO_BTF_ID | PTR_TRUSTED, 9149 }, 9150 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9151 }; 9152 #endif 9153 9154 static const struct bpf_reg_types mem_types = { 9155 .types = { 9156 PTR_TO_STACK, 9157 PTR_TO_PACKET, 9158 PTR_TO_PACKET_META, 9159 PTR_TO_MAP_KEY, 9160 PTR_TO_MAP_VALUE, 9161 PTR_TO_MEM, 9162 PTR_TO_MEM | MEM_RINGBUF, 9163 PTR_TO_BUF, 9164 PTR_TO_BTF_ID | PTR_TRUSTED, 9165 PTR_TO_CTX, 9166 }, 9167 }; 9168 9169 static const struct bpf_reg_types map_value_or_alloc_obj_types = { 9170 .types = { 9171 PTR_TO_MAP_VALUE, 9172 PTR_TO_BTF_ID | MEM_ALLOC, 9173 } 9174 }; 9175 9176 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 9177 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 9178 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 9179 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 9180 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 9181 static const struct bpf_reg_types btf_ptr_types = { 9182 .types = { 9183 PTR_TO_BTF_ID, 9184 PTR_TO_BTF_ID | PTR_TRUSTED, 9185 PTR_TO_BTF_ID | MEM_RCU, 9186 }, 9187 }; 9188 static const struct bpf_reg_types percpu_btf_ptr_types = { 9189 .types = { 9190 PTR_TO_BTF_ID | MEM_PERCPU, 9191 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 9192 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 9193 } 9194 }; 9195 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 9196 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 9197 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 9198 static const struct bpf_reg_types map_value_types = { .types = { PTR_TO_MAP_VALUE } }; 9199 static const struct bpf_reg_types arena_types = { 9200 .types = { 9201 PTR_TO_ARENA, 9202 SCALAR_VALUE, 9203 } 9204 }; 9205 static const struct bpf_reg_types ctx_out_types = { 9206 .types = { PTR_TO_MEM | MEM_RDONLY | PTR_TRUSTED }, 9207 }; 9208 9209 static const struct bpf_reg_types alloc_obj_drop_types = { 9210 .types = { 9211 PTR_TO_BTF_ID | MEM_ALLOC, 9212 PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU, 9213 } 9214 }; 9215 9216 static const struct bpf_reg_types alloc_obj_types = { 9217 .types = { 9218 PTR_TO_BTF_ID | MEM_ALLOC, 9219 PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU, 9220 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 9221 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 9222 } 9223 }; 9224 9225 static const struct bpf_reg_types kptr_xchg_dest_types = { 9226 .types = { 9227 PTR_TO_MAP_VALUE, 9228 PTR_TO_BTF_ID | MEM_ALLOC, 9229 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 9230 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 9231 } 9232 }; 9233 static const struct bpf_reg_types dynptr_types = { 9234 .types = { 9235 PTR_TO_STACK, 9236 CONST_PTR_TO_DYNPTR, 9237 } 9238 }; 9239 9240 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 9241 [ARG_PTR_TO_MAP_KEY] = &mem_types, 9242 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 9243 [ARG_MEM_SIZE] = &scalar_types, 9244 [ARG_MEM_SIZE_OR_ZERO] = &scalar_types, 9245 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 9246 [ARG_SCALAR] = &scalar_types, 9247 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 9248 [ARG_PTR_TO_CTX] = &context_types, 9249 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 9250 #ifdef CONFIG_NET 9251 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 9252 #endif 9253 [ARG_PTR_TO_SOCKET] = &fullsock_types, 9254 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 9255 [ARG_PTR_TO_SPIN_LOCK] = &map_value_or_alloc_obj_types, 9256 [ARG_PTR_TO_MEM] = &mem_types, 9257 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 9258 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 9259 [ARG_PTR_TO_FUNC] = &func_ptr_types, 9260 [ARG_PTR_TO_STACK] = &stack_ptr_types, 9261 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 9262 [ARG_PTR_TO_TIMER] = &map_value_types, 9263 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 9264 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 9265 [ARG_CONST_SCALAR] = &scalar_types, 9266 [ARG_CONST_MEM_SIZE] = &scalar_types, 9267 [ARG_PTR_TO_ALLOC_BTF_ID] = &alloc_obj_drop_types, 9268 [ARG_PTR_TO_REFCOUNTED_KPTR] = &alloc_obj_types, 9269 [ARG_PTR_TO_ITER] = &stack_ptr_types, 9270 [ARG_PTR_TO_LIST_HEAD] = &map_value_or_alloc_obj_types, 9271 [ARG_PTR_TO_LIST_NODE] = &alloc_obj_types, 9272 [ARG_PTR_TO_RB_ROOT] = &map_value_or_alloc_obj_types, 9273 [ARG_PTR_TO_RB_NODE] = &alloc_obj_types, 9274 [ARG_PTR_TO_RES_SPIN_LOCK] = &map_value_or_alloc_obj_types, 9275 [ARG_PTR_TO_WORKQUEUE] = &map_value_types, 9276 [ARG_PTR_TO_TASK_WORK] = &map_value_types, 9277 [ARG_PTR_TO_RCU_HEAD] = &map_value_types, 9278 [ARG_PTR_TO_IRQ_FLAG] = &stack_ptr_types, 9279 [ARG_PTR_TO_ARENA] = &arena_types, 9280 [ARG_PTR_TO_CTX_OUT] = &ctx_out_types, 9281 }; 9282 9283 static void bpf_diag_call_arg(struct bpf_verifier_env *env, u32 insn_idx, argno_t argno, 9284 const char *call_name, const char *reason, 9285 const char *suggestion) 9286 { 9287 int arg = arg_from_argno(argno); 9288 int regno = reg_from_argno(argno); 9289 int stack_slot = -1; 9290 9291 if (arg < 0 && regno >= BPF_REG_1 && regno <= BPF_REG_5) 9292 arg = regno; 9293 if (arg > MAX_BPF_FUNC_REG_ARGS) 9294 stack_slot = arg - MAX_BPF_FUNC_REG_ARGS - 1; 9295 9296 bpf_diag_call_type(env, insn_idx, arg, regno, stack_slot, 9297 call_name && *call_name ? call_name : "call", 9298 reg_arg_name(env, argno), reason, suggestion); 9299 } 9300 9301 static const char *bpf_diag_arg_name(struct bpf_verifier_env *env, argno_t argno) 9302 { 9303 return bpf_diag_fmt(env, "%s", reg_arg_name(env, argno)); 9304 } 9305 9306 __printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx, 9307 argno_t argno, const char *call_name, 9308 const char *suggestion, const char *fmt, ...) 9309 { 9310 const char *reason; 9311 va_list args; 9312 9313 va_start(args, fmt); 9314 reason = bpf_diag_vfmt(env, fmt, args); 9315 va_end(args); 9316 9317 bpf_diag_call_arg(env, insn_idx, argno, call_name, reason, suggestion); 9318 } 9319 9320 static int check_func_arg_nullability(struct bpf_verifier_env *env, 9321 struct bpf_reg_state *reg, u32 arg, argno_t argno, 9322 enum bpf_arg_type arg_type, 9323 struct bpf_call_arg_meta *meta, int insn_idx) 9324 { 9325 const char *expected_type = "pointer"; 9326 9327 if (arg_type_is_scalar(arg_type) || type_may_be_null(arg_type) || 9328 (!bpf_register_is_null(reg) && !type_may_be_null(reg->type))) 9329 return 0; 9330 9331 if (meta->btf) { 9332 u32 arg_btf_id; 9333 9334 arg_btf_id = btf_params(meta->func_proto)[arg].type; 9335 expected_type = bpf_diag_fmt(env, "value of type %s", 9336 bpf_diag_fmt_btf_type(env, meta->btf, arg_btf_id)); 9337 } 9338 9339 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 9340 reg_arg_name(env, argno)); 9341 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 9342 "Add a NULL check and make the call only on the non-NULL path.", 9343 "the pointer may be NULL, but this call requires a non-NULL %s", 9344 expected_type); 9345 return -EACCES; 9346 } 9347 9348 static int check_func_arg_release(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 9349 u32 arg, argno_t argno, enum bpf_arg_type arg_type, 9350 struct bpf_call_arg_meta *meta, int insn_idx) 9351 { 9352 const char *expected_type = "pointer"; 9353 9354 if (!arg_type_is_release(arg_type)) 9355 return 0; 9356 9357 if (arg_type_is_dynptr(arg_type) || reg_is_referenced(env, reg) || 9358 bpf_register_is_null(reg)) 9359 return 0; 9360 9361 verbose(env, "release function %s expects referenced PTR_TO_BTF_ID passed to %s\n", 9362 meta->func_name, reg_arg_name(env, argno)); 9363 9364 if (is_kfunc(meta)) { 9365 const struct btf_param *btf_arg; 9366 const struct btf_type *t; 9367 u32 ref_id; 9368 9369 btf_arg = &btf_params(meta->func_proto)[arg]; 9370 ref_id = btf_arg->type; 9371 t = btf_type_skip_modifiers(meta->btf, btf_arg->type, NULL); 9372 if (btf_type_is_ptr(t)) 9373 btf_type_skip_modifiers(meta->btf, t->type, &ref_id); 9374 expected_type = bpf_diag_fmt(env, "value of type %s", 9375 bpf_diag_fmt_btf_type(env, meta->btf, ref_id)); 9376 } 9377 9378 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 9379 bpf_diag_fmt(env, "Pass the resource-owning %s returned by the matching acquire call, or avoid the release function after ownership has already been transferred or released.", 9380 expected_type), 9381 "release functions require a value that owns a live resource returned by a matching acquire function"); 9382 return -EINVAL; 9383 } 9384 9385 static const char *bpf_diag_expected_reg_types(struct bpf_verifier_env *env, 9386 const enum bpf_reg_type *types, int count) 9387 { 9388 size_t len = 0, size = 1; 9389 char *buf; 9390 int i; 9391 9392 for (i = 0; i < count; i++) 9393 size += strlen(reg_type_str(env, types[i])) + (i ? 2 : 0); 9394 9395 buf = bpf_diag_fmt_buf(env, size); 9396 if (!buf) 9397 return ""; 9398 9399 for (i = 0; i < count; i++) 9400 len += scnprintf(buf + len, size - len, "%s%s", i ? ", " : "", 9401 reg_type_str(env, types[i])); 9402 return buf; 9403 } 9404 9405 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 9406 enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) 9407 { 9408 enum bpf_reg_type expected, type = reg->type; 9409 const struct bpf_reg_types *compatible; 9410 const char *actual, *accepted; 9411 int i, j; 9412 9413 compatible = compatible_reg_types[base_type(arg_type)]; 9414 if (!compatible) { 9415 verifier_bug(env, "unsupported arg type %d", arg_type); 9416 return -EFAULT; 9417 } 9418 if (is_kfunc(meta) && base_type(arg_type) == ARG_PTR_TO_BTF_ID && 9419 (base_type(type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(type)])) 9420 goto found; 9421 9422 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 9423 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 9424 * 9425 * Same for MAYBE_NULL: 9426 * 9427 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 9428 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 9429 * 9430 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 9431 * 9432 * Therefore we fold these flags depending on the arg_type before comparison. 9433 */ 9434 if (arg_type & MEM_RDONLY) 9435 type &= ~MEM_RDONLY; 9436 if (arg_type & PTR_MAYBE_NULL) 9437 type &= ~PTR_MAYBE_NULL; 9438 if (base_type(arg_type) == ARG_PTR_TO_MEM) 9439 type &= ~DYNPTR_TYPE_FLAG_MASK; 9440 /* Allow allocated memory for BTF-defined ARG_PTR_TO_MEM but not helpers. */ 9441 if (!is_helper(meta) && base_type(arg_type) == ARG_PTR_TO_MEM && 9442 type_is_ptr_alloc_obj(type)) 9443 type = PTR_TO_MEM; 9444 9445 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 9446 if (is_helper_call(meta, BPF_FUNC_kptr_xchg) && type_is_alloc(type) && 9447 reg_from_argno(argno) == BPF_REG_2) { 9448 type &= ~MEM_ALLOC; 9449 type &= ~MEM_PERCPU; 9450 } 9451 9452 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 9453 expected = compatible->types[i]; 9454 if (expected == NOT_INIT) 9455 break; 9456 9457 if (type == expected) 9458 goto found; 9459 } 9460 9461 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 9462 for (j = 0; j + 1 < i; j++) 9463 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 9464 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 9465 actual = bpf_diag_fmt(env, "%s", reg_type_str(env, reg->type)); 9466 accepted = bpf_diag_expected_reg_types(env, compatible->types, i); 9467 bpf_diag_call_arg_fmt(env, env->insn_idx, argno, meta->func_name, 9468 bpf_diag_fmt(env, "Pass %s.", bpf_diag_arg_type_plain(arg_type)), 9469 "it has type %s, but this argument accepts %s", 9470 actual, accepted); 9471 return -EACCES; 9472 9473 found: 9474 return 0; 9475 } 9476 9477 static struct btf_field * 9478 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 9479 { 9480 struct btf_field *field; 9481 struct btf_record *rec; 9482 9483 rec = reg_btf_record(reg); 9484 if (!rec) 9485 return NULL; 9486 9487 field = btf_record_find(rec, off, fields); 9488 if (!field) 9489 return NULL; 9490 9491 return field; 9492 } 9493 9494 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 9495 const struct bpf_reg_state *reg, argno_t argno, 9496 enum bpf_arg_type arg_type) 9497 { 9498 u32 type = reg->type; 9499 9500 /* When referenced register is passed to release function, its fixed 9501 * offset must be 0. 9502 * 9503 * We will check arg_type_is_release reg has id when storing 9504 * meta->release_regno. 9505 */ 9506 if (arg_type_is_release(arg_type)) { 9507 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 9508 * may not directly point to the object being released, but to 9509 * dynptr pointing to such object, which might be at some offset 9510 * on the stack. In that case, we simply to fallback to the 9511 * default handling. 9512 */ 9513 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 9514 return 0; 9515 9516 /* Doing check_ptr_off_reg check for the offset will catch this 9517 * because fixed_off_ok is false, but checking here allows us 9518 * to give the user a better error message. 9519 */ 9520 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 9521 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 9522 reg_arg_name(env, argno)); 9523 return -EINVAL; 9524 } 9525 } 9526 9527 switch (type) { 9528 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 9529 case PTR_TO_STACK: 9530 case PTR_TO_PACKET: 9531 case PTR_TO_PACKET_META: 9532 case PTR_TO_MAP_KEY: 9533 case PTR_TO_MAP_VALUE: 9534 case PTR_TO_MEM: 9535 case PTR_TO_MEM | MEM_RDONLY: 9536 case PTR_TO_MEM | MEM_RINGBUF: 9537 case PTR_TO_BUF: 9538 case PTR_TO_BUF | MEM_RDONLY: 9539 case PTR_TO_ARENA: 9540 case SCALAR_VALUE: 9541 return 0; 9542 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 9543 * fixed offset. 9544 */ 9545 case PTR_TO_BTF_ID: 9546 case PTR_TO_BTF_ID | MEM_ALLOC: 9547 case PTR_TO_BTF_ID | PTR_TRUSTED: 9548 case PTR_TO_BTF_ID | MEM_RCU: 9549 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 9550 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 9551 /* When referenced PTR_TO_BTF_ID is passed to release function, 9552 * its fixed offset must be 0. bpf_refcount_acquire() returns the 9553 * pointer it was given while incrementing the refcount at the 9554 * refcount field offset, so it needs a zero offset too. In the 9555 * other cases, fixed offset can be non-zero. var_off always must 9556 * be 0 for PTR_TO_BTF_ID, hence we still need to do checks 9557 * instead of returning. 9558 */ 9559 return __check_ptr_off_reg(env, reg, argno, 9560 base_type(arg_type) != ARG_PTR_TO_REFCOUNTED_KPTR); 9561 case PTR_TO_CTX: 9562 /* 9563 * Allow fixed and variable offsets for syscall context, but 9564 * only when the argument is passed as memory, not ctx, 9565 * otherwise we may get modified ctx in tail called programs and 9566 * global subprogs (that may act as extension prog hooks). 9567 */ 9568 if (base_type(arg_type) != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 9569 return 0; 9570 fallthrough; 9571 default: 9572 return __check_ptr_off_reg(env, reg, argno, false); 9573 } 9574 } 9575 9576 static int check_arg_const_str(struct bpf_verifier_env *env, 9577 struct bpf_reg_state *reg, argno_t argno) 9578 { 9579 struct bpf_map *map = reg->map_ptr; 9580 int err; 9581 int map_off; 9582 u64 map_addr; 9583 char *str_ptr; 9584 u32 cnt; 9585 9586 if (reg->type != PTR_TO_MAP_VALUE) 9587 return -EINVAL; 9588 9589 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 9590 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 9591 reg_arg_name(env, argno)); 9592 return -EACCES; 9593 } 9594 9595 if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) { 9596 verbose(env, "%s points to percpu_array map which cannot be used as const string\n", 9597 reg_arg_name(env, argno)); 9598 return -EACCES; 9599 } 9600 9601 if (!bpf_map_is_rdonly(map)) { 9602 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 9603 return -EACCES; 9604 } 9605 9606 if (!tnum_is_const(reg->var_off)) { 9607 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 9608 return -EACCES; 9609 } 9610 9611 if (!map->ops->map_direct_value_addr) { 9612 verbose(env, "no direct value access support for this map type\n"); 9613 return -EACCES; 9614 } 9615 9616 err = check_map_access(env, reg, argno, 0, 9617 map->value_size - reg->var_off.value, false, 9618 ACCESS_HELPER); 9619 if (err) 9620 return err; 9621 9622 map_off = reg->var_off.value; 9623 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 9624 if (err) { 9625 verbose(env, "direct value access on string failed\n"); 9626 return err; 9627 } 9628 9629 str_ptr = (char *)(long)(map_addr); 9630 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 9631 verbose(env, "string is not zero-terminated\n"); 9632 return -EINVAL; 9633 } 9634 /* the bytes of a pointer to a function are not known until the program is jitted */ 9635 if (bpf_map_range_func_ptrs(env, map, map_off, strlen(str_ptr + map_off) + 1, &cnt)) { 9636 verbose(env, "string overlaps with a pointer to a function\n"); 9637 return -EACCES; 9638 } 9639 return 0; 9640 } 9641 9642 /* Returns constant key value in `value` if possible, else negative error */ 9643 static int get_constant_map_key(struct bpf_verifier_env *env, 9644 struct bpf_reg_state *key, 9645 u32 key_size, 9646 s64 *value) 9647 { 9648 struct bpf_func_state *state = bpf_func(env, key); 9649 struct bpf_stack_state *ss; 9650 struct bpf_reg_state *reg; 9651 int slot, spi, off; 9652 int spill_size = 0; 9653 int zero_size = 0; 9654 int stack_off; 9655 int i, err; 9656 u8 *stype; 9657 9658 if (!env->bpf_capable) 9659 return -EOPNOTSUPP; 9660 if (key->type != PTR_TO_STACK) 9661 return -EOPNOTSUPP; 9662 if (!tnum_is_const(key->var_off)) 9663 return -EOPNOTSUPP; 9664 9665 stack_off = key->var_off.value; 9666 slot = -stack_off - 1; 9667 spi = slot / BPF_REG_SIZE; 9668 off = slot % BPF_REG_SIZE; 9669 ss = bpf_stack_slot(state, spi); 9670 stype = ss->slot_type; 9671 9672 /* First handle precisely tracked STACK_ZERO */ 9673 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 9674 zero_size++; 9675 if (zero_size >= key_size) { 9676 *value = 0; 9677 return 0; 9678 } 9679 9680 /* Check that stack contains a scalar spill of expected size */ 9681 if (!bpf_is_spilled_scalar_reg(ss)) 9682 return -EOPNOTSUPP; 9683 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 9684 spill_size++; 9685 if (spill_size != key_size) 9686 return -EOPNOTSUPP; 9687 9688 reg = &ss->spilled_ptr; 9689 if (!tnum_is_const(reg->var_off)) 9690 /* Stack value not statically known */ 9691 return -EOPNOTSUPP; 9692 9693 /* We are relying on a constant value. So mark as precise 9694 * to prevent pruning on it. 9695 */ 9696 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 9697 err = mark_chain_precision_batch(env, env->cur_state); 9698 if (err < 0) 9699 return err; 9700 9701 *value = reg->var_off.value; 9702 return 0; 9703 } 9704 9705 static bool can_elide_value_nullness(const struct bpf_map *map); 9706 9707 static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 9708 argno_t argno, struct bpf_call_arg_meta *meta) 9709 { 9710 /* Use map_uid (which is unique id of inner map) to reject: 9711 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 9712 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 9713 * if (inner_map1 && inner_map2) { 9714 * timer = bpf_map_lookup_elem(inner_map1); 9715 * if (timer) 9716 * // mismatch would have been allowed 9717 * bpf_timer_init(timer, inner_map2); 9718 * } 9719 * 9720 * Comparing map_ptr is enough to distinguish normal and outer maps. 9721 */ 9722 if (meta->map.ptr && 9723 (meta->map.ptr != reg->map_ptr || meta->map.uid != reg->map_uid)) { 9724 argno_t obj_argno = argno_from_reg(reg_from_argno(argno) - 1); 9725 struct btf_record *rec = meta->map.ptr->record; 9726 const char *obj_name = "workqueue"; 9727 9728 if (rec->timer_off >= 0) 9729 obj_name = "timer"; 9730 else if (rec->task_work_off >= 0) 9731 obj_name = "bpf_task_work"; 9732 else if (rec->rcu_head_off >= 0) 9733 obj_name = "bpf_rcu_head"; 9734 9735 verbose(env, "%s pointer in %s map_uid=%d ", 9736 obj_name, reg_arg_name(env, obj_argno), meta->map.uid); 9737 verbose(env, "doesn't match map pointer in %s map_uid=%d\n", 9738 reg_arg_name(env, argno), reg->map_uid); 9739 return -EINVAL; 9740 } 9741 9742 meta->map.ptr = reg->map_ptr; 9743 meta->map.uid = reg->map_uid; 9744 return 0; 9745 } 9746 9747 /* 9748 * MEM_WRITE alone denotes an input/output buffer. MEM_UNINIT marks an output 9749 * whose incoming contents are not read. 9750 */ 9751 static enum bpf_access_type func_arg_access_type(enum bpf_arg_type arg_type) 9752 { 9753 if (!(arg_type & MEM_WRITE)) 9754 return BPF_READ; 9755 if (arg_type & MEM_UNINIT) 9756 return BPF_WRITE; 9757 return BPF_READ | BPF_WRITE; 9758 } 9759 9760 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot, 9761 struct bpf_call_arg_meta *meta, 9762 int insn_idx) 9763 { 9764 const struct btf_param *btf_arg = is_kfunc(meta) ? 9765 &btf_params(meta->func_proto)[arg] : NULL; 9766 const struct bpf_func_proto *fn = meta->fn; 9767 struct bpf_func_state *caller = cur_func(env); 9768 struct bpf_reg_state *regs = cur_regs(env); 9769 argno_t argno = argno_from_arg(slot + 1); 9770 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, slot); 9771 enum bpf_arg_type arg_type = fn->arg_type[arg]; 9772 int regno = reg_from_argno(argno); 9773 u32 arg_size = arg_type & MEM_FIXED_SIZE ? fn->arg_size[arg] : 0; 9774 u32 key_size; 9775 int err = 0; 9776 9777 if (arg_type == ARG_PTR_TO_PROG_AUX) { 9778 cur_aux(env)->arg_prog = regno; 9779 return 0; 9780 } 9781 9782 if (arg_type == ARG_IGNORE) 9783 return 0; 9784 9785 if (regno >= 0) { 9786 err = check_reg_arg(env, regno, SRC_OP); 9787 if (err) 9788 return err; 9789 } 9790 9791 /* Preserve the legacy helper behavior for privileged pointer leaks. */ 9792 if (arg_type == ARG_ANYTHING) { 9793 if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 9794 verbose(env, "%s leaks addr into helper function\n", 9795 reg_arg_name(env, argno)); 9796 return -EACCES; 9797 } 9798 return 0; 9799 } 9800 9801 err = resolve_func_arg_type(env, reg, arg, argno, meta, &arg_type, &arg_size); 9802 if (err) 9803 return err; 9804 9805 /* 9806 * A slice of a packet is packet data under another name. A helper which 9807 * may reallocate the packet must not go on reading from the old one. 9808 */ 9809 if (is_helper(meta) && reg_is_dynptr_slice_pkt(reg) && 9810 bpf_helper_changes_pkt_data(meta->func_id)) { 9811 verbose(env, "function access to the packet is not allowed\n"); 9812 return -EACCES; 9813 } 9814 9815 if (arg_type_is_raw_mem(arg_type)) 9816 meta->arg_raw_mem.mask |= BIT(slot); 9817 9818 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) { 9819 err = mark_arg_precision(env, argno); 9820 if (err) 9821 return err; 9822 return 0; 9823 } 9824 9825 err = check_func_arg_nullability(env, reg, arg, argno, arg_type, meta, insn_idx); 9826 if (err) 9827 return err; 9828 9829 err = check_reg_type(env, reg, argno, arg_type, meta); 9830 if (err) 9831 return err; 9832 9833 err = check_func_arg_reg_off(env, reg, argno, arg_type); 9834 if (err) 9835 return err; 9836 9837 err = check_func_arg_release(env, reg, arg, argno, arg_type, meta, insn_idx); 9838 if (err) 9839 return err; 9840 9841 if (reg_is_referenced(env, reg)) 9842 update_ref_obj(&meta->ref_obj, reg); 9843 9844 switch (base_type(arg_type)) { 9845 case ARG_CONST_SCALAR: 9846 err = process_const_arg(env, reg, argno, meta); 9847 if (err < 0) { 9848 if (err == -EINVAL) 9849 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 9850 "Pass a compile-time constant or a value the verifier can prove is constant at this call.", 9851 "the function requires this scalar argument to be a verifier-known constant, but %s is variable on this path", 9852 reg_arg_name(env, argno)); 9853 return err; 9854 } 9855 break; 9856 case ARG_SCALAR: 9857 break; 9858 case ARG_CONST_MAP_PTR: 9859 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 9860 err = process_map_ptr_arg(env, reg, argno, meta); 9861 if (err) 9862 return err; 9863 break; 9864 case ARG_PTR_TO_MAP_KEY: 9865 /* bpf_map_xxx(..., map_ptr, ..., key) call: 9866 * check that [key, key + map->key_size) are within 9867 * stack limits and initialized 9868 */ 9869 if (!meta->map.ptr) { 9870 /* in function declaration map_ptr must come before 9871 * map_key, so that it's verified and known before 9872 * we have to check map_key here. Otherwise it means 9873 * that kernel subsystem misconfigured verifier 9874 */ 9875 verifier_bug(env, "invalid map_ptr to access map->key"); 9876 return -EFAULT; 9877 } 9878 key_size = meta->map.ptr->key_size; 9879 err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, meta, 9880 NULL); 9881 if (err) 9882 return err; 9883 if (can_elide_value_nullness(meta->map.ptr)) { 9884 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 9885 if (err < 0) { 9886 meta->const_map_key = -1; 9887 if (err == -EOPNOTSUPP) 9888 err = 0; 9889 else 9890 return err; 9891 } 9892 } 9893 break; 9894 case ARG_PTR_TO_MAP_VALUE: 9895 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 9896 return 0; 9897 9898 /* bpf_map_xxx(..., map_ptr, ..., value) call: 9899 * check [value, value + map->value_size) validity 9900 */ 9901 if (!meta->map.ptr) { 9902 /* kernel subsystem misconfigured verifier */ 9903 verifier_bug(env, "invalid map_ptr to access map->value"); 9904 return -EFAULT; 9905 } 9906 9907 err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size, 9908 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9909 false, meta, NULL); 9910 break; 9911 case ARG_PTR_TO_BTF_ID: 9912 case ARG_PTR_TO_BTF_ID_SOCK_COMMON: 9913 { 9914 const u32 *arg_btf_id = fn->arg_btf_id[arg]; 9915 const struct btf *arg_btf = is_kfunc(meta) ? meta->btf : btf_vmlinux; 9916 enum bpf_reg_type reg_type; 9917 9918 if (!meta->btf) { 9919 const struct bpf_reg_types *compatible; 9920 9921 if (base_type(reg->type) != PTR_TO_BTF_ID) 9922 break; 9923 9924 if (is_helper_call(meta, BPF_FUNC_kptr_xchg)) 9925 return map_kptr_match_type(env, meta->kptr_field, reg, regno) ? 9926 -EACCES : 0; 9927 9928 if (!arg_btf_id) { 9929 compatible = compatible_reg_types[base_type(arg_type)]; 9930 if (!compatible->btf_id) { 9931 verifier_bug(env, "missing arg compatible BTF ID"); 9932 return -EFAULT; 9933 } 9934 arg_btf_id = compatible->btf_id; 9935 } 9936 if (arg_btf_id == BPF_PTR_POISON) { 9937 verbose(env, "verifier internal error:"); 9938 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 9939 reg_arg_name(env, argno)); 9940 return -EACCES; 9941 } 9942 } 9943 9944 reg_type = reg->type & ~(arg_type & PTR_MAYBE_NULL); 9945 if ((arg_type & PTR_TRUSTED) && 9946 (!is_trusted_reg_type(env, reg, reg_type) || 9947 bpf_type_has_unsafe_modifiers(reg_type))) { 9948 if (!(arg_type & MEM_RCU)) { 9949 const char *actual_type, *arg_name, *expected_type; 9950 9951 expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id); 9952 verbose(env, "%s must be referenced or trusted\n", 9953 reg_arg_name(env, argno)); 9954 arg_name = reg_arg_name(env, argno); 9955 actual_type = bpf_diag_reg_type_plain(env, reg->type); 9956 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 9957 "Pass a pointer acquired from a verifier-tracked source, or call this function only inside the required protection if it accepts RCU pointers.", 9958 "the function requires a trusted or resource-owning pointer to %s, but %s is %s", 9959 expected_type, arg_name, actual_type); 9960 return -EINVAL; 9961 } 9962 if (!is_rcu_reg(reg)) { 9963 const char *actual_type, *arg_name, *expected_type; 9964 9965 expected_type = bpf_diag_fmt_btf_type(env, arg_btf, *arg_btf_id); 9966 verbose(env, "%s must be a rcu pointer\n", 9967 reg_arg_name(env, argno)); 9968 arg_name = reg_arg_name(env, argno); 9969 actual_type = bpf_diag_reg_type_plain(env, reg->type); 9970 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 9971 "Use this function with a pointer that is valid in an RCU read lock region.", 9972 "the function requires an RCU-protected pointer to %s, but %s is %s", 9973 expected_type, arg_name, actual_type); 9974 return -EINVAL; 9975 } 9976 } 9977 9978 err = process_arg_ptr_to_btf_id(env, reg, argno, arg_type, arg_btf, 9979 *arg_btf_id, meta, insn_idx); 9980 if (err < 0) 9981 return err; 9982 break; 9983 } 9984 case ARG_PTR_TO_PERCPU_BTF_ID: 9985 if (!reg->btf_id) { 9986 verbose(env, "Helper has invalid btf_id in %s\n", reg_arg_name(env, argno)); 9987 return -EACCES; 9988 } 9989 meta->ret_btf = reg->btf; 9990 meta->ret_btf_id = reg->btf_id; 9991 break; 9992 case ARG_PTR_TO_SPIN_LOCK: 9993 if (in_rbtree_lock_required_cb(env)) { 9994 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 9995 return -EACCES; 9996 } 9997 if (is_helper_call(meta, BPF_FUNC_spin_lock)) { 9998 err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK); 9999 if (err) 10000 return err; 10001 } else if (is_helper_call(meta, BPF_FUNC_spin_unlock)) { 10002 err = process_spin_lock(env, reg, argno, 0); 10003 if (err) 10004 return err; 10005 } else { 10006 verifier_bug(env, "spin lock arg on unexpected helper"); 10007 return -EFAULT; 10008 } 10009 break; 10010 case ARG_PTR_TO_TIMER: 10011 err = process_timer_func(env, reg, argno, &meta->map); 10012 if (err) 10013 return err; 10014 break; 10015 case ARG_PTR_TO_CTX: 10016 if (is_bpf_cast_to_kern_ctx_kfunc(meta)) { 10017 err = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 10018 if (err < 0) 10019 return -EINVAL; 10020 meta->ret_btf_id = err; 10021 } 10022 break; 10023 case ARG_PTR_TO_ARENA: 10024 break; 10025 case ARG_PTR_TO_ALLOC_BTF_ID: 10026 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 10027 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 10028 verbose(env, "%s expected for bpf_obj_drop()\n", 10029 reg_arg_name(env, argno)); 10030 return -EINVAL; 10031 } 10032 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 10033 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 10034 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 10035 reg_arg_name(env, argno)); 10036 return -EINVAL; 10037 } 10038 } 10039 if (!reg_is_referenced(env, reg)) { 10040 verbose(env, "allocated object must be referenced\n"); 10041 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10042 "Pass the owned object pointer before it is released or transferred.", 10043 "the allocated object pointer in %s must still carry verifier-tracked ownership, but this pointer no longer owns a live resource", 10044 reg_arg_name(env, argno)); 10045 return -EINVAL; 10046 } 10047 if (meta->btf == btf_vmlinux) { 10048 meta->arg_btf = reg->btf; 10049 meta->arg_btf_id = reg->btf_id; 10050 } 10051 break; 10052 case ARG_PTR_TO_FUNC: 10053 meta->subprogno = reg->subprogno; 10054 break; 10055 case ARG_PTR_TO_MEM: 10056 { 10057 enum bpf_access_type access_type; 10058 bool known_memory; 10059 10060 /* The access to this pointer is only checked when we hit the 10061 * next is_mem_size argument below. 10062 */ 10063 if (!(arg_type & MEM_FIXED_SIZE)) 10064 break; 10065 10066 access_type = func_arg_access_type(arg_type); 10067 10068 err = check_mem_reg(env, reg, argno, arg_size, access_type, meta, &known_memory); 10069 if (err < 0) { 10070 if (known_memory) 10071 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10072 "Pass memory with at least the required number of accessible bytes and suitable read or write access.", 10073 "the function expects %u bytes of memory, but the verifier cannot prove that %s provides a range of that size with the required read or write access", 10074 arg_size, 10075 bpf_diag_reg_type_plain(env, reg->type)); 10076 else 10077 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10078 "Pass stack, map, context, or other verifier-known memory of the expected type and size, not an integer cast to a pointer.", 10079 "the function expects %u bytes of memory, but it is %s and not verifier-known memory", 10080 arg_size, 10081 bpf_diag_reg_type_plain(env, reg->type)); 10082 return err; 10083 } 10084 /* 10085 * PTR_TO_PACKET gets passed as PTR_TO_MEM, preventing us from adjusting 10086 * bounds tracking information. 10087 */ 10088 if (is_subprog(meta) && meta->subprog_may_change_pkt && 10089 (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))) { 10090 verbose(env, 10091 "cannot pass packet pointer %s to %s(): function may change packet data\n", 10092 reg_arg_name(env, argno), meta->func_name); 10093 return -EINVAL; 10094 } 10095 if (arg_type & MEM_ALIGNED) 10096 err = check_ptr_alignment(env, reg, 0, arg_size, true); 10097 break; 10098 } 10099 case ARG_CONST_MEM_SIZE: 10100 err = process_const_arg(env, reg, argno, meta); 10101 if (err < 0) { 10102 if (err == -EINVAL) 10103 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10104 "Pass a compile-time constant or a value the verifier can prove is constant at this call.", 10105 "the function requires this memory size to be a verifier-known constant, but %s is variable on this path", 10106 reg_arg_name(env, argno)); 10107 return err; 10108 } 10109 fallthrough; 10110 case ARG_MEM_SIZE: 10111 case ARG_MEM_SIZE_OR_ZERO: 10112 { 10113 struct bpf_reg_state *buff_reg = get_func_arg_reg(caller, regs, prev_slot); 10114 argno_t buff_argno = argno_from_arg(prev_slot + 1); 10115 enum bpf_mem_size_failure failure; 10116 const char *buff_arg, *size_arg; 10117 bool zero_size_allowed; 10118 u32 access_type; 10119 10120 if (meta->btf && bpf_register_is_null(buff_reg)) 10121 break; 10122 10123 access_type = func_arg_access_type(fn->arg_type[arg - 1]); 10124 10125 zero_size_allowed = meta->btf || base_type(arg_type) == ARG_MEM_SIZE_OR_ZERO; 10126 10127 err = check_mem_size_reg(env, buff_reg, reg, buff_argno, argno, 10128 access_type, zero_size_allowed, meta, &failure); 10129 if (!err) 10130 break; 10131 10132 buff_arg = bpf_diag_arg_name(env, buff_argno); 10133 size_arg = bpf_diag_arg_name(env, argno); 10134 verbose(env, "%s and ", reg_arg_name(env, buff_argno)); 10135 verbose(env, "%s memory, len pair leads to invalid memory access\n", 10136 reg_arg_name(env, argno)); 10137 if (failure == BPF_MEM_SIZE_FAIL_MEMORY) { 10138 bpf_diag_call_arg_fmt(env, insn_idx, buff_argno, meta->func_name, 10139 "Pass a stack, map, context, or other verifier-known memory pointer, and keep the paired length within that object.", 10140 "it is the memory pointer in a memory/length pair with %s, but %s does not provide a verifier-accessible range of the requested length", 10141 size_arg, buff_arg); 10142 } else if (failure == BPF_MEM_SIZE_FAIL_SIZE) { 10143 if (reg_smin(reg) < 0) 10144 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10145 "Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.", 10146 "the memory size in %s may be negative because its signed minimum is %lld", 10147 size_arg, reg_smin(reg)); 10148 else if (!zero_size_allowed && reg_umin(reg) == 0) 10149 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10150 "Ensure the memory size is non-zero before this call.", 10151 "the memory size in %s may be zero, but the function requires a non-zero size", 10152 size_arg); 10153 else 10154 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10155 "Constrain the memory size to a non-negative value smaller than BPF_MAX_VAR_SIZ before this call.", 10156 "the memory size in %s may reach %llu bytes, but variable memory accesses must stay below %u bytes", 10157 size_arg, reg_umax(reg), BPF_MAX_VAR_SIZ); 10158 } 10159 break; 10160 } 10161 case ARG_PTR_TO_DYNPTR: { 10162 if (is_bpf_dynptr_clone_kfunc(meta) && 10163 (arg_type & MEM_UNINIT)) { 10164 enum bpf_dynptr_type parent_type = meta->dynptr.type; 10165 10166 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 10167 verifier_bug(env, "no dynptr type for parent of clone"); 10168 return -EFAULT; 10169 } 10170 10171 arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 10172 } 10173 10174 err = process_dynptr_func(env, reg, argno, insn_idx, arg_type, meta); 10175 if (err) 10176 return err; 10177 if (!arg && is_kfunc_dynptr_write(meta)) 10178 meta->dynptr_write_type = meta->dynptr.type; 10179 break; 10180 } 10181 case ARG_PTR_TO_ITER: 10182 if (is_bpf_iter_css_task_new_kfunc(meta) && 10183 !check_css_task_iter_allowlist(env)) { 10184 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 10185 return -EINVAL; 10186 } 10187 err = process_iter_arg(env, reg, arg, argno, insn_idx, meta); 10188 if (err < 0) 10189 return err; 10190 break; 10191 case ARG_PTR_TO_LIST_HEAD: 10192 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 10193 !reg_is_referenced(env, reg)) { 10194 verbose(env, "allocated object must be referenced\n"); 10195 return -EINVAL; 10196 } 10197 err = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 10198 if (err < 0) 10199 return err; 10200 break; 10201 case ARG_PTR_TO_RB_ROOT: 10202 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 10203 !reg_is_referenced(env, reg)) { 10204 verbose(env, "allocated object must be referenced\n"); 10205 return -EINVAL; 10206 } 10207 err = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 10208 if (err < 0) 10209 return err; 10210 break; 10211 case ARG_PTR_TO_LIST_NODE: 10212 if (!(is_kfunc_arg_nonown_allowed(meta->btf, btf_arg) && 10213 type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg))) { 10214 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10215 verbose(env, "%s expected pointer to allocated object\n", 10216 reg_arg_name(env, argno)); 10217 return -EINVAL; 10218 } 10219 if (!reg_is_referenced(env, reg)) { 10220 verbose(env, "allocated object must be referenced\n"); 10221 return -EINVAL; 10222 } 10223 } 10224 err = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 10225 if (err < 0) 10226 return err; 10227 break; 10228 case ARG_PTR_TO_RB_NODE: 10229 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 10230 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10231 verbose(env, "%s expected pointer to allocated object\n", 10232 reg_arg_name(env, argno)); 10233 return -EINVAL; 10234 } 10235 if (!reg_is_referenced(env, reg)) { 10236 verbose(env, "allocated object must be referenced\n"); 10237 return -EINVAL; 10238 } 10239 } else { 10240 if (!type_is_non_owning_ref(reg->type) && 10241 !reg_is_referenced(env, reg)) { 10242 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", 10243 meta->func_name); 10244 return -EINVAL; 10245 } 10246 if (in_rbtree_lock_required_cb(env)) { 10247 verbose(env, "%s not allowed in rbtree cb\n", meta->func_name); 10248 return -EINVAL; 10249 } 10250 } 10251 err = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 10252 if (err < 0) 10253 return err; 10254 break; 10255 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 10256 if (meta->btf && is_kfunc_arg_scalar_with_name(meta->btf, btf_arg, 10257 "rdonly_buf_size")) 10258 meta->r0_rdonly = true; 10259 err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem); 10260 if (err < 0) { 10261 if (meta->btf && err == -EINVAL) 10262 bpf_diag_call_arg_fmt(env, insn_idx, argno, meta->func_name, 10263 "Pass a verifier-known constant size for this function's buffer argument.", 10264 "the function uses this argument as a return-buffer size, but %s is invalid or variable on this path", 10265 reg_arg_name(env, argno)); 10266 return err; 10267 } 10268 break; 10269 case ARG_PTR_TO_REFCOUNTED_KPTR: 10270 { 10271 struct btf_record *rec; 10272 10273 if (!type_is_non_owning_ref(reg->type) && reg_is_referenced(env, reg)) 10274 meta->arg_owning_ref = true; 10275 10276 rec = reg_btf_record(reg); 10277 if (!rec) { 10278 verifier_bug(env, "Couldn't find btf_record"); 10279 return -EFAULT; 10280 } 10281 10282 if (rec->refcount_off < 0) { 10283 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 10284 reg_arg_name(env, argno)); 10285 return -EINVAL; 10286 } 10287 10288 meta->arg_btf = reg->btf; 10289 meta->arg_btf_id = reg->btf_id; 10290 break; 10291 } 10292 case ARG_PTR_TO_CONST_STR: 10293 { 10294 err = check_arg_const_str(env, reg, argno); 10295 if (err) 10296 return err; 10297 break; 10298 } 10299 case ARG_PTR_TO_WORKQUEUE: 10300 err = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 10301 if (err < 0) 10302 return err; 10303 break; 10304 case ARG_PTR_TO_TASK_WORK: 10305 err = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 10306 if (err < 0) 10307 return err; 10308 break; 10309 case ARG_PTR_TO_RCU_HEAD: 10310 err = check_map_field_pointer(env, reg, argno, BPF_RCU_HEAD, &meta->map); 10311 if (err < 0) 10312 return err; 10313 break; 10314 case ARG_PTR_TO_IRQ_FLAG: 10315 err = process_irq_flag(env, reg, argno, meta); 10316 if (err < 0) 10317 return err; 10318 break; 10319 case ARG_PTR_TO_CTX_OUT: 10320 if (reg->mem_size != arg_size) { 10321 verbose(env, "%s expected %u bytes of ctx-provided memory, got %u\n", 10322 reg_arg_name(env, argno), arg_size, reg->mem_size); 10323 return -EINVAL; 10324 } 10325 break; 10326 case ARG_PTR_TO_RES_SPIN_LOCK: 10327 { 10328 int flags; 10329 10330 if (in_rbtree_lock_required_cb(env)) { 10331 verbose(env, "can't res_spin_{lock,unlock} in rbtree cb\n"); 10332 return -EACCES; 10333 } 10334 10335 flags = get_bpf_res_spin_lock_kfunc_flags(meta); 10336 if (!flags) 10337 return -EFAULT; 10338 err = process_spin_lock(env, reg, argno, flags); 10339 if (err < 0) 10340 return err; 10341 break; 10342 } 10343 case ARG_KPTR_XCHG_DEST: 10344 err = process_kptr_func(env, regno, meta); 10345 if (err) 10346 return err; 10347 break; 10348 } 10349 10350 return err; 10351 } 10352 10353 /* 10354 * The slots a parameter takes, from its BTF type. This has to agree with 10355 * btf_func_model_arg_slots(), which answers the same from the size the 10356 * func model recorded, or the verifier would check an argument at a slot 10357 * the JIT does not place it at. 10358 */ 10359 static u32 btf_arg_slots(const struct btf_type *t) 10360 { 10361 if (btf_type_is_int(t) || btf_type_is_struct(t)) 10362 return (t->size + BPF_REG_SIZE - 1) / BPF_REG_SIZE; 10363 return 1; 10364 } 10365 10366 static u32 btf_proto_slots(const struct btf *btf, const struct btf_type *func_proto) 10367 { 10368 const struct btf_param *args = btf_params(func_proto); 10369 u32 i, nargs = btf_type_vlen(func_proto), slots_used = 0; 10370 10371 for (i = 0; i < nargs; i++) 10372 slots_used += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL)); 10373 10374 return slots_used; 10375 } 10376 10377 /* The argument slot @slot holds an eightbyte of a by-value argument. */ 10378 static int check_arg_extra_slot(struct bpf_verifier_env *env, struct bpf_func_state *caller, 10379 u32 slot, struct bpf_call_arg_meta *meta) 10380 { 10381 struct bpf_reg_state *reg = get_func_arg_reg(caller, cur_regs(env), slot); 10382 argno_t argno = argno_from_arg(slot + 1); 10383 int regno = reg_from_argno(argno); 10384 int err; 10385 10386 if (regno >= 0) { 10387 err = check_reg_arg(env, regno, SRC_OP); 10388 if (err) 10389 return err; 10390 } 10391 10392 return check_reg_type(env, reg, argno, ARG_SCALAR, meta); 10393 } 10394 10395 static int check_func_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10396 int insn_idx) 10397 { 10398 u32 slot = 0, prev_slot = 0, proto_slots, nslots; 10399 struct bpf_func_state *caller = cur_func(env); 10400 const struct btf_param *args = NULL; 10401 u32 arg, nargs = MAX_BPF_FUNC_REG_ARGS; 10402 int err; 10403 10404 if (meta->btf) { 10405 args = btf_params(meta->func_proto); 10406 nargs = btf_type_vlen(meta->func_proto); 10407 } 10408 10409 /* 10410 * A by-value argument of more than one eightbyte takes a slot per 10411 * eightbyte, so the slots a call occupies are no longer its parameter 10412 * count. Only a proto whose parameters take a slot each can name the 10413 * argument a stack slot belongs to. 10414 */ 10415 proto_slots = meta->btf ? btf_proto_slots(meta->btf, meta->func_proto) : nargs; 10416 10417 if (proto_slots > MAX_BPF_FUNC_REG_ARGS) { 10418 err = check_outgoing_stack_args(env, caller, proto_slots, meta->func_name, 10419 meta->btf, proto_slots == nargs ? args : NULL); 10420 if (err) 10421 return err; 10422 } 10423 10424 for (arg = 0; arg < nargs; arg++, prev_slot = slot, slot += nslots) { 10425 const struct btf_type *t; 10426 u32 k; 10427 10428 nslots = 1; 10429 if (args) { 10430 t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL); 10431 nslots = btf_arg_slots(t); 10432 } 10433 10434 if (meta->fn->arg_type[arg] == ARG_UNUSED) 10435 break; 10436 err = check_func_arg(env, arg, slot, prev_slot, meta, insn_idx); 10437 if (err) 10438 return err; 10439 10440 /* 10441 * check_func_arg() took the first slot. A parameter of more 10442 * than one eightbyte is always a scalar, so every slot it 10443 * takes beyond the first holds one too. 10444 */ 10445 for (k = 1; k < nslots; k++) { 10446 err = check_arg_extra_slot(env, caller, slot + k, meta); 10447 if (err) 10448 return err; 10449 } 10450 } 10451 10452 return 0; 10453 } 10454 10455 static int mark_raw_stack(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10456 int insn_idx) 10457 { 10458 struct bpf_func_state *caller = cur_func(env); 10459 u32 slot; 10460 int i, err; 10461 10462 /* 10463 * Validate every argument before initializing outputs: an input argument 10464 * may alias an output buffer. Use the normal stack-write checks to discard 10465 * stale spills and preserve the rules for special stack objects. 10466 */ 10467 for (slot = 0; slot < MAX_BPF_FUNC_ARGS; slot++) { 10468 struct bpf_reg_state *reg; 10469 argno_t argno = argno_from_arg(slot + 1); 10470 10471 if (!meta->arg_raw_mem.size[slot]) 10472 continue; 10473 reg = get_func_arg_reg(caller, cur_regs(env), slot); 10474 10475 for (i = 0; i < meta->arg_raw_mem.size[slot]; i++) { 10476 err = check_mem_access(env, insn_idx, reg, argno, i, BPF_B, 10477 BPF_WRITE, -1, false, false); 10478 if (err) 10479 return err; 10480 } 10481 } 10482 10483 return 0; 10484 } 10485 10486 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 10487 { 10488 enum bpf_attach_type eatype = env->prog->expected_attach_type; 10489 enum bpf_prog_type type = resolve_prog_type(env->prog); 10490 10491 if (func_id != BPF_FUNC_map_update_elem && 10492 func_id != BPF_FUNC_map_delete_elem) 10493 return false; 10494 10495 /* It's not possible to get access to a locked struct sock in these 10496 * contexts, so updating is safe. 10497 */ 10498 switch (type) { 10499 case BPF_PROG_TYPE_TRACING: 10500 if (eatype == BPF_TRACE_ITER) 10501 return true; 10502 break; 10503 case BPF_PROG_TYPE_SOCK_OPS: 10504 /* map_update allowed only via dedicated helpers with event type checks */ 10505 if (func_id == BPF_FUNC_map_delete_elem) 10506 return true; 10507 break; 10508 case BPF_PROG_TYPE_SK_REUSEPORT: 10509 case BPF_PROG_TYPE_SK_LOOKUP: 10510 return true; 10511 default: 10512 break; 10513 } 10514 10515 verbose(env, "cannot update sockmap in this context\n"); 10516 return false; 10517 } 10518 10519 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 10520 { 10521 return env->prog->jit_requested && 10522 bpf_jit_supports_subprog_tailcalls(); 10523 } 10524 10525 /* 10526 * Is rcu_read_lock_held() true at run time? Unlike for in_rcu_cs(), disabled 10527 * preemption or interrupts will not do. 10528 */ 10529 static bool has_rcu_read_lock(struct bpf_verifier_env *env) 10530 { 10531 struct bpf_verifier_state *state = env->cur_state; 10532 10533 if (state->active_rcu_locks || in_rcu_callback(env)) 10534 return true; 10535 if (in_sleepable(env)) 10536 return false; 10537 return !env->no_rcu_read_lock || state->frame[0]->in_async_callback_fn; 10538 } 10539 10540 /* May the map be used outside of an RCU read side critical section? */ 10541 static bool map_needs_no_rcu(const struct bpf_map *map) 10542 { 10543 switch (map->map_type) { 10544 case BPF_MAP_TYPE_HASH: 10545 case BPF_MAP_TYPE_RHASH: 10546 case BPF_MAP_TYPE_LRU_HASH: 10547 case BPF_MAP_TYPE_ARRAY: 10548 case BPF_MAP_TYPE_PERCPU_HASH: 10549 case BPF_MAP_TYPE_PERCPU_ARRAY: 10550 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 10551 case BPF_MAP_TYPE_LPM_TRIE: 10552 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 10553 case BPF_MAP_TYPE_HASH_OF_MAPS: 10554 case BPF_MAP_TYPE_RINGBUF: 10555 case BPF_MAP_TYPE_USER_RINGBUF: 10556 case BPF_MAP_TYPE_INODE_STORAGE: 10557 case BPF_MAP_TYPE_SK_STORAGE: 10558 case BPF_MAP_TYPE_TASK_STORAGE: 10559 case BPF_MAP_TYPE_CGRP_STORAGE: 10560 case BPF_MAP_TYPE_QUEUE: 10561 case BPF_MAP_TYPE_STACK: 10562 case BPF_MAP_TYPE_ARENA: 10563 case BPF_MAP_TYPE_INSN_ARRAY: 10564 case BPF_MAP_TYPE_PROG_ARRAY: 10565 case BPF_MAP_TYPE_BLOOM_FILTER: 10566 return true; 10567 default: 10568 return false; 10569 } 10570 } 10571 10572 static int check_map_func_compatibility(struct bpf_verifier_env *env, 10573 struct bpf_map *map, int func_id) 10574 { 10575 if (!map) 10576 return 0; 10577 10578 /* 10579 * check_map_prog_compatibility() asks the program. That misses the 10580 * sleepable callback of another program, and an inner map. They may 10581 * use any map under the RCU read lock. Disabled preemption or 10582 * interrupts will not do: the maps ask for rcu_read_lock_held(). 10583 */ 10584 if (!has_rcu_read_lock(env) && !map_needs_no_rcu(map)) { 10585 verbose(env, "map '%s' needs bpf_rcu_read_lock() in sleepable context\n", 10586 map->name); 10587 return -EINVAL; 10588 } 10589 10590 /* We need a two way check, first is from map perspective ... */ 10591 switch (map->map_type) { 10592 case BPF_MAP_TYPE_PROG_ARRAY: 10593 if (func_id != BPF_FUNC_tail_call) 10594 goto error; 10595 break; 10596 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 10597 if (func_id != BPF_FUNC_perf_event_read && 10598 func_id != BPF_FUNC_perf_event_output && 10599 func_id != BPF_FUNC_skb_output && 10600 func_id != BPF_FUNC_perf_event_read_value && 10601 func_id != BPF_FUNC_xdp_output) 10602 goto error; 10603 break; 10604 case BPF_MAP_TYPE_RINGBUF: 10605 if (func_id != BPF_FUNC_ringbuf_output && 10606 func_id != BPF_FUNC_ringbuf_reserve && 10607 func_id != BPF_FUNC_ringbuf_query && 10608 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 10609 func_id != BPF_FUNC_ringbuf_submit_dynptr && 10610 func_id != BPF_FUNC_ringbuf_discard_dynptr) 10611 goto error; 10612 break; 10613 case BPF_MAP_TYPE_USER_RINGBUF: 10614 if (func_id != BPF_FUNC_user_ringbuf_drain) 10615 goto error; 10616 break; 10617 case BPF_MAP_TYPE_STACK_TRACE: 10618 if (func_id != BPF_FUNC_get_stackid) 10619 goto error; 10620 break; 10621 case BPF_MAP_TYPE_CGROUP_ARRAY: 10622 if (func_id != BPF_FUNC_skb_under_cgroup && 10623 func_id != BPF_FUNC_current_task_under_cgroup) 10624 goto error; 10625 break; 10626 case BPF_MAP_TYPE_CGROUP_STORAGE: 10627 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 10628 if (func_id != BPF_FUNC_get_local_storage) 10629 goto error; 10630 break; 10631 case BPF_MAP_TYPE_DEVMAP: 10632 case BPF_MAP_TYPE_DEVMAP_HASH: 10633 if (func_id != BPF_FUNC_redirect_map && 10634 func_id != BPF_FUNC_map_lookup_elem) 10635 goto error; 10636 break; 10637 /* Restrict bpf side of cpumap and xskmap, open when use-cases 10638 * appear. 10639 */ 10640 case BPF_MAP_TYPE_CPUMAP: 10641 if (func_id != BPF_FUNC_redirect_map) 10642 goto error; 10643 break; 10644 case BPF_MAP_TYPE_XSKMAP: 10645 if (func_id != BPF_FUNC_redirect_map && 10646 func_id != BPF_FUNC_map_lookup_elem) 10647 goto error; 10648 break; 10649 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 10650 case BPF_MAP_TYPE_HASH_OF_MAPS: 10651 if (func_id != BPF_FUNC_map_lookup_elem) 10652 goto error; 10653 break; 10654 case BPF_MAP_TYPE_SOCKMAP: 10655 if (func_id != BPF_FUNC_sk_redirect_map && 10656 func_id != BPF_FUNC_sock_map_update && 10657 func_id != BPF_FUNC_msg_redirect_map && 10658 func_id != BPF_FUNC_sk_select_reuseport && 10659 func_id != BPF_FUNC_map_lookup_elem && 10660 !may_update_sockmap(env, func_id)) 10661 goto error; 10662 break; 10663 case BPF_MAP_TYPE_SOCKHASH: 10664 if (func_id != BPF_FUNC_sk_redirect_hash && 10665 func_id != BPF_FUNC_sock_hash_update && 10666 func_id != BPF_FUNC_msg_redirect_hash && 10667 func_id != BPF_FUNC_sk_select_reuseport && 10668 func_id != BPF_FUNC_map_lookup_elem && 10669 !may_update_sockmap(env, func_id)) 10670 goto error; 10671 break; 10672 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 10673 if (func_id != BPF_FUNC_sk_select_reuseport) 10674 goto error; 10675 break; 10676 case BPF_MAP_TYPE_QUEUE: 10677 case BPF_MAP_TYPE_STACK: 10678 if (func_id != BPF_FUNC_map_peek_elem && 10679 func_id != BPF_FUNC_map_pop_elem && 10680 func_id != BPF_FUNC_map_push_elem) 10681 goto error; 10682 break; 10683 case BPF_MAP_TYPE_SK_STORAGE: 10684 if (func_id != BPF_FUNC_sk_storage_get && 10685 func_id != BPF_FUNC_sk_storage_delete && 10686 func_id != BPF_FUNC_kptr_xchg) 10687 goto error; 10688 break; 10689 case BPF_MAP_TYPE_INODE_STORAGE: 10690 if (func_id != BPF_FUNC_inode_storage_get && 10691 func_id != BPF_FUNC_inode_storage_delete && 10692 func_id != BPF_FUNC_kptr_xchg) 10693 goto error; 10694 break; 10695 case BPF_MAP_TYPE_TASK_STORAGE: 10696 if (func_id != BPF_FUNC_task_storage_get && 10697 func_id != BPF_FUNC_task_storage_delete && 10698 func_id != BPF_FUNC_kptr_xchg) 10699 goto error; 10700 break; 10701 case BPF_MAP_TYPE_CGRP_STORAGE: 10702 if (func_id != BPF_FUNC_cgrp_storage_get && 10703 func_id != BPF_FUNC_cgrp_storage_delete && 10704 func_id != BPF_FUNC_kptr_xchg) 10705 goto error; 10706 break; 10707 case BPF_MAP_TYPE_BLOOM_FILTER: 10708 if (func_id != BPF_FUNC_map_peek_elem && 10709 func_id != BPF_FUNC_map_push_elem) 10710 goto error; 10711 break; 10712 case BPF_MAP_TYPE_INSN_ARRAY: 10713 goto error; 10714 default: 10715 break; 10716 } 10717 10718 /* ... and second from the function itself. */ 10719 switch (func_id) { 10720 case BPF_FUNC_tail_call: 10721 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 10722 goto error; 10723 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 10724 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 10725 return -EINVAL; 10726 } 10727 break; 10728 case BPF_FUNC_perf_event_read: 10729 case BPF_FUNC_perf_event_output: 10730 case BPF_FUNC_perf_event_read_value: 10731 case BPF_FUNC_skb_output: 10732 case BPF_FUNC_xdp_output: 10733 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 10734 goto error; 10735 break; 10736 case BPF_FUNC_ringbuf_output: 10737 case BPF_FUNC_ringbuf_reserve: 10738 case BPF_FUNC_ringbuf_query: 10739 case BPF_FUNC_ringbuf_reserve_dynptr: 10740 case BPF_FUNC_ringbuf_submit_dynptr: 10741 case BPF_FUNC_ringbuf_discard_dynptr: 10742 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 10743 goto error; 10744 break; 10745 case BPF_FUNC_user_ringbuf_drain: 10746 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 10747 goto error; 10748 break; 10749 case BPF_FUNC_get_stackid: 10750 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 10751 goto error; 10752 break; 10753 case BPF_FUNC_current_task_under_cgroup: 10754 case BPF_FUNC_skb_under_cgroup: 10755 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 10756 goto error; 10757 break; 10758 case BPF_FUNC_redirect_map: 10759 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 10760 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 10761 map->map_type != BPF_MAP_TYPE_CPUMAP && 10762 map->map_type != BPF_MAP_TYPE_XSKMAP) 10763 goto error; 10764 break; 10765 case BPF_FUNC_sk_redirect_map: 10766 case BPF_FUNC_msg_redirect_map: 10767 case BPF_FUNC_sock_map_update: 10768 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 10769 goto error; 10770 break; 10771 case BPF_FUNC_sk_redirect_hash: 10772 case BPF_FUNC_msg_redirect_hash: 10773 case BPF_FUNC_sock_hash_update: 10774 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 10775 goto error; 10776 break; 10777 case BPF_FUNC_get_local_storage: 10778 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 10779 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 10780 goto error; 10781 break; 10782 case BPF_FUNC_sk_select_reuseport: 10783 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 10784 map->map_type != BPF_MAP_TYPE_SOCKMAP && 10785 map->map_type != BPF_MAP_TYPE_SOCKHASH) 10786 goto error; 10787 break; 10788 case BPF_FUNC_map_pop_elem: 10789 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10790 map->map_type != BPF_MAP_TYPE_STACK) 10791 goto error; 10792 break; 10793 case BPF_FUNC_map_peek_elem: 10794 case BPF_FUNC_map_push_elem: 10795 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10796 map->map_type != BPF_MAP_TYPE_STACK && 10797 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 10798 goto error; 10799 break; 10800 case BPF_FUNC_map_lookup_percpu_elem: 10801 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 10802 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 10803 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 10804 goto error; 10805 break; 10806 case BPF_FUNC_sk_storage_get: 10807 case BPF_FUNC_sk_storage_delete: 10808 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 10809 goto error; 10810 break; 10811 case BPF_FUNC_inode_storage_get: 10812 case BPF_FUNC_inode_storage_delete: 10813 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 10814 goto error; 10815 break; 10816 case BPF_FUNC_task_storage_get: 10817 case BPF_FUNC_task_storage_delete: 10818 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 10819 goto error; 10820 break; 10821 case BPF_FUNC_cgrp_storage_get: 10822 case BPF_FUNC_cgrp_storage_delete: 10823 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 10824 goto error; 10825 break; 10826 default: 10827 break; 10828 } 10829 10830 return 0; 10831 error: 10832 verbose(env, "cannot pass map_type %d into func %s#%d\n", 10833 map->map_type, func_id_name(func_id), func_id); 10834 return -EINVAL; 10835 } 10836 10837 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 10838 { 10839 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 10840 bool has_size = fn->arg_size[arg] != 0; 10841 bool is_next_size = false; 10842 10843 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 10844 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 10845 10846 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 10847 return is_next_size; 10848 10849 return has_size == is_next_size || is_next_size == is_fixed; 10850 } 10851 10852 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 10853 { 10854 /* bpf_xxx(..., buf, len) call will access 'len' 10855 * bytes from memory 'buf'. Both arg types need 10856 * to be paired, so make sure there's no buggy 10857 * helper function specification. 10858 */ 10859 if (arg_type_is_mem_size(fn->arg1_type) || 10860 check_args_pair_invalid(fn, 0) || 10861 check_args_pair_invalid(fn, 1) || 10862 check_args_pair_invalid(fn, 2) || 10863 check_args_pair_invalid(fn, 3) || 10864 check_args_pair_invalid(fn, 4)) 10865 return false; 10866 10867 return true; 10868 } 10869 10870 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 10871 { 10872 int i; 10873 10874 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 10875 if (fn->arg_type[i] == ARG_UNUSED) 10876 break; 10877 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 10878 return !!fn->arg_btf_id[i]; 10879 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 10880 return fn->arg_btf_id[i] == BPF_PTR_POISON; 10881 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 10882 /* arg_btf_id and arg_size are in a union. */ 10883 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 10884 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 10885 return false; 10886 } 10887 10888 return true; 10889 } 10890 10891 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 10892 { 10893 int i; 10894 10895 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 10896 enum bpf_arg_type arg_type = fn->arg_type[i]; 10897 10898 if (arg_type == ARG_UNUSED) 10899 break; 10900 if (base_type(arg_type) != ARG_PTR_TO_MEM) 10901 continue; 10902 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 10903 return false; 10904 } 10905 10906 return true; 10907 } 10908 10909 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 10910 { 10911 int i; 10912 10913 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 10914 enum bpf_arg_type arg_type = fn->arg_type[i]; 10915 10916 if (arg_type == ARG_UNUSED) 10917 break; 10918 if (arg_type_is_release(arg_type)) { 10919 if (meta->release_regno) 10920 return false; 10921 meta->release_regno = i + 1; 10922 } 10923 } 10924 10925 return true; 10926 } 10927 10928 static bool check_arg_prog_aux(struct bpf_verifier_env *env, 10929 const struct bpf_func_proto *proto) 10930 { 10931 bool seen = false; 10932 argno_t argno; 10933 u32 i; 10934 10935 for (i = 0; i < ARRAY_SIZE(proto->arg_type); i++) { 10936 if (proto->arg_type[i] == ARG_UNUSED) 10937 break; 10938 if (proto->arg_type[i] != ARG_PTR_TO_PROG_AUX) 10939 continue; 10940 10941 if (seen) { 10942 verifier_bug(env, "Only 1 prog->aux argument supported"); 10943 return false; 10944 } 10945 10946 argno = argno_from_arg(i + 1); 10947 if (reg_from_argno(argno) < 0) { 10948 verbose(env, "%s prog->aux cannot be a stack argument\n", 10949 reg_arg_name(env, argno)); 10950 return false; 10951 } 10952 10953 seen = true; 10954 } 10955 10956 return true; 10957 } 10958 10959 static int check_func_proto(struct bpf_verifier_env *env, const struct bpf_func_proto *fn, 10960 struct bpf_call_arg_meta *meta) 10961 { 10962 return check_arg_prog_aux(env, fn) && 10963 check_arg_pair_ok(fn) && 10964 check_mem_arg_rw_flag_ok(fn) && 10965 check_proto_release_reg(fn, meta) && 10966 check_btf_id_ok(fn) ? 0 : -EINVAL; 10967 } 10968 10969 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 10970 * are now invalid, so turn them into unknown SCALAR_VALUE. 10971 * 10972 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 10973 * since these slices point to packet data. 10974 */ 10975 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 10976 { 10977 struct bpf_func_state *state; 10978 struct bpf_reg_state *reg; 10979 10980 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10981 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) { 10982 bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_PKT_DATA_CHANGE); 10983 mark_reg_invalid(env, reg); 10984 } 10985 })); 10986 } 10987 10988 static bool holds_pkt_pointers(struct bpf_verifier_env *env) 10989 { 10990 struct bpf_func_state *state; 10991 struct bpf_reg_state *reg; 10992 bool ret = false; 10993 10994 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10995 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 10996 ret = true; 10997 })); 10998 10999 return ret; 11000 } 11001 11002 enum { 11003 AT_PKT_END = -1, 11004 BEYOND_PKT_END = -2, 11005 }; 11006 11007 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 11008 { 11009 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11010 struct bpf_reg_state *reg = &state->regs[regn]; 11011 11012 if (reg->type != PTR_TO_PACKET) 11013 /* PTR_TO_PACKET_META is not supported yet */ 11014 return; 11015 11016 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 11017 * How far beyond pkt_end it goes is unknown. 11018 * if (!range_open) it's the case of pkt >= pkt_end 11019 * if (range_open) it's the case of pkt > pkt_end 11020 * hence this pointer is at least 1 byte bigger than pkt_end 11021 */ 11022 if (range_open) 11023 reg->range = BEYOND_PKT_END; 11024 else 11025 reg->range = AT_PKT_END; 11026 } 11027 11028 static int __release_reference_nomark(struct bpf_verifier_state *state, int id) 11029 { 11030 int i; 11031 11032 for (i = 0; i < state->acquired_refs; i++) { 11033 if (state->refs[i].type != REF_TYPE_PTR) 11034 continue; 11035 if (state->refs[i].id == id) { 11036 release_reference_state(state, i); 11037 return 0; 11038 } 11039 } 11040 return -EINVAL; 11041 } 11042 11043 static int release_reference_nomark(struct bpf_verifier_env *env, int id) 11044 { 11045 int err; 11046 11047 err = __release_reference_nomark(env->cur_state, id); 11048 if (!err) 11049 bpf_diag_record_ref_release(env, env->insn_idx, id); 11050 return err; 11051 } 11052 11053 static int idstack_push(struct bpf_idmap *idmap, u32 id) 11054 { 11055 int i; 11056 11057 if (!id) 11058 return 0; 11059 11060 for (i = 0; i < idmap->cnt; i++) 11061 if (idmap->map[i].old == id) 11062 return 0; 11063 11064 if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE)) 11065 return -EFAULT; 11066 11067 idmap->map[idmap->cnt++].old = id; 11068 return 0; 11069 } 11070 11071 static int idstack_pop(struct bpf_idmap *idmap) 11072 { 11073 if (!idmap->cnt) 11074 return 0; 11075 11076 return idmap->map[--idmap->cnt].old; 11077 } 11078 11079 /* Invalidate id and objects derived from it iteratively in a DFS manner */ 11080 static int invalidate_reference(struct bpf_verifier_env *env, int id) 11081 { 11082 u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); 11083 struct bpf_verifier_state *vstate = env->cur_state; 11084 struct bpf_idmap *idstack = &env->idmap_scratch; 11085 struct bpf_stack_state *stack; 11086 struct bpf_func_state *state; 11087 struct bpf_reg_state *reg; 11088 int i, err; 11089 11090 idstack->cnt = 0; 11091 err = idstack_push(idstack, id); 11092 if (err) 11093 return err; 11094 11095 while ((id = idstack_pop(idstack))) { 11096 /* 11097 * Child references are inaccessible after parent is released, 11098 * any child references that exist at this point are a leak. 11099 */ 11100 for (i = 0; i < vstate->acquired_refs; i++) { 11101 if (vstate->refs[i].type != REF_TYPE_PTR) 11102 continue; 11103 if (vstate->refs[i].parent_id != id) 11104 continue; 11105 verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n", 11106 vstate->refs[i].id, vstate->refs[i].insn_idx); 11107 return -EINVAL; 11108 } 11109 11110 bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ 11111 if (reg->id != id && reg->parent_id != id) 11112 continue; 11113 11114 /* Free objects derived from the current object */ 11115 if (reg->parent_id == id) { 11116 err = idstack_push(idstack, reg->id); 11117 if (err) 11118 return err; 11119 } 11120 11121 /* 11122 * A dynptr occupies two stack slots that invalidate_dynptr() 11123 * clears together. Record both scrubs before invalidating it. 11124 */ 11125 if (stack && stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) { 11126 struct bpf_stack_state *dyn_stack = stack; 11127 11128 if (reg->dynptr.first_slot) 11129 dyn_stack--; 11130 bpf_diag_record_scrub(env, &dyn_stack[0].spilled_ptr, 11131 BPF_DIAG_MOD_REF_RELEASE); 11132 bpf_diag_record_scrub(env, &dyn_stack[1].spilled_ptr, 11133 BPF_DIAG_MOD_REF_RELEASE); 11134 invalidate_dynptr(env, dyn_stack); 11135 continue; 11136 } 11137 bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_REF_RELEASE); 11138 if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL) 11139 mark_reg_invalid(env, reg); 11140 })); 11141 } 11142 11143 return 0; 11144 } 11145 11146 static int release_reference(struct bpf_verifier_env *env, int id) 11147 { 11148 if (find_reference_state(env->cur_state, id)) 11149 WARN_ON_ONCE(release_reference_nomark(env, id)); 11150 11151 return invalidate_reference(env, id); 11152 } 11153 11154 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 11155 { 11156 struct bpf_func_state *unused; 11157 struct bpf_reg_state *reg; 11158 11159 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11160 if (type_is_non_owning_ref(reg->type)) { 11161 bpf_diag_record_scrub(env, reg, BPF_DIAG_MOD_NON_OWN_REF); 11162 mark_reg_invalid(env, reg); 11163 } 11164 })); 11165 } 11166 11167 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env) 11168 { 11169 struct bpf_stack_state *stack; 11170 struct bpf_func_state *state; 11171 struct bpf_reg_state *reg; 11172 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 11173 11174 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({ 11175 if (reg->type & MEM_RCU) { 11176 bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE); 11177 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL | NON_OWN_REF); 11178 reg->type |= PTR_UNTRUSTED; 11179 bpf_diag_mod_end(env); 11180 } 11181 })); 11182 } 11183 11184 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id) 11185 { 11186 struct bpf_func_state *state; 11187 struct bpf_reg_state *reg; 11188 int err; 11189 11190 err = release_reference_nomark(env, id); 11191 if (err) 11192 return err; 11193 11194 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11195 if (reg->id != id) 11196 continue; 11197 if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 11198 bpf_diag_mod_begin(env, reg, NULL, BPF_DIAG_MOD_WRITE); 11199 if (!type_may_be_null(reg->type)) 11200 reg->id = 0; 11201 reg->type &= ~MEM_ALLOC; 11202 reg->type |= MEM_RCU; 11203 bpf_diag_mod_end(env); 11204 } 11205 })); 11206 11207 return err; 11208 } 11209 11210 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 11211 struct bpf_reg_state *regs) 11212 { 11213 int i; 11214 11215 bpf_diag_record_caller_saved(env, regs); 11216 11217 /* after the call registers r0 - r5 were scratched */ 11218 for (i = 0; i < CALLER_SAVED_REGS; i++) { 11219 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 11220 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 11221 } 11222 } 11223 11224 static void invalidate_outgoing_stack_args(struct bpf_verifier_env *env, 11225 struct bpf_func_state *state) 11226 { 11227 int i, nslots = state->out_stack_arg_cnt; 11228 11229 for (i = 0; i < nslots; i++) { 11230 bpf_diag_record_scrub(env, &state->stack_arg_regs[i], BPF_DIAG_MOD_CALLER_SAVED); 11231 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 11232 } 11233 } 11234 11235 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 11236 struct bpf_func_state *caller, 11237 struct bpf_func_state *callee, 11238 int insn_idx); 11239 11240 static int set_callee_state(struct bpf_verifier_env *env, 11241 struct bpf_func_state *caller, 11242 struct bpf_func_state *callee, int insn_idx); 11243 11244 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 11245 set_callee_state_fn set_callee_state_cb, 11246 struct bpf_verifier_state *state) 11247 { 11248 struct bpf_func_state *caller, *callee; 11249 int err; 11250 11251 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 11252 verbose(env, "the call stack of %d frames is too deep\n", 11253 state->curframe + 2); 11254 return -E2BIG; 11255 } 11256 11257 if (state->frame[state->curframe + 1]) { 11258 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 11259 return -EFAULT; 11260 } 11261 11262 caller = state->frame[state->curframe]; 11263 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 11264 if (!callee) 11265 return -ENOMEM; 11266 state->frame[state->curframe + 1] = callee; 11267 11268 /* callee cannot access r0, r6 - r9 for reading and has to write 11269 * into its own stack before reading from it. 11270 * callee can read/write into caller's stack 11271 */ 11272 init_func_state(env, callee, 11273 /* remember the callsite, it will be used by bpf_exit */ 11274 callsite, 11275 state->curframe + 1 /* frameno within this callchain */, 11276 subprog /* subprog number within this prog */); 11277 err = set_callee_state_cb(env, caller, callee, callsite); 11278 if (err) 11279 goto err_out; 11280 11281 /* only increment it after check_reg_arg() finished */ 11282 state->curframe++; 11283 11284 return 0; 11285 11286 err_out: 11287 free_func_state(callee); 11288 state->frame[state->curframe + 1] = NULL; 11289 return err; 11290 } 11291 11292 static void gen_subprog_arg_proto(const struct bpf_subprog_info *sub, const struct btf *btf, 11293 const struct btf_type *func_proto, struct bpf_func_proto *proto) 11294 { 11295 const struct btf_param *args = btf_params(func_proto); 11296 u32 arg, slot = 0; 11297 11298 memset(proto, 0, sizeof(*proto)); 11299 for (arg = 0; arg < btf_type_vlen(func_proto); arg++) { 11300 enum bpf_arg_type arg_type = sub->args[slot].arg_type; 11301 const struct btf_type *t; 11302 11303 if (arg_type & PTR_UNTRUSTED) { 11304 /* 11305 * An __arg_untrusted argument accepts any caller value. The 11306 * callee treats it as read-only and uses probe-read instructions 11307 * to protect against invalid memory access. 11308 */ 11309 arg_type = ARG_IGNORE; 11310 } else if (base_type(arg_type) == ARG_PTR_TO_ARENA) { 11311 arg_type |= PTR_MAYBE_NULL; 11312 } else if (base_type(arg_type) == ARG_PTR_TO_MEM) { 11313 proto->arg_size[arg] = sub->args[slot].mem_size; 11314 arg_type |= MEM_FIXED_SIZE | MEM_WRITE; 11315 } else if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) { 11316 proto->arg_btf_id[arg] = &sub->args[slot].btf_id; 11317 } 11318 proto->arg_type[arg] = arg_type; 11319 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 11320 slot += btf_arg_slots(t); 11321 } 11322 } 11323 11324 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, struct btf *btf) 11325 { 11326 struct bpf_subprog_info *sub = subprog_info(env, subprog); 11327 struct bpf_func_state *caller = cur_func(env); 11328 const struct btf_type *func, *func_proto; 11329 struct bpf_call_arg_meta meta; 11330 struct bpf_func_proto *fn; 11331 int ret, err; 11332 u32 i; 11333 11334 memset(&meta, 0, sizeof(meta)); 11335 meta.btf = btf; 11336 meta.subprog_may_change_pkt = sub->changes_pkt_data; 11337 meta.func_name = bpf_subprog_name(env, subprog); 11338 11339 ret = btf_prepare_func_args(env, subprog); 11340 if (ret) { 11341 if (bpf_in_stack_arg_cnt(sub) > 0) { 11342 err = check_outgoing_stack_args(env, caller, sub->arg_slot_cnt, 11343 bpf_subprog_name(env, subprog), 11344 NULL, NULL); 11345 if (err) 11346 return err; 11347 } 11348 return ret; 11349 } 11350 11351 func = btf_type_by_id(btf, env->prog->aux->func_info[subprog].type_id); 11352 func_proto = btf_type_by_id(btf, func->type); 11353 11354 fn = &env->bpf_subprog_scratch; 11355 gen_subprog_arg_proto(sub, btf, func_proto, fn); 11356 meta.fn = fn; 11357 meta.func_proto = func_proto; 11358 11359 /* 11360 * Check if all register arguments declared in BTF are initialized. 11361 * If they aren't the BTF is unreliable. 11362 */ 11363 if (!bpf_subprog_is_global(env, subprog)) { 11364 for (i = 0; i < min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++) 11365 if (caller->regs[BPF_REG_1 + i].type == NOT_INIT) 11366 return -EINVAL; 11367 } 11368 return check_func_args(env, &meta, env->insn_idx); 11369 } 11370 11371 /* 11372 * Check that call-site argument states match a subprog's BTF signature. 11373 * 11374 * Returns: 11375 * EFAULT - there is a verifier bug. Abort verification. 11376 * Other errors - there is a type mismatch or BTF is not available. 11377 * 0 - BTF matches with what bpf_reg_state expects. 11378 */ 11379 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog) 11380 { 11381 struct bpf_prog *prog = env->prog; 11382 struct btf *btf = prog->aux->btf; 11383 u32 btf_id; 11384 int err; 11385 11386 if (!prog->aux->func_info) 11387 return -EINVAL; 11388 11389 btf_id = prog->aux->func_info[subprog].type_id; 11390 if (!btf_id) 11391 return -EFAULT; 11392 11393 if (prog->aux->func_info_aux[subprog].unreliable) 11394 return -EINVAL; 11395 11396 err = btf_check_func_arg_match(env, subprog, btf); 11397 /* Compiler optimizations can remove arguments from static functions 11398 * or mismatched type can be passed into a global function. 11399 * In such cases mark the function as unreliable from BTF point of view. 11400 */ 11401 if (err) 11402 prog->aux->func_info_aux[subprog].unreliable = true; 11403 return err; 11404 } 11405 11406 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11407 int insn_idx, int subprog, 11408 set_callee_state_fn set_callee_state_cb) 11409 { 11410 struct bpf_verifier_state *state = env->cur_state, *callback_state; 11411 struct bpf_func_state *caller, *callee; 11412 int err; 11413 11414 caller = state->frame[state->curframe]; 11415 err = btf_check_subprog_call(env, subprog); 11416 if (err == -EFAULT) 11417 return err; 11418 if (bpf_in_stack_arg_cnt(&env->subprog_info[subprog])) { 11419 verbose(env, "callback subprog cannot have stack args\n"); 11420 return -EINVAL; 11421 } 11422 11423 /* set_callee_state is used for direct subprog calls, but we are 11424 * interested in validating only BPF helpers that can call subprogs as 11425 * callbacks 11426 */ 11427 env->subprog_info[subprog].is_cb = true; 11428 if (bpf_pseudo_kfunc_call(insn) && 11429 !is_callback_calling_kfunc(insn->imm)) { 11430 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 11431 func_id_name(insn->imm), insn->imm); 11432 return -EFAULT; 11433 } else if (!bpf_pseudo_kfunc_call(insn) && 11434 !is_callback_calling_function(insn->imm)) { /* helper */ 11435 verifier_bug(env, "helper %s#%d not marked as callback-calling", 11436 func_id_name(insn->imm), insn->imm); 11437 return -EFAULT; 11438 } 11439 11440 if (bpf_is_async_callback_calling_insn(insn)) { 11441 struct bpf_verifier_state *async_cb; 11442 11443 /* there is no real recursion here. timer and workqueue callbacks are async */ 11444 env->subprog_info[subprog].is_async_cb = true; 11445 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 11446 insn_idx, subprog, 11447 is_async_cb_sleepable(env, insn)); 11448 if (IS_ERR(async_cb)) 11449 return PTR_ERR(async_cb); 11450 if (is_async_cb_sleepable(env, insn)) 11451 mark_sleepable_async_cb(env); 11452 callee = async_cb->frame[0]; 11453 callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1; 11454 11455 /* Convert bpf_timer_set_callback() args into timer callback args */ 11456 err = set_callee_state_cb(env, caller, callee, insn_idx); 11457 if (err) 11458 return err; 11459 11460 return 0; 11461 } 11462 11463 /* 11464 * The address of the callback might be taken in another function or 11465 * read from a map, see check_func_ptr_read(). Like with callx it's 11466 * known here what is called. 11467 */ 11468 err = record_callx_edge(env, caller->subprogno, subprog); 11469 if (err) 11470 return err; 11471 11472 /* for callback functions enqueue entry to callback and 11473 * proceed with next instruction within current frame. 11474 */ 11475 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 11476 if (IS_ERR(callback_state)) 11477 return PTR_ERR(callback_state); 11478 11479 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 11480 callback_state); 11481 if (err) 11482 return err; 11483 11484 callback_state->callback_unroll_depth++; 11485 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 11486 caller->callback_depth = 0; 11487 return 0; 11488 } 11489 11490 static int process_bpf_exit_full(struct bpf_verifier_env *env, 11491 bool *do_print_state, bool exception_exit); 11492 11493 /* 11494 * Call of a static subprog. The callee is verified in the context of 11495 * the caller, hence set up a new frame and continue from the first 11496 * instruction of the callee. 11497 */ 11498 static int check_static_func_call(struct bpf_verifier_env *env, int subprog, 11499 int *insn_idx) 11500 { 11501 struct bpf_verifier_state *state = env->cur_state; 11502 struct bpf_subprog_info *caller_info; 11503 u16 callee_incoming, stack_arg_cnt; 11504 struct bpf_func_state *caller; 11505 int err; 11506 11507 caller = state->frame[state->curframe]; 11508 11509 /* 11510 * Track caller's total stack arg count (incoming + max outgoing). 11511 * This is needed so the JIT knows how much stack arg space to allocate. 11512 */ 11513 caller_info = &env->subprog_info[caller->subprogno]; 11514 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 11515 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 11516 if (stack_arg_cnt > caller_info->stack_arg_cnt) 11517 caller_info->stack_arg_cnt = stack_arg_cnt; 11518 11519 /* 11520 * For regular function entry setup new frame and continue 11521 * from that frame. 11522 */ 11523 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 11524 if (err) 11525 return err; 11526 11527 bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED); 11528 clear_caller_saved_regs(env, caller->regs); 11529 11530 /* and go analyze first insn of the callee */ 11531 *insn_idx = env->subprog_info[subprog].start - 1; 11532 11533 if (env->log.level & BPF_LOG_LEVEL) { 11534 verbose(env, "caller:\n"); 11535 print_verifier_state(env, state, caller->frameno, true); 11536 verbose(env, "callee:\n"); 11537 print_verifier_state(env, state, state->curframe, true); 11538 } 11539 11540 return 0; 11541 } 11542 11543 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11544 int *insn_idx) 11545 { 11546 struct bpf_verifier_state *state = env->cur_state; 11547 struct bpf_func_state *caller; 11548 int err, subprog, target_insn; 11549 u32 i, nregs; 11550 11551 target_insn = *insn_idx + insn->imm + 1; 11552 subprog = bpf_find_subprog(env, target_insn); 11553 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 11554 target_insn)) 11555 return -EFAULT; 11556 11557 caller = state->frame[state->curframe]; 11558 err = btf_check_subprog_call(env, subprog); 11559 if (err == -EFAULT) 11560 return err; 11561 if (bpf_subprog_is_global(env, subprog)) { 11562 struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog); 11563 const char *sub_name = bpf_subprog_name(env, subprog); 11564 const char *operation; 11565 bool returns_void; 11566 11567 if (env->cur_state->active_locks) { 11568 verbose(env, "global function calls are not allowed while holding a lock,\n" 11569 "use static function instead\n"); 11570 operation = bpf_diag_fmt(env, "global function %s()", sub_name); 11571 bpf_diag_ctx_active(env, *insn_idx, operation, BPF_DIAG_CONTEXT_LOCK, 11572 "Release the lock before calling the global function, or use a static function instead."); 11573 return -EINVAL; 11574 } 11575 11576 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 11577 const char *suggestion; 11578 11579 verbose(env, "sleepable global function %s() called in %s\n", 11580 sub_name, non_sleepable_context_description(env)); 11581 if (in_sleepable(env)) 11582 suggestion = "Move the call outside the critical section, or use a non-sleepable function."; 11583 else 11584 suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable function."; 11585 operation = bpf_diag_fmt(env, "sleepable global function %s()", sub_name); 11586 bpf_diag_ctx_forbidden(env, *insn_idx, operation, suggestion); 11587 return -EINVAL; 11588 } 11589 11590 if (err) { 11591 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 11592 subprog, sub_name); 11593 return err; 11594 } 11595 11596 if (env->log.level & BPF_LOG_LEVEL) 11597 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 11598 subprog, sub_name); 11599 if (in_sleepable_context(env)) 11600 sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] = true; 11601 else if (has_rcu_read_lock(env)) 11602 sub_aux->called[BPF_FUNC_CTX_NON_SLEEPABLE] = true; 11603 else 11604 sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK] = true; 11605 returns_void = subprog_returns_void(env, subprog); 11606 if (env->subprog_info[subprog].changes_pkt_data) 11607 clear_all_pkt_pointers(env); 11608 if (returns_void) 11609 bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED); 11610 else 11611 bpf_diag_mod_begin(env, &caller->regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE); 11612 clear_caller_saved_regs(env, caller->regs); 11613 invalidate_outgoing_stack_args(env, cur_func(env)); 11614 /* 11615 * What the callers of a global function hold is not known 11616 * while it is verified. 11617 */ 11618 if (!env->subprog_info[subprog].changes_pkt_data && 11619 (state->frame[0]->subprogno || holds_pkt_pointers(env))) 11620 sub_aux->called_with_pkt_ptrs = true; 11621 11622 /* 11623 * A non-void global function returns a 64-bit SCALAR_VALUE in 11624 * R0, or a >8 byte SCALAR_VALUE in the R0:R2 register pair. 11625 */ 11626 if (!returns_void) { 11627 nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1; 11628 mark_reg_unknown(env, caller->regs, ret_regs[0]); 11629 bpf_diag_mod_end(env); 11630 for (i = 1; i < nregs; i++) { 11631 bpf_diag_mod_begin(env, &caller->regs[ret_regs[i]], NULL, 11632 BPF_DIAG_MOD_WRITE); 11633 mark_reg_unknown(env, caller->regs, ret_regs[i]); 11634 bpf_diag_mod_end(env); 11635 } 11636 } 11637 11638 if (env->subprog_info[subprog].can_unwind) { 11639 struct bpf_verifier_state *branch; 11640 11641 if (!bpf_is_unwind_goto(insn + 1)) { 11642 verbose(env, "no unwind_goto after the call of %s()\n", sub_name); 11643 return -EINVAL; 11644 } 11645 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 11646 if (IS_ERR(branch)) 11647 return PTR_ERR(branch); 11648 branch->unwound = true; 11649 } 11650 11651 if (env->subprog_info[subprog].might_throw) { 11652 struct bpf_verifier_state *branch; 11653 11654 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 11655 if (IS_ERR(branch)) { 11656 verbose(env, "failed to push state for global subprog exception path\n"); 11657 return PTR_ERR(branch); 11658 } 11659 return process_bpf_exit_full(env, NULL, true); 11660 } 11661 11662 /* continue with next insn after call */ 11663 return 0; 11664 } 11665 11666 return check_static_func_call(env, subprog, insn_idx); 11667 } 11668 11669 /* 11670 * callx dst_reg: call a bpf subprog whose address is in dst_reg. 11671 * 11672 * The address of a subprog is either loaded into a register by ld_imm64 with 11673 * src_reg == BPF_PSEUDO_FUNC, or it is read from a frozen read-only map, see 11674 * resolve_func_ptrs(). Both are possible for static subprogs only. Hence all 11675 * possible callees of callx are discovered by add_subprogs() and are reachable 11676 * in the control flow graph before the main verification pass begins. 11677 * PTR_TO_FUNC register identifies the callee, so from here on callx is verified 11678 * as a direct call of that static subprog. 11679 */ 11680 static int check_func_callx(struct bpf_verifier_env *env, struct bpf_insn *insn, 11681 int *insn_idx) 11682 { 11683 struct bpf_func_state *caller = cur_func(env); 11684 struct bpf_reg_state *reg; 11685 const char *reason; 11686 int err, subprog; 11687 11688 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11689 if (err) 11690 return err; 11691 11692 reg = reg_state(env, insn->dst_reg); 11693 if (reg->type != PTR_TO_FUNC) { 11694 verbose(env, "R%d has type %s, expected func\n", insn->dst_reg, 11695 reg_type_str(env, reg->type)); 11696 reason = bpf_diag_fmt( 11697 env, "R%d holds %s, but callx can only call through the address of a static BPF function.", 11698 insn->dst_reg, bpf_diag_reg_type_plain(env, reg->type)); 11699 bpf_diag_register_type( 11700 env, *insn_idx, insn->dst_reg, "indirect call through a non-function pointer", reason, 11701 "Load the address of a static BPF function into the register before callx."); 11702 return -EACCES; 11703 } 11704 11705 /* 11706 * Arithmetic on PTR_TO_FUNC is allowed, but only unmodified address 11707 * of a subprog can be called. 11708 */ 11709 err = check_ptr_off_reg(env, reg, insn->dst_reg); 11710 if (err) 11711 return err; 11712 11713 /* the callx is valid, but only a JIT can execute it */ 11714 err = require_callx_jit(env); 11715 if (err) 11716 return err; 11717 11718 /* PTR_TO_FUNC is a pointer to a static subprog */ 11719 subprog = reg->subprogno; 11720 err = btf_check_subprog_call(env, subprog); 11721 if (err == -EFAULT) 11722 return err; 11723 11724 err = record_callx_edge(env, caller->subprogno, subprog); 11725 if (err) 11726 return err; 11727 11728 return check_static_func_call(env, subprog, insn_idx); 11729 } 11730 11731 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 11732 struct bpf_func_state *caller, 11733 struct bpf_func_state *callee) 11734 { 11735 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 11736 * void *callback_ctx, u64 flags); 11737 * callback_fn(struct bpf_map *map, void *key, void *value, 11738 * void *callback_ctx); 11739 */ 11740 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 11741 11742 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 11743 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 11744 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 11745 callee->regs[BPF_REG_2].map_uid = caller->regs[BPF_REG_1].map_uid; 11746 11747 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 11748 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 11749 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 11750 callee->regs[BPF_REG_3].map_uid = caller->regs[BPF_REG_1].map_uid; 11751 callee->regs[BPF_REG_3].id = ++env->id_gen; 11752 11753 /* pointer to stack or null */ 11754 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 11755 11756 /* unused */ 11757 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11758 return 0; 11759 } 11760 11761 static int set_callee_state(struct bpf_verifier_env *env, 11762 struct bpf_func_state *caller, 11763 struct bpf_func_state *callee, int insn_idx) 11764 { 11765 int i; 11766 11767 /* copy r1 - r5 args that callee can access. The copy includes parent 11768 * pointers, which connects us up to the liveness chain 11769 */ 11770 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 11771 callee->regs[i] = caller->regs[i]; 11772 return 0; 11773 } 11774 11775 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 11776 struct bpf_func_state *caller, 11777 struct bpf_func_state *callee, 11778 int insn_idx) 11779 { 11780 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 11781 struct bpf_map *map; 11782 int err; 11783 11784 /* valid map_ptr and poison value does not matter */ 11785 map = insn_aux->map_ptr_state.map_ptr; 11786 if (!map->ops->map_set_for_each_callback_args || 11787 !map->ops->map_for_each_callback) { 11788 verbose(env, "callback function not allowed for map\n"); 11789 return -ENOTSUPP; 11790 } 11791 11792 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 11793 if (err) 11794 return err; 11795 11796 switch (map->map_type) { 11797 case BPF_MAP_TYPE_HASH: 11798 case BPF_MAP_TYPE_PERCPU_HASH: 11799 case BPF_MAP_TYPE_LRU_HASH: 11800 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 11801 case BPF_MAP_TYPE_RHASH: 11802 /* Hash tables run the callback under rcu_read_lock(). */ 11803 callee->in_rcu_callback_fn = true; 11804 break; 11805 default: 11806 break; 11807 } 11808 11809 callee->in_callback_fn = true; 11810 callee->callback_ret_range = retval_range(0, 1); 11811 return 0; 11812 } 11813 11814 static int set_loop_callback_state(struct bpf_verifier_env *env, 11815 struct bpf_func_state *caller, 11816 struct bpf_func_state *callee, 11817 int insn_idx) 11818 { 11819 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 11820 * u64 flags); 11821 * callback_fn(u64 index, void *callback_ctx); 11822 */ 11823 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 11824 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 11825 11826 /* unused */ 11827 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 11828 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 11829 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11830 11831 callee->in_callback_fn = true; 11832 callee->callback_ret_range = retval_range(0, 1); 11833 return 0; 11834 } 11835 11836 static int set_timer_callback_state(struct bpf_verifier_env *env, 11837 struct bpf_func_state *caller, 11838 struct bpf_func_state *callee, 11839 int insn_idx) 11840 { 11841 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 11842 u32 map_uid = caller->regs[BPF_REG_1].map_uid; 11843 11844 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 11845 * callback_fn(struct bpf_map *map, void *key, void *value); 11846 */ 11847 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 11848 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 11849 callee->regs[BPF_REG_1].map_ptr = map_ptr; 11850 callee->regs[BPF_REG_1].map_uid = map_uid; 11851 11852 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 11853 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 11854 callee->regs[BPF_REG_2].map_ptr = map_ptr; 11855 callee->regs[BPF_REG_2].map_uid = map_uid; 11856 11857 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 11858 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 11859 callee->regs[BPF_REG_3].map_ptr = map_ptr; 11860 callee->regs[BPF_REG_3].map_uid = map_uid; 11861 callee->regs[BPF_REG_3].id = ++env->id_gen; 11862 11863 /* unused */ 11864 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 11865 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11866 callee->in_async_callback_fn = true; 11867 callee->callback_ret_range = retval_range(0, 0); 11868 return 0; 11869 } 11870 11871 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 11872 struct bpf_func_state *caller, 11873 struct bpf_func_state *callee, 11874 int insn_idx) 11875 { 11876 /* bpf_find_vma(struct task_struct *task, u64 addr, 11877 * void *callback_fn, void *callback_ctx, u64 flags) 11878 * (callback_fn)(struct task_struct *task, 11879 * struct vm_area_struct *vma, void *callback_ctx); 11880 */ 11881 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 11882 11883 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 11884 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 11885 callee->regs[BPF_REG_2].btf = btf_vmlinux; 11886 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 11887 11888 /* pointer to stack or null */ 11889 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 11890 11891 /* unused */ 11892 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 11893 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11894 callee->in_callback_fn = true; 11895 /* bpf_find_vma() runs the callback under mmap_lock and RCU. */ 11896 callee->in_rcu_callback_fn = true; 11897 callee->callback_ret_range = retval_range(0, 1); 11898 return 0; 11899 } 11900 11901 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 11902 struct bpf_func_state *caller, 11903 struct bpf_func_state *callee, 11904 int insn_idx) 11905 { 11906 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 11907 * callback_ctx, u64 flags); 11908 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 11909 */ 11910 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 11911 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 11912 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 11913 11914 /* unused */ 11915 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 11916 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 11917 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11918 11919 callee->in_callback_fn = true; 11920 callee->callback_ret_range = retval_range(0, 1); 11921 return 0; 11922 } 11923 11924 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 11925 struct bpf_func_state *caller, 11926 struct bpf_func_state *callee, 11927 int insn_idx) 11928 { 11929 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 11930 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 11931 * 11932 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 11933 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 11934 * by this point, so look at 'root' 11935 */ 11936 struct btf_field *field; 11937 11938 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 11939 caller->regs[BPF_REG_1].var_off.value, 11940 BPF_RB_ROOT); 11941 if (!field || !field->graph_root.value_btf_id) 11942 return -EFAULT; 11943 11944 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 11945 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 11946 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 11947 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 11948 11949 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 11950 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 11951 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11952 callee->in_callback_fn = true; 11953 callee->callback_ret_range = retval_range(0, 1); 11954 return 0; 11955 } 11956 11957 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 11958 struct bpf_func_state *caller, 11959 struct bpf_func_state *callee, 11960 int insn_idx) 11961 { 11962 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 11963 u32 map_uid = caller->regs[BPF_REG_3].map_uid; 11964 11965 /* 11966 * callback_fn(struct bpf_map *map, void *key, void *value); 11967 */ 11968 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 11969 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 11970 callee->regs[BPF_REG_1].map_ptr = map_ptr; 11971 callee->regs[BPF_REG_1].map_uid = map_uid; 11972 11973 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 11974 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 11975 callee->regs[BPF_REG_2].map_ptr = map_ptr; 11976 callee->regs[BPF_REG_2].map_uid = map_uid; 11977 11978 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 11979 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 11980 callee->regs[BPF_REG_3].map_ptr = map_ptr; 11981 callee->regs[BPF_REG_3].map_uid = map_uid; 11982 callee->regs[BPF_REG_3].id = ++env->id_gen; 11983 11984 /* unused */ 11985 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 11986 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 11987 callee->in_async_callback_fn = true; 11988 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 11989 return 0; 11990 } 11991 11992 static int set_rcu_callback_state(struct bpf_verifier_env *env, 11993 struct bpf_func_state *caller, 11994 struct bpf_func_state *callee, 11995 int insn_idx) 11996 { 11997 struct bpf_map *map_ptr = caller->regs[BPF_REG_2].map_ptr; 11998 u32 map_uid = caller->regs[BPF_REG_2].map_uid; 11999 12000 /* 12001 * callback_fn(struct bpf_map *map, void *key, void *value); 12002 */ 12003 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 12004 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 12005 callee->regs[BPF_REG_1].map_ptr = map_ptr; 12006 callee->regs[BPF_REG_1].map_uid = map_uid; 12007 12008 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 12009 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 12010 callee->regs[BPF_REG_2].map_ptr = map_ptr; 12011 callee->regs[BPF_REG_2].map_uid = map_uid; 12012 12013 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 12014 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 12015 callee->regs[BPF_REG_3].map_ptr = map_ptr; 12016 callee->regs[BPF_REG_3].map_uid = map_uid; 12017 12018 /* unused */ 12019 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 12020 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 12021 callee->in_async_callback_fn = true; 12022 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 12023 return 0; 12024 } 12025 12026 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 12027 12028 static void account_processed_insn(struct bpf_verifier_env *env) 12029 { 12030 struct bpf_func_state *frame = cur_func(env); 12031 12032 env->insn_processed++; 12033 frame->insns_subtotal++; 12034 env->subprog_info[frame->subprogno].insns_self++; 12035 } 12036 12037 static void account_processed_insns(struct bpf_verifier_env *env, 12038 struct bpf_func_state *callee, 12039 struct bpf_func_state *caller) 12040 { 12041 u32 insns; 12042 12043 if (!callee) 12044 return; 12045 12046 insns = callee->insns_subtotal; 12047 12048 env->subprog_info[callee->subprogno].insns_total += insns; 12049 if (caller) 12050 caller->insns_subtotal += insns; 12051 callee->insns_subtotal = 0; 12052 } 12053 12054 static void account_current_path(struct bpf_verifier_env *env) 12055 { 12056 struct bpf_verifier_state *state = env->cur_state; 12057 int frame; 12058 12059 for (frame = state->curframe; frame >= 0; frame--) 12060 account_processed_insns(env, state->frame[frame], 12061 frame ? state->frame[frame - 1] : NULL); 12062 } 12063 12064 /* 12065 * Are we currently verifying the callback for an rbtree kfunc that must 12066 * be called with a lock held, or one of that callback's subprogs? If so, 12067 * no need to complain about an unreleased lock. 12068 */ 12069 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 12070 { 12071 struct bpf_verifier_state *state = env->cur_state; 12072 struct bpf_insn *insn = env->prog->insnsi; 12073 struct bpf_func_state *callee; 12074 int kfunc_btf_id; 12075 u32 frame; 12076 12077 for (frame = state->curframe; frame; frame--) { 12078 callee = state->frame[frame]; 12079 if (!callee->in_callback_fn) 12080 continue; 12081 12082 kfunc_btf_id = insn[callee->callsite].imm; 12083 if (is_rbtree_lock_required_kfunc(kfunc_btf_id)) 12084 return true; 12085 } 12086 12087 return false; 12088 } 12089 12090 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 12091 { 12092 if (range.return_32bit) 12093 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 12094 else 12095 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 12096 } 12097 12098 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 12099 { 12100 struct bpf_verifier_state *state = env->cur_state, *prev_st; 12101 struct bpf_func_state *caller, *callee; 12102 struct bpf_reg_state *r0; 12103 bool in_callback_fn; 12104 u32 i, nregs; 12105 int err; 12106 12107 callee = state->frame[state->curframe]; 12108 r0 = &callee->regs[BPF_REG_0]; 12109 nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1; 12110 for (i = 0; i < nregs; i++) { 12111 if (callee->regs[ret_regs[i]].type != PTR_TO_STACK) 12112 continue; 12113 /* technically it's ok to return caller's stack pointer 12114 * (or caller's caller's pointer) back to the caller, 12115 * since these pointers are valid. Only current stack 12116 * pointer will be invalid as soon as function exits, 12117 * but let's be conservative 12118 */ 12119 verbose(env, "cannot return stack pointer to the caller\n"); 12120 return -EINVAL; 12121 } 12122 12123 caller = state->frame[state->curframe - 1]; 12124 if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx])) { 12125 /* the helper or the kfunc that called it doesn't expect that */ 12126 if (callee->in_callback_fn) { 12127 verbose(env, "callback cannot unwind\n"); 12128 return -EINVAL; 12129 } 12130 if (!bpf_is_unwind_goto(&env->prog->insnsi[callee->callsite + 1])) { 12131 verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n", 12132 callee->callsite); 12133 return -EINVAL; 12134 } 12135 state->unwound = true; 12136 } 12137 if (callee->in_callback_fn) { 12138 if (r0->type != SCALAR_VALUE) { 12139 verbose(env, "R0 not a scalar value\n"); 12140 return -EACCES; 12141 } 12142 12143 /* we are going to rely on register's precise value */ 12144 err = mark_chain_precision(env, BPF_REG_0); 12145 if (err) 12146 return err; 12147 12148 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 12149 if (!retval_range_within(callee->callback_ret_range, r0)) { 12150 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 12151 "At callback return", "R0"); 12152 return -EINVAL; 12153 } 12154 if (!bpf_calls_callback(env, callee->callsite)) { 12155 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 12156 *insn_idx, callee->callsite); 12157 return -EFAULT; 12158 } 12159 } else { 12160 /* 12161 * return to the caller whatever the callee had in the 12162 * return register(s) 12163 */ 12164 for (i = 0; i < nregs; i++) { 12165 u32 regno = ret_regs[i]; 12166 12167 bpf_diag_mod_begin(env, &caller->regs[regno], &callee->regs[regno], 12168 BPF_DIAG_MOD_WRITE); 12169 caller->regs[regno] = callee->regs[regno]; 12170 bpf_diag_mod_end(env); 12171 } 12172 } 12173 12174 /* Invalidate callee-local dynptrs and their slices before the frame goes away. */ 12175 err = destroy_dynptrs_in_stack_slots(env, callee, 0, 12176 callee->allocated_stack / BPF_REG_SIZE - 1); 12177 if (err) 12178 return err; 12179 12180 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 12181 * there function call logic would reschedule callback visit. If iteration 12182 * converges is_state_visited() would prune that visit eventually. 12183 */ 12184 in_callback_fn = callee->in_callback_fn; 12185 if (in_callback_fn) 12186 *insn_idx = callee->callsite; 12187 else 12188 *insn_idx = callee->callsite + 1; 12189 12190 if (env->log.level & BPF_LOG_LEVEL) { 12191 verbose(env, "returning from callee:\n"); 12192 print_verifier_state(env, state, callee->frameno, true); 12193 verbose(env, "to caller at %d:\n", *insn_idx); 12194 print_verifier_state(env, state, caller->frameno, true); 12195 } 12196 account_processed_insns(env, callee, caller); 12197 /* clear everything in the callee. In case of exceptional exits using 12198 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 12199 free_func_state(callee); 12200 state->frame[state->curframe--] = NULL; 12201 invalidate_outgoing_stack_args(env, caller); 12202 12203 /* for callbacks widen imprecise scalars to make programs like below verify: 12204 * 12205 * struct ctx { int i; } 12206 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 12207 * ... 12208 * struct ctx = { .i = 0; } 12209 * bpf_loop(100, cb, &ctx, 0); 12210 * 12211 * This is similar to what is done in process_iter_next_call() for open 12212 * coded iterators. 12213 */ 12214 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 12215 if (prev_st) { 12216 err = widen_imprecise_scalars(env, prev_st, state); 12217 if (err) 12218 return err; 12219 } 12220 return 0; 12221 } 12222 12223 static int do_refine_retval_range(struct bpf_verifier_env *env, 12224 struct bpf_reg_state *regs, int ret_type, 12225 int func_id, 12226 struct bpf_call_arg_meta *meta) 12227 { 12228 struct bpf_retval_range range; 12229 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 12230 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12231 12232 if (ret_type != RET_INTEGER) 12233 return 0; 12234 12235 switch (func_id) { 12236 case BPF_FUNC_get_stack: 12237 case BPF_FUNC_get_task_stack: 12238 case BPF_FUNC_probe_read_str: 12239 case BPF_FUNC_probe_read_kernel_str: 12240 case BPF_FUNC_probe_read_user_str: 12241 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 12242 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 12243 reg_bounds_sync(ret_reg); 12244 break; 12245 case BPF_FUNC_get_smp_processor_id: 12246 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 12247 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 12248 reg_bounds_sync(ret_reg); 12249 break; 12250 case BPF_FUNC_get_retval: 12251 /* 12252 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for 12253 * CGROUP_GETSOCKOPT type. 12254 */ 12255 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 12256 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 12257 break; 12258 12259 if (prog_type == BPF_PROG_TYPE_LSM && 12260 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 12261 if (!env->prog->aux->attach_func_proto->type) 12262 break; 12263 bpf_lsm_get_retval_range(env->prog, &range); 12264 } else { 12265 range.minval = -MAX_ERRNO; 12266 range.maxval = 0; 12267 } 12268 12269 reg_set_srange64(ret_reg, range.minval, range.maxval); 12270 reg_set_srange32(ret_reg, range.minval, range.maxval); 12271 reg_bounds_sync(ret_reg); 12272 break; 12273 } 12274 12275 return reg_bounds_sanity_check(env, ret_reg, "retval"); 12276 } 12277 12278 static int 12279 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 12280 int func_id, int insn_idx) 12281 { 12282 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12283 struct bpf_map *map = meta->map.ptr; 12284 12285 if (func_id != BPF_FUNC_tail_call && 12286 func_id != BPF_FUNC_map_lookup_elem && 12287 func_id != BPF_FUNC_map_update_elem && 12288 func_id != BPF_FUNC_map_delete_elem && 12289 func_id != BPF_FUNC_map_push_elem && 12290 func_id != BPF_FUNC_map_pop_elem && 12291 func_id != BPF_FUNC_map_peek_elem && 12292 func_id != BPF_FUNC_for_each_map_elem && 12293 func_id != BPF_FUNC_redirect_map && 12294 func_id != BPF_FUNC_map_lookup_percpu_elem) 12295 return 0; 12296 12297 if (map == NULL) { 12298 verifier_bug(env, "expected map for helper call"); 12299 return -EFAULT; 12300 } 12301 12302 /* In case of read-only, some additional restrictions 12303 * need to be applied in order to prevent altering the 12304 * state of the map from program side. 12305 */ 12306 if ((map->map_flags & BPF_F_RDONLY_PROG) && 12307 (func_id == BPF_FUNC_map_delete_elem || 12308 func_id == BPF_FUNC_map_update_elem || 12309 func_id == BPF_FUNC_map_push_elem || 12310 func_id == BPF_FUNC_map_pop_elem)) { 12311 verbose(env, "write into map forbidden\n"); 12312 return -EACCES; 12313 } 12314 12315 if (!aux->map_ptr_state.map_ptr) 12316 bpf_map_ptr_store(aux, meta->map.ptr, 12317 !meta->map.ptr->bypass_spec_v1, false); 12318 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 12319 bpf_map_ptr_store(aux, meta->map.ptr, 12320 !meta->map.ptr->bypass_spec_v1, true); 12321 return 0; 12322 } 12323 12324 static int 12325 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 12326 int func_id, int insn_idx) 12327 { 12328 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12329 struct bpf_reg_state *reg; 12330 struct bpf_map *map = meta->map.ptr; 12331 u64 val, max; 12332 int err; 12333 12334 if (func_id != BPF_FUNC_tail_call) 12335 return 0; 12336 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 12337 verbose(env, "expected prog array map for tail call"); 12338 return -EINVAL; 12339 } 12340 12341 reg = reg_state(env, BPF_REG_3); 12342 val = reg->var_off.value; 12343 max = map->max_entries; 12344 12345 if (!(is_reg_const(reg, false) && val < max)) { 12346 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 12347 return 0; 12348 } 12349 12350 err = mark_chain_precision(env, BPF_REG_3); 12351 if (err) 12352 return err; 12353 if (bpf_map_key_unseen(aux)) 12354 bpf_map_key_store(aux, val); 12355 else if (!bpf_map_key_poisoned(aux) && 12356 bpf_map_key_immediate(aux) != val) 12357 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 12358 return 0; 12359 } 12360 12361 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 12362 { 12363 struct bpf_verifier_state *state = env->cur_state; 12364 enum bpf_prog_type type = resolve_prog_type(env->prog); 12365 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 12366 bool refs_lingering = false; 12367 int i; 12368 12369 if (!exception_exit && cur_func(env)->frameno) 12370 return 0; 12371 12372 for (i = 0; i < state->acquired_refs; i++) { 12373 if (state->refs[i].type != REF_TYPE_PTR) 12374 continue; 12375 /* Allow struct_ops programs to return a referenced kptr back to 12376 * kernel. Type checks are performed later in check_return_code. 12377 */ 12378 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 12379 reg->id == state->refs[i].id) 12380 continue; 12381 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 12382 state->refs[i].id, state->refs[i].insn_idx); 12383 bpf_diag_leak(env, state->refs[i].id, state->refs[i].insn_idx, env->insn_idx); 12384 refs_lingering = true; 12385 } 12386 return refs_lingering ? -EINVAL : 0; 12387 } 12388 12389 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 12390 { 12391 int err; 12392 12393 if (check_lock && env->cur_state->active_locks) { 12394 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 12395 bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_LOCK, 12396 "Release the BPF spin lock before this operation on every path."); 12397 return -EINVAL; 12398 } 12399 12400 err = check_reference_leak(env, exception_exit); 12401 if (err) { 12402 verbose(env, "%s would lead to reference leak\n", prefix); 12403 return err; 12404 } 12405 12406 if (check_lock && env->cur_state->active_irq_id) { 12407 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 12408 bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_IRQ, 12409 "Restore the saved IRQ state before this operation on every path."); 12410 return -EINVAL; 12411 } 12412 12413 if (check_lock && env->cur_state->active_rcu_locks) { 12414 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 12415 bpf_diag_ctx_active(env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_RCU, 12416 "Call bpf_rcu_read_unlock() before this operation on every path."); 12417 return -EINVAL; 12418 } 12419 12420 if (check_lock && env->cur_state->active_preempt_locks) { 12421 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 12422 bpf_diag_ctx_active( 12423 env, env->insn_idx, prefix, BPF_DIAG_CONTEXT_PREEMPT, 12424 "Call bpf_preempt_enable() before this operation on every path."); 12425 return -EINVAL; 12426 } 12427 12428 return 0; 12429 } 12430 12431 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 12432 struct bpf_reg_state *regs) 12433 { 12434 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 12435 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 12436 struct bpf_map *fmt_map = fmt_reg->map_ptr; 12437 struct bpf_bprintf_data data = {}; 12438 int err, fmt_map_off, num_args; 12439 u64 fmt_addr; 12440 char *fmt; 12441 12442 /* data must be an array of u64 */ 12443 if (data_len_reg->var_off.value % 8) 12444 return -EINVAL; 12445 num_args = data_len_reg->var_off.value / 8; 12446 12447 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 12448 * and map_direct_value_addr is set. 12449 */ 12450 fmt_map_off = fmt_reg->var_off.value; 12451 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 12452 fmt_map_off); 12453 if (err) { 12454 verbose(env, "failed to retrieve map value address\n"); 12455 return -EFAULT; 12456 } 12457 fmt = (char *)(long)fmt_addr + fmt_map_off; 12458 12459 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 12460 * can focus on validating the format specifiers. 12461 */ 12462 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 12463 if (err < 0) 12464 verbose(env, "Invalid format string\n"); 12465 12466 return err; 12467 } 12468 12469 static int check_get_func_ip(struct bpf_verifier_env *env) 12470 { 12471 enum bpf_prog_type type = resolve_prog_type(env->prog); 12472 int func_id = BPF_FUNC_get_func_ip; 12473 12474 if (type == BPF_PROG_TYPE_TRACING) { 12475 if (!bpf_prog_has_trampoline(env->prog)) { 12476 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 12477 func_id_name(func_id), func_id); 12478 return -ENOTSUPP; 12479 } 12480 return 0; 12481 } else if (type == BPF_PROG_TYPE_KPROBE) { 12482 return 0; 12483 } 12484 12485 verbose(env, "func %s#%d not supported for program type %d\n", 12486 func_id_name(func_id), func_id, type); 12487 return -ENOTSUPP; 12488 } 12489 12490 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 12491 { 12492 return &env->insn_aux_data[env->insn_idx]; 12493 } 12494 12495 /* Returns 1 if R4 is a known zero, 0 if it is not, a negative errno on error. */ 12496 static int loop_flag_is_zero(struct bpf_verifier_env *env) 12497 { 12498 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 12499 int err; 12500 12501 if (!bpf_register_is_null(reg)) 12502 return 0; 12503 12504 err = mark_chain_precision(env, BPF_REG_4); 12505 if (err) 12506 return err; 12507 return 1; 12508 } 12509 12510 static int update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 12511 { 12512 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 12513 int flag_is_zero; 12514 12515 if (!state->initialized) { 12516 flag_is_zero = loop_flag_is_zero(env); 12517 if (flag_is_zero < 0) 12518 return flag_is_zero; 12519 state->initialized = 1; 12520 state->fit_for_inline = flag_is_zero; 12521 state->callback_subprogno = subprogno; 12522 return 0; 12523 } 12524 12525 if (!state->fit_for_inline) 12526 return 0; 12527 12528 flag_is_zero = loop_flag_is_zero(env); 12529 if (flag_is_zero < 0) 12530 return flag_is_zero; 12531 state->fit_for_inline = (flag_is_zero && 12532 state->callback_subprogno == subprogno); 12533 return 0; 12534 } 12535 12536 /* Returns whether or not the given map can potentially elide 12537 * lookup return value nullness check. This is possible if the key 12538 * is statically known. 12539 */ 12540 static bool can_elide_value_nullness(const struct bpf_map *map) 12541 { 12542 if (map->map_flags & BPF_F_INNER_MAP) 12543 return false; 12544 12545 switch (map->map_type) { 12546 case BPF_MAP_TYPE_ARRAY: 12547 case BPF_MAP_TYPE_PERCPU_ARRAY: 12548 return true; 12549 default: 12550 return false; 12551 } 12552 } 12553 12554 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 12555 const struct bpf_func_proto **ptr) 12556 { 12557 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 12558 return -ERANGE; 12559 12560 if (!env->ops->get_func_proto) 12561 return -EINVAL; 12562 12563 *ptr = env->ops->get_func_proto(func_id, env->prog); 12564 return *ptr && (*ptr)->func ? 0 : -EINVAL; 12565 } 12566 12567 /* Is any frame on the current path a callback that runs under RCU? */ 12568 static bool in_rcu_callback(struct bpf_verifier_env *env) 12569 { 12570 struct bpf_verifier_state *state = env->cur_state; 12571 int i; 12572 12573 for (i = 0; i <= state->curframe; i++) 12574 if (state->frame[i]->in_rcu_callback_fn) 12575 return true; 12576 return false; 12577 } 12578 12579 /* Check if we're in a sleepable context. */ 12580 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 12581 { 12582 return !in_rcu_cs(env) && !in_rcu_callback(env); 12583 } 12584 12585 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 12586 { 12587 if (in_sleepable(env)) { 12588 if (env->cur_state->active_rcu_locks) 12589 return "rcu_read_lock region"; 12590 if (env->cur_state->active_preempt_locks) 12591 return "non-preemptible region"; 12592 if (env->cur_state->active_irq_id) 12593 return "IRQ-disabled region"; 12594 if (env->cur_state->active_locks) 12595 return "lock region"; 12596 return "callback running under rcu_read_lock"; 12597 } 12598 return "non-sleepable prog"; 12599 } 12600 12601 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 12602 bool convert_rcu, bool release_dynptr) 12603 { 12604 int err = -EINVAL; 12605 12606 if (bpf_register_is_null(reg)) 12607 return 0; 12608 12609 if (release_dynptr) 12610 err = unmark_stack_slots_dynptr(env, reg); 12611 else if (convert_rcu) 12612 err = ref_convert_alloc_rcu_protected(env, reg->id); 12613 else if (reg_is_referenced(env, reg)) 12614 err = release_reference(env, reg->id); 12615 12616 return err; 12617 } 12618 12619 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12620 int *insn_idx_p) 12621 { 12622 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12623 bool returns_cpu_specific_alloc_ptr = false; 12624 const struct bpf_func_proto *fn = NULL; 12625 enum bpf_return_type ret_type; 12626 enum bpf_type_flag ret_flag; 12627 struct bpf_reg_state *regs; 12628 struct bpf_call_arg_meta meta; 12629 const char *operation; 12630 int insn_idx = *insn_idx_p; 12631 bool changes_data; 12632 int i, err, func_id; 12633 12634 /* find function prototype */ 12635 func_id = insn->imm; 12636 err = bpf_get_helper_proto(env, insn->imm, &fn); 12637 if (err == -ERANGE) { 12638 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 12639 return -EINVAL; 12640 } 12641 12642 if (err) { 12643 verbose(env, "program of this type cannot use helper %s#%d\n", 12644 func_id_name(func_id), func_id); 12645 operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id); 12646 bpf_diag_policy( 12647 env, insn_idx, operation, "this program type does not allow the helper", 12648 "Use a helper allowed for this program type, or move the logic to a compatible program type."); 12649 return err; 12650 } 12651 12652 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 12653 if (!env->prog->gpl_compatible && fn->gpl_only) { 12654 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 12655 operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id); 12656 bpf_diag_policy( 12657 env, insn_idx, operation, 12658 "this helper is restricted to GPL-compatible programs", 12659 "Use a GPL-compatible license, or replace the helper with one that is available to non-GPL programs."); 12660 return -EINVAL; 12661 } 12662 12663 if (fn->allowed && !fn->allowed(env->prog)) { 12664 verbose(env, "helper call is not allowed in probe\n"); 12665 operation = bpf_diag_fmt(env, "helper %s#%d", func_id_name(func_id), func_id); 12666 bpf_diag_policy( 12667 env, insn_idx, operation, 12668 "the helper-specific policy callback rejected this program", 12669 "Use the helper only from an allowed attach point or program configuration."); 12670 return -EINVAL; 12671 } 12672 12673 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 12674 changes_data = bpf_helper_changes_pkt_data(func_id); 12675 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 12676 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 12677 return -EFAULT; 12678 } 12679 12680 memset(&meta, 0, sizeof(meta)); 12681 12682 err = check_func_proto(env, fn, &meta); 12683 if (err) { 12684 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 12685 return err; 12686 } 12687 12688 if (fn->might_sleep && !in_sleepable_context(env)) { 12689 const char *suggestion; 12690 12691 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 12692 non_sleepable_context_description(env)); 12693 if (in_sleepable(env)) 12694 suggestion = "Move the helper call outside the critical section, or use a non-sleepable helper."; 12695 else 12696 suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable helper."; 12697 operation = bpf_diag_fmt(env, "sleepable helper %s#%d", 12698 func_id_name(func_id), func_id); 12699 bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion); 12700 return -EINVAL; 12701 } 12702 12703 /* Track non-sleepable context for helpers. */ 12704 if (!in_sleepable_context(env)) 12705 env->insn_aux_data[insn_idx].non_sleepable = true; 12706 12707 meta.func_id = func_id; 12708 meta.func_name = func_id_name(func_id); 12709 meta.fn = fn; 12710 err = check_func_args(env, &meta, insn_idx); 12711 if (err) 12712 return err; 12713 12714 err = record_func_map(env, &meta, func_id, insn_idx); 12715 if (err) 12716 return err; 12717 12718 err = record_func_key(env, &meta, func_id, insn_idx); 12719 if (err) 12720 return err; 12721 12722 regs = cur_regs(env); 12723 12724 err = mark_raw_stack(env, &meta, insn_idx); 12725 if (err) 12726 return err; 12727 12728 if (meta.release_regno) { 12729 struct bpf_reg_state *reg = ®s[meta.release_regno]; 12730 bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) && 12731 (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU); 12732 12733 err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id); 12734 if (err) 12735 return err; 12736 } 12737 12738 switch (func_id) { 12739 case BPF_FUNC_tail_call: 12740 err = check_resource_leak(env, false, true, "tail_call"); 12741 if (err) 12742 return err; 12743 break; 12744 case BPF_FUNC_get_local_storage: 12745 /* check that flags argument in get_local_storage(map, flags) is 0, 12746 * this is required because get_local_storage() can't return an error. 12747 */ 12748 if (!bpf_register_is_null(®s[BPF_REG_2])) { 12749 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 12750 return -EINVAL; 12751 } 12752 err = mark_chain_precision(env, BPF_REG_2); 12753 if (err) 12754 return err; 12755 break; 12756 case BPF_FUNC_for_each_map_elem: 12757 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12758 set_map_elem_callback_state); 12759 break; 12760 case BPF_FUNC_timer_set_callback: 12761 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12762 set_timer_callback_state); 12763 break; 12764 case BPF_FUNC_find_vma: 12765 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12766 set_find_vma_callback_state); 12767 break; 12768 case BPF_FUNC_snprintf: 12769 err = check_bpf_snprintf_call(env, regs); 12770 break; 12771 case BPF_FUNC_loop: 12772 err = update_loop_inline_state(env, meta.subprogno); 12773 if (err) 12774 return err; 12775 /* Verifier relies on R1 value to determine if bpf_loop() iteration 12776 * is finished, thus mark it precise. 12777 */ 12778 err = mark_chain_precision(env, BPF_REG_1); 12779 if (err) 12780 return err; 12781 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 12782 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12783 set_loop_callback_state); 12784 } else { 12785 cur_func(env)->callback_depth = 0; 12786 if (env->log.level & BPF_LOG_LEVEL2) 12787 verbose(env, "frame%d bpf_loop iteration limit reached\n", 12788 env->cur_state->curframe); 12789 } 12790 break; 12791 case BPF_FUNC_dynptr_from_mem: 12792 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 12793 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 12794 reg_type_str(env, regs[BPF_REG_1].type)); 12795 return -EACCES; 12796 } 12797 break; 12798 case BPF_FUNC_set_retval: 12799 { 12800 struct bpf_retval_range range = { 12801 .minval = -MAX_ERRNO, 12802 .maxval = 0, 12803 .return_32bit = true 12804 }; 12805 struct bpf_reg_state *r1 = ®s[BPF_REG_1]; 12806 12807 if (r1->type != SCALAR_VALUE) { 12808 verbose(env, "R1 is not a scalar\n"); 12809 return -EINVAL; 12810 } 12811 12812 /* CGROUP_GETSOCKOPT is allowed to return arbitrary value */ 12813 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 12814 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 12815 break; 12816 12817 if (prog_type == BPF_PROG_TYPE_LSM && 12818 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 12819 if (!env->prog->aux->attach_func_proto->type) { 12820 /* Make sure programs that attach to void 12821 * hooks don't try to modify return value. 12822 */ 12823 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 12824 return -EINVAL; 12825 } 12826 bpf_lsm_get_retval_range(env->prog, &range); 12827 } 12828 12829 err = mark_chain_precision(env, BPF_REG_1); 12830 if (err) 12831 return err; 12832 12833 if (!retval_range_within(range, r1)) { 12834 verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1"); 12835 return -EINVAL; 12836 } 12837 12838 break; 12839 } 12840 case BPF_FUNC_dynptr_write: 12841 { 12842 enum bpf_dynptr_type dynptr_type = meta.dynptr.type; 12843 12844 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 12845 return -EFAULT; 12846 12847 if (dynptr_write_changes_pkt_data(dynptr_type)) 12848 /* this will trigger clear_all_pkt_pointers(), which will 12849 * invalidate all dynptr slices associated with the skb 12850 */ 12851 changes_data = true; 12852 12853 break; 12854 } 12855 case BPF_FUNC_per_cpu_ptr: 12856 case BPF_FUNC_this_cpu_ptr: 12857 { 12858 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 12859 const struct btf_type *type; 12860 12861 if (reg->type & MEM_RCU) { 12862 type = btf_type_by_id(reg->btf, reg->btf_id); 12863 if (!type || !btf_type_is_struct(type)) { 12864 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 12865 return -EFAULT; 12866 } 12867 returns_cpu_specific_alloc_ptr = true; 12868 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 12869 } 12870 break; 12871 } 12872 case BPF_FUNC_user_ringbuf_drain: 12873 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12874 set_user_ringbuf_callback_state); 12875 break; 12876 } 12877 12878 if (err) 12879 return err; 12880 12881 /* reset caller saved regs */ 12882 bpf_diag_record_caller_saved(env, regs); 12883 bpf_diag_mod_begin(env, ®s[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE); 12884 for (i = 0; i < CALLER_SAVED_REGS; i++) { 12885 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12886 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 12887 } 12888 invalidate_outgoing_stack_args(env, cur_func(env)); 12889 12890 /* update return register (already marked as written above) */ 12891 ret_type = fn->ret_type; 12892 ret_flag = type_flag(ret_type); 12893 12894 switch (base_type(ret_type)) { 12895 case RET_INTEGER: 12896 /* sets type to SCALAR_VALUE */ 12897 mark_reg_unknown(env, regs, BPF_REG_0); 12898 break; 12899 case RET_VOID: 12900 regs[BPF_REG_0].type = NOT_INIT; 12901 break; 12902 case RET_PTR_TO_MAP_VALUE: 12903 /* There is no offset yet applied, variable or fixed */ 12904 mark_reg_known_zero(env, regs, BPF_REG_0); 12905 /* remember map_ptr, so that check_map_access() 12906 * can check 'value_size' boundary of memory access 12907 * to map element returned from bpf_map_lookup_elem() 12908 */ 12909 if (meta.map.ptr == NULL) { 12910 verifier_bug(env, "unexpected null map_ptr"); 12911 return -EFAULT; 12912 } 12913 12914 if (func_id == BPF_FUNC_map_lookup_elem && 12915 can_elide_value_nullness(meta.map.ptr) && 12916 meta.const_map_key >= 0 && 12917 meta.const_map_key < meta.map.ptr->max_entries) 12918 ret_flag &= ~PTR_MAYBE_NULL; 12919 12920 regs[BPF_REG_0].map_ptr = meta.map.ptr; 12921 regs[BPF_REG_0].map_uid = meta.map.uid; 12922 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 12923 if (type_may_be_null(ret_flag) || 12924 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 12925 regs[BPF_REG_0].id = ++env->id_gen; 12926 } 12927 /* requires regs[BPF_REG_0].id to be set because of the map-in-map case */ 12928 refine_map_lookup_value(®s[BPF_REG_0]); 12929 break; 12930 case RET_PTR_TO_SOCKET: 12931 mark_reg_known_zero(env, regs, BPF_REG_0); 12932 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 12933 break; 12934 case RET_PTR_TO_SOCK_COMMON: 12935 mark_reg_known_zero(env, regs, BPF_REG_0); 12936 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 12937 break; 12938 case RET_PTR_TO_TCP_SOCK: 12939 mark_reg_known_zero(env, regs, BPF_REG_0); 12940 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 12941 break; 12942 case RET_PTR_TO_MEM: 12943 mark_reg_known_zero(env, regs, BPF_REG_0); 12944 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 12945 regs[BPF_REG_0].mem_size = meta.ret_mem.size; 12946 break; 12947 case RET_PTR_TO_MEM_OR_BTF_ID: 12948 { 12949 const struct btf_type *t; 12950 12951 mark_reg_known_zero(env, regs, BPF_REG_0); 12952 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 12953 if (!btf_type_is_struct(t)) { 12954 u32 tsize; 12955 const struct btf_type *ret; 12956 const char *tname; 12957 12958 /* resolve the type size of ksym. */ 12959 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 12960 if (IS_ERR(ret)) { 12961 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 12962 verbose(env, "unable to resolve the size of type '%s': %ld\n", 12963 tname, PTR_ERR(ret)); 12964 return -EINVAL; 12965 } 12966 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 12967 regs[BPF_REG_0].mem_size = tsize; 12968 } else { 12969 if (returns_cpu_specific_alloc_ptr) { 12970 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 12971 } else { 12972 /* MEM_RDONLY may be carried from ret_flag, but it 12973 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 12974 * it will confuse the check of PTR_TO_BTF_ID in 12975 * check_mem_access(). 12976 */ 12977 ret_flag &= ~MEM_RDONLY; 12978 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 12979 } 12980 12981 regs[BPF_REG_0].btf = meta.ret_btf; 12982 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12983 } 12984 break; 12985 } 12986 case RET_PTR_TO_BTF_ID: 12987 { 12988 struct btf *ret_btf; 12989 int ret_btf_id; 12990 12991 mark_reg_known_zero(env, regs, BPF_REG_0); 12992 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 12993 if (func_id == BPF_FUNC_kptr_xchg) { 12994 ret_btf = meta.kptr_field->kptr.btf; 12995 ret_btf_id = meta.kptr_field->kptr.btf_id; 12996 if (!btf_is_kernel(ret_btf)) { 12997 regs[BPF_REG_0].type |= MEM_ALLOC; 12998 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 12999 regs[BPF_REG_0].type |= MEM_PERCPU; 13000 } 13001 } else { 13002 if (fn->ret_btf_id == BPF_PTR_POISON) { 13003 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 13004 func_id_name(func_id)); 13005 return -EFAULT; 13006 } 13007 ret_btf = btf_vmlinux; 13008 ret_btf_id = *fn->ret_btf_id; 13009 } 13010 if (ret_btf_id == 0) { 13011 verbose(env, "invalid return type %u of func %s#%d\n", 13012 base_type(ret_type), func_id_name(func_id), 13013 func_id); 13014 return -EINVAL; 13015 } 13016 regs[BPF_REG_0].btf = ret_btf; 13017 regs[BPF_REG_0].btf_id = ret_btf_id; 13018 break; 13019 } 13020 default: 13021 verbose(env, "unknown return type %u of func %s#%d\n", 13022 base_type(ret_type), func_id_name(func_id), func_id); 13023 return -EINVAL; 13024 } 13025 13026 if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id) 13027 regs[BPF_REG_0].id = ++env->id_gen; 13028 13029 if (is_ptr_cast_function(func_id) && 13030 find_reference_state(env->cur_state, meta.ref_obj.id)) { 13031 struct bpf_verifier_state *branch; 13032 struct bpf_reg_state *r0; 13033 13034 err = validate_ref_obj(env, &meta.ref_obj); 13035 if (err) 13036 return err; 13037 13038 bpf_diag_mod_end(env); 13039 13040 /* 13041 * In order for a release of any of the original or cast pointers 13042 * to invalidate all other pointers, reuse the same reference id for 13043 * the cast result. 13044 * This reference id can't be used for nullness propagation, 13045 * as cast might return NULL for a non-NULL input. 13046 * Hence, explore the NULL case as a separate branch. 13047 */ 13048 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13049 if (IS_ERR(branch)) 13050 return PTR_ERR(branch); 13051 13052 r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0]; 13053 __mark_reg_known_zero(r0); 13054 r0->type = SCALAR_VALUE; 13055 13056 bpf_diag_mod_begin(env, ®s[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE); 13057 regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL; 13058 regs[BPF_REG_0].id = meta.ref_obj.id; 13059 } else if (is_acquire_function(func_id, meta.map.ptr)) { 13060 int id = acquire_reference(env, insn_idx, 0); 13061 13062 if (id < 0) 13063 return id; 13064 13065 regs[BPF_REG_0].id = id; 13066 } 13067 13068 if (func_id == BPF_FUNC_dynptr_data) 13069 regs[BPF_REG_0].parent_id = meta.dynptr.id; 13070 13071 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 13072 if (err) 13073 return err; 13074 13075 bpf_diag_mod_end(env); 13076 13077 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 13078 if (err) 13079 return err; 13080 13081 if ((func_id == BPF_FUNC_get_stack || 13082 func_id == BPF_FUNC_get_task_stack) && 13083 !env->prog->has_callchain_buf) { 13084 const char *err_str; 13085 13086 #ifdef CONFIG_PERF_EVENTS 13087 err = get_callchain_buffers(sysctl_perf_event_max_stack); 13088 err_str = "cannot get callchain buffer for func %s#%d\n"; 13089 #else 13090 err = -ENOTSUPP; 13091 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 13092 #endif 13093 if (err) { 13094 verbose(env, err_str, func_id_name(func_id), func_id); 13095 return err; 13096 } 13097 13098 env->prog->has_callchain_buf = true; 13099 } 13100 13101 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 13102 env->prog->call_get_stack = true; 13103 13104 if (func_id == BPF_FUNC_get_func_ip) { 13105 if (check_get_func_ip(env)) 13106 return -ENOTSUPP; 13107 env->prog->call_get_func_ip = true; 13108 } 13109 13110 if (func_id == BPF_FUNC_tail_call) { 13111 if (env->cur_state->curframe) { 13112 struct bpf_verifier_state *branch; 13113 13114 /* 13115 * A taken tail call is modeled as a return from the current 13116 * frame. A callback frame cannot be left that way because 13117 * prepare_func_exit() would apply its return contract to the 13118 * unknown R0 synthesized below. Stack-depth validation rejects 13119 * this construct anyway. 13120 */ 13121 if (cur_func(env)->in_callback_fn) { 13122 verbose(env, "cannot tail call within callback\n"); 13123 return -EINVAL; 13124 } 13125 mark_reg_scratched(env, BPF_REG_0); 13126 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13127 if (IS_ERR(branch)) 13128 return PTR_ERR(branch); 13129 clear_all_pkt_pointers(env); 13130 mark_reg_unknown(env, regs, BPF_REG_0); 13131 err = prepare_func_exit(env, &env->insn_idx); 13132 if (err) 13133 return err; 13134 env->insn_idx--; 13135 } else { 13136 changes_data = false; 13137 } 13138 } 13139 13140 if (changes_data) 13141 clear_all_pkt_pointers(env); 13142 return 0; 13143 } 13144 13145 /* 13146 * Mark the register(s) holding a @size byte kfunc return value as unknown 13147 * scalars and return how many registers that took. Both halves of a register 13148 * pair are treated the same way. 13149 * 13150 * R0 is written in the diagnostic modification scope the caller opened before 13151 * the caller-saved scrub, since R0 gets no scrub record of its own and that 13152 * scope is what carries its pre-call value into the history. A scope tracks a 13153 * single register and does not nest, so close it before recording the rest of 13154 * the return value. A value that fits in R0 leaves the caller's scope open for 13155 * the caller to close, so a later write to R0 still lands in it. 13156 */ 13157 static u32 mark_kfunc_ret_regs(struct bpf_verifier_env *env, 13158 struct bpf_reg_state *regs, u32 size) 13159 { 13160 u32 i, nregs = ret_regs_cnt(size); 13161 13162 mark_reg_unknown(env, regs, ret_regs[0]); 13163 if (nregs == 1) 13164 return nregs; 13165 13166 bpf_diag_mod_end(env); 13167 for (i = 1; i < nregs; i++) { 13168 bpf_diag_mod_begin(env, ®s[ret_regs[i]], NULL, BPF_DIAG_MOD_WRITE); 13169 mark_reg_unknown(env, regs, ret_regs[i]); 13170 bpf_diag_mod_end(env); 13171 } 13172 13173 return nregs; 13174 } 13175 13176 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta) 13177 { 13178 return meta->kfunc_flags & KF_ACQUIRE; 13179 } 13180 13181 static bool is_kfunc_release(struct bpf_call_arg_meta *meta) 13182 { 13183 return meta->kfunc_flags & KF_RELEASE; 13184 } 13185 13186 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta) 13187 { 13188 return meta->kfunc_flags & KF_DESTRUCTIVE; 13189 } 13190 13191 static bool is_kfunc_perfmon(struct bpf_call_arg_meta *meta) 13192 { 13193 return meta->kfunc_flags & KF_PERFMON; 13194 } 13195 13196 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta) 13197 { 13198 return meta->kfunc_flags & KF_RCU; 13199 } 13200 13201 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta) 13202 { 13203 return meta->kfunc_flags & KF_RCU_PROTECTED; 13204 } 13205 13206 static bool is_kfunc_arg_mem_size(const struct btf *btf, 13207 const struct btf_param *arg) 13208 { 13209 const struct btf_type *t; 13210 13211 t = btf_type_skip_modifiers(btf, arg->type, NULL); 13212 if (!btf_type_is_scalar(t)) 13213 return false; 13214 13215 return btf_param_match_suffix(btf, arg, "__sz"); 13216 } 13217 13218 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 13219 const struct btf_param *arg) 13220 { 13221 const struct btf_type *t; 13222 13223 t = btf_type_skip_modifiers(btf, arg->type, NULL); 13224 if (!btf_type_is_scalar(t)) 13225 return false; 13226 13227 return btf_param_match_suffix(btf, arg, "__szk"); 13228 } 13229 13230 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 13231 { 13232 return btf_param_match_suffix(btf, arg, "__k"); 13233 } 13234 13235 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 13236 { 13237 return btf_param_match_suffix(btf, arg, "__ign"); 13238 } 13239 13240 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 13241 { 13242 return btf_param_match_suffix(btf, arg, "__map"); 13243 } 13244 13245 static bool is_kfunc_arg_const_map(const struct btf *btf, const struct btf_param *arg) 13246 { 13247 return btf_param_match_suffix(btf, arg, "__const_map"); 13248 } 13249 13250 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 13251 { 13252 return btf_param_match_suffix(btf, arg, "__alloc"); 13253 } 13254 13255 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 13256 { 13257 return btf_param_match_suffix(btf, arg, "__uninit"); 13258 } 13259 13260 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 13261 { 13262 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 13263 } 13264 13265 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 13266 { 13267 return btf_param_match_suffix(btf, arg, "__nullable") || 13268 btf_param_match_suffix(btf, arg, "__arena"); 13269 } 13270 13271 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 13272 { 13273 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 13274 } 13275 13276 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 13277 { 13278 return btf_param_match_suffix(btf, arg, "__str"); 13279 } 13280 13281 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 13282 { 13283 return btf_param_match_suffix(btf, arg, "__irq_flag"); 13284 } 13285 13286 static bool is_kfunc_arg_ctx_out(const struct btf *btf, const struct btf_param *arg) 13287 { 13288 return btf_param_match_suffix(btf, arg, "__ctx_out"); 13289 } 13290 13291 static bool is_kfunc_arg_arena(const struct btf *btf, const struct btf_param *arg) 13292 { 13293 return btf_param_match_suffix(btf, arg, "__arena__nullable") || 13294 btf_param_match_suffix(btf, arg, "__arena"); 13295 } 13296 13297 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 13298 const struct btf_param *arg, 13299 const char *name) 13300 { 13301 int len, target_len = strlen(name); 13302 const char *param_name; 13303 13304 param_name = btf_name_by_offset(btf, arg->name_off); 13305 if (str_is_empty(param_name)) 13306 return false; 13307 len = strlen(param_name); 13308 if (len != target_len) 13309 return false; 13310 if (strcmp(param_name, name)) 13311 return false; 13312 13313 return true; 13314 } 13315 13316 enum { 13317 KF_ARG_DYNPTR_ID, 13318 KF_ARG_LIST_HEAD_ID, 13319 KF_ARG_LIST_NODE_ID, 13320 KF_ARG_RB_ROOT_ID, 13321 KF_ARG_RB_NODE_ID, 13322 KF_ARG_WORKQUEUE_ID, 13323 KF_ARG_RES_SPIN_LOCK_ID, 13324 KF_ARG_TASK_WORK_ID, 13325 KF_ARG_PROG_AUX_ID, 13326 KF_ARG_TIMER_ID, 13327 KF_ARG_RCU_HEAD_ID 13328 }; 13329 13330 BTF_ID_LIST(kf_arg_btf_ids) 13331 BTF_ID(struct, bpf_dynptr) 13332 BTF_ID(struct, bpf_list_head) 13333 BTF_ID(struct, bpf_list_node) 13334 BTF_ID(struct, bpf_rb_root) 13335 BTF_ID(struct, bpf_rb_node) 13336 BTF_ID(struct, bpf_wq) 13337 BTF_ID(struct, bpf_res_spin_lock) 13338 BTF_ID(struct, bpf_task_work) 13339 BTF_ID(struct, bpf_prog_aux) 13340 BTF_ID(struct, bpf_timer) 13341 BTF_ID(struct, bpf_rcu_head) 13342 13343 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 13344 const struct btf_param *arg, int type) 13345 { 13346 const struct btf_type *t; 13347 u32 res_id; 13348 13349 t = btf_type_skip_modifiers(btf, arg->type, NULL); 13350 if (!t) 13351 return false; 13352 if (!btf_type_is_ptr(t)) 13353 return false; 13354 t = btf_type_skip_modifiers(btf, t->type, &res_id); 13355 if (!t) 13356 return false; 13357 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 13358 } 13359 13360 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 13361 { 13362 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 13363 } 13364 13365 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 13366 { 13367 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 13368 } 13369 13370 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 13371 { 13372 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 13373 } 13374 13375 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 13376 { 13377 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 13378 } 13379 13380 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 13381 { 13382 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 13383 } 13384 13385 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 13386 { 13387 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 13388 } 13389 13390 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 13391 { 13392 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 13393 } 13394 13395 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 13396 { 13397 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 13398 } 13399 13400 static bool is_kfunc_arg_rcu_head(const struct btf *btf, const struct btf_param *arg) 13401 { 13402 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RCU_HEAD_ID); 13403 } 13404 13405 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 13406 { 13407 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 13408 } 13409 13410 static bool is_rbtree_node_type(const struct btf_type *t) 13411 { 13412 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 13413 } 13414 13415 static bool is_list_node_type(const struct btf_type *t) 13416 { 13417 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 13418 } 13419 13420 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 13421 const struct btf_param *arg) 13422 { 13423 const struct btf_type *t; 13424 13425 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 13426 if (!t) 13427 return false; 13428 13429 return true; 13430 } 13431 13432 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 13433 { 13434 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 13435 } 13436 13437 /* 13438 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 13439 * - the _impl prototype with full arg list (meta->func_proto) 13440 * - the BPF API prototype w/o implicit args (func->type in BTF) 13441 * To determine whether an argument is implicit, we compare its position 13442 * against the number of arguments in the prototype w/o implicit args. 13443 */ 13444 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx) 13445 { 13446 const struct btf_type *func, *func_proto; 13447 u32 argn; 13448 13449 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 13450 return false; 13451 13452 func = btf_type_by_id(meta->btf, meta->func_id); 13453 func_proto = btf_type_by_id(meta->btf, func->type); 13454 argn = btf_type_vlen(func_proto); 13455 13456 return argn <= arg_idx; 13457 } 13458 13459 #define BTF_MEMBER_MAX_DEPTH 4 13460 #define BTF_MEMBER_PATH_LEN 64 13461 13462 struct btf_member_path { 13463 const struct btf_member *member[BTF_MEMBER_MAX_DEPTH]; 13464 bool in_array[BTF_MEMBER_MAX_DEPTH]; 13465 const struct btf_type *bad_type; 13466 int depth; 13467 bool too_deep; 13468 }; 13469 13470 static bool btf_member_kind_allowed(const struct btf *btf, const struct btf_type *t, 13471 u32 member_kinds) 13472 { 13473 if ((member_kinds & BTF_MEMBER_SCALAR) && btf_type_is_scalar(t)) 13474 return true; 13475 if ((member_kinds & BTF_MEMBER_ARENA_PTR) && btf_type_is_arena_ptr(btf, t)) 13476 return true; 13477 return false; 13478 } 13479 13480 /* 13481 * Returns true if every member of struct @t is of a kind listed in 13482 * @member_kinds, 4 levels of nesting allowed. An array member counts as its 13483 * element type. 13484 */ 13485 static bool btf_struct_member_walk(struct bpf_verifier_env *env, const struct btf *btf, 13486 const struct btf_type *t, u32 member_kinds, int rec, 13487 struct btf_member_path *path) 13488 { 13489 const struct btf_type *member_type; 13490 const struct btf_member *member; 13491 bool in_array; 13492 u32 i; 13493 13494 if (!btf_type_is_struct(t)) 13495 return false; 13496 13497 for_each_member(i, t, member) { 13498 const struct btf_array *array; 13499 13500 in_array = false; 13501 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 13502 /* 13503 * Every element of an array is laid out in the value being 13504 * returned, so an array counts as its element type however many 13505 * dimensions deep that is. 13506 */ 13507 while (btf_type_is_array(member_type)) { 13508 array = btf_array(member_type); 13509 if (!array->nelems) { 13510 member_type = NULL; 13511 goto bad_member; 13512 } 13513 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 13514 in_array = true; 13515 } 13516 if (btf_type_is_struct(member_type)) { 13517 if (rec >= BTF_MEMBER_MAX_DEPTH - 1) { 13518 verbose(env, "max struct nesting depth exceeded\n"); 13519 if (path) 13520 path->too_deep = true; 13521 return false; 13522 } 13523 if (!btf_struct_member_walk(env, btf, member_type, member_kinds, 13524 rec + 1, path)) 13525 goto bad_path; 13526 continue; 13527 } 13528 if (!btf_member_kind_allowed(btf, member_type, member_kinds)) 13529 goto bad_member; 13530 } 13531 return true; 13532 13533 bad_member: 13534 if (path) { 13535 path->depth = rec + 1; 13536 path->bad_type = member_type; 13537 } 13538 bad_path: 13539 if (path && path->depth) { 13540 path->member[rec] = member; 13541 path->in_array[rec] = in_array; 13542 } 13543 return false; 13544 } 13545 13546 bool btf_struct_is_composed_of(struct bpf_verifier_env *env, 13547 const struct btf *btf, 13548 const struct btf_type *t, u32 member_kinds) 13549 { 13550 return btf_struct_member_walk(env, btf, t, member_kinds, 0, NULL); 13551 } 13552 13553 static bool btf_type_is_scalar_struct(struct bpf_verifier_env *env, 13554 const struct btf *btf, 13555 const struct btf_type *t) 13556 { 13557 return btf_struct_is_composed_of(env, btf, t, BTF_MEMBER_SCALAR); 13558 } 13559 13560 static int resolve_func_arg_type(struct bpf_verifier_env *env, 13561 struct bpf_reg_state *reg, u32 arg, argno_t argno, 13562 struct bpf_call_arg_meta *meta, 13563 enum bpf_arg_type *arg_type, u32 *arg_size) 13564 { 13565 const struct btf_param *args; 13566 const struct btf_type *ref_t, *resolve_ret; 13567 const struct btf *btf; 13568 const char *ref_tname; 13569 u32 ref_id; 13570 13571 if (base_type(*arg_type) == ARG_PTR_TO_MAP_VALUE) 13572 return resolve_map_arg_type(env, meta, arg_type); 13573 13574 if (base_type(*arg_type) != ARG_PTR_TO_BTF_ID) 13575 return 0; 13576 13577 if (!is_kfunc(meta) || arg_type_is_release(*arg_type) || 13578 base_type(reg->type) == PTR_TO_BTF_ID || 13579 reg2btf_ids[base_type(reg->type)]) 13580 return 0; 13581 13582 args = btf_params(meta->func_proto); 13583 ref_id = *meta->fn->arg_btf_id[arg]; 13584 btf = is_kfunc_arg_map(meta->btf, &args[arg]) ? btf_vmlinux : meta->btf; 13585 ref_t = btf_type_skip_modifiers(btf, ref_id, &ref_id); 13586 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13587 13588 if (!btf_type_is_scalar_struct(env, btf, ref_t)) 13589 return 0; 13590 13591 resolve_ret = btf_resolve_size(btf, ref_t, arg_size); 13592 if (IS_ERR(resolve_ret)) { 13593 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 13594 reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname, 13595 PTR_ERR(resolve_ret)); 13596 return -EINVAL; 13597 } 13598 *arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE | 13599 (*arg_type & (PTR_MAYBE_NULL | MEM_UNINIT)); 13600 13601 return 0; 13602 } 13603 13604 static void btf_member_path_str(const struct btf *btf, const struct btf_member_path *path, 13605 char *buf, size_t buf_sz) 13606 { 13607 size_t len = 0; 13608 int i; 13609 13610 buf[0] = '\0'; 13611 for (i = 0; i < path->depth; i++) { 13612 const char *name = btf_name_by_offset(btf, path->member[i]->name_off); 13613 13614 /* An anonymous struct or union has no name to spell. */ 13615 if (!name || !name[0]) 13616 continue; 13617 len += scnprintf(buf + len, buf_sz - len, "%s%s", len ? "." : "", name); 13618 if (path->in_array[i]) 13619 len += scnprintf(buf + len, buf_sz - len, "[]"); 13620 } 13621 } 13622 13623 enum special_kfunc_type { 13624 KF_bpf_obj_new_impl, 13625 KF_bpf_obj_new, 13626 KF_bpf_obj_drop_impl, 13627 KF_bpf_obj_drop, 13628 KF_bpf_refcount_acquire_impl, 13629 KF_bpf_refcount_acquire, 13630 KF_bpf_list_push_front_impl, 13631 KF_bpf_list_push_front, 13632 KF_bpf_list_push_back_impl, 13633 KF_bpf_list_push_back, 13634 KF_bpf_list_add, 13635 KF_bpf_list_pop_front, 13636 KF_bpf_list_pop_back, 13637 KF_bpf_list_del, 13638 KF_bpf_list_front, 13639 KF_bpf_list_back, 13640 KF_bpf_list_is_first, 13641 KF_bpf_list_is_last, 13642 KF_bpf_list_empty, 13643 KF_bpf_cast_to_kern_ctx, 13644 KF_bpf_rdonly_cast, 13645 KF_bpf_rcu_read_lock, 13646 KF_bpf_rcu_read_unlock, 13647 KF_bpf_rbtree_remove, 13648 KF_bpf_rbtree_add_impl, 13649 KF_bpf_rbtree_add, 13650 KF_bpf_rbtree_first, 13651 KF_bpf_rbtree_root, 13652 KF_bpf_rbtree_left, 13653 KF_bpf_rbtree_right, 13654 KF_bpf_dynptr_from_skb, 13655 KF_bpf_dynptr_from_xdp, 13656 KF_bpf_dynptr_from_skb_meta, 13657 KF_bpf_xdp_pull_data, 13658 KF_bpf_dynptr_slice, 13659 KF_bpf_dynptr_slice_rdwr, 13660 KF_bpf_dynptr_clone, 13661 KF_bpf_percpu_obj_new_impl, 13662 KF_bpf_percpu_obj_new, 13663 KF_bpf_percpu_obj_drop_impl, 13664 KF_bpf_percpu_obj_drop, 13665 KF_bpf_throw, 13666 KF_bpf_wq_set_callback, 13667 KF_bpf_preempt_disable, 13668 KF_bpf_preempt_enable, 13669 KF_bpf_iter_css_task_new, 13670 KF_bpf_session_cookie, 13671 KF_bpf_get_kmem_cache, 13672 KF_bpf_local_irq_save, 13673 KF_bpf_local_irq_restore, 13674 KF_bpf_iter_num_new, 13675 KF_bpf_iter_num_next, 13676 KF_bpf_iter_num_destroy, 13677 KF_bpf_set_dentry_xattr, 13678 KF_bpf_remove_dentry_xattr, 13679 KF_bpf_res_spin_lock, 13680 KF_bpf_res_spin_unlock, 13681 KF_bpf_res_spin_lock_irqsave, 13682 KF_bpf_res_spin_unlock_irqrestore, 13683 KF_bpf_dynptr_from_file, 13684 KF_bpf_dynptr_file_discard, 13685 KF___bpf_trap, 13686 KF_bpf_task_work_schedule_signal, 13687 KF_bpf_task_work_schedule_resume, 13688 KF_bpf_call_rcu, 13689 KF_bpf_call_rcu_tasks_trace, 13690 KF_bpf_arena_alloc_pages, 13691 KF_bpf_arena_free_pages, 13692 KF_bpf_session_is_return, 13693 }; 13694 13695 BTF_ID_LIST(special_kfunc_list) 13696 BTF_ID(func, bpf_obj_new_impl) 13697 BTF_ID(func, bpf_obj_new) 13698 BTF_ID(func, bpf_obj_drop_impl) 13699 BTF_ID(func, bpf_obj_drop) 13700 BTF_ID(func, bpf_refcount_acquire_impl) 13701 BTF_ID(func, bpf_refcount_acquire) 13702 BTF_ID(func, bpf_list_push_front_impl) 13703 BTF_ID(func, bpf_list_push_front) 13704 BTF_ID(func, bpf_list_push_back_impl) 13705 BTF_ID(func, bpf_list_push_back) 13706 BTF_ID(func, bpf_list_add) 13707 BTF_ID(func, bpf_list_pop_front) 13708 BTF_ID(func, bpf_list_pop_back) 13709 BTF_ID(func, bpf_list_del) 13710 BTF_ID(func, bpf_list_front) 13711 BTF_ID(func, bpf_list_back) 13712 BTF_ID(func, bpf_list_is_first) 13713 BTF_ID(func, bpf_list_is_last) 13714 BTF_ID(func, bpf_list_empty) 13715 BTF_ID(func, bpf_cast_to_kern_ctx) 13716 BTF_ID(func, bpf_rdonly_cast) 13717 BTF_ID(func, bpf_rcu_read_lock) 13718 BTF_ID(func, bpf_rcu_read_unlock) 13719 BTF_ID(func, bpf_rbtree_remove) 13720 BTF_ID(func, bpf_rbtree_add_impl) 13721 BTF_ID(func, bpf_rbtree_add) 13722 BTF_ID(func, bpf_rbtree_first) 13723 BTF_ID(func, bpf_rbtree_root) 13724 BTF_ID(func, bpf_rbtree_left) 13725 BTF_ID(func, bpf_rbtree_right) 13726 #ifdef CONFIG_NET 13727 BTF_ID(func, bpf_dynptr_from_skb) 13728 BTF_ID(func, bpf_dynptr_from_xdp) 13729 BTF_ID(func, bpf_dynptr_from_skb_meta) 13730 BTF_ID(func, bpf_xdp_pull_data) 13731 #else 13732 BTF_ID_UNUSED 13733 BTF_ID_UNUSED 13734 BTF_ID_UNUSED 13735 BTF_ID_UNUSED 13736 #endif 13737 BTF_ID(func, bpf_dynptr_slice) 13738 BTF_ID(func, bpf_dynptr_slice_rdwr) 13739 BTF_ID(func, bpf_dynptr_clone) 13740 BTF_ID(func, bpf_percpu_obj_new_impl) 13741 BTF_ID(func, bpf_percpu_obj_new) 13742 BTF_ID(func, bpf_percpu_obj_drop_impl) 13743 BTF_ID(func, bpf_percpu_obj_drop) 13744 BTF_ID(func, bpf_throw) 13745 BTF_ID(func, bpf_wq_set_callback) 13746 BTF_ID(func, bpf_preempt_disable) 13747 BTF_ID(func, bpf_preempt_enable) 13748 #ifdef CONFIG_CGROUPS 13749 BTF_ID(func, bpf_iter_css_task_new) 13750 #else 13751 BTF_ID_UNUSED 13752 #endif 13753 #ifdef CONFIG_BPF_EVENTS 13754 BTF_ID(func, bpf_session_cookie) 13755 #else 13756 BTF_ID_UNUSED 13757 #endif 13758 BTF_ID(func, bpf_get_kmem_cache) 13759 BTF_ID(func, bpf_local_irq_save) 13760 BTF_ID(func, bpf_local_irq_restore) 13761 BTF_ID(func, bpf_iter_num_new) 13762 BTF_ID(func, bpf_iter_num_next) 13763 BTF_ID(func, bpf_iter_num_destroy) 13764 #ifdef CONFIG_BPF_LSM 13765 BTF_ID(func, bpf_set_dentry_xattr) 13766 BTF_ID(func, bpf_remove_dentry_xattr) 13767 #else 13768 BTF_ID_UNUSED 13769 BTF_ID_UNUSED 13770 #endif 13771 BTF_ID(func, bpf_res_spin_lock) 13772 BTF_ID(func, bpf_res_spin_unlock) 13773 BTF_ID(func, bpf_res_spin_lock_irqsave) 13774 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 13775 BTF_ID(func, bpf_dynptr_from_file) 13776 BTF_ID(func, bpf_dynptr_file_discard) 13777 BTF_ID(func, __bpf_trap) 13778 BTF_ID(func, bpf_task_work_schedule_signal) 13779 BTF_ID(func, bpf_task_work_schedule_resume) 13780 BTF_ID(func, bpf_call_rcu) 13781 BTF_ID(func, bpf_call_rcu_tasks_trace) 13782 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT) 13783 BTF_ID(func, bpf_arena_alloc_pages) 13784 BTF_ID(func, bpf_arena_free_pages) 13785 #else 13786 BTF_ID_UNUSED 13787 BTF_ID_UNUSED 13788 #endif 13789 #ifdef CONFIG_BPF_EVENTS 13790 BTF_ID(func, bpf_session_is_return) 13791 #else 13792 BTF_ID_UNUSED 13793 #endif 13794 13795 static bool is_bpf_cast_to_kern_ctx_kfunc(const struct bpf_call_arg_meta *meta) 13796 { 13797 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]); 13798 } 13799 13800 static bool is_bpf_dynptr_clone_kfunc(const struct bpf_call_arg_meta *meta) 13801 { 13802 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_clone]); 13803 } 13804 13805 static bool is_bpf_iter_css_task_new_kfunc(const struct bpf_call_arg_meta *meta) 13806 { 13807 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_iter_css_task_new]); 13808 } 13809 13810 static bool is_bpf_obj_new_kfunc(u32 func_id) 13811 { 13812 return func_id == special_kfunc_list[KF_bpf_obj_new] || 13813 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 13814 } 13815 13816 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 13817 { 13818 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 13819 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 13820 } 13821 13822 static bool is_bpf_obj_drop_kfunc(u32 func_id) 13823 { 13824 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 13825 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 13826 } 13827 13828 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 13829 { 13830 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 13831 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 13832 } 13833 13834 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 13835 { 13836 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 13837 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 13838 } 13839 13840 static bool is_bpf_list_push_kfunc(u32 func_id) 13841 { 13842 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 13843 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 13844 func_id == special_kfunc_list[KF_bpf_list_push_back] || 13845 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 13846 func_id == special_kfunc_list[KF_bpf_list_add]; 13847 } 13848 13849 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 13850 { 13851 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 13852 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 13853 } 13854 13855 static bool is_call_rcu_kfunc(u32 func_id) 13856 { 13857 return func_id == special_kfunc_list[KF_bpf_call_rcu] || 13858 func_id == special_kfunc_list[KF_bpf_call_rcu_tasks_trace]; 13859 } 13860 13861 static bool is_task_work_add_kfunc(u32 func_id) 13862 { 13863 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 13864 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 13865 } 13866 13867 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta) 13868 { 13869 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 13870 return false; 13871 13872 return meta->kfunc_flags & KF_RET_NULL; 13873 } 13874 13875 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta) 13876 { 13877 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_lock]); 13878 } 13879 13880 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta) 13881 { 13882 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_rcu_read_unlock]); 13883 } 13884 13885 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta) 13886 { 13887 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_disable]); 13888 } 13889 13890 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta) 13891 { 13892 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_preempt_enable]); 13893 } 13894 13895 /* These write to what their first argument, a dynptr, points to */ 13896 BTF_SET_START(dynptr_write_kfuncs) 13897 BTF_ID(func, bpf_dynptr_copy) 13898 BTF_ID(func, bpf_dynptr_memset) 13899 #ifdef CONFIG_BPF_EVENTS 13900 BTF_ID(func, bpf_probe_read_user_dynptr) 13901 BTF_ID(func, bpf_probe_read_kernel_dynptr) 13902 BTF_ID(func, bpf_probe_read_user_str_dynptr) 13903 BTF_ID(func, bpf_probe_read_kernel_str_dynptr) 13904 BTF_ID(func, bpf_copy_from_user_dynptr) 13905 BTF_ID(func, bpf_copy_from_user_str_dynptr) 13906 BTF_ID(func, bpf_copy_from_user_task_dynptr) 13907 BTF_ID(func, bpf_copy_from_user_task_str_dynptr) 13908 #endif 13909 BTF_SET_END(dynptr_write_kfuncs) 13910 13911 static bool is_kfunc_dynptr_write(struct bpf_call_arg_meta *meta) 13912 { 13913 return meta->btf == btf_vmlinux && 13914 btf_id_set_contains(&dynptr_write_kfuncs, meta->func_id); 13915 } 13916 13917 /* 13918 * A write through the dynptr of an skb may reallocate its head. Before the 13919 * arguments are checked nobody knows what kind of dynptr it is. 13920 */ 13921 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta) 13922 { 13923 return is_kfunc_call(meta, special_kfunc_list[KF_bpf_xdp_pull_data]) || 13924 is_kfunc_dynptr_write(meta); 13925 } 13926 13927 static u32 kfunc_abi_slots(const struct btf_func_model *fm) 13928 { 13929 const struct bpf_jit_arg_abi *abi = bpf_jit_arg_abi(); 13930 u8 pos_of_slot[MAX_BPF_FUNC_ARG_SLOTS]; 13931 u32 i, nslots, slots = 0; 13932 13933 for (i = 0; i < fm->nr_args; i++) 13934 slots += btf_func_model_arg_slots(fm, i); 13935 13936 if (!abi) 13937 return slots; 13938 13939 nslots = bpf_jit_place_args(abi, fm, pos_of_slot); 13940 for (i = 0; i < nslots; i++) 13941 if (pos_of_slot[i] + 1 > slots) 13942 slots = pos_of_slot[i] + 1; 13943 13944 return slots; 13945 } 13946 13947 static u32 __btf_func_arg_align(const struct btf *btf, const struct btf_type *t, int rec) 13948 { 13949 const struct btf_member *member; 13950 const struct btf_type *mt; 13951 u32 align, i; 13952 13953 while (btf_type_is_array(t)) 13954 t = btf_type_skip_modifiers(btf, btf_array(t)->type, NULL); 13955 13956 if (btf_type_is_int(t)) 13957 return t->size > BPF_REG_SIZE ? t->size : BPF_REG_SIZE; 13958 if (!btf_type_is_struct(t)) 13959 return BPF_REG_SIZE; 13960 if (rec >= BTF_MEMBER_MAX_DEPTH) 13961 return 0; 13962 13963 for_each_member(i, t, member) { 13964 mt = btf_type_skip_modifiers(btf, member->type, NULL); 13965 align = __btf_func_arg_align(btf, mt, rec + 1); 13966 if (!align) 13967 return 0; 13968 if (align > BPF_REG_SIZE) 13969 return 2 * BPF_REG_SIZE; 13970 } 13971 return BPF_REG_SIZE; 13972 } 13973 13974 u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t) 13975 { 13976 return __btf_func_arg_align(btf, t, 0); 13977 } 13978 13979 static int 13980 get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 13981 const struct btf_param *args, int arg, int nargs, u32 slot, 13982 struct bpf_func_proto *proto) 13983 { 13984 const struct btf_type *t, *ref_t = NULL, *resolve_ret; 13985 const u32 *ref_id_ptr = NULL; 13986 argno_t argno = argno_from_arg(slot + 1); 13987 const char *ref_tname = NULL; 13988 u32 ref_id, type_size; 13989 int arg_type; 13990 13991 proto->arg_btf_id[arg] = NULL; 13992 13993 if (is_kfunc_arg_prog_aux(meta->btf, &args[arg])) 13994 return ARG_PTR_TO_PROG_AUX; 13995 13996 if (is_kfunc_arg_ignore(meta->btf, &args[arg]) || is_kfunc_arg_implicit(meta, arg)) 13997 return ARG_IGNORE; 13998 13999 t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL); 14000 14001 /* Scalar arguments are classified from their BTF suffix/name alone. */ 14002 if (btf_type_is_scalar(t)) { 14003 if (is_kfunc_arg_constant(meta->btf, &args[arg])) 14004 return ARG_CONST_SCALAR; 14005 if (is_kfunc_arg_const_mem_size(meta->btf, &args[arg])) 14006 return ARG_CONST_MEM_SIZE; 14007 if (is_kfunc_arg_mem_size(meta->btf, &args[arg])) 14008 return ARG_MEM_SIZE; 14009 if (is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdonly_buf_size") || 14010 is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdwr_buf_size")) 14011 return ARG_CONST_ALLOC_SIZE_OR_ZERO; 14012 return ARG_SCALAR; 14013 } 14014 14015 if (btf_type_is_struct(t)) { 14016 if (!t->size || t->size > 2 * BPF_REG_SIZE) { 14017 verbose(env, 14018 "%s type %s has size %u, only 1 to %d bytes " 14019 "can be passed by value\n", 14020 reg_arg_name(env, argno), btf_type_str(t), t->size, 14021 2 * BPF_REG_SIZE); 14022 return -EINVAL; 14023 } 14024 if (!btf_type_is_scalar_struct(env, meta->btf, t)) { 14025 verbose(env, "%s type %s is not composed of scalars\n", 14026 reg_arg_name(env, argno), btf_type_str(t)); 14027 return -EINVAL; 14028 } 14029 return ARG_SCALAR; 14030 } 14031 14032 if (!btf_type_is_ptr(t)) { 14033 verbose(env, "Unrecognized %s type %s\n", 14034 reg_arg_name(env, argno), btf_type_str(t)); 14035 return -EINVAL; 14036 } 14037 /* Keep a pointer to the BTF field containing the resolved referent ID. */ 14038 ref_id_ptr = &t->type; 14039 ref_t = btf_type_skip_modifiers(meta->btf, *ref_id_ptr, &ref_id); 14040 while (*ref_id_ptr != ref_id) 14041 ref_id_ptr = &btf_type_by_id(meta->btf, *ref_id_ptr)->type; 14042 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 14043 14044 /* In this function, we verify the kfunc's BTF as per the argument type, 14045 * leaving the rest of the verification with respect to the register 14046 * type to our caller. When a set of conditions hold in the BTF type of 14047 * arguments, we resolve it to a known bpf_arg_type. 14048 */ 14049 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx]) || 14050 is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_is_return]) || 14051 is_kfunc_call(meta, special_kfunc_list[KF_bpf_session_cookie])) 14052 arg_type = ARG_PTR_TO_CTX; 14053 else if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 14054 arg_type = ARG_PTR_TO_CTX; 14055 else if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 14056 arg_type = ARG_PTR_TO_ALLOC_BTF_ID; 14057 else if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 14058 arg_type = ARG_PTR_TO_REFCOUNTED_KPTR; 14059 else if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) { 14060 arg_type = ARG_PTR_TO_DYNPTR; 14061 14062 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb])) 14063 arg_type |= DYNPTR_TYPE_SKB; 14064 else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_xdp])) 14065 arg_type |= DYNPTR_TYPE_XDP; 14066 else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_skb_meta])) 14067 arg_type |= DYNPTR_TYPE_SKB_META; 14068 else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_from_file]) || 14069 is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_file_discard])) 14070 /* OBJ_RELEASE for the latter comes from KF_RELEASE below */ 14071 arg_type |= DYNPTR_TYPE_FILE; 14072 } else if (is_kfunc_arg_iter(meta, arg, &args[arg])) 14073 arg_type = ARG_PTR_TO_ITER; 14074 else if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 14075 arg_type = ARG_PTR_TO_LIST_HEAD; 14076 else if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 14077 arg_type = ARG_PTR_TO_LIST_NODE; 14078 else if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 14079 arg_type = ARG_PTR_TO_RB_ROOT; 14080 else if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 14081 arg_type = ARG_PTR_TO_RB_NODE; 14082 else if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 14083 arg_type = ARG_PTR_TO_CONST_STR; 14084 else if (is_kfunc_arg_const_map(meta->btf, &args[arg])) 14085 arg_type = ARG_CONST_MAP_PTR; 14086 else if (is_kfunc_arg_map(meta->btf, &args[arg])) 14087 arg_type = ARG_PTR_TO_BTF_ID; 14088 else if (is_kfunc_arg_wq(meta->btf, &args[arg])) 14089 arg_type = ARG_PTR_TO_WORKQUEUE; 14090 else if (is_kfunc_arg_timer(meta->btf, &args[arg])) 14091 arg_type = ARG_PTR_TO_TIMER; 14092 else if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 14093 arg_type = ARG_PTR_TO_TASK_WORK; 14094 else if (is_kfunc_arg_rcu_head(meta->btf, &args[arg])) 14095 arg_type = ARG_PTR_TO_RCU_HEAD; 14096 else if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 14097 arg_type = ARG_PTR_TO_IRQ_FLAG; 14098 else if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 14099 arg_type = ARG_PTR_TO_RES_SPIN_LOCK; 14100 else if (is_kfunc_arg_ctx_out(meta->btf, &args[arg])) { 14101 if (!btf_type_is_scalar(ref_t)) { 14102 verbose(env, "%s __ctx_out argument must point to a scalar\n", 14103 reg_arg_name(env, argno)); 14104 return -EINVAL; 14105 } 14106 resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size); 14107 if (IS_ERR(resolve_ret)) { 14108 verbose(env, 14109 "%s reference type('%s %s') size cannot be determined: %ld\n", 14110 reg_arg_name(env, argno), btf_type_str(ref_t), 14111 ref_tname, PTR_ERR(resolve_ret)); 14112 return -EINVAL; 14113 } 14114 proto->arg_size[arg] = type_size; 14115 arg_type = ARG_PTR_TO_CTX_OUT | MEM_FIXED_SIZE; 14116 } else if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 14117 arg_type = ARG_PTR_TO_FUNC; 14118 else if (is_kfunc_arg_arena(meta->btf, &args[arg])) { 14119 if (!bpf_jit_supports_arena_args()) { 14120 verbose(env, "JIT does not support kfunc %s() with arena pointer arguments\n", 14121 meta->func_name); 14122 return -ENOTSUPP; 14123 } 14124 if (!env->prog->aux->arena) { 14125 verbose(env, 14126 "%s arena pointer requires a program with an associated arena\n", 14127 reg_arg_name(env, argno)); 14128 return -EINVAL; 14129 } 14130 if (reg_from_argno(argno) < 0) { 14131 verbose(env, "%s arena pointer cannot be a stack argument\n", 14132 reg_arg_name(env, argno)); 14133 return -EINVAL; 14134 } 14135 /* 14136 * Both suffixes accept a constant zero. The function model determines 14137 * whether the JIT rebases it to the arena base or preserves NULL. 14138 * The common nullable path below records that verifier property. 14139 */ 14140 arg_type = ARG_PTR_TO_ARENA; 14141 } else if (arg + 1 < nargs && 14142 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1]) || 14143 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1]))) { 14144 if (!btf_type_is_void(ref_t) && !btf_type_is_scalar(ref_t) && 14145 !btf_type_is_scalar_struct(env, meta->btf, ref_t)) { 14146 verbose(env, "%s pointer type %s %s must point to void, scalar, or struct with scalar\n", 14147 reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname); 14148 return -EINVAL; 14149 } 14150 arg_type = ARG_PTR_TO_MEM | MEM_WRITE; 14151 } else if (btf_type_is_struct(ref_t)) 14152 /* A pointer to a struct without a size argument is classified as ARG_PTR_TO_BTF_ID */ 14153 arg_type = ARG_PTR_TO_BTF_ID; 14154 else { 14155 /* 14156 * Otherwise this is a fixed-size memory buffer supported by 14157 * check_helper_mem_access(): a pointer to a scalar or a struct of 14158 * scalars. The access size is derived from the pointed-to BTF type. 14159 */ 14160 if (!btf_type_is_scalar(ref_t) && 14161 !btf_type_is_scalar_struct(env, meta->btf, ref_t)) { 14162 verbose(env, "%s pointer type %s %s must point to scalar, or struct with scalar\n", 14163 reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname); 14164 return -EINVAL; 14165 } 14166 resolve_ret = btf_resolve_size(meta->btf, ref_t, &type_size); 14167 if (IS_ERR(resolve_ret)) { 14168 verbose(env, 14169 "%s reference type('%s %s') size cannot be determined: %ld\n", 14170 reg_arg_name(env, argno), btf_type_str(ref_t), 14171 ref_tname, PTR_ERR(resolve_ret)); 14172 return -EINVAL; 14173 } 14174 proto->arg_size[arg] = type_size; 14175 arg_type = ARG_PTR_TO_MEM | MEM_FIXED_SIZE | MEM_WRITE; 14176 } 14177 14178 if (is_kfunc_arg_uninit(meta->btf, &args[arg])) 14179 arg_type |= MEM_UNINIT; 14180 14181 if (is_kfunc_arg_nullable(meta->btf, &args[arg])) 14182 arg_type |= PTR_MAYBE_NULL; 14183 14184 /* 14185 * Only the first argument of a KF_RELEASE kfunc releases anything, and 14186 * bpf_fetch_kfunc_arg_meta() only ever records BPF_REG_1 for it. 14187 */ 14188 if (is_kfunc_release(meta) && arg == 0) 14189 arg_type |= OBJ_RELEASE; 14190 14191 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID) { 14192 if (is_kfunc_arg_map(meta->btf, &args[arg])) 14193 proto->arg_btf_id[arg] = reg2btf_ids[CONST_PTR_TO_MAP]; 14194 else 14195 proto->arg_btf_id[arg] = ref_id_ptr; 14196 14197 arg_type |= PTR_TRUSTED; 14198 14199 /* 14200 * A KF_RCU kfunc accepts an RCU-protected pointer where it would 14201 * otherwise demand a referenced or trusted one. Other argument kinds 14202 * have their own provenance requirements and must not inherit MEM_RCU. 14203 */ 14204 if (is_kfunc_rcu(meta)) 14205 arg_type |= MEM_RCU; 14206 } 14207 14208 return arg_type; 14209 } 14210 14211 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 14212 const struct btf_func_model *fm, struct bpf_func_proto *proto) 14213 { 14214 const struct bpf_jit_arg_abi *abi; 14215 const struct btf *btf = meta->btf; 14216 const struct btf_param *args; 14217 const struct btf_type *t; 14218 u32 i, nargs, slots_used; 14219 int arg_type; 14220 14221 args = (const struct btf_param *)(meta->func_proto + 1); 14222 nargs = btf_type_vlen(meta->func_proto); 14223 if (nargs > MAX_BPF_FUNC_ARGS) { 14224 verbose(env, "Function %s has %d > %d args\n", meta->func_name, 14225 nargs, MAX_BPF_FUNC_ARGS); 14226 return -EINVAL; 14227 } 14228 14229 for (i = 0, slots_used = 0; i < nargs; i++) { 14230 u32 nslots = btf_func_model_arg_slots(fm, i); 14231 14232 if (nslots > 1) { 14233 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 14234 if (!btf_func_arg_align(btf, t)) { 14235 verbose(env, 14236 "Function %s arg#%d type %s nests structs more than " 14237 "%d levels deep\n", 14238 meta->func_name, i, btf_type_str(t), 14239 BTF_MEMBER_MAX_DEPTH); 14240 return -EINVAL; 14241 } 14242 } 14243 slots_used += nslots; 14244 } 14245 14246 if (slots_used > MAX_BPF_FUNC_ARGS) { 14247 verbose(env, "Function %s needs %d > %d argument slots\n", meta->func_name, 14248 slots_used, MAX_BPF_FUNC_ARGS); 14249 return -EINVAL; 14250 } 14251 14252 abi = bpf_jit_arg_abi(); 14253 14254 for (i = 0, slots_used = 0; i < nargs; i++) { 14255 u32 nslots = btf_func_model_arg_slots(fm, i); 14256 14257 if (!abi && nslots > 1) { 14258 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 14259 verbose(env, 14260 "Function %s arg#%d type %s cannot be passed at " 14261 "argument slot %d on this architecture\n", 14262 meta->func_name, i, btf_type_str(t), slots_used); 14263 return -EINVAL; 14264 } 14265 slots_used += nslots; 14266 14267 arg_type = get_kfunc_arg_type(env, meta, args, i, nargs, 14268 slots_used - nslots, proto); 14269 if (arg_type < 0) 14270 return arg_type; 14271 14272 proto->arg_type[i] = arg_type; 14273 } 14274 14275 if (slots_used > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 14276 verbose(env, "JIT does not support kfunc %s() with %d argument slots\n", 14277 meta->func_name, slots_used); 14278 return -ENOTSUPP; 14279 } 14280 14281 return check_arg_prog_aux(env, proto) ? 0 : -EINVAL; 14282 } 14283 14284 static int process_arg_ptr_to_btf_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 14285 argno_t argno, enum bpf_arg_type arg_type, 14286 const struct btf *arg_btf, u32 arg_btf_id, 14287 struct bpf_call_arg_meta *meta, int insn_idx) 14288 { 14289 bool taking_projection, struct_same, strict_type_match = false; 14290 const struct btf_type *arg_t, *reg_t; 14291 const char *arg_tname, *reg_tname; 14292 const struct btf *reg_btf; 14293 u32 reg_btf_id; 14294 14295 if (base_type(reg->type) == PTR_TO_BTF_ID) { 14296 reg_btf = reg->btf; 14297 reg_btf_id = reg->btf_id; 14298 } else { 14299 reg_btf = btf_vmlinux; 14300 reg_btf_id = *reg2btf_ids[base_type(reg->type)]; 14301 } 14302 14303 /* 14304 * Enforce strict type matching for arguments that release a reference, 14305 * or are no-cast aliases. We do _not_ enforce strict matching by default, 14306 * as we want to enable BPF programs to pass types that are bitwise 14307 * equivalent without forcing them to explicitly cast with something 14308 * like bpf_cast_to_kern_ctx(). 14309 * 14310 * For example, say we had a type like the following: 14311 * 14312 * struct bpf_cpumask { 14313 * cpumask_t cpumask; 14314 * refcount_t usage; 14315 * }; 14316 * 14317 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 14318 * to a struct cpumask, so it would be safe to pass a struct 14319 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 14320 * 14321 * The philosophy here is similar to how we allow scalars of different 14322 * types to be passed to kfuncs as long as the size is the same. The 14323 * only difference here is that we're simply allowing 14324 * btf_struct_ids_match() to walk the struct at the 0th offset, and 14325 * resolve types. 14326 */ 14327 if ((arg_type_is_release(arg_type) && !is_helper_call(meta, BPF_FUNC_sk_release)) || 14328 (is_kfunc(meta) && btf_type_ids_nocast_alias(&env->log, reg_btf, reg_btf_id, 14329 arg_btf, arg_btf_id))) 14330 strict_type_match = true; 14331 14332 arg_t = btf_type_skip_modifiers(arg_btf, arg_btf_id, &arg_btf_id); 14333 arg_tname = btf_name_by_offset(arg_btf, arg_t->name_off); 14334 reg_t = btf_type_skip_modifiers(reg_btf, reg_btf_id, ®_btf_id); 14335 reg_tname = btf_name_by_offset(reg_btf, reg_t->name_off); 14336 14337 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_btf_id, 14338 reg->var_off.value, arg_btf, arg_btf_id, 14339 strict_type_match, !type_is_alloc(reg->type)); 14340 14341 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 14342 * actually use it -- it must cast to the underlying type. So we allow 14343 * caller to pass in the underlying type. 14344 */ 14345 taking_projection = is_kfunc(meta) && btf_is_projection_of(arg_tname, reg_tname); 14346 if (!taking_projection && !struct_same) { 14347 verbose(env, "%s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 14348 meta->func_name, reg_arg_name(env, argno), 14349 btf_type_str(arg_t), arg_tname, 14350 reg_arg_name(env, argno), btf_type_str(reg_t), reg_tname); 14351 return -EINVAL; 14352 } 14353 return 0; 14354 } 14355 14356 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 14357 struct bpf_call_arg_meta *meta) 14358 { 14359 int err, spi, kfunc_class = IRQ_NATIVE_KFUNC; 14360 bool irq_save; 14361 14362 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_save]) || 14363 is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 14364 irq_save = true; 14365 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 14366 kfunc_class = IRQ_LOCK_KFUNC; 14367 } else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_local_irq_restore]) || 14368 is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) { 14369 irq_save = false; 14370 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) 14371 kfunc_class = IRQ_LOCK_KFUNC; 14372 } else { 14373 verifier_bug(env, "unknown irq flags kfunc"); 14374 return -EFAULT; 14375 } 14376 14377 if (irq_save) { 14378 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 14379 verbose(env, "expected uninitialized irq flag as %s\n", 14380 reg_arg_name(env, argno)); 14381 bpf_diag_res(env, env->insn_idx, "IRQ flag is already initialized", 14382 "Saving IRQ state requires an uninitialized stack slot for " 14383 "the IRQ flag, but this slot already contains tracked IRQ " 14384 "flag state.", 14385 "Use a fresh stack slot for this save operation, or restore " 14386 "the existing IRQ flag before reusing the slot."); 14387 return -EINVAL; 14388 } 14389 14390 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 14391 BPF_WRITE, -1, false, false); 14392 if (err) 14393 return err; 14394 14395 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 14396 if (err) 14397 return err; 14398 } else { 14399 err = is_irq_flag_reg_valid_init(env, reg); 14400 if (err) { 14401 verbose(env, "expected an initialized irq flag as %s\n", 14402 reg_arg_name(env, argno)); 14403 bpf_diag_res(env, env->insn_idx, "uninitialized IRQ flag restore", 14404 "Restoring IRQ state requires a stack slot that was " 14405 "initialized by a matching IRQ save operation on this path.", 14406 "Pass the same stack slot that was previously initialized by " 14407 "the matching IRQ save kfunc."); 14408 return err; 14409 } 14410 14411 spi = irq_flag_get_spi(env, reg); 14412 if (spi < 0) 14413 return spi; 14414 14415 mark_stack_slots_scratched(env, spi, 1); 14416 14417 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 14418 if (err) 14419 return err; 14420 14421 if (!in_rcu_cs(env)) 14422 invalidate_rcu_protected_refs(env); 14423 } 14424 return 0; 14425 } 14426 14427 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 14428 { 14429 struct btf_record *rec = reg_btf_record(reg); 14430 14431 if (!env->cur_state->active_locks) { 14432 verifier_bug(env, "%s w/o active lock", __func__); 14433 return -EFAULT; 14434 } 14435 14436 if (type_flag(reg->type) & NON_OWN_REF) { 14437 verifier_bug(env, "NON_OWN_REF already set"); 14438 return -EFAULT; 14439 } 14440 14441 reg->type |= NON_OWN_REF; 14442 if (rec->refcount_off >= 0) 14443 reg->type |= MEM_RCU; 14444 14445 return 0; 14446 } 14447 14448 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id) 14449 { 14450 struct bpf_func_state *unused; 14451 struct bpf_reg_state *reg; 14452 int err; 14453 14454 err = release_reference_nomark(env, id); 14455 WARN_ON_ONCE(err); 14456 14457 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 14458 if (reg->id == id) { 14459 reg->id = 0; 14460 ref_set_non_owning(env, reg); 14461 } 14462 })); 14463 14464 return; 14465 } 14466 14467 /* Implementation details: 14468 * 14469 * Each register points to some region of memory, which we define as an 14470 * allocation. Each allocation may embed a bpf_spin_lock which protects any 14471 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 14472 * allocation. The lock and the data it protects are colocated in the same 14473 * memory region. 14474 * 14475 * Hence, everytime a register holds a pointer value pointing to such 14476 * allocation, the verifier preserves a unique reg->id for it. 14477 * 14478 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 14479 * bpf_spin_lock is called. 14480 * 14481 * To enable this, lock state in the verifier captures two values: 14482 * active_lock.ptr = Register's type specific pointer 14483 * active_lock.id = A unique ID for each register pointer value 14484 * 14485 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 14486 * supported register types. 14487 * 14488 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 14489 * allocated objects is the reg->btf pointer. 14490 * 14491 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 14492 * can establish the provenance of the map value statically for each distinct 14493 * lookup into such maps. They always contain a single map value hence unique 14494 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 14495 * 14496 * So, in case of global variables, they use array maps with max_entries = 1, 14497 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 14498 * into the same map value as max_entries is 1, as described above). 14499 * 14500 * In case of inner map lookups, the inner map pointer has same map_ptr as the 14501 * outer map pointer (in verifier context), but each lookup into an inner map 14502 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 14503 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 14504 * will get different reg->id assigned to each lookup, hence different 14505 * active_lock.id. 14506 * 14507 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 14508 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 14509 * returned from bpf_obj_new. Each allocation receives a new reg->id. 14510 */ 14511 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 14512 { 14513 struct bpf_reference_state *s; 14514 void *ptr; 14515 u32 id; 14516 14517 switch ((int)reg->type) { 14518 case PTR_TO_MAP_VALUE: 14519 ptr = reg->map_ptr; 14520 break; 14521 case PTR_TO_BTF_ID | MEM_ALLOC: 14522 ptr = reg->btf; 14523 break; 14524 default: 14525 verifier_bug(env, "unknown reg type for lock check"); 14526 return -EFAULT; 14527 } 14528 id = reg->id; 14529 14530 if (!env->cur_state->active_locks) 14531 return -EINVAL; 14532 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 14533 if (!s) { 14534 verbose(env, "held lock and object are not in the same allocation\n"); 14535 return -EINVAL; 14536 } 14537 return 0; 14538 } 14539 14540 static bool is_bpf_list_api_kfunc(u32 btf_id) 14541 { 14542 return is_bpf_list_push_kfunc(btf_id) || 14543 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 14544 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 14545 btf_id == special_kfunc_list[KF_bpf_list_del] || 14546 btf_id == special_kfunc_list[KF_bpf_list_front] || 14547 btf_id == special_kfunc_list[KF_bpf_list_back] || 14548 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 14549 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 14550 btf_id == special_kfunc_list[KF_bpf_list_empty]; 14551 } 14552 14553 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 14554 { 14555 return is_bpf_rbtree_add_kfunc(btf_id) || 14556 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 14557 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 14558 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 14559 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 14560 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 14561 } 14562 14563 static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta) 14564 { 14565 int flags = PROCESS_RES_LOCK; 14566 14567 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock]) || 14568 is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 14569 flags |= PROCESS_SPIN_LOCK; 14570 else if (!is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock]) && 14571 !is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) 14572 return 0; 14573 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) || 14574 is_kfunc_call(meta, special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])) 14575 flags |= PROCESS_LOCK_IRQ; 14576 return flags; 14577 } 14578 14579 static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset) 14580 { 14581 struct bpf_kfunc_meta kfunc; 14582 int err; 14583 14584 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 14585 if (err || !kfunc.flags) 14586 return false; 14587 14588 return *kfunc.flags & KF_SPINLOCK_SAFE; 14589 } 14590 14591 /* 14592 * True if insn calls a helper/kfunc that requires one of its arguments to 14593 * be a stack pointer with a constant offset. 14594 */ 14595 bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx) 14596 { 14597 const struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 14598 const struct bpf_func_proto *fn; 14599 struct bpf_kfunc_desc *desc; 14600 u32 *flags, btf_id; 14601 int i; 14602 14603 if (bpf_helper_call(insn)) { 14604 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 14605 return false; 14606 } else if (bpf_pseudo_kfunc_call(insn)) { 14607 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 14608 if (!desc) 14609 return false; 14610 fn = &desc->proto; 14611 } else { 14612 return false; 14613 } 14614 14615 /* Both initialized and uninitialized stack dynptrs need a fixed offset. */ 14616 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) 14617 if (arg_type_is_dynptr(fn->arg_type[i])) 14618 return true; 14619 14620 /* vmlinux kfuncs only */ 14621 if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0) 14622 return false; 14623 btf_id = insn->imm; 14624 14625 flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog); 14626 if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY))) 14627 return true; 14628 14629 if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 14630 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 14631 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 14632 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] || 14633 btf_id == special_kfunc_list[KF_bpf_local_irq_save] || 14634 btf_id == special_kfunc_list[KF_bpf_local_irq_restore]) 14635 return true; 14636 14637 return false; 14638 } 14639 14640 static bool is_sync_callback_calling_kfunc(u32 btf_id) 14641 { 14642 return is_bpf_rbtree_add_kfunc(btf_id); 14643 } 14644 14645 static bool is_async_callback_calling_kfunc(u32 btf_id) 14646 { 14647 return is_bpf_wq_set_callback_kfunc(btf_id) || 14648 is_task_work_add_kfunc(btf_id) || 14649 is_call_rcu_kfunc(btf_id); 14650 } 14651 14652 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 14653 { 14654 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 14655 insn->imm == special_kfunc_list[KF_bpf_throw]; 14656 } 14657 14658 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 14659 { 14660 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 14661 } 14662 14663 static bool is_callback_calling_kfunc(u32 btf_id) 14664 { 14665 return is_sync_callback_calling_kfunc(btf_id) || 14666 is_async_callback_calling_kfunc(btf_id); 14667 } 14668 14669 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 14670 { 14671 return is_bpf_rbtree_api_kfunc(btf_id); 14672 } 14673 14674 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 14675 enum btf_field_type head_field_type, 14676 u32 kfunc_btf_id) 14677 { 14678 bool ret; 14679 14680 switch (head_field_type) { 14681 case BPF_LIST_HEAD: 14682 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 14683 break; 14684 case BPF_RB_ROOT: 14685 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 14686 break; 14687 default: 14688 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 14689 btf_field_type_name(head_field_type)); 14690 return false; 14691 } 14692 14693 if (!ret) 14694 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 14695 btf_field_type_name(head_field_type)); 14696 return ret; 14697 } 14698 14699 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 14700 enum btf_field_type node_field_type, 14701 u32 kfunc_btf_id) 14702 { 14703 bool ret; 14704 14705 switch (node_field_type) { 14706 case BPF_LIST_NODE: 14707 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 14708 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 14709 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 14710 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 14711 break; 14712 case BPF_RB_NODE: 14713 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 14714 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 14715 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 14716 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 14717 break; 14718 default: 14719 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 14720 btf_field_type_name(node_field_type)); 14721 return false; 14722 } 14723 14724 if (!ret) 14725 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 14726 btf_field_type_name(node_field_type)); 14727 return ret; 14728 } 14729 14730 static int 14731 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 14732 struct bpf_reg_state *reg, argno_t argno, 14733 struct bpf_call_arg_meta *meta, 14734 enum btf_field_type head_field_type, 14735 struct btf_field **head_field) 14736 { 14737 const char *head_type_name; 14738 struct btf_field *field; 14739 struct btf_record *rec; 14740 u32 head_off; 14741 14742 if (meta->btf != btf_vmlinux) { 14743 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 14744 return -EFAULT; 14745 } 14746 14747 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 14748 return -EFAULT; 14749 14750 head_type_name = btf_field_type_name(head_field_type); 14751 if (!tnum_is_const(reg->var_off)) { 14752 verbose(env, 14753 "%s doesn't have constant offset. %s has to be at the constant offset\n", 14754 reg_arg_name(env, argno), head_type_name); 14755 return -EINVAL; 14756 } 14757 14758 rec = reg_btf_record(reg); 14759 head_off = reg->var_off.value; 14760 field = btf_record_find(rec, head_off, head_field_type); 14761 if (!field) { 14762 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 14763 return -EINVAL; 14764 } 14765 14766 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 14767 if (check_reg_allocation_locked(env, reg)) { 14768 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 14769 rec->spin_lock_off, head_type_name); 14770 return -EINVAL; 14771 } 14772 14773 if (*head_field) { 14774 verifier_bug(env, "repeating %s arg", head_type_name); 14775 return -EFAULT; 14776 } 14777 *head_field = field; 14778 return 0; 14779 } 14780 14781 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 14782 struct bpf_reg_state *reg, argno_t argno, 14783 struct bpf_call_arg_meta *meta) 14784 { 14785 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 14786 &meta->arg_list_head.field); 14787 } 14788 14789 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 14790 struct bpf_reg_state *reg, argno_t argno, 14791 struct bpf_call_arg_meta *meta) 14792 { 14793 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 14794 &meta->arg_rbtree_root.field); 14795 } 14796 14797 static int 14798 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 14799 struct bpf_reg_state *reg, argno_t argno, 14800 struct bpf_call_arg_meta *meta, 14801 enum btf_field_type head_field_type, 14802 enum btf_field_type node_field_type, 14803 struct btf_field **node_field) 14804 { 14805 const char *node_type_name; 14806 const struct btf_type *et, *t; 14807 struct btf_field *field; 14808 u32 node_off; 14809 14810 if (meta->btf != btf_vmlinux) { 14811 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 14812 return -EFAULT; 14813 } 14814 14815 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 14816 return -EFAULT; 14817 14818 node_type_name = btf_field_type_name(node_field_type); 14819 if (!tnum_is_const(reg->var_off)) { 14820 verbose(env, 14821 "%s doesn't have constant offset. %s has to be at the constant offset\n", 14822 reg_arg_name(env, argno), node_type_name); 14823 return -EINVAL; 14824 } 14825 14826 node_off = reg->var_off.value; 14827 field = reg_find_field_offset(reg, node_off, node_field_type); 14828 if (!field) { 14829 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 14830 return -EINVAL; 14831 } 14832 14833 field = *node_field; 14834 14835 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 14836 t = btf_type_by_id(reg->btf, reg->btf_id); 14837 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 14838 field->graph_root.value_btf_id, true, 14839 !type_is_alloc(reg->type))) { 14840 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 14841 "in struct %s, but arg is at offset=%d in struct %s\n", 14842 btf_field_type_name(head_field_type), 14843 btf_field_type_name(node_field_type), 14844 field->graph_root.node_offset, 14845 btf_name_by_offset(field->graph_root.btf, et->name_off), 14846 node_off, btf_name_by_offset(reg->btf, t->name_off)); 14847 return -EINVAL; 14848 } 14849 meta->arg_btf = reg->btf; 14850 meta->arg_btf_id = reg->btf_id; 14851 14852 if (node_off != field->graph_root.node_offset) { 14853 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 14854 node_off, btf_field_type_name(node_field_type), 14855 field->graph_root.node_offset, 14856 btf_name_by_offset(field->graph_root.btf, et->name_off)); 14857 return -EINVAL; 14858 } 14859 14860 return 0; 14861 } 14862 14863 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 14864 struct bpf_reg_state *reg, argno_t argno, 14865 struct bpf_call_arg_meta *meta) 14866 { 14867 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 14868 BPF_LIST_HEAD, BPF_LIST_NODE, 14869 &meta->arg_list_head.field); 14870 } 14871 14872 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 14873 struct bpf_reg_state *reg, argno_t argno, 14874 struct bpf_call_arg_meta *meta) 14875 { 14876 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 14877 BPF_RB_ROOT, BPF_RB_NODE, 14878 &meta->arg_rbtree_root.field); 14879 } 14880 14881 /* 14882 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 14883 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 14884 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 14885 * them can only be attached to some specific hook points. 14886 */ 14887 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 14888 { 14889 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 14890 14891 switch (prog_type) { 14892 case BPF_PROG_TYPE_LSM: 14893 return true; 14894 case BPF_PROG_TYPE_TRACING: 14895 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 14896 return true; 14897 fallthrough; 14898 default: 14899 return in_sleepable(env); 14900 } 14901 } 14902 14903 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 14904 s32 func_id, 14905 s16 offset, 14906 struct bpf_call_arg_meta *meta) 14907 { 14908 struct bpf_kfunc_meta kfunc; 14909 int err; 14910 14911 memset(meta, 0, sizeof(*meta)); 14912 14913 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 14914 if (err) 14915 return err; 14916 14917 meta->btf = kfunc.btf; 14918 meta->func_id = kfunc.id; 14919 meta->func_proto = kfunc.proto; 14920 meta->func_name = kfunc.name; 14921 14922 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 14923 return -EACCES; 14924 14925 meta->kfunc_flags = *kfunc.flags; 14926 14927 /* Only support release referenced argument passed by register */ 14928 if (is_kfunc_release(meta)) 14929 meta->release_regno = BPF_REG_1; 14930 14931 return 0; 14932 } 14933 14934 /* 14935 * Describe a helper's stack access through argument @arg (0-based, R1-R5). 14936 * must_write means the verifier destroys prior state throughout size bytes. 14937 * In other words, must_write follows the verifier's model of the 14938 * function's behaviour, which is safe to use for is_state_visited() pruning. 14939 */ 14940 struct arg_access_info 14941 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 14942 int arg, int insn_idx) 14943 { 14944 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 14945 struct arg_access_info info = { 14946 .size = U32_MAX, 14947 .may_read = true, 14948 .may_write = true, 14949 }; 14950 const struct bpf_func_proto *fn; 14951 enum bpf_access_type access_type; 14952 enum bpf_arg_type at; 14953 bool exact_size = true; 14954 u64 size = U32_MAX; 14955 14956 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 14957 return info; 14958 14959 at = fn->arg_type[arg]; 14960 access_type = func_arg_access_type(at); 14961 14962 switch (base_type(at)) { 14963 case ARG_PTR_TO_MAP_KEY: 14964 case ARG_PTR_TO_MAP_VALUE: { 14965 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 14966 u64 val; 14967 int i, map_reg; 14968 14969 for (i = 0; i < arg; i++) { 14970 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 14971 break; 14972 } 14973 if (i >= arg) 14974 goto scan_all_maps; 14975 14976 map_reg = BPF_REG_1 + i; 14977 14978 if (!(aux->const_reg_map_mask & BIT(map_reg))) 14979 goto scan_all_maps; 14980 14981 i = aux->const_reg_vals[map_reg]; 14982 if (i < env->used_map_cnt) { 14983 /* Bloom-filter peek reads the value buffer. */ 14984 if (!is_key && insn->imm == BPF_FUNC_map_peek_elem && 14985 env->used_maps[i]->map_type == BPF_MAP_TYPE_BLOOM_FILTER) 14986 access_type = BPF_READ; 14987 size = is_key ? env->used_maps[i]->key_size 14988 : env->used_maps[i]->value_size; 14989 goto out; 14990 } 14991 scan_all_maps: 14992 /* 14993 * Map pointer is not known at this call site (e.g. different 14994 * maps on merged paths). Conservatively return the largest 14995 * key_size or value_size across all maps used by the program. 14996 * This is only an upper bound, so it cannot establish a definite 14997 * write. Map-dependent argument types can also turn an output 14998 * into an input, so conservatively retain a read dependency. 14999 */ 15000 exact_size = false; 15001 access_type |= BPF_READ; 15002 val = 0; 15003 for (i = 0; i < env->used_map_cnt; i++) { 15004 struct bpf_map *map = env->used_maps[i]; 15005 u32 sz = is_key ? map->key_size : map->value_size; 15006 15007 if (sz > val) 15008 val = sz; 15009 if (map->inner_map_meta) { 15010 sz = is_key ? map->inner_map_meta->key_size 15011 : map->inner_map_meta->value_size; 15012 if (sz > val) 15013 val = sz; 15014 } 15015 } 15016 if (!val) 15017 return info; 15018 size = val; 15019 goto out; 15020 } 15021 case ARG_PTR_TO_MEM: 15022 if (at & MEM_FIXED_SIZE) { 15023 size = fn->arg_size[arg]; 15024 goto out; 15025 } 15026 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 15027 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 15028 int size_reg = BPF_REG_1 + arg + 1; 15029 15030 if (aux->const_reg_mask & BIT(size_reg)) { 15031 size = aux->const_reg_vals[size_reg]; 15032 goto out; 15033 } 15034 } 15035 /* Preserve access directions even when the extent is unknown. */ 15036 goto out; 15037 case ARG_PTR_TO_DYNPTR: 15038 size = BPF_DYNPTR_SIZE; 15039 break; 15040 case ARG_PTR_TO_STACK: 15041 /* 15042 * Only used by bpf_calls_callback() helpers. The helper itself 15043 * doesn't access stack. The callback subprog does and it's 15044 * analyzed separately. 15045 */ 15046 return (struct arg_access_info) {}; 15047 default: 15048 return info; 15049 } 15050 out: 15051 info.size = min_t(u64, size, U32_MAX); 15052 info.may_read = !!(access_type & BPF_READ); 15053 info.may_write = !!(access_type & BPF_WRITE); 15054 info.must_write = info.may_write && exact_size && info.size != U32_MAX; 15055 /* Generic unprivileged outputs retain prior initialization state. */ 15056 if (!env->allow_uninit_stack && arg_type_is_raw_mem(at)) { 15057 info.may_read = true; 15058 info.must_write = false; 15059 } 15060 return info; 15061 } 15062 15063 /* 15064 * Describe a kfunc's stack access through argument slot @arg (0-based). 15065 * As for helpers, must_write describes destruction of prior verifier state, 15066 * rather than a guarantee that the callee writes every byte at runtime. 15067 */ 15068 struct arg_access_info 15069 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 15070 int arg, int insn_idx) 15071 { 15072 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 15073 struct arg_access_info info = { 15074 .size = U32_MAX, 15075 .may_read = true, 15076 .may_write = true, 15077 }; 15078 struct bpf_call_arg_meta meta; 15079 const struct btf_param *args; 15080 const struct btf_type *t, *ref_t; 15081 const struct btf *btf; 15082 u32 i, slot, nargs, type_size; 15083 u64 size; 15084 15085 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 15086 return info; 15087 15088 btf = meta.btf; 15089 args = btf_params(meta.func_proto); 15090 nargs = btf_type_vlen(meta.func_proto); 15091 15092 /* 15093 * @arg is an argument slot and a 16-byte parameter takes two of them, 15094 * so walk the parameters to find the one that starts at this slot. A 15095 * slot holding the upper eightbyte of such a parameter belongs to no 15096 * pointer, and neither does a slot past the last parameter. 15097 */ 15098 for (i = 0, slot = 0; i < nargs && slot < arg; i++) 15099 slot += btf_arg_slots(btf_type_skip_modifiers(btf, args[i].type, NULL)); 15100 if (i >= nargs || slot != arg) 15101 return (struct arg_access_info) {}; 15102 15103 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 15104 if (!btf_type_is_ptr(t)) 15105 return (struct arg_access_info) {}; 15106 15107 /* dynptr: fixed 16-byte on-stack representation */ 15108 if (is_kfunc_arg_dynptr(btf, &args[i])) { 15109 size = BPF_DYNPTR_SIZE; 15110 goto out; 15111 } 15112 15113 /* ptr + __sz/__szk pair: the size follows the pointer */ 15114 if (i + 1 < nargs && 15115 (btf_param_match_suffix(btf, &args[i + 1], "__sz") || 15116 btf_param_match_suffix(btf, &args[i + 1], "__szk"))) { 15117 int size_reg = BPF_REG_1 + arg + 1; 15118 15119 if (size_reg <= MAX_BPF_FUNC_REG_ARGS && 15120 (aux->const_reg_mask & BIT(size_reg))) { 15121 size = aux->const_reg_vals[size_reg]; 15122 goto out; 15123 } 15124 /* Unknown size: the read may extend anywhere up to the frame top. */ 15125 return info; 15126 } 15127 15128 /* fixed-size pointed-to type: resolve via BTF */ 15129 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 15130 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 15131 size = type_size; 15132 goto out; 15133 } 15134 15135 return info; 15136 out: 15137 info.size = min_t(u64, size, U32_MAX); 15138 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 15139 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 15140 info.may_read = false; 15141 if (is_kfunc_arg_uninit(btf, &args[i]) && 15142 (is_kfunc_arg_dynptr(btf, &args[i]) || env->allow_uninit_stack)) 15143 info.may_read = false; 15144 info.must_write = !info.may_read && info.size != U32_MAX; 15145 return info; 15146 } 15147 15148 /* 15149 * Called before dead code elimination, some subprograms may be genuinely unreachable. 15150 * Suppress diagnostics so callers can use a conservative result on error. 15151 * The main pass would report errors for reachable subprograms. 15152 */ 15153 static bool try_btf_prepare_func_args(struct bpf_verifier_env *env, int subprog) 15154 { 15155 struct bpf_prog *prog = env->prog; 15156 u32 log_level = env->log.level; 15157 int err; 15158 15159 if (!prog->aux->func_info || !prog->aux->func_info[subprog].type_id) 15160 return false; 15161 15162 env->log.level = 0; 15163 err = btf_prepare_func_args(env, subprog); 15164 env->log.level = log_level; 15165 return !err; 15166 } 15167 15168 /* Prepare argument metadata for liveness; the main program is handled separately. */ 15169 static void prepare_subprog_args(struct bpf_verifier_env *env) 15170 { 15171 int i; 15172 15173 for (i = 1; i < env->subprog_cnt; i++) { 15174 if (!try_btf_prepare_func_args(env, i) && bpf_subprog_is_global(env, i)) 15175 /* Keep all argument registers live if the prototype is unavailable. */ 15176 env->subprog_info[i].arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS; 15177 } 15178 } 15179 15180 /* 15181 * Derive stack effects for a global subprog's argument slot @arg (0-based) 15182 * from its declared type, matching the main pass's argument checks. 15183 */ 15184 struct arg_access_info 15185 bpf_global_subprog_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 15186 int arg, int insn_idx) 15187 { 15188 struct arg_access_info info = { 15189 .size = U32_MAX, 15190 .may_read = true, 15191 .may_write = true, 15192 }; 15193 struct bpf_subprog_info *sub; 15194 int callee; 15195 15196 callee = bpf_find_subprog(env, insn_idx + insn->imm + 1); 15197 if (callee < 0) 15198 return info; 15199 sub = subprog_info(env, callee); 15200 if (!try_btf_prepare_func_args(env, callee)) 15201 return info; 15202 15203 switch (base_type(sub->args[arg].arg_type)) { 15204 case ARG_UNUSED: /* Not an argument slot. */ 15205 case ARG_SCALAR: /* A scalar, the callee can't dereference it. */ 15206 return (struct arg_access_info) {}; 15207 case ARG_PTR_TO_BTF_ID: 15208 /* 15209 * Trusted arguments cannot be stack pointers. 15210 * Untrusted arguments use ARG_IGNORE: 15211 * probe reads need no caller stack state, writes are prohibited. 15212 */ 15213 return (struct arg_access_info) {}; 15214 case ARG_PTR_TO_MEM: 15215 /* mem_size is zero for untrusted pointers of unknown size. */ 15216 if (sub->args[arg].mem_size) { 15217 info.size = sub->args[arg].mem_size; 15218 info.must_write = true; 15219 } 15220 return info; 15221 case ARG_PTR_TO_DYNPTR: 15222 /* The callee may adjust the view, but cannot reinitialize the dynptr. */ 15223 info.size = BPF_DYNPTR_SIZE; 15224 return info; 15225 default: 15226 return info; 15227 } 15228 } 15229 15230 /* check special kfuncs and return: 15231 * 1 - not fall-through to 'else' branch, continue verification 15232 * 0 - fall-through to 'else' branch 15233 * < 0 - not fall-through to 'else' branch, return error 15234 */ 15235 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 15236 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 15237 const struct btf_type *ptr_type, struct btf *desc_btf) 15238 { 15239 const struct btf_type *ret_t; 15240 int err = 0; 15241 15242 if (meta->btf != btf_vmlinux) 15243 return 0; 15244 15245 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 15246 struct btf_struct_meta *struct_meta; 15247 struct btf *ret_btf; 15248 u32 ret_btf_id; 15249 15250 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 15251 return -ENOMEM; 15252 15253 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 15254 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 15255 return -EINVAL; 15256 } 15257 15258 ret_btf = env->prog->aux->btf; 15259 ret_btf_id = meta->arg_constant.value; 15260 15261 /* This may be NULL due to user not supplying a BTF */ 15262 if (!ret_btf) { 15263 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 15264 return -EINVAL; 15265 } 15266 15267 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 15268 if (!ret_t || !__btf_type_is_struct(ret_t)) { 15269 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 15270 return -EINVAL; 15271 } 15272 15273 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 15274 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 15275 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 15276 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 15277 return -EINVAL; 15278 } 15279 15280 if (!bpf_global_percpu_ma_set) { 15281 mutex_lock(&bpf_percpu_ma_lock); 15282 if (!bpf_global_percpu_ma_set) { 15283 /* Charge memory allocated with bpf_global_percpu_ma to 15284 * root memcg. The obj_cgroup for root memcg is NULL. 15285 */ 15286 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 15287 if (!err) 15288 bpf_global_percpu_ma_set = true; 15289 } 15290 mutex_unlock(&bpf_percpu_ma_lock); 15291 if (err) 15292 return err; 15293 } 15294 15295 mutex_lock(&bpf_percpu_ma_lock); 15296 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 15297 mutex_unlock(&bpf_percpu_ma_lock); 15298 if (err) 15299 return err; 15300 } 15301 15302 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 15303 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 15304 if (!btf_type_is_scalar_struct(env, ret_btf, ret_t)) { 15305 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 15306 return -EINVAL; 15307 } 15308 15309 if (struct_meta) { 15310 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 15311 return -EINVAL; 15312 } 15313 } 15314 15315 mark_reg_known_zero(env, regs, BPF_REG_0); 15316 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 15317 regs[BPF_REG_0].btf = ret_btf; 15318 regs[BPF_REG_0].btf_id = ret_btf_id; 15319 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 15320 regs[BPF_REG_0].type |= MEM_PERCPU; 15321 15322 insn_aux->obj_new_size = ret_t->size; 15323 insn_aux->kptr_struct_meta = struct_meta; 15324 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 15325 mark_reg_known_zero(env, regs, BPF_REG_0); 15326 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 15327 regs[BPF_REG_0].btf = meta->arg_btf; 15328 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 15329 15330 insn_aux->kptr_struct_meta = 15331 btf_find_struct_meta(meta->arg_btf, 15332 meta->arg_btf_id); 15333 } else if (is_list_node_type(ptr_type)) { 15334 struct btf_field *field = meta->arg_list_head.field; 15335 15336 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 15337 } else if (is_rbtree_node_type(ptr_type)) { 15338 struct btf_field *field = meta->arg_rbtree_root.field; 15339 15340 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 15341 } else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_cast_to_kern_ctx])) { 15342 mark_reg_known_zero(env, regs, BPF_REG_0); 15343 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 15344 regs[BPF_REG_0].btf = desc_btf; 15345 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 15346 } else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_rdonly_cast])) { 15347 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 15348 if (!ret_t) { 15349 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 15350 meta->arg_constant.value); 15351 return -EINVAL; 15352 } else if (btf_type_is_struct(ret_t)) { 15353 mark_reg_known_zero(env, regs, BPF_REG_0); 15354 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 15355 regs[BPF_REG_0].btf = desc_btf; 15356 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 15357 } else if (btf_type_is_void(ret_t)) { 15358 mark_reg_known_zero(env, regs, BPF_REG_0); 15359 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 15360 regs[BPF_REG_0].mem_size = 0; 15361 } else { 15362 verbose(env, 15363 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 15364 return -EINVAL; 15365 } 15366 } else if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice]) || 15367 is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice_rdwr])) { 15368 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type); 15369 15370 mark_reg_known_zero(env, regs, BPF_REG_0); 15371 15372 if (!meta->arg_constant.found) { 15373 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 15374 return -EFAULT; 15375 } 15376 15377 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 15378 15379 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 15380 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 15381 15382 if (is_kfunc_call(meta, special_kfunc_list[KF_bpf_dynptr_slice])) { 15383 regs[BPF_REG_0].type |= MEM_RDONLY; 15384 } else { 15385 /* this will set env->seen_direct_write to true */ 15386 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 15387 verbose(env, "the prog does not allow writes to packet data\n"); 15388 return -EINVAL; 15389 } 15390 } 15391 15392 if (!meta->dynptr.id) { 15393 verifier_bug(env, "no dynptr id"); 15394 return -EFAULT; 15395 } 15396 regs[BPF_REG_0].parent_id = meta->dynptr.id; 15397 } else { 15398 return 0; 15399 } 15400 15401 return 1; 15402 } 15403 15404 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 15405 15406 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 15407 int *insn_idx_p) 15408 { 15409 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 15410 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15411 struct bpf_reg_state *regs = cur_regs(env); 15412 const char *func_name, *ptr_type_name; 15413 const struct btf_type *t, *ptr_type; 15414 struct bpf_call_arg_meta meta; 15415 struct bpf_insn_aux_data *insn_aux; 15416 const char *operation; 15417 int err, insn_idx = *insn_idx_p; 15418 u32 i, proto_slots, ptr_type_id, ret_nregs = 1; 15419 struct bpf_kfunc_desc *desc; 15420 struct btf *desc_btf; 15421 int id; 15422 15423 /* skip for now, but return error when we find this in fixup_kfunc_call */ 15424 if (!insn->imm) 15425 return 0; 15426 15427 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 15428 if (err == -EACCES && meta.func_name) { 15429 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 15430 operation = bpf_diag_fmt(env, "kfunc %s", meta.func_name); 15431 bpf_diag_policy( 15432 env, insn_idx, operation, "this program cannot call the kfunc", 15433 "Use a kfunc allowed for this program type and attach point, or change the program context."); 15434 } 15435 if (err) 15436 return err; 15437 desc_btf = meta.btf; 15438 func_name = meta.func_name; 15439 insn_aux = &env->insn_aux_data[insn_idx]; 15440 15441 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 15442 if (!desc) { 15443 verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm); 15444 return -EFAULT; 15445 } 15446 meta.fn = &desc->proto; 15447 15448 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 15449 15450 if (!insn->off && 15451 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 15452 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 15453 struct bpf_verifier_state *branch; 15454 struct bpf_reg_state *regs; 15455 15456 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 15457 if (IS_ERR(branch)) { 15458 verbose(env, "failed to push state for failed lock acquisition\n"); 15459 return PTR_ERR(branch); 15460 } 15461 15462 regs = branch->frame[branch->curframe]->regs; 15463 15464 /* Clear r0-r5 registers in forked state */ 15465 for (i = 0; i < CALLER_SAVED_REGS; i++) 15466 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 15467 15468 mark_reg_unknown(env, regs, BPF_REG_0); 15469 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 15470 if (err) { 15471 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 15472 return err; 15473 } 15474 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 15475 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 15476 return -EFAULT; 15477 } 15478 15479 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 15480 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 15481 operation = bpf_diag_fmt(env, "destructive kfunc %s", meta.func_name); 15482 bpf_diag_policy( 15483 env, insn_idx, operation, "destructive kfuncs require CAP_SYS_BOOT", 15484 "Load the program with CAP_SYS_BOOT, or avoid destructive kfuncs."); 15485 return -EACCES; 15486 } 15487 15488 if (is_kfunc_perfmon(&meta) && !env->allow_ptr_leaks) { 15489 verbose(env, "%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 15490 func_name); 15491 operation = bpf_diag_fmt(env, "kfunc %s", func_name); 15492 bpf_diag_policy(env, insn_idx, operation, "the kfunc requires CAP_PERFMON", 15493 "Load the program with CAP_PERFMON, or avoid the kfunc."); 15494 return -EPERM; 15495 } 15496 15497 sleepable = bpf_is_kfunc_sleepable(&meta); 15498 if (sleepable && !in_sleepable_context(env)) { 15499 const char *suggestion; 15500 15501 if (in_sleepable(env)) { 15502 verbose(env, "kernel func %s is sleepable within %s\n", 15503 func_name, non_sleepable_context_description(env)); 15504 suggestion = "Move the kfunc call outside the critical section, or use a non-sleepable kfunc."; 15505 } else { 15506 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", 15507 func_name); 15508 suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc."; 15509 } 15510 operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name); 15511 bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion); 15512 return -EACCES; 15513 } 15514 15515 /* Track non-sleepable context for kfuncs, same as for helpers. */ 15516 if (!in_sleepable_context(env)) 15517 insn_aux->non_sleepable = true; 15518 15519 /* Check the arguments */ 15520 err = check_func_args(env, &meta, insn_idx); 15521 if (err < 0) 15522 return err; 15523 15524 err = mark_raw_stack(env, &meta, insn_idx); 15525 if (err) 15526 return err; 15527 15528 if ((is_bpf_obj_drop_kfunc(meta.func_id) || 15529 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) || 15530 /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */ 15531 (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER 15532 && !env->prog->sleepable))) { 15533 struct btf_struct_meta *struct_meta; 15534 15535 struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 15536 if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) { 15537 verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n", 15538 func_name); 15539 return -EINVAL; 15540 } 15541 } 15542 15543 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 15544 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 15545 set_rbtree_add_callback_state); 15546 if (err) { 15547 verbose(env, "kfunc %s#%d failed callback verification\n", 15548 func_name, meta.func_id); 15549 return err; 15550 } 15551 } 15552 15553 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 15554 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 15555 set_timer_callback_state); 15556 if (err) { 15557 verbose(env, "kfunc %s#%d failed callback verification\n", 15558 func_name, meta.func_id); 15559 return err; 15560 } 15561 } 15562 15563 if (is_task_work_add_kfunc(meta.func_id)) { 15564 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 15565 set_task_work_schedule_callback_state); 15566 if (err) { 15567 verbose(env, "kfunc %s#%d failed callback verification\n", 15568 func_name, meta.func_id); 15569 return err; 15570 } 15571 } 15572 15573 if (is_call_rcu_kfunc(meta.func_id)) { 15574 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 15575 set_rcu_callback_state); 15576 if (err) { 15577 verbose(env, "kfunc %s#%d failed callback verification\n", 15578 func_name, meta.func_id); 15579 return err; 15580 } 15581 } 15582 15583 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 15584 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 15585 15586 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 15587 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 15588 15589 if (rcu_lock) { 15590 env->cur_state->active_rcu_locks++; 15591 bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, true, 15592 env->cur_state->active_rcu_locks); 15593 } else if (rcu_unlock) { 15594 if (env->cur_state->active_rcu_locks == 0) { 15595 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 15596 bpf_diag_ctx_underflow( 15597 env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU, 15598 "Remove the extra bpf_rcu_read_unlock() call, or ensure this path first enters an RCU read lock region."); 15599 return -EINVAL; 15600 } 15601 env->cur_state->active_rcu_locks--; 15602 bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false, 15603 env->cur_state->active_rcu_locks); 15604 if (!in_rcu_cs(env)) 15605 invalidate_rcu_protected_refs(env); 15606 } else if (preempt_disable) { 15607 env->cur_state->active_preempt_locks++; 15608 bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, true, 15609 env->cur_state->active_preempt_locks); 15610 } else if (preempt_enable) { 15611 if (env->cur_state->active_preempt_locks == 0) { 15612 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 15613 bpf_diag_ctx_underflow( 15614 env, insn_idx, func_name, BPF_DIAG_CONTEXT_PREEMPT, 15615 "Remove the extra bpf_preempt_enable() call, or ensure this path first disables preemption."); 15616 return -EINVAL; 15617 } 15618 env->cur_state->active_preempt_locks--; 15619 bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false, 15620 env->cur_state->active_preempt_locks); 15621 if (!in_rcu_cs(env)) 15622 invalidate_rcu_protected_refs(env); 15623 } 15624 15625 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 15626 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 15627 return -EACCES; 15628 } 15629 15630 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 15631 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 15632 bpf_diag_ctx_required( 15633 env, insn_idx, func_name, BPF_DIAG_CONTEXT_RCU, 15634 "Call this kfunc between bpf_rcu_read_lock() and bpf_rcu_read_unlock(), keeping all exit paths balanced."); 15635 return -EACCES; 15636 } 15637 15638 /* In case of release function, we get register number of refcounted 15639 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 15640 */ 15641 if (meta.release_regno) { 15642 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 15643 if (err) 15644 return err; 15645 } 15646 15647 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 15648 id = regs[BPF_REG_2].id; 15649 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 15650 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 15651 ref_convert_owning_non_owning(env, id); 15652 } 15653 15654 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 15655 if (!bpf_jit_supports_exceptions()) { 15656 verbose(env, "JIT does not support calling kfunc %s#%d\n", 15657 func_name, meta.func_id); 15658 return -ENOTSUPP; 15659 } 15660 env->seen_exception = true; 15661 15662 /* In the case of the default callback, the cookie value passed 15663 * to bpf_throw becomes the return value of the program. 15664 */ 15665 if (!env->exception_callback_subprog) { 15666 err = check_return_code(env, BPF_REG_1, "R1"); 15667 if (err < 0) 15668 return err; 15669 } 15670 } 15671 15672 bpf_diag_record_caller_saved(env, regs); 15673 bpf_diag_mod_begin(env, ®s[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE); 15674 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15675 u32 regno = caller_saved[i]; 15676 15677 bpf_mark_reg_not_init(env, ®s[regno]); 15678 } 15679 invalidate_outgoing_stack_args(env, cur_func(env)); 15680 15681 /* Check return type */ 15682 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 15683 15684 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 15685 if (meta.btf != btf_vmlinux || 15686 (!is_bpf_obj_new_kfunc(meta.func_id) && 15687 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 15688 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 15689 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 15690 return -EINVAL; 15691 } 15692 } 15693 15694 if (btf_type_is_scalar(t)) { 15695 ret_nregs = mark_kfunc_ret_regs(env, regs, t->size); 15696 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 15697 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 15698 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 15699 } else if (btf_type_is_struct(t)) { 15700 struct btf_member_path path = {}; 15701 const char *member_note = ""; 15702 15703 /* 15704 * The returned struct comes back as raw register bits modeled 15705 * as an unknown scalar, so a pointer member would be laundered 15706 * into a scalar and escape provenance and reference tracking. 15707 * Only scalars and arena pointers are allowed; see 15708 * btf_validate_return_type() in btf.c for why an arena pointer 15709 * is safe here. 15710 */ 15711 if (!btf_struct_member_walk(env, desc_btf, t, 15712 BTF_MEMBER_SCALAR | BTF_MEMBER_ARENA_PTR, 0, &path)) { 15713 verbose(env, 15714 "kernel function %s returns %s %s that is not composed of scalars or arena pointers\n", 15715 func_name, btf_type_str(t), 15716 btf_name_by_offset(desc_btf, t->name_off)); 15717 if (path.too_deep) { 15718 member_note = bpf_diag_fmt( 15719 env, " It nests structs more than %d levels deep.", 15720 BTF_MEMBER_MAX_DEPTH); 15721 } else if (path.depth) { 15722 char bad_name[BTF_MEMBER_PATH_LEN]; 15723 15724 btf_member_path_str(desc_btf, &path, bad_name, sizeof(bad_name)); 15725 if (!path.bad_type) { 15726 verbose(env, "member '%s' is a zero-length array\n", 15727 bad_name); 15728 member_note = bpf_diag_fmt( 15729 env, " Its member '%s' is a zero-length array.", 15730 bad_name); 15731 } else { 15732 verbose(env, "member '%s' has type %s\n", bad_name, 15733 btf_type_str(path.bad_type)); 15734 member_note = bpf_diag_fmt( 15735 env, 15736 " Its member '%s' is %s, not a scalar or an arena pointer.", 15737 bad_name, btf_type_str(path.bad_type)); 15738 } 15739 } 15740 bpf_diag_program_structure( 15741 env, insn_idx, "unsupported kernel function return type", 15742 "Call a kernel function that returns only scalars or arena pointers by value.", 15743 "%s() returns %s %s by value.%s " 15744 "Only kfuncs returning scalar values or arena pointers, or " 15745 "structures composed of scalar values or arena pointers are " 15746 "supported.", 15747 func_name, btf_type_str(t), 15748 btf_name_by_offset(desc_btf, t->name_off), member_note); 15749 return -EINVAL; 15750 } 15751 ret_nregs = mark_kfunc_ret_regs(env, regs, t->size); 15752 } else if (btf_type_is_ptr(t)) { 15753 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 15754 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 15755 if (err) { 15756 if (err < 0) 15757 return err; 15758 } else if (btf_type_is_void(ptr_type)) { 15759 /* kfunc returning 'void *' is equivalent to returning scalar */ 15760 mark_reg_unknown(env, regs, BPF_REG_0); 15761 } else if (!__btf_type_is_struct(ptr_type)) { 15762 if (!meta.ret_mem.found) { 15763 __u32 sz; 15764 15765 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 15766 meta.ret_mem.found = true; 15767 meta.ret_mem.size = sz; 15768 meta.r0_rdonly = true; 15769 } 15770 15771 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 15772 meta.r0_rdonly = false; 15773 } 15774 if (!meta.ret_mem.found) { 15775 ptr_type_name = btf_name_by_offset(desc_btf, 15776 ptr_type->name_off); 15777 verbose(env, 15778 "kernel function %s returns pointer type %s %s is not supported\n", 15779 func_name, 15780 btf_type_str(ptr_type), 15781 ptr_type_name); 15782 return -EINVAL; 15783 } 15784 15785 mark_reg_known_zero(env, regs, BPF_REG_0); 15786 regs[BPF_REG_0].type = PTR_TO_MEM; 15787 regs[BPF_REG_0].mem_size = meta.ret_mem.size; 15788 15789 if (meta.r0_rdonly) 15790 regs[BPF_REG_0].type |= MEM_RDONLY; 15791 15792 /* Ensures we don't access the memory after a release_reference() */ 15793 if (meta.ref_obj.id) { 15794 err = validate_ref_obj(env, &meta.ref_obj); 15795 if (err) 15796 return err; 15797 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 15798 } 15799 15800 if (is_kfunc_rcu_protected(&meta)) 15801 regs[BPF_REG_0].type |= MEM_RCU; 15802 } else { 15803 enum bpf_reg_type type = PTR_TO_BTF_ID; 15804 15805 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 15806 type |= PTR_UNTRUSTED; 15807 else if (is_kfunc_rcu_protected(&meta) || 15808 (bpf_is_iter_next_kfunc(&meta) && 15809 (get_iter_from_state(env->cur_state, &meta) 15810 ->type & MEM_RCU))) { 15811 /* 15812 * If the iterator's constructor (the _new 15813 * function e.g., bpf_iter_task_new) has been 15814 * annotated with BPF kfunc flag 15815 * KF_RCU_PROTECTED and was called within a RCU 15816 * read-side critical section, also propagate 15817 * the MEM_RCU flag to the pointer returned from 15818 * the iterator's next function (e.g., 15819 * bpf_iter_task_next). 15820 */ 15821 type |= MEM_RCU; 15822 } else { 15823 /* 15824 * Any PTR_TO_BTF_ID that is returned from a BPF 15825 * kfunc should by default be treated as 15826 * implicitly trusted. 15827 */ 15828 type |= PTR_TRUSTED; 15829 } 15830 15831 mark_reg_known_zero(env, regs, BPF_REG_0); 15832 regs[BPF_REG_0].btf = desc_btf; 15833 regs[BPF_REG_0].type = type; 15834 regs[BPF_REG_0].btf_id = ptr_type_id; 15835 if (iter_next_borrows_struct(&meta) && !(type & MEM_RCU)) 15836 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 15837 } 15838 15839 if (is_kfunc_ret_null(&meta)) { 15840 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 15841 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 15842 regs[BPF_REG_0].id = ++env->id_gen; 15843 } 15844 if (is_kfunc_acquire(&meta)) { 15845 id = acquire_reference(env, insn_idx, 0); 15846 if (id < 0) 15847 return id; 15848 regs[BPF_REG_0].id = id; 15849 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 15850 ref_set_non_owning(env, ®s[BPF_REG_0]); 15851 } 15852 15853 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 15854 regs[BPF_REG_0].id = ++env->id_gen; 15855 } else if (btf_type_is_void(t)) { 15856 if (meta.btf == btf_vmlinux) { 15857 if (is_bpf_obj_drop_kfunc(meta.func_id) || 15858 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 15859 insn_aux->kptr_struct_meta = 15860 btf_find_struct_meta(meta.arg_btf, 15861 meta.arg_btf_id); 15862 } 15863 } 15864 } 15865 15866 if (is_kfunc_dynptr_write(&meta) ? 15867 dynptr_write_changes_pkt_data(meta.dynptr_write_type) : 15868 bpf_is_kfunc_pkt_changing(&meta)) 15869 clear_all_pkt_pointers(env); 15870 15871 /* 15872 * These kfuncs write to the head of the skb in place if what they write 15873 * to is linear. Like a direct write that takes bpf_unclone_prologue(). 15874 */ 15875 if (is_kfunc_dynptr_write(&meta) && 15876 dynptr_write_changes_pkt_data(meta.dynptr_write_type)) 15877 may_access_direct_pkt_data(env, NULL, BPF_WRITE); 15878 15879 proto_slots = kfunc_abi_slots(&desc->func_model); 15880 if (proto_slots > MAX_BPF_FUNC_REG_ARGS) { 15881 struct bpf_func_state *caller = cur_func(env); 15882 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 15883 u16 out_stack_arg_cnt = proto_slots - MAX_BPF_FUNC_REG_ARGS; 15884 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 15885 15886 if (stack_arg_cnt > caller_info->stack_arg_cnt) 15887 caller_info->stack_arg_cnt = stack_arg_cnt; 15888 } 15889 15890 /* 15891 * Record R0 before process_iter_next_call() snapshots the alternate 15892 * iterator path's diagnostic position. 15893 */ 15894 if (ret_nregs == 1) 15895 bpf_diag_mod_end(env); 15896 15897 if (bpf_is_iter_next_kfunc(&meta)) { 15898 err = process_iter_next_call(env, insn_idx, &meta); 15899 if (err) 15900 return err; 15901 } 15902 15903 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 15904 env->prog->call_session_cookie = true; 15905 15906 if (bpf_is_throw_kfunc(insn)) 15907 return process_bpf_exit_full(env, NULL, true); 15908 15909 return 0; 15910 } 15911 15912 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 15913 const struct bpf_reg_state *reg, 15914 enum bpf_reg_type type) 15915 { 15916 bool known = tnum_is_const(reg->var_off); 15917 s64 val = reg->var_off.value; 15918 s64 smin = reg_smin(reg); 15919 15920 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 15921 verbose(env, "math between %s pointer and %lld is not allowed\n", 15922 reg_type_str(env, type), val); 15923 return false; 15924 } 15925 15926 if (smin == S64_MIN) { 15927 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 15928 reg_type_str(env, type)); 15929 return false; 15930 } 15931 15932 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 15933 verbose(env, "value %lld makes %s pointer be out of bounds\n", 15934 smin, reg_type_str(env, type)); 15935 return false; 15936 } 15937 15938 return true; 15939 } 15940 15941 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 15942 const struct bpf_reg_state *reg, 15943 enum bpf_reg_type type) 15944 { 15945 bool known = tnum_is_const(reg->var_off); 15946 s64 val = reg->var_off.value; 15947 s64 smin = reg_smin(reg); 15948 15949 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 15950 verbose(env, "%s pointer offset %lld is not allowed\n", 15951 reg_type_str(env, type), val); 15952 return false; 15953 } 15954 15955 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 15956 verbose(env, "%s pointer offset %lld is not allowed\n", 15957 reg_type_str(env, type), smin); 15958 return false; 15959 } 15960 15961 return true; 15962 } 15963 15964 enum { 15965 REASON_BOUNDS = -1, 15966 REASON_TYPE = -2, 15967 REASON_PATHS = -3, 15968 REASON_LIMIT = -4, 15969 REASON_STACK = -5, 15970 }; 15971 15972 static int retrieve_ptr_limit(const struct bpf_verifier_env *env, 15973 const struct bpf_reg_state *ptr_reg, 15974 u32 *alu_limit, bool mask_to_left) 15975 { 15976 u32 max = 0, ptr_limit = 0; 15977 15978 switch (ptr_reg->type) { 15979 case PTR_TO_STACK: 15980 /* Offset 0 is out-of-bounds, but acceptable start for the 15981 * left direction, see BPF_REG_FP. Also, unknown scalar 15982 * offset where we would need to deal with min/max bounds is 15983 * currently prohibited for unprivileged. 15984 */ 15985 max = env->stack_limit + mask_to_left; 15986 ptr_limit = -ptr_reg->var_off.value; 15987 break; 15988 case PTR_TO_MAP_VALUE: 15989 max = ptr_reg->map_ptr->value_size; 15990 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 15991 break; 15992 default: 15993 return REASON_TYPE; 15994 } 15995 15996 if (ptr_limit >= max) 15997 return REASON_LIMIT; 15998 *alu_limit = ptr_limit; 15999 return 0; 16000 } 16001 16002 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 16003 const struct bpf_insn *insn) 16004 { 16005 return env->bypass_spec_v1 || 16006 BPF_SRC(insn->code) == BPF_K || 16007 cur_aux(env)->nospec; 16008 } 16009 16010 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 16011 u32 alu_state, u32 alu_limit) 16012 { 16013 /* If we arrived here from different branches with different 16014 * state or limits to sanitize, then this won't work. 16015 */ 16016 if (aux->alu_state && 16017 (aux->alu_state != alu_state || 16018 aux->alu_limit != alu_limit)) 16019 return REASON_PATHS; 16020 16021 /* Corresponding fixup done in do_misc_fixups(). */ 16022 aux->alu_state = alu_state; 16023 aux->alu_limit = alu_limit; 16024 return 0; 16025 } 16026 16027 static int sanitize_val_alu(struct bpf_verifier_env *env, 16028 struct bpf_insn *insn) 16029 { 16030 struct bpf_insn_aux_data *aux = cur_aux(env); 16031 16032 if (can_skip_alu_sanitation(env, insn)) 16033 return 0; 16034 16035 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 16036 } 16037 16038 static bool sanitize_needed(u8 opcode) 16039 { 16040 return opcode == BPF_ADD || opcode == BPF_SUB; 16041 } 16042 16043 struct bpf_sanitize_info { 16044 struct bpf_insn_aux_data aux; 16045 bool mask_to_left; 16046 }; 16047 16048 static int sanitize_speculative_path(struct bpf_verifier_env *env, 16049 const struct bpf_insn *insn, 16050 u32 next_idx, u32 curr_idx) 16051 { 16052 struct bpf_verifier_state *branch; 16053 struct bpf_reg_state *regs; 16054 16055 branch = push_stack(env, next_idx, curr_idx, true); 16056 if (!IS_ERR(branch) && insn) { 16057 regs = branch->frame[branch->curframe]->regs; 16058 if (BPF_SRC(insn->code) == BPF_K) { 16059 mark_reg_unknown(env, regs, insn->dst_reg); 16060 } else if (BPF_SRC(insn->code) == BPF_X) { 16061 mark_reg_unknown(env, regs, insn->dst_reg); 16062 mark_reg_unknown(env, regs, insn->src_reg); 16063 } 16064 } 16065 return PTR_ERR_OR_ZERO(branch); 16066 } 16067 16068 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 16069 struct bpf_insn *insn, 16070 const struct bpf_reg_state *ptr_reg, 16071 const struct bpf_reg_state *off_reg, 16072 struct bpf_reg_state *dst_reg, 16073 struct bpf_sanitize_info *info, 16074 const bool commit_window) 16075 { 16076 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 16077 struct bpf_verifier_state *vstate = env->cur_state; 16078 bool off_is_imm = tnum_is_const(off_reg->var_off); 16079 bool off_is_neg = reg_smin(off_reg) < 0; 16080 bool ptr_is_dst_reg = ptr_reg == dst_reg; 16081 u8 opcode = BPF_OP(insn->code); 16082 u32 alu_state, alu_limit; 16083 struct bpf_reg_state tmp; 16084 int err; 16085 16086 if (can_skip_alu_sanitation(env, insn)) 16087 return 0; 16088 16089 /* We already marked aux for masking from non-speculative 16090 * paths, thus we got here in the first place. We only care 16091 * to explore bad access from here. 16092 */ 16093 if (vstate->speculative) 16094 goto do_sim; 16095 16096 if (!commit_window) { 16097 if (!tnum_is_const(off_reg->var_off) && 16098 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 16099 return REASON_BOUNDS; 16100 16101 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 16102 (opcode == BPF_SUB && !off_is_neg); 16103 } 16104 16105 err = retrieve_ptr_limit(env, ptr_reg, &alu_limit, info->mask_to_left); 16106 if (err < 0) 16107 return err; 16108 16109 if (commit_window) { 16110 /* In commit phase we narrow the masking window based on 16111 * the observed pointer move after the simulated operation. 16112 */ 16113 alu_state = info->aux.alu_state; 16114 alu_limit = abs(info->aux.alu_limit - alu_limit); 16115 } else { 16116 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 16117 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 16118 alu_state |= ptr_is_dst_reg ? 16119 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 16120 16121 /* Limit pruning on unknown scalars to enable deep search for 16122 * potential masking differences from other program paths. 16123 */ 16124 if (!off_is_imm) 16125 env->explore_alu_limits = true; 16126 } 16127 16128 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 16129 if (err < 0) 16130 return err; 16131 do_sim: 16132 /* If we're in commit phase, we're done here given we already 16133 * pushed the truncated dst_reg into the speculative verification 16134 * stack. 16135 * 16136 * Also, when register is a known constant, we rewrite register-based 16137 * operation to immediate-based, and thus do not need masking (and as 16138 * a consequence, do not need to simulate the zero-truncation either). 16139 */ 16140 if (commit_window || off_is_imm) 16141 return 0; 16142 16143 /* Simulate and find potential out-of-bounds access under 16144 * speculative execution from truncation as a result of 16145 * masking when off was not within expected range. If off 16146 * sits in dst, then we temporarily need to move ptr there 16147 * to simulate dst (== 0) +/-= ptr. Needed, for example, 16148 * for cases where we use K-based arithmetic in one direction 16149 * and truncated reg-based in the other in order to explore 16150 * bad access. 16151 */ 16152 if (!ptr_is_dst_reg) { 16153 tmp = *dst_reg; 16154 *dst_reg = *ptr_reg; 16155 } 16156 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 16157 if (err < 0) 16158 return REASON_STACK; 16159 if (!ptr_is_dst_reg) 16160 *dst_reg = tmp; 16161 return 0; 16162 } 16163 16164 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 16165 { 16166 struct bpf_verifier_state *vstate = env->cur_state; 16167 16168 /* If we simulate paths under speculation, we don't update the 16169 * insn as 'seen' such that when we verify unreachable paths in 16170 * the non-speculative domain, sanitize_dead_code() can still 16171 * rewrite/sanitize them. 16172 */ 16173 if (!vstate->speculative) 16174 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 16175 } 16176 16177 static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason) 16178 { 16179 static const char *err = "pointer arithmetic with it prohibited for !root"; 16180 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 16181 u32 dst = insn->dst_reg, src = insn->src_reg; 16182 struct bpf_reg_state *regs = cur_regs(env); 16183 16184 switch (reason) { 16185 case REASON_BOUNDS: 16186 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 16187 regs[src].type == SCALAR_VALUE ? src : dst, err); 16188 break; 16189 case REASON_TYPE: 16190 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 16191 regs[src].type == SCALAR_VALUE ? dst : src, err); 16192 break; 16193 case REASON_PATHS: 16194 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 16195 dst, op, err); 16196 break; 16197 case REASON_LIMIT: 16198 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 16199 dst, op, err); 16200 break; 16201 case REASON_STACK: 16202 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 16203 dst, err); 16204 return -ENOMEM; 16205 default: 16206 verifier_bug(env, "unknown reason (%d)", reason); 16207 break; 16208 } 16209 16210 return -EACCES; 16211 } 16212 16213 /* check that stack access falls within stack limits and that 'reg' doesn't 16214 * have a variable offset. 16215 * 16216 * Variable offset is prohibited for unprivileged mode for simplicity since it 16217 * requires corresponding support in Spectre masking for stack ALU. See also 16218 * retrieve_ptr_limit(). 16219 */ 16220 static int check_stack_access_for_ptr_arithmetic( 16221 struct bpf_verifier_env *env, 16222 int regno, 16223 const struct bpf_reg_state *reg, 16224 int off) 16225 { 16226 if (!tnum_is_const(reg->var_off)) { 16227 char tn_buf[48]; 16228 16229 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 16230 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 16231 regno, tn_buf, off); 16232 return -EACCES; 16233 } 16234 16235 if (off >= 0 || off < -(int)env->stack_limit) { 16236 verbose(env, "R%d stack pointer arithmetic goes out of range, " 16237 "prohibited for !root; off=%d\n", regno, off); 16238 return -EACCES; 16239 } 16240 16241 return 0; 16242 } 16243 16244 static int sanitize_check_bounds(struct bpf_verifier_env *env, 16245 const struct bpf_insn *insn, 16246 struct bpf_reg_state *dst_reg) 16247 { 16248 u32 dst = insn->dst_reg; 16249 16250 /* For unprivileged we require that resulting offset must be in bounds 16251 * in order to be able to sanitize access later on. 16252 */ 16253 if (env->bypass_spec_v1) 16254 return 0; 16255 16256 switch (dst_reg->type) { 16257 case PTR_TO_STACK: 16258 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 16259 dst_reg->var_off.value)) 16260 return -EACCES; 16261 break; 16262 case PTR_TO_MAP_VALUE: 16263 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 16264 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 16265 "prohibited for !root\n", dst); 16266 return -EACCES; 16267 } 16268 break; 16269 default: 16270 return -EOPNOTSUPP; 16271 } 16272 16273 return 0; 16274 } 16275 16276 static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg) 16277 { 16278 if (tnum_is_const(src_reg->var_off)) 16279 scalar_step_scale(dst_reg, src_reg->var_off.value); 16280 else 16281 reg_step_reset(dst_reg); 16282 } 16283 16284 static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg) 16285 { 16286 u64 amount = src_reg->var_off.value; 16287 16288 if (tnum_is_const(src_reg->var_off) && amount < 64) 16289 scalar_step_scale(dst_reg, 1ULL << amount); 16290 else 16291 reg_step_reset(dst_reg); 16292 } 16293 16294 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 16295 * Caller should also handle BPF_MOV case separately. 16296 * If we return -EACCES, caller may want to try again treating pointer as a 16297 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 16298 */ 16299 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, 16300 u32 ptr_regno, const struct bpf_reg_state *ptr_reg, 16301 const struct bpf_reg_state *off_reg) 16302 { 16303 struct bpf_verifier_state *vstate = env->cur_state; 16304 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 16305 struct bpf_reg_state *regs = state->regs, *dst_reg; 16306 bool known = tnum_is_const(off_reg->var_off); 16307 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 16308 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 16309 struct bpf_sanitize_info info = {}; 16310 u8 opcode = BPF_OP(insn->code); 16311 u32 dst = insn->dst_reg; 16312 const char *reason; 16313 int ret, bounds_ret; 16314 bool to_scalar; 16315 16316 dst_reg = ®s[dst]; 16317 /* 16318 * Only += and -= keep a pointer. Any other op makes a number of it, 16319 * which is fine when the program may see values of pointers anyway. 16320 */ 16321 to_scalar = opcode != BPF_ADD && opcode != BPF_SUB && env->allow_ptr_leaks; 16322 16323 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 16324 smin_val > smax_val || umin_val > umax_val) { 16325 /* Taint dst register if offset had invalid bounds derived from 16326 * e.g. dead branches. 16327 */ 16328 __mark_reg_unknown(env, dst_reg); 16329 return 0; 16330 } 16331 16332 if (BPF_CLASS(insn->code) != BPF_ALU64 && !to_scalar) { 16333 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 16334 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 16335 __mark_reg_unknown(env, dst_reg); 16336 return 0; 16337 } 16338 16339 verbose(env, 16340 "R%d 32-bit pointer arithmetic prohibited\n", 16341 dst); 16342 reason = bpf_diag_fmt( 16343 env, "R%d holds %s. 32-bit ALU operations on pointers discard pointer tracking, so the verifier cannot keep the result as a safe pointer.", 16344 ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type)); 16345 bpf_diag_register_type( 16346 env, env->insn_idx, ptr_regno, "32-bit pointer arithmetic", reason, 16347 "Use a 64-bit ALU instruction with an allowed, bounded scalar offset."); 16348 return -EACCES; 16349 } 16350 16351 if (ptr_reg->type & PTR_MAYBE_NULL) { 16352 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 16353 dst, reg_type_str(env, ptr_reg->type)); 16354 reason = bpf_diag_fmt( 16355 env, "R%d may be NULL (%s). Pointer arithmetic is allowed only after the program proves the pointer is non-NULL on this path.", 16356 ptr_regno, reg_type_str(env, ptr_reg->type)); 16357 bpf_diag_register_type( 16358 env, env->insn_idx, ptr_regno, "pointer arithmetic before NULL check", reason, 16359 "Make sure that a NULL check precedes any arithmetic performed on the pointer."); 16360 return -EACCES; 16361 } 16362 16363 switch (base_type(ptr_reg->type)) { 16364 case PTR_TO_CTX: 16365 case PTR_TO_MAP_VALUE: 16366 case PTR_TO_MAP_KEY: 16367 case PTR_TO_STACK: 16368 case PTR_TO_PACKET_META: 16369 case PTR_TO_PACKET: 16370 case PTR_TO_TP_BUFFER: 16371 case PTR_TO_BTF_ID: 16372 case PTR_TO_MEM: 16373 case PTR_TO_BUF: 16374 case PTR_TO_FUNC: 16375 case CONST_PTR_TO_DYNPTR: 16376 break; 16377 case PTR_TO_FLOW_KEYS: 16378 if (known) 16379 break; 16380 fallthrough; 16381 case CONST_PTR_TO_MAP: 16382 /* smin_val represents the known value */ 16383 if (known && smin_val == 0 && opcode == BPF_ADD) 16384 break; 16385 fallthrough; 16386 default: 16387 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 16388 dst, reg_type_str(env, ptr_reg->type)); 16389 reason = bpf_diag_fmt( 16390 env, "R%d holds %s. This pointer kind does not allow offset arithmetic.", 16391 ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type)); 16392 bpf_diag_register_type( 16393 env, env->insn_idx, ptr_regno, "pointer arithmetic is not allowed", reason, 16394 "Do not change this pointer's offset; use it only in operations accepted for its kind."); 16395 return -EACCES; 16396 } 16397 16398 if (to_scalar) { 16399 __mark_reg_unknown(env, dst_reg); 16400 return 0; 16401 } 16402 16403 /* For 'scalar += pointer', dst_reg inherits the complete pointer 16404 * register state. Individual fields may be adjusted later by pointer 16405 * arithmetic. Callers guarantee that below does not overwrite off_reg. 16406 */ 16407 if (dst_reg != ptr_reg) 16408 *dst_reg = *ptr_reg; 16409 16410 /* 16411 * Accesses to untrusted PTR_TO_MEM are done through probe 16412 * instructions, hence no need to track offsets. 16413 */ 16414 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 16415 return 0; 16416 16417 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type)) { 16418 reason = bpf_diag_fmt( 16419 env, "The scalar offset used with R%d is unbounded or outside the verifier's safe pointer-offset range [-%u, %u].", 16420 ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF); 16421 bpf_diag_register_type( 16422 env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason, 16423 "Clamp or bounds-check the scalar offset before applying it to the pointer."); 16424 return -EINVAL; 16425 } 16426 if (!check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) { 16427 reason = bpf_diag_fmt( 16428 env, "R%d already has an offset outside the verifier's safe range [-%u, %u] for %s.", 16429 ptr_regno, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF, 16430 bpf_diag_reg_type_plain(env, ptr_reg->type)); 16431 bpf_diag_register_type( 16432 env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason, 16433 "Keep the base pointer within the verifier's allowed offset range before applying more arithmetic."); 16434 return -EINVAL; 16435 } 16436 16437 if (sanitize_needed(opcode)) { 16438 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 16439 &info, false); 16440 if (ret < 0) 16441 return sanitize_err(env, insn, ret); 16442 } 16443 16444 /* 16445 * Pointer types do not carry 32-bit bounds at the moment. Blank r32 16446 * only after sanitize_ptr_alu() may have snapshotted dst_reg into a 16447 * speculative path: otherwise reg_bounds_sanity_check() might hit some 16448 * constraints violations. 16449 */ 16450 __mark_reg32_unbounded(dst_reg); 16451 16452 switch (opcode) { 16453 case BPF_ADD: 16454 /* 16455 * dst_reg gets the pointer type and since some positive 16456 * integer value was added to the pointer, give it a new 'id' 16457 * if it's a PTR_TO_PACKET. 16458 * this creates a new 'base' pointer, off_reg (variable) gets 16459 * added into the variable offset, and we copy the fixed offset 16460 * from ptr_reg. 16461 */ 16462 scalar_step_add(dst_reg, ptr_reg, off_reg); 16463 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 16464 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 16465 dst_reg->raw = ptr_reg->raw; 16466 if (reg_is_pkt_pointer(ptr_reg)) { 16467 if (!known) 16468 dst_reg->id = ++env->id_gen; 16469 /* 16470 * Clear range for unknown addends since we can't know 16471 * where the pkt pointer ended up. Also clear AT_PKT_END / 16472 * BEYOND_PKT_END from prior comparison as any pointer 16473 * arithmetic invalidates them. 16474 */ 16475 if (!known || dst_reg->range < 0) 16476 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 16477 } 16478 break; 16479 case BPF_SUB: 16480 if (dst_reg != ptr_reg) { 16481 /* scalar -= pointer. Creates an unknown scalar */ 16482 verbose(env, "R%d tried to subtract pointer from scalar\n", 16483 dst); 16484 reason = bpf_diag_fmt( 16485 env, "This operation subtracts pointer register R%d from scalar register R%d. " 16486 "The verifier only tracks pointer-minus-scalar arithmetic for allowed pointer types.", 16487 ptr_regno, dst); 16488 bpf_diag_register_type( 16489 env, env->insn_idx, ptr_regno, "pointer subtracted from scalar", reason, 16490 "Keep the pointer as the base; only add or subtract bounded scalars when permitted."); 16491 return -EACCES; 16492 } 16493 /* We don't allow subtraction from FP, because (according to 16494 * test_verifier.c test "invalid fp arithmetic", JITs might not 16495 * be able to deal with it. 16496 */ 16497 if (ptr_reg->type == PTR_TO_STACK) { 16498 verbose(env, "R%d subtraction from stack pointer prohibited\n", 16499 dst); 16500 reason = bpf_diag_fmt( 16501 env, "R%d is a stack pointer. The verifier does not allow BPF_SUB to move stack pointers.", 16502 ptr_regno); 16503 bpf_diag_register_type( 16504 env, env->insn_idx, ptr_regno, "subtraction from stack pointer", reason, 16505 "Use addition from R10 to form stack addresses within the tracked stack frame."); 16506 return -EACCES; 16507 } 16508 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 16509 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 16510 dst_reg->raw = ptr_reg->raw; 16511 if (reg_is_pkt_pointer(ptr_reg)) { 16512 if (!known) 16513 dst_reg->id = ++env->id_gen; 16514 /* 16515 * Clear range if the subtrahend may be negative since 16516 * pkt pointer could move past its bounds. A positive 16517 * subtrahend moves it backwards keeping positive range 16518 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 16519 * prior comparison as arithmetic invalidates them. 16520 */ 16521 if ((!known && smin_val < 0) || dst_reg->range < 0) 16522 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 16523 } 16524 reg_step_reset(dst_reg); 16525 break; 16526 case BPF_AND: 16527 case BPF_OR: 16528 case BPF_XOR: 16529 /* bitwise ops on pointers are troublesome, prohibit. */ 16530 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 16531 dst, bpf_alu_string[opcode >> 4]); 16532 reason = bpf_diag_fmt( 16533 env, "R%d holds %s. Bitwise operator %s would destroy the pointer value the verifier is tracking.", 16534 ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type), 16535 bpf_alu_string[opcode >> 4]); 16536 bpf_diag_register_type( 16537 env, env->insn_idx, ptr_regno, "bitwise operation on pointer", reason, 16538 "Do bitwise operations on scalar values, not on pointer-valued registers."); 16539 return -EACCES; 16540 default: 16541 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 16542 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 16543 dst, bpf_alu_string[opcode >> 4]); 16544 reason = bpf_diag_fmt( 16545 env, "R%d holds %s. Operator %s is not one of the limited pointer arithmetic operations the verifier can track.", 16546 ptr_regno, bpf_diag_reg_type_plain(env, ptr_reg->type), 16547 bpf_alu_string[opcode >> 4]); 16548 bpf_diag_register_type( 16549 env, env->insn_idx, ptr_regno, "invalid pointer arithmetic operator", reason, 16550 "Use only verifier-supported addition or subtraction with a bounded scalar offset, or perform this operation on a scalar value."); 16551 return -EACCES; 16552 } 16553 16554 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) { 16555 reason = bpf_diag_fmt( 16556 env, "After this arithmetic, R%d would be outside the verifier's safe offset range [-%u, %u] for %s.", 16557 dst, BPF_MAX_VAR_OFF, BPF_MAX_VAR_OFF, 16558 bpf_diag_reg_type_plain(env, ptr_reg->type)); 16559 bpf_diag_register_type( 16560 env, env->insn_idx, ptr_regno, "pointer offset is not safe", reason, 16561 "Tighten the scalar bounds before the arithmetic so the resulting pointer remains within the allowed range."); 16562 return -EINVAL; 16563 } 16564 /* 16565 * A packet pointer that keeps its id or range is checked against a 16566 * range set from the checked pointer's umax, so var_off must not tighten 16567 * its umax. r32 must still match var_off for reg_bounds_sanity_check(). 16568 */ 16569 if (reg_is_pkt_pointer(dst_reg) && (known || dst_reg->range > 0)) 16570 __update_reg32_bounds(dst_reg); 16571 else 16572 reg_bounds_sync(dst_reg); 16573 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 16574 if (bounds_ret == -EACCES) 16575 return bounds_ret; 16576 if (sanitize_needed(opcode)) { 16577 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 16578 &info, true); 16579 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 16580 && !env->cur_state->speculative 16581 && bounds_ret 16582 && !ret, 16583 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 16584 return -EFAULT; 16585 } 16586 if (ret < 0) 16587 return sanitize_err(env, insn, ret); 16588 } 16589 16590 return 0; 16591 } 16592 16593 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 16594 struct bpf_reg_state *src_reg) 16595 { 16596 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 16597 } 16598 16599 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 16600 struct bpf_reg_state *src_reg) 16601 { 16602 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 16603 } 16604 16605 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 16606 struct bpf_reg_state *src_reg) 16607 { 16608 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 16609 } 16610 16611 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 16612 struct bpf_reg_state *src_reg) 16613 { 16614 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 16615 } 16616 16617 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 16618 struct bpf_reg_state *src_reg) 16619 { 16620 s32 smin = reg_s32_min(dst_reg); 16621 s32 smax = reg_s32_max(dst_reg); 16622 u32 umin = reg_u32_min(dst_reg); 16623 u32 umax = reg_u32_max(dst_reg); 16624 s32 tmp_prod[4]; 16625 16626 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 16627 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 16628 /* Overflow possible, we know nothing */ 16629 umin = 0; 16630 umax = U32_MAX; 16631 } 16632 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 16633 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 16634 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 16635 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 16636 /* Overflow possible, we know nothing */ 16637 smin = S32_MIN; 16638 smax = S32_MAX; 16639 } else { 16640 smin = min_array(tmp_prod, 4); 16641 smax = max_array(tmp_prod, 4); 16642 } 16643 16644 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 16645 cnum32_from_srange(smin, smax)); 16646 } 16647 16648 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 16649 struct bpf_reg_state *src_reg) 16650 { 16651 s64 smin = reg_smin(dst_reg); 16652 s64 smax = reg_smax(dst_reg); 16653 u64 umin = reg_umin(dst_reg); 16654 u64 umax = reg_umax(dst_reg); 16655 s64 tmp_prod[4]; 16656 16657 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 16658 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 16659 /* Overflow possible, we know nothing */ 16660 umin = 0; 16661 umax = U64_MAX; 16662 } 16663 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 16664 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 16665 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 16666 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 16667 /* Overflow possible, we know nothing */ 16668 smin = S64_MIN; 16669 smax = S64_MAX; 16670 } else { 16671 smin = min_array(tmp_prod, 4); 16672 smax = max_array(tmp_prod, 4); 16673 } 16674 16675 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 16676 cnum64_from_srange(smin, smax)); 16677 } 16678 16679 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 16680 struct bpf_reg_state *src_reg) 16681 { 16682 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 16683 16684 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 16685 reg_u32_max(dst_reg) / src_val); 16686 16687 /* Reset other ranges/tnum to unbounded/unknown. */ 16688 reset_reg64_and_tnum(dst_reg); 16689 } 16690 16691 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 16692 struct bpf_reg_state *src_reg) 16693 { 16694 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 16695 16696 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 16697 div64_u64(reg_umax(dst_reg), src_val)); 16698 16699 /* Reset other ranges/tnum to unbounded/unknown. */ 16700 reset_reg32_and_tnum(dst_reg); 16701 } 16702 16703 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 16704 struct bpf_reg_state *src_reg) 16705 { 16706 s32 smin = reg_s32_min(dst_reg); 16707 s32 smax = reg_s32_max(dst_reg); 16708 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 16709 s32 res1, res2; 16710 16711 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 16712 if (smin == S32_MIN && src_val == -1) { 16713 /* 16714 * If the dividend range contains more than just S32_MIN, 16715 * we cannot precisely track the result, so it becomes unbounded. 16716 * e.g., [S32_MIN, S32_MIN+10]/(-1), 16717 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 16718 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 16719 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 16720 */ 16721 if (smax != S32_MIN) { 16722 smin = S32_MIN; 16723 smax = S32_MAX; 16724 } 16725 goto reset; 16726 } 16727 16728 res1 = smin / src_val; 16729 res2 = smax / src_val; 16730 smin = min(res1, res2); 16731 smax = max(res1, res2); 16732 16733 reset: 16734 reg_set_srange32(dst_reg, smin, smax); 16735 /* Reset other ranges/tnum to unbounded/unknown. */ 16736 reset_reg64_and_tnum(dst_reg); 16737 } 16738 16739 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 16740 struct bpf_reg_state *src_reg) 16741 { 16742 s64 smin = reg_smin(dst_reg); 16743 s64 smax = reg_smax(dst_reg); 16744 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 16745 s64 res1, res2; 16746 16747 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 16748 if (smin == S64_MIN && src_val == -1) { 16749 /* 16750 * If the dividend range contains more than just S64_MIN, 16751 * we cannot precisely track the result, so it becomes unbounded. 16752 * e.g., [S64_MIN, S64_MIN+10]/(-1), 16753 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 16754 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 16755 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 16756 */ 16757 if (smax != S64_MIN) { 16758 smin = S64_MIN; 16759 smax = S64_MAX; 16760 } 16761 goto reset; 16762 } 16763 16764 res1 = div64_s64(smin, src_val); 16765 res2 = div64_s64(smax, src_val); 16766 smin = min(res1, res2); 16767 smax = max(res1, res2); 16768 16769 reset: 16770 reg_set_srange64(dst_reg, smin, smax); 16771 /* Reset other ranges/tnum to unbounded/unknown. */ 16772 reset_reg32_and_tnum(dst_reg); 16773 } 16774 16775 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 16776 struct bpf_reg_state *src_reg) 16777 { 16778 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 16779 u32 res_max = src_val - 1; 16780 16781 /* 16782 * If dst_umax <= res_max, the result remains unchanged. 16783 * e.g., [2, 5] % 10 = [2, 5]. 16784 */ 16785 if (reg_u32_max(dst_reg) <= res_max) 16786 return; 16787 16788 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 16789 16790 /* Reset other ranges/tnum to unbounded/unknown. */ 16791 reset_reg64_and_tnum(dst_reg); 16792 } 16793 16794 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 16795 struct bpf_reg_state *src_reg) 16796 { 16797 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 16798 u64 res_max = src_val - 1; 16799 16800 /* 16801 * If dst_umax <= res_max, the result remains unchanged. 16802 * e.g., [2, 5] % 10 = [2, 5]. 16803 */ 16804 if (reg_umax(dst_reg) <= res_max) 16805 return; 16806 16807 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 16808 16809 /* Reset other ranges/tnum to unbounded/unknown. */ 16810 reset_reg32_and_tnum(dst_reg); 16811 } 16812 16813 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 16814 struct bpf_reg_state *src_reg) 16815 { 16816 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 16817 16818 /* 16819 * Safe absolute value calculation: 16820 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 16821 * Here use unsigned integer to avoid overflow. 16822 */ 16823 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 16824 16825 /* 16826 * Calculate the maximum possible absolute value of the result. 16827 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 16828 * 2147483647 (S32_MAX), which fits perfectly in s32. 16829 */ 16830 s32 res_max_abs = src_abs - 1; 16831 16832 /* 16833 * If the dividend is already within the result range, 16834 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 16835 */ 16836 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 16837 return; 16838 16839 /* General case: result has the same sign as the dividend. */ 16840 if (reg_s32_min(dst_reg) >= 0) { 16841 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 16842 } else if (reg_s32_max(dst_reg) <= 0) { 16843 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 16844 } else { 16845 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 16846 } 16847 16848 /* Reset other ranges/tnum to unbounded/unknown. */ 16849 reset_reg64_and_tnum(dst_reg); 16850 } 16851 16852 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 16853 struct bpf_reg_state *src_reg) 16854 { 16855 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 16856 16857 /* 16858 * Safe absolute value calculation: 16859 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 16860 * Here use unsigned integer to avoid overflow. 16861 */ 16862 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 16863 16864 /* 16865 * Calculate the maximum possible absolute value of the result. 16866 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 16867 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 16868 */ 16869 s64 res_max_abs = src_abs - 1; 16870 16871 /* 16872 * If the dividend is already within the result range, 16873 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 16874 */ 16875 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 16876 return; 16877 16878 /* General case: result has the same sign as the dividend. */ 16879 if (reg_smin(dst_reg) >= 0) { 16880 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 16881 } else if (reg_smax(dst_reg) <= 0) { 16882 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 16883 } else { 16884 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 16885 } 16886 16887 /* Reset other ranges/tnum to unbounded/unknown. */ 16888 reset_reg32_and_tnum(dst_reg); 16889 } 16890 16891 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 16892 struct bpf_reg_state *src_reg) 16893 { 16894 bool src_known = tnum_subreg_is_const(src_reg->var_off); 16895 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 16896 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 16897 u32 umax_val = reg_u32_max(src_reg); 16898 16899 if (src_known && dst_known) { 16900 __mark_reg32_known(dst_reg, var32_off.value); 16901 return; 16902 } 16903 16904 /* We get our minimum from the var_off, since that's inherently 16905 * bitwise. Our maximum is the minimum of the operands' maxima. 16906 */ 16907 reg_set_urange32(dst_reg, 16908 var32_off.value, 16909 min(reg_u32_max(dst_reg), umax_val)); 16910 } 16911 16912 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 16913 struct bpf_reg_state *src_reg) 16914 { 16915 bool src_known = tnum_is_const(src_reg->var_off); 16916 bool dst_known = tnum_is_const(dst_reg->var_off); 16917 u64 umax_val = reg_umax(src_reg); 16918 16919 if (src_known && dst_known) { 16920 __mark_reg_known(dst_reg, dst_reg->var_off.value); 16921 return; 16922 } 16923 16924 /* We get our minimum from the var_off, since that's inherently 16925 * bitwise. Our maximum is the minimum of the operands' maxima. 16926 */ 16927 reg_set_urange64(dst_reg, 16928 dst_reg->var_off.value, 16929 min(reg_umax(dst_reg), umax_val)); 16930 16931 /* We may learn something more from the var_off */ 16932 __update_reg_bounds(dst_reg); 16933 } 16934 16935 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 16936 struct bpf_reg_state *src_reg) 16937 { 16938 bool src_known = tnum_subreg_is_const(src_reg->var_off); 16939 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 16940 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 16941 u32 umin_val = reg_u32_min(src_reg); 16942 16943 if (src_known && dst_known) { 16944 __mark_reg32_known(dst_reg, var32_off.value); 16945 return; 16946 } 16947 16948 /* We get our maximum from the var_off, and our minimum is the 16949 * maximum of the operands' minima 16950 */ 16951 reg_set_urange32(dst_reg, 16952 max(reg_u32_min(dst_reg), umin_val), 16953 var32_off.value | var32_off.mask); 16954 } 16955 16956 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 16957 struct bpf_reg_state *src_reg) 16958 { 16959 bool src_known = tnum_is_const(src_reg->var_off); 16960 bool dst_known = tnum_is_const(dst_reg->var_off); 16961 u64 umin_val = reg_umin(src_reg); 16962 16963 if (src_known && dst_known) { 16964 __mark_reg_known(dst_reg, dst_reg->var_off.value); 16965 return; 16966 } 16967 16968 /* We get our maximum from the var_off, and our minimum is the 16969 * maximum of the operands' minima 16970 */ 16971 reg_set_urange64(dst_reg, 16972 max(reg_umin(dst_reg), umin_val), 16973 dst_reg->var_off.value | dst_reg->var_off.mask); 16974 16975 /* We may learn something more from the var_off */ 16976 __update_reg_bounds(dst_reg); 16977 } 16978 16979 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 16980 struct bpf_reg_state *src_reg) 16981 { 16982 bool src_known = tnum_subreg_is_const(src_reg->var_off); 16983 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 16984 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 16985 16986 if (src_known && dst_known) { 16987 __mark_reg32_known(dst_reg, var32_off.value); 16988 return; 16989 } 16990 16991 /* We get both minimum and maximum from the var32_off. */ 16992 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 16993 } 16994 16995 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 16996 struct bpf_reg_state *src_reg) 16997 { 16998 bool src_known = tnum_is_const(src_reg->var_off); 16999 bool dst_known = tnum_is_const(dst_reg->var_off); 17000 17001 if (src_known && dst_known) { 17002 /* dst_reg->var_off.value has been updated earlier */ 17003 __mark_reg_known(dst_reg, dst_reg->var_off.value); 17004 return; 17005 } 17006 17007 /* We get both minimum and maximum from the var_off. */ 17008 reg_set_urange64(dst_reg, 17009 dst_reg->var_off.value, 17010 dst_reg->var_off.value | dst_reg->var_off.mask); 17011 } 17012 17013 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 17014 u64 umin_val, u64 umax_val) 17015 { 17016 /* If we might shift our top bit out, then we know nothing */ 17017 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 17018 reg_set_urange32(dst_reg, 0, U32_MAX); 17019 else 17020 /* We lose all sign bit information (except what we can pick 17021 * up from var_off) 17022 */ 17023 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 17024 reg_u32_max(dst_reg) << umax_val); 17025 } 17026 17027 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 17028 struct bpf_reg_state *src_reg) 17029 { 17030 u32 umax_val = reg_u32_max(src_reg); 17031 u32 umin_val = reg_u32_min(src_reg); 17032 /* u32 alu operation will zext upper bits */ 17033 struct tnum subreg = tnum_subreg(dst_reg->var_off); 17034 17035 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 17036 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 17037 /* Not required but being careful mark reg64 bounds as unknown so 17038 * that we are forced to pick them up from tnum and zext later and 17039 * if some path skips this step we are still safe. 17040 */ 17041 __mark_reg64_unbounded(dst_reg); 17042 __update_reg32_bounds(dst_reg); 17043 } 17044 17045 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 17046 u64 umin_val, u64 umax_val) 17047 { 17048 struct cnum64 u, s; 17049 17050 /* Special case <<32 because it is a common compiler pattern to sign 17051 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 17052 * because s32 bounds don't flip sign when shifting to the left by 17053 * 32bits. 17054 */ 17055 if (umin_val == 32 && umax_val == 32) 17056 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 17057 (s64)reg_s32_max(dst_reg) << 32); 17058 else 17059 s = CNUM64_UNBOUNDED; 17060 17061 /* If we might shift our top bit out, then we know nothing */ 17062 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 17063 u = CNUM64_UNBOUNDED; 17064 else 17065 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 17066 reg_umax(dst_reg) << umax_val); 17067 17068 dst_reg->r64 = cnum64_intersect(u, s); 17069 } 17070 17071 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 17072 struct bpf_reg_state *src_reg) 17073 { 17074 u64 umax_val = reg_umax(src_reg); 17075 u64 umin_val = reg_umin(src_reg); 17076 17077 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 17078 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 17079 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 17080 17081 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 17082 /* We may learn something more from the var_off */ 17083 __update_reg_bounds(dst_reg); 17084 } 17085 17086 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 17087 struct bpf_reg_state *src_reg) 17088 { 17089 struct tnum subreg = tnum_subreg(dst_reg->var_off); 17090 u32 umax_val = reg_u32_max(src_reg); 17091 u32 umin_val = reg_u32_min(src_reg); 17092 17093 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 17094 * be negative, then either: 17095 * 1) src_reg might be zero, so the sign bit of the result is 17096 * unknown, so we lose our signed bounds 17097 * 2) it's known negative, thus the unsigned bounds capture the 17098 * signed bounds 17099 * 3) the signed bounds cross zero, so they tell us nothing 17100 * about the result 17101 * If the value in dst_reg is known nonnegative, then again the 17102 * unsigned bounds capture the signed bounds. 17103 * Thus, in all cases it suffices to blow away our signed bounds 17104 * and rely on inferring new ones from the unsigned bounds and 17105 * var_off of the result. 17106 */ 17107 17108 dst_reg->var_off = tnum_rshift(subreg, umin_val); 17109 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 17110 reg_u32_max(dst_reg) >> umin_val); 17111 17112 __mark_reg64_unbounded(dst_reg); 17113 __update_reg32_bounds(dst_reg); 17114 } 17115 17116 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 17117 struct bpf_reg_state *src_reg) 17118 { 17119 u64 umax_val = reg_umax(src_reg); 17120 u64 umin_val = reg_umin(src_reg); 17121 17122 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 17123 * be negative, then either: 17124 * 1) src_reg might be zero, so the sign bit of the result is 17125 * unknown, so we lose our signed bounds 17126 * 2) it's known negative, thus the unsigned bounds capture the 17127 * signed bounds 17128 * 3) the signed bounds cross zero, so they tell us nothing 17129 * about the result 17130 * If the value in dst_reg is known nonnegative, then again the 17131 * unsigned bounds capture the signed bounds. 17132 * Thus, in all cases it suffices to blow away our signed bounds 17133 * and rely on inferring new ones from the unsigned bounds and 17134 * var_off of the result. 17135 */ 17136 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 17137 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 17138 reg_umax(dst_reg) >> umin_val); 17139 17140 /* Its not easy to operate on alu32 bounds here because it depends 17141 * on bits being shifted in. Take easy way out and mark unbounded 17142 * so we can recalculate later from tnum. 17143 */ 17144 __mark_reg32_unbounded(dst_reg); 17145 __update_reg_bounds(dst_reg); 17146 } 17147 17148 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 17149 struct bpf_reg_state *src_reg) 17150 { 17151 u64 umin_val = reg_u32_min(src_reg); 17152 17153 /* Upon reaching here, src_known is true and 17154 * umax_val is equal to umin_val. 17155 * Blow away the dst_reg umin_value/umax_value and rely on 17156 * dst_reg var_off to refine the result. 17157 */ 17158 reg_set_srange32(dst_reg, 17159 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 17160 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 17161 17162 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 17163 17164 __mark_reg64_unbounded(dst_reg); 17165 __update_reg32_bounds(dst_reg); 17166 } 17167 17168 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 17169 struct bpf_reg_state *src_reg) 17170 { 17171 u64 umin_val = reg_umin(src_reg); 17172 17173 /* Upon reaching here, src_known is true and umax_val is equal 17174 * to umin_val. 17175 */ 17176 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 17177 reg_smax(dst_reg) >> umin_val); 17178 17179 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 17180 17181 /* Its not easy to operate on alu32 bounds here because it depends 17182 * on bits being shifted in from upper 32-bits. Take easy way out 17183 * and mark unbounded so we can recalculate later from tnum. 17184 */ 17185 __mark_reg32_unbounded(dst_reg); 17186 __update_reg_bounds(dst_reg); 17187 } 17188 17189 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 17190 { 17191 /* 17192 * Byte swap operation - update var_off using tnum_bswap. 17193 * Three cases: 17194 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 17195 * unconditional swap 17196 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 17197 * swap on big-endian, truncation or no-op on little-endian 17198 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 17199 * swap on little-endian, truncation or no-op on big-endian 17200 */ 17201 17202 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 17203 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 17204 bool is_big_endian; 17205 #ifdef CONFIG_CPU_BIG_ENDIAN 17206 is_big_endian = true; 17207 #else 17208 is_big_endian = false; 17209 #endif 17210 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 17211 bool need_bswap = alu64 || (to_le == is_big_endian); 17212 17213 /* 17214 * If the register is mutated, manually reset its scalar ID to break 17215 * any existing ties and avoid incorrect bounds propagation. 17216 */ 17217 if (need_bswap || insn->imm == 16 || insn->imm == 32) 17218 clear_scalar_id(dst_reg); 17219 17220 if (need_bswap) { 17221 if (insn->imm == 16) 17222 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 17223 else if (insn->imm == 32) 17224 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 17225 else if (insn->imm == 64) 17226 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 17227 /* 17228 * Byteswap scrambles the range, so we must reset bounds. 17229 * Bounds will be re-derived from the new tnum later. 17230 */ 17231 __mark_reg_unbounded(dst_reg); 17232 reg_step_reset(dst_reg); 17233 } 17234 /* For bswap16/32, truncate dst register to match the swapped size */ 17235 if (insn->imm == 16 || insn->imm == 32) 17236 coerce_reg_to_size(dst_reg, insn->imm / 8); 17237 } 17238 17239 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 17240 const struct bpf_reg_state *src_reg) 17241 { 17242 bool src_is_const = false; 17243 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 17244 17245 if (insn_bitness == 32) { 17246 if (tnum_subreg_is_const(src_reg->var_off) 17247 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 17248 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 17249 src_is_const = true; 17250 } else { 17251 if (tnum_is_const(src_reg->var_off) 17252 && reg_smin(src_reg) == reg_smax(src_reg) 17253 && reg_umin(src_reg) == reg_umax(src_reg)) 17254 src_is_const = true; 17255 } 17256 17257 switch (BPF_OP(insn->code)) { 17258 case BPF_ADD: 17259 case BPF_SUB: 17260 case BPF_NEG: 17261 case BPF_AND: 17262 case BPF_XOR: 17263 case BPF_OR: 17264 case BPF_MUL: 17265 case BPF_END: 17266 return true; 17267 17268 /* 17269 * Division and modulo operators range is only safe to compute when the 17270 * divisor is a constant. 17271 */ 17272 case BPF_DIV: 17273 case BPF_MOD: 17274 return src_is_const; 17275 17276 /* Shift operators range is only computable if shift dimension operand 17277 * is a constant. Shifts greater than 31 or 63 are undefined. This 17278 * includes shifts by a negative number. 17279 */ 17280 case BPF_LSH: 17281 case BPF_RSH: 17282 case BPF_ARSH: 17283 return (src_is_const && reg_umax(src_reg) < insn_bitness); 17284 default: 17285 return false; 17286 } 17287 } 17288 17289 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, 17290 struct bpf_reg_state *dst_reg, struct bpf_reg_state src_reg); 17291 17292 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 17293 struct bpf_reg_state *dst_reg, const struct bpf_reg_state *src_reg) 17294 { 17295 struct bpf_verifier_state *branch; 17296 struct bpf_reg_state *reg; 17297 bool alu32; 17298 17299 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 17300 alu32 = false; 17301 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 17302 alu32 = true; 17303 else 17304 return 0; 17305 17306 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 17307 if (IS_ERR(branch)) 17308 return PTR_ERR(branch); 17309 17310 reg = &branch->frame[branch->curframe]->regs[insn->dst_reg]; 17311 if (alu32) { 17312 __mark_reg32_known(reg, 0); 17313 __mark_reg32_known(dst_reg, -1ull); 17314 } else { 17315 __mark_reg_known(reg, 0); 17316 __mark_reg_known(dst_reg, -1ull); 17317 } 17318 /* 17319 * The insn is done with in the branch too, and what gets to the next insn is a state 17320 * like any other. At this insn the branch is a part of the state that is looked at: 17321 * it must not be compared with it. 17322 */ 17323 clear_scalar_id(reg); 17324 return adjust_scalar_min_max_vals(env, insn, reg, *src_reg); 17325 } 17326 17327 /* WARNING: This function does calculations on 64-bit values, but the actual 17328 * execution may occur on 32-bit values. Therefore, things like bitshifts 17329 * need extra checks in the 32-bit case. 17330 */ 17331 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 17332 struct bpf_insn *insn, 17333 struct bpf_reg_state *dst_reg, 17334 struct bpf_reg_state src_reg) 17335 { 17336 u8 opcode = BPF_OP(insn->code); 17337 s16 off = insn->off; 17338 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 17339 int ret; 17340 17341 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 17342 __mark_reg_unknown(env, dst_reg); 17343 return 0; 17344 } 17345 17346 if (sanitize_needed(opcode)) { 17347 ret = sanitize_val_alu(env, insn); 17348 if (ret < 0) 17349 return sanitize_err(env, insn, ret); 17350 } 17351 17352 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 17353 * There are two classes of instructions: The first class we track both 17354 * alu32 and alu64 sign/unsigned bounds independently this provides the 17355 * greatest amount of precision when alu operations are mixed with jmp32 17356 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 17357 * and BPF_OR. This is possible because these ops have fairly easy to 17358 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 17359 * See alu32 verifier tests for examples. The second class of 17360 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 17361 * with regards to tracking sign/unsigned bounds because the bits may 17362 * cross subreg boundaries in the alu64 case. When this happens we mark 17363 * the reg unbounded in the subreg bound space and use the resulting 17364 * tnum to calculate an approximation of the sign/unsigned bounds. 17365 */ 17366 switch (opcode) { 17367 case BPF_ADD: 17368 scalar_step_add(dst_reg, dst_reg, &src_reg); 17369 scalar32_min_max_add(dst_reg, &src_reg); 17370 scalar_min_max_add(dst_reg, &src_reg); 17371 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 17372 break; 17373 case BPF_SUB: 17374 scalar32_min_max_sub(dst_reg, &src_reg); 17375 scalar_min_max_sub(dst_reg, &src_reg); 17376 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 17377 reg_step_reset(dst_reg); 17378 break; 17379 case BPF_NEG: 17380 env->fake_reg[0] = *dst_reg; 17381 __mark_reg_known(dst_reg, 0); 17382 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 17383 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 17384 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 17385 reg_step_reset(dst_reg); 17386 break; 17387 case BPF_MUL: 17388 scalar_step_mul(dst_reg, &src_reg); 17389 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 17390 scalar32_min_max_mul(dst_reg, &src_reg); 17391 scalar_min_max_mul(dst_reg, &src_reg); 17392 break; 17393 case BPF_DIV: 17394 /* BPF div specification: x / 0 = 0 */ 17395 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 17396 ___mark_reg_known(dst_reg, 0); 17397 break; 17398 } 17399 if (alu32) 17400 if (off == 1) 17401 scalar32_min_max_sdiv(dst_reg, &src_reg); 17402 else 17403 scalar32_min_max_udiv(dst_reg, &src_reg); 17404 else 17405 if (off == 1) 17406 scalar_min_max_sdiv(dst_reg, &src_reg); 17407 else 17408 scalar_min_max_udiv(dst_reg, &src_reg); 17409 reg_step_reset(dst_reg); 17410 break; 17411 case BPF_MOD: 17412 /* BPF mod specification: x % 0 = x */ 17413 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 17414 break; 17415 if (alu32) 17416 if (off == 1) 17417 scalar32_min_max_smod(dst_reg, &src_reg); 17418 else 17419 scalar32_min_max_umod(dst_reg, &src_reg); 17420 else 17421 if (off == 1) 17422 scalar_min_max_smod(dst_reg, &src_reg); 17423 else 17424 scalar_min_max_umod(dst_reg, &src_reg); 17425 reg_step_reset(dst_reg); 17426 break; 17427 case BPF_AND: 17428 if (tnum_is_const(src_reg.var_off)) { 17429 ret = maybe_fork_scalars(env, insn, dst_reg, &src_reg); 17430 if (ret) 17431 return ret; 17432 } 17433 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 17434 scalar32_min_max_and(dst_reg, &src_reg); 17435 scalar_min_max_and(dst_reg, &src_reg); 17436 reg_step_reset(dst_reg); 17437 break; 17438 case BPF_OR: 17439 if (tnum_is_const(src_reg.var_off)) { 17440 ret = maybe_fork_scalars(env, insn, dst_reg, &src_reg); 17441 if (ret) 17442 return ret; 17443 } 17444 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 17445 scalar32_min_max_or(dst_reg, &src_reg); 17446 scalar_min_max_or(dst_reg, &src_reg); 17447 reg_step_reset(dst_reg); 17448 break; 17449 case BPF_XOR: 17450 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 17451 scalar32_min_max_xor(dst_reg, &src_reg); 17452 scalar_min_max_xor(dst_reg, &src_reg); 17453 reg_step_reset(dst_reg); 17454 break; 17455 case BPF_LSH: 17456 scalar_step_lsh(dst_reg, &src_reg); 17457 if (alu32) 17458 scalar32_min_max_lsh(dst_reg, &src_reg); 17459 else 17460 scalar_min_max_lsh(dst_reg, &src_reg); 17461 break; 17462 case BPF_RSH: 17463 if (alu32) 17464 scalar32_min_max_rsh(dst_reg, &src_reg); 17465 else 17466 scalar_min_max_rsh(dst_reg, &src_reg); 17467 reg_step_reset(dst_reg); 17468 break; 17469 case BPF_ARSH: 17470 if (alu32) 17471 scalar32_min_max_arsh(dst_reg, &src_reg); 17472 else 17473 scalar_min_max_arsh(dst_reg, &src_reg); 17474 reg_step_reset(dst_reg); 17475 break; 17476 case BPF_END: 17477 scalar_byte_swap(dst_reg, insn); 17478 reg_step_reset(dst_reg); 17479 break; 17480 default: 17481 break; 17482 } 17483 17484 /* 17485 * ALU32 ops are zero extended into 64bit register. 17486 * 17487 * BPF_END is already handled inside the helper (truncation), 17488 * so skip zext here to avoid unexpected zero extension. 17489 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 17490 * This is a 64bit byte swap operation with alu32==true, 17491 * but we should not zero extend the result. 17492 */ 17493 if (alu32 && opcode != BPF_END) 17494 zext_32_to_64(dst_reg); 17495 reg_bounds_sync(dst_reg); 17496 return 0; 17497 } 17498 17499 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 17500 * and var_off. 17501 */ 17502 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 17503 struct bpf_insn *insn) 17504 { 17505 struct bpf_verifier_state *vstate = env->cur_state; 17506 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17507 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 17508 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 17509 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 17510 struct bpf_insn_aux_data *aux = cur_aux(env); 17511 u8 opcode = BPF_OP(insn->code); 17512 int err; 17513 17514 dst_reg = ®s[insn->dst_reg]; 17515 if (BPF_SRC(insn->code) == BPF_X) 17516 src_reg = ®s[insn->src_reg]; 17517 else 17518 src_reg = NULL; 17519 17520 /* Case where at least one operand is an arena. */ 17521 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 17522 17523 if (dst_reg->type != PTR_TO_ARENA) 17524 *dst_reg = *src_reg; 17525 17526 if (BPF_CLASS(insn->code) == BPF_ALU64) { 17527 /* 17528 * Only arena pointers set needs_zext, but doing so 17529 * modifies the instruction at fixup time to an ALU32 17530 * and makes it unsuitable for 64-bit scalar args. We 17531 * prevent zext from being set if the instruction has 17532 * been previously called with non-arena registers. 17533 */ 17534 if (aux->prevent_zext) { 17535 verbose(env, "same insn cannot be used with and without arena pointer\n"); 17536 return -EINVAL; 17537 } 17538 17539 /* 17540 * 32-bit operations zero upper bits automatically. 17541 * 64-bit operations need to be converted to 32. 17542 */ 17543 aux->needs_zext = true; 17544 aux->zext_dst = true; 17545 } 17546 17547 /* Any arithmetic operations are allowed on arena pointers */ 17548 return 0; 17549 } 17550 17551 /* Prevent the instruction from being used with arena pointers (see above). */ 17552 if (env->prog->aux->arena && BPF_CLASS(insn->code) == BPF_ALU64) { 17553 if (aux->needs_zext) { 17554 verbose(env, "same insn cannot be used with and without arena pointer\n"); 17555 return -EINVAL; 17556 } 17557 17558 aux->prevent_zext = true; 17559 } 17560 17561 if (dst_reg->type != SCALAR_VALUE) 17562 ptr_reg = dst_reg; 17563 17564 if (BPF_SRC(insn->code) == BPF_X) { 17565 if (src_reg->type != SCALAR_VALUE) { 17566 if (dst_reg->type != SCALAR_VALUE) { 17567 /* Combining two pointers by any ALU op yields 17568 * an arbitrary scalar. Disallow all math except 17569 * pointer subtraction 17570 */ 17571 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 17572 mark_reg_unknown(env, regs, insn->dst_reg); 17573 return 0; 17574 } 17575 verbose(env, "R%d pointer %s pointer prohibited\n", 17576 insn->dst_reg, 17577 bpf_alu_string[opcode >> 4]); 17578 return -EACCES; 17579 } else { 17580 /* scalar += pointer 17581 * This is legal, but we have to reverse our 17582 * src/dest handling in computing the range 17583 */ 17584 err = mark_chain_precision(env, insn->dst_reg); 17585 if (err) 17586 return err; 17587 off_reg = *dst_reg; 17588 return adjust_ptr_min_max_vals(env, insn, insn->src_reg, src_reg, 17589 &off_reg); 17590 } 17591 } else if (ptr_reg) { 17592 /* pointer += scalar */ 17593 err = mark_chain_precision(env, insn->src_reg); 17594 if (err) 17595 return err; 17596 return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, dst_reg, src_reg); 17597 } else if (dst_reg->precise) { 17598 /* if dst_reg is precise, src_reg should be precise as well */ 17599 err = mark_chain_precision(env, insn->src_reg); 17600 if (err) 17601 return err; 17602 } 17603 } else { 17604 /* Pretend the src is a reg with a known value, since we only 17605 * need to be able to read from this state. 17606 */ 17607 off_reg.type = SCALAR_VALUE; 17608 __mark_reg_known(&off_reg, insn->imm); 17609 src_reg = &off_reg; 17610 if (ptr_reg) /* pointer += K */ 17611 return adjust_ptr_min_max_vals(env, insn, insn->dst_reg, ptr_reg, src_reg); 17612 } 17613 17614 /* Got here implies adding two SCALAR_VALUEs */ 17615 if (WARN_ON_ONCE(ptr_reg)) { 17616 print_verifier_state(env, vstate, vstate->curframe, true); 17617 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 17618 return -EFAULT; 17619 } 17620 if (WARN_ON(!src_reg)) { 17621 print_verifier_state(env, vstate, vstate->curframe, true); 17622 verbose(env, "verifier internal error: no src_reg\n"); 17623 return -EFAULT; 17624 } 17625 /* 17626 * For alu32 linked register tracking, we need to check dst_reg's 17627 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 17628 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 17629 */ 17630 u64 dst_umax = reg_umax(dst_reg); 17631 17632 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 17633 if (err) 17634 return err; 17635 /* 17636 * Compilers can generate the code 17637 * r1 = r2 17638 * r1 += 0x1 17639 * if r2 < 1000 goto ... 17640 * use r1 in memory access 17641 * So remember constant delta between r2 and r1 and update r1 after 17642 * 'if' condition. 17643 */ 17644 if (env->bpf_capable && 17645 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 17646 dst_reg->id && is_reg_const(src_reg, alu32) && 17647 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 17648 u64 val = reg_const_value(src_reg, alu32); 17649 s32 off; 17650 17651 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 17652 goto clear_id; 17653 17654 if (alu32 && (dst_umax > U32_MAX)) 17655 goto clear_id; 17656 17657 off = (s32)val; 17658 17659 if (BPF_OP(insn->code) == BPF_SUB) { 17660 /* Negating S32_MIN would overflow */ 17661 if (off == S32_MIN) 17662 goto clear_id; 17663 off = -off; 17664 } 17665 17666 if (dst_reg->id & BPF_ADD_CONST) { 17667 /* 17668 * If the register already went through rX += val 17669 * we cannot accumulate another val into rx->off. 17670 */ 17671 clear_id: 17672 clear_scalar_id(dst_reg); 17673 } else { 17674 if (alu32) 17675 dst_reg->id |= BPF_ADD_CONST32; 17676 else 17677 dst_reg->id |= BPF_ADD_CONST64; 17678 dst_reg->delta = off; 17679 } 17680 } else { 17681 /* 17682 * Make sure ID is cleared otherwise dst_reg min/max could be 17683 * incorrectly propagated into other registers by sync_linked_regs() 17684 */ 17685 clear_scalar_id(dst_reg); 17686 } 17687 return 0; 17688 } 17689 17690 /* 17691 * Many checks done by this function are quite conservative. 17692 * This is because main verification pass does not maintain 17693 * enough information to track object identities for some 17694 * of the interesting types, e.g. PTR_TO_MEM. 17695 */ 17696 bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a, 17697 const struct bpf_reg_state *reg_b) 17698 { 17699 if (reg_a == reg_b) 17700 return true; 17701 /* Require matching flags and base types. */ 17702 if (reg_a->type != reg_b->type) 17703 return false; 17704 /* NULL can't be compared to some base+offset pointer. */ 17705 if (type_may_be_null(reg_a->type)) 17706 return false; 17707 17708 switch (base_type(reg_a->type)) { 17709 case PTR_TO_STACK: 17710 return reg_a->frameno == reg_b->frameno; 17711 case PTR_TO_MAP_VALUE: 17712 if (reg_a->map_ptr != reg_b->map_ptr || reg_a->map_uid != reg_b->map_uid) 17713 return false; 17714 if (reg_a->id && reg_a->id == reg_b->id) 17715 return true; 17716 /* 17717 * A plain single-element array has one stable value address, 17718 * but not when BPF_F_INNER_MAP is set, see arraymap.c:array_map_meta_equal(). 17719 */ 17720 if (reg_a->map_ptr->map_type == BPF_MAP_TYPE_ARRAY && 17721 reg_a->map_ptr->max_entries == 1 && 17722 !(reg_a->map_ptr->map_flags & BPF_F_INNER_MAP)) 17723 return true; 17724 /* 17725 * The rules above can be simplified / relaxed if: 17726 * - fresh IDs would always be assigned for map-value lookups; 17727 * - direct map value loads would always have and ID of zero. 17728 */ 17729 return false; 17730 case PTR_TO_MEM: 17731 case PTR_TO_BUF: 17732 return reg_a->id && reg_a->id == reg_b->id; 17733 17734 default: 17735 return false; 17736 } 17737 } 17738 17739 int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 17740 struct cnum64 r64, struct cnum32 r32, u16 base, u16 step) 17741 { 17742 reg->r64 = r64; 17743 reg->r32 = r32; 17744 reg->step = step; 17745 reg->base = base; 17746 reg->var_off = tnum_unknown; 17747 reg_bounds_sync(reg); /* this should infer the tnum alignment */ 17748 return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range"); 17749 } 17750 17751 /* 17752 * Checks if pointer and packet metadata matches between two registers. 17753 * For use with bpf_reg_union(). 17754 */ 17755 bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b) 17756 { 17757 if (a->type != b->type) 17758 return false; 17759 if (a->type == SCALAR_VALUE) 17760 return true; 17761 return !memcmp(a, b, offsetof(struct bpf_reg_state, var_off)) && 17762 a->id == b->id && a->parent_id == b->parent_id && a->map_uid == b->map_uid; 17763 } 17764 17765 /* 17766 * Extends acc's scalar range to include src's scalar range. 17767 * Caller must ensure that other kinds of metadata is compatible. 17768 * Caller must clear acc's scalar ID. 17769 */ 17770 int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc, 17771 const struct bpf_reg_state *src) 17772 { 17773 u16 base, step; 17774 17775 if (!bpf_reg_union_compatible(acc, src)) { 17776 verifier_bug(env, "union of incompatible registers"); 17777 return -EFAULT; 17778 } 17779 acc->r64 = cnum64_union(acc->r64, src->r64); 17780 acc->r32 = cnum32_union(acc->r32, src->r32); 17781 acc->var_off = tnum_union(acc->var_off, src->var_off); 17782 17783 /* Retain a common congruence if the bases agree modulo the gcd. */ 17784 step = gcd(acc->step, src->step); 17785 base = acc->base % step; 17786 if (base != src->base % step) { 17787 reg_step_reset(acc); 17788 } else { 17789 acc->base = base; 17790 acc->step = step; 17791 } 17792 reg_bounds_sync(acc); 17793 return reg_bounds_sanity_check(env, acc, "bpf_reg_union"); 17794 } 17795 17796 /* check validity of 32-bit and 64-bit arithmetic operations */ 17797 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 17798 { 17799 struct bpf_reg_state *regs = cur_regs(env); 17800 u8 opcode = BPF_OP(insn->code); 17801 int err; 17802 17803 bpf_diag_mod_begin(env, ®s[insn->dst_reg], NULL, BPF_DIAG_MOD_WRITE); 17804 17805 if (opcode == BPF_END || opcode == BPF_NEG) { 17806 /* check src operand */ 17807 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17808 if (err) 17809 return err; 17810 17811 if (is_pointer_value(env, insn->dst_reg)) { 17812 verbose(env, "R%d pointer arithmetic prohibited\n", 17813 insn->dst_reg); 17814 return -EACCES; 17815 } 17816 17817 /* check dest operand */ 17818 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 17819 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17820 err = err ?: adjust_scalar_min_max_vals(env, insn, 17821 ®s[insn->dst_reg], 17822 regs[insn->dst_reg]); 17823 } else { 17824 err = check_reg_arg(env, insn->dst_reg, DST_OP); 17825 } 17826 if (err) 17827 return err; 17828 17829 } else if (opcode == BPF_MOV) { 17830 17831 if (BPF_SRC(insn->code) == BPF_X) { 17832 if (insn->off == BPF_ADDR_SPACE_CAST) { 17833 if (!env->prog->aux->arena) { 17834 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 17835 return -EINVAL; 17836 } 17837 } 17838 17839 /* check src operand */ 17840 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17841 if (err) 17842 return err; 17843 } 17844 17845 /* check dest operand, mark as required later */ 17846 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17847 if (err) 17848 return err; 17849 17850 if (BPF_SRC(insn->code) == BPF_X) { 17851 struct bpf_reg_state *src_reg = regs + insn->src_reg; 17852 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 17853 17854 if (BPF_CLASS(insn->code) == BPF_ALU64) { 17855 if (insn->imm) { 17856 /* off == BPF_ADDR_SPACE_CAST */ 17857 mark_reg_unknown(env, regs, insn->dst_reg); 17858 if (insn->imm == 1) /* cast from as(1) to as(0) */ 17859 dst_reg->type = PTR_TO_ARENA; 17860 } else if (insn->off == 0) { 17861 /* case: R1 = R2 17862 * copy register state to dest reg 17863 */ 17864 assign_scalar_id_before_mov(env, src_reg); 17865 *dst_reg = *src_reg; 17866 } else { 17867 /* case: R1 = (s8, s16 s32)R2 */ 17868 if (is_pointer_value(env, insn->src_reg)) { 17869 verbose(env, 17870 "R%d sign-extension part of pointer\n", 17871 insn->src_reg); 17872 return -EACCES; 17873 } else if (src_reg->type == SCALAR_VALUE) { 17874 bool no_sext; 17875 17876 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 17877 if (no_sext) 17878 assign_scalar_id_before_mov(env, src_reg); 17879 *dst_reg = *src_reg; 17880 if (!no_sext) 17881 clear_scalar_id(dst_reg); 17882 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 17883 } else { 17884 mark_reg_unknown(env, regs, insn->dst_reg); 17885 } 17886 } 17887 } else { 17888 /* R1 = (u32) R2 */ 17889 if (is_pointer_value(env, insn->src_reg)) { 17890 verbose(env, 17891 "R%d partial copy of pointer\n", 17892 insn->src_reg); 17893 return -EACCES; 17894 } else if (src_reg->type == SCALAR_VALUE) { 17895 if (insn->off == 0) { 17896 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 17897 17898 if (is_src_reg_u32) 17899 assign_scalar_id_before_mov(env, src_reg); 17900 *dst_reg = *src_reg; 17901 /* Make sure ID is cleared if src_reg is not in u32 17902 * range otherwise dst_reg min/max could be incorrectly 17903 * propagated into src_reg by sync_linked_regs() 17904 */ 17905 if (!is_src_reg_u32) 17906 clear_scalar_id(dst_reg); 17907 } else { 17908 /* case: W1 = (s8, s16)W2 */ 17909 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 17910 17911 if (no_sext) 17912 assign_scalar_id_before_mov(env, src_reg); 17913 *dst_reg = *src_reg; 17914 if (!no_sext) 17915 clear_scalar_id(dst_reg); 17916 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 17917 } 17918 } else { 17919 mark_reg_unknown(env, regs, 17920 insn->dst_reg); 17921 } 17922 zext_32_to_64(dst_reg); 17923 reg_bounds_sync(dst_reg); 17924 } 17925 } else { 17926 /* case: R = imm 17927 * remember the value we stored into this reg 17928 */ 17929 /* clear any state __mark_reg_known doesn't set */ 17930 mark_reg_unknown(env, regs, insn->dst_reg); 17931 regs[insn->dst_reg].type = SCALAR_VALUE; 17932 if (BPF_CLASS(insn->code) == BPF_ALU64) { 17933 __mark_reg_known(regs + insn->dst_reg, 17934 insn->imm); 17935 } else { 17936 __mark_reg_known(regs + insn->dst_reg, 17937 (u32)insn->imm); 17938 } 17939 } 17940 17941 } else { /* all other ALU ops: and, sub, xor, add, ... */ 17942 17943 if (BPF_SRC(insn->code) == BPF_X) { 17944 /* check src1 operand */ 17945 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17946 if (err) 17947 return err; 17948 } 17949 17950 /* check src2 operand */ 17951 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17952 if (err) 17953 return err; 17954 17955 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 17956 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 17957 verbose(env, "div by zero\n"); 17958 return -EINVAL; 17959 } 17960 17961 if ((opcode == BPF_LSH || opcode == BPF_RSH || 17962 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 17963 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 17964 17965 if (insn->imm < 0 || insn->imm >= size) { 17966 verbose(env, "invalid shift %d\n", insn->imm); 17967 return -EINVAL; 17968 } 17969 } 17970 17971 /* check dest operand */ 17972 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17973 err = err ?: adjust_reg_min_max_vals(env, insn); 17974 if (err) 17975 return err; 17976 } 17977 17978 err = reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 17979 if (err) 17980 return err; 17981 17982 bpf_diag_mod_end(env); 17983 return 0; 17984 } 17985 17986 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 17987 struct bpf_reg_state *dst_reg, 17988 enum bpf_reg_type type, 17989 bool range_right_open) 17990 { 17991 struct bpf_func_state *state; 17992 struct bpf_reg_state *reg; 17993 int new_range; 17994 17995 if (reg_umax(dst_reg) == 0 && range_right_open) 17996 /* This doesn't give us any range */ 17997 return; 17998 17999 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 18000 /* Risk of overflow. For instance, ptr + (1<<63) may be less 18001 * than pkt_end, but that's because it's also less than pkt. 18002 */ 18003 return; 18004 18005 new_range = reg_umax(dst_reg); 18006 if (range_right_open) 18007 new_range++; 18008 18009 /* Examples for register markings: 18010 * 18011 * pkt_data in dst register: 18012 * 18013 * r2 = r3; 18014 * r2 += 8; 18015 * if (r2 > pkt_end) goto <handle exception> 18016 * <access okay> 18017 * 18018 * r2 = r3; 18019 * r2 += 8; 18020 * if (r2 < pkt_end) goto <access okay> 18021 * <handle exception> 18022 * 18023 * Where: 18024 * r2 == dst_reg, pkt_end == src_reg 18025 * r2=pkt(id=n,off=8,r=0) 18026 * r3=pkt(id=n,off=0,r=0) 18027 * 18028 * pkt_data in src register: 18029 * 18030 * r2 = r3; 18031 * r2 += 8; 18032 * if (pkt_end >= r2) goto <access okay> 18033 * <handle exception> 18034 * 18035 * r2 = r3; 18036 * r2 += 8; 18037 * if (pkt_end <= r2) goto <handle exception> 18038 * <access okay> 18039 * 18040 * Where: 18041 * pkt_end == dst_reg, r2 == src_reg 18042 * r2=pkt(id=n,off=8,r=0) 18043 * r3=pkt(id=n,off=0,r=0) 18044 * 18045 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 18046 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 18047 * and [r3, r3 + 8-1) respectively is safe to access depending on 18048 * the check. 18049 */ 18050 18051 /* If our ids match, then we must have the same max_value. And we 18052 * don't care about the other reg's fixed offset, since if it's too big 18053 * the range won't allow anything. 18054 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 18055 */ 18056 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 18057 if (reg->type == type && reg->id == dst_reg->id) 18058 /* keep the maximum range already checked */ 18059 reg->range = max(reg->range, new_range); 18060 })); 18061 } 18062 18063 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 18064 u8 opcode, bool is_jmp32); 18065 /* 18066 * Learn more information about live branches by simulating refinement on both branches. 18067 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 18068 * that branch is dead. 18069 */ 18070 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 18071 { 18072 /* Fallthrough (FALSE) branch */ 18073 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32); 18074 reg_bounds_sync(&env->false_reg1); 18075 reg_bounds_sync(&env->false_reg2); 18076 /* 18077 * If there is a range bounds violation in *any* of the abstract values in either 18078 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 18079 * TRUE branch will be taken. 18080 */ 18081 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 18082 return 1; 18083 18084 /* Jump (TRUE) branch */ 18085 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 18086 reg_bounds_sync(&env->true_reg1); 18087 reg_bounds_sync(&env->true_reg2); 18088 /* 18089 * If there is a range bounds violation in *any* of the abstract values in either 18090 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 18091 * Only FALSE branch will be taken. 18092 */ 18093 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 18094 return 0; 18095 18096 /* Both branches are possible, we can't determine which one will be taken. */ 18097 return -1; 18098 } 18099 18100 /* 18101 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 18102 */ 18103 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 18104 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 18105 { 18106 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 18107 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 18108 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 18109 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 18110 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 18111 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 18112 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 18113 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 18114 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 18115 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 18116 18117 if (reg1 == reg2) { 18118 switch (opcode) { 18119 case BPF_JGE: 18120 case BPF_JLE: 18121 case BPF_JSGE: 18122 case BPF_JSLE: 18123 case BPF_JEQ: 18124 return 1; 18125 case BPF_JGT: 18126 case BPF_JLT: 18127 case BPF_JSGT: 18128 case BPF_JSLT: 18129 case BPF_JNE: 18130 return 0; 18131 case BPF_JSET: 18132 if (tnum_is_const(t1)) 18133 return t1.value != 0; 18134 else 18135 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 18136 default: 18137 return -1; 18138 } 18139 } 18140 18141 switch (opcode) { 18142 case BPF_JEQ: 18143 /* constants, umin/umax and smin/smax checks would be 18144 * redundant in this case because they all should match 18145 */ 18146 if (tnum_is_const(t1) && tnum_is_const(t2)) 18147 return t1.value == t2.value; 18148 if (!tnum_overlap(t1, t2)) 18149 return 0; 18150 /* non-overlapping ranges */ 18151 if (umin1 > umax2 || umax1 < umin2) 18152 return 0; 18153 if (smin1 > smax2 || smax1 < smin2) 18154 return 0; 18155 if (!is_jmp32) { 18156 /* if 64-bit ranges are inconclusive, see if we can 18157 * utilize 32-bit subrange knowledge to eliminate 18158 * branches that can't be taken a priori 18159 */ 18160 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 18161 reg_u32_max(reg1) < reg_u32_min(reg2)) 18162 return 0; 18163 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 18164 reg_s32_max(reg1) < reg_s32_min(reg2)) 18165 return 0; 18166 } 18167 break; 18168 case BPF_JNE: 18169 /* constants, umin/umax and smin/smax checks would be 18170 * redundant in this case because they all should match 18171 */ 18172 if (tnum_is_const(t1) && tnum_is_const(t2)) 18173 return t1.value != t2.value; 18174 if (!tnum_overlap(t1, t2)) 18175 return 1; 18176 /* non-overlapping ranges */ 18177 if (umin1 > umax2 || umax1 < umin2) 18178 return 1; 18179 if (smin1 > smax2 || smax1 < smin2) 18180 return 1; 18181 if (!is_jmp32) { 18182 /* if 64-bit ranges are inconclusive, see if we can 18183 * utilize 32-bit subrange knowledge to eliminate 18184 * branches that can't be taken a priori 18185 */ 18186 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 18187 reg_u32_max(reg1) < reg_u32_min(reg2)) 18188 return 1; 18189 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 18190 reg_s32_max(reg1) < reg_s32_min(reg2)) 18191 return 1; 18192 } 18193 break; 18194 case BPF_JSET: 18195 if (!is_reg_const(reg2, is_jmp32)) { 18196 swap(reg1, reg2); 18197 swap(t1, t2); 18198 } 18199 if (!is_reg_const(reg2, is_jmp32)) 18200 return -1; 18201 if ((~t1.mask & t1.value) & t2.value) 18202 return 1; 18203 if (!((t1.mask | t1.value) & t2.value)) 18204 return 0; 18205 break; 18206 case BPF_JGT: 18207 if (umin1 > umax2) 18208 return 1; 18209 else if (umax1 <= umin2) 18210 return 0; 18211 break; 18212 case BPF_JSGT: 18213 if (smin1 > smax2) 18214 return 1; 18215 else if (smax1 <= smin2) 18216 return 0; 18217 break; 18218 case BPF_JLT: 18219 if (umax1 < umin2) 18220 return 1; 18221 else if (umin1 >= umax2) 18222 return 0; 18223 break; 18224 case BPF_JSLT: 18225 if (smax1 < smin2) 18226 return 1; 18227 else if (smin1 >= smax2) 18228 return 0; 18229 break; 18230 case BPF_JGE: 18231 if (umin1 >= umax2) 18232 return 1; 18233 else if (umax1 < umin2) 18234 return 0; 18235 break; 18236 case BPF_JSGE: 18237 if (smin1 >= smax2) 18238 return 1; 18239 else if (smax1 < smin2) 18240 return 0; 18241 break; 18242 case BPF_JLE: 18243 if (umax1 <= umin2) 18244 return 1; 18245 else if (umin1 > umax2) 18246 return 0; 18247 break; 18248 case BPF_JSLE: 18249 if (smax1 <= smin2) 18250 return 1; 18251 else if (smin1 > smax2) 18252 return 0; 18253 break; 18254 } 18255 18256 return simulate_both_branches_taken(env, opcode, is_jmp32); 18257 } 18258 18259 int bpf_flip_opcode(u32 opcode) 18260 { 18261 /* How can we transform "a <op> b" into "b <op> a"? */ 18262 static const u8 opcode_flip[16] = { 18263 /* these stay the same */ 18264 [BPF_JEQ >> 4] = BPF_JEQ, 18265 [BPF_JNE >> 4] = BPF_JNE, 18266 [BPF_JSET >> 4] = BPF_JSET, 18267 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 18268 [BPF_JGE >> 4] = BPF_JLE, 18269 [BPF_JGT >> 4] = BPF_JLT, 18270 [BPF_JLE >> 4] = BPF_JGE, 18271 [BPF_JLT >> 4] = BPF_JGT, 18272 [BPF_JSGE >> 4] = BPF_JSLE, 18273 [BPF_JSGT >> 4] = BPF_JSLT, 18274 [BPF_JSLE >> 4] = BPF_JSGE, 18275 [BPF_JSLT >> 4] = BPF_JSGT 18276 }; 18277 return opcode_flip[opcode >> 4]; 18278 } 18279 18280 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 18281 struct bpf_reg_state *src_reg, 18282 u8 opcode) 18283 { 18284 struct bpf_reg_state *pkt; 18285 18286 if (src_reg->type == PTR_TO_PACKET_END) { 18287 pkt = dst_reg; 18288 } else if (dst_reg->type == PTR_TO_PACKET_END) { 18289 pkt = src_reg; 18290 opcode = bpf_flip_opcode(opcode); 18291 } else { 18292 return -1; 18293 } 18294 18295 if (pkt->range >= 0) 18296 return -1; 18297 18298 switch (opcode) { 18299 case BPF_JLE: 18300 /* pkt <= pkt_end */ 18301 fallthrough; 18302 case BPF_JGT: 18303 /* pkt > pkt_end */ 18304 if (pkt->range == BEYOND_PKT_END) 18305 /* pkt has at last one extra byte beyond pkt_end */ 18306 return opcode == BPF_JGT; 18307 break; 18308 case BPF_JLT: 18309 /* pkt < pkt_end */ 18310 fallthrough; 18311 case BPF_JGE: 18312 /* pkt >= pkt_end */ 18313 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 18314 return opcode == BPF_JGE; 18315 break; 18316 } 18317 return -1; 18318 } 18319 18320 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 18321 * and return: 18322 * 1 - branch will be taken and "goto target" will be executed 18323 * 0 - branch will not be taken and fall-through to next insn 18324 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 18325 * range [0,10] 18326 */ 18327 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 18328 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 18329 { 18330 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 18331 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 18332 18333 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 18334 u64 val; 18335 18336 /* 18337 * The low 32 bits of a valid pointer may well be zero, hence 18338 * nothing below applies to a 32-bit comparison. 18339 */ 18340 if (is_jmp32) 18341 return -1; 18342 18343 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 18344 if (!is_reg_const(reg2, is_jmp32)) { 18345 opcode = bpf_flip_opcode(opcode); 18346 swap(reg1, reg2); 18347 } 18348 /* and ensure that reg2 is a constant */ 18349 if (!is_reg_const(reg2, is_jmp32)) 18350 return -1; 18351 18352 if (!reg_not_null(env, reg1)) 18353 return -1; 18354 18355 /* If pointer is valid tests against zero will fail so we can 18356 * use this to direct branch taken. 18357 */ 18358 val = reg_const_value(reg2, is_jmp32); 18359 if (val != 0) 18360 return -1; 18361 18362 switch (opcode) { 18363 case BPF_JEQ: 18364 return 0; 18365 case BPF_JNE: 18366 return 1; 18367 default: 18368 return -1; 18369 } 18370 } 18371 18372 /* now deal with two scalars, but not necessarily constants */ 18373 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 18374 } 18375 18376 /* Opcode that corresponds to a *false* branch condition. 18377 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 18378 */ 18379 u8 bpf_rev_opcode(u8 opcode) 18380 { 18381 switch (opcode) { 18382 case BPF_JEQ: return BPF_JNE; 18383 case BPF_JNE: return BPF_JEQ; 18384 /* JSET doesn't have it's reverse opcode in BPF, so add 18385 * BPF_X flag to denote the reverse of that operation 18386 */ 18387 case BPF_JSET: return BPF_JSET | BPF_X; 18388 case BPF_JSET | BPF_X: return BPF_JSET; 18389 case BPF_JGE: return BPF_JLT; 18390 case BPF_JGT: return BPF_JLE; 18391 case BPF_JLE: return BPF_JGT; 18392 case BPF_JLT: return BPF_JGE; 18393 case BPF_JSGE: return BPF_JSLT; 18394 case BPF_JSGT: return BPF_JSLE; 18395 case BPF_JSLE: return BPF_JSGT; 18396 case BPF_JSLT: return BPF_JSGE; 18397 default: return 0; 18398 } 18399 } 18400 18401 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 18402 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 18403 u8 opcode, bool is_jmp32) 18404 { 18405 struct tnum t; 18406 u64 val; 18407 18408 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 18409 switch (opcode) { 18410 case BPF_JGE: 18411 case BPF_JGT: 18412 case BPF_JSGE: 18413 case BPF_JSGT: 18414 opcode = bpf_flip_opcode(opcode); 18415 swap(reg1, reg2); 18416 break; 18417 default: 18418 break; 18419 } 18420 18421 switch (opcode) { 18422 case BPF_JEQ: 18423 if (is_jmp32) { 18424 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 18425 reg2->r32 = reg1->r32; 18426 18427 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 18428 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 18429 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 18430 } else { 18431 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 18432 reg2->r64 = reg1->r64; 18433 18434 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 18435 reg2->var_off = reg1->var_off; 18436 } 18437 break; 18438 case BPF_JNE: 18439 if (!is_reg_const(reg2, is_jmp32)) 18440 swap(reg1, reg2); 18441 if (!is_reg_const(reg2, is_jmp32)) 18442 break; 18443 18444 /* try to recompute the bound of reg1 if reg2 is a const and 18445 * is exactly the edge of reg1. 18446 */ 18447 val = reg_const_value(reg2, is_jmp32); 18448 if (is_jmp32) { 18449 /* Complement of the range [val, val] as cnum32. */ 18450 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 18451 } else { 18452 /* Complement of the range [val, val] as cnum64. */ 18453 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 18454 } 18455 break; 18456 case BPF_JSET: 18457 if (!is_reg_const(reg2, is_jmp32)) 18458 swap(reg1, reg2); 18459 if (!is_reg_const(reg2, is_jmp32)) 18460 break; 18461 val = reg_const_value(reg2, is_jmp32); 18462 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 18463 * requires single bit to learn something useful. E.g., if we 18464 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 18465 * are actually set? We can learn something definite only if 18466 * it's a single-bit value to begin with. 18467 * 18468 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 18469 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 18470 * bit 1 is set, which we can readily use in adjustments. 18471 */ 18472 if (hweight64(val) != 1) 18473 break; 18474 if (is_jmp32) { 18475 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 18476 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 18477 } else { 18478 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 18479 } 18480 break; 18481 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see bpf_rev_opcode() */ 18482 if (!is_reg_const(reg2, is_jmp32)) 18483 swap(reg1, reg2); 18484 if (!is_reg_const(reg2, is_jmp32)) 18485 break; 18486 val = reg_const_value(reg2, is_jmp32); 18487 /* Forget the ranges before narrowing tnums, to avoid invariant 18488 * violations if we're on a dead branch. 18489 */ 18490 __mark_reg_unbounded(reg1); 18491 reg_step_reset(reg1); 18492 if (is_jmp32) { 18493 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 18494 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 18495 } else { 18496 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 18497 } 18498 break; 18499 case BPF_JLE: 18500 if (is_jmp32) { 18501 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 18502 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 18503 } else { 18504 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 18505 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 18506 } 18507 break; 18508 case BPF_JLT: 18509 if (is_jmp32) { 18510 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 18511 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 18512 } else { 18513 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 18514 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 18515 } 18516 break; 18517 case BPF_JSLE: 18518 if (is_jmp32) { 18519 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 18520 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 18521 } else { 18522 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 18523 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 18524 } 18525 break; 18526 case BPF_JSLT: 18527 if (is_jmp32) { 18528 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 18529 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 18530 } else { 18531 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 18532 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 18533 } 18534 break; 18535 default: 18536 return; 18537 } 18538 } 18539 18540 /* Check for invariant violations on the registers for both branches of a condition */ 18541 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 18542 { 18543 int err; 18544 18545 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 18546 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 18547 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 18548 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 18549 return err; 18550 } 18551 18552 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 18553 struct bpf_reg_state *reg, u32 id, 18554 bool is_null) 18555 { 18556 if (type_may_be_null(reg->type) && reg->id == id && 18557 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 18558 /* Old offset should have been known-zero, because we don't 18559 * allow pointer arithmetic on pointers that might be NULL. 18560 * If we see this happening, don't convert the register. 18561 * 18562 * But in some cases, some helpers that return local kptrs 18563 * advance offset for the returned pointer. In those cases, 18564 * it is fine to expect to see reg->var_off. 18565 */ 18566 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 18567 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 18568 return; 18569 if (is_null) { 18570 /* We don't need id from this point 18571 * onwards anymore, thus we should better reset it, 18572 * so that state pruning has chances to take effect. 18573 */ 18574 __mark_reg_known_zero(reg); 18575 reg->type = SCALAR_VALUE; 18576 18577 return; 18578 } 18579 18580 mark_ptr_not_null_reg(reg); 18581 18582 /* 18583 * reg->id is preserved for object relationship tracking 18584 * and spin_lock lock state tracking 18585 */ 18586 } 18587 } 18588 18589 /* The logic is similar to find_good_pkt_pointers(), both could eventually 18590 * be folded together at some point. 18591 */ 18592 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 18593 bool is_null) 18594 { 18595 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 18596 struct bpf_reg_state *regs = state->regs, *reg; 18597 u32 id = regs[regno].id; 18598 18599 if (is_null && find_reference_state(vstate, id)) 18600 /* regs[regno] is in the " == NULL" branch. 18601 * No one could have freed the reference state before 18602 * doing the NULL check. 18603 */ 18604 WARN_ON_ONCE(__release_reference_nomark(vstate, id)); 18605 18606 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 18607 mark_ptr_or_null_reg(state, reg, id, is_null); 18608 })); 18609 } 18610 18611 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 18612 struct bpf_reg_state *dst_reg, 18613 struct bpf_reg_state *src_reg, 18614 struct bpf_verifier_state *this_branch, 18615 struct bpf_verifier_state *other_branch) 18616 { 18617 if (BPF_SRC(insn->code) != BPF_X) 18618 return false; 18619 18620 /* Pointers are always 64-bit. */ 18621 if (BPF_CLASS(insn->code) == BPF_JMP32) 18622 return false; 18623 18624 switch (BPF_OP(insn->code)) { 18625 case BPF_JGT: 18626 if ((dst_reg->type == PTR_TO_PACKET && 18627 src_reg->type == PTR_TO_PACKET_END) || 18628 (dst_reg->type == PTR_TO_PACKET_META && 18629 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 18630 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 18631 find_good_pkt_pointers(this_branch, dst_reg, 18632 dst_reg->type, false); 18633 mark_pkt_end(other_branch, insn->dst_reg, true); 18634 } else if ((dst_reg->type == PTR_TO_PACKET_END && 18635 src_reg->type == PTR_TO_PACKET) || 18636 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 18637 src_reg->type == PTR_TO_PACKET_META)) { 18638 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 18639 find_good_pkt_pointers(other_branch, src_reg, 18640 src_reg->type, true); 18641 mark_pkt_end(this_branch, insn->src_reg, false); 18642 } else { 18643 return false; 18644 } 18645 break; 18646 case BPF_JLT: 18647 if ((dst_reg->type == PTR_TO_PACKET && 18648 src_reg->type == PTR_TO_PACKET_END) || 18649 (dst_reg->type == PTR_TO_PACKET_META && 18650 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 18651 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 18652 find_good_pkt_pointers(other_branch, dst_reg, 18653 dst_reg->type, true); 18654 mark_pkt_end(this_branch, insn->dst_reg, false); 18655 } else if ((dst_reg->type == PTR_TO_PACKET_END && 18656 src_reg->type == PTR_TO_PACKET) || 18657 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 18658 src_reg->type == PTR_TO_PACKET_META)) { 18659 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 18660 find_good_pkt_pointers(this_branch, src_reg, 18661 src_reg->type, false); 18662 mark_pkt_end(other_branch, insn->src_reg, true); 18663 } else { 18664 return false; 18665 } 18666 break; 18667 case BPF_JGE: 18668 if ((dst_reg->type == PTR_TO_PACKET && 18669 src_reg->type == PTR_TO_PACKET_END) || 18670 (dst_reg->type == PTR_TO_PACKET_META && 18671 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 18672 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 18673 find_good_pkt_pointers(this_branch, dst_reg, 18674 dst_reg->type, true); 18675 mark_pkt_end(other_branch, insn->dst_reg, false); 18676 } else if ((dst_reg->type == PTR_TO_PACKET_END && 18677 src_reg->type == PTR_TO_PACKET) || 18678 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 18679 src_reg->type == PTR_TO_PACKET_META)) { 18680 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 18681 find_good_pkt_pointers(other_branch, src_reg, 18682 src_reg->type, false); 18683 mark_pkt_end(this_branch, insn->src_reg, true); 18684 } else { 18685 return false; 18686 } 18687 break; 18688 case BPF_JLE: 18689 if ((dst_reg->type == PTR_TO_PACKET && 18690 src_reg->type == PTR_TO_PACKET_END) || 18691 (dst_reg->type == PTR_TO_PACKET_META && 18692 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 18693 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 18694 find_good_pkt_pointers(other_branch, dst_reg, 18695 dst_reg->type, false); 18696 mark_pkt_end(this_branch, insn->dst_reg, true); 18697 } else if ((dst_reg->type == PTR_TO_PACKET_END && 18698 src_reg->type == PTR_TO_PACKET) || 18699 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 18700 src_reg->type == PTR_TO_PACKET_META)) { 18701 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 18702 find_good_pkt_pointers(this_branch, src_reg, 18703 src_reg->type, true); 18704 mark_pkt_end(other_branch, insn->src_reg, false); 18705 } else { 18706 return false; 18707 } 18708 break; 18709 default: 18710 return false; 18711 } 18712 18713 return true; 18714 } 18715 18716 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 18717 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 18718 { 18719 struct linked_reg *e; 18720 18721 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 18722 return; 18723 18724 e = linked_regs_push(reg_set); 18725 if (e) { 18726 e->frameno = frameno; 18727 e->is_reg = is_reg; 18728 e->regno = spi_or_reg; 18729 } else { 18730 clear_scalar_id(reg); 18731 } 18732 } 18733 18734 /* For all R being scalar registers or spilled scalar registers 18735 * in verifier state, save R in linked_regs if R->id == id. 18736 * If there are too many Rs sharing same id, reset id for leftover Rs. 18737 */ 18738 static void collect_linked_regs(struct bpf_verifier_env *env, 18739 struct bpf_verifier_state *vstate, 18740 u32 id, 18741 struct linked_regs *linked_regs) 18742 { 18743 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18744 struct bpf_func_state *func; 18745 struct bpf_reg_state *reg; 18746 u16 live_regs; 18747 int i, j; 18748 18749 id = id & ~BPF_ADD_CONST; 18750 for (i = vstate->curframe; i >= 0; i--) { 18751 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 18752 func = vstate->frame[i]; 18753 for (j = 0; j < BPF_REG_FP; j++) { 18754 if (!(live_regs & BIT(j))) 18755 continue; 18756 reg = &func->regs[j]; 18757 __collect_linked_regs(linked_regs, reg, id, i, j, true); 18758 } 18759 for (j = 0; j < bpf_stack_nr_slots(func); j++) { 18760 struct bpf_stack_state *ss = bpf_stack_slot(func, j); 18761 18762 if (!bpf_is_spilled_reg(ss)) 18763 continue; 18764 reg = &ss->spilled_ptr; 18765 __collect_linked_regs(linked_regs, reg, id, i, j, false); 18766 } 18767 } 18768 } 18769 18770 /* For all R in linked_regs, copy known_reg range into R 18771 * if R->id == known_reg->id. 18772 */ 18773 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 18774 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 18775 { 18776 struct bpf_reg_state fake_reg; 18777 struct bpf_reg_state *reg; 18778 struct linked_reg *e; 18779 int i; 18780 18781 for (i = 0; i < linked_regs->cnt; ++i) { 18782 e = &linked_regs->entries[i]; 18783 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 18784 : &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr; 18785 if (reg->type != SCALAR_VALUE || reg == known_reg) 18786 continue; 18787 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 18788 continue; 18789 /* 18790 * Skip mixed 32/64-bit links: the delta relationship doesn't 18791 * hold across different ALU widths. 18792 */ 18793 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 18794 continue; 18795 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 18796 reg->delta == known_reg->delta) { 18797 *reg = *known_reg; 18798 } else { 18799 s32 saved_off = reg->delta; 18800 u32 saved_id = reg->id; 18801 18802 fake_reg.type = SCALAR_VALUE; 18803 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 18804 18805 /* reg = known_reg; reg += delta */ 18806 *reg = *known_reg; 18807 /* 18808 * Must preserve off and id, otherwise another sync_linked_regs() 18809 * will be incorrect. 18810 */ 18811 reg->delta = saved_off; 18812 reg->id = saved_id; 18813 18814 scalar_step_add(reg, reg, &fake_reg); 18815 scalar32_min_max_add(reg, &fake_reg); 18816 scalar_min_max_add(reg, &fake_reg); 18817 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 18818 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 18819 zext_32_to_64(reg); 18820 reg_bounds_sync(reg); 18821 } 18822 if (e->is_reg) 18823 mark_reg_scratched(env, e->regno); 18824 else 18825 mark_stack_slot_scratched(env, e->spi); 18826 } 18827 } 18828 18829 static int check_cond_jmp_op(struct bpf_verifier_env *env, 18830 struct bpf_insn *insn, int *insn_idx) 18831 { 18832 struct bpf_verifier_state *this_branch = env->cur_state; 18833 struct bpf_verifier_state *other_branch; 18834 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 18835 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 18836 struct bpf_reg_state *eq_branch_regs; 18837 struct linked_regs linked_regs = {}; 18838 u8 opcode = BPF_OP(insn->code); 18839 int insn_flags = 0; 18840 bool is_jmp32; 18841 int pred = -1; 18842 int err; 18843 18844 /* Only conditional jumps are expected to reach here. */ 18845 if (opcode == BPF_JA || opcode > BPF_JCOND) { 18846 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 18847 return -EINVAL; 18848 } 18849 18850 if (bpf_is_unwind_goto(insn)) { 18851 if (!env->cur_state->unwound) 18852 return 0; 18853 env->cur_state->unwound = false; 18854 /* 18855 * unwind_exit changed its return address, so the return is 18856 * mispredicted and what follows unwind_goto runs speculatively. 18857 */ 18858 if (!env->bypass_spec_v1) { 18859 err = sanitize_speculative_path(env, NULL, *insn_idx + 1, *insn_idx); 18860 if (err) 18861 return err; 18862 } 18863 *insn_idx += insn->off; 18864 return 0; 18865 } 18866 18867 if (opcode == BPF_JCOND) { 18868 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 18869 int idx = *insn_idx; 18870 18871 prev_st = find_prev_entry(env, cur_st->parent, idx); 18872 18873 /* branch out 'fallthrough' insn as a new state to explore */ 18874 queued_st = push_stack(env, idx + 1, idx, false); 18875 if (IS_ERR(queued_st)) 18876 return PTR_ERR(queued_st); 18877 18878 queued_st->may_goto_depth++; 18879 if (prev_st) 18880 widen_imprecise_scalars(env, prev_st, queued_st); 18881 *insn_idx += insn->off; 18882 return 0; 18883 } 18884 18885 /* check src2 operand */ 18886 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18887 if (err) 18888 return err; 18889 18890 dst_reg = ®s[insn->dst_reg]; 18891 if (BPF_SRC(insn->code) == BPF_X) { 18892 /* check src1 operand */ 18893 err = check_reg_arg(env, insn->src_reg, SRC_OP); 18894 if (err) 18895 return err; 18896 18897 src_reg = ®s[insn->src_reg]; 18898 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 18899 is_pointer_value(env, insn->src_reg)) { 18900 verbose(env, "R%d pointer comparison prohibited\n", 18901 insn->src_reg); 18902 return -EACCES; 18903 } 18904 18905 if (src_reg->type == PTR_TO_STACK) 18906 insn_flags |= INSN_F_SRC_REG_STACK; 18907 if (dst_reg->type == PTR_TO_STACK) 18908 insn_flags |= INSN_F_DST_REG_STACK; 18909 } else { 18910 src_reg = &env->fake_reg[0]; 18911 memset(src_reg, 0, sizeof(*src_reg)); 18912 src_reg->type = SCALAR_VALUE; 18913 __mark_reg_known(src_reg, insn->imm); 18914 18915 if (dst_reg->type == PTR_TO_STACK) 18916 insn_flags |= INSN_F_DST_REG_STACK; 18917 } 18918 18919 if (insn_flags) { 18920 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, NULL, 0); 18921 if (err) 18922 return err; 18923 } 18924 18925 /* 18926 * Collect the linked registers before env->{true,false}_reg{1,2} setup, 18927 * otherwise ids dropped by collect_linked_regs() would be resurrected 18928 * when env->{true,false}_reg{1,2} are copied back. 18929 */ 18930 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 18931 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 18932 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 18933 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 18934 18935 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 18936 env->false_reg1 = *dst_reg; 18937 env->false_reg2 = *src_reg; 18938 env->true_reg1 = *dst_reg; 18939 env->true_reg2 = *src_reg; 18940 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 18941 if (pred >= 0) { 18942 /* If we get here with a dst_reg pointer type it is because 18943 * above is_branch_taken() special cased the 0 comparison. 18944 */ 18945 if (!__is_pointer_value(false, dst_reg)) 18946 err = mark_chain_precision(env, insn->dst_reg); 18947 if (BPF_SRC(insn->code) == BPF_X && !err && 18948 !__is_pointer_value(false, src_reg)) 18949 err = mark_chain_precision(env, insn->src_reg); 18950 if (err) 18951 return err; 18952 } 18953 18954 if (pred == 1) { 18955 /* Only follow the goto, ignore fall-through. If needed, push 18956 * the fall-through branch for simulation under speculative 18957 * execution. 18958 */ 18959 if (!env->bypass_spec_v1) { 18960 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 18961 if (err < 0) 18962 return err; 18963 } 18964 if (env->log.level & BPF_LOG_LEVEL) 18965 print_insn_state(env, this_branch, this_branch->curframe); 18966 *insn_idx += insn->off; 18967 return 0; 18968 } else if (pred == 0) { 18969 /* Only follow the fall-through branch, since that's where the 18970 * program will go. If needed, push the goto branch for 18971 * simulation under speculative execution. 18972 */ 18973 if (!env->bypass_spec_v1) { 18974 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 18975 *insn_idx); 18976 if (err < 0) 18977 return err; 18978 } 18979 if (env->log.level & BPF_LOG_LEVEL) 18980 print_insn_state(env, this_branch, this_branch->curframe); 18981 return 0; 18982 } 18983 18984 /* Push scalar registers sharing same ID to jump history, 18985 * do this before creating 'other_branch', so that both 18986 * 'this_branch' and 'other_branch' share this history 18987 * if parent state is created. 18988 */ 18989 if (linked_regs.cnt > 1) { 18990 u16 packed[LINKED_REGS_MAX]; 18991 18992 linked_regs_pack(&linked_regs, packed); 18993 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, packed, linked_regs.cnt); 18994 if (err) 18995 return err; 18996 } 18997 18998 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 18999 if (IS_ERR(other_branch)) 19000 return PTR_ERR(other_branch); 19001 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 19002 19003 err = regs_bounds_sanity_check_branches(env); 19004 if (err) 19005 return err; 19006 19007 *dst_reg = env->false_reg1; 19008 *src_reg = env->false_reg2; 19009 other_branch_regs[insn->dst_reg] = env->true_reg1; 19010 if (BPF_SRC(insn->code) == BPF_X) 19011 other_branch_regs[insn->src_reg] = env->true_reg2; 19012 19013 if (BPF_SRC(insn->code) == BPF_X && 19014 src_reg->type == SCALAR_VALUE && src_reg->id && 19015 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 19016 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 19017 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 19018 &linked_regs); 19019 } 19020 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 19021 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 19022 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 19023 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 19024 &linked_regs); 19025 } 19026 19027 /* if one pointer register is compared to another pointer 19028 * register check if PTR_MAYBE_NULL could be lifted. 19029 * E.g. register A - maybe null 19030 * register B - not null 19031 * for JNE A, B, ... - A is not null in the false branch; 19032 * for JEQ A, B, ... - A is not null in the true branch. 19033 * 19034 * Since PTR_TO_BTF_ID points to a kernel struct that does 19035 * not need to be null checked by the BPF program, i.e., 19036 * could be null even without PTR_MAYBE_NULL marking, so 19037 * only propagate nullness when neither reg is that type. 19038 */ 19039 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 19040 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 19041 base_type(src_reg->type) != PTR_TO_BTF_ID && 19042 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 19043 eq_branch_regs = NULL; 19044 switch (opcode) { 19045 case BPF_JEQ: 19046 eq_branch_regs = other_branch_regs; 19047 break; 19048 case BPF_JNE: 19049 eq_branch_regs = regs; 19050 break; 19051 default: 19052 /* do nothing */ 19053 break; 19054 } 19055 if (eq_branch_regs) { 19056 /* src == dst && dst != NULL => src != NULL */ 19057 if (reg_not_null(env, dst_reg) && type_may_be_null(src_reg->type)) 19058 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 19059 /* src == dst && src != NULL => dst != NULL */ 19060 if (reg_not_null(env, src_reg) && type_may_be_null(dst_reg->type)) 19061 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 19062 } 19063 } 19064 19065 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 19066 * Also does the same detection for a register whose the value is 19067 * known to be 0. 19068 * NOTE: these optimizations below are related with pointer comparison 19069 * which will never be JMP32. 19070 */ 19071 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 19072 type_may_be_null(dst_reg->type) && 19073 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 19074 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 19075 /* 19076 * For BPF_X the zero is a property of this execution path, 19077 * hence src_reg has to be precise. 19078 */ 19079 if (BPF_SRC(insn->code) == BPF_X) { 19080 err = mark_chain_precision(env, insn->src_reg); 19081 if (err) 19082 return err; 19083 } 19084 /* Mark all identical registers in each branch as either 19085 * safe or unknown depending R == 0 or R != 0 conditional. 19086 */ 19087 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 19088 opcode == BPF_JNE); 19089 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 19090 opcode == BPF_JEQ); 19091 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 19092 this_branch, other_branch) && 19093 is_pointer_value(env, insn->dst_reg)) { 19094 verbose(env, "R%d pointer comparison prohibited\n", 19095 insn->dst_reg); 19096 return -EACCES; 19097 } 19098 if (env->log.level & BPF_LOG_LEVEL) 19099 print_insn_state(env, this_branch, this_branch->curframe); 19100 return 0; 19101 } 19102 19103 /* verify BPF_LD_IMM64 instruction */ 19104 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 19105 { 19106 struct bpf_insn_aux_data *aux = cur_aux(env); 19107 struct bpf_reg_state *regs = cur_regs(env); 19108 struct bpf_reg_state *dst_reg; 19109 struct bpf_map *map; 19110 int err; 19111 19112 if (BPF_SIZE(insn->code) != BPF_DW) { 19113 verbose(env, "invalid BPF_LD_IMM insn\n"); 19114 return -EINVAL; 19115 } 19116 19117 err = check_reg_arg(env, insn->dst_reg, DST_OP); 19118 if (err) 19119 return err; 19120 19121 dst_reg = ®s[insn->dst_reg]; 19122 bpf_diag_mod_begin(env, dst_reg, NULL, BPF_DIAG_MOD_WRITE); 19123 if (insn->src_reg == 0) { 19124 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 19125 19126 dst_reg->type = SCALAR_VALUE; 19127 __mark_reg_known(®s[insn->dst_reg], imm); 19128 bpf_diag_mod_end(env); 19129 return 0; 19130 } 19131 19132 /* All special src_reg cases are listed below. From this point onwards 19133 * we either succeed and assign a corresponding dst_reg->type after 19134 * zeroing the offset, or fail and reject the program. 19135 */ 19136 mark_reg_known_zero(env, regs, insn->dst_reg); 19137 19138 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 19139 dst_reg->type = aux->btf_var.reg_type; 19140 switch (base_type(dst_reg->type)) { 19141 case PTR_TO_MEM: 19142 dst_reg->mem_size = aux->btf_var.mem_size; 19143 break; 19144 case PTR_TO_BTF_ID: 19145 dst_reg->btf = aux->btf_var.btf; 19146 dst_reg->btf_id = aux->btf_var.btf_id; 19147 break; 19148 default: 19149 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 19150 return -EFAULT; 19151 } 19152 bpf_diag_mod_end(env); 19153 return 0; 19154 } 19155 19156 if (insn->src_reg == BPF_PSEUDO_FUNC) { 19157 struct bpf_prog_aux *aux = env->prog->aux; 19158 u32 subprogno = bpf_find_subprog(env, 19159 env->insn_idx + insn->imm + 1); 19160 19161 if (!aux->func_info) { 19162 verbose(env, "missing btf func_info\n"); 19163 return -EINVAL; 19164 } 19165 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 19166 verbose(env, "callback function not static\n"); 19167 return -EINVAL; 19168 } 19169 /* 19170 * When env->subprog_cnt == 1 this instruction won't be rewritten 19171 * to hold a real function address. Assume that no usable program 19172 * combines e.g. main and timer callback and just reject here. 19173 */ 19174 if (subprogno == 0) { 19175 verbose(env, "callback function cannot be the main program\n"); 19176 return -EINVAL; 19177 } 19178 19179 dst_reg->type = PTR_TO_FUNC; 19180 dst_reg->subprogno = subprogno; 19181 bpf_diag_mod_end(env); 19182 return 0; 19183 } 19184 19185 map = env->used_maps[aux->map_index]; 19186 19187 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 19188 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 19189 if (map->map_type == BPF_MAP_TYPE_ARENA) { 19190 __mark_reg_unknown(env, dst_reg); 19191 dst_reg->map_ptr = map; 19192 bpf_diag_mod_end(env); 19193 return 0; 19194 } 19195 __mark_reg_known(dst_reg, aux->map_off); 19196 dst_reg->type = PTR_TO_MAP_VALUE; 19197 dst_reg->map_ptr = map; 19198 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 19199 map->max_entries != 1); 19200 /* We want reg->id to be same (0) as map_value is not distinct */ 19201 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 19202 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 19203 dst_reg->type = CONST_PTR_TO_MAP; 19204 dst_reg->map_ptr = map; 19205 } else { 19206 verifier_bug(env, "unexpected src reg value for ldimm64"); 19207 return -EFAULT; 19208 } 19209 19210 bpf_diag_mod_end(env); 19211 return 0; 19212 } 19213 19214 static bool may_access_skb(enum bpf_prog_type type) 19215 { 19216 switch (type) { 19217 case BPF_PROG_TYPE_SOCKET_FILTER: 19218 case BPF_PROG_TYPE_SCHED_CLS: 19219 case BPF_PROG_TYPE_SCHED_ACT: 19220 return true; 19221 default: 19222 return false; 19223 } 19224 } 19225 19226 /* verify safety of LD_ABS|LD_IND instructions: 19227 * - they can only appear in the programs where ctx == skb 19228 * - since they are wrappers of function calls, they scratch R1-R5 registers, 19229 * preserve R6-R9, and store return value into R0 19230 * 19231 * Implicit input: 19232 * ctx == skb == R6 == CTX 19233 * 19234 * Explicit input: 19235 * SRC == any register 19236 * IMM == 32-bit immediate 19237 * 19238 * Output: 19239 * R0 - 8/16/32-bit skb data converted to cpu endianness 19240 */ 19241 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 19242 { 19243 struct bpf_verifier_state *state = env->cur_state; 19244 struct bpf_reg_state *regs = cur_regs(env); 19245 static const int ctx_reg = BPF_REG_6; 19246 u8 mode = BPF_MODE(insn->code); 19247 int i, err; 19248 19249 if (!may_access_skb(resolve_prog_type(env->prog))) { 19250 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 19251 return -EINVAL; 19252 } 19253 19254 for (i = state->curframe; i; i--) { 19255 if (state->frame[i]->in_callback_fn) { 19256 verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n"); 19257 return -EINVAL; 19258 } 19259 } 19260 19261 if (!env->ops->gen_ld_abs) { 19262 verifier_bug(env, "gen_ld_abs is null"); 19263 return -EFAULT; 19264 } 19265 19266 /* check whether implicit source operand (register R6) is readable */ 19267 err = check_reg_arg(env, ctx_reg, SRC_OP); 19268 if (err) 19269 return err; 19270 19271 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 19272 * gen_ld_abs() may terminate the program at runtime, leading to 19273 * reference leak. 19274 */ 19275 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 19276 if (err) 19277 return err; 19278 19279 if (regs[ctx_reg].type != PTR_TO_CTX) { 19280 verbose(env, 19281 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 19282 return -EINVAL; 19283 } 19284 19285 if (mode == BPF_IND) { 19286 /* check explicit source operand */ 19287 err = check_reg_arg(env, insn->src_reg, SRC_OP); 19288 if (err) 19289 return err; 19290 } 19291 19292 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 19293 if (err < 0) 19294 return err; 19295 19296 /* reset caller saved regs to unreadable */ 19297 bpf_diag_record_caller_saved(env, regs); 19298 bpf_diag_mod_begin(env, ®s[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE); 19299 for (i = 0; i < CALLER_SAVED_REGS; i++) { 19300 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 19301 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 19302 } 19303 19304 /* mark destination R0 register as readable, since it contains 19305 * the value fetched from the packet. 19306 * Already marked as written above. 19307 */ 19308 mark_reg_unknown(env, regs, BPF_REG_0); 19309 bpf_diag_mod_end(env); 19310 /* 19311 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 19312 * which must be explored by the verifier when in a subprog. 19313 */ 19314 if (env->cur_state->curframe) { 19315 struct bpf_verifier_state *branch; 19316 19317 mark_reg_scratched(env, BPF_REG_0); 19318 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 19319 if (IS_ERR(branch)) 19320 return PTR_ERR(branch); 19321 mark_reg_known_zero(env, regs, BPF_REG_0); 19322 err = prepare_func_exit(env, &env->insn_idx); 19323 if (err) 19324 return err; 19325 env->insn_idx--; 19326 } 19327 return 0; 19328 } 19329 19330 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 19331 { 19332 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 19333 19334 /* Default return value range. */ 19335 *range = retval_range(0, 1); 19336 19337 switch (prog_type) { 19338 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 19339 switch (env->prog->expected_attach_type) { 19340 case BPF_CGROUP_UDP4_RECVMSG: 19341 case BPF_CGROUP_UDP6_RECVMSG: 19342 case BPF_CGROUP_UNIX_RECVMSG: 19343 case BPF_CGROUP_INET4_GETPEERNAME: 19344 case BPF_CGROUP_INET6_GETPEERNAME: 19345 case BPF_CGROUP_UNIX_GETPEERNAME: 19346 case BPF_CGROUP_INET4_GETSOCKNAME: 19347 case BPF_CGROUP_INET6_GETSOCKNAME: 19348 case BPF_CGROUP_UNIX_GETSOCKNAME: 19349 *range = retval_range(1, 1); 19350 break; 19351 case BPF_CGROUP_INET4_BIND: 19352 case BPF_CGROUP_INET6_BIND: 19353 *range = retval_range(0, 3); 19354 break; 19355 default: 19356 break; 19357 } 19358 break; 19359 case BPF_PROG_TYPE_CGROUP_SKB: 19360 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 19361 *range = retval_range(0, 3); 19362 break; 19363 case BPF_PROG_TYPE_CGROUP_SOCK: 19364 case BPF_PROG_TYPE_SOCK_OPS: 19365 case BPF_PROG_TYPE_CGROUP_DEVICE: 19366 case BPF_PROG_TYPE_CGROUP_SYSCTL: 19367 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 19368 break; 19369 case BPF_PROG_TYPE_RAW_TRACEPOINT: 19370 if (!env->prog->aux->attach_btf_id) 19371 return false; 19372 *range = retval_range(0, 0); 19373 break; 19374 case BPF_PROG_TYPE_TRACING: 19375 switch (env->prog->expected_attach_type) { 19376 case BPF_TRACE_FENTRY: 19377 case BPF_TRACE_FEXIT: 19378 case BPF_TRACE_FSESSION: 19379 case BPF_TRACE_FENTRY_MULTI: 19380 case BPF_TRACE_FEXIT_MULTI: 19381 case BPF_TRACE_FSESSION_MULTI: 19382 *range = retval_range(0, 0); 19383 break; 19384 case BPF_TRACE_RAW_TP: 19385 case BPF_MODIFY_RETURN: 19386 return false; 19387 case BPF_TRACE_ITER: 19388 default: 19389 break; 19390 } 19391 break; 19392 case BPF_PROG_TYPE_KPROBE: 19393 switch (env->prog->expected_attach_type) { 19394 case BPF_TRACE_KPROBE_SESSION: 19395 case BPF_TRACE_UPROBE_SESSION: 19396 break; 19397 default: 19398 return false; 19399 } 19400 break; 19401 case BPF_PROG_TYPE_SK_LOOKUP: 19402 *range = retval_range(SK_DROP, SK_PASS); 19403 break; 19404 19405 case BPF_PROG_TYPE_LSM: 19406 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 19407 /* no range found, any return value is allowed */ 19408 if (!get_func_retval_range(env->prog, range)) 19409 return false; 19410 /* no restricted range, any return value is allowed */ 19411 if (range->minval == S32_MIN && range->maxval == S32_MAX) 19412 return false; 19413 range->return_32bit = true; 19414 } else if (!env->prog->aux->attach_func_proto->type) { 19415 /* Make sure programs that attach to void 19416 * hooks don't try to modify return value. 19417 */ 19418 *range = retval_range(1, 1); 19419 } 19420 break; 19421 19422 case BPF_PROG_TYPE_NETFILTER: 19423 *range = retval_range(NF_DROP, NF_ACCEPT); 19424 break; 19425 case BPF_PROG_TYPE_STRUCT_OPS: 19426 *range = retval_range(0, 0); 19427 break; 19428 case BPF_PROG_TYPE_EXT: 19429 /* freplace program can return anything as its return value 19430 * depends on the to-be-replaced kernel func or bpf program. 19431 */ 19432 default: 19433 return false; 19434 } 19435 19436 /* Continue calculating. */ 19437 19438 return true; 19439 } 19440 19441 static bool program_returns_void(struct bpf_verifier_env *env) 19442 { 19443 const struct bpf_prog *prog = env->prog; 19444 enum bpf_prog_type prog_type = prog->type; 19445 19446 switch (prog_type) { 19447 case BPF_PROG_TYPE_LSM: 19448 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 19449 if (prog->expected_attach_type != BPF_LSM_CGROUP && 19450 !prog->aux->attach_func_proto->type) 19451 return true; 19452 break; 19453 case BPF_PROG_TYPE_STRUCT_OPS: 19454 if (!prog->aux->attach_func_proto->type) 19455 return true; 19456 break; 19457 case BPF_PROG_TYPE_EXT: 19458 /* 19459 * If the actual program is an extension, let it 19460 * return void - attaching will succeed only if the 19461 * program being replaced also returns void, and since 19462 * it has passed verification its actual type doesn't matter. 19463 */ 19464 if (subprog_returns_void(env, 0)) 19465 return true; 19466 break; 19467 default: 19468 break; 19469 } 19470 return false; 19471 } 19472 19473 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 19474 { 19475 const char *exit_ctx = "At program exit"; 19476 struct tnum enforce_attach_type_range = tnum_unknown; 19477 const struct bpf_prog *prog = env->prog; 19478 struct bpf_reg_state *reg = reg_state(env, regno); 19479 struct bpf_retval_range range = retval_range(0, 1); 19480 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 19481 struct bpf_func_state *frame = env->cur_state->frame[0]; 19482 const struct btf_type *reg_type, *ret_type = NULL; 19483 int err; 19484 19485 /* LSM and struct_ops func-ptr's return type could be "void" */ 19486 if (!frame->in_async_callback_fn && program_returns_void(env)) 19487 return 0; 19488 19489 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 19490 /* Allow a struct_ops program to return a referenced kptr if it 19491 * matches the operator's return type and is in its unmodified 19492 * form. A scalar zero (i.e., a null pointer) is also allowed. 19493 */ 19494 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 19495 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 19496 prog->aux->attach_func_proto->type, 19497 NULL); 19498 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 19499 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 19500 } 19501 19502 /* eBPF calling convention is such that R0 is used 19503 * to return the value from eBPF program. 19504 * Make sure that it's readable at this time 19505 * of bpf_exit, which means that program wrote 19506 * something into it earlier 19507 */ 19508 err = check_reg_arg(env, regno, SRC_OP); 19509 if (err) 19510 return err; 19511 19512 if (is_pointer_value(env, regno)) { 19513 verbose(env, "R%d leaks addr as return value\n", regno); 19514 return -EACCES; 19515 } 19516 19517 if (frame->in_async_callback_fn) { 19518 exit_ctx = "At async callback return"; 19519 range = frame->callback_ret_range; 19520 goto enforce_retval; 19521 } 19522 19523 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 19524 return 0; 19525 19526 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 19527 enforce_attach_type_range = tnum_range(2, 3); 19528 19529 if (!return_retval_range(env, &range)) 19530 return 0; 19531 19532 enforce_retval: 19533 if (reg->type != SCALAR_VALUE) { 19534 verbose(env, "%s the register R%d is not a known value (%s)\n", 19535 exit_ctx, regno, reg_type_str(env, reg->type)); 19536 return -EINVAL; 19537 } 19538 19539 err = mark_chain_precision(env, regno); 19540 if (err) 19541 return err; 19542 19543 if (!retval_range_within(range, reg)) { 19544 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 19545 if (prog->expected_attach_type == BPF_LSM_CGROUP && 19546 prog_type == BPF_PROG_TYPE_LSM && 19547 !prog->aux->attach_func_proto->type) 19548 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 19549 return -EINVAL; 19550 } 19551 19552 if (!tnum_is_unknown(enforce_attach_type_range) && 19553 tnum_in(enforce_attach_type_range, reg->var_off)) 19554 env->prog->enforce_expected_attach_type = 1; 19555 return 0; 19556 } 19557 19558 static int check_global_ret_scalar_reg(struct bpf_verifier_env *env, u32 regno) 19559 { 19560 struct bpf_reg_state *reg; 19561 int err; 19562 19563 err = check_reg_arg(env, regno, SRC_OP); 19564 if (err) 19565 return err; 19566 19567 /* Pointers to arena are safe to pass between subprograms. */ 19568 if (is_arena_reg(env, regno)) 19569 return 0; 19570 19571 if (is_pointer_value(env, regno)) { 19572 verbose(env, "R%d leaks addr as return value\n", regno); 19573 return -EACCES; 19574 } 19575 19576 reg = reg_state(env, regno); 19577 if (reg->type != SCALAR_VALUE) { 19578 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 19579 regno, reg_type_str(env, reg->type)); 19580 return -EINVAL; 19581 } 19582 19583 return 0; 19584 } 19585 19586 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 19587 { 19588 struct bpf_func_state *cur_frame = cur_func(env); 19589 u32 subprog = cur_frame->subprogno; 19590 u32 i, nregs; 19591 int err; 19592 19593 if (subprog_returns_void(env, subprog)) 19594 return 0; 19595 19596 nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1; 19597 for (i = 0; i < nregs; i++) { 19598 err = check_global_ret_scalar_reg(env, ret_regs[i]); 19599 if (err) 19600 return err; 19601 } 19602 19603 return 0; 19604 } 19605 19606 /* Bitmask with 1s for all caller saved registers */ 19607 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 19608 19609 /* True if do_misc_fixups() replaces calls to helper number 'imm', 19610 * replacement patch is presumed to follow bpf_fastcall contract 19611 * (see mark_fastcall_pattern_for_call() below). 19612 */ 19613 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 19614 { 19615 switch (imm) { 19616 #ifdef CONFIG_X86_64 19617 case BPF_FUNC_get_smp_processor_id: 19618 #ifdef CONFIG_SMP 19619 case BPF_FUNC_get_current_task_btf: 19620 case BPF_FUNC_get_current_task: 19621 #endif 19622 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 19623 #endif 19624 default: 19625 return false; 19626 } 19627 } 19628 19629 /* If @call is a kfunc or helper call, fills @cs and returns true, 19630 * otherwise returns false. 19631 */ 19632 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 19633 struct bpf_call_summary *cs) 19634 { 19635 struct bpf_call_arg_meta meta; 19636 const struct bpf_func_proto *fn; 19637 int i; 19638 19639 if (bpf_helper_call(call)) { 19640 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 19641 /* error would be reported later */ 19642 return false; 19643 cs->fastcall = fn->allow_fastcall && 19644 (bpf_verifier_inlines_helper_call(env, call->imm) || 19645 bpf_jit_inlines_helper_call(call->imm)); 19646 cs->is_void = fn->ret_type == RET_VOID; 19647 cs->arg_slot_cnt = 0; 19648 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 19649 if (fn->arg_type[i] == ARG_UNUSED) 19650 break; 19651 cs->arg_slot_cnt++; 19652 } 19653 return true; 19654 } 19655 19656 if (bpf_pseudo_kfunc_call(call)) { 19657 int err; 19658 19659 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 19660 if (err < 0) 19661 /* error would be reported later */ 19662 return false; 19663 cs->arg_slot_cnt = btf_proto_slots(meta.btf, meta.func_proto); 19664 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 19665 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 19666 return true; 19667 } 19668 19669 return false; 19670 } 19671 19672 /* LLVM define a bpf_fastcall function attribute. 19673 * This attribute means that function scratches only some of 19674 * the caller saved registers defined by ABI. 19675 * For BPF the set of such registers could be defined as follows: 19676 * - R0 is scratched only if function is non-void; 19677 * - R1-R5 are scratched only if corresponding parameter type is defined 19678 * in the function prototype. 19679 * 19680 * The contract between kernel and clang allows to simultaneously use 19681 * such functions and maintain backwards compatibility with old 19682 * kernels that don't understand bpf_fastcall calls: 19683 * 19684 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 19685 * registers are not scratched by the call; 19686 * 19687 * - as a post-processing step, clang visits each bpf_fastcall call and adds 19688 * spill/fill for every live r0-r5; 19689 * 19690 * - stack offsets used for the spill/fill are allocated as lowest 19691 * stack offsets in whole function and are not used for any other 19692 * purposes; 19693 * 19694 * - when kernel loads a program, it looks for such patterns 19695 * (bpf_fastcall function surrounded by spills/fills) and checks if 19696 * spill/fill stack offsets are used exclusively in fastcall patterns; 19697 * 19698 * - if so, and if verifier or current JIT inlines the call to the 19699 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 19700 * spill/fill pairs; 19701 * 19702 * - when old kernel loads a program, presence of spill/fill pairs 19703 * keeps BPF program valid, albeit slightly less efficient. 19704 * 19705 * For example: 19706 * 19707 * r1 = 1; 19708 * r2 = 2; 19709 * *(u64 *)(r10 - 8) = r1; r1 = 1; 19710 * *(u64 *)(r10 - 16) = r2; r2 = 2; 19711 * call %[to_be_inlined] --> call %[to_be_inlined] 19712 * r2 = *(u64 *)(r10 - 16); r0 = r1; 19713 * r1 = *(u64 *)(r10 - 8); r0 += r2; 19714 * r0 = r1; exit; 19715 * r0 += r2; 19716 * exit; 19717 * 19718 * The purpose of mark_fastcall_pattern_for_call is to: 19719 * - look for such patterns; 19720 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 19721 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 19722 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 19723 * at which bpf_fastcall spill/fill stack slots start; 19724 * - update env->subprog_info[*]->keep_fastcall_stack. 19725 * 19726 * The .fastcall_pattern and .fastcall_stack_off are used by 19727 * check_fastcall_stack_contract() to check if every stack access to 19728 * fastcall spill/fill stack slot originates from spill/fill 19729 * instructions, members of fastcall patterns. 19730 * 19731 * If such condition holds true for a subprogram, fastcall patterns could 19732 * be rewritten by remove_fastcall_spills_fills(). 19733 * Otherwise bpf_fastcall patterns are not changed in the subprogram 19734 * (code, presumably, generated by an older clang version). 19735 * 19736 * For example, it is *not* safe to remove spill/fill below: 19737 * 19738 * r1 = 1; 19739 * *(u64 *)(r10 - 8) = r1; r1 = 1; 19740 * call %[to_be_inlined] --> call %[to_be_inlined] 19741 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 19742 * r0 = *(u64 *)(r10 - 8); r0 += r1; 19743 * r0 += r1; exit; 19744 * exit; 19745 * 19746 * Both uses of the marks assume that a pattern is entered at its first 19747 * spill and thus executes as a unit, hence a pattern is not grown past 19748 * an instruction targeted by a jump. 19749 */ 19750 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 19751 struct bpf_subprog_info *subprog, 19752 int insn_idx, s16 lowest_off) 19753 { 19754 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 19755 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 19756 u32 clobbered_regs_mask; 19757 struct bpf_call_summary cs; 19758 u32 expected_regs_mask; 19759 s16 off; 19760 int i; 19761 19762 if (!bpf_get_call_summary(env, call, &cs)) 19763 return; 19764 19765 /* A bitmask specifying which caller saved registers are clobbered 19766 * by a call to a helper/kfunc *as if* this helper/kfunc follows 19767 * bpf_fastcall contract: 19768 * - includes R0 if function is non-void; 19769 * - includes R1-R5 if corresponding parameter has is described 19770 * in the function prototype. 19771 */ 19772 clobbered_regs_mask = GENMASK(cs.arg_slot_cnt, cs.is_void ? 1 : 0); 19773 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 19774 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 19775 19776 /* match pairs of form: 19777 * 19778 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 19779 * ... 19780 * call %[to_be_inlined] 19781 * ... 19782 * rX = *(u64 *)(r10 - Y) 19783 */ 19784 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 19785 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 19786 break; 19787 /* stx/ldx/call must not be a jump targets, a jump to the first stx is fine */ 19788 if (bpf_is_jump_target(env, insn_idx - i + 1) || 19789 bpf_is_jump_target(env, insn_idx + i)) 19790 break; 19791 stx = &insns[insn_idx - i]; 19792 ldx = &insns[insn_idx + i]; 19793 /* must be a stack spill/fill pair */ 19794 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 19795 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 19796 stx->dst_reg != BPF_REG_10 || 19797 ldx->src_reg != BPF_REG_10) 19798 break; 19799 /* must be a spill/fill for the same reg */ 19800 if (stx->src_reg != ldx->dst_reg) 19801 break; 19802 /* must be one of the previously unseen registers */ 19803 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 19804 break; 19805 /* must be a spill/fill for the same expected offset, 19806 * no need to check offset alignment, BPF_DW stack access 19807 * is always 8-byte aligned. 19808 */ 19809 if (stx->off != off || ldx->off != off) 19810 break; 19811 expected_regs_mask &= ~BIT(stx->src_reg); 19812 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 19813 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 19814 } 19815 if (i == 1) 19816 return; 19817 19818 /* Conditionally set 'fastcall_spills_num' to allow forward 19819 * compatibility when more helper functions are marked as 19820 * bpf_fastcall at compile time than current kernel supports, e.g: 19821 * 19822 * 1: *(u64 *)(r10 - 8) = r1 19823 * 2: call A ;; assume A is bpf_fastcall for current kernel 19824 * 3: r1 = *(u64 *)(r10 - 8) 19825 * 4: *(u64 *)(r10 - 8) = r1 19826 * 5: call B ;; assume B is not bpf_fastcall for current kernel 19827 * 6: r1 = *(u64 *)(r10 - 8) 19828 * 19829 * There is no need to block bpf_fastcall rewrite for such program. 19830 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 19831 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 19832 * does not remove spill/fill pair {4,6}. 19833 */ 19834 if (cs.fastcall) 19835 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 19836 else 19837 subprog->keep_fastcall_stack = 1; 19838 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 19839 } 19840 19841 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 19842 { 19843 struct bpf_subprog_info *subprog = env->subprog_info; 19844 struct bpf_insn *insn; 19845 s16 lowest_off; 19846 int s, i; 19847 19848 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 19849 /* find lowest stack spill offset used in this subprog */ 19850 lowest_off = 0; 19851 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 19852 insn = env->prog->insnsi + i; 19853 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 19854 insn->dst_reg != BPF_REG_10) 19855 continue; 19856 lowest_off = min(lowest_off, insn->off); 19857 } 19858 /* use this offset to find fastcall patterns */ 19859 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 19860 insn = env->prog->insnsi + i; 19861 if (insn->code != (BPF_JMP | BPF_CALL)) 19862 continue; 19863 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 19864 } 19865 } 19866 return 0; 19867 } 19868 19869 static void adjust_btf_func(struct bpf_verifier_env *env) 19870 { 19871 struct bpf_prog_aux *aux = env->prog->aux; 19872 int i; 19873 19874 if (!aux->func_info) 19875 return; 19876 19877 /* func_info is not available for hidden subprogs */ 19878 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 19879 aux->func_info[i].insn_off = env->subprog_info[i].start; 19880 } 19881 19882 /* Find id in idset and increment its count, or add new entry */ 19883 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 19884 { 19885 u32 i; 19886 19887 for (i = 0; i < idset->num_ids; i++) { 19888 if (idset->entries[i].id == id) { 19889 idset->entries[i].cnt++; 19890 return; 19891 } 19892 } 19893 /* New id */ 19894 if (idset->num_ids < BPF_ID_MAP_SIZE) { 19895 idset->entries[idset->num_ids].id = id; 19896 idset->entries[idset->num_ids].cnt = 1; 19897 idset->num_ids++; 19898 } 19899 } 19900 19901 /* Find id in idset and return its count, or 0 if not found */ 19902 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 19903 { 19904 u32 i; 19905 19906 for (i = 0; i < idset->num_ids; i++) { 19907 if (idset->entries[i].id == id) 19908 return idset->entries[i].cnt; 19909 } 19910 return 0; 19911 } 19912 19913 /* 19914 * Clear singular scalar ids in a state. 19915 * A register with a non-zero id is called singular if no other register shares 19916 * the same base id. Such registers can be treated as independent (id=0). 19917 */ 19918 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 19919 struct bpf_verifier_state *st) 19920 { 19921 struct bpf_idset *idset = &env->idset_scratch; 19922 struct bpf_func_state *func; 19923 struct bpf_reg_state *reg; 19924 19925 idset->num_ids = 0; 19926 19927 bpf_for_each_reg_in_vstate(st, func, reg, ({ 19928 if (reg->type != SCALAR_VALUE) 19929 continue; 19930 if (!reg->id) 19931 continue; 19932 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 19933 })); 19934 19935 bpf_for_each_reg_in_vstate(st, func, reg, ({ 19936 if (reg->type != SCALAR_VALUE) 19937 continue; 19938 if (!reg->id) 19939 continue; 19940 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 19941 clear_scalar_id(reg); 19942 })); 19943 } 19944 19945 /* Return true if it's OK to have the same insn return a different type. */ 19946 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 19947 { 19948 switch (base_type(type)) { 19949 case PTR_TO_CTX: 19950 case PTR_TO_SOCKET: 19951 case PTR_TO_SOCK_COMMON: 19952 case PTR_TO_TCP_SOCK: 19953 case PTR_TO_XDP_SOCK: 19954 case PTR_TO_BTF_ID: 19955 case PTR_TO_ARENA: 19956 return false; 19957 case PTR_TO_MEM: 19958 return !bpf_may_fault_on_deref(type); 19959 default: 19960 return true; 19961 } 19962 } 19963 19964 /* If an instruction was previously used with particular pointer types, then we 19965 * need to be careful to avoid cases such as the below, where it may be ok 19966 * for one branch accessing the pointer, but not ok for the other branch: 19967 * 19968 * R1 = sock_ptr 19969 * goto X; 19970 * ... 19971 * R1 = some_other_valid_ptr; 19972 * goto X; 19973 * ... 19974 * R2 = *(u32 *)(R1 + 0); 19975 */ 19976 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 19977 { 19978 return src != prev && (!reg_type_mismatch_ok(src) || 19979 !reg_type_mismatch_ok(prev)); 19980 } 19981 19982 static bool is_ptr_to_mem(enum bpf_reg_type type) 19983 { 19984 return base_type(type) == PTR_TO_MEM; 19985 } 19986 19987 static enum bpf_reg_type merge_ptr_types(enum bpf_reg_type type_a, 19988 enum bpf_reg_type type_b) 19989 { 19990 bool to_mem = is_ptr_to_mem(type_a) || is_ptr_to_mem(type_b); 19991 enum bpf_reg_type type_merged = to_mem ? PTR_TO_MEM : PTR_TO_BTF_ID; 19992 19993 if (bpf_may_fault_on_deref(type_a) || bpf_may_fault_on_deref(type_b)) 19994 type_merged |= to_mem ? MEM_RDONLY | PTR_UNTRUSTED : 19995 PTR_UNTRUSTED; 19996 else 19997 type_merged |= ((type_a | type_b) & MEM_RDONLY); 19998 return type_merged; 19999 } 20000 20001 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 20002 bool allow_trust_mismatch) 20003 { 20004 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 20005 20006 if (*prev_type == NOT_INIT) { 20007 /* Saw a valid insn 20008 * dst_reg = *(u32 *)(src_reg + off) 20009 * save type to validate intersecting paths 20010 */ 20011 *prev_type = type; 20012 } else if (reg_type_mismatch(type, *prev_type)) { 20013 /* Abuser program is trying to use the same insn 20014 * dst_reg = *(u32*) (src_reg + off) 20015 * with different pointer types: 20016 * src_reg == ctx in one branch and 20017 * src_reg == stack|map in some other branch. 20018 * Reject it. 20019 */ 20020 if (allow_trust_mismatch && 20021 bpf_is_ptr_to_mem_or_btf_id(type) && 20022 bpf_is_ptr_to_mem_or_btf_id(*prev_type)) { 20023 /* 20024 * Have to support a use case when one path through 20025 * the program yields a TRUSTED pointer while another 20026 * is UNTRUSTED. Merge them into a type which keeps 20027 * the BPF_PROBE_MEM/BPF_PROBE_MEMSX rewrite when 20028 * either side needs it. 20029 */ 20030 *prev_type = merge_ptr_types(type, *prev_type); 20031 } else { 20032 verbose(env, "same insn cannot be used with different pointers\n"); 20033 return -EINVAL; 20034 } 20035 } 20036 20037 return 0; 20038 } 20039 20040 enum { 20041 PROCESS_BPF_EXIT = 1, 20042 INSN_IDX_UPDATED = 2, 20043 }; 20044 20045 static int process_bpf_exit_full(struct bpf_verifier_env *env, 20046 bool *do_print_state, 20047 bool exception_exit) 20048 { 20049 struct bpf_func_state *cur_frame = cur_func(env); 20050 20051 /* We must do check_reference_leak here before 20052 * prepare_func_exit to handle the case when 20053 * state->curframe > 0, it may be a callback function, 20054 * for which reference_state must match caller reference 20055 * state when it exits. 20056 */ 20057 int err = check_resource_leak(env, exception_exit, 20058 exception_exit || !env->cur_state->curframe, 20059 exception_exit ? "bpf_throw" : 20060 "BPF_EXIT instruction in main prog"); 20061 if (err) 20062 return err; 20063 20064 /* The side effect of the prepare_func_exit which is 20065 * being skipped is that it frees bpf_func_state. 20066 * Typically, process_bpf_exit will only be hit with 20067 * outermost exit. copy_verifier_state in pop_stack will 20068 * handle freeing of any extra bpf_func_state left over 20069 * from not processing all nested function exits. We 20070 * also skip return code checks as they are not needed 20071 * for exceptional exits. 20072 */ 20073 if (exception_exit) 20074 return PROCESS_BPF_EXIT; 20075 20076 if (env->cur_state->curframe) { 20077 /* exit from nested function */ 20078 err = prepare_func_exit(env, &env->insn_idx); 20079 if (err) 20080 return err; 20081 *do_print_state = true; 20082 return INSN_IDX_UPDATED; 20083 } 20084 20085 /* 20086 * Return from a regular global subprogram differs from return 20087 * from the main program or async/exception callback. 20088 * Main program exit implies return code restrictions 20089 * that depend on program type. 20090 * Exit from exception callback is equivalent to main program exit. 20091 * Exit from async callback implies return code restrictions 20092 * that depend on async scheduling mechanism. 20093 */ 20094 if (cur_frame->subprogno && 20095 !cur_frame->in_async_callback_fn && 20096 !cur_frame->in_exception_callback_fn) 20097 err = check_global_subprog_return_code(env); 20098 else 20099 err = check_return_code(env, BPF_REG_0, "R0"); 20100 if (err) 20101 return err; 20102 return PROCESS_BPF_EXIT; 20103 } 20104 20105 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 20106 int regno, 20107 struct bpf_map *map, 20108 u32 *pmin_index, u32 *pmax_index) 20109 { 20110 struct bpf_reg_state *reg = reg_state(env, regno); 20111 u64 min_index = reg_umin(reg); 20112 u64 max_index = reg_umax(reg); 20113 const u32 size = 8; 20114 20115 if (min_index > (u64) U32_MAX * size) { 20116 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 20117 return -ERANGE; 20118 } 20119 if (max_index > (u64) U32_MAX * size) { 20120 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 20121 return -ERANGE; 20122 } 20123 20124 min_index /= size; 20125 max_index /= size; 20126 20127 if (max_index >= map->max_entries) { 20128 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 20129 regno, min_index, max_index, map->max_entries); 20130 return -EINVAL; 20131 } 20132 20133 *pmin_index = min_index; 20134 *pmax_index = max_index; 20135 return 0; 20136 } 20137 20138 static int reject_gotox_out_of_subprog(struct bpf_verifier_env *env, u32 target, 20139 u32 subprog_start, u32 subprog_end) 20140 { 20141 verbose(env, "indirect jump from insn %d to %u leaves the subprog [%u,%u)\n", 20142 env->insn_idx, target, subprog_start, subprog_end); 20143 bpf_diag_program_structure( 20144 env, env->insn_idx, "indirect jump leaves subprogram", 20145 "Keep every reachable jump-table target inside the subprogram of the indirect jump.", 20146 "Instruction %d can jump indirectly to instruction %u, which is outside its own subprogram [%u,%u).", 20147 env->insn_idx, target, subprog_start, subprog_end); 20148 return -EINVAL; 20149 } 20150 20151 /* gotox *dst_reg */ 20152 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 20153 { 20154 struct bpf_verifier_state *other_branch; 20155 struct bpf_subprog_info *subprog; 20156 u32 subprog_start, subprog_end; 20157 struct bpf_reg_state *dst_reg; 20158 struct bpf_map *map; 20159 u32 min_index, max_index; 20160 int err = 0; 20161 int n; 20162 int i; 20163 20164 dst_reg = reg_state(env, insn->dst_reg); 20165 if (dst_reg->type != PTR_TO_INSN) { 20166 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 20167 insn->dst_reg, reg_type_str(env, dst_reg->type)); 20168 return -EINVAL; 20169 } 20170 20171 map = dst_reg->map_ptr; 20172 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 20173 return -EFAULT; 20174 20175 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 20176 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 20177 return -EFAULT; 20178 20179 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 20180 if (err) 20181 return err; 20182 20183 /* Ensure that the buffer is large enough */ 20184 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 20185 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 20186 max_index - min_index + 1); 20187 if (!env->gotox_tmp_buf) 20188 return -ENOMEM; 20189 } 20190 20191 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 20192 if (n < 0) 20193 return n; 20194 if (n == 0) { 20195 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 20196 insn->dst_reg, map->id); 20197 return -EINVAL; 20198 } 20199 20200 subprog = bpf_find_containing_subprog(env, env->insn_idx); 20201 if (verifier_bug_if(!subprog, env, "no subprog contains insn %d", env->insn_idx)) 20202 return -EFAULT; 20203 subprog_start = subprog->start; 20204 subprog_end = (subprog + 1)->start; 20205 20206 /* 20207 * Maps are confined to a subprog, see compute_subprog_jts(), and the 20208 * targets are sorted and free of duplicates, see sort_insn_array_uniq(), 20209 * so either all of them belong to this subprog or none of them does. 20210 */ 20211 if (env->gotox_tmp_buf->items[0] < subprog_start) 20212 return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[0], 20213 subprog_start, subprog_end); 20214 if (env->gotox_tmp_buf->items[n - 1] >= subprog_end) 20215 return reject_gotox_out_of_subprog(env, env->gotox_tmp_buf->items[n - 1], 20216 subprog_start, subprog_end); 20217 20218 for (i = 0; i < n - 1; i++) { 20219 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 20220 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 20221 env->insn_idx, env->cur_state->speculative); 20222 if (IS_ERR(other_branch)) 20223 return PTR_ERR(other_branch); 20224 } 20225 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 20226 mark_indirect_target(env, env->insn_idx); 20227 return INSN_IDX_UPDATED; 20228 } 20229 20230 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 20231 { 20232 int err; 20233 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 20234 u8 class = BPF_CLASS(insn->code); 20235 20236 switch (class) { 20237 case BPF_ALU: 20238 case BPF_ALU64: 20239 return check_alu_op(env, insn); 20240 20241 case BPF_LDX: 20242 return check_load_mem(env, insn, false, 20243 BPF_MODE(insn->code) == BPF_MEMSX, 20244 true, "ldx"); 20245 20246 case BPF_STX: 20247 if (BPF_MODE(insn->code) == BPF_ATOMIC) 20248 return check_atomic(env, insn); 20249 return check_store_reg(env, insn, false); 20250 20251 case BPF_ST: { 20252 /* Handle stack arg write (store immediate) */ 20253 if (is_stack_arg_st(insn)) { 20254 struct bpf_verifier_state *vstate = env->cur_state; 20255 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 20256 20257 return check_stack_arg_write(env, state, insn->off, NULL); 20258 } 20259 20260 enum bpf_reg_type dst_reg_type; 20261 20262 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 20263 if (err) 20264 return err; 20265 20266 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 20267 20268 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, 20269 argno_from_reg(insn->dst_reg), 20270 insn->off, BPF_SIZE(insn->code), 20271 BPF_WRITE, -1, false, false); 20272 if (err) 20273 return err; 20274 20275 return save_aux_ptr_type(env, dst_reg_type, false); 20276 } 20277 case BPF_JMP: 20278 case BPF_JMP32: { 20279 u8 opcode = BPF_OP(insn->code); 20280 20281 env->jmps_processed++; 20282 if (opcode == BPF_CALL) { 20283 if (env->cur_state->active_locks) { 20284 /* similar to static subprog calls callx is allowed under a lock */ 20285 if (!bpf_is_callx(insn) && 20286 ((insn->src_reg == BPF_REG_0 && 20287 insn->imm != BPF_FUNC_spin_unlock && 20288 insn->imm != BPF_FUNC_kptr_xchg) || 20289 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 20290 !kfunc_spin_allowed(env, insn->imm, insn->off)))) { 20291 verbose(env, 20292 "function calls are not allowed while holding a lock\n"); 20293 bpf_diag_ctx_active( 20294 env, env->insn_idx, 20295 "function call", BPF_DIAG_CONTEXT_LOCK, 20296 "Release the BPF spin lock before making this call, or move the call outside the locked region."); 20297 return -EINVAL; 20298 } 20299 } 20300 mark_reg_scratched(env, BPF_REG_0); 20301 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 20302 cur_func(env)->no_stack_arg_load = true; 20303 if (bpf_is_callx(insn)) 20304 return check_func_callx(env, insn, &env->insn_idx); 20305 if (insn->src_reg == BPF_PSEUDO_CALL) 20306 return check_func_call(env, insn, &env->insn_idx); 20307 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 20308 return check_kfunc_call(env, insn, &env->insn_idx); 20309 return check_helper_call(env, insn, &env->insn_idx); 20310 } else if (opcode == BPF_JA) { 20311 if (BPF_SRC(insn->code) == BPF_X) 20312 return check_indirect_jump(env, insn); 20313 20314 if (class == BPF_JMP) 20315 env->insn_idx += insn->off + 1; 20316 else 20317 env->insn_idx += insn->imm + 1; 20318 return INSN_IDX_UPDATED; 20319 } else if (opcode == BPF_EXIT) { 20320 return process_bpf_exit_full(env, do_print_state, false); 20321 } 20322 return check_cond_jmp_op(env, insn, &env->insn_idx); 20323 } 20324 case BPF_LD: { 20325 u8 mode = BPF_MODE(insn->code); 20326 20327 if (mode == BPF_ABS || mode == BPF_IND) 20328 return check_ld_abs(env, insn); 20329 20330 if (mode == BPF_IMM) { 20331 err = check_ld_imm(env, insn); 20332 if (err) 20333 return err; 20334 20335 env->insn_idx++; 20336 sanitize_mark_insn_seen(env); 20337 } 20338 return 0; 20339 } 20340 } 20341 /* all class values are handled above. silence compiler warning */ 20342 return -EFAULT; 20343 } 20344 20345 /* 20346 * Push the loop entered at insn_idx onto the stack. Usually this adds a single 20347 * entry on top of its enclosing loop. However, an edge may enter an inner loop 20348 * directly, bypassing the header(s) of its enclosing loop(s), e.g.: 20349 * 20350 * 1: for (...): // enclosing loop, header at 1 20351 * 2: for (...): // inner loop, header at 2 20352 * ... 20353 * 3: if ...: 20354 * goto 2b; // enters loop 2 without going through header 1 20355 * 20356 * Such a bypass makes the enclosing loop irreducible, so its header is missing 20357 * from the stack and both headers (1) and (2) need to be pushed onto stack. 20358 * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds; 20359 * the bypassed ancestors are irreducible and pushed as non-terminating. 20360 * 20361 * Assumes loop_stack_pop() has already truncated the stack to the common ancestor 20362 * of the bpf_loop_at_index(env->insn_idx) and whatever was at the top of the loop stack. 20363 */ 20364 static int loop_stack_push(struct bpf_verifier_env *env, bool *pushed) 20365 { 20366 struct bpf_insn_aux_data *aux = env->insn_aux_data; 20367 struct bpf_func_state *frame = cur_func(env); 20368 struct loop_stack_entry *loop_stack = frame->loop_stack; 20369 u32 missing_headers[LOOP_STACK_SIZE]; 20370 u32 cnt = frame->loop_stack_cnt; 20371 u32 num_missing = 0; 20372 int h; 20373 20374 *pushed = false; 20375 20376 for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) { 20377 if (cnt && loop_stack[cnt - 1].loop_id == h) 20378 break; 20379 if (num_missing == LOOP_STACK_SIZE) 20380 goto e2big; 20381 missing_headers[num_missing] = h; 20382 } 20383 20384 if (num_missing == 0) 20385 return 0; 20386 if (cnt + num_missing > LOOP_STACK_SIZE) 20387 goto e2big; 20388 frame->loop_stack = realloc_array(frame->loop_stack, cnt, cnt + num_missing, 20389 sizeof(*frame->loop_stack)); 20390 if (!frame->loop_stack) 20391 return -ENOMEM; 20392 loop_stack = frame->loop_stack; 20393 20394 for (; num_missing; num_missing--, cnt++) { 20395 h = missing_headers[num_missing - 1]; 20396 loop_stack[cnt] = (struct loop_stack_entry){ .loop_id = h }; 20397 if (env->log.level & BPF_LOG_LEVEL2) 20398 verbose(env, "entering loop %d\n", h); 20399 *pushed = true; 20400 } 20401 frame->loop_stack_cnt = cnt; 20402 return 0; 20403 20404 e2big: 20405 verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx); 20406 return -E2BIG; 20407 } 20408 20409 /* 20410 * An exit from a loop can cross several nested loops, e.g.: 20411 * 20412 * 1: for (...): 20413 * 2: for (...): 20414 * 3: for (...): 20415 * if ...: // before goto the loop stack is [1, 2, 3 <top>] 20416 * goto 1b; // after goto it should become [1] 20417 */ 20418 static int loop_stack_pop(struct bpf_verifier_env *env) 20419 { 20420 struct bpf_insn_aux_data *aux = env->insn_aux_data; 20421 struct bpf_func_state *frame = cur_func(env); 20422 int new_cnt = 0; 20423 int h, i; 20424 20425 /* 20426 * Walk the loop nest of insn_idx outwards (innermost first) and stop at 20427 * the first loop that is present on the stack - that loop is the common 20428 * ancestor and becomes the new top. If no enclosing loop is on the 20429 * stack, drop all loops. 20430 */ 20431 for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) { 20432 for (i = frame->loop_stack_cnt - 1; i >= 0; i--) { 20433 if (frame->loop_stack[i].loop_id == h) { 20434 new_cnt = i + 1; 20435 goto pop; 20436 } 20437 } 20438 } 20439 20440 pop: 20441 if (env->log.level & BPF_LOG_LEVEL2) 20442 for (i = frame->loop_stack_cnt - 1; i >= new_cnt; i--) 20443 verbose(env, "exiting loop %d\n", frame->loop_stack[i].loop_id); 20444 frame->loop_stack_cnt = new_cnt; 20445 return 0; 20446 } 20447 20448 static int maybe_clamp_scev_regs(struct bpf_verifier_env *env) 20449 { 20450 struct bpf_func_state *frame = cur_func(env); 20451 struct loop_stack_entry *entry; 20452 20453 if (frame->loop_stack_cnt == 0) { 20454 verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx); 20455 return -EFAULT; 20456 } 20457 20458 entry = &frame->loop_stack[frame->loop_stack_cnt - 1]; 20459 if (!entry->terminates) 20460 return 0; 20461 20462 return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state, 20463 entry->max_header_count); 20464 } 20465 20466 static int handle_loop_entry_exit(struct bpf_verifier_env *env) 20467 { 20468 struct bpf_verifier_state *cur = env->cur_state; 20469 struct bpf_func_state *frame = cur_func(env); 20470 struct loop_stack_entry *entry; 20471 struct bpf_loop_iters iters; 20472 bool pushed, terminates; 20473 int err; 20474 20475 err = loop_stack_pop(env); 20476 if (err) 20477 return err; 20478 20479 err = loop_stack_push(env, &pushed); 20480 if (err) 20481 return err; 20482 20483 if (frame->loop_stack_cnt == 0) 20484 return 0; 20485 20486 entry = &frame->loop_stack[frame->loop_stack_cnt - 1]; 20487 if (env->insn_idx != entry->loop_id) 20488 return 0; 20489 20490 /* If nothing was pushed and env->insn_idx is a loop header, we've taken a backedge. */ 20491 if (!pushed) 20492 return maybe_clamp_scev_regs(env); 20493 20494 err = bpf_compute_loop_iters(env, env->cur_state, &iters); 20495 if (err < 0) 20496 return err; 20497 20498 terminates = err == 1; 20499 if (!terminates) 20500 return 0; 20501 20502 /* Create a loop_entry checkpoint before widening */ 20503 err = bpf_split_cur_state(env); 20504 if (err) 20505 return err; 20506 20507 entry->min_header_count = iters.min_header_count; 20508 entry->max_header_count = iters.max_header_count; 20509 entry->entry_state = cur->parent; 20510 entry->terminates = true; 20511 err = bpf_widen_scev_regs(env, cur, cur->parent, &iters); 20512 if (err < 0) 20513 return err; 20514 return 0; 20515 } 20516 20517 static int do_check(struct bpf_verifier_env *env) 20518 { 20519 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20520 struct bpf_verifier_state *state = env->cur_state; 20521 struct bpf_insn *insns = env->prog->insnsi; 20522 int insn_cnt = env->prog->len; 20523 bool do_print_state = false; 20524 int prev_insn_idx = -1; 20525 20526 for (;;) { 20527 struct bpf_insn *insn; 20528 struct bpf_insn_aux_data *insn_aux; 20529 int err; 20530 20531 if (signal_pending(current)) 20532 return -EAGAIN; 20533 20534 if (need_resched()) 20535 cond_resched(); 20536 20537 /* reset current history entry on each new instruction */ 20538 env->cur_hist_ent = NULL; 20539 20540 env->prev_insn_idx = prev_insn_idx; 20541 if (env->insn_idx >= insn_cnt) { 20542 verbose(env, "invalid insn idx %d insn_cnt %d\n", 20543 env->insn_idx, insn_cnt); 20544 return -EFAULT; 20545 } 20546 20547 insn = &insns[env->insn_idx]; 20548 insn_aux = &env->insn_aux_data[env->insn_idx]; 20549 20550 account_processed_insn(env); 20551 20552 if (env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 20553 verbose(env, 20554 "BPF program is too large. Processed %d insn\n", 20555 env->insn_processed); 20556 return -E2BIG; 20557 } 20558 20559 state->last_insn_idx = env->prev_insn_idx; 20560 state->insn_idx = env->insn_idx; 20561 /* 20562 * Record the incoming edge so active and queued paths use the same 20563 * branch-recording path. A zero-offset conditional has identical 20564 * successors, so its outcome cannot be reconstructed from the edge. 20565 */ 20566 if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) { 20567 struct bpf_insn *prev_insn = &insns[prev_insn_idx]; 20568 int fallthrough_idx = prev_insn_idx + 1; 20569 int branch_idx = prev_insn_idx + bpf_jmp_offset(prev_insn) + 1; 20570 u8 class = BPF_CLASS(prev_insn->code); 20571 u8 opcode = BPF_OP(prev_insn->code); 20572 20573 if ((class == BPF_JMP || class == BPF_JMP32) && 20574 opcode != BPF_JA && opcode != BPF_CALL && opcode != BPF_EXIT && 20575 opcode <= BPF_JCOND && branch_idx != fallthrough_idx) { 20576 if (env->insn_idx == branch_idx) 20577 bpf_diag_record_branch(env, prev_insn_idx, true); 20578 else if (env->insn_idx == fallthrough_idx) 20579 bpf_diag_record_branch(env, prev_insn_idx, false); 20580 } 20581 } 20582 20583 /* 20584 * Possibly widen the registers before creating a checkpoint 20585 * in bpf_is_state_visited(). The next loop iteration will 20586 * have a chance to hit this checkpoint and converge. 20587 */ 20588 err = handle_loop_entry_exit(env); 20589 if (err) 20590 return err; 20591 20592 if (bpf_is_prune_point(env, env->insn_idx)) { 20593 err = bpf_is_state_visited(env, env->insn_idx); 20594 if (err < 0) 20595 return err; 20596 if (err == 1) { 20597 /* found equivalent state, can prune the search */ 20598 if (env->log.level & BPF_LOG_LEVEL) { 20599 if (do_print_state) 20600 verbose(env, "\nfrom %d to %d%s: safe\n", 20601 env->prev_insn_idx, env->insn_idx, 20602 env->cur_state->speculative ? 20603 " (speculative execution)" : ""); 20604 else 20605 verbose(env, "%d: safe\n", env->insn_idx); 20606 } 20607 goto process_bpf_exit; 20608 } 20609 } 20610 20611 if (bpf_is_jmp_point(env, env->insn_idx)) { 20612 err = bpf_push_jmp_history(env, state, 0, 0, 0, NULL, 0); 20613 if (err) 20614 return err; 20615 } 20616 20617 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 20618 verbose(env, "\nfrom %d to %d%s:", 20619 env->prev_insn_idx, env->insn_idx, 20620 env->cur_state->speculative ? 20621 " (speculative execution)" : ""); 20622 print_verifier_state(env, state, state->curframe, true); 20623 do_print_state = false; 20624 } 20625 20626 if (bpf_loop_at_index(env, env->insn_idx) >= 0 && 20627 cur_func(env)->loop_stack_cnt == 0) { 20628 verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n", 20629 env->insn_idx, bpf_loop_at_index(env, env->insn_idx)); 20630 return -EFAULT; 20631 } 20632 20633 if (env->log.level & BPF_LOG_LEVEL) { 20634 if (verifier_state_scratched(env)) 20635 print_insn_state(env, state, state->curframe); 20636 20637 verbose_linfo(env, env->insn_idx, "; "); 20638 env->prev_log_pos = env->log.end_pos; 20639 verbose(env, "%d: ", env->insn_idx); 20640 bpf_verbose_insn(env, insn); 20641 verbose(env, "\n"); 20642 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 20643 env->prev_log_pos = env->log.end_pos; 20644 } 20645 20646 if (bpf_prog_is_offloaded(env->prog->aux)) { 20647 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 20648 env->prev_insn_idx); 20649 if (err) 20650 return err; 20651 } 20652 20653 sanitize_mark_insn_seen(env); 20654 prev_insn_idx = env->insn_idx; 20655 20656 /* Sanity check: precomputed constants must match verifier state */ 20657 if (!state->speculative && insn_aux->const_reg_mask) { 20658 struct bpf_reg_state *regs = cur_regs(env); 20659 u16 mask = insn_aux->const_reg_mask; 20660 20661 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 20662 u32 cval = insn_aux->const_reg_vals[r]; 20663 20664 if (!(mask & BIT(r))) 20665 continue; 20666 if (regs[r].type != SCALAR_VALUE) 20667 continue; 20668 if (!tnum_is_const(regs[r].var_off)) 20669 continue; 20670 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 20671 env, "const R%d: %u != %llu", 20672 r, cval, regs[r].var_off.value)) 20673 return -EFAULT; 20674 } 20675 } 20676 20677 /* Reduce verification complexity by stopping speculative path 20678 * verification when a nospec is encountered. 20679 */ 20680 if (state->speculative && insn_aux->nospec) 20681 goto process_bpf_exit; 20682 20683 err = do_check_insn(env, &do_print_state); 20684 if (error_recoverable_with_nospec(err) && state->speculative) { 20685 /* Prevent this speculative path from ever reaching the 20686 * insn that would have been unsafe to execute. 20687 */ 20688 insn_aux->nospec = true; 20689 /* If it was an ADD/SUB insn, potentially remove any 20690 * markings for alu sanitization. 20691 */ 20692 insn_aux->alu_state = 0; 20693 goto process_bpf_exit; 20694 } else if (err < 0) { 20695 return err; 20696 } else if (err == PROCESS_BPF_EXIT) { 20697 goto process_bpf_exit; 20698 } else if (err == INSN_IDX_UPDATED) { 20699 } else if (err == 0) { 20700 env->insn_idx++; 20701 } 20702 20703 if (state->speculative && insn_aux->nospec_result) { 20704 /* If we are on a path that performed a jump-op, this 20705 * may skip a nospec patched-in after the jump. This can 20706 * currently never happen because nospec_result is only 20707 * used for the write-ops 20708 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 20709 * calls. These must never skip the following insn 20710 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 20711 * is false). Still, add a warning to document this in 20712 * case nospec_result is used elsewhere in the future. 20713 * 20714 * All non-branch instructions have a single 20715 * fall-through edge. For these, nospec_result should 20716 * already work. 20717 */ 20718 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 20719 BPF_CLASS(insn->code) == BPF_JMP32) && 20720 BPF_OP(insn->code) != BPF_CALL, env, 20721 "speculation barrier after jump instruction may not have the desired effect")) 20722 return -EFAULT; 20723 process_bpf_exit: 20724 account_current_path(env); 20725 mark_verifier_state_scratched(env); 20726 err = bpf_update_branch_counts(env, env->cur_state); 20727 if (err) 20728 return err; 20729 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 20730 pop_log); 20731 if (err < 0) { 20732 if (err != -ENOENT) 20733 return err; 20734 break; 20735 } else { 20736 do_print_state = true; 20737 continue; 20738 } 20739 } 20740 } 20741 20742 return 0; 20743 } 20744 20745 static int find_btf_percpu_datasec(struct btf *btf) 20746 { 20747 const struct btf_type *t; 20748 const char *tname; 20749 int i, n; 20750 20751 /* 20752 * Both vmlinux and module each have their own ".data..percpu" 20753 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 20754 * types to look at only module's own BTF types. 20755 */ 20756 n = btf_nr_types(btf); 20757 for (i = btf_named_start_id(btf, true); i < n; i++) { 20758 t = btf_type_by_id(btf, i); 20759 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 20760 continue; 20761 20762 tname = btf_name_by_offset(btf, t->name_off); 20763 if (!strcmp(tname, ".data..percpu")) 20764 return i; 20765 } 20766 20767 return -ENOENT; 20768 } 20769 20770 /* 20771 * Add btf to the env->used_btfs array. If needed, refcount the 20772 * corresponding kernel module. To simplify caller's logic 20773 * in case of error or if btf was added before the function 20774 * decreases the btf refcount. 20775 */ 20776 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 20777 { 20778 struct btf_mod_pair *btf_mod; 20779 int ret = 0; 20780 int i; 20781 20782 /* check whether we recorded this BTF (and maybe module) already */ 20783 for (i = 0; i < env->used_btf_cnt; i++) 20784 if (env->used_btfs[i].btf == btf) 20785 goto ret_put; 20786 20787 if (env->signature) { 20788 verbose(env, "signed program cannot bind any BTF\n"); 20789 ret = -EACCES; 20790 goto ret_put; 20791 } 20792 if (env->used_btf_cnt >= MAX_USED_BTFS) { 20793 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 20794 MAX_USED_BTFS); 20795 ret = -E2BIG; 20796 goto ret_put; 20797 } 20798 20799 btf_mod = &env->used_btfs[env->used_btf_cnt]; 20800 btf_mod->btf = btf; 20801 btf_mod->module = NULL; 20802 20803 /* if we reference variables from kernel module, bump its refcount */ 20804 if (btf_is_module(btf)) { 20805 btf_mod->module = btf_try_get_module(btf); 20806 if (!btf_mod->module) { 20807 ret = -ENXIO; 20808 goto ret_put; 20809 } 20810 } 20811 20812 env->used_btf_cnt++; 20813 return 0; 20814 20815 ret_put: 20816 /* Either error or this BTF was already added */ 20817 btf_put(btf); 20818 return ret; 20819 } 20820 20821 /* replace pseudo btf_id with kernel symbol address */ 20822 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 20823 struct bpf_insn *insn, 20824 struct bpf_insn_aux_data *aux, 20825 struct btf *btf) 20826 { 20827 const struct btf_var_secinfo *vsi; 20828 const struct btf_type *datasec; 20829 const struct btf_type *t; 20830 const char *sym_name; 20831 bool percpu = false; 20832 u32 type, id = insn->imm; 20833 s32 datasec_id; 20834 u64 addr; 20835 int i; 20836 20837 t = btf_type_by_id(btf, id); 20838 if (!t) { 20839 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 20840 return -ENOENT; 20841 } 20842 20843 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 20844 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 20845 return -EINVAL; 20846 } 20847 20848 sym_name = btf_name_by_offset(btf, t->name_off); 20849 addr = kallsyms_lookup_name(sym_name); 20850 if (!addr) { 20851 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 20852 sym_name); 20853 return -ENOENT; 20854 } 20855 insn[0].imm = (u32)addr; 20856 insn[1].imm = addr >> 32; 20857 20858 if (btf_type_is_func(t)) { 20859 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20860 aux->btf_var.mem_size = 0; 20861 return 0; 20862 } 20863 20864 datasec_id = find_btf_percpu_datasec(btf); 20865 if (datasec_id > 0) { 20866 datasec = btf_type_by_id(btf, datasec_id); 20867 for_each_vsi(i, datasec, vsi) { 20868 if (vsi->type == id) { 20869 percpu = true; 20870 break; 20871 } 20872 } 20873 } 20874 20875 type = t->type; 20876 t = btf_type_skip_modifiers(btf, type, NULL); 20877 if (percpu) { 20878 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 20879 aux->btf_var.btf = btf; 20880 aux->btf_var.btf_id = type; 20881 } else if (!btf_type_is_struct(t)) { 20882 const struct btf_type *ret; 20883 const char *tname; 20884 u32 tsize; 20885 20886 /* resolve the type size of ksym. */ 20887 ret = btf_resolve_size(btf, t, &tsize); 20888 if (IS_ERR(ret)) { 20889 tname = btf_name_by_offset(btf, t->name_off); 20890 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 20891 tname, PTR_ERR(ret)); 20892 return -EINVAL; 20893 } 20894 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20895 aux->btf_var.mem_size = tsize; 20896 } else { 20897 aux->btf_var.reg_type = PTR_TO_BTF_ID; 20898 aux->btf_var.btf = btf; 20899 aux->btf_var.btf_id = type; 20900 } 20901 20902 return 0; 20903 } 20904 20905 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 20906 struct bpf_insn *insn, 20907 struct bpf_insn_aux_data *aux) 20908 { 20909 struct btf *btf; 20910 int btf_fd; 20911 int err; 20912 20913 btf_fd = insn[1].imm; 20914 if (btf_fd) { 20915 btf = btf_get_by_fd(btf_fd); 20916 if (IS_ERR(btf)) { 20917 verbose(env, "invalid module BTF object FD specified.\n"); 20918 return -EINVAL; 20919 } 20920 } else { 20921 if (!btf_vmlinux) { 20922 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 20923 return -EINVAL; 20924 } 20925 btf_get(btf_vmlinux); 20926 btf = btf_vmlinux; 20927 } 20928 20929 err = __check_pseudo_btf_id(env, insn, aux, btf); 20930 if (err) { 20931 btf_put(btf); 20932 return err; 20933 } 20934 20935 return __add_used_btf(env, btf); 20936 } 20937 20938 static bool is_tracing_prog_type(enum bpf_prog_type type) 20939 { 20940 switch (type) { 20941 case BPF_PROG_TYPE_KPROBE: 20942 case BPF_PROG_TYPE_TRACEPOINT: 20943 case BPF_PROG_TYPE_PERF_EVENT: 20944 case BPF_PROG_TYPE_RAW_TRACEPOINT: 20945 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 20946 return true; 20947 default: 20948 return false; 20949 } 20950 } 20951 20952 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 20953 { 20954 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 20955 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 20956 } 20957 20958 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 20959 struct bpf_map *map, 20960 struct bpf_prog *prog) 20961 20962 { 20963 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20964 20965 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 20966 btf_record_has_field(map->record, BPF_RB_ROOT)) { 20967 if (is_tracing_prog_type(prog_type)) { 20968 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 20969 return -EINVAL; 20970 } 20971 } 20972 20973 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 20974 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 20975 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 20976 return -EINVAL; 20977 } 20978 } 20979 20980 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 20981 if (is_tracing_prog_type(prog_type)) { 20982 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 20983 return -EINVAL; 20984 } 20985 } 20986 20987 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 20988 !bpf_offload_prog_map_match(prog, map)) { 20989 verbose(env, "offload device mismatch between prog and map\n"); 20990 return -EINVAL; 20991 } 20992 20993 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 20994 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 20995 return -EINVAL; 20996 } 20997 20998 if (prog->sleepable && !map_needs_no_rcu(map)) { 20999 verbose(env, 21000 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 21001 return -EINVAL; 21002 } 21003 21004 if (bpf_map_is_cgroup_storage(map) && 21005 bpf_cgroup_storage_assign(env->prog->aux, map)) { 21006 verbose(env, "only one cgroup storage of each type is allowed\n"); 21007 return -EBUSY; 21008 } 21009 21010 if (map->map_type == BPF_MAP_TYPE_ARENA) { 21011 if (env->prog->aux->arena) { 21012 verbose(env, "Only one arena per program\n"); 21013 return -EBUSY; 21014 } 21015 if (!env->allow_ptr_leaks || !env->bpf_capable) { 21016 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 21017 return -EPERM; 21018 } 21019 if (!env->prog->jit_requested) { 21020 verbose(env, "JIT is required to use arena\n"); 21021 return -EOPNOTSUPP; 21022 } 21023 if (!bpf_jit_supports_arena()) { 21024 verbose(env, "JIT doesn't support arena\n"); 21025 return -EOPNOTSUPP; 21026 } 21027 env->prog->aux->arena = (void *)map; 21028 env->prog->jit_required = true; 21029 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 21030 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 21031 return -EINVAL; 21032 } 21033 } 21034 21035 return 0; 21036 } 21037 21038 /* 21039 * Keep track of whether the map is used by one program only. Such program may 21040 * store the addresses of its functions into the map when it's frozen, see 21041 * resolve_func_ptrs(), since nothing else relies on what the map has. After 21042 * that the map is not available to other programs. 21043 */ 21044 static int bpf_map_claim(struct bpf_verifier_env *env, struct bpf_map *map) 21045 { 21046 unsigned long me = (unsigned long)env->prog->aux, old; 21047 21048 for (;;) { 21049 old = READ_ONCE(map->user); 21050 if (old == me || old == BPF_MAP_USER_MANY) 21051 return 0; 21052 if (old & BPF_MAP_USER_PATCHED) { 21053 verbose(env, "map '%s' has addresses of functions of another program\n", 21054 map->name); 21055 return -EBUSY; 21056 } 21057 if (cmpxchg(&map->user, old, old ? BPF_MAP_USER_MANY : me) == old) 21058 return 0; 21059 } 21060 } 21061 21062 /* 21063 * An exclusive map is bound to the digest of its program. The digest covers 21064 * the insns as they are verified, after the CO-RE relocations the kernel 21065 * applies, so it exists only once check_and_resolve_insns() has computed it, 21066 * and the maps are checked against it there, whether an insn referred to 21067 * them or a continuous fd_array bound them before. 21068 */ 21069 static int check_excl_maps(struct bpf_verifier_env *env) 21070 { 21071 int i; 21072 21073 for (i = 0; i < env->used_map_cnt; i++) { 21074 struct bpf_map *map = env->used_maps[i]; 21075 21076 if (map->excl_prog_sha && 21077 memcmp(map->excl_prog_sha, env->prog->digest, SHA256_DIGEST_SIZE)) { 21078 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 21079 return -EACCES; 21080 } 21081 } 21082 return 0; 21083 } 21084 21085 /* 21086 * The program may use every map it referred to, see check_excl_maps(). Only now 21087 * does it leave a trace on them: it claims each as its user, see 21088 * bpf_map_claim(), and takes over its insn arrays. A program rejected before 21089 * this point, one that is not the owner of an exclusive map in particular, 21090 * leaves the maps as it found them. Nothing consults a claim before 21091 * resolve_func_ptrs() and the fixup passes, which run later. 21092 */ 21093 static int claim_used_maps(struct bpf_verifier_env *env) 21094 { 21095 int i, err; 21096 21097 for (i = 0; i < env->used_map_cnt; i++) { 21098 struct bpf_map *map = env->used_maps[i]; 21099 21100 err = bpf_map_claim(env, map); 21101 if (err) 21102 return err; 21103 21104 if (map->map_type != BPF_MAP_TYPE_INSN_ARRAY) 21105 continue; 21106 err = bpf_insn_array_init(map, env->prog); 21107 if (err) { 21108 verbose(env, "Failed to properly initialize insn array\n"); 21109 return err; 21110 } 21111 env->insn_array_maps[env->insn_array_map_cnt++] = map; 21112 env->prog->jit_required = true; 21113 } 21114 return 0; 21115 } 21116 21117 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 21118 { 21119 int i, err; 21120 21121 /* check whether we recorded this map already */ 21122 for (i = 0; i < env->used_map_cnt; i++) 21123 if (env->used_maps[i] == map) 21124 return i; 21125 21126 if (env->signature && 21127 env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) { 21128 verbose(env, "signed program cannot bind map '%s' not covered by the signature\n", 21129 map->name); 21130 return -EACCES; 21131 } 21132 if (env->used_map_cnt >= MAX_USED_MAPS) { 21133 verbose(env, "The total number of maps per program has reached the limit of %u\n", 21134 MAX_USED_MAPS); 21135 return -E2BIG; 21136 } 21137 21138 err = check_map_prog_compatibility(env, map, env->prog); 21139 if (err) 21140 return err; 21141 21142 if (bpf_prog_runs_sleepable(env->prog)) 21143 atomic64_inc(&map->sleepable_refcnt); 21144 21145 /* hold the map. If the program is rejected by verifier, 21146 * the map will be released by release_maps() or it 21147 * will be used by the valid program until it's unloaded 21148 * and all maps are released in bpf_free_used_maps() 21149 */ 21150 bpf_map_inc(map); 21151 21152 env->used_maps[env->used_map_cnt++] = map; 21153 21154 return env->used_map_cnt - 1; 21155 } 21156 21157 /* Add map behind fd to used maps list, if it's not already there, and return 21158 * its index. 21159 * Returns <0 on error, or >= 0 index, on success. 21160 */ 21161 static int add_used_map(struct bpf_verifier_env *env, int fd) 21162 { 21163 struct bpf_map *map; 21164 CLASS(fd, f)(fd); 21165 21166 map = __bpf_map_get(f); 21167 if (IS_ERR(map)) { 21168 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 21169 return PTR_ERR(map); 21170 } 21171 21172 return __add_used_map(env, map); 21173 } 21174 21175 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx) 21176 { 21177 struct bpf_map *map; 21178 21179 if (idx >= env->fd_array_cnt) { 21180 verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n", 21181 idx, env->fd_array_cnt); 21182 return -EINVAL; 21183 } 21184 map = fd_slot_map(env->fd_array[idx]); 21185 if (!map) { 21186 verbose(env, "fd_idx %u is not a map\n", idx); 21187 return -EINVAL; 21188 } 21189 return __add_used_map(env, map); 21190 } 21191 21192 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx) 21193 { 21194 int fd; 21195 21196 if (copy_from_bpfptr_offset(&fd, env->fd_array_raw, 21197 (size_t)idx * sizeof(fd), sizeof(fd))) 21198 return -EFAULT; 21199 return add_used_map(env, fd); 21200 } 21201 21202 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx) 21203 { 21204 if (env->fd_array) 21205 return fd_array_get_map_idx_continuous(env, idx); 21206 if (env->signature) { 21207 verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n"); 21208 return -EACCES; 21209 } 21210 if (!bpfptr_is_null(env->fd_array_raw)) 21211 return fd_array_get_map_idx_sparse(env, idx); 21212 21213 verbose(env, "fd_idx without fd_array is invalid\n"); 21214 return -EPROTO; 21215 } 21216 21217 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 21218 { 21219 u8 class = BPF_CLASS(insn->code); 21220 u8 opcode = BPF_OP(insn->code); 21221 21222 switch (opcode) { 21223 case BPF_NEG: 21224 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 21225 insn->off != 0 || insn->imm != 0) { 21226 verbose(env, "BPF_NEG uses reserved fields\n"); 21227 return -EINVAL; 21228 } 21229 return 0; 21230 case BPF_END: 21231 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 21232 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 21233 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 21234 verbose(env, "BPF_END uses reserved fields\n"); 21235 return -EINVAL; 21236 } 21237 return 0; 21238 case BPF_MOV: 21239 if (BPF_SRC(insn->code) == BPF_X) { 21240 if (class == BPF_ALU) { 21241 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 21242 insn->imm) { 21243 verbose(env, "BPF_MOV uses reserved fields\n"); 21244 return -EINVAL; 21245 } 21246 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 21247 if (insn->imm != 1 && insn->imm != 1u << 16) { 21248 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 21249 return -EINVAL; 21250 } 21251 } else if ((insn->off != 0 && insn->off != 8 && 21252 insn->off != 16 && insn->off != 32) || insn->imm) { 21253 verbose(env, "BPF_MOV uses reserved fields\n"); 21254 return -EINVAL; 21255 } 21256 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 21257 verbose(env, "BPF_MOV uses reserved fields\n"); 21258 return -EINVAL; 21259 } 21260 return 0; 21261 case BPF_ADD: 21262 case BPF_SUB: 21263 case BPF_AND: 21264 case BPF_OR: 21265 case BPF_XOR: 21266 case BPF_LSH: 21267 case BPF_RSH: 21268 case BPF_ARSH: 21269 case BPF_MUL: 21270 case BPF_DIV: 21271 case BPF_MOD: 21272 if (BPF_SRC(insn->code) == BPF_X) { 21273 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 21274 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 21275 verbose(env, "BPF_ALU uses reserved fields\n"); 21276 return -EINVAL; 21277 } 21278 } else if (insn->src_reg != BPF_REG_0 || 21279 (insn->off != 0 && insn->off != 1) || 21280 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 21281 verbose(env, "BPF_ALU uses reserved fields\n"); 21282 return -EINVAL; 21283 } 21284 return 0; 21285 default: 21286 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 21287 return -EINVAL; 21288 } 21289 } 21290 21291 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 21292 { 21293 u8 class = BPF_CLASS(insn->code); 21294 u8 opcode = BPF_OP(insn->code); 21295 21296 switch (opcode) { 21297 case BPF_CALL: 21298 if (bpf_is_callx(insn)) { 21299 /* callx dst_reg */ 21300 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 21301 verbose(env, "BPF_CALL|BPF_X uses reserved fields\n"); 21302 return -EINVAL; 21303 } 21304 return 0; 21305 } 21306 if (BPF_SRC(insn->code) != BPF_K || 21307 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 21308 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 21309 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 21310 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 21311 verbose(env, "BPF_CALL uses reserved fields\n"); 21312 return -EINVAL; 21313 } 21314 return 0; 21315 case BPF_JA: 21316 if (BPF_SRC(insn->code) == BPF_X) { 21317 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 21318 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 21319 return -EINVAL; 21320 } 21321 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 21322 (class == BPF_JMP && insn->imm != 0) || 21323 (class == BPF_JMP32 && insn->off != 0)) { 21324 verbose(env, "BPF_JA uses reserved fields\n"); 21325 return -EINVAL; 21326 } 21327 return 0; 21328 case BPF_EXIT: 21329 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 21330 insn->src_reg > BPF_UNWIND_EXIT || insn->dst_reg != BPF_REG_0 || 21331 class == BPF_JMP32) { 21332 verbose(env, "BPF_EXIT uses reserved fields\n"); 21333 return -EINVAL; 21334 } 21335 return 0; 21336 case BPF_JCOND: 21337 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg > BPF_UNWIND_GOTO || 21338 insn->dst_reg || insn->imm) { 21339 verbose(env, "invalid may_goto imm %d\n", insn->imm); 21340 return -EINVAL; 21341 } 21342 return 0; 21343 default: 21344 if (BPF_SRC(insn->code) == BPF_X) { 21345 if (insn->imm != 0) { 21346 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 21347 return -EINVAL; 21348 } 21349 } else if (insn->src_reg != BPF_REG_0) { 21350 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 21351 return -EINVAL; 21352 } 21353 return 0; 21354 } 21355 } 21356 21357 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 21358 { 21359 switch (BPF_CLASS(insn->code)) { 21360 case BPF_ALU: 21361 case BPF_ALU64: 21362 return check_alu_fields(env, insn); 21363 case BPF_LDX: 21364 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 21365 insn->imm != 0) { 21366 verbose(env, "BPF_LDX uses reserved fields\n"); 21367 return -EINVAL; 21368 } 21369 return 0; 21370 case BPF_STX: 21371 if (BPF_MODE(insn->code) == BPF_ATOMIC) 21372 return 0; 21373 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 21374 verbose(env, "BPF_STX uses reserved fields\n"); 21375 return -EINVAL; 21376 } 21377 return 0; 21378 case BPF_ST: 21379 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 21380 verbose(env, "BPF_ST uses reserved fields\n"); 21381 return -EINVAL; 21382 } 21383 return 0; 21384 case BPF_JMP: 21385 case BPF_JMP32: 21386 return check_jmp_fields(env, insn); 21387 case BPF_LD: { 21388 u8 mode = BPF_MODE(insn->code); 21389 21390 if (mode == BPF_ABS || mode == BPF_IND) { 21391 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 21392 BPF_SIZE(insn->code) == BPF_DW || 21393 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 21394 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 21395 return -EINVAL; 21396 } 21397 } else if (mode != BPF_IMM) { 21398 verbose(env, "invalid BPF_LD mode\n"); 21399 return -EINVAL; 21400 } 21401 return 0; 21402 } 21403 default: 21404 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 21405 return -EINVAL; 21406 } 21407 } 21408 21409 /* 21410 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 21411 * 21412 * 1. if it accesses map FD, replace it with actual map pointer. 21413 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 21414 * 21415 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 21416 */ 21417 static int check_and_resolve_insns(struct bpf_verifier_env *env) 21418 { 21419 struct bpf_insn *insn = env->prog->insnsi; 21420 int insn_cnt = env->prog->len; 21421 int i, err; 21422 21423 err = bpf_prog_calc_tag(env->prog); 21424 if (err) 21425 return err; 21426 21427 for (i = 0; i < insn_cnt; i++, insn++) { 21428 if (insn->dst_reg >= MAX_BPF_REG && 21429 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 21430 verbose(env, "R%d is invalid\n", insn->dst_reg); 21431 return -EINVAL; 21432 } 21433 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 21434 verbose(env, "R%d is invalid\n", insn->src_reg); 21435 return -EINVAL; 21436 } 21437 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 21438 struct bpf_insn_aux_data *aux; 21439 struct bpf_map *map; 21440 int map_idx; 21441 u64 addr; 21442 21443 if (i == insn_cnt - 1 || insn[1].code != 0 || 21444 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 21445 insn[1].off != 0) { 21446 verbose(env, "invalid bpf_ld_imm64 insn\n"); 21447 return -EINVAL; 21448 } 21449 21450 if (insn[0].off != 0) { 21451 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 21452 return -EINVAL; 21453 } 21454 21455 if (insn[0].src_reg == 0) 21456 /* valid generic load 64-bit imm */ 21457 goto next_insn; 21458 21459 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 21460 aux = &env->insn_aux_data[i]; 21461 err = check_pseudo_btf_id(env, insn, aux); 21462 if (err) 21463 return err; 21464 goto next_insn; 21465 } 21466 21467 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 21468 aux = &env->insn_aux_data[i]; 21469 aux->ptr_type = PTR_TO_FUNC; 21470 goto next_insn; 21471 } 21472 21473 /* In final convert_pseudo_ld_imm64() step, this is 21474 * converted into regular 64-bit imm load insn. 21475 */ 21476 switch (insn[0].src_reg) { 21477 case BPF_PSEUDO_MAP_VALUE: 21478 case BPF_PSEUDO_MAP_IDX_VALUE: 21479 break; 21480 case BPF_PSEUDO_MAP_FD: 21481 case BPF_PSEUDO_MAP_IDX: 21482 if (insn[1].imm == 0) 21483 break; 21484 fallthrough; 21485 default: 21486 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 21487 return -EINVAL; 21488 } 21489 21490 switch (insn[0].src_reg) { 21491 case BPF_PSEUDO_MAP_IDX_VALUE: 21492 case BPF_PSEUDO_MAP_IDX: 21493 map_idx = fd_array_get_map_idx(env, insn[0].imm); 21494 break; 21495 default: 21496 if (env->signature) { 21497 verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n"); 21498 return -EINVAL; 21499 } 21500 map_idx = add_used_map(env, insn[0].imm); 21501 break; 21502 } 21503 21504 if (map_idx < 0) 21505 return map_idx; 21506 map = env->used_maps[map_idx]; 21507 21508 aux = &env->insn_aux_data[i]; 21509 aux->map_index = map_idx; 21510 21511 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 21512 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 21513 addr = (unsigned long)map; 21514 } else { 21515 u32 off = insn[1].imm; 21516 21517 if (!map->ops->map_direct_value_addr) { 21518 verbose(env, "no direct value access support for this map type\n"); 21519 return -EINVAL; 21520 } 21521 21522 err = map->ops->map_direct_value_addr(map, &addr, off); 21523 if (err) { 21524 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 21525 map->value_size, off); 21526 return err; 21527 } 21528 21529 aux->map_off = off; 21530 addr += off; 21531 } 21532 21533 insn[0].imm = (u32)addr; 21534 insn[1].imm = addr >> 32; 21535 21536 next_insn: 21537 insn++; 21538 i++; 21539 continue; 21540 } 21541 21542 /* Basic sanity check before we invest more work here. */ 21543 if (!bpf_opcode_in_insntable(insn->code)) { 21544 verbose(env, "unknown opcode %02x\n", insn->code); 21545 return -EINVAL; 21546 } 21547 21548 err = check_insn_fields(env, insn); 21549 if (err) 21550 return err; 21551 } 21552 21553 /* now all pseudo BPF_LD_IMM64 instructions load valid 21554 * 'struct bpf_map *' into a register instead of user map_fd. 21555 * These pointers will be used later by verifier to validate map access. 21556 */ 21557 err = check_excl_maps(env); 21558 if (err) 21559 return err; 21560 return claim_used_maps(env); 21561 } 21562 21563 /* that many pointers to functions are recognized in the maps of a program at most */ 21564 #define BPF_MAX_FUNC_PTRS (1 << 20) 21565 21566 static int add_func_ptr(struct bpf_verifier_env *env, struct bpf_map *map, u32 map_off, 21567 u32 xlated_off) 21568 { 21569 struct bpf_func_ptr *ptrs; 21570 21571 if (env->func_ptr_cnt == BPF_MAX_FUNC_PTRS) { 21572 verbose(env, "too many pointers to functions in maps, the limit is %d\n", 21573 BPF_MAX_FUNC_PTRS); 21574 return -E2BIG; 21575 } 21576 21577 /* grow by doubling, the array is sorted and searched later */ 21578 if (!(env->func_ptr_cnt & (env->func_ptr_cnt - 1))) { 21579 ptrs = kvrealloc(env->func_ptrs, 21580 array_size(max(2 * env->func_ptr_cnt, 16U), sizeof(*ptrs)), 21581 GFP_KERNEL_ACCOUNT); 21582 if (!ptrs) 21583 return -ENOMEM; 21584 env->func_ptrs = ptrs; 21585 } 21586 env->func_ptrs[env->func_ptr_cnt++] = (struct bpf_func_ptr){ 21587 .map = map, 21588 .map_off = map_off, 21589 .orig_off = xlated_off, 21590 .xlated_off = xlated_off, 21591 }; 21592 return 0; 21593 } 21594 21595 /* 21596 * Compilers put pointers to functions into read-only data: tables of functions, 21597 * structures of operations, vtables, where they are mixed with other data. 21598 * The loader stores such data in a frozen read-only array map and resolves 21599 * a pointer to a static function to the offset in bytes of its first 21600 * instruction in the program: the address of the function in the program. 21601 * 21602 * Find 64-bit values that look like that in the maps of a program that uses 21603 * callx. It's a guess. When the value is not a pointer, the program either 21604 * fails to load, because it does with a pointer what can be done with 21605 * a number only, or it sees the address of a function instead of the number. 21606 * It's known before the control flow graph of the program is built and the main 21607 * verification pass begins which functions may be called via callx. 21608 * 21609 * When the program is jitted the offsets are replaced with the addresses of 21610 * the functions in the map itself, see jit_subprogs(). Hence the program has to 21611 * be the only user of the map, see bpf_map_claim(): nothing else may rely on 21612 * what the map had. 21613 * 21614 * The program reads the addresses of its functions from there like any other 21615 * data, so it has to be allowed to leak pointers. 21616 */ 21617 static int resolve_func_ptrs(struct bpf_verifier_env *env) 21618 { 21619 int insn_cnt = env->prog->len; 21620 int i, err, subprog; 21621 struct bpf_map *map; 21622 u64 addr, val; 21623 u32 off; 21624 21625 if (!env->has_callx || !env->allow_ptr_leaks) 21626 return 0; 21627 21628 for (i = 0; i < env->used_map_cnt; i++) { 21629 map = env->used_maps[i]; 21630 /* coincidences in maps that are shared with other programs don't matter */ 21631 if (READ_ONCE(map->user) != (unsigned long)env->prog->aux) 21632 continue; 21633 if (map->map_type != BPF_MAP_TYPE_ARRAY || map->max_entries != 1 || 21634 !bpf_map_is_rdonly(map) || !map->ops->map_direct_value_addr || 21635 !IS_ERR_OR_NULL(map->record)) 21636 continue; 21637 if (map->ops->map_direct_value_addr(map, &addr, 0)) 21638 continue; 21639 21640 for (off = 0; off + sizeof(u64) <= map->value_size; off += sizeof(u64)) { 21641 if (!(off % SZ_64K)) 21642 cond_resched(); 21643 val = *(u64 *)(unsigned long)(addr + off); 21644 if (!val || val % sizeof(struct bpf_insn) || 21645 val / sizeof(struct bpf_insn) >= insn_cnt) 21646 continue; 21647 subprog = bpf_find_subprog(env, val / sizeof(struct bpf_insn)); 21648 if (subprog <= 0 || bpf_subprog_is_global(env, subprog)) 21649 continue; 21650 err = add_func_ptr(env, map, off, val / sizeof(struct bpf_insn)); 21651 if (err) 21652 return err; 21653 } 21654 } 21655 if (env->func_ptr_cnt) 21656 sort(env->func_ptrs, env->func_ptr_cnt, sizeof(*env->func_ptrs), 21657 cmp_func_ptrs, NULL); 21658 return 0; 21659 } 21660 21661 /* drop refcnt of maps used by the rejected program */ 21662 static void release_maps(struct bpf_verifier_env *env) 21663 { 21664 __bpf_free_used_maps(env->prog->aux, env->used_maps, 21665 env->used_map_cnt); 21666 } 21667 21668 /* drop refcnt of maps used by the rejected program */ 21669 static void release_btfs(struct bpf_verifier_env *env) 21670 { 21671 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 21672 } 21673 21674 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 21675 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 21676 { 21677 struct bpf_insn *insn = env->prog->insnsi; 21678 int insn_cnt = env->prog->len; 21679 int i; 21680 21681 for (i = 0; i < insn_cnt; i++, insn++) { 21682 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 21683 continue; 21684 if (insn->src_reg == BPF_PSEUDO_FUNC) 21685 continue; 21686 insn->src_reg = 0; 21687 } 21688 } 21689 21690 static void release_insn_arrays(struct bpf_verifier_env *env) 21691 { 21692 int i; 21693 21694 for (i = 0; i < env->insn_array_map_cnt; i++) 21695 bpf_insn_array_release(env->insn_array_maps[i]); 21696 } 21697 21698 /* The verifier does more data flow analysis than llvm and will not 21699 * explore branches that are dead at run time. Malicious programs can 21700 * have dead code too. Therefore replace all dead at-run-time code 21701 * with 'ja -1'. 21702 * 21703 * Just nops are not optimal, e.g. if they would sit at the end of the 21704 * program and through another bug we would manage to jump there, then 21705 * we'd execute beyond program memory otherwise. Returning exception 21706 * code also wouldn't work since we can have subprogs where the dead 21707 * code could be located. 21708 */ 21709 static void sanitize_dead_code(struct bpf_verifier_env *env) 21710 { 21711 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21712 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 21713 struct bpf_insn *insn = env->prog->insnsi; 21714 const int insn_cnt = env->prog->len; 21715 int i; 21716 21717 for (i = 0; i < insn_cnt; i++) { 21718 if (aux_data[i].seen) 21719 continue; 21720 memcpy(insn + i, &trap, sizeof(trap)); 21721 aux_data[i].zext_dst = false; 21722 } 21723 } 21724 21725 static void free_states(struct bpf_verifier_env *env) 21726 { 21727 struct bpf_verifier_state_list *sl; 21728 struct list_head *head, *pos, *tmp; 21729 struct bpf_scc_info *info; 21730 int i, j; 21731 21732 bpf_free_verifier_state(env->cur_state, true); 21733 env->cur_state = NULL; 21734 while (!pop_stack(env, NULL, NULL, false)); 21735 21736 list_for_each_safe(pos, tmp, &env->free_list) { 21737 sl = container_of(pos, struct bpf_verifier_state_list, node); 21738 bpf_free_verifier_state(&sl->state, false); 21739 kfree(sl); 21740 } 21741 INIT_LIST_HEAD(&env->free_list); 21742 21743 for (i = 0; i < env->scc_cnt; ++i) { 21744 info = env->scc_info[i]; 21745 if (!info) 21746 continue; 21747 for (j = 0; j < info->num_visits; j++) 21748 bpf_free_backedges(&info->visits[j]); 21749 kvfree(info); 21750 env->scc_info[i] = NULL; 21751 } 21752 21753 if (!env->explored_states) 21754 return; 21755 21756 for (i = 0; i < state_htab_size(env); i++) { 21757 head = &env->explored_states[i]; 21758 21759 list_for_each_safe(pos, tmp, head) { 21760 sl = container_of(pos, struct bpf_verifier_state_list, node); 21761 bpf_free_verifier_state(&sl->state, false); 21762 kfree(sl); 21763 } 21764 INIT_LIST_HEAD(&env->explored_states[i]); 21765 } 21766 } 21767 21768 static int do_check_common(struct bpf_verifier_env *env, int subprog, 21769 enum bpf_func_context context) 21770 { 21771 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 21772 struct bpf_subprog_info *sub = subprog_info(env, subprog); 21773 struct bpf_prog_aux *aux = env->prog->aux; 21774 struct bpf_verifier_state *state; 21775 struct bpf_reg_state *regs; 21776 u32 old_insns_total = sub->insns_total; 21777 u32 insn_processed = env->insn_processed; 21778 int ret, i; 21779 21780 env->prev_linfo = NULL; 21781 env->pass_cnt++; 21782 21783 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 21784 if (!state) 21785 return -ENOMEM; 21786 state->curframe = 0; 21787 state->speculative = false; 21788 state->branches = 1; 21789 state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE; 21790 env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK; 21791 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 21792 if (!state->frame[0]) { 21793 kfree(state); 21794 return -ENOMEM; 21795 } 21796 env->cur_state = state; 21797 init_func_state(env, state->frame[0], 21798 BPF_MAIN_FUNC /* callsite */, 21799 0 /* frameno */, 21800 subprog); 21801 state->first_insn_idx = env->subprog_info[subprog].start; 21802 state->last_insn_idx = -1; 21803 21804 regs = state->frame[state->curframe]->regs; 21805 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 21806 const char *sub_name = bpf_subprog_name(env, subprog); 21807 struct bpf_subprog_arg_info *arg; 21808 struct bpf_reg_state *reg; 21809 21810 if (env->log.level & BPF_LOG_LEVEL) 21811 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 21812 ret = btf_prepare_func_args(env, subprog); 21813 if (ret) 21814 goto out; 21815 21816 if (subprog_is_exc_cb(env, subprog)) { 21817 state->frame[0]->in_exception_callback_fn = true; 21818 21819 /* 21820 * Global functions are scalar or void, make sure 21821 * we return a scalar. 21822 */ 21823 if (subprog_returns_void(env, subprog)) { 21824 verbose(env, "exception cb cannot return void\n"); 21825 ret = -EINVAL; 21826 goto out; 21827 } 21828 21829 /* Also ensure the callback only has a single scalar argument. */ 21830 if (sub->arg_slot_cnt != 1 || sub->args[0].arg_type != ARG_SCALAR) { 21831 verbose(env, "exception cb only supports single integer argument\n"); 21832 ret = -EINVAL; 21833 goto out; 21834 } 21835 } 21836 for (i = BPF_REG_1; 21837 i <= min_t(u32, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 21838 arg = &sub->args[i - BPF_REG_1]; 21839 reg = ®s[i]; 21840 21841 if (arg->arg_type == ARG_PTR_TO_CTX) { 21842 reg->type = PTR_TO_CTX; 21843 mark_reg_known_zero(env, regs, i); 21844 } else if (arg->arg_type == ARG_SCALAR) { 21845 reg->type = SCALAR_VALUE; 21846 mark_reg_unknown(env, regs, i); 21847 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 21848 /* 21849 * The callers may hand in a dynptr of any type. 21850 * Take it for that of an skb, so that a write 21851 * through it and its slices are treated with care. 21852 */ 21853 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen, 0); 21854 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 21855 reg->type = PTR_TO_MEM; 21856 reg->type |= arg->arg_type & 21857 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 21858 mark_reg_known_zero(env, regs, i); 21859 reg->mem_size = arg->mem_size; 21860 if (arg->arg_type & PTR_MAYBE_NULL) 21861 reg->id = ++env->id_gen; 21862 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 21863 reg->type = PTR_TO_BTF_ID; 21864 if (arg->arg_type & PTR_MAYBE_NULL) 21865 reg->type |= PTR_MAYBE_NULL; 21866 if (arg->arg_type & PTR_UNTRUSTED) 21867 reg->type |= PTR_UNTRUSTED; 21868 if (arg->arg_type & PTR_TRUSTED) 21869 reg->type |= PTR_TRUSTED; 21870 mark_reg_known_zero(env, regs, i); 21871 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 21872 reg->btf_id = arg->btf_id; 21873 reg->id = ++env->id_gen; 21874 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 21875 /* caller can pass either PTR_TO_ARENA or SCALAR */ 21876 mark_reg_unknown(env, regs, i); 21877 } else { 21878 verifier_bug(env, "unhandled arg#%d type %d", 21879 i - BPF_REG_1 + 1, arg->arg_type); 21880 ret = -EFAULT; 21881 goto out; 21882 } 21883 } 21884 if (env->prog->type == BPF_PROG_TYPE_EXT && 21885 sub->arg_slot_cnt > MAX_BPF_FUNC_REG_ARGS) { 21886 verbose(env, "freplace programs with >%d args not supported yet\n", 21887 MAX_BPF_FUNC_REG_ARGS); 21888 ret = -EINVAL; 21889 goto out; 21890 } 21891 } else { 21892 /* if main BPF program has associated BTF info, validate that 21893 * it's matching expected signature, and otherwise mark BTF 21894 * info for main program as unreliable 21895 */ 21896 if (env->prog->aux->func_info_aux) { 21897 ret = btf_prepare_func_args(env, 0); 21898 if (ret || sub->arg_slot_cnt != 1 || 21899 sub->args[0].arg_type != ARG_PTR_TO_CTX) { 21900 env->prog->aux->func_info_aux[0].unreliable = true; 21901 sub->arg_slot_cnt = 1; 21902 sub->stack_arg_cnt = 0; 21903 } 21904 } 21905 21906 /* 1st arg to a function */ 21907 regs[BPF_REG_1].type = PTR_TO_CTX; 21908 mark_reg_known_zero(env, regs, BPF_REG_1); 21909 } 21910 21911 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 21912 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 21913 for (i = 0; i < aux->ctx_arg_info_size; i++) { 21914 ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0; 21915 if (ret < 0) 21916 goto out; 21917 21918 aux->ctx_arg_info[i].ref_id = ret; 21919 } 21920 } 21921 21922 ret = do_check(env); 21923 out: 21924 account_current_path(env); 21925 if (!ret) { 21926 if (pop_log) 21927 bpf_vlog_reset(&env->log, 0); 21928 bpf_diag_event_log_restore(env, 0); 21929 } 21930 free_states(env); 21931 21932 /* 21933 * The override is needed to account for async subprograms, which 21934 * are verified with their own set of stack frames and thus are 21935 * not accounted as callees by account_current_path(). 21936 * Accumulate their total counts as total counts of the main or 21937 * global subprog hosting the async call. 21938 * Start from the saved total of earlier contexts: adding to the current 21939 * total would count this pass's synchronous paths twice. 21940 */ 21941 sub->insns_total = old_insns_total + (env->insn_processed - insn_processed); 21942 return ret; 21943 } 21944 21945 /* Lazily verify all global functions based on their BTF, if they are called 21946 * from main BPF program or any of subprograms transitively. 21947 * BPF global subprogs called from dead code are not validated. 21948 * All callable global functions must pass verification. 21949 * Otherwise the whole program is rejected. 21950 * Consider: 21951 * int bar(int); 21952 * int foo(int f) 21953 * { 21954 * return bar(f); 21955 * } 21956 * int bar(int b) 21957 * { 21958 * ... 21959 * } 21960 * foo() will be verified first for R1=any_scalar_value. During verification it 21961 * will be assumed that bar() already verified successfully and call to bar() 21962 * from foo() will be checked for type match only. Later bar() will be verified 21963 * independently to check that it's safe for R1=any_scalar_value. 21964 */ 21965 static int do_check_subprogs(struct bpf_verifier_env *env) 21966 { 21967 struct bpf_prog_aux *aux = env->prog->aux; 21968 struct bpf_func_info_aux *sub_aux; 21969 int context, i, ret, new_cnt; 21970 21971 if (!aux->func_info) 21972 return 0; 21973 21974 /* 21975 * Callbacks cannot throw, so the exception callback always runs in the 21976 * main program's context. It is presumed to be always called. 21977 */ 21978 if (env->exception_callback_subprog) { 21979 sub_aux = subprog_aux(env, env->exception_callback_subprog); 21980 sub_aux->called[env->prog->sleepable] = true; 21981 } 21982 21983 again: 21984 new_cnt = 0; 21985 for (i = 1; i < env->subprog_cnt; i++) { 21986 if (!bpf_subprog_is_global(env, i)) 21987 continue; 21988 21989 sub_aux = subprog_aux(env, i); 21990 for (context = 0; context < ARRAY_SIZE(sub_aux->called); context++) { 21991 if (!sub_aux->called[context] || sub_aux->verified[context]) 21992 continue; 21993 21994 env->insn_idx = env->subprog_info[i].start; 21995 WARN_ON_ONCE(env->insn_idx == 0); 21996 ret = do_check_common(env, i, context); 21997 if (ret) 21998 return ret; 21999 if (env->log.level & BPF_LOG_LEVEL) 22000 verbose(env, "Func#%d ('%s') is safe for any args " 22001 "that match its prototype\n", 22002 i, bpf_subprog_name(env, i)); 22003 22004 sub_aux->verified[context] = true; 22005 new_cnt++; 22006 } 22007 } 22008 22009 /* 22010 * We can't loop forever as each pass verifies at least one new context, 22011 * and there are only three contexts per global subprog. 22012 */ 22013 if (new_cnt) 22014 goto again; 22015 22016 return 0; 22017 } 22018 22019 static int do_check_main(struct bpf_verifier_env *env) 22020 { 22021 int ret; 22022 22023 env->insn_idx = 0; 22024 ret = do_check_common(env, 0, env->prog->sleepable); 22025 if (!ret) 22026 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 22027 return ret; 22028 } 22029 22030 static void print_verification_stats(struct bpf_verifier_env *env) 22031 { 22032 /* Skip over hidden subprogs which are not verified. */ 22033 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 22034 22035 if (env->log.level & BPF_LOG_STATS) { 22036 verbose(env, "verification time %lld usec\n", 22037 div_u64(env->verification_time, 1000)); 22038 verbose(env, "stack depth max %d\n", env->max_stack_depth); 22039 for (i = 0; i < subprog_cnt; i++) { 22040 const char *name = env->subprog_info[i].name; 22041 const char *kind; 22042 22043 if (!name || !name[0]) 22044 name = "<unknown>"; 22045 kind = i == 0 ? "main" : 22046 bpf_subprog_is_global(env, i) ? "global" : "static"; 22047 verbose(env, "subprog %d (%s) %s insns_self %d insns_total %d stack %d\n", 22048 i, name, kind, env->subprog_info[i].insns_self, 22049 env->subprog_info[i].insns_total, 22050 env->subprog_info[i].stack_depth); 22051 } 22052 } 22053 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 22054 "total_states %d peak_states %d mark_read %d\n", 22055 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 22056 env->max_states_per_insn, env->total_states, 22057 env->peak_states, env->longest_mark_read_walk); 22058 } 22059 22060 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 22061 const struct bpf_ctx_arg_aux *info, u32 cnt) 22062 { 22063 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 22064 prog->aux->ctx_arg_info_size = cnt; 22065 22066 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 22067 } 22068 22069 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 22070 { 22071 const struct btf_type *t, *func_proto; 22072 const struct bpf_struct_ops_desc *st_ops_desc; 22073 const struct bpf_struct_ops_arg_info *arg_info; 22074 const struct bpf_struct_ops *st_ops; 22075 const struct btf_member *member; 22076 struct bpf_prog *prog = env->prog; 22077 bool has_refcounted_arg = false; 22078 u32 btf_id, member_idx, member_off; 22079 struct btf *btf; 22080 const char *mname; 22081 int i, err; 22082 22083 if (!prog->gpl_compatible) { 22084 verbose(env, "struct ops programs must have a GPL compatible license\n"); 22085 return -EINVAL; 22086 } 22087 22088 if (!prog->aux->attach_btf_id) 22089 return -ENOTSUPP; 22090 22091 btf = prog->aux->attach_btf; 22092 if (btf_is_module(btf)) { 22093 /* Make sure st_ops is valid through the lifetime of env */ 22094 env->attach_btf_mod = btf_try_get_module(btf); 22095 if (!env->attach_btf_mod) { 22096 verbose(env, "struct_ops module %s is not found\n", 22097 btf_get_name(btf)); 22098 return -ENOTSUPP; 22099 } 22100 } 22101 22102 btf_id = prog->aux->attach_btf_id; 22103 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 22104 if (!st_ops_desc) { 22105 verbose(env, "attach_btf_id %u is not a supported struct\n", 22106 btf_id); 22107 return -ENOTSUPP; 22108 } 22109 st_ops = st_ops_desc->st_ops; 22110 22111 t = st_ops_desc->type; 22112 member_idx = prog->expected_attach_type; 22113 if (member_idx >= btf_type_vlen(t)) { 22114 verbose(env, "attach to invalid member idx %u of struct %s\n", 22115 member_idx, st_ops->name); 22116 return -EINVAL; 22117 } 22118 22119 member = &btf_type_member(t)[member_idx]; 22120 mname = btf_name_by_offset(btf, member->name_off); 22121 func_proto = btf_type_resolve_func_ptr(btf, member->type, 22122 NULL); 22123 if (!func_proto) { 22124 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 22125 mname, member_idx, st_ops->name); 22126 return -EINVAL; 22127 } 22128 22129 member_off = __btf_member_bit_offset(t, member) / 8; 22130 err = bpf_struct_ops_supported(st_ops, member_off); 22131 if (err) { 22132 verbose(env, "attach to unsupported member %s of struct %s\n", 22133 mname, st_ops->name); 22134 return err; 22135 } 22136 22137 if (st_ops->check_member) { 22138 err = st_ops->check_member(t, member, prog); 22139 22140 if (err) { 22141 verbose(env, "attach to unsupported member %s of struct %s\n", 22142 mname, st_ops->name); 22143 return err; 22144 } 22145 } 22146 22147 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 22148 verbose(env, "Private stack not supported by jit\n"); 22149 return -EACCES; 22150 } 22151 22152 arg_info = &st_ops_desc->arg_info[member_idx]; 22153 for (i = 0; i < arg_info->cnt; i++) { 22154 const struct bpf_ctx_arg_aux *info = &arg_info->info[i]; 22155 22156 if (info->refcounted) 22157 has_refcounted_arg = true; 22158 if (base_type(info->reg_type) == PTR_TO_ARENA) { 22159 if (!bpf_jit_supports_arena_args()) { 22160 verbose(env, "JIT does not support arena arguments\n"); 22161 return -ENOTSUPP; 22162 } 22163 if (!prog->aux->arena) { 22164 verbose(env, 22165 "arena argument of %s requires a program with an associated arena\n", 22166 mname); 22167 return -EINVAL; 22168 } 22169 } 22170 } 22171 22172 /* Tail call is not allowed for programs with refcounted arguments since we 22173 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 22174 */ 22175 for (i = 0; i < env->subprog_cnt; i++) { 22176 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 22177 verbose(env, "program with __ref argument cannot tail call\n"); 22178 return -EINVAL; 22179 } 22180 } 22181 22182 prog->aux->st_ops = st_ops; 22183 prog->aux->attach_st_ops_member_off = member_off; 22184 22185 prog->aux->attach_func_proto = func_proto; 22186 prog->aux->attach_func_name = mname; 22187 env->ops = st_ops->verifier_ops; 22188 22189 return bpf_prog_ctx_arg_info_init(prog, arg_info->info, arg_info->cnt); 22190 } 22191 #define SECURITY_PREFIX "security_" 22192 22193 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 22194 22195 /* list of non-sleepable functions that are otherwise on 22196 * ALLOW_ERROR_INJECTION list 22197 */ 22198 BTF_SET_START(btf_non_sleepable_error_inject) 22199 /* Three functions below can be called from sleepable and non-sleepable context. 22200 * Assume non-sleepable from bpf safety point of view. 22201 */ 22202 BTF_ID(func, __filemap_add_folio) 22203 #ifdef CONFIG_FAIL_PAGE_ALLOC 22204 BTF_ID(func, should_fail_alloc_page) 22205 #endif 22206 #ifdef CONFIG_FAILSLAB 22207 BTF_ID(func, should_failslab) 22208 #endif 22209 BTF_SET_END(btf_non_sleepable_error_inject) 22210 22211 static int check_non_sleepable_error_inject(u32 btf_id) 22212 { 22213 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 22214 } 22215 22216 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 22217 { 22218 /* fentry/fexit/fmod_ret progs can be sleepable if they are 22219 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 22220 */ 22221 if (!check_non_sleepable_error_inject(btf_id) && 22222 within_error_injection_list(addr)) 22223 return 0; 22224 22225 return -EINVAL; 22226 } 22227 22228 static int check_attach_modify_return(unsigned long addr, const char *func_name) 22229 { 22230 if (within_error_injection_list(addr) || 22231 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 22232 return 0; 22233 22234 return -EINVAL; 22235 } 22236 22237 #else 22238 22239 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 22240 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 22241 * but that just compares two concrete function names. 22242 */ 22243 static bool has_arch_syscall_prefix(const char *func_name) 22244 { 22245 #if defined(__x86_64__) 22246 return !strncmp(func_name, "__x64_", 6); 22247 #elif defined(__i386__) 22248 return !strncmp(func_name, "__ia32_", 7); 22249 #elif defined(__s390x__) 22250 return !strncmp(func_name, "__s390x_", 8); 22251 #elif defined(__aarch64__) 22252 return !strncmp(func_name, "__arm64_", 8); 22253 #elif defined(__riscv) 22254 return !strncmp(func_name, "__riscv_", 8); 22255 #elif defined(__powerpc__) || defined(__powerpc64__) 22256 return !strncmp(func_name, "sys_", 4); 22257 #elif defined(__loongarch__) 22258 return !strncmp(func_name, "sys_", 4); 22259 #else 22260 return false; 22261 #endif 22262 } 22263 22264 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 22265 22266 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 22267 { 22268 if (has_arch_syscall_prefix(func_name)) 22269 return 0; 22270 22271 return -EINVAL; 22272 } 22273 22274 static int check_attach_modify_return(unsigned long addr, const char *func_name) 22275 { 22276 if (has_arch_syscall_prefix(func_name) || 22277 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 22278 return 0; 22279 22280 return -EINVAL; 22281 } 22282 22283 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 22284 22285 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id) 22286 { 22287 return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id; 22288 } 22289 22290 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog, 22291 const struct btf *btf) 22292 { 22293 const struct btf_type *t; 22294 const char *tname; 22295 22296 if (!btf_is_kernel(btf)) 22297 return -EINVAL; 22298 22299 switch (prog->type) { 22300 case BPF_PROG_TYPE_TRACING: 22301 t = btf_type_by_id(btf, btf_id); 22302 if (!t) 22303 return -EINVAL; 22304 tname = btf_name_by_offset(btf, t->name_off); 22305 if (!tname) 22306 return -EINVAL; 22307 22308 /* 22309 * *.multi sleepable programs will pass initial sleepable check, 22310 * the actual attached btf ids are checked later during the link 22311 * attachment. 22312 */ 22313 if (is_tracing_multi_id(prog, btf_id)) 22314 return 0; 22315 if (!check_attach_sleepable(btf_id, addr, tname)) 22316 return 0; 22317 /* 22318 * fentry/fexit/fmod_ret progs can also be sleepable if they are 22319 * in the fmodret id set with the KF_SLEEPABLE flag. 22320 */ 22321 else { 22322 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog); 22323 22324 if (flags && (*flags & KF_SLEEPABLE)) 22325 return 0; 22326 } 22327 break; 22328 case BPF_PROG_TYPE_LSM: 22329 /* 22330 * LSM progs check that they are attached to bpf_lsm_*() funcs. 22331 * Only some of them are sleepable. 22332 */ 22333 if (bpf_lsm_is_sleepable_hook(btf_id)) 22334 return 0; 22335 break; 22336 default: 22337 break; 22338 } 22339 return -EINVAL; 22340 } 22341 22342 /* 22343 * Resolve the prototype describing a trace target's real ABI. A 22344 * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public 22345 * prototype, so use the _impl prototype; other targets use their own. 22346 */ 22347 static const struct btf_type * 22348 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id) 22349 { 22350 const struct btf_type *func; 22351 struct module *mod = NULL; 22352 const char *name; 22353 int implicit; 22354 22355 func = btf_type_by_id(btf, func_id); 22356 if (!func || !btf_type_is_func(func)) 22357 return NULL; 22358 name = btf_name_by_offset(btf, func->name_off); 22359 22360 /* 22361 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is 22362 * stable only once it is live; hold a module ref across the read to 22363 * exclude a concurrent module load. 22364 */ 22365 if (btf_is_module(btf)) { 22366 mod = btf_try_get_module(btf); 22367 if (!mod) 22368 return NULL; 22369 } 22370 implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS); 22371 module_put(mod); 22372 22373 if (implicit == -EINVAL) { 22374 bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name); 22375 return NULL; 22376 } 22377 if (implicit > 0) 22378 return find_kfunc_impl_proto(log, btf, name); 22379 22380 return btf_type_by_id(btf, func->type); 22381 } 22382 22383 static bool attach_uses_trampoline_retval(enum bpf_attach_type type) 22384 { 22385 switch (type) { 22386 case BPF_MODIFY_RETURN: 22387 case BPF_TRACE_FEXIT: 22388 case BPF_TRACE_FEXIT_MULTI: 22389 case BPF_TRACE_FSESSION: 22390 case BPF_TRACE_FSESSION_MULTI: 22391 return true; 22392 default: 22393 return false; 22394 } 22395 } 22396 22397 /* 22398 * BPF code passes argument slot N where the kernel convention passes its Nth 22399 * u64 argument, so describe a BPF function to its trampoline as one u64 per 22400 * slot, and every arch places its arguments right. 22401 */ 22402 static int flatten_bpf_func_model(struct bpf_verifier_log *log, const char *tname, 22403 struct btf_func_model *m) 22404 { 22405 u32 i, nslots = 0; 22406 22407 for (i = 0; i < m->nr_args; i++) 22408 nslots += btf_func_model_arg_slots(m, i); 22409 if (nslots > MAX_BPF_FUNC_ARGS) { 22410 bpf_log(log, "The function %s has %u argument slots. Too many.\n", 22411 tname, nslots); 22412 return -EINVAL; 22413 } 22414 22415 for (i = 0; i < nslots; i++) { 22416 m->arg_size[i] = sizeof(u64); 22417 m->arg_flags[i] = 0; 22418 } 22419 m->nr_args = nslots; 22420 return 0; 22421 } 22422 22423 /* 22424 * The verifier lets a static function use stack arguments counted from its 22425 * BTF, even if that BTF turns out unreliable. A trampoline on the function is 22426 * then given only MAX_BPF_FUNC_REG_ARGS u64 arguments and would lose the 22427 * stack arguments, so such a function cannot be attached to. 22428 */ 22429 static int check_unreliable_func_args(struct bpf_verifier_log *log, struct btf *btf, 22430 const struct btf_type *func_proto, const char *tname) 22431 { 22432 struct btf_func_model m; 22433 u32 i, nslots = 0; 22434 22435 if (btf_distill_func_proto(NULL, btf, func_proto, tname, &m)) { 22436 /* at least a slot for each argument */ 22437 nslots = btf_type_vlen(func_proto); 22438 } else { 22439 for (i = 0; i < m.nr_args; i++) 22440 nslots += btf_func_model_arg_slots(&m, i); 22441 } 22442 if (nslots <= MAX_BPF_FUNC_REG_ARGS) 22443 return 0; 22444 22445 bpf_log(log, "Cannot attach to static function %s: unreliable BTF and stack arguments\n", 22446 tname); 22447 return -EINVAL; 22448 } 22449 22450 /* Functions may share a type id. The first of them is attached to. */ 22451 static int find_tgt_subprog(const struct bpf_prog *tgt_prog, u32 btf_id) 22452 { 22453 const struct bpf_prog_aux *aux = tgt_prog->aux; 22454 int i; 22455 22456 for (i = 0; i < aux->func_info_cnt; i++) 22457 if (aux->func_info[i].type_id == btf_id) 22458 return i; 22459 22460 return -1; 22461 } 22462 22463 /* 22464 * The prologue of an extension gives a cloned skb a new head, unless the 22465 * prologue of the target program has done that. The callers of the function 22466 * that it replaces must not hold on to the old head. 22467 */ 22468 int bpf_check_ext_prologue(struct bpf_verifier_log *log, 22469 const struct bpf_prog *tgt_prog, u32 btf_id) 22470 { 22471 const struct bpf_prog_aux *aux = tgt_prog->aux; 22472 int subprog = find_tgt_subprog(tgt_prog, btf_id); 22473 22474 if (aux->has_prologue) 22475 return 0; 22476 22477 if (subprog >= 0 && !aux->func_info_aux[subprog].called_with_pkt_ptrs) 22478 return 0; 22479 22480 bpf_log(log, 22481 "Extension writing packet data cannot replace a function whose callers keep packet pointers\n"); 22482 return -EINVAL; 22483 } 22484 22485 /* 22486 * An extension is verified as a program that runs under the RCU read lock. Does 22487 * the function that it is to replace? 22488 */ 22489 static bool func_has_rcu_read_lock(const struct bpf_prog *prog, int subprog) 22490 { 22491 const struct bpf_func_info_aux *sub_aux = &prog->aux->func_info_aux[subprog]; 22492 22493 if (!subprog) 22494 return !prog->sleepable; 22495 22496 return !sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] && 22497 !sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK]; 22498 } 22499 22500 int bpf_check_attach_target(struct bpf_verifier_log *log, 22501 const struct bpf_prog *prog, 22502 const struct bpf_prog *tgt_prog, 22503 u32 btf_id, 22504 struct bpf_attach_target_info *tgt_info) 22505 { 22506 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 22507 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 22508 char trace_symbol[KSYM_SYMBOL_LEN]; 22509 const char prefix[] = "btf_trace_"; 22510 struct bpf_raw_event_map *btp; 22511 int ret = 0, subprog = -1; 22512 const struct btf_type *t; 22513 bool conservative = true; 22514 const char *tname, *fname; 22515 struct btf *btf; 22516 long addr = 0; 22517 struct module *mod = NULL; 22518 22519 if (!btf_id) { 22520 bpf_log(log, "Tracing programs must provide btf_id\n"); 22521 return -EINVAL; 22522 } 22523 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 22524 if (!btf) { 22525 bpf_log(log, 22526 "Tracing program can only be attached to another program annotated with BTF\n"); 22527 return -EINVAL; 22528 } 22529 t = btf_type_by_id(btf, btf_id); 22530 if (!t) { 22531 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 22532 return -EINVAL; 22533 } 22534 tname = btf_name_by_offset(btf, t->name_off); 22535 if (!tname) { 22536 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 22537 return -EINVAL; 22538 } 22539 if (tgt_prog) { 22540 struct bpf_prog_aux *aux = tgt_prog->aux; 22541 bool tgt_changes_pkt_data; 22542 bool tgt_might_sleep; 22543 bool tgt_can_unwind; 22544 22545 if (bpf_prog_is_dev_bound(prog->aux) && 22546 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 22547 bpf_log(log, "Target program bound device mismatch"); 22548 return -EINVAL; 22549 } 22550 22551 subprog = find_tgt_subprog(tgt_prog, btf_id); 22552 if (subprog == -1) { 22553 bpf_log(log, "Subprog %s doesn't exist\n", tname); 22554 return -EINVAL; 22555 } 22556 /* 22557 * A struct_ops indirect trampoline converts arena arguments 22558 * before invoking its program. A tracing or extension program 22559 * attached to the main program would see the converted offset as a 22560 * regular BTF pointer. 22561 */ 22562 if (subprog == 0 && bpf_prog_has_arena_ctx_arg(tgt_prog)) { 22563 bpf_log(log, "Cannot attach to a target with arena context arguments\n"); 22564 return -EOPNOTSUPP; 22565 } 22566 if (aux->func && aux->func[subprog]->aux->exception_cb) { 22567 bpf_log(log, 22568 "%s programs cannot attach to exception callback\n", 22569 prog_extension ? "Extension" : "Tracing"); 22570 return -EINVAL; 22571 } 22572 /* unwind_exit of the main prog is exit, unless it's an extension */ 22573 tgt_can_unwind = (subprog || tgt_prog->type == BPF_PROG_TYPE_EXT) && 22574 (aux->func ? aux->func[subprog]->aux->can_unwind 22575 : aux->can_unwind); 22576 /* unwind_exit would return to the trampoline that called the target */ 22577 if (tgt_can_unwind && !prog_extension && 22578 prog->expected_attach_type != BPF_TRACE_FENTRY) { 22579 bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname); 22580 return -EINVAL; 22581 } 22582 conservative = aux->func_info_aux[subprog].unreliable; 22583 if (prog_extension) { 22584 if (aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL || 22585 conservative) { 22586 bpf_log(log, 22587 "Cannot replace static functions\n"); 22588 return -EINVAL; 22589 } 22590 if (!prog->jit_requested) { 22591 bpf_log(log, 22592 "Extension programs should be JITed\n"); 22593 return -EINVAL; 22594 } 22595 /* 22596 * How much of the buffer of the tracepoint is used 22597 * is checked for the program that is attached to it. 22598 */ 22599 if (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) { 22600 bpf_log(log, 22601 "Cannot extend a writable raw tracepoint program\n"); 22602 return -EINVAL; 22603 } 22604 if (!func_has_rcu_read_lock(tgt_prog, subprog)) { 22605 bpf_log(log, 22606 "Cannot extend a function that runs without RCU read lock\n"); 22607 return -EINVAL; 22608 } 22609 tgt_changes_pkt_data = aux->func 22610 ? aux->func[subprog]->aux->changes_pkt_data 22611 : aux->changes_pkt_data; 22612 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 22613 bpf_log(log, 22614 "Extension program changes packet data, while original does not\n"); 22615 return -EINVAL; 22616 } 22617 if (prog->aux->has_prologue && 22618 bpf_check_ext_prologue(log, tgt_prog, btf_id)) 22619 return -EINVAL; 22620 22621 tgt_might_sleep = aux->func 22622 ? aux->func[subprog]->aux->might_sleep 22623 : aux->might_sleep; 22624 if (prog->aux->might_sleep && !tgt_might_sleep) { 22625 bpf_log(log, 22626 "Extension program may sleep, while original does not\n"); 22627 return -EINVAL; 22628 } 22629 /* There is no unwind_goto after the calls of the original */ 22630 if (prog->aux->can_unwind && !tgt_can_unwind) { 22631 bpf_log(log, 22632 "Extension program can unwind, while original does not\n"); 22633 return -EINVAL; 22634 } 22635 } 22636 if (!tgt_prog->jited) { 22637 bpf_log(log, "Can attach to only JITed progs\n"); 22638 return -EINVAL; 22639 } 22640 if (prog_tracing) { 22641 if (aux->attach_tracing_prog) { 22642 /* 22643 * Target program is an fentry/fexit which is already attached 22644 * to another tracing program. More levels of nesting 22645 * attachment are not allowed. 22646 */ 22647 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 22648 return -EINVAL; 22649 } 22650 } else if (tgt_prog->type == prog->type) { 22651 /* 22652 * To avoid potential call chain cycles, prevent attaching of a 22653 * program extension to another extension. It's ok to attach 22654 * fentry/fexit to extension program. 22655 */ 22656 bpf_log(log, "Cannot recursively attach\n"); 22657 return -EINVAL; 22658 } 22659 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 22660 prog_extension && 22661 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 22662 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 22663 tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || 22664 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 22665 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || 22666 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 22667 /* Program extensions can extend all program types 22668 * except fentry/fexit. The reason is the following. 22669 * The fentry/fexit programs are used for performance 22670 * analysis, stats and can be attached to any program 22671 * type. When extension program is replacing XDP function 22672 * it is necessary to allow performance analysis of all 22673 * functions. Both original XDP program and its program 22674 * extension. Hence attaching fentry/fexit to 22675 * BPF_PROG_TYPE_EXT is allowed. If extending of 22676 * fentry/fexit was allowed it would be possible to create 22677 * long call chain fentry->extension->fentry->extension 22678 * beyond reasonable stack size. Hence extending fentry 22679 * is not allowed. 22680 */ 22681 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 22682 return -EINVAL; 22683 } 22684 } else { 22685 if (prog_extension) { 22686 bpf_log(log, "Cannot replace kernel functions\n"); 22687 return -EINVAL; 22688 } 22689 } 22690 22691 switch (prog->expected_attach_type) { 22692 case BPF_TRACE_RAW_TP: 22693 if (tgt_prog) { 22694 bpf_log(log, 22695 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 22696 return -EINVAL; 22697 } 22698 if (!btf_type_is_typedef(t)) { 22699 bpf_log(log, "attach_btf_id %u is not a typedef\n", 22700 btf_id); 22701 return -EINVAL; 22702 } 22703 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 22704 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 22705 btf_id, tname); 22706 return -EINVAL; 22707 } 22708 tname += sizeof(prefix) - 1; 22709 22710 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 22711 * names. Thus using bpf_raw_event_map to get argument names. 22712 */ 22713 btp = bpf_get_raw_tracepoint(tname); 22714 if (!btp) 22715 return -EINVAL; 22716 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 22717 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 22718 tname); 22719 bpf_put_raw_tracepoint(btp); 22720 return -EINVAL; 22721 } 22722 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 22723 trace_symbol); 22724 bpf_put_raw_tracepoint(btp); 22725 22726 if (fname) 22727 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 22728 22729 if (!fname || ret < 0) { 22730 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 22731 prefix, tname); 22732 t = btf_type_by_id(btf, t->type); 22733 if (!btf_type_is_ptr(t)) 22734 /* should never happen in valid vmlinux build */ 22735 return -EINVAL; 22736 } else { 22737 t = btf_type_by_id(btf, ret); 22738 if (!btf_type_is_func(t)) 22739 /* should never happen in valid vmlinux build */ 22740 return -EINVAL; 22741 } 22742 22743 t = btf_type_by_id(btf, t->type); 22744 if (!btf_type_is_func_proto(t)) 22745 /* should never happen in valid vmlinux build */ 22746 return -EINVAL; 22747 22748 break; 22749 case BPF_TRACE_ITER: 22750 if (!btf_type_is_func(t)) { 22751 bpf_log(log, "attach_btf_id %u is not a function\n", 22752 btf_id); 22753 return -EINVAL; 22754 } 22755 t = btf_type_by_id(btf, t->type); 22756 if (!btf_type_is_func_proto(t)) 22757 return -EINVAL; 22758 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22759 if (ret) 22760 return ret; 22761 break; 22762 default: 22763 if (!prog_extension) 22764 return -EINVAL; 22765 fallthrough; 22766 case BPF_MODIFY_RETURN: 22767 case BPF_LSM_MAC: 22768 case BPF_LSM_CGROUP: 22769 case BPF_TRACE_FENTRY: 22770 case BPF_TRACE_FEXIT: 22771 case BPF_TRACE_FSESSION: 22772 case BPF_TRACE_FSESSION_MULTI: 22773 case BPF_TRACE_FENTRY_MULTI: 22774 case BPF_TRACE_FEXIT_MULTI: 22775 if ((prog->expected_attach_type == BPF_TRACE_FSESSION || 22776 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 22777 !bpf_jit_supports_fsession()) { 22778 bpf_log(log, "JIT does not support fsession\n"); 22779 return -EOPNOTSUPP; 22780 } 22781 if (!btf_type_is_func(t)) { 22782 bpf_log(log, "attach_btf_id %u is not a function\n", 22783 btf_id); 22784 return -EINVAL; 22785 } 22786 if (prog_extension && 22787 btf_check_type_match(log, prog, btf, t)) 22788 return -EINVAL; 22789 t = btf_attach_func_proto(log, btf, btf_id); 22790 if (!t || !btf_type_is_func_proto(t)) 22791 return -EINVAL; 22792 22793 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 22794 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 22795 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 22796 return -EINVAL; 22797 22798 if (tgt_prog && conservative) { 22799 if (subprog > 0) { 22800 ret = check_unreliable_func_args(log, btf, t, tname); 22801 if (ret) 22802 return ret; 22803 } 22804 t = NULL; 22805 } 22806 22807 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 22808 if (ret < 0) 22809 return ret; 22810 if (tgt_prog) { 22811 ret = flatten_bpf_func_model(log, tname, &tgt_info->fmodel); 22812 if (ret < 0) 22813 return ret; 22814 } 22815 22816 if (tgt_info->fmodel.ret_size > 8 && 22817 attach_uses_trampoline_retval(prog->expected_attach_type)) { 22818 bpf_log(log, 22819 "Attach to function %s with a >8 byte return value is not supported for this attach type\n", 22820 tname); 22821 return -EOPNOTSUPP; 22822 } 22823 22824 /* 22825 * *.multi programs don't need an address during program 22826 * verification, we just take the module ref if needed. 22827 */ 22828 if (is_tracing_multi_id(prog, btf_id)) { 22829 if (btf_is_module(btf)) { 22830 mod = btf_try_get_module(btf); 22831 if (!mod) 22832 return -ENOENT; 22833 } 22834 addr = 0; 22835 } else if (tgt_prog) { 22836 if (subprog == 0) 22837 addr = (long) tgt_prog->bpf_func; 22838 else 22839 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 22840 } else { 22841 if (btf_is_module(btf)) { 22842 mod = btf_try_get_module(btf); 22843 if (mod) 22844 addr = find_kallsyms_symbol_value(mod, tname); 22845 else 22846 addr = 0; 22847 } else { 22848 addr = kallsyms_lookup_name(tname); 22849 } 22850 if (!addr) { 22851 module_put(mod); 22852 bpf_log(log, 22853 "The address of function %s cannot be found\n", 22854 tname); 22855 return -ENOENT; 22856 } 22857 } 22858 22859 if (prog->sleepable) { 22860 ret = btf_id_allow_sleepable(btf_id, addr, prog, btf); 22861 if (ret) { 22862 module_put(mod); 22863 bpf_log(log, "%s is not sleepable\n", tname); 22864 return ret; 22865 } 22866 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 22867 if (tgt_prog) { 22868 module_put(mod); 22869 bpf_log(log, "can't modify return codes of BPF programs\n"); 22870 return -EINVAL; 22871 } 22872 ret = -EINVAL; 22873 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 22874 !check_attach_modify_return(addr, tname)) 22875 ret = 0; 22876 if (ret) { 22877 module_put(mod); 22878 bpf_log(log, "%s() is not modifiable\n", tname); 22879 return ret; 22880 } 22881 } 22882 22883 break; 22884 } 22885 tgt_info->tgt_addr = addr; 22886 tgt_info->tgt_name = tname; 22887 tgt_info->tgt_type = t; 22888 tgt_info->tgt_mod = mod; 22889 return 0; 22890 } 22891 22892 BTF_SET_START(btf_id_deny) 22893 BTF_ID_UNUSED 22894 #ifdef CONFIG_SMP 22895 BTF_ID(func, ___migrate_enable) 22896 BTF_ID(func, migrate_disable) 22897 BTF_ID(func, migrate_enable) 22898 #endif 22899 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 22900 BTF_ID(func, rcu_read_unlock_strict) 22901 #endif 22902 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 22903 BTF_ID(func, preempt_count_add) 22904 BTF_ID(func, preempt_count_sub) 22905 #endif 22906 #ifdef CONFIG_PREEMPT_RCU 22907 BTF_ID(func, __rcu_read_lock) 22908 BTF_ID(func, __rcu_read_unlock) 22909 #endif 22910 BTF_SET_END(btf_id_deny) 22911 22912 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 22913 * Currently, we must manually list all __noreturn functions here. Once a more 22914 * robust solution is implemented, this workaround can be removed. 22915 */ 22916 BTF_SET_START(noreturn_deny) 22917 #ifdef CONFIG_IA32_EMULATION 22918 BTF_ID(func, __ia32_sys_exit) 22919 BTF_ID(func, __ia32_sys_exit_group) 22920 #endif 22921 #ifdef CONFIG_KUNIT 22922 BTF_ID(func, __kunit_abort) 22923 BTF_ID(func, kunit_try_catch_throw) 22924 #endif 22925 #ifdef CONFIG_MODULES 22926 BTF_ID(func, __module_put_and_kthread_exit) 22927 #endif 22928 #ifdef CONFIG_X86_64 22929 BTF_ID(func, __x64_sys_exit) 22930 BTF_ID(func, __x64_sys_exit_group) 22931 #endif 22932 BTF_ID(func, do_exit) 22933 BTF_ID(func, do_group_exit) 22934 BTF_ID(func, kthread_complete_and_exit) 22935 BTF_ID(func, make_task_dead) 22936 BTF_SET_END(noreturn_deny) 22937 22938 static bool can_be_sleepable(struct bpf_prog *prog) 22939 { 22940 if (prog->type == BPF_PROG_TYPE_TRACING) { 22941 switch (prog->expected_attach_type) { 22942 case BPF_TRACE_FENTRY: 22943 case BPF_TRACE_FEXIT: 22944 case BPF_MODIFY_RETURN: 22945 case BPF_TRACE_ITER: 22946 case BPF_TRACE_FSESSION: 22947 case BPF_TRACE_RAW_TP: 22948 case BPF_TRACE_FENTRY_MULTI: 22949 case BPF_TRACE_FEXIT_MULTI: 22950 case BPF_TRACE_FSESSION_MULTI: 22951 return true; 22952 default: 22953 return false; 22954 } 22955 } 22956 if (prog->type == BPF_PROG_TYPE_LSM) 22957 return prog->expected_attach_type != BPF_LSM_CGROUP; 22958 22959 return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 22960 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 22961 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 22962 prog->type == BPF_PROG_TYPE_TRACEPOINT; 22963 } 22964 22965 static int check_attach_btf_id(struct bpf_verifier_env *env) 22966 { 22967 struct bpf_prog *prog = env->prog; 22968 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 22969 struct bpf_attach_target_info tgt_info = {}; 22970 u32 btf_id = prog->aux->attach_btf_id; 22971 struct bpf_trampoline *tr; 22972 int ret; 22973 u64 key; 22974 22975 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 22976 if (prog->sleepable) 22977 /* attach_btf_id checked to be zero already */ 22978 return 0; 22979 verbose(env, "Syscall programs can only be sleepable\n"); 22980 return -EINVAL; 22981 } 22982 22983 if (prog->sleepable && !can_be_sleepable(prog)) { 22984 verbose(env, "Program of this type cannot be sleepable\n"); 22985 return -EINVAL; 22986 } 22987 22988 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 22989 return check_struct_ops_btf_id(env); 22990 22991 if (prog->type != BPF_PROG_TYPE_TRACING && 22992 prog->type != BPF_PROG_TYPE_LSM && 22993 prog->type != BPF_PROG_TYPE_EXT) 22994 return 0; 22995 22996 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 22997 if (ret) 22998 return ret; 22999 23000 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 23001 /* to make freplace equivalent to their targets, they need to 23002 * inherit env->ops and expected_attach_type for the rest of the 23003 * verification 23004 */ 23005 env->ops = bpf_verifier_ops[tgt_prog->type]; 23006 prog->expected_attach_type = tgt_prog->expected_attach_type; 23007 } 23008 23009 /* store info about the attachment target that will be used later */ 23010 prog->aux->attach_func_proto = tgt_info.tgt_type; 23011 prog->aux->attach_func_name = tgt_info.tgt_name; 23012 prog->aux->mod = tgt_info.tgt_mod; 23013 23014 if (tgt_prog) { 23015 prog->aux->saved_dst_prog_type = tgt_prog->type; 23016 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 23017 } 23018 23019 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 23020 prog->aux->attach_btf_trace = true; 23021 return 0; 23022 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 23023 return bpf_iter_prog_supported(prog); 23024 } 23025 23026 if (prog->type == BPF_PROG_TYPE_LSM) { 23027 ret = bpf_lsm_verify_prog(&env->log, prog); 23028 if (ret < 0) 23029 return ret; 23030 } else if (prog->type == BPF_PROG_TYPE_TRACING && 23031 btf_id_set_contains(&btf_id_deny, btf_id)) { 23032 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 23033 tgt_info.tgt_name); 23034 return -EINVAL; 23035 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 23036 prog->expected_attach_type == BPF_TRACE_FSESSION || 23037 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI || 23038 prog->expected_attach_type == BPF_MODIFY_RETURN) && 23039 btf_id_set_contains(&noreturn_deny, btf_id)) { 23040 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 23041 tgt_info.tgt_name); 23042 return -EINVAL; 23043 } 23044 23045 /* 23046 * We don't get trampoline for tracing_multi programs at this point, 23047 * it's done when tracing_multi link is created. 23048 */ 23049 if (prog->type == BPF_PROG_TYPE_TRACING && 23050 is_tracing_multi(prog->expected_attach_type)) 23051 return 0; 23052 23053 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 23054 tr = bpf_trampoline_get(key, &tgt_info); 23055 if (!tr) 23056 return -ENOMEM; 23057 23058 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 23059 bpf_trampoline_set_flags(tr, BPF_TRAMP_F_TAIL_CALL_CTX); 23060 23061 prog->aux->dst_trampoline = tr; 23062 return 0; 23063 } 23064 23065 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id, 23066 struct bpf_attach_target_info *tgt_info) 23067 { 23068 const struct btf_type *t; 23069 unsigned long addr; 23070 const char *tname; 23071 int err; 23072 23073 if (!btf_id || !btf) 23074 return -EINVAL; 23075 23076 /* Check noreturn attachment. */ 23077 if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 23078 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 23079 btf_id_set_contains(&noreturn_deny, btf_id)) 23080 return -EINVAL; 23081 /* Check denied attachment. */ 23082 if (btf_id_set_contains(&btf_id_deny, btf_id)) 23083 return -EINVAL; 23084 23085 /* Check and get function target data. */ 23086 t = btf_type_by_id(btf, btf_id); 23087 if (!t) 23088 return -EINVAL; 23089 tname = btf_name_by_offset(btf, t->name_off); 23090 if (!tname) 23091 return -EINVAL; 23092 t = btf_attach_func_proto(NULL, btf, btf_id); 23093 if (!t || !btf_type_is_func_proto(t)) 23094 return -EINVAL; 23095 err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel); 23096 if (err < 0) 23097 return err; 23098 if (tgt_info->fmodel.ret_size > 8 && 23099 attach_uses_trampoline_retval(prog->expected_attach_type)) 23100 return -EOPNOTSUPP; 23101 if (btf_is_module(btf)) { 23102 /* The bpf program already holds reference to module. */ 23103 if (WARN_ON_ONCE(!prog->aux->mod)) 23104 return -EINVAL; 23105 addr = find_kallsyms_symbol_value(prog->aux->mod, tname); 23106 } else { 23107 addr = kallsyms_lookup_name(tname); 23108 } 23109 if (!addr || !ftrace_location(addr)) 23110 return -ENOENT; 23111 23112 /* Check sleepable program attachment. */ 23113 if (prog->sleepable) { 23114 err = btf_id_allow_sleepable(btf_id, addr, prog, btf); 23115 if (err) 23116 return err; 23117 } 23118 tgt_info->tgt_addr = addr; 23119 return 0; 23120 } 23121 23122 struct btf *bpf_get_btf_vmlinux(void) 23123 { 23124 /* Pairs with the smp_store_release() on the parse path below. */ 23125 struct btf *btf = smp_load_acquire(&btf_vmlinux); 23126 23127 if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 23128 mutex_lock(&btf_vmlinux_lock); 23129 btf = btf_vmlinux; 23130 if (!btf) { 23131 btf = btf_parse_vmlinux(); 23132 /* 23133 * Order the parsed BTF contents and the globals the 23134 * parse populated (e.g. bpf_ctx_convert.t) before 23135 * the pointer publication. Pairs with the acquire 23136 * on the lockless fast path above. 23137 */ 23138 smp_store_release(&btf_vmlinux, btf); 23139 } 23140 mutex_unlock(&btf_vmlinux_lock); 23141 } 23142 return btf; 23143 } 23144 23145 /* 23146 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 23147 * this case expect that every file descriptor in the array is either a map or 23148 * a BTF. Everything else is considered to be trash. 23149 */ 23150 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd) 23151 { 23152 struct bpf_map *map; 23153 struct btf *btf; 23154 CLASS(fd, f)(fd); 23155 int err; 23156 23157 map = __bpf_map_get(f); 23158 if (!IS_ERR(map)) { 23159 err = __add_used_map(env, map); 23160 if (err < 0) 23161 return err; 23162 fd_slot_set_map(&env->fd_array[idx], map); 23163 return 0; 23164 } 23165 23166 btf = __btf_get_by_fd(f); 23167 if (!IS_ERR(btf)) { 23168 btf_get(btf); 23169 err = __add_used_btf(env, btf); 23170 if (err < 0) 23171 return err; 23172 fd_slot_set_btf(&env->fd_array[idx], btf); 23173 return 0; 23174 } 23175 23176 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 23177 return PTR_ERR(map); 23178 } 23179 23180 /* 23181 * A continuous fd_array is resolved into an in-memory cache with one slot 23182 * per entry. The bound here is deliberately generous and not derived from 23183 * the per-program object limits: Duplicate entries /are/ permitted, and 23184 * the number of distinct maps and BTFs a program can bind is enforced when 23185 * each entry is resolved by __add_used_map() and __add_used_btf(). 23186 */ 23187 #define MAX_FD_ARRAY_CNT 4096 23188 23189 static int process_fd_array_continuous(struct bpf_verifier_env *env, 23190 bpfptr_t fd_array, u32 cnt) 23191 { 23192 int fd, ret; 23193 u32 i; 23194 23195 if (cnt > MAX_FD_ARRAY_CNT) { 23196 verbose(env, "fd_array has too many entries (%u, max %u)\n", 23197 cnt, MAX_FD_ARRAY_CNT); 23198 return -E2BIG; 23199 } 23200 23201 env->fd_array = kvzalloc_objs(*env->fd_array, cnt, GFP_KERNEL_ACCOUNT); 23202 if (!env->fd_array) 23203 return -ENOMEM; 23204 env->fd_array_cnt = cnt; 23205 for (i = 0; i < cnt; i++) { 23206 if (copy_from_bpfptr_offset(&fd, fd_array, 23207 (size_t)i * sizeof(fd), sizeof(fd))) 23208 return -EFAULT; 23209 ret = add_fd_from_fd_array(env, i, fd); 23210 if (ret) 23211 return ret; 23212 } 23213 return 0; 23214 } 23215 23216 static int process_fd_array(struct bpf_verifier_env *env, 23217 union bpf_attr *attr, bpfptr_t uattr) 23218 { 23219 bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 23220 23221 if (bpfptr_is_null(fd_array)) { 23222 if (attr->fd_array_cnt) { 23223 verbose(env, "fd_array_cnt %u without fd_array is invalid\n", 23224 attr->fd_array_cnt); 23225 return -EINVAL; 23226 } 23227 return 0; 23228 } 23229 /* 23230 * New API: the caller passes fd_array_cnt and a continuous array that 23231 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep 23232 * the caller's array and resolve entries on the spot at each reference. 23233 */ 23234 if (attr->fd_array_cnt) 23235 return process_fd_array_continuous(env, fd_array, 23236 attr->fd_array_cnt); 23237 env->fd_array_raw = fd_array; 23238 return 0; 23239 } 23240 23241 /* replace a generic kfunc with a specialized version if necessary */ 23242 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 23243 { 23244 struct bpf_prog *prog = env->prog; 23245 bool seen_direct_write; 23246 void *xdp_kfunc; 23247 bool is_rdonly; 23248 u32 func_id = desc->func_id; 23249 u16 offset = desc->offset; 23250 unsigned long addr = desc->addr; 23251 23252 if (offset) /* return if module BTF is used */ 23253 return 0; 23254 23255 if (bpf_dev_bound_kfunc_id(func_id)) { 23256 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 23257 if (xdp_kfunc) 23258 addr = (unsigned long)xdp_kfunc; 23259 /* fallback to default kfunc when not supported by netdev */ 23260 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 23261 seen_direct_write = env->seen_direct_write; 23262 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 23263 23264 if (is_rdonly) 23265 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 23266 23267 /* restore env->seen_direct_write to its original value, since 23268 * may_access_direct_pkt_data mutates it 23269 */ 23270 env->seen_direct_write = seen_direct_write; 23271 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 23272 if (bpf_lsm_has_d_inode_locked(prog)) 23273 addr = (unsigned long)bpf_set_dentry_xattr_locked; 23274 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 23275 if (bpf_lsm_has_d_inode_locked(prog)) 23276 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 23277 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 23278 if (!env->insn_aux_data[insn_idx].non_sleepable) 23279 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 23280 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 23281 if (env->insn_aux_data[insn_idx].non_sleepable) 23282 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 23283 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 23284 if (env->insn_aux_data[insn_idx].non_sleepable) 23285 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 23286 } 23287 desc->addr = addr; 23288 return 0; 23289 } 23290 23291 static int add_kfunc_desc_target(struct bpf_verifier_env *env, 23292 const struct bpf_kfunc_desc *target_desc, 23293 u16 base_desc_idx, u16 *desc_idx) 23294 { 23295 struct bpf_kfunc_desc desc = *target_desc; 23296 struct bpf_kfunc_desc_tab *new_tab; 23297 struct bpf_kfunc_desc_tab *tab; 23298 struct bpf_prog_aux *prog_aux; 23299 u32 i; 23300 23301 prog_aux = env->prog->aux; 23302 tab = prog_aux->kfunc_tab; 23303 23304 if (base_desc_idx >= tab->nr_base_descs) { 23305 verifier_bug(env, "kfunc desc_idx %d out of bounds (%d descriptors)", 23306 base_desc_idx, tab->nr_base_descs); 23307 return -EFAULT; 23308 } 23309 if (tab->descs[base_desc_idx].func_id != desc.func_id) { 23310 verifier_bug(env, "kfunc desc %d has invalid id (expected %d, got %d)", 23311 base_desc_idx, tab->descs[base_desc_idx].func_id, desc.func_id); 23312 return -EFAULT; 23313 } 23314 if (tab->descs[base_desc_idx].offset != desc.offset) { 23315 verifier_bug(env, "kfunc desc %d has invalid offset (expected %d, got %d)", 23316 base_desc_idx, tab->descs[base_desc_idx].offset, desc.offset); 23317 return -EFAULT; 23318 } 23319 23320 if (tab->descs[base_desc_idx].addr == desc.addr) { 23321 *desc_idx = base_desc_idx; 23322 return 0; 23323 } 23324 23325 for (i = tab->nr_base_descs; i < tab->nr_descs; i++) { 23326 if (tab->descs[i].func_id == desc.func_id && 23327 tab->descs[i].offset == desc.offset && 23328 tab->descs[i].addr == desc.addr) { 23329 *desc_idx = i; 23330 return 0; 23331 } 23332 } 23333 23334 if (tab->nr_descs == MAX_KFUNC_CALL_DESCS) { 23335 verbose(env, "too many different kernel function call targets\n"); 23336 return -E2BIG; 23337 } 23338 23339 new_tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), 23340 GFP_KERNEL_ACCOUNT); 23341 if (!new_tab) 23342 return -ENOMEM; 23343 tab = new_tab; 23344 prog_aux->kfunc_tab = tab; 23345 23346 *desc_idx = tab->nr_descs; 23347 tab->descs[tab->nr_descs++] = desc; 23348 return 0; 23349 } 23350 23351 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 23352 u16 struct_meta_reg, 23353 u16 node_offset_reg, 23354 struct bpf_insn *insn, 23355 struct bpf_insn *insn_buf, 23356 int *cnt) 23357 { 23358 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 23359 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 23360 23361 insn_buf[0] = addr[0]; 23362 insn_buf[1] = addr[1]; 23363 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 23364 insn_buf[3] = *insn; 23365 *cnt = 4; 23366 } 23367 23368 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 23369 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 23370 { 23371 struct bpf_kfunc_desc desc_copy; 23372 struct bpf_kfunc_desc *desc; 23373 unsigned long call_imm; 23374 u16 base_desc_idx, desc_idx; 23375 bool near_call; 23376 int err; 23377 23378 if (!insn->imm) { 23379 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 23380 return -EINVAL; 23381 } 23382 23383 *cnt = 0; 23384 23385 /* insn->imm has the btf func_id. Replace it with an offset relative to 23386 * __bpf_call_base, unless the JIT needs to call functions that are 23387 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 23388 */ 23389 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 23390 if (!desc) { 23391 verifier_bug(env, "kernel function descriptor not found for func_id %u", 23392 insn->imm); 23393 return -EFAULT; 23394 } 23395 base_desc_idx = desc - env->prog->aux->kfunc_tab->descs; 23396 23397 near_call = !bpf_jit_supports_far_kfunc_call(); 23398 desc_copy = *desc; 23399 desc = &desc_copy; 23400 23401 err = specialize_kfunc(env, desc, insn_idx); 23402 if (err) 23403 return err; 23404 23405 if (near_call) { 23406 call_imm = BPF_CALL_IMM(desc->addr); 23407 if ((unsigned long)(s32)call_imm != call_imm) { 23408 verbose(env, "address of kernel func_id %u is out of range\n", 23409 desc->func_id); 23410 return -EINVAL; 23411 } 23412 insn->imm = call_imm; 23413 } 23414 23415 err = add_kfunc_desc_target(env, desc, base_desc_idx, &desc_idx); 23416 if (err) 23417 return err; 23418 insn->off = desc_idx; 23419 23420 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 23421 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 23422 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 23423 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 23424 23425 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 23426 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 23427 insn_idx); 23428 return -EFAULT; 23429 } 23430 23431 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 23432 insn_buf[1] = addr[0]; 23433 insn_buf[2] = addr[1]; 23434 insn_buf[3] = *insn; 23435 *cnt = 4; 23436 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 23437 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 23438 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 23439 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 23440 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 23441 23442 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 23443 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 23444 insn_idx); 23445 return -EFAULT; 23446 } 23447 23448 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 23449 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 23450 insn_idx); 23451 return -EFAULT; 23452 } 23453 23454 insn_buf[0] = addr[0]; 23455 insn_buf[1] = addr[1]; 23456 insn_buf[2] = *insn; 23457 *cnt = 3; 23458 } else if (is_bpf_list_push_kfunc(desc->func_id) || 23459 is_bpf_rbtree_add_kfunc(desc->func_id)) { 23460 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 23461 int struct_meta_reg = BPF_REG_3; 23462 int node_offset_reg = BPF_REG_4; 23463 23464 /* list_add/rbtree_add have an extra arg (prev/less), 23465 * so args-to-fixup are in diff regs. 23466 */ 23467 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 23468 is_bpf_rbtree_add_kfunc(desc->func_id)) { 23469 struct_meta_reg = BPF_REG_4; 23470 node_offset_reg = BPF_REG_5; 23471 } 23472 23473 if (!kptr_struct_meta) { 23474 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 23475 insn_idx); 23476 return -EFAULT; 23477 } 23478 23479 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 23480 node_offset_reg, insn, insn_buf, cnt); 23481 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 23482 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 23483 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 23484 *cnt = 1; 23485 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 23486 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 23487 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 23488 23489 /* 23490 * inline the bpf_session_is_return() for fsession: 23491 * bool bpf_session_is_return(void *ctx) 23492 * { 23493 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 23494 * } 23495 */ 23496 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 23497 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 23498 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 23499 *cnt = 3; 23500 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 23501 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 23502 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 23503 /* 23504 * inline bpf_session_cookie() for fsession: 23505 * __u64 *bpf_session_cookie(void *ctx) 23506 * { 23507 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 23508 * return &((u64 *)ctx)[-off]; 23509 * } 23510 */ 23511 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 23512 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 23513 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 23514 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 23515 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 23516 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 23517 *cnt = 6; 23518 } else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_new]) { 23519 /* inline bpf_iter_num_new(&it, start, end); R1=&it, R2=start, R3=end */ 23520 int i = 0; 23521 23522 /* if (start > end) goto einval; */ 23523 insn_buf[i++] = BPF_JMP32_REG(BPF_JSGT, BPF_REG_2, BPF_REG_3, 8); 23524 /* r0 = (u32)end - (u32)start; if (r0 > BPF_MAX_LOOPS) goto e2big; */ 23525 insn_buf[i++] = BPF_MOV32_REG(BPF_REG_0, BPF_REG_3); 23526 insn_buf[i++] = BPF_ALU32_REG(BPF_SUB, BPF_REG_0, BPF_REG_2); 23527 insn_buf[i++] = BPF_JMP_IMM(BPF_JGT, BPF_REG_0, BPF_MAX_LOOPS, 8); 23528 /* s->cur = start - 1; s->end = end; return 0; */ 23529 insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_2, -1); 23530 insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_2, 0); 23531 insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, 4); 23532 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0); 23533 insn_buf[i++] = BPF_JMP_A(5); 23534 /* einval: s->cur = s->end = 0; return -EINVAL; */ 23535 insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0); 23536 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 23537 insn_buf[i++] = BPF_JMP_A(2); 23538 /* e2big: s->cur = s->end = 0; return -E2BIG; */ 23539 insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0); 23540 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG); 23541 *cnt = i; 23542 } else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_next]) { 23543 /* inline bpf_iter_num_next(&it); R1=&it, returns &s->cur or NULL */ 23544 int i = 0; 23545 23546 /* r0 = s->cur + 1; if ((s32)r0 >= s->end) goto done; */ 23547 insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0); 23548 insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_0, 1); 23549 insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4); 23550 insn_buf[i++] = BPF_JMP32_REG(BPF_JSGE, BPF_REG_0, BPF_REG_2, 3); 23551 /* s->cur = r0; return &s->cur; */ 23552 insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0, 0); 23553 insn_buf[i++] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 23554 insn_buf[i++] = BPF_JMP_A(2); 23555 /* done: s->cur = s->end = 0; return NULL; */ 23556 insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0); 23557 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0); 23558 *cnt = i; 23559 } else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_destroy]) { 23560 /* bpf_iter_num_destroy() is a no-op; emit a nop to drop the call */ 23561 insn_buf[0] = BPF_JMP_A(0); 23562 *cnt = 1; 23563 } 23564 23565 if (env->insn_aux_data[insn_idx].arg_prog) { 23566 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 23567 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 23568 int idx = *cnt; 23569 23570 insn_buf[idx++] = ld_addrs[0]; 23571 insn_buf[idx++] = ld_addrs[1]; 23572 insn_buf[idx++] = *insn; 23573 *cnt = idx; 23574 } 23575 return 0; 23576 } 23577 23578 /* 23579 * Upper bound on the PKCS#7 signature blob passed with a program. Comfortably 23580 * above the largest signature the kernel can verify, and far below anything 23581 * that would make rejecting a load expensive. Deliberately a fixed number so 23582 * that what the syscall accepts does not depend on PAGE_SIZE. 23583 */ 23584 #define BPF_PROG_MAX_SIGNATURE_SIZE (64 * 1024) 23585 23586 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id) 23587 { 23588 switch (keyring_id) { 23589 case 0: 23590 return BPF_SIG_KEYRING_BUILTIN; 23591 case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING: 23592 return BPF_SIG_KEYRING_SECONDARY; 23593 case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING: 23594 return BPF_SIG_KEYRING_PLATFORM; 23595 case KEY_SPEC_BPF_KEYRING: 23596 return BPF_SIG_KEYRING_BPF; 23597 default: 23598 return BPF_SIG_KEYRING_USER; 23599 } 23600 } 23601 23602 /* 23603 * Verify the PKCS#7 signature of a loaded program. Called from bpf_check() 23604 * once the program's metadata maps have been resolved into used_maps, so 23605 * the exact maps folded into the signature are the ones the program binds. 23606 * 23607 * The signature covers the instructions followed by the frozen contents of 23608 * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the 23609 * verdict and keyring info are recorded on prog->aux. 23610 */ 23611 static int bpf_prog_verify_signature(struct bpf_verifier_env *env, 23612 union bpf_attr *attr, bool is_kernel) 23613 { 23614 bpfptr_t usig = make_bpfptr(attr->signature, is_kernel); 23615 struct bpf_dynptr_kern sig_ptr, data_ptr; 23616 struct bpf_prog *prog = env->prog; 23617 struct bpf_map **maps = env->used_maps; 23618 struct bpf_key *key = NULL; 23619 void *sig, *data = NULL; 23620 u32 map_cnt = env->used_map_cnt; 23621 u32 i, off, insns_sz; 23622 u64 data_sz; 23623 int err = 0; 23624 23625 /* 23626 * The signature covers the insns as submitted. CO-RE relocations would 23627 * have the kernel rewrite them afterwards, with values the loader picks 23628 * through the BTF it supplies, see bpf_check_core_relo(). 23629 */ 23630 if (attr->core_relo_cnt) { 23631 verbose(env, "signed program cannot carry CO-RE relocations\n"); 23632 return -EACCES; 23633 } 23634 if (!attr->signature_size || 23635 attr->signature_size > BPF_PROG_MAX_SIGNATURE_SIZE) 23636 return -EINVAL; 23637 23638 if (system_keyring_id_check(attr->keyring_id) == 0) { 23639 key = bpf_lookup_system_key(attr->keyring_id); 23640 } else if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) { 23641 key = bpf_lookup_keyring(); 23642 } else if (bpf_keyring_enforced()) { 23643 verbose(env, "caller-supplied keyring refused, use bpf keyring\n"); 23644 return -EPERM; 23645 } else { 23646 key = bpf_lookup_user_key(attr->keyring_id, 0); 23647 } 23648 if (!key) { 23649 if (attr->keyring_id == KEY_SPEC_BPF_KEYRING) { 23650 verbose(env, "the bpf keyring is empty or has not been restricted\n"); 23651 return -ENOKEY; 23652 } 23653 verbose(env, "cannot resolve signing keyring with keyring_id %d\n", 23654 attr->keyring_id); 23655 return -EINVAL; 23656 } 23657 23658 sig = kvmemdup_bpfptr(usig, attr->signature_size); 23659 if (IS_ERR(sig)) { 23660 bpf_key_put(key); 23661 return PTR_ERR(sig); 23662 } 23663 23664 insns_sz = prog->len * sizeof(struct bpf_insn); 23665 data_sz = insns_sz; 23666 for (i = 0; i < map_cnt; i++) { 23667 struct bpf_map *map = maps[i]; 23668 23669 if (map->map_type != BPF_MAP_TYPE_ARRAY || 23670 !map->ops->map_direct_value_addr) { 23671 verbose(env, "signed program metadata map '%s' must be an array\n", 23672 map->name); 23673 err = -EINVAL; 23674 goto out; 23675 } 23676 if (!READ_ONCE(map->frozen)) { 23677 verbose(env, "signed program metadata map '%s' must be frozen\n", 23678 map->name); 23679 err = -EPERM; 23680 goto out; 23681 } 23682 if (bpf_map_write_active(map)) { 23683 verbose(env, "signed program metadata map '%s' has active writers\n", 23684 map->name); 23685 err = -EBUSY; 23686 goto out; 23687 } 23688 if (!map->excl_prog_sha) { 23689 verbose(env, "signed program metadata map '%s' must be exclusive\n", 23690 map->name); 23691 err = -EPERM; 23692 goto out; 23693 } 23694 data_sz += map->value_size; 23695 } 23696 if (bpf_dynptr_check_size(data_sz)) { 23697 verbose(env, "signed payload too large: %llu bytes\n", data_sz); 23698 err = -E2BIG; 23699 goto out; 23700 } 23701 data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO); 23702 if (!data) { 23703 err = -ENOMEM; 23704 goto out; 23705 } 23706 memcpy(data, prog->insnsi, insns_sz); 23707 off = insns_sz; 23708 for (i = 0; i < map_cnt; i++) { 23709 struct bpf_map *map = maps[i]; 23710 u64 addr; 23711 23712 err = map->ops->map_direct_value_addr(map, &addr, 0); 23713 if (err) { 23714 verbose(env, "failed to read signed metadata map '%s': %d\n", 23715 map->name, err); 23716 goto out; 23717 } 23718 memcpy(data + off, (void *)(unsigned long)addr, 23719 map->value_size); 23720 off += map->value_size; 23721 } 23722 23723 bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz); 23724 bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0, 23725 attr->signature_size); 23726 23727 err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr, 23728 (struct bpf_dynptr *)&sig_ptr, key); 23729 if (err) { 23730 verbose(env, "signature verification failed: %d\n", err); 23731 } else { 23732 verbose(env, "signature verification passed\n"); 23733 prog->aux->sig.keyring_serial = bpf_key_serial(key); 23734 prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id); 23735 prog->aux->sig.verdict = BPF_SIG_VERIFIED; 23736 } 23737 out: 23738 kvfree(data); 23739 bpf_key_put(key); 23740 kvfree(sig); 23741 return err; 23742 } 23743 23744 /* 23745 * bpf_clone_redirect() transmits from inside the program, so a tc egress or 23746 * lwt_xmit program that redirects to its own device runs again on top of its 23747 * own frame, and again from there, until the datapath's recursion limit drops 23748 * the packet: ten frames deep. Ten MAX_BPF_STACK frames fit the kernel stack 23749 * as they always did; ten MAX_BPF_STACK_JIT frames would not, so a program 23750 * calling it keeps the smaller budget. The redirect helpers that transmit 23751 * after the program has returned leave no frame behind. 23752 */ 23753 static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog) 23754 { 23755 const struct bpf_insn *insn = prog->insnsi; 23756 int i; 23757 23758 for (i = 0; i < prog->len; i++, insn++) 23759 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_clone_redirect) 23760 return true; 23761 return false; 23762 } 23763 23764 /* Various log level 2 information about the program */ 23765 static void log_program(struct bpf_verifier_env *env) 23766 { 23767 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 23768 struct bpf_insn *insns = env->prog->insnsi; 23769 u32 insn_cnt = env->prog->len; 23770 u64 pos, insn_pos; 23771 u32 i, j; 23772 23773 verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n"); 23774 for (i = 0; i < insn_cnt; ++i) { 23775 verbose_linfo(env, i, " ; "); 23776 if (env->insn_aux_data[i].scc) 23777 verbose(env, "%3d ", env->insn_aux_data[i].scc); 23778 else 23779 verbose(env, " "); 23780 if (env->insn_aux_data[i].loop_header >= 0) 23781 verbose(env, "%3d ", env->insn_aux_data[i].loop_header); 23782 else 23783 verbose(env, " "); 23784 verbose(env, "%3d ", env->idoms[i]); 23785 verbose(env, "%3d: ", i); 23786 for (j = BPF_REG_0; j < BPF_REG_10; ++j) 23787 if (insn_aux[i].live_regs_before & BIT(j)) 23788 verbose(env, "%d", j); 23789 else 23790 verbose(env, "."); 23791 verbose(env, " "); 23792 pos = env->log.end_pos; 23793 bpf_verbose_insn(env, &insns[i]); 23794 insn_pos = env->log.end_pos; 23795 if (insn_aux[i].zext_dst) 23796 verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' '); 23797 verbose(env, "\n"); 23798 if (bpf_is_ldimm64(&insns[i])) 23799 i++; 23800 } 23801 } 23802 23803 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 23804 struct bpf_log_attr *attr_log) 23805 { 23806 u64 start_time = ktime_get_ns(); 23807 struct bpf_verifier_env *env; 23808 int i, len, ret = -EINVAL, err; 23809 bool is_priv; 23810 23811 BTF_TYPE_EMIT(enum bpf_features); 23812 23813 /* no program is valid */ 23814 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 23815 return -EINVAL; 23816 23817 /* 'struct bpf_verifier_env' can be global, but since it's not small, 23818 * allocate/free it every time bpf_check() is called 23819 */ 23820 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 23821 if (!env) 23822 return -ENOMEM; 23823 23824 env->bt.env = env; 23825 env->prog = *prog; 23826 env->ops = bpf_verifier_ops[env->prog->type]; 23827 env->stack_limit = bpf_prog_stack_limit(env->prog); 23828 if (bpf_prog_reenters_datapath(env->prog)) 23829 env->stack_limit = MAX_BPF_STACK; 23830 23831 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 23832 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 23833 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 23834 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 23835 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 23836 env->signature = attr->signature; 23837 23838 /* user could have requested verbose verifier output 23839 * and supplied buffer to store the verification trace 23840 */ 23841 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 23842 if (ret) 23843 goto err_free_env; 23844 ret = bpf_diag_init(env); 23845 if (ret) 23846 goto err_prep; 23847 if (env->prog->insnsi[env->prog->len - 1].code == (BPF_LD | BPF_IMM | BPF_DW)) { 23848 verbose(env, "invalid bpf_ld_imm64 insn\n"); 23849 ret = -EINVAL; 23850 goto err_prep; 23851 } 23852 23853 ret = process_fd_array(env, attr, uattr); 23854 if (ret) 23855 goto err_prep; 23856 23857 if (env->signature) { 23858 ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel); 23859 if (ret) 23860 goto err_prep; 23861 } 23862 23863 ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token, 23864 uattr.is_kernel); 23865 if (ret) 23866 goto err_prep; 23867 23868 bpf_get_btf_vmlinux(); 23869 23870 /* Serialize verification of unprivileged programs. */ 23871 if (!is_priv) 23872 mutex_lock(&bpf_verifier_lock); 23873 23874 len = env->insn_aux_data_len = env->prog->len; 23875 env->insn_aux_data = 23876 __vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len), 23877 GFP_KERNEL_ACCOUNT | __GFP_ZERO); 23878 ret = -ENOMEM; 23879 if (!env->insn_aux_data) 23880 goto skip_full_check; 23881 for (i = 0; i < len; i++) 23882 env->insn_aux_data[i].orig_idx = i; 23883 env->succ = bpf_iarray_realloc(NULL, 2); 23884 if (!env->succ) 23885 goto skip_full_check; 23886 23887 mark_verifier_state_clean(env); 23888 23889 if (IS_ERR(btf_vmlinux)) { 23890 /* Either gcc or pahole or kernel are broken. */ 23891 verbose(env, "in-kernel BTF is malformed\n"); 23892 ret = PTR_ERR(btf_vmlinux); 23893 goto skip_full_check; 23894 } 23895 23896 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 23897 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 23898 env->strict_alignment = true; 23899 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 23900 env->strict_alignment = false; 23901 23902 if (is_priv) 23903 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 23904 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 23905 23906 env->explored_states = kvzalloc_objs(struct list_head, 23907 state_htab_size(env), 23908 GFP_KERNEL_ACCOUNT); 23909 ret = -ENOMEM; 23910 if (!env->explored_states) 23911 goto skip_full_check; 23912 23913 for (i = 0; i < state_htab_size(env); i++) 23914 INIT_LIST_HEAD(&env->explored_states[i]); 23915 INIT_LIST_HEAD(&env->free_list); 23916 23917 /* Prepare BTF and func_info needed to discover all subprograms. */ 23918 ret = bpf_prepare_btf_info(env, attr, uattr); 23919 if (ret < 0) 23920 goto skip_full_check; 23921 23922 /* Apply CO-RE before validating the program's instruction layout. */ 23923 ret = bpf_check_core_relo(env, attr, uattr); 23924 if (ret < 0) 23925 goto skip_full_check; 23926 23927 /* Discover all subprograms and collect the properties needed by BTF validation. */ 23928 ret = add_subprogs(env); 23929 if (ret < 0) 23930 goto skip_full_check; 23931 23932 find_subprog_properties(env); 23933 23934 /* Validate BTF before reporting subprogram layout errors. */ 23935 ret = bpf_check_btf_info(env, attr, uattr); 23936 if (ret < 0) 23937 goto skip_full_check; 23938 23939 ret = check_subprogs(env); 23940 if (ret < 0) 23941 goto skip_full_check; 23942 23943 /* Validate instructions and resolve the program's referenced resources. */ 23944 ret = check_and_resolve_insns(env); 23945 if (ret < 0) 23946 goto skip_full_check; 23947 23948 /* Find pointers to functions in the read-only maps of the program. */ 23949 ret = resolve_func_ptrs(env); 23950 if (ret < 0) 23951 goto skip_full_check; 23952 23953 /* Build kfunc prototypes after resolving program resources. */ 23954 ret = add_kfuncs(env); 23955 if (ret < 0) 23956 goto skip_full_check; 23957 23958 if (bpf_prog_is_offloaded(env->prog->aux)) { 23959 ret = bpf_prog_offload_verifier_prep(env->prog); 23960 if (ret) 23961 goto skip_full_check; 23962 } 23963 23964 ret = bpf_check_cfg(env); 23965 if (ret < 0) 23966 goto skip_full_check; 23967 23968 ret = check_unwind_insns(env); 23969 if (ret < 0) 23970 goto skip_full_check; 23971 23972 ret = bpf_compute_postorder(env); 23973 if (ret < 0) 23974 goto skip_full_check; 23975 23976 ret = bpf_stack_liveness_init(env); 23977 if (ret) 23978 goto skip_full_check; 23979 23980 ret = check_attach_btf_id(env); 23981 if (ret) 23982 goto skip_full_check; 23983 23984 ret = bpf_compute_const_regs(env); 23985 if (ret < 0) 23986 goto skip_full_check; 23987 23988 ret = bpf_prune_dead_branches(env); 23989 if (ret < 0) 23990 goto skip_full_check; 23991 23992 ret = sort_subprogs_topo(env); 23993 if (ret < 0) 23994 goto skip_full_check; 23995 23996 ret = bpf_compute_scc(env); 23997 if (ret < 0) 23998 goto skip_full_check; 23999 24000 /* must precede the first bpf_ret_reg_pair() user below */ 24001 ret = bpf_compute_subprog_ret_regs(env); 24002 if (ret < 0) 24003 goto skip_full_check; 24004 24005 prepare_subprog_args(env); 24006 24007 ret = bpf_compute_idoms(env); 24008 if (ret < 0) 24009 goto skip_full_check; 24010 24011 ret = bpf_compute_loops(env); 24012 if (ret < 0) 24013 goto skip_full_check; 24014 24015 ret = bpf_compute_live_registers(env); 24016 if (ret < 0) 24017 goto skip_full_check; 24018 24019 if (env->log.level & BPF_LOG_LEVEL2) 24020 log_program(env); 24021 24022 ret = bpf_init_scev(env); 24023 if (ret < 0) 24024 goto skip_full_check; 24025 24026 ret = bpf_compute_scev(env); 24027 if (ret < 0) 24028 goto skip_full_check; 24029 24030 bpf_free_subprog_jts(env); 24031 24032 ret = mark_fastcall_patterns(env); 24033 if (ret < 0) 24034 goto skip_full_check; 24035 24036 ret = do_check_main(env); 24037 ret = ret ?: do_check_subprogs(env); 24038 24039 /* reject recursion through the callx edges found by the main pass */ 24040 if (ret == 0 && env->callx_edges) 24041 ret = sort_subprogs_topo(env); 24042 24043 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 24044 ret = bpf_prog_offload_finalize(env); 24045 24046 skip_full_check: 24047 kvfree(env->explored_states); 24048 24049 /* might decrease stack depth, keep it before passes that 24050 * allocate additional slots. 24051 */ 24052 if (ret == 0) 24053 ret = bpf_remove_fastcall_spills_fills(env); 24054 24055 if (ret == 0) 24056 ret = check_max_stack_depth(env); 24057 24058 /* instruction rewrites happen after this point */ 24059 if (ret == 0) 24060 ret = bpf_optimize_bpf_loop(env); 24061 24062 if (is_priv) { 24063 if (ret == 0) 24064 bpf_opt_hard_wire_dead_code_branches(env); 24065 if (ret == 0) 24066 ret = bpf_opt_remove_dead_code(env); 24067 if (ret == 0) 24068 ret = bpf_opt_remove_nops(env); 24069 } else { 24070 if (ret == 0) 24071 sanitize_dead_code(env); 24072 } 24073 24074 if (ret == 0) 24075 /* program is valid, convert *(u32*)(ctx + off) accesses */ 24076 ret = bpf_convert_ctx_accesses(env); 24077 24078 if (ret == 0) 24079 ret = bpf_do_misc_fixups(env); 24080 24081 /* do 32-bit optimization after insn patching has done so those patched 24082 * insns could be handled correctly. 24083 */ 24084 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 24085 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 24086 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 24087 : false; 24088 } 24089 24090 if (ret == 0) 24091 ret = bpf_fixup_call_args(env); 24092 24093 env->verification_time = ktime_get_ns() - start_time; 24094 print_verification_stats(env); 24095 env->prog->aux->verified_insns = env->insn_processed; 24096 24097 /* preserve original error even if log finalization is successful */ 24098 err = bpf_log_attr_finalize(attr_log, &env->log); 24099 if (err) 24100 ret = err; 24101 24102 if (ret) 24103 goto err_release_maps; 24104 24105 if (env->used_map_cnt) { 24106 /* if program passed verifier, update used_maps in bpf_prog_info */ 24107 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 24108 env->used_map_cnt, 24109 GFP_KERNEL_ACCOUNT); 24110 24111 if (!env->prog->aux->used_maps) { 24112 ret = -ENOMEM; 24113 goto err_release_maps; 24114 } 24115 24116 memcpy(env->prog->aux->used_maps, env->used_maps, 24117 sizeof(env->used_maps[0]) * env->used_map_cnt); 24118 env->prog->aux->used_map_cnt = env->used_map_cnt; 24119 } 24120 if (env->used_btf_cnt) { 24121 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 24122 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 24123 env->used_btf_cnt, 24124 GFP_KERNEL_ACCOUNT); 24125 if (!env->prog->aux->used_btfs) { 24126 ret = -ENOMEM; 24127 goto err_release_maps; 24128 } 24129 24130 memcpy(env->prog->aux->used_btfs, env->used_btfs, 24131 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 24132 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 24133 } 24134 if (env->used_map_cnt || env->used_btf_cnt) { 24135 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 24136 * bpf_ld_imm64 instructions 24137 */ 24138 convert_pseudo_ld_imm64(env); 24139 } 24140 24141 adjust_btf_func(env); 24142 24143 /* extension progs temporarily inherit the attach_type of their targets 24144 for verification purposes, so set it back to zero before returning 24145 */ 24146 if (env->prog->type == BPF_PROG_TYPE_EXT) 24147 env->prog->expected_attach_type = 0; 24148 24149 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 24150 24151 err_release_maps: 24152 if (ret) 24153 release_insn_arrays(env); 24154 if (!env->prog->aux->used_maps) 24155 /* if we didn't copy map pointers into bpf_prog_info, release 24156 * them now. Otherwise free_used_maps() will release them. 24157 */ 24158 release_maps(env); 24159 if (!env->prog->aux->used_btfs) 24160 release_btfs(env); 24161 24162 *prog = env->prog; 24163 24164 module_put(env->attach_btf_mod); 24165 if (!is_priv) 24166 mutex_unlock(&bpf_verifier_lock); 24167 goto err_free_env; 24168 err_prep: 24169 err = bpf_log_attr_finalize(attr_log, &env->log); 24170 if (err) 24171 ret = err; 24172 release_insn_arrays(env); 24173 release_maps(env); 24174 release_btfs(env); 24175 err_free_env: 24176 bpf_free_subprog_jts(env); 24177 if (env->insn_aux_data) 24178 bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len); 24179 vfree(env->insn_aux_data); 24180 kvfree(env->fd_array); 24181 bpf_free_scev(env); 24182 bpf_stack_liveness_free(env); 24183 kvfree(env->cfg.postorder_nums); 24184 kvfree(env->cfg.insn_postorder); 24185 kvfree(env->scc_info); 24186 kvfree(env->succ); 24187 kvfree(env->gotox_tmp_buf); 24188 kvfree(env->callx_edges); 24189 kvfree(env->func_ptrs); 24190 bpf_diag_free(env); 24191 kvfree(env->idoms); 24192 kvfree(env); 24193 return ret; 24194 } 24195