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/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 32 #include "disasm.h" 33 34 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 35 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 36 [_id] = & _name ## _verifier_ops, 37 #define BPF_MAP_TYPE(_id, _ops) 38 #define BPF_LINK_TYPE(_id, _name) 39 #include <linux/bpf_types.h> 40 #undef BPF_PROG_TYPE 41 #undef BPF_MAP_TYPE 42 #undef BPF_LINK_TYPE 43 }; 44 45 struct bpf_mem_alloc bpf_global_percpu_ma; 46 static bool bpf_global_percpu_ma_set; 47 48 /* bpf_check() is a static code analyzer that walks eBPF program 49 * instruction by instruction and updates register/stack state. 50 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 51 * 52 * The first pass is depth-first-search to check that the program is a DAG. 53 * It rejects the following programs: 54 * - larger than BPF_MAXINSNS insns 55 * - if loop is present (detected via back-edge) 56 * - unreachable insns exist (shouldn't be a forest. program = one function) 57 * - out of bounds or malformed jumps 58 * The second pass is all possible path descent from the 1st insn. 59 * Since it's analyzing all paths through the program, the length of the 60 * analysis is limited to 64k insn, which may be hit even if total number of 61 * insn is less then 4K, but there are too many branches that change stack/regs. 62 * Number of 'branches to be analyzed' is limited to 1k 63 * 64 * On entry to each instruction, each register has a type, and the instruction 65 * changes the types of the registers depending on instruction semantics. 66 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 67 * copied to R1. 68 * 69 * All registers are 64-bit. 70 * R0 - return register 71 * R1-R5 argument passing registers 72 * R6-R9 callee saved registers 73 * R10 - frame pointer read-only 74 * 75 * At the start of BPF program the register R1 contains a pointer to bpf_context 76 * and has type PTR_TO_CTX. 77 * 78 * Verifier tracks arithmetic operations on pointers in case: 79 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 80 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 81 * 1st insn copies R10 (which has FRAME_PTR) type into R1 82 * and 2nd arithmetic instruction is pattern matched to recognize 83 * that it wants to construct a pointer to some element within stack. 84 * So after 2nd insn, the register R1 has type PTR_TO_STACK 85 * (and -20 constant is saved for further stack bounds checking). 86 * Meaning that this reg is a pointer to stack plus known immediate constant. 87 * 88 * Most of the time the registers have SCALAR_VALUE type, which 89 * means the register has some value, but it's not a valid pointer. 90 * (like pointer plus pointer becomes SCALAR_VALUE type) 91 * 92 * When verifier sees load or store instructions the type of base register 93 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 94 * four pointer types recognized by check_mem_access() function. 95 * 96 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 97 * and the range of [ptr, ptr + map's value_size) is accessible. 98 * 99 * registers used to pass values to function calls are checked against 100 * function argument constraints. 101 * 102 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 103 * It means that the register type passed to this function must be 104 * PTR_TO_STACK and it will be used inside the function as 105 * 'pointer to map element key' 106 * 107 * For example the argument constraints for bpf_map_lookup_elem(): 108 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 109 * .arg1_type = ARG_CONST_MAP_PTR, 110 * .arg2_type = ARG_PTR_TO_MAP_KEY, 111 * 112 * ret_type says that this function returns 'pointer to map elem value or null' 113 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 114 * 2nd argument should be a pointer to stack, which will be used inside 115 * the helper function as a pointer to map element key. 116 * 117 * On the kernel side the helper function looks like: 118 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 119 * { 120 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 121 * void *key = (void *) (unsigned long) r2; 122 * void *value; 123 * 124 * here kernel can access 'key' and 'map' pointers safely, knowing that 125 * [key, key + map->key_size) bytes are valid and were initialized on 126 * the stack of eBPF program. 127 * } 128 * 129 * Corresponding eBPF program may look like: 130 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 131 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 132 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 133 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 134 * here verifier looks at prototype of map_lookup_elem() and sees: 135 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 136 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 137 * 138 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 139 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 140 * and were initialized prior to this call. 141 * If it's ok, then verifier allows this BPF_CALL insn and looks at 142 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 143 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 144 * returns either pointer to map value or NULL. 145 * 146 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 147 * insn, the register holding that pointer in the true branch changes state to 148 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 149 * branch. See check_cond_jmp_op(). 150 * 151 * After the call R0 is set to return type of the function and registers R1-R5 152 * are set to NOT_INIT to indicate that they are no longer readable. 153 * 154 * The following reference types represent a potential reference to a kernel 155 * resource which, after first being allocated, must be checked and freed by 156 * the BPF program: 157 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 158 * 159 * When the verifier sees a helper call return a reference type, it allocates a 160 * pointer id for the reference and stores it in the current function state. 161 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 162 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 163 * passes through a NULL-check conditional. For the branch wherein the state is 164 * changed to CONST_IMM, the verifier releases the reference. 165 * 166 * For each helper function that allocates a reference, such as 167 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 168 * bpf_sk_release(). When a reference type passes into the release function, 169 * the verifier also releases the reference. If any unchecked or unreleased 170 * reference remains at the end of the program, the verifier rejects it. 171 */ 172 173 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 174 struct bpf_verifier_stack_elem { 175 /* verifier state is 'st' 176 * before processing instruction 'insn_idx' 177 * and after processing instruction 'prev_insn_idx' 178 */ 179 struct bpf_verifier_state st; 180 int insn_idx; 181 int prev_insn_idx; 182 struct bpf_verifier_stack_elem *next; 183 /* length of verifier log at the time this state was pushed on stack */ 184 u32 log_pos; 185 }; 186 187 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 188 #define BPF_COMPLEXITY_LIMIT_STATES 64 189 190 #define BPF_MAP_KEY_POISON (1ULL << 63) 191 #define BPF_MAP_KEY_SEEN (1ULL << 62) 192 193 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 194 195 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 196 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 197 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 198 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 199 static int ref_set_non_owning(struct bpf_verifier_env *env, 200 struct bpf_reg_state *reg); 201 static void specialize_kfunc(struct bpf_verifier_env *env, 202 u32 func_id, u16 offset, unsigned long *addr); 203 static bool is_trusted_reg(const struct bpf_reg_state *reg); 204 205 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 206 { 207 return aux->map_ptr_state.poison; 208 } 209 210 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 211 { 212 return aux->map_ptr_state.unpriv; 213 } 214 215 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 216 struct bpf_map *map, 217 bool unpriv, bool poison) 218 { 219 unpriv |= bpf_map_ptr_unpriv(aux); 220 aux->map_ptr_state.unpriv = unpriv; 221 aux->map_ptr_state.poison = poison; 222 aux->map_ptr_state.map_ptr = map; 223 } 224 225 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 226 { 227 return aux->map_key_state & BPF_MAP_KEY_POISON; 228 } 229 230 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 231 { 232 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 233 } 234 235 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 236 { 237 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 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 bool bpf_helper_call(const struct bpf_insn *insn) 249 { 250 return insn->code == (BPF_JMP | BPF_CALL) && 251 insn->src_reg == 0; 252 } 253 254 static bool bpf_pseudo_call(const struct bpf_insn *insn) 255 { 256 return insn->code == (BPF_JMP | BPF_CALL) && 257 insn->src_reg == BPF_PSEUDO_CALL; 258 } 259 260 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 261 { 262 return insn->code == (BPF_JMP | BPF_CALL) && 263 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 264 } 265 266 struct bpf_call_arg_meta { 267 struct bpf_map *map_ptr; 268 bool raw_mode; 269 bool pkt_access; 270 u8 release_regno; 271 int regno; 272 int access_size; 273 int mem_size; 274 u64 msize_max_value; 275 int ref_obj_id; 276 int dynptr_id; 277 int map_uid; 278 int func_id; 279 struct btf *btf; 280 u32 btf_id; 281 struct btf *ret_btf; 282 u32 ret_btf_id; 283 u32 subprogno; 284 struct btf_field *kptr_field; 285 }; 286 287 struct bpf_kfunc_call_arg_meta { 288 /* In parameters */ 289 struct btf *btf; 290 u32 func_id; 291 u32 kfunc_flags; 292 const struct btf_type *func_proto; 293 const char *func_name; 294 /* Out parameters */ 295 u32 ref_obj_id; 296 u8 release_regno; 297 bool r0_rdonly; 298 u32 ret_btf_id; 299 u64 r0_size; 300 u32 subprogno; 301 struct { 302 u64 value; 303 bool found; 304 } arg_constant; 305 306 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 307 * generally to pass info about user-defined local kptr types to later 308 * verification logic 309 * bpf_obj_drop/bpf_percpu_obj_drop 310 * Record the local kptr type to be drop'd 311 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 312 * Record the local kptr type to be refcount_incr'd and use 313 * arg_owning_ref to determine whether refcount_acquire should be 314 * fallible 315 */ 316 struct btf *arg_btf; 317 u32 arg_btf_id; 318 bool arg_owning_ref; 319 320 struct { 321 struct btf_field *field; 322 } arg_list_head; 323 struct { 324 struct btf_field *field; 325 } arg_rbtree_root; 326 struct { 327 enum bpf_dynptr_type type; 328 u32 id; 329 u32 ref_obj_id; 330 } initialized_dynptr; 331 struct { 332 u8 spi; 333 u8 frameno; 334 } iter; 335 struct { 336 struct bpf_map *ptr; 337 int uid; 338 } map; 339 u64 mem_size; 340 }; 341 342 struct btf *btf_vmlinux; 343 344 static const char *btf_type_name(const struct btf *btf, u32 id) 345 { 346 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 347 } 348 349 static DEFINE_MUTEX(bpf_verifier_lock); 350 static DEFINE_MUTEX(bpf_percpu_ma_lock); 351 352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 353 { 354 struct bpf_verifier_env *env = private_data; 355 va_list args; 356 357 if (!bpf_verifier_log_needed(&env->log)) 358 return; 359 360 va_start(args, fmt); 361 bpf_verifier_vlog(&env->log, fmt, args); 362 va_end(args); 363 } 364 365 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 366 struct bpf_reg_state *reg, 367 struct bpf_retval_range range, const char *ctx, 368 const char *reg_name) 369 { 370 bool unknown = true; 371 372 verbose(env, "%s the register %s has", ctx, reg_name); 373 if (reg->smin_value > S64_MIN) { 374 verbose(env, " smin=%lld", reg->smin_value); 375 unknown = false; 376 } 377 if (reg->smax_value < S64_MAX) { 378 verbose(env, " smax=%lld", reg->smax_value); 379 unknown = false; 380 } 381 if (unknown) 382 verbose(env, " unknown scalar value"); 383 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 384 } 385 386 static bool type_may_be_null(u32 type) 387 { 388 return type & PTR_MAYBE_NULL; 389 } 390 391 static bool reg_not_null(const struct bpf_reg_state *reg) 392 { 393 enum bpf_reg_type type; 394 395 type = reg->type; 396 if (type_may_be_null(type)) 397 return false; 398 399 type = base_type(type); 400 return type == PTR_TO_SOCKET || 401 type == PTR_TO_TCP_SOCK || 402 type == PTR_TO_MAP_VALUE || 403 type == PTR_TO_MAP_KEY || 404 type == PTR_TO_SOCK_COMMON || 405 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 406 type == PTR_TO_MEM; 407 } 408 409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 410 { 411 struct btf_record *rec = NULL; 412 struct btf_struct_meta *meta; 413 414 if (reg->type == PTR_TO_MAP_VALUE) { 415 rec = reg->map_ptr->record; 416 } else if (type_is_ptr_alloc_obj(reg->type)) { 417 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 418 if (meta) 419 rec = meta->record; 420 } 421 return rec; 422 } 423 424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 425 { 426 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 427 428 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 429 } 430 431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 432 { 433 struct bpf_func_info *info; 434 435 if (!env->prog->aux->func_info) 436 return ""; 437 438 info = &env->prog->aux->func_info[subprog]; 439 return btf_type_name(env->prog->aux->btf, info->type_id); 440 } 441 442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 443 { 444 struct bpf_subprog_info *info = subprog_info(env, subprog); 445 446 info->is_cb = true; 447 info->is_async_cb = true; 448 info->is_exception_cb = true; 449 } 450 451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 452 { 453 return subprog_info(env, subprog)->is_exception_cb; 454 } 455 456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 457 { 458 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 459 } 460 461 static bool type_is_rdonly_mem(u32 type) 462 { 463 return type & MEM_RDONLY; 464 } 465 466 static bool is_acquire_function(enum bpf_func_id func_id, 467 const struct bpf_map *map) 468 { 469 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 470 471 if (func_id == BPF_FUNC_sk_lookup_tcp || 472 func_id == BPF_FUNC_sk_lookup_udp || 473 func_id == BPF_FUNC_skc_lookup_tcp || 474 func_id == BPF_FUNC_ringbuf_reserve || 475 func_id == BPF_FUNC_kptr_xchg) 476 return true; 477 478 if (func_id == BPF_FUNC_map_lookup_elem && 479 (map_type == BPF_MAP_TYPE_SOCKMAP || 480 map_type == BPF_MAP_TYPE_SOCKHASH)) 481 return true; 482 483 return false; 484 } 485 486 static bool is_ptr_cast_function(enum bpf_func_id func_id) 487 { 488 return func_id == BPF_FUNC_tcp_sock || 489 func_id == BPF_FUNC_sk_fullsock || 490 func_id == BPF_FUNC_skc_to_tcp_sock || 491 func_id == BPF_FUNC_skc_to_tcp6_sock || 492 func_id == BPF_FUNC_skc_to_udp6_sock || 493 func_id == BPF_FUNC_skc_to_mptcp_sock || 494 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 495 func_id == BPF_FUNC_skc_to_tcp_request_sock; 496 } 497 498 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 499 { 500 return func_id == BPF_FUNC_dynptr_data; 501 } 502 503 static bool is_sync_callback_calling_kfunc(u32 btf_id); 504 static bool is_async_callback_calling_kfunc(u32 btf_id); 505 static bool is_callback_calling_kfunc(u32 btf_id); 506 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 507 508 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 509 510 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 511 { 512 return func_id == BPF_FUNC_for_each_map_elem || 513 func_id == BPF_FUNC_find_vma || 514 func_id == BPF_FUNC_loop || 515 func_id == BPF_FUNC_user_ringbuf_drain; 516 } 517 518 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 519 { 520 return func_id == BPF_FUNC_timer_set_callback; 521 } 522 523 static bool is_callback_calling_function(enum bpf_func_id func_id) 524 { 525 return is_sync_callback_calling_function(func_id) || 526 is_async_callback_calling_function(func_id); 527 } 528 529 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 530 { 531 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 532 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 533 } 534 535 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 536 { 537 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 538 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 539 } 540 541 static bool is_may_goto_insn(struct bpf_insn *insn) 542 { 543 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 544 } 545 546 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 547 { 548 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 549 } 550 551 static bool is_storage_get_function(enum bpf_func_id func_id) 552 { 553 return func_id == BPF_FUNC_sk_storage_get || 554 func_id == BPF_FUNC_inode_storage_get || 555 func_id == BPF_FUNC_task_storage_get || 556 func_id == BPF_FUNC_cgrp_storage_get; 557 } 558 559 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 560 const struct bpf_map *map) 561 { 562 int ref_obj_uses = 0; 563 564 if (is_ptr_cast_function(func_id)) 565 ref_obj_uses++; 566 if (is_acquire_function(func_id, map)) 567 ref_obj_uses++; 568 if (is_dynptr_ref_function(func_id)) 569 ref_obj_uses++; 570 571 return ref_obj_uses > 1; 572 } 573 574 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 575 { 576 return BPF_CLASS(insn->code) == BPF_STX && 577 BPF_MODE(insn->code) == BPF_ATOMIC && 578 insn->imm == BPF_CMPXCHG; 579 } 580 581 static int __get_spi(s32 off) 582 { 583 return (-off - 1) / BPF_REG_SIZE; 584 } 585 586 static struct bpf_func_state *func(struct bpf_verifier_env *env, 587 const struct bpf_reg_state *reg) 588 { 589 struct bpf_verifier_state *cur = env->cur_state; 590 591 return cur->frame[reg->frameno]; 592 } 593 594 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 595 { 596 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 597 598 /* We need to check that slots between [spi - nr_slots + 1, spi] are 599 * within [0, allocated_stack). 600 * 601 * Please note that the spi grows downwards. For example, a dynptr 602 * takes the size of two stack slots; the first slot will be at 603 * spi and the second slot will be at spi - 1. 604 */ 605 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 606 } 607 608 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 609 const char *obj_kind, int nr_slots) 610 { 611 int off, spi; 612 613 if (!tnum_is_const(reg->var_off)) { 614 verbose(env, "%s has to be at a constant offset\n", obj_kind); 615 return -EINVAL; 616 } 617 618 off = reg->off + reg->var_off.value; 619 if (off % BPF_REG_SIZE) { 620 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 621 return -EINVAL; 622 } 623 624 spi = __get_spi(off); 625 if (spi + 1 < nr_slots) { 626 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 627 return -EINVAL; 628 } 629 630 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 631 return -ERANGE; 632 return spi; 633 } 634 635 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 636 { 637 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 638 } 639 640 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 641 { 642 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 643 } 644 645 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 646 { 647 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 648 case DYNPTR_TYPE_LOCAL: 649 return BPF_DYNPTR_TYPE_LOCAL; 650 case DYNPTR_TYPE_RINGBUF: 651 return BPF_DYNPTR_TYPE_RINGBUF; 652 case DYNPTR_TYPE_SKB: 653 return BPF_DYNPTR_TYPE_SKB; 654 case DYNPTR_TYPE_XDP: 655 return BPF_DYNPTR_TYPE_XDP; 656 default: 657 return BPF_DYNPTR_TYPE_INVALID; 658 } 659 } 660 661 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 662 { 663 switch (type) { 664 case BPF_DYNPTR_TYPE_LOCAL: 665 return DYNPTR_TYPE_LOCAL; 666 case BPF_DYNPTR_TYPE_RINGBUF: 667 return DYNPTR_TYPE_RINGBUF; 668 case BPF_DYNPTR_TYPE_SKB: 669 return DYNPTR_TYPE_SKB; 670 case BPF_DYNPTR_TYPE_XDP: 671 return DYNPTR_TYPE_XDP; 672 default: 673 return 0; 674 } 675 } 676 677 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 678 { 679 return type == BPF_DYNPTR_TYPE_RINGBUF; 680 } 681 682 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 683 enum bpf_dynptr_type type, 684 bool first_slot, int dynptr_id); 685 686 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 687 struct bpf_reg_state *reg); 688 689 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 690 struct bpf_reg_state *sreg1, 691 struct bpf_reg_state *sreg2, 692 enum bpf_dynptr_type type) 693 { 694 int id = ++env->id_gen; 695 696 __mark_dynptr_reg(sreg1, type, true, id); 697 __mark_dynptr_reg(sreg2, type, false, id); 698 } 699 700 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 701 struct bpf_reg_state *reg, 702 enum bpf_dynptr_type type) 703 { 704 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 705 } 706 707 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 708 struct bpf_func_state *state, int spi); 709 710 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 711 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 712 { 713 struct bpf_func_state *state = func(env, reg); 714 enum bpf_dynptr_type type; 715 int spi, i, err; 716 717 spi = dynptr_get_spi(env, reg); 718 if (spi < 0) 719 return spi; 720 721 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 722 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 723 * to ensure that for the following example: 724 * [d1][d1][d2][d2] 725 * spi 3 2 1 0 726 * So marking spi = 2 should lead to destruction of both d1 and d2. In 727 * case they do belong to same dynptr, second call won't see slot_type 728 * as STACK_DYNPTR and will simply skip destruction. 729 */ 730 err = destroy_if_dynptr_stack_slot(env, state, spi); 731 if (err) 732 return err; 733 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 734 if (err) 735 return err; 736 737 for (i = 0; i < BPF_REG_SIZE; i++) { 738 state->stack[spi].slot_type[i] = STACK_DYNPTR; 739 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 740 } 741 742 type = arg_to_dynptr_type(arg_type); 743 if (type == BPF_DYNPTR_TYPE_INVALID) 744 return -EINVAL; 745 746 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 747 &state->stack[spi - 1].spilled_ptr, type); 748 749 if (dynptr_type_refcounted(type)) { 750 /* The id is used to track proper releasing */ 751 int id; 752 753 if (clone_ref_obj_id) 754 id = clone_ref_obj_id; 755 else 756 id = acquire_reference_state(env, insn_idx); 757 758 if (id < 0) 759 return id; 760 761 state->stack[spi].spilled_ptr.ref_obj_id = id; 762 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 763 } 764 765 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 766 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 767 768 return 0; 769 } 770 771 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 772 { 773 int i; 774 775 for (i = 0; i < BPF_REG_SIZE; i++) { 776 state->stack[spi].slot_type[i] = STACK_INVALID; 777 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 778 } 779 780 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 781 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 782 783 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 784 * 785 * While we don't allow reading STACK_INVALID, it is still possible to 786 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 787 * helpers or insns can do partial read of that part without failing, 788 * but check_stack_range_initialized, check_stack_read_var_off, and 789 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 790 * the slot conservatively. Hence we need to prevent those liveness 791 * marking walks. 792 * 793 * This was not a problem before because STACK_INVALID is only set by 794 * default (where the default reg state has its reg->parent as NULL), or 795 * in clean_live_states after REG_LIVE_DONE (at which point 796 * mark_reg_read won't walk reg->parent chain), but not randomly during 797 * verifier state exploration (like we did above). Hence, for our case 798 * parentage chain will still be live (i.e. reg->parent may be 799 * non-NULL), while earlier reg->parent was NULL, so we need 800 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 801 * done later on reads or by mark_dynptr_read as well to unnecessary 802 * mark registers in verifier state. 803 */ 804 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 805 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 806 } 807 808 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 809 { 810 struct bpf_func_state *state = func(env, reg); 811 int spi, ref_obj_id, i; 812 813 spi = dynptr_get_spi(env, reg); 814 if (spi < 0) 815 return spi; 816 817 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 818 invalidate_dynptr(env, state, spi); 819 return 0; 820 } 821 822 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 823 824 /* If the dynptr has a ref_obj_id, then we need to invalidate 825 * two things: 826 * 827 * 1) Any dynptrs with a matching ref_obj_id (clones) 828 * 2) Any slices derived from this dynptr. 829 */ 830 831 /* Invalidate any slices associated with this dynptr */ 832 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 833 834 /* Invalidate any dynptr clones */ 835 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 836 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 837 continue; 838 839 /* it should always be the case that if the ref obj id 840 * matches then the stack slot also belongs to a 841 * dynptr 842 */ 843 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 844 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 845 return -EFAULT; 846 } 847 if (state->stack[i].spilled_ptr.dynptr.first_slot) 848 invalidate_dynptr(env, state, i); 849 } 850 851 return 0; 852 } 853 854 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 855 struct bpf_reg_state *reg); 856 857 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 858 { 859 if (!env->allow_ptr_leaks) 860 __mark_reg_not_init(env, reg); 861 else 862 __mark_reg_unknown(env, reg); 863 } 864 865 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 866 struct bpf_func_state *state, int spi) 867 { 868 struct bpf_func_state *fstate; 869 struct bpf_reg_state *dreg; 870 int i, dynptr_id; 871 872 /* We always ensure that STACK_DYNPTR is never set partially, 873 * hence just checking for slot_type[0] is enough. This is 874 * different for STACK_SPILL, where it may be only set for 875 * 1 byte, so code has to use is_spilled_reg. 876 */ 877 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 878 return 0; 879 880 /* Reposition spi to first slot */ 881 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 882 spi = spi + 1; 883 884 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 885 verbose(env, "cannot overwrite referenced dynptr\n"); 886 return -EINVAL; 887 } 888 889 mark_stack_slot_scratched(env, spi); 890 mark_stack_slot_scratched(env, spi - 1); 891 892 /* Writing partially to one dynptr stack slot destroys both. */ 893 for (i = 0; i < BPF_REG_SIZE; i++) { 894 state->stack[spi].slot_type[i] = STACK_INVALID; 895 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 896 } 897 898 dynptr_id = state->stack[spi].spilled_ptr.id; 899 /* Invalidate any slices associated with this dynptr */ 900 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 901 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 902 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 903 continue; 904 if (dreg->dynptr_id == dynptr_id) 905 mark_reg_invalid(env, dreg); 906 })); 907 908 /* Do not release reference state, we are destroying dynptr on stack, 909 * not using some helper to release it. Just reset register. 910 */ 911 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 912 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 913 914 /* Same reason as unmark_stack_slots_dynptr above */ 915 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 916 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 917 918 return 0; 919 } 920 921 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 922 { 923 int spi; 924 925 if (reg->type == CONST_PTR_TO_DYNPTR) 926 return false; 927 928 spi = dynptr_get_spi(env, reg); 929 930 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 931 * error because this just means the stack state hasn't been updated yet. 932 * We will do check_mem_access to check and update stack bounds later. 933 */ 934 if (spi < 0 && spi != -ERANGE) 935 return false; 936 937 /* We don't need to check if the stack slots are marked by previous 938 * dynptr initializations because we allow overwriting existing unreferenced 939 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 940 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 941 * touching are completely destructed before we reinitialize them for a new 942 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 943 * instead of delaying it until the end where the user will get "Unreleased 944 * reference" error. 945 */ 946 return true; 947 } 948 949 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 950 { 951 struct bpf_func_state *state = func(env, reg); 952 int i, spi; 953 954 /* This already represents first slot of initialized bpf_dynptr. 955 * 956 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 957 * check_func_arg_reg_off's logic, so we don't need to check its 958 * offset and alignment. 959 */ 960 if (reg->type == CONST_PTR_TO_DYNPTR) 961 return true; 962 963 spi = dynptr_get_spi(env, reg); 964 if (spi < 0) 965 return false; 966 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 967 return false; 968 969 for (i = 0; i < BPF_REG_SIZE; i++) { 970 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 971 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 972 return false; 973 } 974 975 return true; 976 } 977 978 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 979 enum bpf_arg_type arg_type) 980 { 981 struct bpf_func_state *state = func(env, reg); 982 enum bpf_dynptr_type dynptr_type; 983 int spi; 984 985 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 986 if (arg_type == ARG_PTR_TO_DYNPTR) 987 return true; 988 989 dynptr_type = arg_to_dynptr_type(arg_type); 990 if (reg->type == CONST_PTR_TO_DYNPTR) { 991 return reg->dynptr.type == dynptr_type; 992 } else { 993 spi = dynptr_get_spi(env, reg); 994 if (spi < 0) 995 return false; 996 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 997 } 998 } 999 1000 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1001 1002 static bool in_rcu_cs(struct bpf_verifier_env *env); 1003 1004 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1005 1006 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1007 struct bpf_kfunc_call_arg_meta *meta, 1008 struct bpf_reg_state *reg, int insn_idx, 1009 struct btf *btf, u32 btf_id, int nr_slots) 1010 { 1011 struct bpf_func_state *state = func(env, reg); 1012 int spi, i, j, id; 1013 1014 spi = iter_get_spi(env, reg, nr_slots); 1015 if (spi < 0) 1016 return spi; 1017 1018 id = acquire_reference_state(env, insn_idx); 1019 if (id < 0) 1020 return id; 1021 1022 for (i = 0; i < nr_slots; i++) { 1023 struct bpf_stack_state *slot = &state->stack[spi - i]; 1024 struct bpf_reg_state *st = &slot->spilled_ptr; 1025 1026 __mark_reg_known_zero(st); 1027 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1028 if (is_kfunc_rcu_protected(meta)) { 1029 if (in_rcu_cs(env)) 1030 st->type |= MEM_RCU; 1031 else 1032 st->type |= PTR_UNTRUSTED; 1033 } 1034 st->live |= REG_LIVE_WRITTEN; 1035 st->ref_obj_id = i == 0 ? id : 0; 1036 st->iter.btf = btf; 1037 st->iter.btf_id = btf_id; 1038 st->iter.state = BPF_ITER_STATE_ACTIVE; 1039 st->iter.depth = 0; 1040 1041 for (j = 0; j < BPF_REG_SIZE; j++) 1042 slot->slot_type[j] = STACK_ITER; 1043 1044 mark_stack_slot_scratched(env, spi - i); 1045 } 1046 1047 return 0; 1048 } 1049 1050 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1051 struct bpf_reg_state *reg, int nr_slots) 1052 { 1053 struct bpf_func_state *state = func(env, reg); 1054 int spi, i, j; 1055 1056 spi = iter_get_spi(env, reg, nr_slots); 1057 if (spi < 0) 1058 return spi; 1059 1060 for (i = 0; i < nr_slots; i++) { 1061 struct bpf_stack_state *slot = &state->stack[spi - i]; 1062 struct bpf_reg_state *st = &slot->spilled_ptr; 1063 1064 if (i == 0) 1065 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1066 1067 __mark_reg_not_init(env, st); 1068 1069 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1070 st->live |= REG_LIVE_WRITTEN; 1071 1072 for (j = 0; j < BPF_REG_SIZE; j++) 1073 slot->slot_type[j] = STACK_INVALID; 1074 1075 mark_stack_slot_scratched(env, spi - i); 1076 } 1077 1078 return 0; 1079 } 1080 1081 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1082 struct bpf_reg_state *reg, int nr_slots) 1083 { 1084 struct bpf_func_state *state = func(env, reg); 1085 int spi, i, j; 1086 1087 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1088 * will do check_mem_access to check and update stack bounds later, so 1089 * return true for that case. 1090 */ 1091 spi = iter_get_spi(env, reg, nr_slots); 1092 if (spi == -ERANGE) 1093 return true; 1094 if (spi < 0) 1095 return false; 1096 1097 for (i = 0; i < nr_slots; i++) { 1098 struct bpf_stack_state *slot = &state->stack[spi - i]; 1099 1100 for (j = 0; j < BPF_REG_SIZE; j++) 1101 if (slot->slot_type[j] == STACK_ITER) 1102 return false; 1103 } 1104 1105 return true; 1106 } 1107 1108 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1109 struct btf *btf, u32 btf_id, int nr_slots) 1110 { 1111 struct bpf_func_state *state = func(env, reg); 1112 int spi, i, j; 1113 1114 spi = iter_get_spi(env, reg, nr_slots); 1115 if (spi < 0) 1116 return -EINVAL; 1117 1118 for (i = 0; i < nr_slots; i++) { 1119 struct bpf_stack_state *slot = &state->stack[spi - i]; 1120 struct bpf_reg_state *st = &slot->spilled_ptr; 1121 1122 if (st->type & PTR_UNTRUSTED) 1123 return -EPROTO; 1124 /* only main (first) slot has ref_obj_id set */ 1125 if (i == 0 && !st->ref_obj_id) 1126 return -EINVAL; 1127 if (i != 0 && st->ref_obj_id) 1128 return -EINVAL; 1129 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1130 return -EINVAL; 1131 1132 for (j = 0; j < BPF_REG_SIZE; j++) 1133 if (slot->slot_type[j] != STACK_ITER) 1134 return -EINVAL; 1135 } 1136 1137 return 0; 1138 } 1139 1140 /* Check if given stack slot is "special": 1141 * - spilled register state (STACK_SPILL); 1142 * - dynptr state (STACK_DYNPTR); 1143 * - iter state (STACK_ITER). 1144 */ 1145 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1146 { 1147 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1148 1149 switch (type) { 1150 case STACK_SPILL: 1151 case STACK_DYNPTR: 1152 case STACK_ITER: 1153 return true; 1154 case STACK_INVALID: 1155 case STACK_MISC: 1156 case STACK_ZERO: 1157 return false; 1158 default: 1159 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1160 return true; 1161 } 1162 } 1163 1164 /* The reg state of a pointer or a bounded scalar was saved when 1165 * it was spilled to the stack. 1166 */ 1167 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1168 { 1169 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1170 } 1171 1172 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1173 { 1174 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1175 stack->spilled_ptr.type == SCALAR_VALUE; 1176 } 1177 1178 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1179 { 1180 return stack->slot_type[0] == STACK_SPILL && 1181 stack->spilled_ptr.type == SCALAR_VALUE; 1182 } 1183 1184 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1185 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1186 * more precise STACK_ZERO. 1187 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1188 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1189 */ 1190 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1191 { 1192 if (*stype == STACK_ZERO) 1193 return; 1194 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1195 return; 1196 *stype = STACK_MISC; 1197 } 1198 1199 static void scrub_spilled_slot(u8 *stype) 1200 { 1201 if (*stype != STACK_INVALID) 1202 *stype = STACK_MISC; 1203 } 1204 1205 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1206 * small to hold src. This is different from krealloc since we don't want to preserve 1207 * the contents of dst. 1208 * 1209 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1210 * not be allocated. 1211 */ 1212 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1213 { 1214 size_t alloc_bytes; 1215 void *orig = dst; 1216 size_t bytes; 1217 1218 if (ZERO_OR_NULL_PTR(src)) 1219 goto out; 1220 1221 if (unlikely(check_mul_overflow(n, size, &bytes))) 1222 return NULL; 1223 1224 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1225 dst = krealloc(orig, alloc_bytes, flags); 1226 if (!dst) { 1227 kfree(orig); 1228 return NULL; 1229 } 1230 1231 memcpy(dst, src, bytes); 1232 out: 1233 return dst ? dst : ZERO_SIZE_PTR; 1234 } 1235 1236 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1237 * small to hold new_n items. new items are zeroed out if the array grows. 1238 * 1239 * Contrary to krealloc_array, does not free arr if new_n is zero. 1240 */ 1241 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1242 { 1243 size_t alloc_size; 1244 void *new_arr; 1245 1246 if (!new_n || old_n == new_n) 1247 goto out; 1248 1249 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1250 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1251 if (!new_arr) { 1252 kfree(arr); 1253 return NULL; 1254 } 1255 arr = new_arr; 1256 1257 if (new_n > old_n) 1258 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1259 1260 out: 1261 return arr ? arr : ZERO_SIZE_PTR; 1262 } 1263 1264 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1265 { 1266 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1267 sizeof(struct bpf_reference_state), GFP_KERNEL); 1268 if (!dst->refs) 1269 return -ENOMEM; 1270 1271 dst->acquired_refs = src->acquired_refs; 1272 return 0; 1273 } 1274 1275 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1276 { 1277 size_t n = src->allocated_stack / BPF_REG_SIZE; 1278 1279 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1280 GFP_KERNEL); 1281 if (!dst->stack) 1282 return -ENOMEM; 1283 1284 dst->allocated_stack = src->allocated_stack; 1285 return 0; 1286 } 1287 1288 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1289 { 1290 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1291 sizeof(struct bpf_reference_state)); 1292 if (!state->refs) 1293 return -ENOMEM; 1294 1295 state->acquired_refs = n; 1296 return 0; 1297 } 1298 1299 /* Possibly update state->allocated_stack to be at least size bytes. Also 1300 * possibly update the function's high-water mark in its bpf_subprog_info. 1301 */ 1302 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1303 { 1304 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1305 1306 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1307 size = round_up(size, BPF_REG_SIZE); 1308 n = size / BPF_REG_SIZE; 1309 1310 if (old_n >= n) 1311 return 0; 1312 1313 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1314 if (!state->stack) 1315 return -ENOMEM; 1316 1317 state->allocated_stack = size; 1318 1319 /* update known max for given subprogram */ 1320 if (env->subprog_info[state->subprogno].stack_depth < size) 1321 env->subprog_info[state->subprogno].stack_depth = size; 1322 1323 return 0; 1324 } 1325 1326 /* Acquire a pointer id from the env and update the state->refs to include 1327 * this new pointer reference. 1328 * On success, returns a valid pointer id to associate with the register 1329 * On failure, returns a negative errno. 1330 */ 1331 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1332 { 1333 struct bpf_func_state *state = cur_func(env); 1334 int new_ofs = state->acquired_refs; 1335 int id, err; 1336 1337 err = resize_reference_state(state, state->acquired_refs + 1); 1338 if (err) 1339 return err; 1340 id = ++env->id_gen; 1341 state->refs[new_ofs].id = id; 1342 state->refs[new_ofs].insn_idx = insn_idx; 1343 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1344 1345 return id; 1346 } 1347 1348 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1349 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1350 { 1351 int i, last_idx; 1352 1353 last_idx = state->acquired_refs - 1; 1354 for (i = 0; i < state->acquired_refs; i++) { 1355 if (state->refs[i].id == ptr_id) { 1356 /* Cannot release caller references in callbacks */ 1357 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1358 return -EINVAL; 1359 if (last_idx && i != last_idx) 1360 memcpy(&state->refs[i], &state->refs[last_idx], 1361 sizeof(*state->refs)); 1362 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1363 state->acquired_refs--; 1364 return 0; 1365 } 1366 } 1367 return -EINVAL; 1368 } 1369 1370 static void free_func_state(struct bpf_func_state *state) 1371 { 1372 if (!state) 1373 return; 1374 kfree(state->refs); 1375 kfree(state->stack); 1376 kfree(state); 1377 } 1378 1379 static void clear_jmp_history(struct bpf_verifier_state *state) 1380 { 1381 kfree(state->jmp_history); 1382 state->jmp_history = NULL; 1383 state->jmp_history_cnt = 0; 1384 } 1385 1386 static void free_verifier_state(struct bpf_verifier_state *state, 1387 bool free_self) 1388 { 1389 int i; 1390 1391 for (i = 0; i <= state->curframe; i++) { 1392 free_func_state(state->frame[i]); 1393 state->frame[i] = NULL; 1394 } 1395 clear_jmp_history(state); 1396 if (free_self) 1397 kfree(state); 1398 } 1399 1400 /* copy verifier state from src to dst growing dst stack space 1401 * when necessary to accommodate larger src stack 1402 */ 1403 static int copy_func_state(struct bpf_func_state *dst, 1404 const struct bpf_func_state *src) 1405 { 1406 int err; 1407 1408 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1409 err = copy_reference_state(dst, src); 1410 if (err) 1411 return err; 1412 return copy_stack_state(dst, src); 1413 } 1414 1415 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1416 const struct bpf_verifier_state *src) 1417 { 1418 struct bpf_func_state *dst; 1419 int i, err; 1420 1421 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1422 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1423 GFP_USER); 1424 if (!dst_state->jmp_history) 1425 return -ENOMEM; 1426 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1427 1428 /* if dst has more stack frames then src frame, free them, this is also 1429 * necessary in case of exceptional exits using bpf_throw. 1430 */ 1431 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1432 free_func_state(dst_state->frame[i]); 1433 dst_state->frame[i] = NULL; 1434 } 1435 dst_state->speculative = src->speculative; 1436 dst_state->active_rcu_lock = src->active_rcu_lock; 1437 dst_state->active_preempt_lock = src->active_preempt_lock; 1438 dst_state->in_sleepable = src->in_sleepable; 1439 dst_state->curframe = src->curframe; 1440 dst_state->active_lock.ptr = src->active_lock.ptr; 1441 dst_state->active_lock.id = src->active_lock.id; 1442 dst_state->branches = src->branches; 1443 dst_state->parent = src->parent; 1444 dst_state->first_insn_idx = src->first_insn_idx; 1445 dst_state->last_insn_idx = src->last_insn_idx; 1446 dst_state->dfs_depth = src->dfs_depth; 1447 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1448 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1449 dst_state->may_goto_depth = src->may_goto_depth; 1450 for (i = 0; i <= src->curframe; i++) { 1451 dst = dst_state->frame[i]; 1452 if (!dst) { 1453 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1454 if (!dst) 1455 return -ENOMEM; 1456 dst_state->frame[i] = dst; 1457 } 1458 err = copy_func_state(dst, src->frame[i]); 1459 if (err) 1460 return err; 1461 } 1462 return 0; 1463 } 1464 1465 static u32 state_htab_size(struct bpf_verifier_env *env) 1466 { 1467 return env->prog->len; 1468 } 1469 1470 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1471 { 1472 struct bpf_verifier_state *cur = env->cur_state; 1473 struct bpf_func_state *state = cur->frame[cur->curframe]; 1474 1475 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1476 } 1477 1478 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1479 { 1480 int fr; 1481 1482 if (a->curframe != b->curframe) 1483 return false; 1484 1485 for (fr = a->curframe; fr >= 0; fr--) 1486 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1487 return false; 1488 1489 return true; 1490 } 1491 1492 /* Open coded iterators allow back-edges in the state graph in order to 1493 * check unbounded loops that iterators. 1494 * 1495 * In is_state_visited() it is necessary to know if explored states are 1496 * part of some loops in order to decide whether non-exact states 1497 * comparison could be used: 1498 * - non-exact states comparison establishes sub-state relation and uses 1499 * read and precision marks to do so, these marks are propagated from 1500 * children states and thus are not guaranteed to be final in a loop; 1501 * - exact states comparison just checks if current and explored states 1502 * are identical (and thus form a back-edge). 1503 * 1504 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1505 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1506 * algorithm for loop structure detection and gives an overview of 1507 * relevant terminology. It also has helpful illustrations. 1508 * 1509 * [1] https://api.semanticscholar.org/CorpusID:15784067 1510 * 1511 * We use a similar algorithm but because loop nested structure is 1512 * irrelevant for verifier ours is significantly simpler and resembles 1513 * strongly connected components algorithm from Sedgewick's textbook. 1514 * 1515 * Define topmost loop entry as a first node of the loop traversed in a 1516 * depth first search starting from initial state. The goal of the loop 1517 * tracking algorithm is to associate topmost loop entries with states 1518 * derived from these entries. 1519 * 1520 * For each step in the DFS states traversal algorithm needs to identify 1521 * the following situations: 1522 * 1523 * initial initial initial 1524 * | | | 1525 * V V V 1526 * ... ... .---------> hdr 1527 * | | | | 1528 * V V | V 1529 * cur .-> succ | .------... 1530 * | | | | | | 1531 * V | V | V V 1532 * succ '-- cur | ... ... 1533 * | | | 1534 * | V V 1535 * | succ <- cur 1536 * | | 1537 * | V 1538 * | ... 1539 * | | 1540 * '----' 1541 * 1542 * (A) successor state of cur (B) successor state of cur or it's entry 1543 * not yet traversed are in current DFS path, thus cur and succ 1544 * are members of the same outermost loop 1545 * 1546 * initial initial 1547 * | | 1548 * V V 1549 * ... ... 1550 * | | 1551 * V V 1552 * .------... .------... 1553 * | | | | 1554 * V V V V 1555 * .-> hdr ... ... ... 1556 * | | | | | 1557 * | V V V V 1558 * | succ <- cur succ <- cur 1559 * | | | 1560 * | V V 1561 * | ... ... 1562 * | | | 1563 * '----' exit 1564 * 1565 * (C) successor state of cur is a part of some loop but this loop 1566 * does not include cur or successor state is not in a loop at all. 1567 * 1568 * Algorithm could be described as the following python code: 1569 * 1570 * traversed = set() # Set of traversed nodes 1571 * entries = {} # Mapping from node to loop entry 1572 * depths = {} # Depth level assigned to graph node 1573 * path = set() # Current DFS path 1574 * 1575 * # Find outermost loop entry known for n 1576 * def get_loop_entry(n): 1577 * h = entries.get(n, None) 1578 * while h in entries and entries[h] != h: 1579 * h = entries[h] 1580 * return h 1581 * 1582 * # Update n's loop entry if h's outermost entry comes 1583 * # before n's outermost entry in current DFS path. 1584 * def update_loop_entry(n, h): 1585 * n1 = get_loop_entry(n) or n 1586 * h1 = get_loop_entry(h) or h 1587 * if h1 in path and depths[h1] <= depths[n1]: 1588 * entries[n] = h1 1589 * 1590 * def dfs(n, depth): 1591 * traversed.add(n) 1592 * path.add(n) 1593 * depths[n] = depth 1594 * for succ in G.successors(n): 1595 * if succ not in traversed: 1596 * # Case A: explore succ and update cur's loop entry 1597 * # only if succ's entry is in current DFS path. 1598 * dfs(succ, depth + 1) 1599 * h = get_loop_entry(succ) 1600 * update_loop_entry(n, h) 1601 * else: 1602 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1603 * update_loop_entry(n, succ) 1604 * path.remove(n) 1605 * 1606 * To adapt this algorithm for use with verifier: 1607 * - use st->branch == 0 as a signal that DFS of succ had been finished 1608 * and cur's loop entry has to be updated (case A), handle this in 1609 * update_branch_counts(); 1610 * - use st->branch > 0 as a signal that st is in the current DFS path; 1611 * - handle cases B and C in is_state_visited(); 1612 * - update topmost loop entry for intermediate states in get_loop_entry(). 1613 */ 1614 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1615 { 1616 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1617 1618 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1619 topmost = topmost->loop_entry; 1620 /* Update loop entries for intermediate states to avoid this 1621 * traversal in future get_loop_entry() calls. 1622 */ 1623 while (st && st->loop_entry != topmost) { 1624 old = st->loop_entry; 1625 st->loop_entry = topmost; 1626 st = old; 1627 } 1628 return topmost; 1629 } 1630 1631 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1632 { 1633 struct bpf_verifier_state *cur1, *hdr1; 1634 1635 cur1 = get_loop_entry(cur) ?: cur; 1636 hdr1 = get_loop_entry(hdr) ?: hdr; 1637 /* The head1->branches check decides between cases B and C in 1638 * comment for get_loop_entry(). If hdr1->branches == 0 then 1639 * head's topmost loop entry is not in current DFS path, 1640 * hence 'cur' and 'hdr' are not in the same loop and there is 1641 * no need to update cur->loop_entry. 1642 */ 1643 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1644 cur->loop_entry = hdr; 1645 hdr->used_as_loop_entry = true; 1646 } 1647 } 1648 1649 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1650 { 1651 while (st) { 1652 u32 br = --st->branches; 1653 1654 /* br == 0 signals that DFS exploration for 'st' is finished, 1655 * thus it is necessary to update parent's loop entry if it 1656 * turned out that st is a part of some loop. 1657 * This is a part of 'case A' in get_loop_entry() comment. 1658 */ 1659 if (br == 0 && st->parent && st->loop_entry) 1660 update_loop_entry(st->parent, st->loop_entry); 1661 1662 /* WARN_ON(br > 1) technically makes sense here, 1663 * but see comment in push_stack(), hence: 1664 */ 1665 WARN_ONCE((int)br < 0, 1666 "BUG update_branch_counts:branches_to_explore=%d\n", 1667 br); 1668 if (br) 1669 break; 1670 st = st->parent; 1671 } 1672 } 1673 1674 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1675 int *insn_idx, bool pop_log) 1676 { 1677 struct bpf_verifier_state *cur = env->cur_state; 1678 struct bpf_verifier_stack_elem *elem, *head = env->head; 1679 int err; 1680 1681 if (env->head == NULL) 1682 return -ENOENT; 1683 1684 if (cur) { 1685 err = copy_verifier_state(cur, &head->st); 1686 if (err) 1687 return err; 1688 } 1689 if (pop_log) 1690 bpf_vlog_reset(&env->log, head->log_pos); 1691 if (insn_idx) 1692 *insn_idx = head->insn_idx; 1693 if (prev_insn_idx) 1694 *prev_insn_idx = head->prev_insn_idx; 1695 elem = head->next; 1696 free_verifier_state(&head->st, false); 1697 kfree(head); 1698 env->head = elem; 1699 env->stack_size--; 1700 return 0; 1701 } 1702 1703 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1704 int insn_idx, int prev_insn_idx, 1705 bool speculative) 1706 { 1707 struct bpf_verifier_state *cur = env->cur_state; 1708 struct bpf_verifier_stack_elem *elem; 1709 int err; 1710 1711 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1712 if (!elem) 1713 goto err; 1714 1715 elem->insn_idx = insn_idx; 1716 elem->prev_insn_idx = prev_insn_idx; 1717 elem->next = env->head; 1718 elem->log_pos = env->log.end_pos; 1719 env->head = elem; 1720 env->stack_size++; 1721 err = copy_verifier_state(&elem->st, cur); 1722 if (err) 1723 goto err; 1724 elem->st.speculative |= speculative; 1725 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1726 verbose(env, "The sequence of %d jumps is too complex.\n", 1727 env->stack_size); 1728 goto err; 1729 } 1730 if (elem->st.parent) { 1731 ++elem->st.parent->branches; 1732 /* WARN_ON(branches > 2) technically makes sense here, 1733 * but 1734 * 1. speculative states will bump 'branches' for non-branch 1735 * instructions 1736 * 2. is_state_visited() heuristics may decide not to create 1737 * a new state for a sequence of branches and all such current 1738 * and cloned states will be pointing to a single parent state 1739 * which might have large 'branches' count. 1740 */ 1741 } 1742 return &elem->st; 1743 err: 1744 free_verifier_state(env->cur_state, true); 1745 env->cur_state = NULL; 1746 /* pop all elements and return */ 1747 while (!pop_stack(env, NULL, NULL, false)); 1748 return NULL; 1749 } 1750 1751 #define CALLER_SAVED_REGS 6 1752 static const int caller_saved[CALLER_SAVED_REGS] = { 1753 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1754 }; 1755 1756 /* This helper doesn't clear reg->id */ 1757 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1758 { 1759 reg->var_off = tnum_const(imm); 1760 reg->smin_value = (s64)imm; 1761 reg->smax_value = (s64)imm; 1762 reg->umin_value = imm; 1763 reg->umax_value = imm; 1764 1765 reg->s32_min_value = (s32)imm; 1766 reg->s32_max_value = (s32)imm; 1767 reg->u32_min_value = (u32)imm; 1768 reg->u32_max_value = (u32)imm; 1769 } 1770 1771 /* Mark the unknown part of a register (variable offset or scalar value) as 1772 * known to have the value @imm. 1773 */ 1774 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1775 { 1776 /* Clear off and union(map_ptr, range) */ 1777 memset(((u8 *)reg) + sizeof(reg->type), 0, 1778 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1779 reg->id = 0; 1780 reg->ref_obj_id = 0; 1781 ___mark_reg_known(reg, imm); 1782 } 1783 1784 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1785 { 1786 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1787 reg->s32_min_value = (s32)imm; 1788 reg->s32_max_value = (s32)imm; 1789 reg->u32_min_value = (u32)imm; 1790 reg->u32_max_value = (u32)imm; 1791 } 1792 1793 /* Mark the 'variable offset' part of a register as zero. This should be 1794 * used only on registers holding a pointer type. 1795 */ 1796 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1797 { 1798 __mark_reg_known(reg, 0); 1799 } 1800 1801 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1802 { 1803 __mark_reg_known(reg, 0); 1804 reg->type = SCALAR_VALUE; 1805 /* all scalars are assumed imprecise initially (unless unprivileged, 1806 * in which case everything is forced to be precise) 1807 */ 1808 reg->precise = !env->bpf_capable; 1809 } 1810 1811 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1812 struct bpf_reg_state *regs, u32 regno) 1813 { 1814 if (WARN_ON(regno >= MAX_BPF_REG)) { 1815 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1816 /* Something bad happened, let's kill all regs */ 1817 for (regno = 0; regno < MAX_BPF_REG; regno++) 1818 __mark_reg_not_init(env, regs + regno); 1819 return; 1820 } 1821 __mark_reg_known_zero(regs + regno); 1822 } 1823 1824 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1825 bool first_slot, int dynptr_id) 1826 { 1827 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1828 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1829 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1830 */ 1831 __mark_reg_known_zero(reg); 1832 reg->type = CONST_PTR_TO_DYNPTR; 1833 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1834 reg->id = dynptr_id; 1835 reg->dynptr.type = type; 1836 reg->dynptr.first_slot = first_slot; 1837 } 1838 1839 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1840 { 1841 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1842 const struct bpf_map *map = reg->map_ptr; 1843 1844 if (map->inner_map_meta) { 1845 reg->type = CONST_PTR_TO_MAP; 1846 reg->map_ptr = map->inner_map_meta; 1847 /* transfer reg's id which is unique for every map_lookup_elem 1848 * as UID of the inner map. 1849 */ 1850 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1851 reg->map_uid = reg->id; 1852 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 1853 reg->map_uid = reg->id; 1854 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1855 reg->type = PTR_TO_XDP_SOCK; 1856 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1857 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1858 reg->type = PTR_TO_SOCKET; 1859 } else { 1860 reg->type = PTR_TO_MAP_VALUE; 1861 } 1862 return; 1863 } 1864 1865 reg->type &= ~PTR_MAYBE_NULL; 1866 } 1867 1868 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1869 struct btf_field_graph_root *ds_head) 1870 { 1871 __mark_reg_known_zero(®s[regno]); 1872 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1873 regs[regno].btf = ds_head->btf; 1874 regs[regno].btf_id = ds_head->value_btf_id; 1875 regs[regno].off = ds_head->node_offset; 1876 } 1877 1878 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1879 { 1880 return type_is_pkt_pointer(reg->type); 1881 } 1882 1883 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1884 { 1885 return reg_is_pkt_pointer(reg) || 1886 reg->type == PTR_TO_PACKET_END; 1887 } 1888 1889 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1890 { 1891 return base_type(reg->type) == PTR_TO_MEM && 1892 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1893 } 1894 1895 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1896 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1897 enum bpf_reg_type which) 1898 { 1899 /* The register can already have a range from prior markings. 1900 * This is fine as long as it hasn't been advanced from its 1901 * origin. 1902 */ 1903 return reg->type == which && 1904 reg->id == 0 && 1905 reg->off == 0 && 1906 tnum_equals_const(reg->var_off, 0); 1907 } 1908 1909 /* Reset the min/max bounds of a register */ 1910 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1911 { 1912 reg->smin_value = S64_MIN; 1913 reg->smax_value = S64_MAX; 1914 reg->umin_value = 0; 1915 reg->umax_value = U64_MAX; 1916 1917 reg->s32_min_value = S32_MIN; 1918 reg->s32_max_value = S32_MAX; 1919 reg->u32_min_value = 0; 1920 reg->u32_max_value = U32_MAX; 1921 } 1922 1923 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1924 { 1925 reg->smin_value = S64_MIN; 1926 reg->smax_value = S64_MAX; 1927 reg->umin_value = 0; 1928 reg->umax_value = U64_MAX; 1929 } 1930 1931 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1932 { 1933 reg->s32_min_value = S32_MIN; 1934 reg->s32_max_value = S32_MAX; 1935 reg->u32_min_value = 0; 1936 reg->u32_max_value = U32_MAX; 1937 } 1938 1939 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1940 { 1941 struct tnum var32_off = tnum_subreg(reg->var_off); 1942 1943 /* min signed is max(sign bit) | min(other bits) */ 1944 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1945 var32_off.value | (var32_off.mask & S32_MIN)); 1946 /* max signed is min(sign bit) | max(other bits) */ 1947 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1948 var32_off.value | (var32_off.mask & S32_MAX)); 1949 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1950 reg->u32_max_value = min(reg->u32_max_value, 1951 (u32)(var32_off.value | var32_off.mask)); 1952 } 1953 1954 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1955 { 1956 /* min signed is max(sign bit) | min(other bits) */ 1957 reg->smin_value = max_t(s64, reg->smin_value, 1958 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1959 /* max signed is min(sign bit) | max(other bits) */ 1960 reg->smax_value = min_t(s64, reg->smax_value, 1961 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1962 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1963 reg->umax_value = min(reg->umax_value, 1964 reg->var_off.value | reg->var_off.mask); 1965 } 1966 1967 static void __update_reg_bounds(struct bpf_reg_state *reg) 1968 { 1969 __update_reg32_bounds(reg); 1970 __update_reg64_bounds(reg); 1971 } 1972 1973 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1974 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1975 { 1976 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1977 * bits to improve our u32/s32 boundaries. 1978 * 1979 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1980 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1981 * [10, 20] range. But this property holds for any 64-bit range as 1982 * long as upper 32 bits in that entire range of values stay the same. 1983 * 1984 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1985 * in decimal) has the same upper 32 bits throughout all the values in 1986 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1987 * range. 1988 * 1989 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1990 * following the rules outlined below about u64/s64 correspondence 1991 * (which equally applies to u32 vs s32 correspondence). In general it 1992 * depends on actual hexadecimal values of 32-bit range. They can form 1993 * only valid u32, or only valid s32 ranges in some cases. 1994 * 1995 * So we use all these insights to derive bounds for subregisters here. 1996 */ 1997 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1998 /* u64 to u32 casting preserves validity of low 32 bits as 1999 * a range, if upper 32 bits are the same 2000 */ 2001 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2002 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2003 2004 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2005 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2006 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2007 } 2008 } 2009 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2010 /* low 32 bits should form a proper u32 range */ 2011 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2012 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2013 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2014 } 2015 /* low 32 bits should form a proper s32 range */ 2016 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2017 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2018 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2019 } 2020 } 2021 /* Special case where upper bits form a small sequence of two 2022 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2023 * 0x00000000 is also valid), while lower bits form a proper s32 range 2024 * going from negative numbers to positive numbers. E.g., let's say we 2025 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2026 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2027 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2028 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2029 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2030 * upper 32 bits. As a random example, s64 range 2031 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2032 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2033 */ 2034 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2035 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2036 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2037 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2038 } 2039 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2040 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2041 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2042 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2043 } 2044 /* if u32 range forms a valid s32 range (due to matching sign bit), 2045 * try to learn from that 2046 */ 2047 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2048 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2049 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2050 } 2051 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2052 * are the same, so combine. This works even in the negative case, e.g. 2053 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2054 */ 2055 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2056 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2057 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2058 } 2059 } 2060 2061 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2062 { 2063 /* If u64 range forms a valid s64 range (due to matching sign bit), 2064 * try to learn from that. Let's do a bit of ASCII art to see when 2065 * this is happening. Let's take u64 range first: 2066 * 2067 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2068 * |-------------------------------|--------------------------------| 2069 * 2070 * Valid u64 range is formed when umin and umax are anywhere in the 2071 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2072 * straightforward. Let's see how s64 range maps onto the same range 2073 * of values, annotated below the line for comparison: 2074 * 2075 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2076 * |-------------------------------|--------------------------------| 2077 * 0 S64_MAX S64_MIN -1 2078 * 2079 * So s64 values basically start in the middle and they are logically 2080 * contiguous to the right of it, wrapping around from -1 to 0, and 2081 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2082 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2083 * more visually as mapped to sign-agnostic range of hex values. 2084 * 2085 * u64 start u64 end 2086 * _______________________________________________________________ 2087 * / \ 2088 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2089 * |-------------------------------|--------------------------------| 2090 * 0 S64_MAX S64_MIN -1 2091 * / \ 2092 * >------------------------------ -------------------------------> 2093 * s64 continues... s64 end s64 start s64 "midpoint" 2094 * 2095 * What this means is that, in general, we can't always derive 2096 * something new about u64 from any random s64 range, and vice versa. 2097 * 2098 * But we can do that in two particular cases. One is when entire 2099 * u64/s64 range is *entirely* contained within left half of the above 2100 * diagram or when it is *entirely* contained in the right half. I.e.: 2101 * 2102 * |-------------------------------|--------------------------------| 2103 * ^ ^ ^ ^ 2104 * A B C D 2105 * 2106 * [A, B] and [C, D] are contained entirely in their respective halves 2107 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2108 * will be non-negative both as u64 and s64 (and in fact it will be 2109 * identical ranges no matter the signedness). [C, D] treated as s64 2110 * will be a range of negative values, while in u64 it will be 2111 * non-negative range of values larger than 0x8000000000000000. 2112 * 2113 * Now, any other range here can't be represented in both u64 and s64 2114 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2115 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2116 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2117 * for example. Similarly, valid s64 range [D, A] (going from negative 2118 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2119 * ranges as u64. Currently reg_state can't represent two segments per 2120 * numeric domain, so in such situations we can only derive maximal 2121 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2122 * 2123 * So we use these facts to derive umin/umax from smin/smax and vice 2124 * versa only if they stay within the same "half". This is equivalent 2125 * to checking sign bit: lower half will have sign bit as zero, upper 2126 * half have sign bit 1. Below in code we simplify this by just 2127 * casting umin/umax as smin/smax and checking if they form valid 2128 * range, and vice versa. Those are equivalent checks. 2129 */ 2130 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2131 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2132 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2133 } 2134 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2135 * are the same, so combine. This works even in the negative case, e.g. 2136 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2137 */ 2138 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2139 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2140 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2141 } 2142 } 2143 2144 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2145 { 2146 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2147 * values on both sides of 64-bit range in hope to have tighter range. 2148 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2149 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2150 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2151 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2152 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2153 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2154 * We just need to make sure that derived bounds we are intersecting 2155 * with are well-formed ranges in respective s64 or u64 domain, just 2156 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2157 */ 2158 __u64 new_umin, new_umax; 2159 __s64 new_smin, new_smax; 2160 2161 /* u32 -> u64 tightening, it's always well-formed */ 2162 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2163 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2164 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2165 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2166 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2167 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2168 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2169 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2170 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2171 2172 /* if s32 can be treated as valid u32 range, we can use it as well */ 2173 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2174 /* s32 -> u64 tightening */ 2175 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2176 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2177 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2178 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2179 /* s32 -> s64 tightening */ 2180 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2181 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2182 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2183 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2184 } 2185 } 2186 2187 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2188 { 2189 __reg32_deduce_bounds(reg); 2190 __reg64_deduce_bounds(reg); 2191 __reg_deduce_mixed_bounds(reg); 2192 } 2193 2194 /* Attempts to improve var_off based on unsigned min/max information */ 2195 static void __reg_bound_offset(struct bpf_reg_state *reg) 2196 { 2197 struct tnum var64_off = tnum_intersect(reg->var_off, 2198 tnum_range(reg->umin_value, 2199 reg->umax_value)); 2200 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2201 tnum_range(reg->u32_min_value, 2202 reg->u32_max_value)); 2203 2204 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2205 } 2206 2207 static void reg_bounds_sync(struct bpf_reg_state *reg) 2208 { 2209 /* We might have learned new bounds from the var_off. */ 2210 __update_reg_bounds(reg); 2211 /* We might have learned something about the sign bit. */ 2212 __reg_deduce_bounds(reg); 2213 __reg_deduce_bounds(reg); 2214 /* We might have learned some bits from the bounds. */ 2215 __reg_bound_offset(reg); 2216 /* Intersecting with the old var_off might have improved our bounds 2217 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2218 * then new var_off is (0; 0x7f...fc) which improves our umax. 2219 */ 2220 __update_reg_bounds(reg); 2221 } 2222 2223 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2224 struct bpf_reg_state *reg, const char *ctx) 2225 { 2226 const char *msg; 2227 2228 if (reg->umin_value > reg->umax_value || 2229 reg->smin_value > reg->smax_value || 2230 reg->u32_min_value > reg->u32_max_value || 2231 reg->s32_min_value > reg->s32_max_value) { 2232 msg = "range bounds violation"; 2233 goto out; 2234 } 2235 2236 if (tnum_is_const(reg->var_off)) { 2237 u64 uval = reg->var_off.value; 2238 s64 sval = (s64)uval; 2239 2240 if (reg->umin_value != uval || reg->umax_value != uval || 2241 reg->smin_value != sval || reg->smax_value != sval) { 2242 msg = "const tnum out of sync with range bounds"; 2243 goto out; 2244 } 2245 } 2246 2247 if (tnum_subreg_is_const(reg->var_off)) { 2248 u32 uval32 = tnum_subreg(reg->var_off).value; 2249 s32 sval32 = (s32)uval32; 2250 2251 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2252 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2253 msg = "const subreg tnum out of sync with range bounds"; 2254 goto out; 2255 } 2256 } 2257 2258 return 0; 2259 out: 2260 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2261 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2262 ctx, msg, reg->umin_value, reg->umax_value, 2263 reg->smin_value, reg->smax_value, 2264 reg->u32_min_value, reg->u32_max_value, 2265 reg->s32_min_value, reg->s32_max_value, 2266 reg->var_off.value, reg->var_off.mask); 2267 if (env->test_reg_invariants) 2268 return -EFAULT; 2269 __mark_reg_unbounded(reg); 2270 return 0; 2271 } 2272 2273 static bool __reg32_bound_s64(s32 a) 2274 { 2275 return a >= 0 && a <= S32_MAX; 2276 } 2277 2278 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2279 { 2280 reg->umin_value = reg->u32_min_value; 2281 reg->umax_value = reg->u32_max_value; 2282 2283 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2284 * be positive otherwise set to worse case bounds and refine later 2285 * from tnum. 2286 */ 2287 if (__reg32_bound_s64(reg->s32_min_value) && 2288 __reg32_bound_s64(reg->s32_max_value)) { 2289 reg->smin_value = reg->s32_min_value; 2290 reg->smax_value = reg->s32_max_value; 2291 } else { 2292 reg->smin_value = 0; 2293 reg->smax_value = U32_MAX; 2294 } 2295 } 2296 2297 /* Mark a register as having a completely unknown (scalar) value. */ 2298 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2299 { 2300 /* 2301 * Clear type, off, and union(map_ptr, range) and 2302 * padding between 'type' and union 2303 */ 2304 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2305 reg->type = SCALAR_VALUE; 2306 reg->id = 0; 2307 reg->ref_obj_id = 0; 2308 reg->var_off = tnum_unknown; 2309 reg->frameno = 0; 2310 reg->precise = false; 2311 __mark_reg_unbounded(reg); 2312 } 2313 2314 /* Mark a register as having a completely unknown (scalar) value, 2315 * initialize .precise as true when not bpf capable. 2316 */ 2317 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2318 struct bpf_reg_state *reg) 2319 { 2320 __mark_reg_unknown_imprecise(reg); 2321 reg->precise = !env->bpf_capable; 2322 } 2323 2324 static void mark_reg_unknown(struct bpf_verifier_env *env, 2325 struct bpf_reg_state *regs, u32 regno) 2326 { 2327 if (WARN_ON(regno >= MAX_BPF_REG)) { 2328 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2329 /* Something bad happened, let's kill all regs except FP */ 2330 for (regno = 0; regno < BPF_REG_FP; regno++) 2331 __mark_reg_not_init(env, regs + regno); 2332 return; 2333 } 2334 __mark_reg_unknown(env, regs + regno); 2335 } 2336 2337 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2338 struct bpf_reg_state *reg) 2339 { 2340 __mark_reg_unknown(env, reg); 2341 reg->type = NOT_INIT; 2342 } 2343 2344 static void mark_reg_not_init(struct bpf_verifier_env *env, 2345 struct bpf_reg_state *regs, u32 regno) 2346 { 2347 if (WARN_ON(regno >= MAX_BPF_REG)) { 2348 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2349 /* Something bad happened, let's kill all regs except FP */ 2350 for (regno = 0; regno < BPF_REG_FP; regno++) 2351 __mark_reg_not_init(env, regs + regno); 2352 return; 2353 } 2354 __mark_reg_not_init(env, regs + regno); 2355 } 2356 2357 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2358 struct bpf_reg_state *regs, u32 regno, 2359 enum bpf_reg_type reg_type, 2360 struct btf *btf, u32 btf_id, 2361 enum bpf_type_flag flag) 2362 { 2363 if (reg_type == SCALAR_VALUE) { 2364 mark_reg_unknown(env, regs, regno); 2365 return; 2366 } 2367 mark_reg_known_zero(env, regs, regno); 2368 regs[regno].type = PTR_TO_BTF_ID | flag; 2369 regs[regno].btf = btf; 2370 regs[regno].btf_id = btf_id; 2371 if (type_may_be_null(flag)) 2372 regs[regno].id = ++env->id_gen; 2373 } 2374 2375 #define DEF_NOT_SUBREG (0) 2376 static void init_reg_state(struct bpf_verifier_env *env, 2377 struct bpf_func_state *state) 2378 { 2379 struct bpf_reg_state *regs = state->regs; 2380 int i; 2381 2382 for (i = 0; i < MAX_BPF_REG; i++) { 2383 mark_reg_not_init(env, regs, i); 2384 regs[i].live = REG_LIVE_NONE; 2385 regs[i].parent = NULL; 2386 regs[i].subreg_def = DEF_NOT_SUBREG; 2387 } 2388 2389 /* frame pointer */ 2390 regs[BPF_REG_FP].type = PTR_TO_STACK; 2391 mark_reg_known_zero(env, regs, BPF_REG_FP); 2392 regs[BPF_REG_FP].frameno = state->frameno; 2393 } 2394 2395 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2396 { 2397 return (struct bpf_retval_range){ minval, maxval }; 2398 } 2399 2400 #define BPF_MAIN_FUNC (-1) 2401 static void init_func_state(struct bpf_verifier_env *env, 2402 struct bpf_func_state *state, 2403 int callsite, int frameno, int subprogno) 2404 { 2405 state->callsite = callsite; 2406 state->frameno = frameno; 2407 state->subprogno = subprogno; 2408 state->callback_ret_range = retval_range(0, 0); 2409 init_reg_state(env, state); 2410 mark_verifier_state_scratched(env); 2411 } 2412 2413 /* Similar to push_stack(), but for async callbacks */ 2414 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2415 int insn_idx, int prev_insn_idx, 2416 int subprog, bool is_sleepable) 2417 { 2418 struct bpf_verifier_stack_elem *elem; 2419 struct bpf_func_state *frame; 2420 2421 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2422 if (!elem) 2423 goto err; 2424 2425 elem->insn_idx = insn_idx; 2426 elem->prev_insn_idx = prev_insn_idx; 2427 elem->next = env->head; 2428 elem->log_pos = env->log.end_pos; 2429 env->head = elem; 2430 env->stack_size++; 2431 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2432 verbose(env, 2433 "The sequence of %d jumps is too complex for async cb.\n", 2434 env->stack_size); 2435 goto err; 2436 } 2437 /* Unlike push_stack() do not copy_verifier_state(). 2438 * The caller state doesn't matter. 2439 * This is async callback. It starts in a fresh stack. 2440 * Initialize it similar to do_check_common(). 2441 */ 2442 elem->st.branches = 1; 2443 elem->st.in_sleepable = is_sleepable; 2444 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2445 if (!frame) 2446 goto err; 2447 init_func_state(env, frame, 2448 BPF_MAIN_FUNC /* callsite */, 2449 0 /* frameno within this callchain */, 2450 subprog /* subprog number within this prog */); 2451 elem->st.frame[0] = frame; 2452 return &elem->st; 2453 err: 2454 free_verifier_state(env->cur_state, true); 2455 env->cur_state = NULL; 2456 /* pop all elements and return */ 2457 while (!pop_stack(env, NULL, NULL, false)); 2458 return NULL; 2459 } 2460 2461 2462 enum reg_arg_type { 2463 SRC_OP, /* register is used as source operand */ 2464 DST_OP, /* register is used as destination operand */ 2465 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2466 }; 2467 2468 static int cmp_subprogs(const void *a, const void *b) 2469 { 2470 return ((struct bpf_subprog_info *)a)->start - 2471 ((struct bpf_subprog_info *)b)->start; 2472 } 2473 2474 static int find_subprog(struct bpf_verifier_env *env, int off) 2475 { 2476 struct bpf_subprog_info *p; 2477 2478 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2479 sizeof(env->subprog_info[0]), cmp_subprogs); 2480 if (!p) 2481 return -ENOENT; 2482 return p - env->subprog_info; 2483 2484 } 2485 2486 static int add_subprog(struct bpf_verifier_env *env, int off) 2487 { 2488 int insn_cnt = env->prog->len; 2489 int ret; 2490 2491 if (off >= insn_cnt || off < 0) { 2492 verbose(env, "call to invalid destination\n"); 2493 return -EINVAL; 2494 } 2495 ret = find_subprog(env, off); 2496 if (ret >= 0) 2497 return ret; 2498 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2499 verbose(env, "too many subprograms\n"); 2500 return -E2BIG; 2501 } 2502 /* determine subprog starts. The end is one before the next starts */ 2503 env->subprog_info[env->subprog_cnt++].start = off; 2504 sort(env->subprog_info, env->subprog_cnt, 2505 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2506 return env->subprog_cnt - 1; 2507 } 2508 2509 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2510 { 2511 struct bpf_prog_aux *aux = env->prog->aux; 2512 struct btf *btf = aux->btf; 2513 const struct btf_type *t; 2514 u32 main_btf_id, id; 2515 const char *name; 2516 int ret, i; 2517 2518 /* Non-zero func_info_cnt implies valid btf */ 2519 if (!aux->func_info_cnt) 2520 return 0; 2521 main_btf_id = aux->func_info[0].type_id; 2522 2523 t = btf_type_by_id(btf, main_btf_id); 2524 if (!t) { 2525 verbose(env, "invalid btf id for main subprog in func_info\n"); 2526 return -EINVAL; 2527 } 2528 2529 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2530 if (IS_ERR(name)) { 2531 ret = PTR_ERR(name); 2532 /* If there is no tag present, there is no exception callback */ 2533 if (ret == -ENOENT) 2534 ret = 0; 2535 else if (ret == -EEXIST) 2536 verbose(env, "multiple exception callback tags for main subprog\n"); 2537 return ret; 2538 } 2539 2540 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2541 if (ret < 0) { 2542 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2543 return ret; 2544 } 2545 id = ret; 2546 t = btf_type_by_id(btf, id); 2547 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2548 verbose(env, "exception callback '%s' must have global linkage\n", name); 2549 return -EINVAL; 2550 } 2551 ret = 0; 2552 for (i = 0; i < aux->func_info_cnt; i++) { 2553 if (aux->func_info[i].type_id != id) 2554 continue; 2555 ret = aux->func_info[i].insn_off; 2556 /* Further func_info and subprog checks will also happen 2557 * later, so assume this is the right insn_off for now. 2558 */ 2559 if (!ret) { 2560 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2561 ret = -EINVAL; 2562 } 2563 } 2564 if (!ret) { 2565 verbose(env, "exception callback type id not found in func_info\n"); 2566 ret = -EINVAL; 2567 } 2568 return ret; 2569 } 2570 2571 #define MAX_KFUNC_DESCS 256 2572 #define MAX_KFUNC_BTFS 256 2573 2574 struct bpf_kfunc_desc { 2575 struct btf_func_model func_model; 2576 u32 func_id; 2577 s32 imm; 2578 u16 offset; 2579 unsigned long addr; 2580 }; 2581 2582 struct bpf_kfunc_btf { 2583 struct btf *btf; 2584 struct module *module; 2585 u16 offset; 2586 }; 2587 2588 struct bpf_kfunc_desc_tab { 2589 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2590 * verification. JITs do lookups by bpf_insn, where func_id may not be 2591 * available, therefore at the end of verification do_misc_fixups() 2592 * sorts this by imm and offset. 2593 */ 2594 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2595 u32 nr_descs; 2596 }; 2597 2598 struct bpf_kfunc_btf_tab { 2599 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2600 u32 nr_descs; 2601 }; 2602 2603 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2604 { 2605 const struct bpf_kfunc_desc *d0 = a; 2606 const struct bpf_kfunc_desc *d1 = b; 2607 2608 /* func_id is not greater than BTF_MAX_TYPE */ 2609 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2610 } 2611 2612 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2613 { 2614 const struct bpf_kfunc_btf *d0 = a; 2615 const struct bpf_kfunc_btf *d1 = b; 2616 2617 return d0->offset - d1->offset; 2618 } 2619 2620 static const struct bpf_kfunc_desc * 2621 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2622 { 2623 struct bpf_kfunc_desc desc = { 2624 .func_id = func_id, 2625 .offset = offset, 2626 }; 2627 struct bpf_kfunc_desc_tab *tab; 2628 2629 tab = prog->aux->kfunc_tab; 2630 return bsearch(&desc, tab->descs, tab->nr_descs, 2631 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2632 } 2633 2634 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2635 u16 btf_fd_idx, u8 **func_addr) 2636 { 2637 const struct bpf_kfunc_desc *desc; 2638 2639 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2640 if (!desc) 2641 return -EFAULT; 2642 2643 *func_addr = (u8 *)desc->addr; 2644 return 0; 2645 } 2646 2647 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2648 s16 offset) 2649 { 2650 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2651 struct bpf_kfunc_btf_tab *tab; 2652 struct bpf_kfunc_btf *b; 2653 struct module *mod; 2654 struct btf *btf; 2655 int btf_fd; 2656 2657 tab = env->prog->aux->kfunc_btf_tab; 2658 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2659 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2660 if (!b) { 2661 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2662 verbose(env, "too many different module BTFs\n"); 2663 return ERR_PTR(-E2BIG); 2664 } 2665 2666 if (bpfptr_is_null(env->fd_array)) { 2667 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2668 return ERR_PTR(-EPROTO); 2669 } 2670 2671 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2672 offset * sizeof(btf_fd), 2673 sizeof(btf_fd))) 2674 return ERR_PTR(-EFAULT); 2675 2676 btf = btf_get_by_fd(btf_fd); 2677 if (IS_ERR(btf)) { 2678 verbose(env, "invalid module BTF fd specified\n"); 2679 return btf; 2680 } 2681 2682 if (!btf_is_module(btf)) { 2683 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2684 btf_put(btf); 2685 return ERR_PTR(-EINVAL); 2686 } 2687 2688 mod = btf_try_get_module(btf); 2689 if (!mod) { 2690 btf_put(btf); 2691 return ERR_PTR(-ENXIO); 2692 } 2693 2694 b = &tab->descs[tab->nr_descs++]; 2695 b->btf = btf; 2696 b->module = mod; 2697 b->offset = offset; 2698 2699 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2700 kfunc_btf_cmp_by_off, NULL); 2701 } 2702 return b->btf; 2703 } 2704 2705 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2706 { 2707 if (!tab) 2708 return; 2709 2710 while (tab->nr_descs--) { 2711 module_put(tab->descs[tab->nr_descs].module); 2712 btf_put(tab->descs[tab->nr_descs].btf); 2713 } 2714 kfree(tab); 2715 } 2716 2717 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2718 { 2719 if (offset) { 2720 if (offset < 0) { 2721 /* In the future, this can be allowed to increase limit 2722 * of fd index into fd_array, interpreted as u16. 2723 */ 2724 verbose(env, "negative offset disallowed for kernel module function call\n"); 2725 return ERR_PTR(-EINVAL); 2726 } 2727 2728 return __find_kfunc_desc_btf(env, offset); 2729 } 2730 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2731 } 2732 2733 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2734 { 2735 const struct btf_type *func, *func_proto; 2736 struct bpf_kfunc_btf_tab *btf_tab; 2737 struct bpf_kfunc_desc_tab *tab; 2738 struct bpf_prog_aux *prog_aux; 2739 struct bpf_kfunc_desc *desc; 2740 const char *func_name; 2741 struct btf *desc_btf; 2742 unsigned long call_imm; 2743 unsigned long addr; 2744 int err; 2745 2746 prog_aux = env->prog->aux; 2747 tab = prog_aux->kfunc_tab; 2748 btf_tab = prog_aux->kfunc_btf_tab; 2749 if (!tab) { 2750 if (!btf_vmlinux) { 2751 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2752 return -ENOTSUPP; 2753 } 2754 2755 if (!env->prog->jit_requested) { 2756 verbose(env, "JIT is required for calling kernel function\n"); 2757 return -ENOTSUPP; 2758 } 2759 2760 if (!bpf_jit_supports_kfunc_call()) { 2761 verbose(env, "JIT does not support calling kernel function\n"); 2762 return -ENOTSUPP; 2763 } 2764 2765 if (!env->prog->gpl_compatible) { 2766 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2767 return -EINVAL; 2768 } 2769 2770 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2771 if (!tab) 2772 return -ENOMEM; 2773 prog_aux->kfunc_tab = tab; 2774 } 2775 2776 /* func_id == 0 is always invalid, but instead of returning an error, be 2777 * conservative and wait until the code elimination pass before returning 2778 * error, so that invalid calls that get pruned out can be in BPF programs 2779 * loaded from userspace. It is also required that offset be untouched 2780 * for such calls. 2781 */ 2782 if (!func_id && !offset) 2783 return 0; 2784 2785 if (!btf_tab && offset) { 2786 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2787 if (!btf_tab) 2788 return -ENOMEM; 2789 prog_aux->kfunc_btf_tab = btf_tab; 2790 } 2791 2792 desc_btf = find_kfunc_desc_btf(env, offset); 2793 if (IS_ERR(desc_btf)) { 2794 verbose(env, "failed to find BTF for kernel function\n"); 2795 return PTR_ERR(desc_btf); 2796 } 2797 2798 if (find_kfunc_desc(env->prog, func_id, offset)) 2799 return 0; 2800 2801 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2802 verbose(env, "too many different kernel function calls\n"); 2803 return -E2BIG; 2804 } 2805 2806 func = btf_type_by_id(desc_btf, func_id); 2807 if (!func || !btf_type_is_func(func)) { 2808 verbose(env, "kernel btf_id %u is not a function\n", 2809 func_id); 2810 return -EINVAL; 2811 } 2812 func_proto = btf_type_by_id(desc_btf, func->type); 2813 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2814 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2815 func_id); 2816 return -EINVAL; 2817 } 2818 2819 func_name = btf_name_by_offset(desc_btf, func->name_off); 2820 addr = kallsyms_lookup_name(func_name); 2821 if (!addr) { 2822 verbose(env, "cannot find address for kernel function %s\n", 2823 func_name); 2824 return -EINVAL; 2825 } 2826 specialize_kfunc(env, func_id, offset, &addr); 2827 2828 if (bpf_jit_supports_far_kfunc_call()) { 2829 call_imm = func_id; 2830 } else { 2831 call_imm = BPF_CALL_IMM(addr); 2832 /* Check whether the relative offset overflows desc->imm */ 2833 if ((unsigned long)(s32)call_imm != call_imm) { 2834 verbose(env, "address of kernel function %s is out of range\n", 2835 func_name); 2836 return -EINVAL; 2837 } 2838 } 2839 2840 if (bpf_dev_bound_kfunc_id(func_id)) { 2841 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2842 if (err) 2843 return err; 2844 } 2845 2846 desc = &tab->descs[tab->nr_descs++]; 2847 desc->func_id = func_id; 2848 desc->imm = call_imm; 2849 desc->offset = offset; 2850 desc->addr = addr; 2851 err = btf_distill_func_proto(&env->log, desc_btf, 2852 func_proto, func_name, 2853 &desc->func_model); 2854 if (!err) 2855 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2856 kfunc_desc_cmp_by_id_off, NULL); 2857 return err; 2858 } 2859 2860 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2861 { 2862 const struct bpf_kfunc_desc *d0 = a; 2863 const struct bpf_kfunc_desc *d1 = b; 2864 2865 if (d0->imm != d1->imm) 2866 return d0->imm < d1->imm ? -1 : 1; 2867 if (d0->offset != d1->offset) 2868 return d0->offset < d1->offset ? -1 : 1; 2869 return 0; 2870 } 2871 2872 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2873 { 2874 struct bpf_kfunc_desc_tab *tab; 2875 2876 tab = prog->aux->kfunc_tab; 2877 if (!tab) 2878 return; 2879 2880 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2881 kfunc_desc_cmp_by_imm_off, NULL); 2882 } 2883 2884 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2885 { 2886 return !!prog->aux->kfunc_tab; 2887 } 2888 2889 const struct btf_func_model * 2890 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2891 const struct bpf_insn *insn) 2892 { 2893 const struct bpf_kfunc_desc desc = { 2894 .imm = insn->imm, 2895 .offset = insn->off, 2896 }; 2897 const struct bpf_kfunc_desc *res; 2898 struct bpf_kfunc_desc_tab *tab; 2899 2900 tab = prog->aux->kfunc_tab; 2901 res = bsearch(&desc, tab->descs, tab->nr_descs, 2902 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2903 2904 return res ? &res->func_model : NULL; 2905 } 2906 2907 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2908 { 2909 struct bpf_subprog_info *subprog = env->subprog_info; 2910 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2911 struct bpf_insn *insn = env->prog->insnsi; 2912 2913 /* Add entry function. */ 2914 ret = add_subprog(env, 0); 2915 if (ret) 2916 return ret; 2917 2918 for (i = 0; i < insn_cnt; i++, insn++) { 2919 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2920 !bpf_pseudo_kfunc_call(insn)) 2921 continue; 2922 2923 if (!env->bpf_capable) { 2924 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2925 return -EPERM; 2926 } 2927 2928 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2929 ret = add_subprog(env, i + insn->imm + 1); 2930 else 2931 ret = add_kfunc_call(env, insn->imm, insn->off); 2932 2933 if (ret < 0) 2934 return ret; 2935 } 2936 2937 ret = bpf_find_exception_callback_insn_off(env); 2938 if (ret < 0) 2939 return ret; 2940 ex_cb_insn = ret; 2941 2942 /* If ex_cb_insn > 0, this means that the main program has a subprog 2943 * marked using BTF decl tag to serve as the exception callback. 2944 */ 2945 if (ex_cb_insn) { 2946 ret = add_subprog(env, ex_cb_insn); 2947 if (ret < 0) 2948 return ret; 2949 for (i = 1; i < env->subprog_cnt; i++) { 2950 if (env->subprog_info[i].start != ex_cb_insn) 2951 continue; 2952 env->exception_callback_subprog = i; 2953 mark_subprog_exc_cb(env, i); 2954 break; 2955 } 2956 } 2957 2958 /* Add a fake 'exit' subprog which could simplify subprog iteration 2959 * logic. 'subprog_cnt' should not be increased. 2960 */ 2961 subprog[env->subprog_cnt].start = insn_cnt; 2962 2963 if (env->log.level & BPF_LOG_LEVEL2) 2964 for (i = 0; i < env->subprog_cnt; i++) 2965 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2966 2967 return 0; 2968 } 2969 2970 static int check_subprogs(struct bpf_verifier_env *env) 2971 { 2972 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2973 struct bpf_subprog_info *subprog = env->subprog_info; 2974 struct bpf_insn *insn = env->prog->insnsi; 2975 int insn_cnt = env->prog->len; 2976 2977 /* now check that all jumps are within the same subprog */ 2978 subprog_start = subprog[cur_subprog].start; 2979 subprog_end = subprog[cur_subprog + 1].start; 2980 for (i = 0; i < insn_cnt; i++) { 2981 u8 code = insn[i].code; 2982 2983 if (code == (BPF_JMP | BPF_CALL) && 2984 insn[i].src_reg == 0 && 2985 insn[i].imm == BPF_FUNC_tail_call) 2986 subprog[cur_subprog].has_tail_call = true; 2987 if (BPF_CLASS(code) == BPF_LD && 2988 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2989 subprog[cur_subprog].has_ld_abs = true; 2990 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2991 goto next; 2992 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2993 goto next; 2994 if (code == (BPF_JMP32 | BPF_JA)) 2995 off = i + insn[i].imm + 1; 2996 else 2997 off = i + insn[i].off + 1; 2998 if (off < subprog_start || off >= subprog_end) { 2999 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3000 return -EINVAL; 3001 } 3002 next: 3003 if (i == subprog_end - 1) { 3004 /* to avoid fall-through from one subprog into another 3005 * the last insn of the subprog should be either exit 3006 * or unconditional jump back or bpf_throw call 3007 */ 3008 if (code != (BPF_JMP | BPF_EXIT) && 3009 code != (BPF_JMP32 | BPF_JA) && 3010 code != (BPF_JMP | BPF_JA)) { 3011 verbose(env, "last insn is not an exit or jmp\n"); 3012 return -EINVAL; 3013 } 3014 subprog_start = subprog_end; 3015 cur_subprog++; 3016 if (cur_subprog < env->subprog_cnt) 3017 subprog_end = subprog[cur_subprog + 1].start; 3018 } 3019 } 3020 return 0; 3021 } 3022 3023 /* Parentage chain of this register (or stack slot) should take care of all 3024 * issues like callee-saved registers, stack slot allocation time, etc. 3025 */ 3026 static int mark_reg_read(struct bpf_verifier_env *env, 3027 const struct bpf_reg_state *state, 3028 struct bpf_reg_state *parent, u8 flag) 3029 { 3030 bool writes = parent == state->parent; /* Observe write marks */ 3031 int cnt = 0; 3032 3033 while (parent) { 3034 /* if read wasn't screened by an earlier write ... */ 3035 if (writes && state->live & REG_LIVE_WRITTEN) 3036 break; 3037 if (parent->live & REG_LIVE_DONE) { 3038 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3039 reg_type_str(env, parent->type), 3040 parent->var_off.value, parent->off); 3041 return -EFAULT; 3042 } 3043 /* The first condition is more likely to be true than the 3044 * second, checked it first. 3045 */ 3046 if ((parent->live & REG_LIVE_READ) == flag || 3047 parent->live & REG_LIVE_READ64) 3048 /* The parentage chain never changes and 3049 * this parent was already marked as LIVE_READ. 3050 * There is no need to keep walking the chain again and 3051 * keep re-marking all parents as LIVE_READ. 3052 * This case happens when the same register is read 3053 * multiple times without writes into it in-between. 3054 * Also, if parent has the stronger REG_LIVE_READ64 set, 3055 * then no need to set the weak REG_LIVE_READ32. 3056 */ 3057 break; 3058 /* ... then we depend on parent's value */ 3059 parent->live |= flag; 3060 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3061 if (flag == REG_LIVE_READ64) 3062 parent->live &= ~REG_LIVE_READ32; 3063 state = parent; 3064 parent = state->parent; 3065 writes = true; 3066 cnt++; 3067 } 3068 3069 if (env->longest_mark_read_walk < cnt) 3070 env->longest_mark_read_walk = cnt; 3071 return 0; 3072 } 3073 3074 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3075 { 3076 struct bpf_func_state *state = func(env, reg); 3077 int spi, ret; 3078 3079 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3080 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3081 * check_kfunc_call. 3082 */ 3083 if (reg->type == CONST_PTR_TO_DYNPTR) 3084 return 0; 3085 spi = dynptr_get_spi(env, reg); 3086 if (spi < 0) 3087 return spi; 3088 /* Caller ensures dynptr is valid and initialized, which means spi is in 3089 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3090 * read. 3091 */ 3092 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3093 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3094 if (ret) 3095 return ret; 3096 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3097 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3098 } 3099 3100 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3101 int spi, int nr_slots) 3102 { 3103 struct bpf_func_state *state = func(env, reg); 3104 int err, i; 3105 3106 for (i = 0; i < nr_slots; i++) { 3107 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3108 3109 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3110 if (err) 3111 return err; 3112 3113 mark_stack_slot_scratched(env, spi - i); 3114 } 3115 3116 return 0; 3117 } 3118 3119 /* This function is supposed to be used by the following 32-bit optimization 3120 * code only. It returns TRUE if the source or destination register operates 3121 * on 64-bit, otherwise return FALSE. 3122 */ 3123 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3124 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3125 { 3126 u8 code, class, op; 3127 3128 code = insn->code; 3129 class = BPF_CLASS(code); 3130 op = BPF_OP(code); 3131 if (class == BPF_JMP) { 3132 /* BPF_EXIT for "main" will reach here. Return TRUE 3133 * conservatively. 3134 */ 3135 if (op == BPF_EXIT) 3136 return true; 3137 if (op == BPF_CALL) { 3138 /* BPF to BPF call will reach here because of marking 3139 * caller saved clobber with DST_OP_NO_MARK for which we 3140 * don't care the register def because they are anyway 3141 * marked as NOT_INIT already. 3142 */ 3143 if (insn->src_reg == BPF_PSEUDO_CALL) 3144 return false; 3145 /* Helper call will reach here because of arg type 3146 * check, conservatively return TRUE. 3147 */ 3148 if (t == SRC_OP) 3149 return true; 3150 3151 return false; 3152 } 3153 } 3154 3155 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3156 return false; 3157 3158 if (class == BPF_ALU64 || class == BPF_JMP || 3159 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3160 return true; 3161 3162 if (class == BPF_ALU || class == BPF_JMP32) 3163 return false; 3164 3165 if (class == BPF_LDX) { 3166 if (t != SRC_OP) 3167 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3168 /* LDX source must be ptr. */ 3169 return true; 3170 } 3171 3172 if (class == BPF_STX) { 3173 /* BPF_STX (including atomic variants) has multiple source 3174 * operands, one of which is a ptr. Check whether the caller is 3175 * asking about it. 3176 */ 3177 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3178 return true; 3179 return BPF_SIZE(code) == BPF_DW; 3180 } 3181 3182 if (class == BPF_LD) { 3183 u8 mode = BPF_MODE(code); 3184 3185 /* LD_IMM64 */ 3186 if (mode == BPF_IMM) 3187 return true; 3188 3189 /* Both LD_IND and LD_ABS return 32-bit data. */ 3190 if (t != SRC_OP) 3191 return false; 3192 3193 /* Implicit ctx ptr. */ 3194 if (regno == BPF_REG_6) 3195 return true; 3196 3197 /* Explicit source could be any width. */ 3198 return true; 3199 } 3200 3201 if (class == BPF_ST) 3202 /* The only source register for BPF_ST is a ptr. */ 3203 return true; 3204 3205 /* Conservatively return true at default. */ 3206 return true; 3207 } 3208 3209 /* Return the regno defined by the insn, or -1. */ 3210 static int insn_def_regno(const struct bpf_insn *insn) 3211 { 3212 switch (BPF_CLASS(insn->code)) { 3213 case BPF_JMP: 3214 case BPF_JMP32: 3215 case BPF_ST: 3216 return -1; 3217 case BPF_STX: 3218 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3219 (insn->imm & BPF_FETCH)) { 3220 if (insn->imm == BPF_CMPXCHG) 3221 return BPF_REG_0; 3222 else 3223 return insn->src_reg; 3224 } else { 3225 return -1; 3226 } 3227 default: 3228 return insn->dst_reg; 3229 } 3230 } 3231 3232 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3233 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3234 { 3235 int dst_reg = insn_def_regno(insn); 3236 3237 if (dst_reg == -1) 3238 return false; 3239 3240 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3241 } 3242 3243 static void mark_insn_zext(struct bpf_verifier_env *env, 3244 struct bpf_reg_state *reg) 3245 { 3246 s32 def_idx = reg->subreg_def; 3247 3248 if (def_idx == DEF_NOT_SUBREG) 3249 return; 3250 3251 env->insn_aux_data[def_idx - 1].zext_dst = true; 3252 /* The dst will be zero extended, so won't be sub-register anymore. */ 3253 reg->subreg_def = DEF_NOT_SUBREG; 3254 } 3255 3256 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3257 enum reg_arg_type t) 3258 { 3259 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3260 struct bpf_reg_state *reg; 3261 bool rw64; 3262 3263 if (regno >= MAX_BPF_REG) { 3264 verbose(env, "R%d is invalid\n", regno); 3265 return -EINVAL; 3266 } 3267 3268 mark_reg_scratched(env, regno); 3269 3270 reg = ®s[regno]; 3271 rw64 = is_reg64(env, insn, regno, reg, t); 3272 if (t == SRC_OP) { 3273 /* check whether register used as source operand can be read */ 3274 if (reg->type == NOT_INIT) { 3275 verbose(env, "R%d !read_ok\n", regno); 3276 return -EACCES; 3277 } 3278 /* We don't need to worry about FP liveness because it's read-only */ 3279 if (regno == BPF_REG_FP) 3280 return 0; 3281 3282 if (rw64) 3283 mark_insn_zext(env, reg); 3284 3285 return mark_reg_read(env, reg, reg->parent, 3286 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3287 } else { 3288 /* check whether register used as dest operand can be written to */ 3289 if (regno == BPF_REG_FP) { 3290 verbose(env, "frame pointer is read only\n"); 3291 return -EACCES; 3292 } 3293 reg->live |= REG_LIVE_WRITTEN; 3294 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3295 if (t == DST_OP) 3296 mark_reg_unknown(env, regs, regno); 3297 } 3298 return 0; 3299 } 3300 3301 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3302 enum reg_arg_type t) 3303 { 3304 struct bpf_verifier_state *vstate = env->cur_state; 3305 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3306 3307 return __check_reg_arg(env, state->regs, regno, t); 3308 } 3309 3310 static int insn_stack_access_flags(int frameno, int spi) 3311 { 3312 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3313 } 3314 3315 static int insn_stack_access_spi(int insn_flags) 3316 { 3317 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3318 } 3319 3320 static int insn_stack_access_frameno(int insn_flags) 3321 { 3322 return insn_flags & INSN_F_FRAMENO_MASK; 3323 } 3324 3325 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3326 { 3327 env->insn_aux_data[idx].jmp_point = true; 3328 } 3329 3330 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3331 { 3332 return env->insn_aux_data[insn_idx].jmp_point; 3333 } 3334 3335 /* for any branch, call, exit record the history of jmps in the given state */ 3336 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3337 int insn_flags) 3338 { 3339 u32 cnt = cur->jmp_history_cnt; 3340 struct bpf_jmp_history_entry *p; 3341 size_t alloc_size; 3342 3343 /* combine instruction flags if we already recorded this instruction */ 3344 if (env->cur_hist_ent) { 3345 /* atomic instructions push insn_flags twice, for READ and 3346 * WRITE sides, but they should agree on stack slot 3347 */ 3348 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3349 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3350 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3351 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3352 env->cur_hist_ent->flags |= insn_flags; 3353 return 0; 3354 } 3355 3356 cnt++; 3357 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3358 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3359 if (!p) 3360 return -ENOMEM; 3361 cur->jmp_history = p; 3362 3363 p = &cur->jmp_history[cnt - 1]; 3364 p->idx = env->insn_idx; 3365 p->prev_idx = env->prev_insn_idx; 3366 p->flags = insn_flags; 3367 cur->jmp_history_cnt = cnt; 3368 env->cur_hist_ent = p; 3369 3370 return 0; 3371 } 3372 3373 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3374 u32 hist_end, int insn_idx) 3375 { 3376 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3377 return &st->jmp_history[hist_end - 1]; 3378 return NULL; 3379 } 3380 3381 /* Backtrack one insn at a time. If idx is not at the top of recorded 3382 * history then previous instruction came from straight line execution. 3383 * Return -ENOENT if we exhausted all instructions within given state. 3384 * 3385 * It's legal to have a bit of a looping with the same starting and ending 3386 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3387 * instruction index is the same as state's first_idx doesn't mean we are 3388 * done. If there is still some jump history left, we should keep going. We 3389 * need to take into account that we might have a jump history between given 3390 * state's parent and itself, due to checkpointing. In this case, we'll have 3391 * history entry recording a jump from last instruction of parent state and 3392 * first instruction of given state. 3393 */ 3394 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3395 u32 *history) 3396 { 3397 u32 cnt = *history; 3398 3399 if (i == st->first_insn_idx) { 3400 if (cnt == 0) 3401 return -ENOENT; 3402 if (cnt == 1 && st->jmp_history[0].idx == i) 3403 return -ENOENT; 3404 } 3405 3406 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3407 i = st->jmp_history[cnt - 1].prev_idx; 3408 (*history)--; 3409 } else { 3410 i--; 3411 } 3412 return i; 3413 } 3414 3415 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3416 { 3417 const struct btf_type *func; 3418 struct btf *desc_btf; 3419 3420 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3421 return NULL; 3422 3423 desc_btf = find_kfunc_desc_btf(data, insn->off); 3424 if (IS_ERR(desc_btf)) 3425 return "<error>"; 3426 3427 func = btf_type_by_id(desc_btf, insn->imm); 3428 return btf_name_by_offset(desc_btf, func->name_off); 3429 } 3430 3431 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3432 { 3433 bt->frame = frame; 3434 } 3435 3436 static inline void bt_reset(struct backtrack_state *bt) 3437 { 3438 struct bpf_verifier_env *env = bt->env; 3439 3440 memset(bt, 0, sizeof(*bt)); 3441 bt->env = env; 3442 } 3443 3444 static inline u32 bt_empty(struct backtrack_state *bt) 3445 { 3446 u64 mask = 0; 3447 int i; 3448 3449 for (i = 0; i <= bt->frame; i++) 3450 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3451 3452 return mask == 0; 3453 } 3454 3455 static inline int bt_subprog_enter(struct backtrack_state *bt) 3456 { 3457 if (bt->frame == MAX_CALL_FRAMES - 1) { 3458 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3459 WARN_ONCE(1, "verifier backtracking bug"); 3460 return -EFAULT; 3461 } 3462 bt->frame++; 3463 return 0; 3464 } 3465 3466 static inline int bt_subprog_exit(struct backtrack_state *bt) 3467 { 3468 if (bt->frame == 0) { 3469 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3470 WARN_ONCE(1, "verifier backtracking bug"); 3471 return -EFAULT; 3472 } 3473 bt->frame--; 3474 return 0; 3475 } 3476 3477 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3478 { 3479 bt->reg_masks[frame] |= 1 << reg; 3480 } 3481 3482 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3483 { 3484 bt->reg_masks[frame] &= ~(1 << reg); 3485 } 3486 3487 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3488 { 3489 bt_set_frame_reg(bt, bt->frame, reg); 3490 } 3491 3492 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3493 { 3494 bt_clear_frame_reg(bt, bt->frame, reg); 3495 } 3496 3497 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3498 { 3499 bt->stack_masks[frame] |= 1ull << slot; 3500 } 3501 3502 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3503 { 3504 bt->stack_masks[frame] &= ~(1ull << slot); 3505 } 3506 3507 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3508 { 3509 return bt->reg_masks[frame]; 3510 } 3511 3512 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3513 { 3514 return bt->reg_masks[bt->frame]; 3515 } 3516 3517 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3518 { 3519 return bt->stack_masks[frame]; 3520 } 3521 3522 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3523 { 3524 return bt->stack_masks[bt->frame]; 3525 } 3526 3527 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3528 { 3529 return bt->reg_masks[bt->frame] & (1 << reg); 3530 } 3531 3532 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3533 { 3534 return bt->stack_masks[frame] & (1ull << slot); 3535 } 3536 3537 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3538 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3539 { 3540 DECLARE_BITMAP(mask, 64); 3541 bool first = true; 3542 int i, n; 3543 3544 buf[0] = '\0'; 3545 3546 bitmap_from_u64(mask, reg_mask); 3547 for_each_set_bit(i, mask, 32) { 3548 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3549 first = false; 3550 buf += n; 3551 buf_sz -= n; 3552 if (buf_sz < 0) 3553 break; 3554 } 3555 } 3556 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3557 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3558 { 3559 DECLARE_BITMAP(mask, 64); 3560 bool first = true; 3561 int i, n; 3562 3563 buf[0] = '\0'; 3564 3565 bitmap_from_u64(mask, stack_mask); 3566 for_each_set_bit(i, mask, 64) { 3567 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3568 first = false; 3569 buf += n; 3570 buf_sz -= n; 3571 if (buf_sz < 0) 3572 break; 3573 } 3574 } 3575 3576 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3577 3578 /* For given verifier state backtrack_insn() is called from the last insn to 3579 * the first insn. Its purpose is to compute a bitmask of registers and 3580 * stack slots that needs precision in the parent verifier state. 3581 * 3582 * @idx is an index of the instruction we are currently processing; 3583 * @subseq_idx is an index of the subsequent instruction that: 3584 * - *would be* executed next, if jump history is viewed in forward order; 3585 * - *was* processed previously during backtracking. 3586 */ 3587 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3588 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3589 { 3590 const struct bpf_insn_cbs cbs = { 3591 .cb_call = disasm_kfunc_name, 3592 .cb_print = verbose, 3593 .private_data = env, 3594 }; 3595 struct bpf_insn *insn = env->prog->insnsi + idx; 3596 u8 class = BPF_CLASS(insn->code); 3597 u8 opcode = BPF_OP(insn->code); 3598 u8 mode = BPF_MODE(insn->code); 3599 u32 dreg = insn->dst_reg; 3600 u32 sreg = insn->src_reg; 3601 u32 spi, i, fr; 3602 3603 if (insn->code == 0) 3604 return 0; 3605 if (env->log.level & BPF_LOG_LEVEL2) { 3606 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3607 verbose(env, "mark_precise: frame%d: regs=%s ", 3608 bt->frame, env->tmp_str_buf); 3609 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3610 verbose(env, "stack=%s before ", env->tmp_str_buf); 3611 verbose(env, "%d: ", idx); 3612 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3613 } 3614 3615 if (class == BPF_ALU || class == BPF_ALU64) { 3616 if (!bt_is_reg_set(bt, dreg)) 3617 return 0; 3618 if (opcode == BPF_END || opcode == BPF_NEG) { 3619 /* sreg is reserved and unused 3620 * dreg still need precision before this insn 3621 */ 3622 return 0; 3623 } else if (opcode == BPF_MOV) { 3624 if (BPF_SRC(insn->code) == BPF_X) { 3625 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3626 * dreg needs precision after this insn 3627 * sreg needs precision before this insn 3628 */ 3629 bt_clear_reg(bt, dreg); 3630 if (sreg != BPF_REG_FP) 3631 bt_set_reg(bt, sreg); 3632 } else { 3633 /* dreg = K 3634 * dreg needs precision after this insn. 3635 * Corresponding register is already marked 3636 * as precise=true in this verifier state. 3637 * No further markings in parent are necessary 3638 */ 3639 bt_clear_reg(bt, dreg); 3640 } 3641 } else { 3642 if (BPF_SRC(insn->code) == BPF_X) { 3643 /* dreg += sreg 3644 * both dreg and sreg need precision 3645 * before this insn 3646 */ 3647 if (sreg != BPF_REG_FP) 3648 bt_set_reg(bt, sreg); 3649 } /* else dreg += K 3650 * dreg still needs precision before this insn 3651 */ 3652 } 3653 } else if (class == BPF_LDX) { 3654 if (!bt_is_reg_set(bt, dreg)) 3655 return 0; 3656 bt_clear_reg(bt, dreg); 3657 3658 /* scalars can only be spilled into stack w/o losing precision. 3659 * Load from any other memory can be zero extended. 3660 * The desire to keep that precision is already indicated 3661 * by 'precise' mark in corresponding register of this state. 3662 * No further tracking necessary. 3663 */ 3664 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3665 return 0; 3666 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3667 * that [fp - off] slot contains scalar that needs to be 3668 * tracked with precision 3669 */ 3670 spi = insn_stack_access_spi(hist->flags); 3671 fr = insn_stack_access_frameno(hist->flags); 3672 bt_set_frame_slot(bt, fr, spi); 3673 } else if (class == BPF_STX || class == BPF_ST) { 3674 if (bt_is_reg_set(bt, dreg)) 3675 /* stx & st shouldn't be using _scalar_ dst_reg 3676 * to access memory. It means backtracking 3677 * encountered a case of pointer subtraction. 3678 */ 3679 return -ENOTSUPP; 3680 /* scalars can only be spilled into stack */ 3681 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3682 return 0; 3683 spi = insn_stack_access_spi(hist->flags); 3684 fr = insn_stack_access_frameno(hist->flags); 3685 if (!bt_is_frame_slot_set(bt, fr, spi)) 3686 return 0; 3687 bt_clear_frame_slot(bt, fr, spi); 3688 if (class == BPF_STX) 3689 bt_set_reg(bt, sreg); 3690 } else if (class == BPF_JMP || class == BPF_JMP32) { 3691 if (bpf_pseudo_call(insn)) { 3692 int subprog_insn_idx, subprog; 3693 3694 subprog_insn_idx = idx + insn->imm + 1; 3695 subprog = find_subprog(env, subprog_insn_idx); 3696 if (subprog < 0) 3697 return -EFAULT; 3698 3699 if (subprog_is_global(env, subprog)) { 3700 /* check that jump history doesn't have any 3701 * extra instructions from subprog; the next 3702 * instruction after call to global subprog 3703 * should be literally next instruction in 3704 * caller program 3705 */ 3706 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3707 /* r1-r5 are invalidated after subprog call, 3708 * so for global func call it shouldn't be set 3709 * anymore 3710 */ 3711 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3712 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3713 WARN_ONCE(1, "verifier backtracking bug"); 3714 return -EFAULT; 3715 } 3716 /* global subprog always sets R0 */ 3717 bt_clear_reg(bt, BPF_REG_0); 3718 return 0; 3719 } else { 3720 /* static subprog call instruction, which 3721 * means that we are exiting current subprog, 3722 * so only r1-r5 could be still requested as 3723 * precise, r0 and r6-r10 or any stack slot in 3724 * the current frame should be zero by now 3725 */ 3726 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3727 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3728 WARN_ONCE(1, "verifier backtracking bug"); 3729 return -EFAULT; 3730 } 3731 /* we are now tracking register spills correctly, 3732 * so any instance of leftover slots is a bug 3733 */ 3734 if (bt_stack_mask(bt) != 0) { 3735 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3736 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3737 return -EFAULT; 3738 } 3739 /* propagate r1-r5 to the caller */ 3740 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3741 if (bt_is_reg_set(bt, i)) { 3742 bt_clear_reg(bt, i); 3743 bt_set_frame_reg(bt, bt->frame - 1, i); 3744 } 3745 } 3746 if (bt_subprog_exit(bt)) 3747 return -EFAULT; 3748 return 0; 3749 } 3750 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3751 /* exit from callback subprog to callback-calling helper or 3752 * kfunc call. Use idx/subseq_idx check to discern it from 3753 * straight line code backtracking. 3754 * Unlike the subprog call handling above, we shouldn't 3755 * propagate precision of r1-r5 (if any requested), as they are 3756 * not actually arguments passed directly to callback subprogs 3757 */ 3758 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3759 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3760 WARN_ONCE(1, "verifier backtracking bug"); 3761 return -EFAULT; 3762 } 3763 if (bt_stack_mask(bt) != 0) { 3764 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3765 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3766 return -EFAULT; 3767 } 3768 /* clear r1-r5 in callback subprog's mask */ 3769 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3770 bt_clear_reg(bt, i); 3771 if (bt_subprog_exit(bt)) 3772 return -EFAULT; 3773 return 0; 3774 } else if (opcode == BPF_CALL) { 3775 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3776 * catch this error later. Make backtracking conservative 3777 * with ENOTSUPP. 3778 */ 3779 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3780 return -ENOTSUPP; 3781 /* regular helper call sets R0 */ 3782 bt_clear_reg(bt, BPF_REG_0); 3783 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3784 /* if backtracing was looking for registers R1-R5 3785 * they should have been found already. 3786 */ 3787 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3788 WARN_ONCE(1, "verifier backtracking bug"); 3789 return -EFAULT; 3790 } 3791 } else if (opcode == BPF_EXIT) { 3792 bool r0_precise; 3793 3794 /* Backtracking to a nested function call, 'idx' is a part of 3795 * the inner frame 'subseq_idx' is a part of the outer frame. 3796 * In case of a regular function call, instructions giving 3797 * precision to registers R1-R5 should have been found already. 3798 * In case of a callback, it is ok to have R1-R5 marked for 3799 * backtracking, as these registers are set by the function 3800 * invoking callback. 3801 */ 3802 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3803 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3804 bt_clear_reg(bt, i); 3805 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3806 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3807 WARN_ONCE(1, "verifier backtracking bug"); 3808 return -EFAULT; 3809 } 3810 3811 /* BPF_EXIT in subprog or callback always returns 3812 * right after the call instruction, so by checking 3813 * whether the instruction at subseq_idx-1 is subprog 3814 * call or not we can distinguish actual exit from 3815 * *subprog* from exit from *callback*. In the former 3816 * case, we need to propagate r0 precision, if 3817 * necessary. In the former we never do that. 3818 */ 3819 r0_precise = subseq_idx - 1 >= 0 && 3820 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3821 bt_is_reg_set(bt, BPF_REG_0); 3822 3823 bt_clear_reg(bt, BPF_REG_0); 3824 if (bt_subprog_enter(bt)) 3825 return -EFAULT; 3826 3827 if (r0_precise) 3828 bt_set_reg(bt, BPF_REG_0); 3829 /* r6-r9 and stack slots will stay set in caller frame 3830 * bitmasks until we return back from callee(s) 3831 */ 3832 return 0; 3833 } else if (BPF_SRC(insn->code) == BPF_X) { 3834 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3835 return 0; 3836 /* dreg <cond> sreg 3837 * Both dreg and sreg need precision before 3838 * this insn. If only sreg was marked precise 3839 * before it would be equally necessary to 3840 * propagate it to dreg. 3841 */ 3842 bt_set_reg(bt, dreg); 3843 bt_set_reg(bt, sreg); 3844 /* else dreg <cond> K 3845 * Only dreg still needs precision before 3846 * this insn, so for the K-based conditional 3847 * there is nothing new to be marked. 3848 */ 3849 } 3850 } else if (class == BPF_LD) { 3851 if (!bt_is_reg_set(bt, dreg)) 3852 return 0; 3853 bt_clear_reg(bt, dreg); 3854 /* It's ld_imm64 or ld_abs or ld_ind. 3855 * For ld_imm64 no further tracking of precision 3856 * into parent is necessary 3857 */ 3858 if (mode == BPF_IND || mode == BPF_ABS) 3859 /* to be analyzed */ 3860 return -ENOTSUPP; 3861 } 3862 return 0; 3863 } 3864 3865 /* the scalar precision tracking algorithm: 3866 * . at the start all registers have precise=false. 3867 * . scalar ranges are tracked as normal through alu and jmp insns. 3868 * . once precise value of the scalar register is used in: 3869 * . ptr + scalar alu 3870 * . if (scalar cond K|scalar) 3871 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3872 * backtrack through the verifier states and mark all registers and 3873 * stack slots with spilled constants that these scalar regisers 3874 * should be precise. 3875 * . during state pruning two registers (or spilled stack slots) 3876 * are equivalent if both are not precise. 3877 * 3878 * Note the verifier cannot simply walk register parentage chain, 3879 * since many different registers and stack slots could have been 3880 * used to compute single precise scalar. 3881 * 3882 * The approach of starting with precise=true for all registers and then 3883 * backtrack to mark a register as not precise when the verifier detects 3884 * that program doesn't care about specific value (e.g., when helper 3885 * takes register as ARG_ANYTHING parameter) is not safe. 3886 * 3887 * It's ok to walk single parentage chain of the verifier states. 3888 * It's possible that this backtracking will go all the way till 1st insn. 3889 * All other branches will be explored for needing precision later. 3890 * 3891 * The backtracking needs to deal with cases like: 3892 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0) 3893 * r9 -= r8 3894 * r5 = r9 3895 * if r5 > 0x79f goto pc+7 3896 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3897 * r5 += 1 3898 * ... 3899 * call bpf_perf_event_output#25 3900 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3901 * 3902 * and this case: 3903 * r6 = 1 3904 * call foo // uses callee's r6 inside to compute r0 3905 * r0 += r6 3906 * if r0 == 0 goto 3907 * 3908 * to track above reg_mask/stack_mask needs to be independent for each frame. 3909 * 3910 * Also if parent's curframe > frame where backtracking started, 3911 * the verifier need to mark registers in both frames, otherwise callees 3912 * may incorrectly prune callers. This is similar to 3913 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3914 * 3915 * For now backtracking falls back into conservative marking. 3916 */ 3917 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3918 struct bpf_verifier_state *st) 3919 { 3920 struct bpf_func_state *func; 3921 struct bpf_reg_state *reg; 3922 int i, j; 3923 3924 if (env->log.level & BPF_LOG_LEVEL2) { 3925 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3926 st->curframe); 3927 } 3928 3929 /* big hammer: mark all scalars precise in this path. 3930 * pop_stack may still get !precise scalars. 3931 * We also skip current state and go straight to first parent state, 3932 * because precision markings in current non-checkpointed state are 3933 * not needed. See why in the comment in __mark_chain_precision below. 3934 */ 3935 for (st = st->parent; st; st = st->parent) { 3936 for (i = 0; i <= st->curframe; i++) { 3937 func = st->frame[i]; 3938 for (j = 0; j < BPF_REG_FP; j++) { 3939 reg = &func->regs[j]; 3940 if (reg->type != SCALAR_VALUE || reg->precise) 3941 continue; 3942 reg->precise = true; 3943 if (env->log.level & BPF_LOG_LEVEL2) { 3944 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3945 i, j); 3946 } 3947 } 3948 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3949 if (!is_spilled_reg(&func->stack[j])) 3950 continue; 3951 reg = &func->stack[j].spilled_ptr; 3952 if (reg->type != SCALAR_VALUE || reg->precise) 3953 continue; 3954 reg->precise = true; 3955 if (env->log.level & BPF_LOG_LEVEL2) { 3956 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3957 i, -(j + 1) * 8); 3958 } 3959 } 3960 } 3961 } 3962 } 3963 3964 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3965 { 3966 struct bpf_func_state *func; 3967 struct bpf_reg_state *reg; 3968 int i, j; 3969 3970 for (i = 0; i <= st->curframe; i++) { 3971 func = st->frame[i]; 3972 for (j = 0; j < BPF_REG_FP; j++) { 3973 reg = &func->regs[j]; 3974 if (reg->type != SCALAR_VALUE) 3975 continue; 3976 reg->precise = false; 3977 } 3978 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3979 if (!is_spilled_reg(&func->stack[j])) 3980 continue; 3981 reg = &func->stack[j].spilled_ptr; 3982 if (reg->type != SCALAR_VALUE) 3983 continue; 3984 reg->precise = false; 3985 } 3986 } 3987 } 3988 3989 static bool idset_contains(struct bpf_idset *s, u32 id) 3990 { 3991 u32 i; 3992 3993 for (i = 0; i < s->count; ++i) 3994 if (s->ids[i] == (id & ~BPF_ADD_CONST)) 3995 return true; 3996 3997 return false; 3998 } 3999 4000 static int idset_push(struct bpf_idset *s, u32 id) 4001 { 4002 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 4003 return -EFAULT; 4004 s->ids[s->count++] = id & ~BPF_ADD_CONST; 4005 return 0; 4006 } 4007 4008 static void idset_reset(struct bpf_idset *s) 4009 { 4010 s->count = 0; 4011 } 4012 4013 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 4014 * Mark all registers with these IDs as precise. 4015 */ 4016 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4017 { 4018 struct bpf_idset *precise_ids = &env->idset_scratch; 4019 struct backtrack_state *bt = &env->bt; 4020 struct bpf_func_state *func; 4021 struct bpf_reg_state *reg; 4022 DECLARE_BITMAP(mask, 64); 4023 int i, fr; 4024 4025 idset_reset(precise_ids); 4026 4027 for (fr = bt->frame; fr >= 0; fr--) { 4028 func = st->frame[fr]; 4029 4030 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4031 for_each_set_bit(i, mask, 32) { 4032 reg = &func->regs[i]; 4033 if (!reg->id || reg->type != SCALAR_VALUE) 4034 continue; 4035 if (idset_push(precise_ids, reg->id)) 4036 return -EFAULT; 4037 } 4038 4039 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4040 for_each_set_bit(i, mask, 64) { 4041 if (i >= func->allocated_stack / BPF_REG_SIZE) 4042 break; 4043 if (!is_spilled_scalar_reg(&func->stack[i])) 4044 continue; 4045 reg = &func->stack[i].spilled_ptr; 4046 if (!reg->id) 4047 continue; 4048 if (idset_push(precise_ids, reg->id)) 4049 return -EFAULT; 4050 } 4051 } 4052 4053 for (fr = 0; fr <= st->curframe; ++fr) { 4054 func = st->frame[fr]; 4055 4056 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4057 reg = &func->regs[i]; 4058 if (!reg->id) 4059 continue; 4060 if (!idset_contains(precise_ids, reg->id)) 4061 continue; 4062 bt_set_frame_reg(bt, fr, i); 4063 } 4064 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4065 if (!is_spilled_scalar_reg(&func->stack[i])) 4066 continue; 4067 reg = &func->stack[i].spilled_ptr; 4068 if (!reg->id) 4069 continue; 4070 if (!idset_contains(precise_ids, reg->id)) 4071 continue; 4072 bt_set_frame_slot(bt, fr, i); 4073 } 4074 } 4075 4076 return 0; 4077 } 4078 4079 /* 4080 * __mark_chain_precision() backtracks BPF program instruction sequence and 4081 * chain of verifier states making sure that register *regno* (if regno >= 0) 4082 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4083 * SCALARS, as well as any other registers and slots that contribute to 4084 * a tracked state of given registers/stack slots, depending on specific BPF 4085 * assembly instructions (see backtrack_insns() for exact instruction handling 4086 * logic). This backtracking relies on recorded jmp_history and is able to 4087 * traverse entire chain of parent states. This process ends only when all the 4088 * necessary registers/slots and their transitive dependencies are marked as 4089 * precise. 4090 * 4091 * One important and subtle aspect is that precise marks *do not matter* in 4092 * the currently verified state (current state). It is important to understand 4093 * why this is the case. 4094 * 4095 * First, note that current state is the state that is not yet "checkpointed", 4096 * i.e., it is not yet put into env->explored_states, and it has no children 4097 * states as well. It's ephemeral, and can end up either a) being discarded if 4098 * compatible explored state is found at some point or BPF_EXIT instruction is 4099 * reached or b) checkpointed and put into env->explored_states, branching out 4100 * into one or more children states. 4101 * 4102 * In the former case, precise markings in current state are completely 4103 * ignored by state comparison code (see regsafe() for details). Only 4104 * checkpointed ("old") state precise markings are important, and if old 4105 * state's register/slot is precise, regsafe() assumes current state's 4106 * register/slot as precise and checks value ranges exactly and precisely. If 4107 * states turn out to be compatible, current state's necessary precise 4108 * markings and any required parent states' precise markings are enforced 4109 * after the fact with propagate_precision() logic, after the fact. But it's 4110 * important to realize that in this case, even after marking current state 4111 * registers/slots as precise, we immediately discard current state. So what 4112 * actually matters is any of the precise markings propagated into current 4113 * state's parent states, which are always checkpointed (due to b) case above). 4114 * As such, for scenario a) it doesn't matter if current state has precise 4115 * markings set or not. 4116 * 4117 * Now, for the scenario b), checkpointing and forking into child(ren) 4118 * state(s). Note that before current state gets to checkpointing step, any 4119 * processed instruction always assumes precise SCALAR register/slot 4120 * knowledge: if precise value or range is useful to prune jump branch, BPF 4121 * verifier takes this opportunity enthusiastically. Similarly, when 4122 * register's value is used to calculate offset or memory address, exact 4123 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4124 * what we mentioned above about state comparison ignoring precise markings 4125 * during state comparison, BPF verifier ignores and also assumes precise 4126 * markings *at will* during instruction verification process. But as verifier 4127 * assumes precision, it also propagates any precision dependencies across 4128 * parent states, which are not yet finalized, so can be further restricted 4129 * based on new knowledge gained from restrictions enforced by their children 4130 * states. This is so that once those parent states are finalized, i.e., when 4131 * they have no more active children state, state comparison logic in 4132 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4133 * required for correctness. 4134 * 4135 * To build a bit more intuition, note also that once a state is checkpointed, 4136 * the path we took to get to that state is not important. This is crucial 4137 * property for state pruning. When state is checkpointed and finalized at 4138 * some instruction index, it can be correctly and safely used to "short 4139 * circuit" any *compatible* state that reaches exactly the same instruction 4140 * index. I.e., if we jumped to that instruction from a completely different 4141 * code path than original finalized state was derived from, it doesn't 4142 * matter, current state can be discarded because from that instruction 4143 * forward having a compatible state will ensure we will safely reach the 4144 * exit. States describe preconditions for further exploration, but completely 4145 * forget the history of how we got here. 4146 * 4147 * This also means that even if we needed precise SCALAR range to get to 4148 * finalized state, but from that point forward *that same* SCALAR register is 4149 * never used in a precise context (i.e., it's precise value is not needed for 4150 * correctness), it's correct and safe to mark such register as "imprecise" 4151 * (i.e., precise marking set to false). This is what we rely on when we do 4152 * not set precise marking in current state. If no child state requires 4153 * precision for any given SCALAR register, it's safe to dictate that it can 4154 * be imprecise. If any child state does require this register to be precise, 4155 * we'll mark it precise later retroactively during precise markings 4156 * propagation from child state to parent states. 4157 * 4158 * Skipping precise marking setting in current state is a mild version of 4159 * relying on the above observation. But we can utilize this property even 4160 * more aggressively by proactively forgetting any precise marking in the 4161 * current state (which we inherited from the parent state), right before we 4162 * checkpoint it and branch off into new child state. This is done by 4163 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4164 * finalized states which help in short circuiting more future states. 4165 */ 4166 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4167 { 4168 struct backtrack_state *bt = &env->bt; 4169 struct bpf_verifier_state *st = env->cur_state; 4170 int first_idx = st->first_insn_idx; 4171 int last_idx = env->insn_idx; 4172 int subseq_idx = -1; 4173 struct bpf_func_state *func; 4174 struct bpf_reg_state *reg; 4175 bool skip_first = true; 4176 int i, fr, err; 4177 4178 if (!env->bpf_capable) 4179 return 0; 4180 4181 /* set frame number from which we are starting to backtrack */ 4182 bt_init(bt, env->cur_state->curframe); 4183 4184 /* Do sanity checks against current state of register and/or stack 4185 * slot, but don't set precise flag in current state, as precision 4186 * tracking in the current state is unnecessary. 4187 */ 4188 func = st->frame[bt->frame]; 4189 if (regno >= 0) { 4190 reg = &func->regs[regno]; 4191 if (reg->type != SCALAR_VALUE) { 4192 WARN_ONCE(1, "backtracing misuse"); 4193 return -EFAULT; 4194 } 4195 bt_set_reg(bt, regno); 4196 } 4197 4198 if (bt_empty(bt)) 4199 return 0; 4200 4201 for (;;) { 4202 DECLARE_BITMAP(mask, 64); 4203 u32 history = st->jmp_history_cnt; 4204 struct bpf_jmp_history_entry *hist; 4205 4206 if (env->log.level & BPF_LOG_LEVEL2) { 4207 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4208 bt->frame, last_idx, first_idx, subseq_idx); 4209 } 4210 4211 /* If some register with scalar ID is marked as precise, 4212 * make sure that all registers sharing this ID are also precise. 4213 * This is needed to estimate effect of find_equal_scalars(). 4214 * Do this at the last instruction of each state, 4215 * bpf_reg_state::id fields are valid for these instructions. 4216 * 4217 * Allows to track precision in situation like below: 4218 * 4219 * r2 = unknown value 4220 * ... 4221 * --- state #0 --- 4222 * ... 4223 * r1 = r2 // r1 and r2 now share the same ID 4224 * ... 4225 * --- state #1 {r1.id = A, r2.id = A} --- 4226 * ... 4227 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4228 * ... 4229 * --- state #2 {r1.id = A, r2.id = A} --- 4230 * r3 = r10 4231 * r3 += r1 // need to mark both r1 and r2 4232 */ 4233 if (mark_precise_scalar_ids(env, st)) 4234 return -EFAULT; 4235 4236 if (last_idx < 0) { 4237 /* we are at the entry into subprog, which 4238 * is expected for global funcs, but only if 4239 * requested precise registers are R1-R5 4240 * (which are global func's input arguments) 4241 */ 4242 if (st->curframe == 0 && 4243 st->frame[0]->subprogno > 0 && 4244 st->frame[0]->callsite == BPF_MAIN_FUNC && 4245 bt_stack_mask(bt) == 0 && 4246 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4247 bitmap_from_u64(mask, bt_reg_mask(bt)); 4248 for_each_set_bit(i, mask, 32) { 4249 reg = &st->frame[0]->regs[i]; 4250 bt_clear_reg(bt, i); 4251 if (reg->type == SCALAR_VALUE) 4252 reg->precise = true; 4253 } 4254 return 0; 4255 } 4256 4257 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4258 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4259 WARN_ONCE(1, "verifier backtracking bug"); 4260 return -EFAULT; 4261 } 4262 4263 for (i = last_idx;;) { 4264 if (skip_first) { 4265 err = 0; 4266 skip_first = false; 4267 } else { 4268 hist = get_jmp_hist_entry(st, history, i); 4269 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4270 } 4271 if (err == -ENOTSUPP) { 4272 mark_all_scalars_precise(env, env->cur_state); 4273 bt_reset(bt); 4274 return 0; 4275 } else if (err) { 4276 return err; 4277 } 4278 if (bt_empty(bt)) 4279 /* Found assignment(s) into tracked register in this state. 4280 * Since this state is already marked, just return. 4281 * Nothing to be tracked further in the parent state. 4282 */ 4283 return 0; 4284 subseq_idx = i; 4285 i = get_prev_insn_idx(st, i, &history); 4286 if (i == -ENOENT) 4287 break; 4288 if (i >= env->prog->len) { 4289 /* This can happen if backtracking reached insn 0 4290 * and there are still reg_mask or stack_mask 4291 * to backtrack. 4292 * It means the backtracking missed the spot where 4293 * particular register was initialized with a constant. 4294 */ 4295 verbose(env, "BUG backtracking idx %d\n", i); 4296 WARN_ONCE(1, "verifier backtracking bug"); 4297 return -EFAULT; 4298 } 4299 } 4300 st = st->parent; 4301 if (!st) 4302 break; 4303 4304 for (fr = bt->frame; fr >= 0; fr--) { 4305 func = st->frame[fr]; 4306 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4307 for_each_set_bit(i, mask, 32) { 4308 reg = &func->regs[i]; 4309 if (reg->type != SCALAR_VALUE) { 4310 bt_clear_frame_reg(bt, fr, i); 4311 continue; 4312 } 4313 if (reg->precise) 4314 bt_clear_frame_reg(bt, fr, i); 4315 else 4316 reg->precise = true; 4317 } 4318 4319 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4320 for_each_set_bit(i, mask, 64) { 4321 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4322 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4323 i, func->allocated_stack / BPF_REG_SIZE); 4324 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4325 return -EFAULT; 4326 } 4327 4328 if (!is_spilled_scalar_reg(&func->stack[i])) { 4329 bt_clear_frame_slot(bt, fr, i); 4330 continue; 4331 } 4332 reg = &func->stack[i].spilled_ptr; 4333 if (reg->precise) 4334 bt_clear_frame_slot(bt, fr, i); 4335 else 4336 reg->precise = true; 4337 } 4338 if (env->log.level & BPF_LOG_LEVEL2) { 4339 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4340 bt_frame_reg_mask(bt, fr)); 4341 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4342 fr, env->tmp_str_buf); 4343 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4344 bt_frame_stack_mask(bt, fr)); 4345 verbose(env, "stack=%s: ", env->tmp_str_buf); 4346 print_verifier_state(env, func, true); 4347 } 4348 } 4349 4350 if (bt_empty(bt)) 4351 return 0; 4352 4353 subseq_idx = first_idx; 4354 last_idx = st->last_insn_idx; 4355 first_idx = st->first_insn_idx; 4356 } 4357 4358 /* if we still have requested precise regs or slots, we missed 4359 * something (e.g., stack access through non-r10 register), so 4360 * fallback to marking all precise 4361 */ 4362 if (!bt_empty(bt)) { 4363 mark_all_scalars_precise(env, env->cur_state); 4364 bt_reset(bt); 4365 } 4366 4367 return 0; 4368 } 4369 4370 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4371 { 4372 return __mark_chain_precision(env, regno); 4373 } 4374 4375 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4376 * desired reg and stack masks across all relevant frames 4377 */ 4378 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4379 { 4380 return __mark_chain_precision(env, -1); 4381 } 4382 4383 static bool is_spillable_regtype(enum bpf_reg_type type) 4384 { 4385 switch (base_type(type)) { 4386 case PTR_TO_MAP_VALUE: 4387 case PTR_TO_STACK: 4388 case PTR_TO_CTX: 4389 case PTR_TO_PACKET: 4390 case PTR_TO_PACKET_META: 4391 case PTR_TO_PACKET_END: 4392 case PTR_TO_FLOW_KEYS: 4393 case CONST_PTR_TO_MAP: 4394 case PTR_TO_SOCKET: 4395 case PTR_TO_SOCK_COMMON: 4396 case PTR_TO_TCP_SOCK: 4397 case PTR_TO_XDP_SOCK: 4398 case PTR_TO_BTF_ID: 4399 case PTR_TO_BUF: 4400 case PTR_TO_MEM: 4401 case PTR_TO_FUNC: 4402 case PTR_TO_MAP_KEY: 4403 case PTR_TO_ARENA: 4404 return true; 4405 default: 4406 return false; 4407 } 4408 } 4409 4410 /* Does this register contain a constant zero? */ 4411 static bool register_is_null(struct bpf_reg_state *reg) 4412 { 4413 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4414 } 4415 4416 /* check if register is a constant scalar value */ 4417 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4418 { 4419 return reg->type == SCALAR_VALUE && 4420 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4421 } 4422 4423 /* assuming is_reg_const() is true, return constant value of a register */ 4424 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4425 { 4426 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4427 } 4428 4429 static bool __is_pointer_value(bool allow_ptr_leaks, 4430 const struct bpf_reg_state *reg) 4431 { 4432 if (allow_ptr_leaks) 4433 return false; 4434 4435 return reg->type != SCALAR_VALUE; 4436 } 4437 4438 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4439 struct bpf_reg_state *src_reg) 4440 { 4441 if (src_reg->type != SCALAR_VALUE) 4442 return; 4443 4444 if (src_reg->id & BPF_ADD_CONST) { 4445 /* 4446 * The verifier is processing rX = rY insn and 4447 * rY->id has special linked register already. 4448 * Cleared it, since multiple rX += const are not supported. 4449 */ 4450 src_reg->id = 0; 4451 src_reg->off = 0; 4452 } 4453 4454 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 4455 /* Ensure that src_reg has a valid ID that will be copied to 4456 * dst_reg and then will be used by find_equal_scalars() to 4457 * propagate min/max range. 4458 */ 4459 src_reg->id = ++env->id_gen; 4460 } 4461 4462 /* Copy src state preserving dst->parent and dst->live fields */ 4463 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4464 { 4465 struct bpf_reg_state *parent = dst->parent; 4466 enum bpf_reg_liveness live = dst->live; 4467 4468 *dst = *src; 4469 dst->parent = parent; 4470 dst->live = live; 4471 } 4472 4473 static void save_register_state(struct bpf_verifier_env *env, 4474 struct bpf_func_state *state, 4475 int spi, struct bpf_reg_state *reg, 4476 int size) 4477 { 4478 int i; 4479 4480 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4481 if (size == BPF_REG_SIZE) 4482 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4483 4484 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4485 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4486 4487 /* size < 8 bytes spill */ 4488 for (; i; i--) 4489 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4490 } 4491 4492 static bool is_bpf_st_mem(struct bpf_insn *insn) 4493 { 4494 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4495 } 4496 4497 static int get_reg_width(struct bpf_reg_state *reg) 4498 { 4499 return fls64(reg->umax_value); 4500 } 4501 4502 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4503 * stack boundary and alignment are checked in check_mem_access() 4504 */ 4505 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4506 /* stack frame we're writing to */ 4507 struct bpf_func_state *state, 4508 int off, int size, int value_regno, 4509 int insn_idx) 4510 { 4511 struct bpf_func_state *cur; /* state of the current function */ 4512 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4513 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4514 struct bpf_reg_state *reg = NULL; 4515 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4516 4517 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4518 * so it's aligned access and [off, off + size) are within stack limits 4519 */ 4520 if (!env->allow_ptr_leaks && 4521 is_spilled_reg(&state->stack[spi]) && 4522 size != BPF_REG_SIZE) { 4523 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4524 return -EACCES; 4525 } 4526 4527 cur = env->cur_state->frame[env->cur_state->curframe]; 4528 if (value_regno >= 0) 4529 reg = &cur->regs[value_regno]; 4530 if (!env->bypass_spec_v4) { 4531 bool sanitize = reg && is_spillable_regtype(reg->type); 4532 4533 for (i = 0; i < size; i++) { 4534 u8 type = state->stack[spi].slot_type[i]; 4535 4536 if (type != STACK_MISC && type != STACK_ZERO) { 4537 sanitize = true; 4538 break; 4539 } 4540 } 4541 4542 if (sanitize) 4543 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4544 } 4545 4546 err = destroy_if_dynptr_stack_slot(env, state, spi); 4547 if (err) 4548 return err; 4549 4550 mark_stack_slot_scratched(env, spi); 4551 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4552 bool reg_value_fits; 4553 4554 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4555 /* Make sure that reg had an ID to build a relation on spill. */ 4556 if (reg_value_fits) 4557 assign_scalar_id_before_mov(env, reg); 4558 save_register_state(env, state, spi, reg, size); 4559 /* Break the relation on a narrowing spill. */ 4560 if (!reg_value_fits) 4561 state->stack[spi].spilled_ptr.id = 0; 4562 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4563 env->bpf_capable) { 4564 struct bpf_reg_state fake_reg = {}; 4565 4566 __mark_reg_known(&fake_reg, insn->imm); 4567 fake_reg.type = SCALAR_VALUE; 4568 save_register_state(env, state, spi, &fake_reg, size); 4569 } else if (reg && is_spillable_regtype(reg->type)) { 4570 /* register containing pointer is being spilled into stack */ 4571 if (size != BPF_REG_SIZE) { 4572 verbose_linfo(env, insn_idx, "; "); 4573 verbose(env, "invalid size of register spill\n"); 4574 return -EACCES; 4575 } 4576 if (state != cur && reg->type == PTR_TO_STACK) { 4577 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4578 return -EINVAL; 4579 } 4580 save_register_state(env, state, spi, reg, size); 4581 } else { 4582 u8 type = STACK_MISC; 4583 4584 /* regular write of data into stack destroys any spilled ptr */ 4585 state->stack[spi].spilled_ptr.type = NOT_INIT; 4586 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4587 if (is_stack_slot_special(&state->stack[spi])) 4588 for (i = 0; i < BPF_REG_SIZE; i++) 4589 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4590 4591 /* only mark the slot as written if all 8 bytes were written 4592 * otherwise read propagation may incorrectly stop too soon 4593 * when stack slots are partially written. 4594 * This heuristic means that read propagation will be 4595 * conservative, since it will add reg_live_read marks 4596 * to stack slots all the way to first state when programs 4597 * writes+reads less than 8 bytes 4598 */ 4599 if (size == BPF_REG_SIZE) 4600 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4601 4602 /* when we zero initialize stack slots mark them as such */ 4603 if ((reg && register_is_null(reg)) || 4604 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4605 /* STACK_ZERO case happened because register spill 4606 * wasn't properly aligned at the stack slot boundary, 4607 * so it's not a register spill anymore; force 4608 * originating register to be precise to make 4609 * STACK_ZERO correct for subsequent states 4610 */ 4611 err = mark_chain_precision(env, value_regno); 4612 if (err) 4613 return err; 4614 type = STACK_ZERO; 4615 } 4616 4617 /* Mark slots affected by this stack write. */ 4618 for (i = 0; i < size; i++) 4619 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4620 insn_flags = 0; /* not a register spill */ 4621 } 4622 4623 if (insn_flags) 4624 return push_jmp_history(env, env->cur_state, insn_flags); 4625 return 0; 4626 } 4627 4628 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4629 * known to contain a variable offset. 4630 * This function checks whether the write is permitted and conservatively 4631 * tracks the effects of the write, considering that each stack slot in the 4632 * dynamic range is potentially written to. 4633 * 4634 * 'off' includes 'regno->off'. 4635 * 'value_regno' can be -1, meaning that an unknown value is being written to 4636 * the stack. 4637 * 4638 * Spilled pointers in range are not marked as written because we don't know 4639 * what's going to be actually written. This means that read propagation for 4640 * future reads cannot be terminated by this write. 4641 * 4642 * For privileged programs, uninitialized stack slots are considered 4643 * initialized by this write (even though we don't know exactly what offsets 4644 * are going to be written to). The idea is that we don't want the verifier to 4645 * reject future reads that access slots written to through variable offsets. 4646 */ 4647 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4648 /* func where register points to */ 4649 struct bpf_func_state *state, 4650 int ptr_regno, int off, int size, 4651 int value_regno, int insn_idx) 4652 { 4653 struct bpf_func_state *cur; /* state of the current function */ 4654 int min_off, max_off; 4655 int i, err; 4656 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4657 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4658 bool writing_zero = false; 4659 /* set if the fact that we're writing a zero is used to let any 4660 * stack slots remain STACK_ZERO 4661 */ 4662 bool zero_used = false; 4663 4664 cur = env->cur_state->frame[env->cur_state->curframe]; 4665 ptr_reg = &cur->regs[ptr_regno]; 4666 min_off = ptr_reg->smin_value + off; 4667 max_off = ptr_reg->smax_value + off + size; 4668 if (value_regno >= 0) 4669 value_reg = &cur->regs[value_regno]; 4670 if ((value_reg && register_is_null(value_reg)) || 4671 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4672 writing_zero = true; 4673 4674 for (i = min_off; i < max_off; i++) { 4675 int spi; 4676 4677 spi = __get_spi(i); 4678 err = destroy_if_dynptr_stack_slot(env, state, spi); 4679 if (err) 4680 return err; 4681 } 4682 4683 /* Variable offset writes destroy any spilled pointers in range. */ 4684 for (i = min_off; i < max_off; i++) { 4685 u8 new_type, *stype; 4686 int slot, spi; 4687 4688 slot = -i - 1; 4689 spi = slot / BPF_REG_SIZE; 4690 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4691 mark_stack_slot_scratched(env, spi); 4692 4693 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4694 /* Reject the write if range we may write to has not 4695 * been initialized beforehand. If we didn't reject 4696 * here, the ptr status would be erased below (even 4697 * though not all slots are actually overwritten), 4698 * possibly opening the door to leaks. 4699 * 4700 * We do however catch STACK_INVALID case below, and 4701 * only allow reading possibly uninitialized memory 4702 * later for CAP_PERFMON, as the write may not happen to 4703 * that slot. 4704 */ 4705 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4706 insn_idx, i); 4707 return -EINVAL; 4708 } 4709 4710 /* If writing_zero and the spi slot contains a spill of value 0, 4711 * maintain the spill type. 4712 */ 4713 if (writing_zero && *stype == STACK_SPILL && 4714 is_spilled_scalar_reg(&state->stack[spi])) { 4715 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4716 4717 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4718 zero_used = true; 4719 continue; 4720 } 4721 } 4722 4723 /* Erase all other spilled pointers. */ 4724 state->stack[spi].spilled_ptr.type = NOT_INIT; 4725 4726 /* Update the slot type. */ 4727 new_type = STACK_MISC; 4728 if (writing_zero && *stype == STACK_ZERO) { 4729 new_type = STACK_ZERO; 4730 zero_used = true; 4731 } 4732 /* If the slot is STACK_INVALID, we check whether it's OK to 4733 * pretend that it will be initialized by this write. The slot 4734 * might not actually be written to, and so if we mark it as 4735 * initialized future reads might leak uninitialized memory. 4736 * For privileged programs, we will accept such reads to slots 4737 * that may or may not be written because, if we're reject 4738 * them, the error would be too confusing. 4739 */ 4740 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4741 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4742 insn_idx, i); 4743 return -EINVAL; 4744 } 4745 *stype = new_type; 4746 } 4747 if (zero_used) { 4748 /* backtracking doesn't work for STACK_ZERO yet. */ 4749 err = mark_chain_precision(env, value_regno); 4750 if (err) 4751 return err; 4752 } 4753 return 0; 4754 } 4755 4756 /* When register 'dst_regno' is assigned some values from stack[min_off, 4757 * max_off), we set the register's type according to the types of the 4758 * respective stack slots. If all the stack values are known to be zeros, then 4759 * so is the destination reg. Otherwise, the register is considered to be 4760 * SCALAR. This function does not deal with register filling; the caller must 4761 * ensure that all spilled registers in the stack range have been marked as 4762 * read. 4763 */ 4764 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4765 /* func where src register points to */ 4766 struct bpf_func_state *ptr_state, 4767 int min_off, int max_off, int dst_regno) 4768 { 4769 struct bpf_verifier_state *vstate = env->cur_state; 4770 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4771 int i, slot, spi; 4772 u8 *stype; 4773 int zeros = 0; 4774 4775 for (i = min_off; i < max_off; i++) { 4776 slot = -i - 1; 4777 spi = slot / BPF_REG_SIZE; 4778 mark_stack_slot_scratched(env, spi); 4779 stype = ptr_state->stack[spi].slot_type; 4780 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4781 break; 4782 zeros++; 4783 } 4784 if (zeros == max_off - min_off) { 4785 /* Any access_size read into register is zero extended, 4786 * so the whole register == const_zero. 4787 */ 4788 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4789 } else { 4790 /* have read misc data from the stack */ 4791 mark_reg_unknown(env, state->regs, dst_regno); 4792 } 4793 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4794 } 4795 4796 /* Read the stack at 'off' and put the results into the register indicated by 4797 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4798 * spilled reg. 4799 * 4800 * 'dst_regno' can be -1, meaning that the read value is not going to a 4801 * register. 4802 * 4803 * The access is assumed to be within the current stack bounds. 4804 */ 4805 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4806 /* func where src register points to */ 4807 struct bpf_func_state *reg_state, 4808 int off, int size, int dst_regno) 4809 { 4810 struct bpf_verifier_state *vstate = env->cur_state; 4811 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4812 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4813 struct bpf_reg_state *reg; 4814 u8 *stype, type; 4815 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4816 4817 stype = reg_state->stack[spi].slot_type; 4818 reg = ®_state->stack[spi].spilled_ptr; 4819 4820 mark_stack_slot_scratched(env, spi); 4821 4822 if (is_spilled_reg(®_state->stack[spi])) { 4823 u8 spill_size = 1; 4824 4825 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4826 spill_size++; 4827 4828 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4829 if (reg->type != SCALAR_VALUE) { 4830 verbose_linfo(env, env->insn_idx, "; "); 4831 verbose(env, "invalid size of register fill\n"); 4832 return -EACCES; 4833 } 4834 4835 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4836 if (dst_regno < 0) 4837 return 0; 4838 4839 if (size <= spill_size && 4840 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4841 /* The earlier check_reg_arg() has decided the 4842 * subreg_def for this insn. Save it first. 4843 */ 4844 s32 subreg_def = state->regs[dst_regno].subreg_def; 4845 4846 copy_register_state(&state->regs[dst_regno], reg); 4847 state->regs[dst_regno].subreg_def = subreg_def; 4848 4849 /* Break the relation on a narrowing fill. 4850 * coerce_reg_to_size will adjust the boundaries. 4851 */ 4852 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4853 state->regs[dst_regno].id = 0; 4854 } else { 4855 int spill_cnt = 0, zero_cnt = 0; 4856 4857 for (i = 0; i < size; i++) { 4858 type = stype[(slot - i) % BPF_REG_SIZE]; 4859 if (type == STACK_SPILL) { 4860 spill_cnt++; 4861 continue; 4862 } 4863 if (type == STACK_MISC) 4864 continue; 4865 if (type == STACK_ZERO) { 4866 zero_cnt++; 4867 continue; 4868 } 4869 if (type == STACK_INVALID && env->allow_uninit_stack) 4870 continue; 4871 verbose(env, "invalid read from stack off %d+%d size %d\n", 4872 off, i, size); 4873 return -EACCES; 4874 } 4875 4876 if (spill_cnt == size && 4877 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4878 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4879 /* this IS register fill, so keep insn_flags */ 4880 } else if (zero_cnt == size) { 4881 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4882 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4883 insn_flags = 0; /* not restoring original register state */ 4884 } else { 4885 mark_reg_unknown(env, state->regs, dst_regno); 4886 insn_flags = 0; /* not restoring original register state */ 4887 } 4888 } 4889 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4890 } else if (dst_regno >= 0) { 4891 /* restore register state from stack */ 4892 copy_register_state(&state->regs[dst_regno], reg); 4893 /* mark reg as written since spilled pointer state likely 4894 * has its liveness marks cleared by is_state_visited() 4895 * which resets stack/reg liveness for state transitions 4896 */ 4897 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4898 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4899 /* If dst_regno==-1, the caller is asking us whether 4900 * it is acceptable to use this value as a SCALAR_VALUE 4901 * (e.g. for XADD). 4902 * We must not allow unprivileged callers to do that 4903 * with spilled pointers. 4904 */ 4905 verbose(env, "leaking pointer from stack off %d\n", 4906 off); 4907 return -EACCES; 4908 } 4909 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4910 } else { 4911 for (i = 0; i < size; i++) { 4912 type = stype[(slot - i) % BPF_REG_SIZE]; 4913 if (type == STACK_MISC) 4914 continue; 4915 if (type == STACK_ZERO) 4916 continue; 4917 if (type == STACK_INVALID && env->allow_uninit_stack) 4918 continue; 4919 verbose(env, "invalid read from stack off %d+%d size %d\n", 4920 off, i, size); 4921 return -EACCES; 4922 } 4923 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4924 if (dst_regno >= 0) 4925 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4926 insn_flags = 0; /* we are not restoring spilled register */ 4927 } 4928 if (insn_flags) 4929 return push_jmp_history(env, env->cur_state, insn_flags); 4930 return 0; 4931 } 4932 4933 enum bpf_access_src { 4934 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4935 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4936 }; 4937 4938 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4939 int regno, int off, int access_size, 4940 bool zero_size_allowed, 4941 enum bpf_access_src type, 4942 struct bpf_call_arg_meta *meta); 4943 4944 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4945 { 4946 return cur_regs(env) + regno; 4947 } 4948 4949 /* Read the stack at 'ptr_regno + off' and put the result into the register 4950 * 'dst_regno'. 4951 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4952 * but not its variable offset. 4953 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4954 * 4955 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4956 * filling registers (i.e. reads of spilled register cannot be detected when 4957 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4958 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4959 * offset; for a fixed offset check_stack_read_fixed_off should be used 4960 * instead. 4961 */ 4962 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4963 int ptr_regno, int off, int size, int dst_regno) 4964 { 4965 /* The state of the source register. */ 4966 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4967 struct bpf_func_state *ptr_state = func(env, reg); 4968 int err; 4969 int min_off, max_off; 4970 4971 /* Note that we pass a NULL meta, so raw access will not be permitted. 4972 */ 4973 err = check_stack_range_initialized(env, ptr_regno, off, size, 4974 false, ACCESS_DIRECT, NULL); 4975 if (err) 4976 return err; 4977 4978 min_off = reg->smin_value + off; 4979 max_off = reg->smax_value + off; 4980 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4981 return 0; 4982 } 4983 4984 /* check_stack_read dispatches to check_stack_read_fixed_off or 4985 * check_stack_read_var_off. 4986 * 4987 * The caller must ensure that the offset falls within the allocated stack 4988 * bounds. 4989 * 4990 * 'dst_regno' is a register which will receive the value from the stack. It 4991 * can be -1, meaning that the read value is not going to a register. 4992 */ 4993 static int check_stack_read(struct bpf_verifier_env *env, 4994 int ptr_regno, int off, int size, 4995 int dst_regno) 4996 { 4997 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4998 struct bpf_func_state *state = func(env, reg); 4999 int err; 5000 /* Some accesses are only permitted with a static offset. */ 5001 bool var_off = !tnum_is_const(reg->var_off); 5002 5003 /* The offset is required to be static when reads don't go to a 5004 * register, in order to not leak pointers (see 5005 * check_stack_read_fixed_off). 5006 */ 5007 if (dst_regno < 0 && var_off) { 5008 char tn_buf[48]; 5009 5010 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5011 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5012 tn_buf, off, size); 5013 return -EACCES; 5014 } 5015 /* Variable offset is prohibited for unprivileged mode for simplicity 5016 * since it requires corresponding support in Spectre masking for stack 5017 * ALU. See also retrieve_ptr_limit(). The check in 5018 * check_stack_access_for_ptr_arithmetic() called by 5019 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5020 * with variable offsets, therefore no check is required here. Further, 5021 * just checking it here would be insufficient as speculative stack 5022 * writes could still lead to unsafe speculative behaviour. 5023 */ 5024 if (!var_off) { 5025 off += reg->var_off.value; 5026 err = check_stack_read_fixed_off(env, state, off, size, 5027 dst_regno); 5028 } else { 5029 /* Variable offset stack reads need more conservative handling 5030 * than fixed offset ones. Note that dst_regno >= 0 on this 5031 * branch. 5032 */ 5033 err = check_stack_read_var_off(env, ptr_regno, off, size, 5034 dst_regno); 5035 } 5036 return err; 5037 } 5038 5039 5040 /* check_stack_write dispatches to check_stack_write_fixed_off or 5041 * check_stack_write_var_off. 5042 * 5043 * 'ptr_regno' is the register used as a pointer into the stack. 5044 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5045 * 'value_regno' is the register whose value we're writing to the stack. It can 5046 * be -1, meaning that we're not writing from a register. 5047 * 5048 * The caller must ensure that the offset falls within the maximum stack size. 5049 */ 5050 static int check_stack_write(struct bpf_verifier_env *env, 5051 int ptr_regno, int off, int size, 5052 int value_regno, int insn_idx) 5053 { 5054 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5055 struct bpf_func_state *state = func(env, reg); 5056 int err; 5057 5058 if (tnum_is_const(reg->var_off)) { 5059 off += reg->var_off.value; 5060 err = check_stack_write_fixed_off(env, state, off, size, 5061 value_regno, insn_idx); 5062 } else { 5063 /* Variable offset stack reads need more conservative handling 5064 * than fixed offset ones. 5065 */ 5066 err = check_stack_write_var_off(env, state, 5067 ptr_regno, off, size, 5068 value_regno, insn_idx); 5069 } 5070 return err; 5071 } 5072 5073 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5074 int off, int size, enum bpf_access_type type) 5075 { 5076 struct bpf_reg_state *regs = cur_regs(env); 5077 struct bpf_map *map = regs[regno].map_ptr; 5078 u32 cap = bpf_map_flags_to_cap(map); 5079 5080 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5081 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5082 map->value_size, off, size); 5083 return -EACCES; 5084 } 5085 5086 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5087 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5088 map->value_size, off, size); 5089 return -EACCES; 5090 } 5091 5092 return 0; 5093 } 5094 5095 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5096 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5097 int off, int size, u32 mem_size, 5098 bool zero_size_allowed) 5099 { 5100 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5101 struct bpf_reg_state *reg; 5102 5103 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5104 return 0; 5105 5106 reg = &cur_regs(env)[regno]; 5107 switch (reg->type) { 5108 case PTR_TO_MAP_KEY: 5109 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5110 mem_size, off, size); 5111 break; 5112 case PTR_TO_MAP_VALUE: 5113 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5114 mem_size, off, size); 5115 break; 5116 case PTR_TO_PACKET: 5117 case PTR_TO_PACKET_META: 5118 case PTR_TO_PACKET_END: 5119 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5120 off, size, regno, reg->id, off, mem_size); 5121 break; 5122 case PTR_TO_MEM: 5123 default: 5124 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5125 mem_size, off, size); 5126 } 5127 5128 return -EACCES; 5129 } 5130 5131 /* check read/write into a memory region with possible variable offset */ 5132 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5133 int off, int size, u32 mem_size, 5134 bool zero_size_allowed) 5135 { 5136 struct bpf_verifier_state *vstate = env->cur_state; 5137 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5138 struct bpf_reg_state *reg = &state->regs[regno]; 5139 int err; 5140 5141 /* We may have adjusted the register pointing to memory region, so we 5142 * need to try adding each of min_value and max_value to off 5143 * to make sure our theoretical access will be safe. 5144 * 5145 * The minimum value is only important with signed 5146 * comparisons where we can't assume the floor of a 5147 * value is 0. If we are using signed variables for our 5148 * index'es we need to make sure that whatever we use 5149 * will have a set floor within our range. 5150 */ 5151 if (reg->smin_value < 0 && 5152 (reg->smin_value == S64_MIN || 5153 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5154 reg->smin_value + off < 0)) { 5155 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5156 regno); 5157 return -EACCES; 5158 } 5159 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5160 mem_size, zero_size_allowed); 5161 if (err) { 5162 verbose(env, "R%d min value is outside of the allowed memory range\n", 5163 regno); 5164 return err; 5165 } 5166 5167 /* If we haven't set a max value then we need to bail since we can't be 5168 * sure we won't do bad things. 5169 * If reg->umax_value + off could overflow, treat that as unbounded too. 5170 */ 5171 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5172 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5173 regno); 5174 return -EACCES; 5175 } 5176 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5177 mem_size, zero_size_allowed); 5178 if (err) { 5179 verbose(env, "R%d max value is outside of the allowed memory range\n", 5180 regno); 5181 return err; 5182 } 5183 5184 return 0; 5185 } 5186 5187 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5188 const struct bpf_reg_state *reg, int regno, 5189 bool fixed_off_ok) 5190 { 5191 /* Access to this pointer-typed register or passing it to a helper 5192 * is only allowed in its original, unmodified form. 5193 */ 5194 5195 if (reg->off < 0) { 5196 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5197 reg_type_str(env, reg->type), regno, reg->off); 5198 return -EACCES; 5199 } 5200 5201 if (!fixed_off_ok && reg->off) { 5202 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5203 reg_type_str(env, reg->type), regno, reg->off); 5204 return -EACCES; 5205 } 5206 5207 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5208 char tn_buf[48]; 5209 5210 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5211 verbose(env, "variable %s access var_off=%s disallowed\n", 5212 reg_type_str(env, reg->type), tn_buf); 5213 return -EACCES; 5214 } 5215 5216 return 0; 5217 } 5218 5219 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5220 const struct bpf_reg_state *reg, int regno) 5221 { 5222 return __check_ptr_off_reg(env, reg, regno, false); 5223 } 5224 5225 static int map_kptr_match_type(struct bpf_verifier_env *env, 5226 struct btf_field *kptr_field, 5227 struct bpf_reg_state *reg, u32 regno) 5228 { 5229 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5230 int perm_flags; 5231 const char *reg_name = ""; 5232 5233 if (btf_is_kernel(reg->btf)) { 5234 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5235 5236 /* Only unreferenced case accepts untrusted pointers */ 5237 if (kptr_field->type == BPF_KPTR_UNREF) 5238 perm_flags |= PTR_UNTRUSTED; 5239 } else { 5240 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5241 if (kptr_field->type == BPF_KPTR_PERCPU) 5242 perm_flags |= MEM_PERCPU; 5243 } 5244 5245 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5246 goto bad_type; 5247 5248 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5249 reg_name = btf_type_name(reg->btf, reg->btf_id); 5250 5251 /* For ref_ptr case, release function check should ensure we get one 5252 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5253 * normal store of unreferenced kptr, we must ensure var_off is zero. 5254 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5255 * reg->off and reg->ref_obj_id are not needed here. 5256 */ 5257 if (__check_ptr_off_reg(env, reg, regno, true)) 5258 return -EACCES; 5259 5260 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5261 * we also need to take into account the reg->off. 5262 * 5263 * We want to support cases like: 5264 * 5265 * struct foo { 5266 * struct bar br; 5267 * struct baz bz; 5268 * }; 5269 * 5270 * struct foo *v; 5271 * v = func(); // PTR_TO_BTF_ID 5272 * val->foo = v; // reg->off is zero, btf and btf_id match type 5273 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5274 * // first member type of struct after comparison fails 5275 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5276 * // to match type 5277 * 5278 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5279 * is zero. We must also ensure that btf_struct_ids_match does not walk 5280 * the struct to match type against first member of struct, i.e. reject 5281 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5282 * strict mode to true for type match. 5283 */ 5284 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5285 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5286 kptr_field->type != BPF_KPTR_UNREF)) 5287 goto bad_type; 5288 return 0; 5289 bad_type: 5290 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5291 reg_type_str(env, reg->type), reg_name); 5292 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5293 if (kptr_field->type == BPF_KPTR_UNREF) 5294 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5295 targ_name); 5296 else 5297 verbose(env, "\n"); 5298 return -EINVAL; 5299 } 5300 5301 static bool in_sleepable(struct bpf_verifier_env *env) 5302 { 5303 return env->prog->sleepable || 5304 (env->cur_state && env->cur_state->in_sleepable); 5305 } 5306 5307 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5308 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5309 */ 5310 static bool in_rcu_cs(struct bpf_verifier_env *env) 5311 { 5312 return env->cur_state->active_rcu_lock || 5313 env->cur_state->active_lock.ptr || 5314 !in_sleepable(env); 5315 } 5316 5317 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5318 BTF_SET_START(rcu_protected_types) 5319 BTF_ID(struct, prog_test_ref_kfunc) 5320 #ifdef CONFIG_CGROUPS 5321 BTF_ID(struct, cgroup) 5322 #endif 5323 #ifdef CONFIG_BPF_JIT 5324 BTF_ID(struct, bpf_cpumask) 5325 #endif 5326 BTF_ID(struct, task_struct) 5327 BTF_ID(struct, bpf_crypto_ctx) 5328 BTF_SET_END(rcu_protected_types) 5329 5330 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5331 { 5332 if (!btf_is_kernel(btf)) 5333 return true; 5334 return btf_id_set_contains(&rcu_protected_types, btf_id); 5335 } 5336 5337 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5338 { 5339 struct btf_struct_meta *meta; 5340 5341 if (btf_is_kernel(kptr_field->kptr.btf)) 5342 return NULL; 5343 5344 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5345 kptr_field->kptr.btf_id); 5346 5347 return meta ? meta->record : NULL; 5348 } 5349 5350 static bool rcu_safe_kptr(const struct btf_field *field) 5351 { 5352 const struct btf_field_kptr *kptr = &field->kptr; 5353 5354 return field->type == BPF_KPTR_PERCPU || 5355 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5356 } 5357 5358 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5359 { 5360 struct btf_record *rec; 5361 u32 ret; 5362 5363 ret = PTR_MAYBE_NULL; 5364 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5365 ret |= MEM_RCU; 5366 if (kptr_field->type == BPF_KPTR_PERCPU) 5367 ret |= MEM_PERCPU; 5368 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5369 ret |= MEM_ALLOC; 5370 5371 rec = kptr_pointee_btf_record(kptr_field); 5372 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5373 ret |= NON_OWN_REF; 5374 } else { 5375 ret |= PTR_UNTRUSTED; 5376 } 5377 5378 return ret; 5379 } 5380 5381 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5382 int value_regno, int insn_idx, 5383 struct btf_field *kptr_field) 5384 { 5385 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5386 int class = BPF_CLASS(insn->code); 5387 struct bpf_reg_state *val_reg; 5388 5389 /* Things we already checked for in check_map_access and caller: 5390 * - Reject cases where variable offset may touch kptr 5391 * - size of access (must be BPF_DW) 5392 * - tnum_is_const(reg->var_off) 5393 * - kptr_field->offset == off + reg->var_off.value 5394 */ 5395 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5396 if (BPF_MODE(insn->code) != BPF_MEM) { 5397 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5398 return -EACCES; 5399 } 5400 5401 /* We only allow loading referenced kptr, since it will be marked as 5402 * untrusted, similar to unreferenced kptr. 5403 */ 5404 if (class != BPF_LDX && 5405 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5406 verbose(env, "store to referenced kptr disallowed\n"); 5407 return -EACCES; 5408 } 5409 5410 if (class == BPF_LDX) { 5411 val_reg = reg_state(env, value_regno); 5412 /* We can simply mark the value_regno receiving the pointer 5413 * value from map as PTR_TO_BTF_ID, with the correct type. 5414 */ 5415 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5416 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5417 } else if (class == BPF_STX) { 5418 val_reg = reg_state(env, value_regno); 5419 if (!register_is_null(val_reg) && 5420 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5421 return -EACCES; 5422 } else if (class == BPF_ST) { 5423 if (insn->imm) { 5424 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5425 kptr_field->offset); 5426 return -EACCES; 5427 } 5428 } else { 5429 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5430 return -EACCES; 5431 } 5432 return 0; 5433 } 5434 5435 /* check read/write into a map element with possible variable offset */ 5436 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5437 int off, int size, bool zero_size_allowed, 5438 enum bpf_access_src src) 5439 { 5440 struct bpf_verifier_state *vstate = env->cur_state; 5441 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5442 struct bpf_reg_state *reg = &state->regs[regno]; 5443 struct bpf_map *map = reg->map_ptr; 5444 struct btf_record *rec; 5445 int err, i; 5446 5447 err = check_mem_region_access(env, regno, off, size, map->value_size, 5448 zero_size_allowed); 5449 if (err) 5450 return err; 5451 5452 if (IS_ERR_OR_NULL(map->record)) 5453 return 0; 5454 rec = map->record; 5455 for (i = 0; i < rec->cnt; i++) { 5456 struct btf_field *field = &rec->fields[i]; 5457 u32 p = field->offset; 5458 5459 /* If any part of a field can be touched by load/store, reject 5460 * this program. To check that [x1, x2) overlaps with [y1, y2), 5461 * it is sufficient to check x1 < y2 && y1 < x2. 5462 */ 5463 if (reg->smin_value + off < p + field->size && 5464 p < reg->umax_value + off + size) { 5465 switch (field->type) { 5466 case BPF_KPTR_UNREF: 5467 case BPF_KPTR_REF: 5468 case BPF_KPTR_PERCPU: 5469 if (src != ACCESS_DIRECT) { 5470 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5471 return -EACCES; 5472 } 5473 if (!tnum_is_const(reg->var_off)) { 5474 verbose(env, "kptr access cannot have variable offset\n"); 5475 return -EACCES; 5476 } 5477 if (p != off + reg->var_off.value) { 5478 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5479 p, off + reg->var_off.value); 5480 return -EACCES; 5481 } 5482 if (size != bpf_size_to_bytes(BPF_DW)) { 5483 verbose(env, "kptr access size must be BPF_DW\n"); 5484 return -EACCES; 5485 } 5486 break; 5487 default: 5488 verbose(env, "%s cannot be accessed directly by load/store\n", 5489 btf_field_type_name(field->type)); 5490 return -EACCES; 5491 } 5492 } 5493 } 5494 return 0; 5495 } 5496 5497 #define MAX_PACKET_OFF 0xffff 5498 5499 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5500 const struct bpf_call_arg_meta *meta, 5501 enum bpf_access_type t) 5502 { 5503 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5504 5505 switch (prog_type) { 5506 /* Program types only with direct read access go here! */ 5507 case BPF_PROG_TYPE_LWT_IN: 5508 case BPF_PROG_TYPE_LWT_OUT: 5509 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5510 case BPF_PROG_TYPE_SK_REUSEPORT: 5511 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5512 case BPF_PROG_TYPE_CGROUP_SKB: 5513 if (t == BPF_WRITE) 5514 return false; 5515 fallthrough; 5516 5517 /* Program types with direct read + write access go here! */ 5518 case BPF_PROG_TYPE_SCHED_CLS: 5519 case BPF_PROG_TYPE_SCHED_ACT: 5520 case BPF_PROG_TYPE_XDP: 5521 case BPF_PROG_TYPE_LWT_XMIT: 5522 case BPF_PROG_TYPE_SK_SKB: 5523 case BPF_PROG_TYPE_SK_MSG: 5524 if (meta) 5525 return meta->pkt_access; 5526 5527 env->seen_direct_write = true; 5528 return true; 5529 5530 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5531 if (t == BPF_WRITE) 5532 env->seen_direct_write = true; 5533 5534 return true; 5535 5536 default: 5537 return false; 5538 } 5539 } 5540 5541 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5542 int size, bool zero_size_allowed) 5543 { 5544 struct bpf_reg_state *regs = cur_regs(env); 5545 struct bpf_reg_state *reg = ®s[regno]; 5546 int err; 5547 5548 /* We may have added a variable offset to the packet pointer; but any 5549 * reg->range we have comes after that. We are only checking the fixed 5550 * offset. 5551 */ 5552 5553 /* We don't allow negative numbers, because we aren't tracking enough 5554 * detail to prove they're safe. 5555 */ 5556 if (reg->smin_value < 0) { 5557 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5558 regno); 5559 return -EACCES; 5560 } 5561 5562 err = reg->range < 0 ? -EINVAL : 5563 __check_mem_access(env, regno, off, size, reg->range, 5564 zero_size_allowed); 5565 if (err) { 5566 verbose(env, "R%d offset is outside of the packet\n", regno); 5567 return err; 5568 } 5569 5570 /* __check_mem_access has made sure "off + size - 1" is within u16. 5571 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5572 * otherwise find_good_pkt_pointers would have refused to set range info 5573 * that __check_mem_access would have rejected this pkt access. 5574 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5575 */ 5576 env->prog->aux->max_pkt_offset = 5577 max_t(u32, env->prog->aux->max_pkt_offset, 5578 off + reg->umax_value + size - 1); 5579 5580 return err; 5581 } 5582 5583 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5584 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5585 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5586 struct btf **btf, u32 *btf_id) 5587 { 5588 struct bpf_insn_access_aux info = { 5589 .reg_type = *reg_type, 5590 .log = &env->log, 5591 }; 5592 5593 if (env->ops->is_valid_access && 5594 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5595 /* A non zero info.ctx_field_size indicates that this field is a 5596 * candidate for later verifier transformation to load the whole 5597 * field and then apply a mask when accessed with a narrower 5598 * access than actual ctx access size. A zero info.ctx_field_size 5599 * will only allow for whole field access and rejects any other 5600 * type of narrower access. 5601 */ 5602 *reg_type = info.reg_type; 5603 5604 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5605 *btf = info.btf; 5606 *btf_id = info.btf_id; 5607 } else { 5608 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5609 } 5610 /* remember the offset of last byte accessed in ctx */ 5611 if (env->prog->aux->max_ctx_offset < off + size) 5612 env->prog->aux->max_ctx_offset = off + size; 5613 return 0; 5614 } 5615 5616 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5617 return -EACCES; 5618 } 5619 5620 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5621 int size) 5622 { 5623 if (size < 0 || off < 0 || 5624 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5625 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5626 off, size); 5627 return -EACCES; 5628 } 5629 return 0; 5630 } 5631 5632 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5633 u32 regno, int off, int size, 5634 enum bpf_access_type t) 5635 { 5636 struct bpf_reg_state *regs = cur_regs(env); 5637 struct bpf_reg_state *reg = ®s[regno]; 5638 struct bpf_insn_access_aux info = {}; 5639 bool valid; 5640 5641 if (reg->smin_value < 0) { 5642 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5643 regno); 5644 return -EACCES; 5645 } 5646 5647 switch (reg->type) { 5648 case PTR_TO_SOCK_COMMON: 5649 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5650 break; 5651 case PTR_TO_SOCKET: 5652 valid = bpf_sock_is_valid_access(off, size, t, &info); 5653 break; 5654 case PTR_TO_TCP_SOCK: 5655 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5656 break; 5657 case PTR_TO_XDP_SOCK: 5658 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5659 break; 5660 default: 5661 valid = false; 5662 } 5663 5664 5665 if (valid) { 5666 env->insn_aux_data[insn_idx].ctx_field_size = 5667 info.ctx_field_size; 5668 return 0; 5669 } 5670 5671 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5672 regno, reg_type_str(env, reg->type), off, size); 5673 5674 return -EACCES; 5675 } 5676 5677 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5678 { 5679 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5680 } 5681 5682 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5683 { 5684 const struct bpf_reg_state *reg = reg_state(env, regno); 5685 5686 return reg->type == PTR_TO_CTX; 5687 } 5688 5689 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5690 { 5691 const struct bpf_reg_state *reg = reg_state(env, regno); 5692 5693 return type_is_sk_pointer(reg->type); 5694 } 5695 5696 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5697 { 5698 const struct bpf_reg_state *reg = reg_state(env, regno); 5699 5700 return type_is_pkt_pointer(reg->type); 5701 } 5702 5703 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5704 { 5705 const struct bpf_reg_state *reg = reg_state(env, regno); 5706 5707 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5708 return reg->type == PTR_TO_FLOW_KEYS; 5709 } 5710 5711 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5712 { 5713 const struct bpf_reg_state *reg = reg_state(env, regno); 5714 5715 return reg->type == PTR_TO_ARENA; 5716 } 5717 5718 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5719 #ifdef CONFIG_NET 5720 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5721 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5722 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5723 #endif 5724 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5725 }; 5726 5727 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5728 { 5729 /* A referenced register is always trusted. */ 5730 if (reg->ref_obj_id) 5731 return true; 5732 5733 /* Types listed in the reg2btf_ids are always trusted */ 5734 if (reg2btf_ids[base_type(reg->type)] && 5735 !bpf_type_has_unsafe_modifiers(reg->type)) 5736 return true; 5737 5738 /* If a register is not referenced, it is trusted if it has the 5739 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5740 * other type modifiers may be safe, but we elect to take an opt-in 5741 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5742 * not. 5743 * 5744 * Eventually, we should make PTR_TRUSTED the single source of truth 5745 * for whether a register is trusted. 5746 */ 5747 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5748 !bpf_type_has_unsafe_modifiers(reg->type); 5749 } 5750 5751 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5752 { 5753 return reg->type & MEM_RCU; 5754 } 5755 5756 static void clear_trusted_flags(enum bpf_type_flag *flag) 5757 { 5758 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5759 } 5760 5761 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5762 const struct bpf_reg_state *reg, 5763 int off, int size, bool strict) 5764 { 5765 struct tnum reg_off; 5766 int ip_align; 5767 5768 /* Byte size accesses are always allowed. */ 5769 if (!strict || size == 1) 5770 return 0; 5771 5772 /* For platforms that do not have a Kconfig enabling 5773 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5774 * NET_IP_ALIGN is universally set to '2'. And on platforms 5775 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5776 * to this code only in strict mode where we want to emulate 5777 * the NET_IP_ALIGN==2 checking. Therefore use an 5778 * unconditional IP align value of '2'. 5779 */ 5780 ip_align = 2; 5781 5782 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5783 if (!tnum_is_aligned(reg_off, size)) { 5784 char tn_buf[48]; 5785 5786 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5787 verbose(env, 5788 "misaligned packet access off %d+%s+%d+%d size %d\n", 5789 ip_align, tn_buf, reg->off, off, size); 5790 return -EACCES; 5791 } 5792 5793 return 0; 5794 } 5795 5796 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5797 const struct bpf_reg_state *reg, 5798 const char *pointer_desc, 5799 int off, int size, bool strict) 5800 { 5801 struct tnum reg_off; 5802 5803 /* Byte size accesses are always allowed. */ 5804 if (!strict || size == 1) 5805 return 0; 5806 5807 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5808 if (!tnum_is_aligned(reg_off, size)) { 5809 char tn_buf[48]; 5810 5811 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5812 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5813 pointer_desc, tn_buf, reg->off, off, size); 5814 return -EACCES; 5815 } 5816 5817 return 0; 5818 } 5819 5820 static int check_ptr_alignment(struct bpf_verifier_env *env, 5821 const struct bpf_reg_state *reg, int off, 5822 int size, bool strict_alignment_once) 5823 { 5824 bool strict = env->strict_alignment || strict_alignment_once; 5825 const char *pointer_desc = ""; 5826 5827 switch (reg->type) { 5828 case PTR_TO_PACKET: 5829 case PTR_TO_PACKET_META: 5830 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5831 * right in front, treat it the very same way. 5832 */ 5833 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5834 case PTR_TO_FLOW_KEYS: 5835 pointer_desc = "flow keys "; 5836 break; 5837 case PTR_TO_MAP_KEY: 5838 pointer_desc = "key "; 5839 break; 5840 case PTR_TO_MAP_VALUE: 5841 pointer_desc = "value "; 5842 break; 5843 case PTR_TO_CTX: 5844 pointer_desc = "context "; 5845 break; 5846 case PTR_TO_STACK: 5847 pointer_desc = "stack "; 5848 /* The stack spill tracking logic in check_stack_write_fixed_off() 5849 * and check_stack_read_fixed_off() relies on stack accesses being 5850 * aligned. 5851 */ 5852 strict = true; 5853 break; 5854 case PTR_TO_SOCKET: 5855 pointer_desc = "sock "; 5856 break; 5857 case PTR_TO_SOCK_COMMON: 5858 pointer_desc = "sock_common "; 5859 break; 5860 case PTR_TO_TCP_SOCK: 5861 pointer_desc = "tcp_sock "; 5862 break; 5863 case PTR_TO_XDP_SOCK: 5864 pointer_desc = "xdp_sock "; 5865 break; 5866 case PTR_TO_ARENA: 5867 return 0; 5868 default: 5869 break; 5870 } 5871 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5872 strict); 5873 } 5874 5875 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5876 { 5877 if (env->prog->jit_requested) 5878 return round_up(stack_depth, 16); 5879 5880 /* round up to 32-bytes, since this is granularity 5881 * of interpreter stack size 5882 */ 5883 return round_up(max_t(u32, stack_depth, 1), 32); 5884 } 5885 5886 /* starting from main bpf function walk all instructions of the function 5887 * and recursively walk all callees that given function can call. 5888 * Ignore jump and exit insns. 5889 * Since recursion is prevented by check_cfg() this algorithm 5890 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5891 */ 5892 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5893 { 5894 struct bpf_subprog_info *subprog = env->subprog_info; 5895 struct bpf_insn *insn = env->prog->insnsi; 5896 int depth = 0, frame = 0, i, subprog_end; 5897 bool tail_call_reachable = false; 5898 int ret_insn[MAX_CALL_FRAMES]; 5899 int ret_prog[MAX_CALL_FRAMES]; 5900 int j; 5901 5902 i = subprog[idx].start; 5903 process_func: 5904 /* protect against potential stack overflow that might happen when 5905 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5906 * depth for such case down to 256 so that the worst case scenario 5907 * would result in 8k stack size (32 which is tailcall limit * 256 = 5908 * 8k). 5909 * 5910 * To get the idea what might happen, see an example: 5911 * func1 -> sub rsp, 128 5912 * subfunc1 -> sub rsp, 256 5913 * tailcall1 -> add rsp, 256 5914 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5915 * subfunc2 -> sub rsp, 64 5916 * subfunc22 -> sub rsp, 128 5917 * tailcall2 -> add rsp, 128 5918 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5919 * 5920 * tailcall will unwind the current stack frame but it will not get rid 5921 * of caller's stack as shown on the example above. 5922 */ 5923 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5924 verbose(env, 5925 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5926 depth); 5927 return -EACCES; 5928 } 5929 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 5930 if (depth > MAX_BPF_STACK) { 5931 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5932 frame + 1, depth); 5933 return -EACCES; 5934 } 5935 continue_func: 5936 subprog_end = subprog[idx + 1].start; 5937 for (; i < subprog_end; i++) { 5938 int next_insn, sidx; 5939 5940 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5941 bool err = false; 5942 5943 if (!is_bpf_throw_kfunc(insn + i)) 5944 continue; 5945 if (subprog[idx].is_cb) 5946 err = true; 5947 for (int c = 0; c < frame && !err; c++) { 5948 if (subprog[ret_prog[c]].is_cb) { 5949 err = true; 5950 break; 5951 } 5952 } 5953 if (!err) 5954 continue; 5955 verbose(env, 5956 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5957 i, idx); 5958 return -EINVAL; 5959 } 5960 5961 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5962 continue; 5963 /* remember insn and function to return to */ 5964 ret_insn[frame] = i + 1; 5965 ret_prog[frame] = idx; 5966 5967 /* find the callee */ 5968 next_insn = i + insn[i].imm + 1; 5969 sidx = find_subprog(env, next_insn); 5970 if (sidx < 0) { 5971 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5972 next_insn); 5973 return -EFAULT; 5974 } 5975 if (subprog[sidx].is_async_cb) { 5976 if (subprog[sidx].has_tail_call) { 5977 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5978 return -EFAULT; 5979 } 5980 /* async callbacks don't increase bpf prog stack size unless called directly */ 5981 if (!bpf_pseudo_call(insn + i)) 5982 continue; 5983 if (subprog[sidx].is_exception_cb) { 5984 verbose(env, "insn %d cannot call exception cb directly\n", i); 5985 return -EINVAL; 5986 } 5987 } 5988 i = next_insn; 5989 idx = sidx; 5990 5991 if (subprog[idx].has_tail_call) 5992 tail_call_reachable = true; 5993 5994 frame++; 5995 if (frame >= MAX_CALL_FRAMES) { 5996 verbose(env, "the call stack of %d frames is too deep !\n", 5997 frame); 5998 return -E2BIG; 5999 } 6000 goto process_func; 6001 } 6002 /* if tail call got detected across bpf2bpf calls then mark each of the 6003 * currently present subprog frames as tail call reachable subprogs; 6004 * this info will be utilized by JIT so that we will be preserving the 6005 * tail call counter throughout bpf2bpf calls combined with tailcalls 6006 */ 6007 if (tail_call_reachable) 6008 for (j = 0; j < frame; j++) { 6009 if (subprog[ret_prog[j]].is_exception_cb) { 6010 verbose(env, "cannot tail call within exception cb\n"); 6011 return -EINVAL; 6012 } 6013 subprog[ret_prog[j]].tail_call_reachable = true; 6014 } 6015 if (subprog[0].tail_call_reachable) 6016 env->prog->aux->tail_call_reachable = true; 6017 6018 /* end of for() loop means the last insn of the 'subprog' 6019 * was reached. Doesn't matter whether it was JA or EXIT 6020 */ 6021 if (frame == 0) 6022 return 0; 6023 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6024 frame--; 6025 i = ret_insn[frame]; 6026 idx = ret_prog[frame]; 6027 goto continue_func; 6028 } 6029 6030 static int check_max_stack_depth(struct bpf_verifier_env *env) 6031 { 6032 struct bpf_subprog_info *si = env->subprog_info; 6033 int ret; 6034 6035 for (int i = 0; i < env->subprog_cnt; i++) { 6036 if (!i || si[i].is_async_cb) { 6037 ret = check_max_stack_depth_subprog(env, i); 6038 if (ret < 0) 6039 return ret; 6040 } 6041 continue; 6042 } 6043 return 0; 6044 } 6045 6046 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6047 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6048 const struct bpf_insn *insn, int idx) 6049 { 6050 int start = idx + insn->imm + 1, subprog; 6051 6052 subprog = find_subprog(env, start); 6053 if (subprog < 0) { 6054 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6055 start); 6056 return -EFAULT; 6057 } 6058 return env->subprog_info[subprog].stack_depth; 6059 } 6060 #endif 6061 6062 static int __check_buffer_access(struct bpf_verifier_env *env, 6063 const char *buf_info, 6064 const struct bpf_reg_state *reg, 6065 int regno, int off, int size) 6066 { 6067 if (off < 0) { 6068 verbose(env, 6069 "R%d invalid %s buffer access: off=%d, size=%d\n", 6070 regno, buf_info, off, size); 6071 return -EACCES; 6072 } 6073 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6074 char tn_buf[48]; 6075 6076 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6077 verbose(env, 6078 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6079 regno, off, tn_buf); 6080 return -EACCES; 6081 } 6082 6083 return 0; 6084 } 6085 6086 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6087 const struct bpf_reg_state *reg, 6088 int regno, int off, int size) 6089 { 6090 int err; 6091 6092 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6093 if (err) 6094 return err; 6095 6096 if (off + size > env->prog->aux->max_tp_access) 6097 env->prog->aux->max_tp_access = off + size; 6098 6099 return 0; 6100 } 6101 6102 static int check_buffer_access(struct bpf_verifier_env *env, 6103 const struct bpf_reg_state *reg, 6104 int regno, int off, int size, 6105 bool zero_size_allowed, 6106 u32 *max_access) 6107 { 6108 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6109 int err; 6110 6111 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6112 if (err) 6113 return err; 6114 6115 if (off + size > *max_access) 6116 *max_access = off + size; 6117 6118 return 0; 6119 } 6120 6121 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6122 static void zext_32_to_64(struct bpf_reg_state *reg) 6123 { 6124 reg->var_off = tnum_subreg(reg->var_off); 6125 __reg_assign_32_into_64(reg); 6126 } 6127 6128 /* truncate register to smaller size (in bytes) 6129 * must be called with size < BPF_REG_SIZE 6130 */ 6131 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6132 { 6133 u64 mask; 6134 6135 /* clear high bits in bit representation */ 6136 reg->var_off = tnum_cast(reg->var_off, size); 6137 6138 /* fix arithmetic bounds */ 6139 mask = ((u64)1 << (size * 8)) - 1; 6140 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6141 reg->umin_value &= mask; 6142 reg->umax_value &= mask; 6143 } else { 6144 reg->umin_value = 0; 6145 reg->umax_value = mask; 6146 } 6147 reg->smin_value = reg->umin_value; 6148 reg->smax_value = reg->umax_value; 6149 6150 /* If size is smaller than 32bit register the 32bit register 6151 * values are also truncated so we push 64-bit bounds into 6152 * 32-bit bounds. Above were truncated < 32-bits already. 6153 */ 6154 if (size < 4) 6155 __mark_reg32_unbounded(reg); 6156 6157 reg_bounds_sync(reg); 6158 } 6159 6160 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6161 { 6162 if (size == 1) { 6163 reg->smin_value = reg->s32_min_value = S8_MIN; 6164 reg->smax_value = reg->s32_max_value = S8_MAX; 6165 } else if (size == 2) { 6166 reg->smin_value = reg->s32_min_value = S16_MIN; 6167 reg->smax_value = reg->s32_max_value = S16_MAX; 6168 } else { 6169 /* size == 4 */ 6170 reg->smin_value = reg->s32_min_value = S32_MIN; 6171 reg->smax_value = reg->s32_max_value = S32_MAX; 6172 } 6173 reg->umin_value = reg->u32_min_value = 0; 6174 reg->umax_value = U64_MAX; 6175 reg->u32_max_value = U32_MAX; 6176 reg->var_off = tnum_unknown; 6177 } 6178 6179 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6180 { 6181 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6182 u64 top_smax_value, top_smin_value; 6183 u64 num_bits = size * 8; 6184 6185 if (tnum_is_const(reg->var_off)) { 6186 u64_cval = reg->var_off.value; 6187 if (size == 1) 6188 reg->var_off = tnum_const((s8)u64_cval); 6189 else if (size == 2) 6190 reg->var_off = tnum_const((s16)u64_cval); 6191 else 6192 /* size == 4 */ 6193 reg->var_off = tnum_const((s32)u64_cval); 6194 6195 u64_cval = reg->var_off.value; 6196 reg->smax_value = reg->smin_value = u64_cval; 6197 reg->umax_value = reg->umin_value = u64_cval; 6198 reg->s32_max_value = reg->s32_min_value = u64_cval; 6199 reg->u32_max_value = reg->u32_min_value = u64_cval; 6200 return; 6201 } 6202 6203 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6204 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6205 6206 if (top_smax_value != top_smin_value) 6207 goto out; 6208 6209 /* find the s64_min and s64_min after sign extension */ 6210 if (size == 1) { 6211 init_s64_max = (s8)reg->smax_value; 6212 init_s64_min = (s8)reg->smin_value; 6213 } else if (size == 2) { 6214 init_s64_max = (s16)reg->smax_value; 6215 init_s64_min = (s16)reg->smin_value; 6216 } else { 6217 init_s64_max = (s32)reg->smax_value; 6218 init_s64_min = (s32)reg->smin_value; 6219 } 6220 6221 s64_max = max(init_s64_max, init_s64_min); 6222 s64_min = min(init_s64_max, init_s64_min); 6223 6224 /* both of s64_max/s64_min positive or negative */ 6225 if ((s64_max >= 0) == (s64_min >= 0)) { 6226 reg->smin_value = reg->s32_min_value = s64_min; 6227 reg->smax_value = reg->s32_max_value = s64_max; 6228 reg->umin_value = reg->u32_min_value = s64_min; 6229 reg->umax_value = reg->u32_max_value = s64_max; 6230 reg->var_off = tnum_range(s64_min, s64_max); 6231 return; 6232 } 6233 6234 out: 6235 set_sext64_default_val(reg, size); 6236 } 6237 6238 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6239 { 6240 if (size == 1) { 6241 reg->s32_min_value = S8_MIN; 6242 reg->s32_max_value = S8_MAX; 6243 } else { 6244 /* size == 2 */ 6245 reg->s32_min_value = S16_MIN; 6246 reg->s32_max_value = S16_MAX; 6247 } 6248 reg->u32_min_value = 0; 6249 reg->u32_max_value = U32_MAX; 6250 } 6251 6252 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6253 { 6254 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6255 u32 top_smax_value, top_smin_value; 6256 u32 num_bits = size * 8; 6257 6258 if (tnum_is_const(reg->var_off)) { 6259 u32_val = reg->var_off.value; 6260 if (size == 1) 6261 reg->var_off = tnum_const((s8)u32_val); 6262 else 6263 reg->var_off = tnum_const((s16)u32_val); 6264 6265 u32_val = reg->var_off.value; 6266 reg->s32_min_value = reg->s32_max_value = u32_val; 6267 reg->u32_min_value = reg->u32_max_value = u32_val; 6268 return; 6269 } 6270 6271 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6272 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6273 6274 if (top_smax_value != top_smin_value) 6275 goto out; 6276 6277 /* find the s32_min and s32_min after sign extension */ 6278 if (size == 1) { 6279 init_s32_max = (s8)reg->s32_max_value; 6280 init_s32_min = (s8)reg->s32_min_value; 6281 } else { 6282 /* size == 2 */ 6283 init_s32_max = (s16)reg->s32_max_value; 6284 init_s32_min = (s16)reg->s32_min_value; 6285 } 6286 s32_max = max(init_s32_max, init_s32_min); 6287 s32_min = min(init_s32_max, init_s32_min); 6288 6289 if ((s32_min >= 0) == (s32_max >= 0)) { 6290 reg->s32_min_value = s32_min; 6291 reg->s32_max_value = s32_max; 6292 reg->u32_min_value = (u32)s32_min; 6293 reg->u32_max_value = (u32)s32_max; 6294 return; 6295 } 6296 6297 out: 6298 set_sext32_default_val(reg, size); 6299 } 6300 6301 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6302 { 6303 /* A map is considered read-only if the following condition are true: 6304 * 6305 * 1) BPF program side cannot change any of the map content. The 6306 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6307 * and was set at map creation time. 6308 * 2) The map value(s) have been initialized from user space by a 6309 * loader and then "frozen", such that no new map update/delete 6310 * operations from syscall side are possible for the rest of 6311 * the map's lifetime from that point onwards. 6312 * 3) Any parallel/pending map update/delete operations from syscall 6313 * side have been completed. Only after that point, it's safe to 6314 * assume that map value(s) are immutable. 6315 */ 6316 return (map->map_flags & BPF_F_RDONLY_PROG) && 6317 READ_ONCE(map->frozen) && 6318 !bpf_map_write_active(map); 6319 } 6320 6321 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6322 bool is_ldsx) 6323 { 6324 void *ptr; 6325 u64 addr; 6326 int err; 6327 6328 err = map->ops->map_direct_value_addr(map, &addr, off); 6329 if (err) 6330 return err; 6331 ptr = (void *)(long)addr + off; 6332 6333 switch (size) { 6334 case sizeof(u8): 6335 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6336 break; 6337 case sizeof(u16): 6338 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6339 break; 6340 case sizeof(u32): 6341 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6342 break; 6343 case sizeof(u64): 6344 *val = *(u64 *)ptr; 6345 break; 6346 default: 6347 return -EINVAL; 6348 } 6349 return 0; 6350 } 6351 6352 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6353 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6354 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6355 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6356 6357 /* 6358 * Allow list few fields as RCU trusted or full trusted. 6359 * This logic doesn't allow mix tagging and will be removed once GCC supports 6360 * btf_type_tag. 6361 */ 6362 6363 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6364 BTF_TYPE_SAFE_RCU(struct task_struct) { 6365 const cpumask_t *cpus_ptr; 6366 struct css_set __rcu *cgroups; 6367 struct task_struct __rcu *real_parent; 6368 struct task_struct *group_leader; 6369 }; 6370 6371 BTF_TYPE_SAFE_RCU(struct cgroup) { 6372 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6373 struct kernfs_node *kn; 6374 }; 6375 6376 BTF_TYPE_SAFE_RCU(struct css_set) { 6377 struct cgroup *dfl_cgrp; 6378 }; 6379 6380 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6381 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6382 struct file __rcu *exe_file; 6383 }; 6384 6385 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6386 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6387 */ 6388 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6389 struct sock *sk; 6390 }; 6391 6392 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6393 struct sock *sk; 6394 }; 6395 6396 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6397 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6398 struct seq_file *seq; 6399 }; 6400 6401 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6402 struct bpf_iter_meta *meta; 6403 struct task_struct *task; 6404 }; 6405 6406 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6407 struct file *file; 6408 }; 6409 6410 BTF_TYPE_SAFE_TRUSTED(struct file) { 6411 struct inode *f_inode; 6412 }; 6413 6414 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6415 /* no negative dentry-s in places where bpf can see it */ 6416 struct inode *d_inode; 6417 }; 6418 6419 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 6420 struct sock *sk; 6421 }; 6422 6423 static bool type_is_rcu(struct bpf_verifier_env *env, 6424 struct bpf_reg_state *reg, 6425 const char *field_name, u32 btf_id) 6426 { 6427 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6428 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6429 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6430 6431 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6432 } 6433 6434 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6435 struct bpf_reg_state *reg, 6436 const char *field_name, u32 btf_id) 6437 { 6438 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6439 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6440 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6441 6442 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6443 } 6444 6445 static bool type_is_trusted(struct bpf_verifier_env *env, 6446 struct bpf_reg_state *reg, 6447 const char *field_name, u32 btf_id) 6448 { 6449 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6450 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6451 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6452 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6453 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6454 6455 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6456 } 6457 6458 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 6459 struct bpf_reg_state *reg, 6460 const char *field_name, u32 btf_id) 6461 { 6462 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 6463 6464 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 6465 "__safe_trusted_or_null"); 6466 } 6467 6468 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6469 struct bpf_reg_state *regs, 6470 int regno, int off, int size, 6471 enum bpf_access_type atype, 6472 int value_regno) 6473 { 6474 struct bpf_reg_state *reg = regs + regno; 6475 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6476 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6477 const char *field_name = NULL; 6478 enum bpf_type_flag flag = 0; 6479 u32 btf_id = 0; 6480 int ret; 6481 6482 if (!env->allow_ptr_leaks) { 6483 verbose(env, 6484 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6485 tname); 6486 return -EPERM; 6487 } 6488 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6489 verbose(env, 6490 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6491 tname); 6492 return -EINVAL; 6493 } 6494 if (off < 0) { 6495 verbose(env, 6496 "R%d is ptr_%s invalid negative access: off=%d\n", 6497 regno, tname, off); 6498 return -EACCES; 6499 } 6500 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6501 char tn_buf[48]; 6502 6503 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6504 verbose(env, 6505 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6506 regno, tname, off, tn_buf); 6507 return -EACCES; 6508 } 6509 6510 if (reg->type & MEM_USER) { 6511 verbose(env, 6512 "R%d is ptr_%s access user memory: off=%d\n", 6513 regno, tname, off); 6514 return -EACCES; 6515 } 6516 6517 if (reg->type & MEM_PERCPU) { 6518 verbose(env, 6519 "R%d is ptr_%s access percpu memory: off=%d\n", 6520 regno, tname, off); 6521 return -EACCES; 6522 } 6523 6524 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6525 if (!btf_is_kernel(reg->btf)) { 6526 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6527 return -EFAULT; 6528 } 6529 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6530 } else { 6531 /* Writes are permitted with default btf_struct_access for 6532 * program allocated objects (which always have ref_obj_id > 0), 6533 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6534 */ 6535 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6536 verbose(env, "only read is supported\n"); 6537 return -EACCES; 6538 } 6539 6540 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6541 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6542 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6543 return -EFAULT; 6544 } 6545 6546 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6547 } 6548 6549 if (ret < 0) 6550 return ret; 6551 6552 if (ret != PTR_TO_BTF_ID) { 6553 /* just mark; */ 6554 6555 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6556 /* If this is an untrusted pointer, all pointers formed by walking it 6557 * also inherit the untrusted flag. 6558 */ 6559 flag = PTR_UNTRUSTED; 6560 6561 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6562 /* By default any pointer obtained from walking a trusted pointer is no 6563 * longer trusted, unless the field being accessed has explicitly been 6564 * marked as inheriting its parent's state of trust (either full or RCU). 6565 * For example: 6566 * 'cgroups' pointer is untrusted if task->cgroups dereference 6567 * happened in a sleepable program outside of bpf_rcu_read_lock() 6568 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6569 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6570 * 6571 * A regular RCU-protected pointer with __rcu tag can also be deemed 6572 * trusted if we are in an RCU CS. Such pointer can be NULL. 6573 */ 6574 if (type_is_trusted(env, reg, field_name, btf_id)) { 6575 flag |= PTR_TRUSTED; 6576 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6577 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6578 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6579 if (type_is_rcu(env, reg, field_name, btf_id)) { 6580 /* ignore __rcu tag and mark it MEM_RCU */ 6581 flag |= MEM_RCU; 6582 } else if (flag & MEM_RCU || 6583 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6584 /* __rcu tagged pointers can be NULL */ 6585 flag |= MEM_RCU | PTR_MAYBE_NULL; 6586 6587 /* We always trust them */ 6588 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6589 flag & PTR_UNTRUSTED) 6590 flag &= ~PTR_UNTRUSTED; 6591 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6592 /* keep as-is */ 6593 } else { 6594 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6595 clear_trusted_flags(&flag); 6596 } 6597 } else { 6598 /* 6599 * If not in RCU CS or MEM_RCU pointer can be NULL then 6600 * aggressively mark as untrusted otherwise such 6601 * pointers will be plain PTR_TO_BTF_ID without flags 6602 * and will be allowed to be passed into helpers for 6603 * compat reasons. 6604 */ 6605 flag = PTR_UNTRUSTED; 6606 } 6607 } else { 6608 /* Old compat. Deprecated */ 6609 clear_trusted_flags(&flag); 6610 } 6611 6612 if (atype == BPF_READ && value_regno >= 0) 6613 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6614 6615 return 0; 6616 } 6617 6618 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6619 struct bpf_reg_state *regs, 6620 int regno, int off, int size, 6621 enum bpf_access_type atype, 6622 int value_regno) 6623 { 6624 struct bpf_reg_state *reg = regs + regno; 6625 struct bpf_map *map = reg->map_ptr; 6626 struct bpf_reg_state map_reg; 6627 enum bpf_type_flag flag = 0; 6628 const struct btf_type *t; 6629 const char *tname; 6630 u32 btf_id; 6631 int ret; 6632 6633 if (!btf_vmlinux) { 6634 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6635 return -ENOTSUPP; 6636 } 6637 6638 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6639 verbose(env, "map_ptr access not supported for map type %d\n", 6640 map->map_type); 6641 return -ENOTSUPP; 6642 } 6643 6644 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6645 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6646 6647 if (!env->allow_ptr_leaks) { 6648 verbose(env, 6649 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6650 tname); 6651 return -EPERM; 6652 } 6653 6654 if (off < 0) { 6655 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6656 regno, tname, off); 6657 return -EACCES; 6658 } 6659 6660 if (atype != BPF_READ) { 6661 verbose(env, "only read from %s is supported\n", tname); 6662 return -EACCES; 6663 } 6664 6665 /* Simulate access to a PTR_TO_BTF_ID */ 6666 memset(&map_reg, 0, sizeof(map_reg)); 6667 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6668 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6669 if (ret < 0) 6670 return ret; 6671 6672 if (value_regno >= 0) 6673 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6674 6675 return 0; 6676 } 6677 6678 /* Check that the stack access at the given offset is within bounds. The 6679 * maximum valid offset is -1. 6680 * 6681 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6682 * -state->allocated_stack for reads. 6683 */ 6684 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6685 s64 off, 6686 struct bpf_func_state *state, 6687 enum bpf_access_type t) 6688 { 6689 int min_valid_off; 6690 6691 if (t == BPF_WRITE || env->allow_uninit_stack) 6692 min_valid_off = -MAX_BPF_STACK; 6693 else 6694 min_valid_off = -state->allocated_stack; 6695 6696 if (off < min_valid_off || off > -1) 6697 return -EACCES; 6698 return 0; 6699 } 6700 6701 /* Check that the stack access at 'regno + off' falls within the maximum stack 6702 * bounds. 6703 * 6704 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6705 */ 6706 static int check_stack_access_within_bounds( 6707 struct bpf_verifier_env *env, 6708 int regno, int off, int access_size, 6709 enum bpf_access_src src, enum bpf_access_type type) 6710 { 6711 struct bpf_reg_state *regs = cur_regs(env); 6712 struct bpf_reg_state *reg = regs + regno; 6713 struct bpf_func_state *state = func(env, reg); 6714 s64 min_off, max_off; 6715 int err; 6716 char *err_extra; 6717 6718 if (src == ACCESS_HELPER) 6719 /* We don't know if helpers are reading or writing (or both). */ 6720 err_extra = " indirect access to"; 6721 else if (type == BPF_READ) 6722 err_extra = " read from"; 6723 else 6724 err_extra = " write to"; 6725 6726 if (tnum_is_const(reg->var_off)) { 6727 min_off = (s64)reg->var_off.value + off; 6728 max_off = min_off + access_size; 6729 } else { 6730 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6731 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6732 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6733 err_extra, regno); 6734 return -EACCES; 6735 } 6736 min_off = reg->smin_value + off; 6737 max_off = reg->smax_value + off + access_size; 6738 } 6739 6740 err = check_stack_slot_within_bounds(env, min_off, state, type); 6741 if (!err && max_off > 0) 6742 err = -EINVAL; /* out of stack access into non-negative offsets */ 6743 if (!err && access_size < 0) 6744 /* access_size should not be negative (or overflow an int); others checks 6745 * along the way should have prevented such an access. 6746 */ 6747 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6748 6749 if (err) { 6750 if (tnum_is_const(reg->var_off)) { 6751 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6752 err_extra, regno, off, access_size); 6753 } else { 6754 char tn_buf[48]; 6755 6756 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6757 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6758 err_extra, regno, tn_buf, off, access_size); 6759 } 6760 return err; 6761 } 6762 6763 /* Note that there is no stack access with offset zero, so the needed stack 6764 * size is -min_off, not -min_off+1. 6765 */ 6766 return grow_stack_state(env, state, -min_off /* size */); 6767 } 6768 6769 /* check whether memory at (regno + off) is accessible for t = (read | write) 6770 * if t==write, value_regno is a register which value is stored into memory 6771 * if t==read, value_regno is a register which will receive the value from memory 6772 * if t==write && value_regno==-1, some unknown value is stored into memory 6773 * if t==read && value_regno==-1, don't care what we read from memory 6774 */ 6775 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6776 int off, int bpf_size, enum bpf_access_type t, 6777 int value_regno, bool strict_alignment_once, bool is_ldsx) 6778 { 6779 struct bpf_reg_state *regs = cur_regs(env); 6780 struct bpf_reg_state *reg = regs + regno; 6781 int size, err = 0; 6782 6783 size = bpf_size_to_bytes(bpf_size); 6784 if (size < 0) 6785 return size; 6786 6787 /* alignment checks will add in reg->off themselves */ 6788 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6789 if (err) 6790 return err; 6791 6792 /* for access checks, reg->off is just part of off */ 6793 off += reg->off; 6794 6795 if (reg->type == PTR_TO_MAP_KEY) { 6796 if (t == BPF_WRITE) { 6797 verbose(env, "write to change key R%d not allowed\n", regno); 6798 return -EACCES; 6799 } 6800 6801 err = check_mem_region_access(env, regno, off, size, 6802 reg->map_ptr->key_size, false); 6803 if (err) 6804 return err; 6805 if (value_regno >= 0) 6806 mark_reg_unknown(env, regs, value_regno); 6807 } else if (reg->type == PTR_TO_MAP_VALUE) { 6808 struct btf_field *kptr_field = NULL; 6809 6810 if (t == BPF_WRITE && value_regno >= 0 && 6811 is_pointer_value(env, value_regno)) { 6812 verbose(env, "R%d leaks addr into map\n", value_regno); 6813 return -EACCES; 6814 } 6815 err = check_map_access_type(env, regno, off, size, t); 6816 if (err) 6817 return err; 6818 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6819 if (err) 6820 return err; 6821 if (tnum_is_const(reg->var_off)) 6822 kptr_field = btf_record_find(reg->map_ptr->record, 6823 off + reg->var_off.value, BPF_KPTR); 6824 if (kptr_field) { 6825 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6826 } else if (t == BPF_READ && value_regno >= 0) { 6827 struct bpf_map *map = reg->map_ptr; 6828 6829 /* if map is read-only, track its contents as scalars */ 6830 if (tnum_is_const(reg->var_off) && 6831 bpf_map_is_rdonly(map) && 6832 map->ops->map_direct_value_addr) { 6833 int map_off = off + reg->var_off.value; 6834 u64 val = 0; 6835 6836 err = bpf_map_direct_read(map, map_off, size, 6837 &val, is_ldsx); 6838 if (err) 6839 return err; 6840 6841 regs[value_regno].type = SCALAR_VALUE; 6842 __mark_reg_known(®s[value_regno], val); 6843 } else { 6844 mark_reg_unknown(env, regs, value_regno); 6845 } 6846 } 6847 } else if (base_type(reg->type) == PTR_TO_MEM) { 6848 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6849 6850 if (type_may_be_null(reg->type)) { 6851 verbose(env, "R%d invalid mem access '%s'\n", regno, 6852 reg_type_str(env, reg->type)); 6853 return -EACCES; 6854 } 6855 6856 if (t == BPF_WRITE && rdonly_mem) { 6857 verbose(env, "R%d cannot write into %s\n", 6858 regno, reg_type_str(env, reg->type)); 6859 return -EACCES; 6860 } 6861 6862 if (t == BPF_WRITE && value_regno >= 0 && 6863 is_pointer_value(env, value_regno)) { 6864 verbose(env, "R%d leaks addr into mem\n", value_regno); 6865 return -EACCES; 6866 } 6867 6868 err = check_mem_region_access(env, regno, off, size, 6869 reg->mem_size, false); 6870 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6871 mark_reg_unknown(env, regs, value_regno); 6872 } else if (reg->type == PTR_TO_CTX) { 6873 enum bpf_reg_type reg_type = SCALAR_VALUE; 6874 struct btf *btf = NULL; 6875 u32 btf_id = 0; 6876 6877 if (t == BPF_WRITE && value_regno >= 0 && 6878 is_pointer_value(env, value_regno)) { 6879 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6880 return -EACCES; 6881 } 6882 6883 err = check_ptr_off_reg(env, reg, regno); 6884 if (err < 0) 6885 return err; 6886 6887 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6888 &btf_id); 6889 if (err) 6890 verbose_linfo(env, insn_idx, "; "); 6891 if (!err && t == BPF_READ && value_regno >= 0) { 6892 /* ctx access returns either a scalar, or a 6893 * PTR_TO_PACKET[_META,_END]. In the latter 6894 * case, we know the offset is zero. 6895 */ 6896 if (reg_type == SCALAR_VALUE) { 6897 mark_reg_unknown(env, regs, value_regno); 6898 } else { 6899 mark_reg_known_zero(env, regs, 6900 value_regno); 6901 if (type_may_be_null(reg_type)) 6902 regs[value_regno].id = ++env->id_gen; 6903 /* A load of ctx field could have different 6904 * actual load size with the one encoded in the 6905 * insn. When the dst is PTR, it is for sure not 6906 * a sub-register. 6907 */ 6908 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6909 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6910 regs[value_regno].btf = btf; 6911 regs[value_regno].btf_id = btf_id; 6912 } 6913 } 6914 regs[value_regno].type = reg_type; 6915 } 6916 6917 } else if (reg->type == PTR_TO_STACK) { 6918 /* Basic bounds checks. */ 6919 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6920 if (err) 6921 return err; 6922 6923 if (t == BPF_READ) 6924 err = check_stack_read(env, regno, off, size, 6925 value_regno); 6926 else 6927 err = check_stack_write(env, regno, off, size, 6928 value_regno, insn_idx); 6929 } else if (reg_is_pkt_pointer(reg)) { 6930 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6931 verbose(env, "cannot write into packet\n"); 6932 return -EACCES; 6933 } 6934 if (t == BPF_WRITE && value_regno >= 0 && 6935 is_pointer_value(env, value_regno)) { 6936 verbose(env, "R%d leaks addr into packet\n", 6937 value_regno); 6938 return -EACCES; 6939 } 6940 err = check_packet_access(env, regno, off, size, false); 6941 if (!err && t == BPF_READ && value_regno >= 0) 6942 mark_reg_unknown(env, regs, value_regno); 6943 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6944 if (t == BPF_WRITE && value_regno >= 0 && 6945 is_pointer_value(env, value_regno)) { 6946 verbose(env, "R%d leaks addr into flow keys\n", 6947 value_regno); 6948 return -EACCES; 6949 } 6950 6951 err = check_flow_keys_access(env, off, size); 6952 if (!err && t == BPF_READ && value_regno >= 0) 6953 mark_reg_unknown(env, regs, value_regno); 6954 } else if (type_is_sk_pointer(reg->type)) { 6955 if (t == BPF_WRITE) { 6956 verbose(env, "R%d cannot write into %s\n", 6957 regno, reg_type_str(env, reg->type)); 6958 return -EACCES; 6959 } 6960 err = check_sock_access(env, insn_idx, regno, off, size, t); 6961 if (!err && value_regno >= 0) 6962 mark_reg_unknown(env, regs, value_regno); 6963 } else if (reg->type == PTR_TO_TP_BUFFER) { 6964 err = check_tp_buffer_access(env, reg, regno, off, size); 6965 if (!err && t == BPF_READ && value_regno >= 0) 6966 mark_reg_unknown(env, regs, value_regno); 6967 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6968 !type_may_be_null(reg->type)) { 6969 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6970 value_regno); 6971 } else if (reg->type == CONST_PTR_TO_MAP) { 6972 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6973 value_regno); 6974 } else if (base_type(reg->type) == PTR_TO_BUF) { 6975 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6976 u32 *max_access; 6977 6978 if (rdonly_mem) { 6979 if (t == BPF_WRITE) { 6980 verbose(env, "R%d cannot write into %s\n", 6981 regno, reg_type_str(env, reg->type)); 6982 return -EACCES; 6983 } 6984 max_access = &env->prog->aux->max_rdonly_access; 6985 } else { 6986 max_access = &env->prog->aux->max_rdwr_access; 6987 } 6988 6989 err = check_buffer_access(env, reg, regno, off, size, false, 6990 max_access); 6991 6992 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6993 mark_reg_unknown(env, regs, value_regno); 6994 } else if (reg->type == PTR_TO_ARENA) { 6995 if (t == BPF_READ && value_regno >= 0) 6996 mark_reg_unknown(env, regs, value_regno); 6997 } else { 6998 verbose(env, "R%d invalid mem access '%s'\n", regno, 6999 reg_type_str(env, reg->type)); 7000 return -EACCES; 7001 } 7002 7003 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7004 regs[value_regno].type == SCALAR_VALUE) { 7005 if (!is_ldsx) 7006 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7007 coerce_reg_to_size(®s[value_regno], size); 7008 else 7009 coerce_reg_to_size_sx(®s[value_regno], size); 7010 } 7011 return err; 7012 } 7013 7014 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7015 bool allow_trust_mismatch); 7016 7017 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 7018 { 7019 int load_reg; 7020 int err; 7021 7022 switch (insn->imm) { 7023 case BPF_ADD: 7024 case BPF_ADD | BPF_FETCH: 7025 case BPF_AND: 7026 case BPF_AND | BPF_FETCH: 7027 case BPF_OR: 7028 case BPF_OR | BPF_FETCH: 7029 case BPF_XOR: 7030 case BPF_XOR | BPF_FETCH: 7031 case BPF_XCHG: 7032 case BPF_CMPXCHG: 7033 break; 7034 default: 7035 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 7036 return -EINVAL; 7037 } 7038 7039 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7040 verbose(env, "invalid atomic operand size\n"); 7041 return -EINVAL; 7042 } 7043 7044 /* check src1 operand */ 7045 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7046 if (err) 7047 return err; 7048 7049 /* check src2 operand */ 7050 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7051 if (err) 7052 return err; 7053 7054 if (insn->imm == BPF_CMPXCHG) { 7055 /* Check comparison of R0 with memory location */ 7056 const u32 aux_reg = BPF_REG_0; 7057 7058 err = check_reg_arg(env, aux_reg, SRC_OP); 7059 if (err) 7060 return err; 7061 7062 if (is_pointer_value(env, aux_reg)) { 7063 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7064 return -EACCES; 7065 } 7066 } 7067 7068 if (is_pointer_value(env, insn->src_reg)) { 7069 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7070 return -EACCES; 7071 } 7072 7073 if (is_ctx_reg(env, insn->dst_reg) || 7074 is_pkt_reg(env, insn->dst_reg) || 7075 is_flow_key_reg(env, insn->dst_reg) || 7076 is_sk_reg(env, insn->dst_reg) || 7077 (is_arena_reg(env, insn->dst_reg) && !bpf_jit_supports_insn(insn, true))) { 7078 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7079 insn->dst_reg, 7080 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7081 return -EACCES; 7082 } 7083 7084 if (insn->imm & BPF_FETCH) { 7085 if (insn->imm == BPF_CMPXCHG) 7086 load_reg = BPF_REG_0; 7087 else 7088 load_reg = insn->src_reg; 7089 7090 /* check and record load of old value */ 7091 err = check_reg_arg(env, load_reg, DST_OP); 7092 if (err) 7093 return err; 7094 } else { 7095 /* This instruction accesses a memory location but doesn't 7096 * actually load it into a register. 7097 */ 7098 load_reg = -1; 7099 } 7100 7101 /* Check whether we can read the memory, with second call for fetch 7102 * case to simulate the register fill. 7103 */ 7104 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7105 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7106 if (!err && load_reg >= 0) 7107 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7108 BPF_SIZE(insn->code), BPF_READ, load_reg, 7109 true, false); 7110 if (err) 7111 return err; 7112 7113 if (is_arena_reg(env, insn->dst_reg)) { 7114 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7115 if (err) 7116 return err; 7117 } 7118 /* Check whether we can write into the same memory. */ 7119 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7120 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7121 if (err) 7122 return err; 7123 return 0; 7124 } 7125 7126 /* When register 'regno' is used to read the stack (either directly or through 7127 * a helper function) make sure that it's within stack boundary and, depending 7128 * on the access type and privileges, that all elements of the stack are 7129 * initialized. 7130 * 7131 * 'off' includes 'regno->off', but not its dynamic part (if any). 7132 * 7133 * All registers that have been spilled on the stack in the slots within the 7134 * read offsets are marked as read. 7135 */ 7136 static int check_stack_range_initialized( 7137 struct bpf_verifier_env *env, int regno, int off, 7138 int access_size, bool zero_size_allowed, 7139 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7140 { 7141 struct bpf_reg_state *reg = reg_state(env, regno); 7142 struct bpf_func_state *state = func(env, reg); 7143 int err, min_off, max_off, i, j, slot, spi; 7144 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7145 enum bpf_access_type bounds_check_type; 7146 /* Some accesses can write anything into the stack, others are 7147 * read-only. 7148 */ 7149 bool clobber = false; 7150 7151 if (access_size == 0 && !zero_size_allowed) { 7152 verbose(env, "invalid zero-sized read\n"); 7153 return -EACCES; 7154 } 7155 7156 if (type == ACCESS_HELPER) { 7157 /* The bounds checks for writes are more permissive than for 7158 * reads. However, if raw_mode is not set, we'll do extra 7159 * checks below. 7160 */ 7161 bounds_check_type = BPF_WRITE; 7162 clobber = true; 7163 } else { 7164 bounds_check_type = BPF_READ; 7165 } 7166 err = check_stack_access_within_bounds(env, regno, off, access_size, 7167 type, bounds_check_type); 7168 if (err) 7169 return err; 7170 7171 7172 if (tnum_is_const(reg->var_off)) { 7173 min_off = max_off = reg->var_off.value + off; 7174 } else { 7175 /* Variable offset is prohibited for unprivileged mode for 7176 * simplicity since it requires corresponding support in 7177 * Spectre masking for stack ALU. 7178 * See also retrieve_ptr_limit(). 7179 */ 7180 if (!env->bypass_spec_v1) { 7181 char tn_buf[48]; 7182 7183 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7184 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7185 regno, err_extra, tn_buf); 7186 return -EACCES; 7187 } 7188 /* Only initialized buffer on stack is allowed to be accessed 7189 * with variable offset. With uninitialized buffer it's hard to 7190 * guarantee that whole memory is marked as initialized on 7191 * helper return since specific bounds are unknown what may 7192 * cause uninitialized stack leaking. 7193 */ 7194 if (meta && meta->raw_mode) 7195 meta = NULL; 7196 7197 min_off = reg->smin_value + off; 7198 max_off = reg->smax_value + off; 7199 } 7200 7201 if (meta && meta->raw_mode) { 7202 /* Ensure we won't be overwriting dynptrs when simulating byte 7203 * by byte access in check_helper_call using meta.access_size. 7204 * This would be a problem if we have a helper in the future 7205 * which takes: 7206 * 7207 * helper(uninit_mem, len, dynptr) 7208 * 7209 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7210 * may end up writing to dynptr itself when touching memory from 7211 * arg 1. This can be relaxed on a case by case basis for known 7212 * safe cases, but reject due to the possibilitiy of aliasing by 7213 * default. 7214 */ 7215 for (i = min_off; i < max_off + access_size; i++) { 7216 int stack_off = -i - 1; 7217 7218 spi = __get_spi(i); 7219 /* raw_mode may write past allocated_stack */ 7220 if (state->allocated_stack <= stack_off) 7221 continue; 7222 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7223 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7224 return -EACCES; 7225 } 7226 } 7227 meta->access_size = access_size; 7228 meta->regno = regno; 7229 return 0; 7230 } 7231 7232 for (i = min_off; i < max_off + access_size; i++) { 7233 u8 *stype; 7234 7235 slot = -i - 1; 7236 spi = slot / BPF_REG_SIZE; 7237 if (state->allocated_stack <= slot) { 7238 verbose(env, "verifier bug: allocated_stack too small"); 7239 return -EFAULT; 7240 } 7241 7242 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7243 if (*stype == STACK_MISC) 7244 goto mark; 7245 if ((*stype == STACK_ZERO) || 7246 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7247 if (clobber) { 7248 /* helper can write anything into the stack */ 7249 *stype = STACK_MISC; 7250 } 7251 goto mark; 7252 } 7253 7254 if (is_spilled_reg(&state->stack[spi]) && 7255 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7256 env->allow_ptr_leaks)) { 7257 if (clobber) { 7258 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7259 for (j = 0; j < BPF_REG_SIZE; j++) 7260 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7261 } 7262 goto mark; 7263 } 7264 7265 if (tnum_is_const(reg->var_off)) { 7266 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7267 err_extra, regno, min_off, i - min_off, access_size); 7268 } else { 7269 char tn_buf[48]; 7270 7271 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7272 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7273 err_extra, regno, tn_buf, i - min_off, access_size); 7274 } 7275 return -EACCES; 7276 mark: 7277 /* reading any byte out of 8-byte 'spill_slot' will cause 7278 * the whole slot to be marked as 'read' 7279 */ 7280 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7281 state->stack[spi].spilled_ptr.parent, 7282 REG_LIVE_READ64); 7283 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7284 * be sure that whether stack slot is written to or not. Hence, 7285 * we must still conservatively propagate reads upwards even if 7286 * helper may write to the entire memory range. 7287 */ 7288 } 7289 return 0; 7290 } 7291 7292 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7293 int access_size, bool zero_size_allowed, 7294 struct bpf_call_arg_meta *meta) 7295 { 7296 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7297 u32 *max_access; 7298 7299 switch (base_type(reg->type)) { 7300 case PTR_TO_PACKET: 7301 case PTR_TO_PACKET_META: 7302 return check_packet_access(env, regno, reg->off, access_size, 7303 zero_size_allowed); 7304 case PTR_TO_MAP_KEY: 7305 if (meta && meta->raw_mode) { 7306 verbose(env, "R%d cannot write into %s\n", regno, 7307 reg_type_str(env, reg->type)); 7308 return -EACCES; 7309 } 7310 return check_mem_region_access(env, regno, reg->off, access_size, 7311 reg->map_ptr->key_size, false); 7312 case PTR_TO_MAP_VALUE: 7313 if (check_map_access_type(env, regno, reg->off, access_size, 7314 meta && meta->raw_mode ? BPF_WRITE : 7315 BPF_READ)) 7316 return -EACCES; 7317 return check_map_access(env, regno, reg->off, access_size, 7318 zero_size_allowed, ACCESS_HELPER); 7319 case PTR_TO_MEM: 7320 if (type_is_rdonly_mem(reg->type)) { 7321 if (meta && meta->raw_mode) { 7322 verbose(env, "R%d cannot write into %s\n", regno, 7323 reg_type_str(env, reg->type)); 7324 return -EACCES; 7325 } 7326 } 7327 return check_mem_region_access(env, regno, reg->off, 7328 access_size, reg->mem_size, 7329 zero_size_allowed); 7330 case PTR_TO_BUF: 7331 if (type_is_rdonly_mem(reg->type)) { 7332 if (meta && meta->raw_mode) { 7333 verbose(env, "R%d cannot write into %s\n", regno, 7334 reg_type_str(env, reg->type)); 7335 return -EACCES; 7336 } 7337 7338 max_access = &env->prog->aux->max_rdonly_access; 7339 } else { 7340 max_access = &env->prog->aux->max_rdwr_access; 7341 } 7342 return check_buffer_access(env, reg, regno, reg->off, 7343 access_size, zero_size_allowed, 7344 max_access); 7345 case PTR_TO_STACK: 7346 return check_stack_range_initialized( 7347 env, 7348 regno, reg->off, access_size, 7349 zero_size_allowed, ACCESS_HELPER, meta); 7350 case PTR_TO_BTF_ID: 7351 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7352 access_size, BPF_READ, -1); 7353 case PTR_TO_CTX: 7354 /* in case the function doesn't know how to access the context, 7355 * (because we are in a program of type SYSCALL for example), we 7356 * can not statically check its size. 7357 * Dynamically check it now. 7358 */ 7359 if (!env->ops->convert_ctx_access) { 7360 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7361 int offset = access_size - 1; 7362 7363 /* Allow zero-byte read from PTR_TO_CTX */ 7364 if (access_size == 0) 7365 return zero_size_allowed ? 0 : -EACCES; 7366 7367 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7368 atype, -1, false, false); 7369 } 7370 7371 fallthrough; 7372 default: /* scalar_value or invalid ptr */ 7373 /* Allow zero-byte read from NULL, regardless of pointer type */ 7374 if (zero_size_allowed && access_size == 0 && 7375 register_is_null(reg)) 7376 return 0; 7377 7378 verbose(env, "R%d type=%s ", regno, 7379 reg_type_str(env, reg->type)); 7380 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7381 return -EACCES; 7382 } 7383 } 7384 7385 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7386 * size. 7387 * 7388 * @regno is the register containing the access size. regno-1 is the register 7389 * containing the pointer. 7390 */ 7391 static int check_mem_size_reg(struct bpf_verifier_env *env, 7392 struct bpf_reg_state *reg, u32 regno, 7393 bool zero_size_allowed, 7394 struct bpf_call_arg_meta *meta) 7395 { 7396 int err; 7397 7398 /* This is used to refine r0 return value bounds for helpers 7399 * that enforce this value as an upper bound on return values. 7400 * See do_refine_retval_range() for helpers that can refine 7401 * the return value. C type of helper is u32 so we pull register 7402 * bound from umax_value however, if negative verifier errors 7403 * out. Only upper bounds can be learned because retval is an 7404 * int type and negative retvals are allowed. 7405 */ 7406 meta->msize_max_value = reg->umax_value; 7407 7408 /* The register is SCALAR_VALUE; the access check 7409 * happens using its boundaries. 7410 */ 7411 if (!tnum_is_const(reg->var_off)) 7412 /* For unprivileged variable accesses, disable raw 7413 * mode so that the program is required to 7414 * initialize all the memory that the helper could 7415 * just partially fill up. 7416 */ 7417 meta = NULL; 7418 7419 if (reg->smin_value < 0) { 7420 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7421 regno); 7422 return -EACCES; 7423 } 7424 7425 if (reg->umin_value == 0 && !zero_size_allowed) { 7426 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7427 regno, reg->umin_value, reg->umax_value); 7428 return -EACCES; 7429 } 7430 7431 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7432 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7433 regno); 7434 return -EACCES; 7435 } 7436 err = check_helper_mem_access(env, regno - 1, 7437 reg->umax_value, 7438 zero_size_allowed, meta); 7439 if (!err) 7440 err = mark_chain_precision(env, regno); 7441 return err; 7442 } 7443 7444 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7445 u32 regno, u32 mem_size) 7446 { 7447 bool may_be_null = type_may_be_null(reg->type); 7448 struct bpf_reg_state saved_reg; 7449 struct bpf_call_arg_meta meta; 7450 int err; 7451 7452 if (register_is_null(reg)) 7453 return 0; 7454 7455 memset(&meta, 0, sizeof(meta)); 7456 /* Assuming that the register contains a value check if the memory 7457 * access is safe. Temporarily save and restore the register's state as 7458 * the conversion shouldn't be visible to a caller. 7459 */ 7460 if (may_be_null) { 7461 saved_reg = *reg; 7462 mark_ptr_not_null_reg(reg); 7463 } 7464 7465 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7466 /* Check access for BPF_WRITE */ 7467 meta.raw_mode = true; 7468 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7469 7470 if (may_be_null) 7471 *reg = saved_reg; 7472 7473 return err; 7474 } 7475 7476 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7477 u32 regno) 7478 { 7479 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7480 bool may_be_null = type_may_be_null(mem_reg->type); 7481 struct bpf_reg_state saved_reg; 7482 struct bpf_call_arg_meta meta; 7483 int err; 7484 7485 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7486 7487 memset(&meta, 0, sizeof(meta)); 7488 7489 if (may_be_null) { 7490 saved_reg = *mem_reg; 7491 mark_ptr_not_null_reg(mem_reg); 7492 } 7493 7494 err = check_mem_size_reg(env, reg, regno, true, &meta); 7495 /* Check access for BPF_WRITE */ 7496 meta.raw_mode = true; 7497 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7498 7499 if (may_be_null) 7500 *mem_reg = saved_reg; 7501 return err; 7502 } 7503 7504 /* Implementation details: 7505 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7506 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7507 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7508 * Two separate bpf_obj_new will also have different reg->id. 7509 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7510 * clears reg->id after value_or_null->value transition, since the verifier only 7511 * cares about the range of access to valid map value pointer and doesn't care 7512 * about actual address of the map element. 7513 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7514 * reg->id > 0 after value_or_null->value transition. By doing so 7515 * two bpf_map_lookups will be considered two different pointers that 7516 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7517 * returned from bpf_obj_new. 7518 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7519 * dead-locks. 7520 * Since only one bpf_spin_lock is allowed the checks are simpler than 7521 * reg_is_refcounted() logic. The verifier needs to remember only 7522 * one spin_lock instead of array of acquired_refs. 7523 * cur_state->active_lock remembers which map value element or allocated 7524 * object got locked and clears it after bpf_spin_unlock. 7525 */ 7526 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7527 bool is_lock) 7528 { 7529 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7530 struct bpf_verifier_state *cur = env->cur_state; 7531 bool is_const = tnum_is_const(reg->var_off); 7532 u64 val = reg->var_off.value; 7533 struct bpf_map *map = NULL; 7534 struct btf *btf = NULL; 7535 struct btf_record *rec; 7536 7537 if (!is_const) { 7538 verbose(env, 7539 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7540 regno); 7541 return -EINVAL; 7542 } 7543 if (reg->type == PTR_TO_MAP_VALUE) { 7544 map = reg->map_ptr; 7545 if (!map->btf) { 7546 verbose(env, 7547 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7548 map->name); 7549 return -EINVAL; 7550 } 7551 } else { 7552 btf = reg->btf; 7553 } 7554 7555 rec = reg_btf_record(reg); 7556 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7557 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7558 map ? map->name : "kptr"); 7559 return -EINVAL; 7560 } 7561 if (rec->spin_lock_off != val + reg->off) { 7562 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7563 val + reg->off, rec->spin_lock_off); 7564 return -EINVAL; 7565 } 7566 if (is_lock) { 7567 if (cur->active_lock.ptr) { 7568 verbose(env, 7569 "Locking two bpf_spin_locks are not allowed\n"); 7570 return -EINVAL; 7571 } 7572 if (map) 7573 cur->active_lock.ptr = map; 7574 else 7575 cur->active_lock.ptr = btf; 7576 cur->active_lock.id = reg->id; 7577 } else { 7578 void *ptr; 7579 7580 if (map) 7581 ptr = map; 7582 else 7583 ptr = btf; 7584 7585 if (!cur->active_lock.ptr) { 7586 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7587 return -EINVAL; 7588 } 7589 if (cur->active_lock.ptr != ptr || 7590 cur->active_lock.id != reg->id) { 7591 verbose(env, "bpf_spin_unlock of different lock\n"); 7592 return -EINVAL; 7593 } 7594 7595 invalidate_non_owning_refs(env); 7596 7597 cur->active_lock.ptr = NULL; 7598 cur->active_lock.id = 0; 7599 } 7600 return 0; 7601 } 7602 7603 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7604 struct bpf_call_arg_meta *meta) 7605 { 7606 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7607 bool is_const = tnum_is_const(reg->var_off); 7608 struct bpf_map *map = reg->map_ptr; 7609 u64 val = reg->var_off.value; 7610 7611 if (!is_const) { 7612 verbose(env, 7613 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7614 regno); 7615 return -EINVAL; 7616 } 7617 if (!map->btf) { 7618 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7619 map->name); 7620 return -EINVAL; 7621 } 7622 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7623 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7624 return -EINVAL; 7625 } 7626 if (map->record->timer_off != val + reg->off) { 7627 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7628 val + reg->off, map->record->timer_off); 7629 return -EINVAL; 7630 } 7631 if (meta->map_ptr) { 7632 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7633 return -EFAULT; 7634 } 7635 meta->map_uid = reg->map_uid; 7636 meta->map_ptr = map; 7637 return 0; 7638 } 7639 7640 static int process_wq_func(struct bpf_verifier_env *env, int regno, 7641 struct bpf_kfunc_call_arg_meta *meta) 7642 { 7643 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7644 struct bpf_map *map = reg->map_ptr; 7645 u64 val = reg->var_off.value; 7646 7647 if (map->record->wq_off != val + reg->off) { 7648 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 7649 val + reg->off, map->record->wq_off); 7650 return -EINVAL; 7651 } 7652 meta->map.uid = reg->map_uid; 7653 meta->map.ptr = map; 7654 return 0; 7655 } 7656 7657 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7658 struct bpf_call_arg_meta *meta) 7659 { 7660 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7661 struct bpf_map *map_ptr = reg->map_ptr; 7662 struct btf_field *kptr_field; 7663 u32 kptr_off; 7664 7665 if (!tnum_is_const(reg->var_off)) { 7666 verbose(env, 7667 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7668 regno); 7669 return -EINVAL; 7670 } 7671 if (!map_ptr->btf) { 7672 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7673 map_ptr->name); 7674 return -EINVAL; 7675 } 7676 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7677 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7678 return -EINVAL; 7679 } 7680 7681 meta->map_ptr = map_ptr; 7682 kptr_off = reg->off + reg->var_off.value; 7683 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7684 if (!kptr_field) { 7685 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7686 return -EACCES; 7687 } 7688 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7689 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7690 return -EACCES; 7691 } 7692 meta->kptr_field = kptr_field; 7693 return 0; 7694 } 7695 7696 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7697 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7698 * 7699 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7700 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7701 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7702 * 7703 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7704 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7705 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7706 * mutate the view of the dynptr and also possibly destroy it. In the latter 7707 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7708 * memory that dynptr points to. 7709 * 7710 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7711 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7712 * readonly dynptr view yet, hence only the first case is tracked and checked. 7713 * 7714 * This is consistent with how C applies the const modifier to a struct object, 7715 * where the pointer itself inside bpf_dynptr becomes const but not what it 7716 * points to. 7717 * 7718 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7719 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7720 */ 7721 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7722 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7723 { 7724 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7725 int err; 7726 7727 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7728 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7729 */ 7730 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7731 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7732 return -EFAULT; 7733 } 7734 7735 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7736 * constructing a mutable bpf_dynptr object. 7737 * 7738 * Currently, this is only possible with PTR_TO_STACK 7739 * pointing to a region of at least 16 bytes which doesn't 7740 * contain an existing bpf_dynptr. 7741 * 7742 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7743 * mutated or destroyed. However, the memory it points to 7744 * may be mutated. 7745 * 7746 * None - Points to a initialized dynptr that can be mutated and 7747 * destroyed, including mutation of the memory it points 7748 * to. 7749 */ 7750 if (arg_type & MEM_UNINIT) { 7751 int i; 7752 7753 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7754 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7755 return -EINVAL; 7756 } 7757 7758 /* we write BPF_DW bits (8 bytes) at a time */ 7759 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7760 err = check_mem_access(env, insn_idx, regno, 7761 i, BPF_DW, BPF_WRITE, -1, false, false); 7762 if (err) 7763 return err; 7764 } 7765 7766 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7767 } else /* MEM_RDONLY and None case from above */ { 7768 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7769 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7770 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7771 return -EINVAL; 7772 } 7773 7774 if (!is_dynptr_reg_valid_init(env, reg)) { 7775 verbose(env, 7776 "Expected an initialized dynptr as arg #%d\n", 7777 regno); 7778 return -EINVAL; 7779 } 7780 7781 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7782 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7783 verbose(env, 7784 "Expected a dynptr of type %s as arg #%d\n", 7785 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7786 return -EINVAL; 7787 } 7788 7789 err = mark_dynptr_read(env, reg); 7790 } 7791 return err; 7792 } 7793 7794 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7795 { 7796 struct bpf_func_state *state = func(env, reg); 7797 7798 return state->stack[spi].spilled_ptr.ref_obj_id; 7799 } 7800 7801 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7802 { 7803 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7804 } 7805 7806 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7807 { 7808 return meta->kfunc_flags & KF_ITER_NEW; 7809 } 7810 7811 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7812 { 7813 return meta->kfunc_flags & KF_ITER_NEXT; 7814 } 7815 7816 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7817 { 7818 return meta->kfunc_flags & KF_ITER_DESTROY; 7819 } 7820 7821 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7822 { 7823 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7824 * kfunc is iter state pointer 7825 */ 7826 return arg == 0 && is_iter_kfunc(meta); 7827 } 7828 7829 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7830 struct bpf_kfunc_call_arg_meta *meta) 7831 { 7832 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7833 const struct btf_type *t; 7834 const struct btf_param *arg; 7835 int spi, err, i, nr_slots; 7836 u32 btf_id; 7837 7838 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7839 arg = &btf_params(meta->func_proto)[0]; 7840 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7841 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7842 nr_slots = t->size / BPF_REG_SIZE; 7843 7844 if (is_iter_new_kfunc(meta)) { 7845 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7846 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7847 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7848 iter_type_str(meta->btf, btf_id), regno); 7849 return -EINVAL; 7850 } 7851 7852 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7853 err = check_mem_access(env, insn_idx, regno, 7854 i, BPF_DW, BPF_WRITE, -1, false, false); 7855 if (err) 7856 return err; 7857 } 7858 7859 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7860 if (err) 7861 return err; 7862 } else { 7863 /* iter_next() or iter_destroy() expect initialized iter state*/ 7864 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7865 switch (err) { 7866 case 0: 7867 break; 7868 case -EINVAL: 7869 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7870 iter_type_str(meta->btf, btf_id), regno); 7871 return err; 7872 case -EPROTO: 7873 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7874 return err; 7875 default: 7876 return err; 7877 } 7878 7879 spi = iter_get_spi(env, reg, nr_slots); 7880 if (spi < 0) 7881 return spi; 7882 7883 err = mark_iter_read(env, reg, spi, nr_slots); 7884 if (err) 7885 return err; 7886 7887 /* remember meta->iter info for process_iter_next_call() */ 7888 meta->iter.spi = spi; 7889 meta->iter.frameno = reg->frameno; 7890 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7891 7892 if (is_iter_destroy_kfunc(meta)) { 7893 err = unmark_stack_slots_iter(env, reg, nr_slots); 7894 if (err) 7895 return err; 7896 } 7897 } 7898 7899 return 0; 7900 } 7901 7902 /* Look for a previous loop entry at insn_idx: nearest parent state 7903 * stopped at insn_idx with callsites matching those in cur->frame. 7904 */ 7905 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7906 struct bpf_verifier_state *cur, 7907 int insn_idx) 7908 { 7909 struct bpf_verifier_state_list *sl; 7910 struct bpf_verifier_state *st; 7911 7912 /* Explored states are pushed in stack order, most recent states come first */ 7913 sl = *explored_state(env, insn_idx); 7914 for (; sl; sl = sl->next) { 7915 /* If st->branches != 0 state is a part of current DFS verification path, 7916 * hence cur & st for a loop. 7917 */ 7918 st = &sl->state; 7919 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7920 st->dfs_depth < cur->dfs_depth) 7921 return st; 7922 } 7923 7924 return NULL; 7925 } 7926 7927 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7928 static bool regs_exact(const struct bpf_reg_state *rold, 7929 const struct bpf_reg_state *rcur, 7930 struct bpf_idmap *idmap); 7931 7932 static void maybe_widen_reg(struct bpf_verifier_env *env, 7933 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7934 struct bpf_idmap *idmap) 7935 { 7936 if (rold->type != SCALAR_VALUE) 7937 return; 7938 if (rold->type != rcur->type) 7939 return; 7940 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7941 return; 7942 __mark_reg_unknown(env, rcur); 7943 } 7944 7945 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7946 struct bpf_verifier_state *old, 7947 struct bpf_verifier_state *cur) 7948 { 7949 struct bpf_func_state *fold, *fcur; 7950 int i, fr; 7951 7952 reset_idmap_scratch(env); 7953 for (fr = old->curframe; fr >= 0; fr--) { 7954 fold = old->frame[fr]; 7955 fcur = cur->frame[fr]; 7956 7957 for (i = 0; i < MAX_BPF_REG; i++) 7958 maybe_widen_reg(env, 7959 &fold->regs[i], 7960 &fcur->regs[i], 7961 &env->idmap_scratch); 7962 7963 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7964 if (!is_spilled_reg(&fold->stack[i]) || 7965 !is_spilled_reg(&fcur->stack[i])) 7966 continue; 7967 7968 maybe_widen_reg(env, 7969 &fold->stack[i].spilled_ptr, 7970 &fcur->stack[i].spilled_ptr, 7971 &env->idmap_scratch); 7972 } 7973 } 7974 return 0; 7975 } 7976 7977 /* process_iter_next_call() is called when verifier gets to iterator's next 7978 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7979 * to it as just "iter_next()" in comments below. 7980 * 7981 * BPF verifier relies on a crucial contract for any iter_next() 7982 * implementation: it should *eventually* return NULL, and once that happens 7983 * it should keep returning NULL. That is, once iterator exhausts elements to 7984 * iterate, it should never reset or spuriously return new elements. 7985 * 7986 * With the assumption of such contract, process_iter_next_call() simulates 7987 * a fork in the verifier state to validate loop logic correctness and safety 7988 * without having to simulate infinite amount of iterations. 7989 * 7990 * In current state, we first assume that iter_next() returned NULL and 7991 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7992 * conditions we should not form an infinite loop and should eventually reach 7993 * exit. 7994 * 7995 * Besides that, we also fork current state and enqueue it for later 7996 * verification. In a forked state we keep iterator state as ACTIVE 7997 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7998 * also bump iteration depth to prevent erroneous infinite loop detection 7999 * later on (see iter_active_depths_differ() comment for details). In this 8000 * state we assume that we'll eventually loop back to another iter_next() 8001 * calls (it could be in exactly same location or in some other instruction, 8002 * it doesn't matter, we don't make any unnecessary assumptions about this, 8003 * everything revolves around iterator state in a stack slot, not which 8004 * instruction is calling iter_next()). When that happens, we either will come 8005 * to iter_next() with equivalent state and can conclude that next iteration 8006 * will proceed in exactly the same way as we just verified, so it's safe to 8007 * assume that loop converges. If not, we'll go on another iteration 8008 * simulation with a different input state, until all possible starting states 8009 * are validated or we reach maximum number of instructions limit. 8010 * 8011 * This way, we will either exhaustively discover all possible input states 8012 * that iterator loop can start with and eventually will converge, or we'll 8013 * effectively regress into bounded loop simulation logic and either reach 8014 * maximum number of instructions if loop is not provably convergent, or there 8015 * is some statically known limit on number of iterations (e.g., if there is 8016 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8017 * 8018 * Iteration convergence logic in is_state_visited() relies on exact 8019 * states comparison, which ignores read and precision marks. 8020 * This is necessary because read and precision marks are not finalized 8021 * while in the loop. Exact comparison might preclude convergence for 8022 * simple programs like below: 8023 * 8024 * i = 0; 8025 * while(iter_next(&it)) 8026 * i++; 8027 * 8028 * At each iteration step i++ would produce a new distinct state and 8029 * eventually instruction processing limit would be reached. 8030 * 8031 * To avoid such behavior speculatively forget (widen) range for 8032 * imprecise scalar registers, if those registers were not precise at the 8033 * end of the previous iteration and do not match exactly. 8034 * 8035 * This is a conservative heuristic that allows to verify wide range of programs, 8036 * however it precludes verification of programs that conjure an 8037 * imprecise value on the first loop iteration and use it as precise on a second. 8038 * For example, the following safe program would fail to verify: 8039 * 8040 * struct bpf_num_iter it; 8041 * int arr[10]; 8042 * int i = 0, a = 0; 8043 * bpf_iter_num_new(&it, 0, 10); 8044 * while (bpf_iter_num_next(&it)) { 8045 * if (a == 0) { 8046 * a = 1; 8047 * i = 7; // Because i changed verifier would forget 8048 * // it's range on second loop entry. 8049 * } else { 8050 * arr[i] = 42; // This would fail to verify. 8051 * } 8052 * } 8053 * bpf_iter_num_destroy(&it); 8054 */ 8055 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8056 struct bpf_kfunc_call_arg_meta *meta) 8057 { 8058 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8059 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8060 struct bpf_reg_state *cur_iter, *queued_iter; 8061 int iter_frameno = meta->iter.frameno; 8062 int iter_spi = meta->iter.spi; 8063 8064 BTF_TYPE_EMIT(struct bpf_iter); 8065 8066 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8067 8068 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8069 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8070 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8071 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8072 return -EFAULT; 8073 } 8074 8075 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8076 /* Because iter_next() call is a checkpoint is_state_visitied() 8077 * should guarantee parent state with same call sites and insn_idx. 8078 */ 8079 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8080 !same_callsites(cur_st->parent, cur_st)) { 8081 verbose(env, "bug: bad parent state for iter next call"); 8082 return -EFAULT; 8083 } 8084 /* Note cur_st->parent in the call below, it is necessary to skip 8085 * checkpoint created for cur_st by is_state_visited() 8086 * right at this instruction. 8087 */ 8088 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8089 /* branch out active iter state */ 8090 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8091 if (!queued_st) 8092 return -ENOMEM; 8093 8094 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8095 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8096 queued_iter->iter.depth++; 8097 if (prev_st) 8098 widen_imprecise_scalars(env, prev_st, queued_st); 8099 8100 queued_fr = queued_st->frame[queued_st->curframe]; 8101 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8102 } 8103 8104 /* switch to DRAINED state, but keep the depth unchanged */ 8105 /* mark current iter state as drained and assume returned NULL */ 8106 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8107 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8108 8109 return 0; 8110 } 8111 8112 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8113 { 8114 return type == ARG_CONST_SIZE || 8115 type == ARG_CONST_SIZE_OR_ZERO; 8116 } 8117 8118 static bool arg_type_is_release(enum bpf_arg_type type) 8119 { 8120 return type & OBJ_RELEASE; 8121 } 8122 8123 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8124 { 8125 return base_type(type) == ARG_PTR_TO_DYNPTR; 8126 } 8127 8128 static int int_ptr_type_to_size(enum bpf_arg_type type) 8129 { 8130 if (type == ARG_PTR_TO_INT) 8131 return sizeof(u32); 8132 else if (type == ARG_PTR_TO_LONG) 8133 return sizeof(u64); 8134 8135 return -EINVAL; 8136 } 8137 8138 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8139 const struct bpf_call_arg_meta *meta, 8140 enum bpf_arg_type *arg_type) 8141 { 8142 if (!meta->map_ptr) { 8143 /* kernel subsystem misconfigured verifier */ 8144 verbose(env, "invalid map_ptr to access map->type\n"); 8145 return -EACCES; 8146 } 8147 8148 switch (meta->map_ptr->map_type) { 8149 case BPF_MAP_TYPE_SOCKMAP: 8150 case BPF_MAP_TYPE_SOCKHASH: 8151 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8152 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8153 } else { 8154 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8155 return -EINVAL; 8156 } 8157 break; 8158 case BPF_MAP_TYPE_BLOOM_FILTER: 8159 if (meta->func_id == BPF_FUNC_map_peek_elem) 8160 *arg_type = ARG_PTR_TO_MAP_VALUE; 8161 break; 8162 default: 8163 break; 8164 } 8165 return 0; 8166 } 8167 8168 struct bpf_reg_types { 8169 const enum bpf_reg_type types[10]; 8170 u32 *btf_id; 8171 }; 8172 8173 static const struct bpf_reg_types sock_types = { 8174 .types = { 8175 PTR_TO_SOCK_COMMON, 8176 PTR_TO_SOCKET, 8177 PTR_TO_TCP_SOCK, 8178 PTR_TO_XDP_SOCK, 8179 }, 8180 }; 8181 8182 #ifdef CONFIG_NET 8183 static const struct bpf_reg_types btf_id_sock_common_types = { 8184 .types = { 8185 PTR_TO_SOCK_COMMON, 8186 PTR_TO_SOCKET, 8187 PTR_TO_TCP_SOCK, 8188 PTR_TO_XDP_SOCK, 8189 PTR_TO_BTF_ID, 8190 PTR_TO_BTF_ID | PTR_TRUSTED, 8191 }, 8192 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8193 }; 8194 #endif 8195 8196 static const struct bpf_reg_types mem_types = { 8197 .types = { 8198 PTR_TO_STACK, 8199 PTR_TO_PACKET, 8200 PTR_TO_PACKET_META, 8201 PTR_TO_MAP_KEY, 8202 PTR_TO_MAP_VALUE, 8203 PTR_TO_MEM, 8204 PTR_TO_MEM | MEM_RINGBUF, 8205 PTR_TO_BUF, 8206 PTR_TO_BTF_ID | PTR_TRUSTED, 8207 }, 8208 }; 8209 8210 static const struct bpf_reg_types int_ptr_types = { 8211 .types = { 8212 PTR_TO_STACK, 8213 PTR_TO_PACKET, 8214 PTR_TO_PACKET_META, 8215 PTR_TO_MAP_KEY, 8216 PTR_TO_MAP_VALUE, 8217 }, 8218 }; 8219 8220 static const struct bpf_reg_types spin_lock_types = { 8221 .types = { 8222 PTR_TO_MAP_VALUE, 8223 PTR_TO_BTF_ID | MEM_ALLOC, 8224 } 8225 }; 8226 8227 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8228 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8229 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8230 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8231 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8232 static const struct bpf_reg_types btf_ptr_types = { 8233 .types = { 8234 PTR_TO_BTF_ID, 8235 PTR_TO_BTF_ID | PTR_TRUSTED, 8236 PTR_TO_BTF_ID | MEM_RCU, 8237 }, 8238 }; 8239 static const struct bpf_reg_types percpu_btf_ptr_types = { 8240 .types = { 8241 PTR_TO_BTF_ID | MEM_PERCPU, 8242 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8243 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8244 } 8245 }; 8246 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8247 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8248 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8249 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8250 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8251 static const struct bpf_reg_types dynptr_types = { 8252 .types = { 8253 PTR_TO_STACK, 8254 CONST_PTR_TO_DYNPTR, 8255 } 8256 }; 8257 8258 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8259 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8260 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8261 [ARG_CONST_SIZE] = &scalar_types, 8262 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8263 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8264 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8265 [ARG_PTR_TO_CTX] = &context_types, 8266 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8267 #ifdef CONFIG_NET 8268 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8269 #endif 8270 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8271 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8272 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8273 [ARG_PTR_TO_MEM] = &mem_types, 8274 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8275 [ARG_PTR_TO_INT] = &int_ptr_types, 8276 [ARG_PTR_TO_LONG] = &int_ptr_types, 8277 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8278 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8279 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8280 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8281 [ARG_PTR_TO_TIMER] = &timer_types, 8282 [ARG_PTR_TO_KPTR] = &kptr_types, 8283 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8284 }; 8285 8286 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8287 enum bpf_arg_type arg_type, 8288 const u32 *arg_btf_id, 8289 struct bpf_call_arg_meta *meta) 8290 { 8291 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8292 enum bpf_reg_type expected, type = reg->type; 8293 const struct bpf_reg_types *compatible; 8294 int i, j; 8295 8296 compatible = compatible_reg_types[base_type(arg_type)]; 8297 if (!compatible) { 8298 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8299 return -EFAULT; 8300 } 8301 8302 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8303 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8304 * 8305 * Same for MAYBE_NULL: 8306 * 8307 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8308 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8309 * 8310 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8311 * 8312 * Therefore we fold these flags depending on the arg_type before comparison. 8313 */ 8314 if (arg_type & MEM_RDONLY) 8315 type &= ~MEM_RDONLY; 8316 if (arg_type & PTR_MAYBE_NULL) 8317 type &= ~PTR_MAYBE_NULL; 8318 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8319 type &= ~DYNPTR_TYPE_FLAG_MASK; 8320 8321 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8322 type &= ~MEM_ALLOC; 8323 type &= ~MEM_PERCPU; 8324 } 8325 8326 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8327 expected = compatible->types[i]; 8328 if (expected == NOT_INIT) 8329 break; 8330 8331 if (type == expected) 8332 goto found; 8333 } 8334 8335 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8336 for (j = 0; j + 1 < i; j++) 8337 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8338 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8339 return -EACCES; 8340 8341 found: 8342 if (base_type(reg->type) != PTR_TO_BTF_ID) 8343 return 0; 8344 8345 if (compatible == &mem_types) { 8346 if (!(arg_type & MEM_RDONLY)) { 8347 verbose(env, 8348 "%s() may write into memory pointed by R%d type=%s\n", 8349 func_id_name(meta->func_id), 8350 regno, reg_type_str(env, reg->type)); 8351 return -EACCES; 8352 } 8353 return 0; 8354 } 8355 8356 switch ((int)reg->type) { 8357 case PTR_TO_BTF_ID: 8358 case PTR_TO_BTF_ID | PTR_TRUSTED: 8359 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8360 case PTR_TO_BTF_ID | MEM_RCU: 8361 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8362 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8363 { 8364 /* For bpf_sk_release, it needs to match against first member 8365 * 'struct sock_common', hence make an exception for it. This 8366 * allows bpf_sk_release to work for multiple socket types. 8367 */ 8368 bool strict_type_match = arg_type_is_release(arg_type) && 8369 meta->func_id != BPF_FUNC_sk_release; 8370 8371 if (type_may_be_null(reg->type) && 8372 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8373 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8374 return -EACCES; 8375 } 8376 8377 if (!arg_btf_id) { 8378 if (!compatible->btf_id) { 8379 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8380 return -EFAULT; 8381 } 8382 arg_btf_id = compatible->btf_id; 8383 } 8384 8385 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8386 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8387 return -EACCES; 8388 } else { 8389 if (arg_btf_id == BPF_PTR_POISON) { 8390 verbose(env, "verifier internal error:"); 8391 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8392 regno); 8393 return -EACCES; 8394 } 8395 8396 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8397 btf_vmlinux, *arg_btf_id, 8398 strict_type_match)) { 8399 verbose(env, "R%d is of type %s but %s is expected\n", 8400 regno, btf_type_name(reg->btf, reg->btf_id), 8401 btf_type_name(btf_vmlinux, *arg_btf_id)); 8402 return -EACCES; 8403 } 8404 } 8405 break; 8406 } 8407 case PTR_TO_BTF_ID | MEM_ALLOC: 8408 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8409 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8410 meta->func_id != BPF_FUNC_kptr_xchg) { 8411 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8412 return -EFAULT; 8413 } 8414 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8415 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8416 return -EACCES; 8417 } 8418 break; 8419 case PTR_TO_BTF_ID | MEM_PERCPU: 8420 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8421 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8422 /* Handled by helper specific checks */ 8423 break; 8424 default: 8425 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8426 return -EFAULT; 8427 } 8428 return 0; 8429 } 8430 8431 static struct btf_field * 8432 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8433 { 8434 struct btf_field *field; 8435 struct btf_record *rec; 8436 8437 rec = reg_btf_record(reg); 8438 if (!rec) 8439 return NULL; 8440 8441 field = btf_record_find(rec, off, fields); 8442 if (!field) 8443 return NULL; 8444 8445 return field; 8446 } 8447 8448 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8449 const struct bpf_reg_state *reg, int regno, 8450 enum bpf_arg_type arg_type) 8451 { 8452 u32 type = reg->type; 8453 8454 /* When referenced register is passed to release function, its fixed 8455 * offset must be 0. 8456 * 8457 * We will check arg_type_is_release reg has ref_obj_id when storing 8458 * meta->release_regno. 8459 */ 8460 if (arg_type_is_release(arg_type)) { 8461 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8462 * may not directly point to the object being released, but to 8463 * dynptr pointing to such object, which might be at some offset 8464 * on the stack. In that case, we simply to fallback to the 8465 * default handling. 8466 */ 8467 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8468 return 0; 8469 8470 /* Doing check_ptr_off_reg check for the offset will catch this 8471 * because fixed_off_ok is false, but checking here allows us 8472 * to give the user a better error message. 8473 */ 8474 if (reg->off) { 8475 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8476 regno); 8477 return -EINVAL; 8478 } 8479 return __check_ptr_off_reg(env, reg, regno, false); 8480 } 8481 8482 switch (type) { 8483 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8484 case PTR_TO_STACK: 8485 case PTR_TO_PACKET: 8486 case PTR_TO_PACKET_META: 8487 case PTR_TO_MAP_KEY: 8488 case PTR_TO_MAP_VALUE: 8489 case PTR_TO_MEM: 8490 case PTR_TO_MEM | MEM_RDONLY: 8491 case PTR_TO_MEM | MEM_RINGBUF: 8492 case PTR_TO_BUF: 8493 case PTR_TO_BUF | MEM_RDONLY: 8494 case PTR_TO_ARENA: 8495 case SCALAR_VALUE: 8496 return 0; 8497 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8498 * fixed offset. 8499 */ 8500 case PTR_TO_BTF_ID: 8501 case PTR_TO_BTF_ID | MEM_ALLOC: 8502 case PTR_TO_BTF_ID | PTR_TRUSTED: 8503 case PTR_TO_BTF_ID | MEM_RCU: 8504 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8505 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8506 /* When referenced PTR_TO_BTF_ID is passed to release function, 8507 * its fixed offset must be 0. In the other cases, fixed offset 8508 * can be non-zero. This was already checked above. So pass 8509 * fixed_off_ok as true to allow fixed offset for all other 8510 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8511 * still need to do checks instead of returning. 8512 */ 8513 return __check_ptr_off_reg(env, reg, regno, true); 8514 default: 8515 return __check_ptr_off_reg(env, reg, regno, false); 8516 } 8517 } 8518 8519 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8520 const struct bpf_func_proto *fn, 8521 struct bpf_reg_state *regs) 8522 { 8523 struct bpf_reg_state *state = NULL; 8524 int i; 8525 8526 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8527 if (arg_type_is_dynptr(fn->arg_type[i])) { 8528 if (state) { 8529 verbose(env, "verifier internal error: multiple dynptr args\n"); 8530 return NULL; 8531 } 8532 state = ®s[BPF_REG_1 + i]; 8533 } 8534 8535 if (!state) 8536 verbose(env, "verifier internal error: no dynptr arg found\n"); 8537 8538 return state; 8539 } 8540 8541 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8542 { 8543 struct bpf_func_state *state = func(env, reg); 8544 int spi; 8545 8546 if (reg->type == CONST_PTR_TO_DYNPTR) 8547 return reg->id; 8548 spi = dynptr_get_spi(env, reg); 8549 if (spi < 0) 8550 return spi; 8551 return state->stack[spi].spilled_ptr.id; 8552 } 8553 8554 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8555 { 8556 struct bpf_func_state *state = func(env, reg); 8557 int spi; 8558 8559 if (reg->type == CONST_PTR_TO_DYNPTR) 8560 return reg->ref_obj_id; 8561 spi = dynptr_get_spi(env, reg); 8562 if (spi < 0) 8563 return spi; 8564 return state->stack[spi].spilled_ptr.ref_obj_id; 8565 } 8566 8567 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8568 struct bpf_reg_state *reg) 8569 { 8570 struct bpf_func_state *state = func(env, reg); 8571 int spi; 8572 8573 if (reg->type == CONST_PTR_TO_DYNPTR) 8574 return reg->dynptr.type; 8575 8576 spi = __get_spi(reg->off); 8577 if (spi < 0) { 8578 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8579 return BPF_DYNPTR_TYPE_INVALID; 8580 } 8581 8582 return state->stack[spi].spilled_ptr.dynptr.type; 8583 } 8584 8585 static int check_reg_const_str(struct bpf_verifier_env *env, 8586 struct bpf_reg_state *reg, u32 regno) 8587 { 8588 struct bpf_map *map = reg->map_ptr; 8589 int err; 8590 int map_off; 8591 u64 map_addr; 8592 char *str_ptr; 8593 8594 if (reg->type != PTR_TO_MAP_VALUE) 8595 return -EINVAL; 8596 8597 if (!bpf_map_is_rdonly(map)) { 8598 verbose(env, "R%d does not point to a readonly map'\n", regno); 8599 return -EACCES; 8600 } 8601 8602 if (!tnum_is_const(reg->var_off)) { 8603 verbose(env, "R%d is not a constant address'\n", regno); 8604 return -EACCES; 8605 } 8606 8607 if (!map->ops->map_direct_value_addr) { 8608 verbose(env, "no direct value access support for this map type\n"); 8609 return -EACCES; 8610 } 8611 8612 err = check_map_access(env, regno, reg->off, 8613 map->value_size - reg->off, false, 8614 ACCESS_HELPER); 8615 if (err) 8616 return err; 8617 8618 map_off = reg->off + reg->var_off.value; 8619 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8620 if (err) { 8621 verbose(env, "direct value access on string failed\n"); 8622 return err; 8623 } 8624 8625 str_ptr = (char *)(long)(map_addr); 8626 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8627 verbose(env, "string is not zero-terminated\n"); 8628 return -EINVAL; 8629 } 8630 return 0; 8631 } 8632 8633 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8634 struct bpf_call_arg_meta *meta, 8635 const struct bpf_func_proto *fn, 8636 int insn_idx) 8637 { 8638 u32 regno = BPF_REG_1 + arg; 8639 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8640 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8641 enum bpf_reg_type type = reg->type; 8642 u32 *arg_btf_id = NULL; 8643 int err = 0; 8644 8645 if (arg_type == ARG_DONTCARE) 8646 return 0; 8647 8648 err = check_reg_arg(env, regno, SRC_OP); 8649 if (err) 8650 return err; 8651 8652 if (arg_type == ARG_ANYTHING) { 8653 if (is_pointer_value(env, regno)) { 8654 verbose(env, "R%d leaks addr into helper function\n", 8655 regno); 8656 return -EACCES; 8657 } 8658 return 0; 8659 } 8660 8661 if (type_is_pkt_pointer(type) && 8662 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8663 verbose(env, "helper access to the packet is not allowed\n"); 8664 return -EACCES; 8665 } 8666 8667 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8668 err = resolve_map_arg_type(env, meta, &arg_type); 8669 if (err) 8670 return err; 8671 } 8672 8673 if (register_is_null(reg) && type_may_be_null(arg_type)) 8674 /* A NULL register has a SCALAR_VALUE type, so skip 8675 * type checking. 8676 */ 8677 goto skip_type_check; 8678 8679 /* arg_btf_id and arg_size are in a union. */ 8680 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8681 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8682 arg_btf_id = fn->arg_btf_id[arg]; 8683 8684 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8685 if (err) 8686 return err; 8687 8688 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8689 if (err) 8690 return err; 8691 8692 skip_type_check: 8693 if (arg_type_is_release(arg_type)) { 8694 if (arg_type_is_dynptr(arg_type)) { 8695 struct bpf_func_state *state = func(env, reg); 8696 int spi; 8697 8698 /* Only dynptr created on stack can be released, thus 8699 * the get_spi and stack state checks for spilled_ptr 8700 * should only be done before process_dynptr_func for 8701 * PTR_TO_STACK. 8702 */ 8703 if (reg->type == PTR_TO_STACK) { 8704 spi = dynptr_get_spi(env, reg); 8705 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8706 verbose(env, "arg %d is an unacquired reference\n", regno); 8707 return -EINVAL; 8708 } 8709 } else { 8710 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8711 return -EINVAL; 8712 } 8713 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8714 verbose(env, "R%d must be referenced when passed to release function\n", 8715 regno); 8716 return -EINVAL; 8717 } 8718 if (meta->release_regno) { 8719 verbose(env, "verifier internal error: more than one release argument\n"); 8720 return -EFAULT; 8721 } 8722 meta->release_regno = regno; 8723 } 8724 8725 if (reg->ref_obj_id) { 8726 if (meta->ref_obj_id) { 8727 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8728 regno, reg->ref_obj_id, 8729 meta->ref_obj_id); 8730 return -EFAULT; 8731 } 8732 meta->ref_obj_id = reg->ref_obj_id; 8733 } 8734 8735 switch (base_type(arg_type)) { 8736 case ARG_CONST_MAP_PTR: 8737 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8738 if (meta->map_ptr) { 8739 /* Use map_uid (which is unique id of inner map) to reject: 8740 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8741 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8742 * if (inner_map1 && inner_map2) { 8743 * timer = bpf_map_lookup_elem(inner_map1); 8744 * if (timer) 8745 * // mismatch would have been allowed 8746 * bpf_timer_init(timer, inner_map2); 8747 * } 8748 * 8749 * Comparing map_ptr is enough to distinguish normal and outer maps. 8750 */ 8751 if (meta->map_ptr != reg->map_ptr || 8752 meta->map_uid != reg->map_uid) { 8753 verbose(env, 8754 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8755 meta->map_uid, reg->map_uid); 8756 return -EINVAL; 8757 } 8758 } 8759 meta->map_ptr = reg->map_ptr; 8760 meta->map_uid = reg->map_uid; 8761 break; 8762 case ARG_PTR_TO_MAP_KEY: 8763 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8764 * check that [key, key + map->key_size) are within 8765 * stack limits and initialized 8766 */ 8767 if (!meta->map_ptr) { 8768 /* in function declaration map_ptr must come before 8769 * map_key, so that it's verified and known before 8770 * we have to check map_key here. Otherwise it means 8771 * that kernel subsystem misconfigured verifier 8772 */ 8773 verbose(env, "invalid map_ptr to access map->key\n"); 8774 return -EACCES; 8775 } 8776 err = check_helper_mem_access(env, regno, 8777 meta->map_ptr->key_size, false, 8778 NULL); 8779 break; 8780 case ARG_PTR_TO_MAP_VALUE: 8781 if (type_may_be_null(arg_type) && register_is_null(reg)) 8782 return 0; 8783 8784 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8785 * check [value, value + map->value_size) validity 8786 */ 8787 if (!meta->map_ptr) { 8788 /* kernel subsystem misconfigured verifier */ 8789 verbose(env, "invalid map_ptr to access map->value\n"); 8790 return -EACCES; 8791 } 8792 meta->raw_mode = arg_type & MEM_UNINIT; 8793 err = check_helper_mem_access(env, regno, 8794 meta->map_ptr->value_size, false, 8795 meta); 8796 break; 8797 case ARG_PTR_TO_PERCPU_BTF_ID: 8798 if (!reg->btf_id) { 8799 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8800 return -EACCES; 8801 } 8802 meta->ret_btf = reg->btf; 8803 meta->ret_btf_id = reg->btf_id; 8804 break; 8805 case ARG_PTR_TO_SPIN_LOCK: 8806 if (in_rbtree_lock_required_cb(env)) { 8807 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8808 return -EACCES; 8809 } 8810 if (meta->func_id == BPF_FUNC_spin_lock) { 8811 err = process_spin_lock(env, regno, true); 8812 if (err) 8813 return err; 8814 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8815 err = process_spin_lock(env, regno, false); 8816 if (err) 8817 return err; 8818 } else { 8819 verbose(env, "verifier internal error\n"); 8820 return -EFAULT; 8821 } 8822 break; 8823 case ARG_PTR_TO_TIMER: 8824 err = process_timer_func(env, regno, meta); 8825 if (err) 8826 return err; 8827 break; 8828 case ARG_PTR_TO_FUNC: 8829 meta->subprogno = reg->subprogno; 8830 break; 8831 case ARG_PTR_TO_MEM: 8832 /* The access to this pointer is only checked when we hit the 8833 * next is_mem_size argument below. 8834 */ 8835 meta->raw_mode = arg_type & MEM_UNINIT; 8836 if (arg_type & MEM_FIXED_SIZE) { 8837 err = check_helper_mem_access(env, regno, 8838 fn->arg_size[arg], false, 8839 meta); 8840 } 8841 break; 8842 case ARG_CONST_SIZE: 8843 err = check_mem_size_reg(env, reg, regno, false, meta); 8844 break; 8845 case ARG_CONST_SIZE_OR_ZERO: 8846 err = check_mem_size_reg(env, reg, regno, true, meta); 8847 break; 8848 case ARG_PTR_TO_DYNPTR: 8849 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8850 if (err) 8851 return err; 8852 break; 8853 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8854 if (!tnum_is_const(reg->var_off)) { 8855 verbose(env, "R%d is not a known constant'\n", 8856 regno); 8857 return -EACCES; 8858 } 8859 meta->mem_size = reg->var_off.value; 8860 err = mark_chain_precision(env, regno); 8861 if (err) 8862 return err; 8863 break; 8864 case ARG_PTR_TO_INT: 8865 case ARG_PTR_TO_LONG: 8866 { 8867 int size = int_ptr_type_to_size(arg_type); 8868 8869 err = check_helper_mem_access(env, regno, size, false, meta); 8870 if (err) 8871 return err; 8872 err = check_ptr_alignment(env, reg, 0, size, true); 8873 break; 8874 } 8875 case ARG_PTR_TO_CONST_STR: 8876 { 8877 err = check_reg_const_str(env, reg, regno); 8878 if (err) 8879 return err; 8880 break; 8881 } 8882 case ARG_PTR_TO_KPTR: 8883 err = process_kptr_func(env, regno, meta); 8884 if (err) 8885 return err; 8886 break; 8887 } 8888 8889 return err; 8890 } 8891 8892 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8893 { 8894 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8895 enum bpf_prog_type type = resolve_prog_type(env->prog); 8896 8897 if (func_id != BPF_FUNC_map_update_elem && 8898 func_id != BPF_FUNC_map_delete_elem) 8899 return false; 8900 8901 /* It's not possible to get access to a locked struct sock in these 8902 * contexts, so updating is safe. 8903 */ 8904 switch (type) { 8905 case BPF_PROG_TYPE_TRACING: 8906 if (eatype == BPF_TRACE_ITER) 8907 return true; 8908 break; 8909 case BPF_PROG_TYPE_SOCK_OPS: 8910 /* map_update allowed only via dedicated helpers with event type checks */ 8911 if (func_id == BPF_FUNC_map_delete_elem) 8912 return true; 8913 break; 8914 case BPF_PROG_TYPE_SOCKET_FILTER: 8915 case BPF_PROG_TYPE_SCHED_CLS: 8916 case BPF_PROG_TYPE_SCHED_ACT: 8917 case BPF_PROG_TYPE_XDP: 8918 case BPF_PROG_TYPE_SK_REUSEPORT: 8919 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8920 case BPF_PROG_TYPE_SK_LOOKUP: 8921 return true; 8922 default: 8923 break; 8924 } 8925 8926 verbose(env, "cannot update sockmap in this context\n"); 8927 return false; 8928 } 8929 8930 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8931 { 8932 return env->prog->jit_requested && 8933 bpf_jit_supports_subprog_tailcalls(); 8934 } 8935 8936 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8937 struct bpf_map *map, int func_id) 8938 { 8939 if (!map) 8940 return 0; 8941 8942 /* We need a two way check, first is from map perspective ... */ 8943 switch (map->map_type) { 8944 case BPF_MAP_TYPE_PROG_ARRAY: 8945 if (func_id != BPF_FUNC_tail_call) 8946 goto error; 8947 break; 8948 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8949 if (func_id != BPF_FUNC_perf_event_read && 8950 func_id != BPF_FUNC_perf_event_output && 8951 func_id != BPF_FUNC_skb_output && 8952 func_id != BPF_FUNC_perf_event_read_value && 8953 func_id != BPF_FUNC_xdp_output) 8954 goto error; 8955 break; 8956 case BPF_MAP_TYPE_RINGBUF: 8957 if (func_id != BPF_FUNC_ringbuf_output && 8958 func_id != BPF_FUNC_ringbuf_reserve && 8959 func_id != BPF_FUNC_ringbuf_query && 8960 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8961 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8962 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8963 goto error; 8964 break; 8965 case BPF_MAP_TYPE_USER_RINGBUF: 8966 if (func_id != BPF_FUNC_user_ringbuf_drain) 8967 goto error; 8968 break; 8969 case BPF_MAP_TYPE_STACK_TRACE: 8970 if (func_id != BPF_FUNC_get_stackid) 8971 goto error; 8972 break; 8973 case BPF_MAP_TYPE_CGROUP_ARRAY: 8974 if (func_id != BPF_FUNC_skb_under_cgroup && 8975 func_id != BPF_FUNC_current_task_under_cgroup) 8976 goto error; 8977 break; 8978 case BPF_MAP_TYPE_CGROUP_STORAGE: 8979 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8980 if (func_id != BPF_FUNC_get_local_storage) 8981 goto error; 8982 break; 8983 case BPF_MAP_TYPE_DEVMAP: 8984 case BPF_MAP_TYPE_DEVMAP_HASH: 8985 if (func_id != BPF_FUNC_redirect_map && 8986 func_id != BPF_FUNC_map_lookup_elem) 8987 goto error; 8988 break; 8989 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8990 * appear. 8991 */ 8992 case BPF_MAP_TYPE_CPUMAP: 8993 if (func_id != BPF_FUNC_redirect_map) 8994 goto error; 8995 break; 8996 case BPF_MAP_TYPE_XSKMAP: 8997 if (func_id != BPF_FUNC_redirect_map && 8998 func_id != BPF_FUNC_map_lookup_elem) 8999 goto error; 9000 break; 9001 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9002 case BPF_MAP_TYPE_HASH_OF_MAPS: 9003 if (func_id != BPF_FUNC_map_lookup_elem) 9004 goto error; 9005 break; 9006 case BPF_MAP_TYPE_SOCKMAP: 9007 if (func_id != BPF_FUNC_sk_redirect_map && 9008 func_id != BPF_FUNC_sock_map_update && 9009 func_id != BPF_FUNC_msg_redirect_map && 9010 func_id != BPF_FUNC_sk_select_reuseport && 9011 func_id != BPF_FUNC_map_lookup_elem && 9012 !may_update_sockmap(env, func_id)) 9013 goto error; 9014 break; 9015 case BPF_MAP_TYPE_SOCKHASH: 9016 if (func_id != BPF_FUNC_sk_redirect_hash && 9017 func_id != BPF_FUNC_sock_hash_update && 9018 func_id != BPF_FUNC_msg_redirect_hash && 9019 func_id != BPF_FUNC_sk_select_reuseport && 9020 func_id != BPF_FUNC_map_lookup_elem && 9021 !may_update_sockmap(env, func_id)) 9022 goto error; 9023 break; 9024 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9025 if (func_id != BPF_FUNC_sk_select_reuseport) 9026 goto error; 9027 break; 9028 case BPF_MAP_TYPE_QUEUE: 9029 case BPF_MAP_TYPE_STACK: 9030 if (func_id != BPF_FUNC_map_peek_elem && 9031 func_id != BPF_FUNC_map_pop_elem && 9032 func_id != BPF_FUNC_map_push_elem) 9033 goto error; 9034 break; 9035 case BPF_MAP_TYPE_SK_STORAGE: 9036 if (func_id != BPF_FUNC_sk_storage_get && 9037 func_id != BPF_FUNC_sk_storage_delete && 9038 func_id != BPF_FUNC_kptr_xchg) 9039 goto error; 9040 break; 9041 case BPF_MAP_TYPE_INODE_STORAGE: 9042 if (func_id != BPF_FUNC_inode_storage_get && 9043 func_id != BPF_FUNC_inode_storage_delete && 9044 func_id != BPF_FUNC_kptr_xchg) 9045 goto error; 9046 break; 9047 case BPF_MAP_TYPE_TASK_STORAGE: 9048 if (func_id != BPF_FUNC_task_storage_get && 9049 func_id != BPF_FUNC_task_storage_delete && 9050 func_id != BPF_FUNC_kptr_xchg) 9051 goto error; 9052 break; 9053 case BPF_MAP_TYPE_CGRP_STORAGE: 9054 if (func_id != BPF_FUNC_cgrp_storage_get && 9055 func_id != BPF_FUNC_cgrp_storage_delete && 9056 func_id != BPF_FUNC_kptr_xchg) 9057 goto error; 9058 break; 9059 case BPF_MAP_TYPE_BLOOM_FILTER: 9060 if (func_id != BPF_FUNC_map_peek_elem && 9061 func_id != BPF_FUNC_map_push_elem) 9062 goto error; 9063 break; 9064 default: 9065 break; 9066 } 9067 9068 /* ... and second from the function itself. */ 9069 switch (func_id) { 9070 case BPF_FUNC_tail_call: 9071 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9072 goto error; 9073 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9074 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9075 return -EINVAL; 9076 } 9077 break; 9078 case BPF_FUNC_perf_event_read: 9079 case BPF_FUNC_perf_event_output: 9080 case BPF_FUNC_perf_event_read_value: 9081 case BPF_FUNC_skb_output: 9082 case BPF_FUNC_xdp_output: 9083 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9084 goto error; 9085 break; 9086 case BPF_FUNC_ringbuf_output: 9087 case BPF_FUNC_ringbuf_reserve: 9088 case BPF_FUNC_ringbuf_query: 9089 case BPF_FUNC_ringbuf_reserve_dynptr: 9090 case BPF_FUNC_ringbuf_submit_dynptr: 9091 case BPF_FUNC_ringbuf_discard_dynptr: 9092 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9093 goto error; 9094 break; 9095 case BPF_FUNC_user_ringbuf_drain: 9096 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9097 goto error; 9098 break; 9099 case BPF_FUNC_get_stackid: 9100 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9101 goto error; 9102 break; 9103 case BPF_FUNC_current_task_under_cgroup: 9104 case BPF_FUNC_skb_under_cgroup: 9105 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9106 goto error; 9107 break; 9108 case BPF_FUNC_redirect_map: 9109 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9110 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9111 map->map_type != BPF_MAP_TYPE_CPUMAP && 9112 map->map_type != BPF_MAP_TYPE_XSKMAP) 9113 goto error; 9114 break; 9115 case BPF_FUNC_sk_redirect_map: 9116 case BPF_FUNC_msg_redirect_map: 9117 case BPF_FUNC_sock_map_update: 9118 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9119 goto error; 9120 break; 9121 case BPF_FUNC_sk_redirect_hash: 9122 case BPF_FUNC_msg_redirect_hash: 9123 case BPF_FUNC_sock_hash_update: 9124 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9125 goto error; 9126 break; 9127 case BPF_FUNC_get_local_storage: 9128 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9129 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9130 goto error; 9131 break; 9132 case BPF_FUNC_sk_select_reuseport: 9133 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9134 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9135 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9136 goto error; 9137 break; 9138 case BPF_FUNC_map_pop_elem: 9139 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9140 map->map_type != BPF_MAP_TYPE_STACK) 9141 goto error; 9142 break; 9143 case BPF_FUNC_map_peek_elem: 9144 case BPF_FUNC_map_push_elem: 9145 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9146 map->map_type != BPF_MAP_TYPE_STACK && 9147 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9148 goto error; 9149 break; 9150 case BPF_FUNC_map_lookup_percpu_elem: 9151 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9152 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9153 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9154 goto error; 9155 break; 9156 case BPF_FUNC_sk_storage_get: 9157 case BPF_FUNC_sk_storage_delete: 9158 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9159 goto error; 9160 break; 9161 case BPF_FUNC_inode_storage_get: 9162 case BPF_FUNC_inode_storage_delete: 9163 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9164 goto error; 9165 break; 9166 case BPF_FUNC_task_storage_get: 9167 case BPF_FUNC_task_storage_delete: 9168 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9169 goto error; 9170 break; 9171 case BPF_FUNC_cgrp_storage_get: 9172 case BPF_FUNC_cgrp_storage_delete: 9173 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9174 goto error; 9175 break; 9176 default: 9177 break; 9178 } 9179 9180 return 0; 9181 error: 9182 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9183 map->map_type, func_id_name(func_id), func_id); 9184 return -EINVAL; 9185 } 9186 9187 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9188 { 9189 int count = 0; 9190 9191 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9192 count++; 9193 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9194 count++; 9195 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9196 count++; 9197 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9198 count++; 9199 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9200 count++; 9201 9202 /* We only support one arg being in raw mode at the moment, 9203 * which is sufficient for the helper functions we have 9204 * right now. 9205 */ 9206 return count <= 1; 9207 } 9208 9209 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9210 { 9211 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9212 bool has_size = fn->arg_size[arg] != 0; 9213 bool is_next_size = false; 9214 9215 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9216 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9217 9218 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9219 return is_next_size; 9220 9221 return has_size == is_next_size || is_next_size == is_fixed; 9222 } 9223 9224 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9225 { 9226 /* bpf_xxx(..., buf, len) call will access 'len' 9227 * bytes from memory 'buf'. Both arg types need 9228 * to be paired, so make sure there's no buggy 9229 * helper function specification. 9230 */ 9231 if (arg_type_is_mem_size(fn->arg1_type) || 9232 check_args_pair_invalid(fn, 0) || 9233 check_args_pair_invalid(fn, 1) || 9234 check_args_pair_invalid(fn, 2) || 9235 check_args_pair_invalid(fn, 3) || 9236 check_args_pair_invalid(fn, 4)) 9237 return false; 9238 9239 return true; 9240 } 9241 9242 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9243 { 9244 int i; 9245 9246 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9247 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9248 return !!fn->arg_btf_id[i]; 9249 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9250 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9251 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9252 /* arg_btf_id and arg_size are in a union. */ 9253 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9254 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9255 return false; 9256 } 9257 9258 return true; 9259 } 9260 9261 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9262 { 9263 return check_raw_mode_ok(fn) && 9264 check_arg_pair_ok(fn) && 9265 check_btf_id_ok(fn) ? 0 : -EINVAL; 9266 } 9267 9268 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9269 * are now invalid, so turn them into unknown SCALAR_VALUE. 9270 * 9271 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9272 * since these slices point to packet data. 9273 */ 9274 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9275 { 9276 struct bpf_func_state *state; 9277 struct bpf_reg_state *reg; 9278 9279 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9280 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9281 mark_reg_invalid(env, reg); 9282 })); 9283 } 9284 9285 enum { 9286 AT_PKT_END = -1, 9287 BEYOND_PKT_END = -2, 9288 }; 9289 9290 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9291 { 9292 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9293 struct bpf_reg_state *reg = &state->regs[regn]; 9294 9295 if (reg->type != PTR_TO_PACKET) 9296 /* PTR_TO_PACKET_META is not supported yet */ 9297 return; 9298 9299 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9300 * How far beyond pkt_end it goes is unknown. 9301 * if (!range_open) it's the case of pkt >= pkt_end 9302 * if (range_open) it's the case of pkt > pkt_end 9303 * hence this pointer is at least 1 byte bigger than pkt_end 9304 */ 9305 if (range_open) 9306 reg->range = BEYOND_PKT_END; 9307 else 9308 reg->range = AT_PKT_END; 9309 } 9310 9311 /* The pointer with the specified id has released its reference to kernel 9312 * resources. Identify all copies of the same pointer and clear the reference. 9313 */ 9314 static int release_reference(struct bpf_verifier_env *env, 9315 int ref_obj_id) 9316 { 9317 struct bpf_func_state *state; 9318 struct bpf_reg_state *reg; 9319 int err; 9320 9321 err = release_reference_state(cur_func(env), ref_obj_id); 9322 if (err) 9323 return err; 9324 9325 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9326 if (reg->ref_obj_id == ref_obj_id) 9327 mark_reg_invalid(env, reg); 9328 })); 9329 9330 return 0; 9331 } 9332 9333 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9334 { 9335 struct bpf_func_state *unused; 9336 struct bpf_reg_state *reg; 9337 9338 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9339 if (type_is_non_owning_ref(reg->type)) 9340 mark_reg_invalid(env, reg); 9341 })); 9342 } 9343 9344 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9345 struct bpf_reg_state *regs) 9346 { 9347 int i; 9348 9349 /* after the call registers r0 - r5 were scratched */ 9350 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9351 mark_reg_not_init(env, regs, caller_saved[i]); 9352 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9353 } 9354 } 9355 9356 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9357 struct bpf_func_state *caller, 9358 struct bpf_func_state *callee, 9359 int insn_idx); 9360 9361 static int set_callee_state(struct bpf_verifier_env *env, 9362 struct bpf_func_state *caller, 9363 struct bpf_func_state *callee, int insn_idx); 9364 9365 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9366 set_callee_state_fn set_callee_state_cb, 9367 struct bpf_verifier_state *state) 9368 { 9369 struct bpf_func_state *caller, *callee; 9370 int err; 9371 9372 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9373 verbose(env, "the call stack of %d frames is too deep\n", 9374 state->curframe + 2); 9375 return -E2BIG; 9376 } 9377 9378 if (state->frame[state->curframe + 1]) { 9379 verbose(env, "verifier bug. Frame %d already allocated\n", 9380 state->curframe + 1); 9381 return -EFAULT; 9382 } 9383 9384 caller = state->frame[state->curframe]; 9385 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9386 if (!callee) 9387 return -ENOMEM; 9388 state->frame[state->curframe + 1] = callee; 9389 9390 /* callee cannot access r0, r6 - r9 for reading and has to write 9391 * into its own stack before reading from it. 9392 * callee can read/write into caller's stack 9393 */ 9394 init_func_state(env, callee, 9395 /* remember the callsite, it will be used by bpf_exit */ 9396 callsite, 9397 state->curframe + 1 /* frameno within this callchain */, 9398 subprog /* subprog number within this prog */); 9399 /* Transfer references to the callee */ 9400 err = copy_reference_state(callee, caller); 9401 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9402 if (err) 9403 goto err_out; 9404 9405 /* only increment it after check_reg_arg() finished */ 9406 state->curframe++; 9407 9408 return 0; 9409 9410 err_out: 9411 free_func_state(callee); 9412 state->frame[state->curframe + 1] = NULL; 9413 return err; 9414 } 9415 9416 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9417 const struct btf *btf, 9418 struct bpf_reg_state *regs) 9419 { 9420 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9421 struct bpf_verifier_log *log = &env->log; 9422 u32 i; 9423 int ret; 9424 9425 ret = btf_prepare_func_args(env, subprog); 9426 if (ret) 9427 return ret; 9428 9429 /* check that BTF function arguments match actual types that the 9430 * verifier sees. 9431 */ 9432 for (i = 0; i < sub->arg_cnt; i++) { 9433 u32 regno = i + 1; 9434 struct bpf_reg_state *reg = ®s[regno]; 9435 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9436 9437 if (arg->arg_type == ARG_ANYTHING) { 9438 if (reg->type != SCALAR_VALUE) { 9439 bpf_log(log, "R%d is not a scalar\n", regno); 9440 return -EINVAL; 9441 } 9442 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9443 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9444 if (ret < 0) 9445 return ret; 9446 /* If function expects ctx type in BTF check that caller 9447 * is passing PTR_TO_CTX. 9448 */ 9449 if (reg->type != PTR_TO_CTX) { 9450 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9451 return -EINVAL; 9452 } 9453 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9454 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9455 if (ret < 0) 9456 return ret; 9457 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9458 return -EINVAL; 9459 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9460 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9461 return -EINVAL; 9462 } 9463 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9464 /* 9465 * Can pass any value and the kernel won't crash, but 9466 * only PTR_TO_ARENA or SCALAR make sense. Everything 9467 * else is a bug in the bpf program. Point it out to 9468 * the user at the verification time instead of 9469 * run-time debug nightmare. 9470 */ 9471 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9472 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9473 return -EINVAL; 9474 } 9475 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9476 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9477 if (ret) 9478 return ret; 9479 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9480 struct bpf_call_arg_meta meta; 9481 int err; 9482 9483 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9484 continue; 9485 9486 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9487 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9488 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9489 if (err) 9490 return err; 9491 } else { 9492 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9493 i, arg->arg_type); 9494 return -EFAULT; 9495 } 9496 } 9497 9498 return 0; 9499 } 9500 9501 /* Compare BTF of a function call with given bpf_reg_state. 9502 * Returns: 9503 * EFAULT - there is a verifier bug. Abort verification. 9504 * EINVAL - there is a type mismatch or BTF is not available. 9505 * 0 - BTF matches with what bpf_reg_state expects. 9506 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9507 */ 9508 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9509 struct bpf_reg_state *regs) 9510 { 9511 struct bpf_prog *prog = env->prog; 9512 struct btf *btf = prog->aux->btf; 9513 u32 btf_id; 9514 int err; 9515 9516 if (!prog->aux->func_info) 9517 return -EINVAL; 9518 9519 btf_id = prog->aux->func_info[subprog].type_id; 9520 if (!btf_id) 9521 return -EFAULT; 9522 9523 if (prog->aux->func_info_aux[subprog].unreliable) 9524 return -EINVAL; 9525 9526 err = btf_check_func_arg_match(env, subprog, btf, regs); 9527 /* Compiler optimizations can remove arguments from static functions 9528 * or mismatched type can be passed into a global function. 9529 * In such cases mark the function as unreliable from BTF point of view. 9530 */ 9531 if (err) 9532 prog->aux->func_info_aux[subprog].unreliable = true; 9533 return err; 9534 } 9535 9536 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9537 int insn_idx, int subprog, 9538 set_callee_state_fn set_callee_state_cb) 9539 { 9540 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9541 struct bpf_func_state *caller, *callee; 9542 int err; 9543 9544 caller = state->frame[state->curframe]; 9545 err = btf_check_subprog_call(env, subprog, caller->regs); 9546 if (err == -EFAULT) 9547 return err; 9548 9549 /* set_callee_state is used for direct subprog calls, but we are 9550 * interested in validating only BPF helpers that can call subprogs as 9551 * callbacks 9552 */ 9553 env->subprog_info[subprog].is_cb = true; 9554 if (bpf_pseudo_kfunc_call(insn) && 9555 !is_callback_calling_kfunc(insn->imm)) { 9556 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9557 func_id_name(insn->imm), insn->imm); 9558 return -EFAULT; 9559 } else if (!bpf_pseudo_kfunc_call(insn) && 9560 !is_callback_calling_function(insn->imm)) { /* helper */ 9561 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9562 func_id_name(insn->imm), insn->imm); 9563 return -EFAULT; 9564 } 9565 9566 if (is_async_callback_calling_insn(insn)) { 9567 struct bpf_verifier_state *async_cb; 9568 9569 /* there is no real recursion here. timer and workqueue callbacks are async */ 9570 env->subprog_info[subprog].is_async_cb = true; 9571 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9572 insn_idx, subprog, 9573 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 9574 if (!async_cb) 9575 return -EFAULT; 9576 callee = async_cb->frame[0]; 9577 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9578 9579 /* Convert bpf_timer_set_callback() args into timer callback args */ 9580 err = set_callee_state_cb(env, caller, callee, insn_idx); 9581 if (err) 9582 return err; 9583 9584 return 0; 9585 } 9586 9587 /* for callback functions enqueue entry to callback and 9588 * proceed with next instruction within current frame. 9589 */ 9590 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9591 if (!callback_state) 9592 return -ENOMEM; 9593 9594 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9595 callback_state); 9596 if (err) 9597 return err; 9598 9599 callback_state->callback_unroll_depth++; 9600 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9601 caller->callback_depth = 0; 9602 return 0; 9603 } 9604 9605 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9606 int *insn_idx) 9607 { 9608 struct bpf_verifier_state *state = env->cur_state; 9609 struct bpf_func_state *caller; 9610 int err, subprog, target_insn; 9611 9612 target_insn = *insn_idx + insn->imm + 1; 9613 subprog = find_subprog(env, target_insn); 9614 if (subprog < 0) { 9615 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9616 return -EFAULT; 9617 } 9618 9619 caller = state->frame[state->curframe]; 9620 err = btf_check_subprog_call(env, subprog, caller->regs); 9621 if (err == -EFAULT) 9622 return err; 9623 if (subprog_is_global(env, subprog)) { 9624 const char *sub_name = subprog_name(env, subprog); 9625 9626 /* Only global subprogs cannot be called with a lock held. */ 9627 if (env->cur_state->active_lock.ptr) { 9628 verbose(env, "global function calls are not allowed while holding a lock,\n" 9629 "use static function instead\n"); 9630 return -EINVAL; 9631 } 9632 9633 /* Only global subprogs cannot be called with preemption disabled. */ 9634 if (env->cur_state->active_preempt_lock) { 9635 verbose(env, "global function calls are not allowed with preemption disabled,\n" 9636 "use static function instead\n"); 9637 return -EINVAL; 9638 } 9639 9640 if (err) { 9641 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9642 subprog, sub_name); 9643 return err; 9644 } 9645 9646 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9647 subprog, sub_name); 9648 /* mark global subprog for verifying after main prog */ 9649 subprog_aux(env, subprog)->called = true; 9650 clear_caller_saved_regs(env, caller->regs); 9651 9652 /* All global functions return a 64-bit SCALAR_VALUE */ 9653 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9654 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9655 9656 /* continue with next insn after call */ 9657 return 0; 9658 } 9659 9660 /* for regular function entry setup new frame and continue 9661 * from that frame. 9662 */ 9663 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9664 if (err) 9665 return err; 9666 9667 clear_caller_saved_regs(env, caller->regs); 9668 9669 /* and go analyze first insn of the callee */ 9670 *insn_idx = env->subprog_info[subprog].start - 1; 9671 9672 if (env->log.level & BPF_LOG_LEVEL) { 9673 verbose(env, "caller:\n"); 9674 print_verifier_state(env, caller, true); 9675 verbose(env, "callee:\n"); 9676 print_verifier_state(env, state->frame[state->curframe], true); 9677 } 9678 9679 return 0; 9680 } 9681 9682 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9683 struct bpf_func_state *caller, 9684 struct bpf_func_state *callee) 9685 { 9686 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9687 * void *callback_ctx, u64 flags); 9688 * callback_fn(struct bpf_map *map, void *key, void *value, 9689 * void *callback_ctx); 9690 */ 9691 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9692 9693 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9694 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9695 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9696 9697 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9698 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9699 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9700 9701 /* pointer to stack or null */ 9702 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9703 9704 /* unused */ 9705 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9706 return 0; 9707 } 9708 9709 static int set_callee_state(struct bpf_verifier_env *env, 9710 struct bpf_func_state *caller, 9711 struct bpf_func_state *callee, int insn_idx) 9712 { 9713 int i; 9714 9715 /* copy r1 - r5 args that callee can access. The copy includes parent 9716 * pointers, which connects us up to the liveness chain 9717 */ 9718 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9719 callee->regs[i] = caller->regs[i]; 9720 return 0; 9721 } 9722 9723 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9724 struct bpf_func_state *caller, 9725 struct bpf_func_state *callee, 9726 int insn_idx) 9727 { 9728 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9729 struct bpf_map *map; 9730 int err; 9731 9732 /* valid map_ptr and poison value does not matter */ 9733 map = insn_aux->map_ptr_state.map_ptr; 9734 if (!map->ops->map_set_for_each_callback_args || 9735 !map->ops->map_for_each_callback) { 9736 verbose(env, "callback function not allowed for map\n"); 9737 return -ENOTSUPP; 9738 } 9739 9740 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9741 if (err) 9742 return err; 9743 9744 callee->in_callback_fn = true; 9745 callee->callback_ret_range = retval_range(0, 1); 9746 return 0; 9747 } 9748 9749 static int set_loop_callback_state(struct bpf_verifier_env *env, 9750 struct bpf_func_state *caller, 9751 struct bpf_func_state *callee, 9752 int insn_idx) 9753 { 9754 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9755 * u64 flags); 9756 * callback_fn(u32 index, void *callback_ctx); 9757 */ 9758 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9759 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9760 9761 /* unused */ 9762 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9763 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9764 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9765 9766 callee->in_callback_fn = true; 9767 callee->callback_ret_range = retval_range(0, 1); 9768 return 0; 9769 } 9770 9771 static int set_timer_callback_state(struct bpf_verifier_env *env, 9772 struct bpf_func_state *caller, 9773 struct bpf_func_state *callee, 9774 int insn_idx) 9775 { 9776 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9777 9778 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9779 * callback_fn(struct bpf_map *map, void *key, void *value); 9780 */ 9781 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9782 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9783 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9784 9785 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9786 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9787 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9788 9789 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9790 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9791 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9792 9793 /* unused */ 9794 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9795 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9796 callee->in_async_callback_fn = true; 9797 callee->callback_ret_range = retval_range(0, 1); 9798 return 0; 9799 } 9800 9801 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9802 struct bpf_func_state *caller, 9803 struct bpf_func_state *callee, 9804 int insn_idx) 9805 { 9806 /* bpf_find_vma(struct task_struct *task, u64 addr, 9807 * void *callback_fn, void *callback_ctx, u64 flags) 9808 * (callback_fn)(struct task_struct *task, 9809 * struct vm_area_struct *vma, void *callback_ctx); 9810 */ 9811 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9812 9813 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9814 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9815 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9816 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9817 9818 /* pointer to stack or null */ 9819 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9820 9821 /* unused */ 9822 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9823 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9824 callee->in_callback_fn = true; 9825 callee->callback_ret_range = retval_range(0, 1); 9826 return 0; 9827 } 9828 9829 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9830 struct bpf_func_state *caller, 9831 struct bpf_func_state *callee, 9832 int insn_idx) 9833 { 9834 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9835 * callback_ctx, u64 flags); 9836 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9837 */ 9838 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9839 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9840 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9841 9842 /* unused */ 9843 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9844 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9845 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9846 9847 callee->in_callback_fn = true; 9848 callee->callback_ret_range = retval_range(0, 1); 9849 return 0; 9850 } 9851 9852 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9853 struct bpf_func_state *caller, 9854 struct bpf_func_state *callee, 9855 int insn_idx) 9856 { 9857 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9858 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9859 * 9860 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9861 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9862 * by this point, so look at 'root' 9863 */ 9864 struct btf_field *field; 9865 9866 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9867 BPF_RB_ROOT); 9868 if (!field || !field->graph_root.value_btf_id) 9869 return -EFAULT; 9870 9871 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9872 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9873 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9874 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9875 9876 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9877 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9878 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9879 callee->in_callback_fn = true; 9880 callee->callback_ret_range = retval_range(0, 1); 9881 return 0; 9882 } 9883 9884 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9885 9886 /* Are we currently verifying the callback for a rbtree helper that must 9887 * be called with lock held? If so, no need to complain about unreleased 9888 * lock 9889 */ 9890 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9891 { 9892 struct bpf_verifier_state *state = env->cur_state; 9893 struct bpf_insn *insn = env->prog->insnsi; 9894 struct bpf_func_state *callee; 9895 int kfunc_btf_id; 9896 9897 if (!state->curframe) 9898 return false; 9899 9900 callee = state->frame[state->curframe]; 9901 9902 if (!callee->in_callback_fn) 9903 return false; 9904 9905 kfunc_btf_id = insn[callee->callsite].imm; 9906 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9907 } 9908 9909 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9910 { 9911 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9912 } 9913 9914 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9915 { 9916 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9917 struct bpf_func_state *caller, *callee; 9918 struct bpf_reg_state *r0; 9919 bool in_callback_fn; 9920 int err; 9921 9922 callee = state->frame[state->curframe]; 9923 r0 = &callee->regs[BPF_REG_0]; 9924 if (r0->type == PTR_TO_STACK) { 9925 /* technically it's ok to return caller's stack pointer 9926 * (or caller's caller's pointer) back to the caller, 9927 * since these pointers are valid. Only current stack 9928 * pointer will be invalid as soon as function exits, 9929 * but let's be conservative 9930 */ 9931 verbose(env, "cannot return stack pointer to the caller\n"); 9932 return -EINVAL; 9933 } 9934 9935 caller = state->frame[state->curframe - 1]; 9936 if (callee->in_callback_fn) { 9937 if (r0->type != SCALAR_VALUE) { 9938 verbose(env, "R0 not a scalar value\n"); 9939 return -EACCES; 9940 } 9941 9942 /* we are going to rely on register's precise value */ 9943 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9944 err = err ?: mark_chain_precision(env, BPF_REG_0); 9945 if (err) 9946 return err; 9947 9948 /* enforce R0 return value range */ 9949 if (!retval_range_within(callee->callback_ret_range, r0)) { 9950 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9951 "At callback return", "R0"); 9952 return -EINVAL; 9953 } 9954 if (!calls_callback(env, callee->callsite)) { 9955 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9956 *insn_idx, callee->callsite); 9957 return -EFAULT; 9958 } 9959 } else { 9960 /* return to the caller whatever r0 had in the callee */ 9961 caller->regs[BPF_REG_0] = *r0; 9962 } 9963 9964 /* callback_fn frame should have released its own additions to parent's 9965 * reference state at this point, or check_reference_leak would 9966 * complain, hence it must be the same as the caller. There is no need 9967 * to copy it back. 9968 */ 9969 if (!callee->in_callback_fn) { 9970 /* Transfer references to the caller */ 9971 err = copy_reference_state(caller, callee); 9972 if (err) 9973 return err; 9974 } 9975 9976 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9977 * there function call logic would reschedule callback visit. If iteration 9978 * converges is_state_visited() would prune that visit eventually. 9979 */ 9980 in_callback_fn = callee->in_callback_fn; 9981 if (in_callback_fn) 9982 *insn_idx = callee->callsite; 9983 else 9984 *insn_idx = callee->callsite + 1; 9985 9986 if (env->log.level & BPF_LOG_LEVEL) { 9987 verbose(env, "returning from callee:\n"); 9988 print_verifier_state(env, callee, true); 9989 verbose(env, "to caller at %d:\n", *insn_idx); 9990 print_verifier_state(env, caller, true); 9991 } 9992 /* clear everything in the callee. In case of exceptional exits using 9993 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9994 free_func_state(callee); 9995 state->frame[state->curframe--] = NULL; 9996 9997 /* for callbacks widen imprecise scalars to make programs like below verify: 9998 * 9999 * struct ctx { int i; } 10000 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 10001 * ... 10002 * struct ctx = { .i = 0; } 10003 * bpf_loop(100, cb, &ctx, 0); 10004 * 10005 * This is similar to what is done in process_iter_next_call() for open 10006 * coded iterators. 10007 */ 10008 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10009 if (prev_st) { 10010 err = widen_imprecise_scalars(env, prev_st, state); 10011 if (err) 10012 return err; 10013 } 10014 return 0; 10015 } 10016 10017 static int do_refine_retval_range(struct bpf_verifier_env *env, 10018 struct bpf_reg_state *regs, int ret_type, 10019 int func_id, 10020 struct bpf_call_arg_meta *meta) 10021 { 10022 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10023 10024 if (ret_type != RET_INTEGER) 10025 return 0; 10026 10027 switch (func_id) { 10028 case BPF_FUNC_get_stack: 10029 case BPF_FUNC_get_task_stack: 10030 case BPF_FUNC_probe_read_str: 10031 case BPF_FUNC_probe_read_kernel_str: 10032 case BPF_FUNC_probe_read_user_str: 10033 ret_reg->smax_value = meta->msize_max_value; 10034 ret_reg->s32_max_value = meta->msize_max_value; 10035 ret_reg->smin_value = -MAX_ERRNO; 10036 ret_reg->s32_min_value = -MAX_ERRNO; 10037 reg_bounds_sync(ret_reg); 10038 break; 10039 case BPF_FUNC_get_smp_processor_id: 10040 ret_reg->umax_value = nr_cpu_ids - 1; 10041 ret_reg->u32_max_value = nr_cpu_ids - 1; 10042 ret_reg->smax_value = nr_cpu_ids - 1; 10043 ret_reg->s32_max_value = nr_cpu_ids - 1; 10044 ret_reg->umin_value = 0; 10045 ret_reg->u32_min_value = 0; 10046 ret_reg->smin_value = 0; 10047 ret_reg->s32_min_value = 0; 10048 reg_bounds_sync(ret_reg); 10049 break; 10050 } 10051 10052 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10053 } 10054 10055 static int 10056 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10057 int func_id, int insn_idx) 10058 { 10059 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10060 struct bpf_map *map = meta->map_ptr; 10061 10062 if (func_id != BPF_FUNC_tail_call && 10063 func_id != BPF_FUNC_map_lookup_elem && 10064 func_id != BPF_FUNC_map_update_elem && 10065 func_id != BPF_FUNC_map_delete_elem && 10066 func_id != BPF_FUNC_map_push_elem && 10067 func_id != BPF_FUNC_map_pop_elem && 10068 func_id != BPF_FUNC_map_peek_elem && 10069 func_id != BPF_FUNC_for_each_map_elem && 10070 func_id != BPF_FUNC_redirect_map && 10071 func_id != BPF_FUNC_map_lookup_percpu_elem) 10072 return 0; 10073 10074 if (map == NULL) { 10075 verbose(env, "kernel subsystem misconfigured verifier\n"); 10076 return -EINVAL; 10077 } 10078 10079 /* In case of read-only, some additional restrictions 10080 * need to be applied in order to prevent altering the 10081 * state of the map from program side. 10082 */ 10083 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10084 (func_id == BPF_FUNC_map_delete_elem || 10085 func_id == BPF_FUNC_map_update_elem || 10086 func_id == BPF_FUNC_map_push_elem || 10087 func_id == BPF_FUNC_map_pop_elem)) { 10088 verbose(env, "write into map forbidden\n"); 10089 return -EACCES; 10090 } 10091 10092 if (!aux->map_ptr_state.map_ptr) 10093 bpf_map_ptr_store(aux, meta->map_ptr, 10094 !meta->map_ptr->bypass_spec_v1, false); 10095 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10096 bpf_map_ptr_store(aux, meta->map_ptr, 10097 !meta->map_ptr->bypass_spec_v1, true); 10098 return 0; 10099 } 10100 10101 static int 10102 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10103 int func_id, int insn_idx) 10104 { 10105 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10106 struct bpf_reg_state *regs = cur_regs(env), *reg; 10107 struct bpf_map *map = meta->map_ptr; 10108 u64 val, max; 10109 int err; 10110 10111 if (func_id != BPF_FUNC_tail_call) 10112 return 0; 10113 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10114 verbose(env, "kernel subsystem misconfigured verifier\n"); 10115 return -EINVAL; 10116 } 10117 10118 reg = ®s[BPF_REG_3]; 10119 val = reg->var_off.value; 10120 max = map->max_entries; 10121 10122 if (!(is_reg_const(reg, false) && val < max)) { 10123 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10124 return 0; 10125 } 10126 10127 err = mark_chain_precision(env, BPF_REG_3); 10128 if (err) 10129 return err; 10130 if (bpf_map_key_unseen(aux)) 10131 bpf_map_key_store(aux, val); 10132 else if (!bpf_map_key_poisoned(aux) && 10133 bpf_map_key_immediate(aux) != val) 10134 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10135 return 0; 10136 } 10137 10138 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10139 { 10140 struct bpf_func_state *state = cur_func(env); 10141 bool refs_lingering = false; 10142 int i; 10143 10144 if (!exception_exit && state->frameno && !state->in_callback_fn) 10145 return 0; 10146 10147 for (i = 0; i < state->acquired_refs; i++) { 10148 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10149 continue; 10150 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10151 state->refs[i].id, state->refs[i].insn_idx); 10152 refs_lingering = true; 10153 } 10154 return refs_lingering ? -EINVAL : 0; 10155 } 10156 10157 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10158 struct bpf_reg_state *regs) 10159 { 10160 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10161 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10162 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10163 struct bpf_bprintf_data data = {}; 10164 int err, fmt_map_off, num_args; 10165 u64 fmt_addr; 10166 char *fmt; 10167 10168 /* data must be an array of u64 */ 10169 if (data_len_reg->var_off.value % 8) 10170 return -EINVAL; 10171 num_args = data_len_reg->var_off.value / 8; 10172 10173 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10174 * and map_direct_value_addr is set. 10175 */ 10176 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10177 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10178 fmt_map_off); 10179 if (err) { 10180 verbose(env, "verifier bug\n"); 10181 return -EFAULT; 10182 } 10183 fmt = (char *)(long)fmt_addr + fmt_map_off; 10184 10185 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10186 * can focus on validating the format specifiers. 10187 */ 10188 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10189 if (err < 0) 10190 verbose(env, "Invalid format string\n"); 10191 10192 return err; 10193 } 10194 10195 static int check_get_func_ip(struct bpf_verifier_env *env) 10196 { 10197 enum bpf_prog_type type = resolve_prog_type(env->prog); 10198 int func_id = BPF_FUNC_get_func_ip; 10199 10200 if (type == BPF_PROG_TYPE_TRACING) { 10201 if (!bpf_prog_has_trampoline(env->prog)) { 10202 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10203 func_id_name(func_id), func_id); 10204 return -ENOTSUPP; 10205 } 10206 return 0; 10207 } else if (type == BPF_PROG_TYPE_KPROBE) { 10208 return 0; 10209 } 10210 10211 verbose(env, "func %s#%d not supported for program type %d\n", 10212 func_id_name(func_id), func_id, type); 10213 return -ENOTSUPP; 10214 } 10215 10216 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10217 { 10218 return &env->insn_aux_data[env->insn_idx]; 10219 } 10220 10221 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10222 { 10223 struct bpf_reg_state *regs = cur_regs(env); 10224 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10225 bool reg_is_null = register_is_null(reg); 10226 10227 if (reg_is_null) 10228 mark_chain_precision(env, BPF_REG_4); 10229 10230 return reg_is_null; 10231 } 10232 10233 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10234 { 10235 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10236 10237 if (!state->initialized) { 10238 state->initialized = 1; 10239 state->fit_for_inline = loop_flag_is_zero(env); 10240 state->callback_subprogno = subprogno; 10241 return; 10242 } 10243 10244 if (!state->fit_for_inline) 10245 return; 10246 10247 state->fit_for_inline = (loop_flag_is_zero(env) && 10248 state->callback_subprogno == subprogno); 10249 } 10250 10251 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10252 int *insn_idx_p) 10253 { 10254 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10255 bool returns_cpu_specific_alloc_ptr = false; 10256 const struct bpf_func_proto *fn = NULL; 10257 enum bpf_return_type ret_type; 10258 enum bpf_type_flag ret_flag; 10259 struct bpf_reg_state *regs; 10260 struct bpf_call_arg_meta meta; 10261 int insn_idx = *insn_idx_p; 10262 bool changes_data; 10263 int i, err, func_id; 10264 10265 /* find function prototype */ 10266 func_id = insn->imm; 10267 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10268 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10269 func_id); 10270 return -EINVAL; 10271 } 10272 10273 if (env->ops->get_func_proto) 10274 fn = env->ops->get_func_proto(func_id, env->prog); 10275 if (!fn) { 10276 verbose(env, "program of this type cannot use helper %s#%d\n", 10277 func_id_name(func_id), func_id); 10278 return -EINVAL; 10279 } 10280 10281 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10282 if (!env->prog->gpl_compatible && fn->gpl_only) { 10283 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10284 return -EINVAL; 10285 } 10286 10287 if (fn->allowed && !fn->allowed(env->prog)) { 10288 verbose(env, "helper call is not allowed in probe\n"); 10289 return -EINVAL; 10290 } 10291 10292 if (!in_sleepable(env) && fn->might_sleep) { 10293 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10294 return -EINVAL; 10295 } 10296 10297 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10298 changes_data = bpf_helper_changes_pkt_data(fn->func); 10299 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10300 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10301 func_id_name(func_id), func_id); 10302 return -EINVAL; 10303 } 10304 10305 memset(&meta, 0, sizeof(meta)); 10306 meta.pkt_access = fn->pkt_access; 10307 10308 err = check_func_proto(fn, func_id); 10309 if (err) { 10310 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10311 func_id_name(func_id), func_id); 10312 return err; 10313 } 10314 10315 if (env->cur_state->active_rcu_lock) { 10316 if (fn->might_sleep) { 10317 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10318 func_id_name(func_id), func_id); 10319 return -EINVAL; 10320 } 10321 10322 if (in_sleepable(env) && is_storage_get_function(func_id)) 10323 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10324 } 10325 10326 if (env->cur_state->active_preempt_lock) { 10327 if (fn->might_sleep) { 10328 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 10329 func_id_name(func_id), func_id); 10330 return -EINVAL; 10331 } 10332 10333 if (in_sleepable(env) && is_storage_get_function(func_id)) 10334 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10335 } 10336 10337 meta.func_id = func_id; 10338 /* check args */ 10339 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10340 err = check_func_arg(env, i, &meta, fn, insn_idx); 10341 if (err) 10342 return err; 10343 } 10344 10345 err = record_func_map(env, &meta, func_id, insn_idx); 10346 if (err) 10347 return err; 10348 10349 err = record_func_key(env, &meta, func_id, insn_idx); 10350 if (err) 10351 return err; 10352 10353 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10354 * is inferred from register state. 10355 */ 10356 for (i = 0; i < meta.access_size; i++) { 10357 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10358 BPF_WRITE, -1, false, false); 10359 if (err) 10360 return err; 10361 } 10362 10363 regs = cur_regs(env); 10364 10365 if (meta.release_regno) { 10366 err = -EINVAL; 10367 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10368 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10369 * is safe to do directly. 10370 */ 10371 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10372 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10373 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10374 return -EFAULT; 10375 } 10376 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10377 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10378 u32 ref_obj_id = meta.ref_obj_id; 10379 bool in_rcu = in_rcu_cs(env); 10380 struct bpf_func_state *state; 10381 struct bpf_reg_state *reg; 10382 10383 err = release_reference_state(cur_func(env), ref_obj_id); 10384 if (!err) { 10385 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10386 if (reg->ref_obj_id == ref_obj_id) { 10387 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10388 reg->ref_obj_id = 0; 10389 reg->type &= ~MEM_ALLOC; 10390 reg->type |= MEM_RCU; 10391 } else { 10392 mark_reg_invalid(env, reg); 10393 } 10394 } 10395 })); 10396 } 10397 } else if (meta.ref_obj_id) { 10398 err = release_reference(env, meta.ref_obj_id); 10399 } else if (register_is_null(®s[meta.release_regno])) { 10400 /* meta.ref_obj_id can only be 0 if register that is meant to be 10401 * released is NULL, which must be > R0. 10402 */ 10403 err = 0; 10404 } 10405 if (err) { 10406 verbose(env, "func %s#%d reference has not been acquired before\n", 10407 func_id_name(func_id), func_id); 10408 return err; 10409 } 10410 } 10411 10412 switch (func_id) { 10413 case BPF_FUNC_tail_call: 10414 err = check_reference_leak(env, false); 10415 if (err) { 10416 verbose(env, "tail_call would lead to reference leak\n"); 10417 return err; 10418 } 10419 break; 10420 case BPF_FUNC_get_local_storage: 10421 /* check that flags argument in get_local_storage(map, flags) is 0, 10422 * this is required because get_local_storage() can't return an error. 10423 */ 10424 if (!register_is_null(®s[BPF_REG_2])) { 10425 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10426 return -EINVAL; 10427 } 10428 break; 10429 case BPF_FUNC_for_each_map_elem: 10430 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10431 set_map_elem_callback_state); 10432 break; 10433 case BPF_FUNC_timer_set_callback: 10434 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10435 set_timer_callback_state); 10436 break; 10437 case BPF_FUNC_find_vma: 10438 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10439 set_find_vma_callback_state); 10440 break; 10441 case BPF_FUNC_snprintf: 10442 err = check_bpf_snprintf_call(env, regs); 10443 break; 10444 case BPF_FUNC_loop: 10445 update_loop_inline_state(env, meta.subprogno); 10446 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10447 * is finished, thus mark it precise. 10448 */ 10449 err = mark_chain_precision(env, BPF_REG_1); 10450 if (err) 10451 return err; 10452 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10453 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10454 set_loop_callback_state); 10455 } else { 10456 cur_func(env)->callback_depth = 0; 10457 if (env->log.level & BPF_LOG_LEVEL2) 10458 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10459 env->cur_state->curframe); 10460 } 10461 break; 10462 case BPF_FUNC_dynptr_from_mem: 10463 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10464 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10465 reg_type_str(env, regs[BPF_REG_1].type)); 10466 return -EACCES; 10467 } 10468 break; 10469 case BPF_FUNC_set_retval: 10470 if (prog_type == BPF_PROG_TYPE_LSM && 10471 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10472 if (!env->prog->aux->attach_func_proto->type) { 10473 /* Make sure programs that attach to void 10474 * hooks don't try to modify return value. 10475 */ 10476 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10477 return -EINVAL; 10478 } 10479 } 10480 break; 10481 case BPF_FUNC_dynptr_data: 10482 { 10483 struct bpf_reg_state *reg; 10484 int id, ref_obj_id; 10485 10486 reg = get_dynptr_arg_reg(env, fn, regs); 10487 if (!reg) 10488 return -EFAULT; 10489 10490 10491 if (meta.dynptr_id) { 10492 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10493 return -EFAULT; 10494 } 10495 if (meta.ref_obj_id) { 10496 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10497 return -EFAULT; 10498 } 10499 10500 id = dynptr_id(env, reg); 10501 if (id < 0) { 10502 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10503 return id; 10504 } 10505 10506 ref_obj_id = dynptr_ref_obj_id(env, reg); 10507 if (ref_obj_id < 0) { 10508 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10509 return ref_obj_id; 10510 } 10511 10512 meta.dynptr_id = id; 10513 meta.ref_obj_id = ref_obj_id; 10514 10515 break; 10516 } 10517 case BPF_FUNC_dynptr_write: 10518 { 10519 enum bpf_dynptr_type dynptr_type; 10520 struct bpf_reg_state *reg; 10521 10522 reg = get_dynptr_arg_reg(env, fn, regs); 10523 if (!reg) 10524 return -EFAULT; 10525 10526 dynptr_type = dynptr_get_type(env, reg); 10527 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10528 return -EFAULT; 10529 10530 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10531 /* this will trigger clear_all_pkt_pointers(), which will 10532 * invalidate all dynptr slices associated with the skb 10533 */ 10534 changes_data = true; 10535 10536 break; 10537 } 10538 case BPF_FUNC_per_cpu_ptr: 10539 case BPF_FUNC_this_cpu_ptr: 10540 { 10541 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10542 const struct btf_type *type; 10543 10544 if (reg->type & MEM_RCU) { 10545 type = btf_type_by_id(reg->btf, reg->btf_id); 10546 if (!type || !btf_type_is_struct(type)) { 10547 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10548 return -EFAULT; 10549 } 10550 returns_cpu_specific_alloc_ptr = true; 10551 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10552 } 10553 break; 10554 } 10555 case BPF_FUNC_user_ringbuf_drain: 10556 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10557 set_user_ringbuf_callback_state); 10558 break; 10559 } 10560 10561 if (err) 10562 return err; 10563 10564 /* reset caller saved regs */ 10565 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10566 mark_reg_not_init(env, regs, caller_saved[i]); 10567 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10568 } 10569 10570 /* helper call returns 64-bit value. */ 10571 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10572 10573 /* update return register (already marked as written above) */ 10574 ret_type = fn->ret_type; 10575 ret_flag = type_flag(ret_type); 10576 10577 switch (base_type(ret_type)) { 10578 case RET_INTEGER: 10579 /* sets type to SCALAR_VALUE */ 10580 mark_reg_unknown(env, regs, BPF_REG_0); 10581 break; 10582 case RET_VOID: 10583 regs[BPF_REG_0].type = NOT_INIT; 10584 break; 10585 case RET_PTR_TO_MAP_VALUE: 10586 /* There is no offset yet applied, variable or fixed */ 10587 mark_reg_known_zero(env, regs, BPF_REG_0); 10588 /* remember map_ptr, so that check_map_access() 10589 * can check 'value_size' boundary of memory access 10590 * to map element returned from bpf_map_lookup_elem() 10591 */ 10592 if (meta.map_ptr == NULL) { 10593 verbose(env, 10594 "kernel subsystem misconfigured verifier\n"); 10595 return -EINVAL; 10596 } 10597 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10598 regs[BPF_REG_0].map_uid = meta.map_uid; 10599 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10600 if (!type_may_be_null(ret_type) && 10601 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10602 regs[BPF_REG_0].id = ++env->id_gen; 10603 } 10604 break; 10605 case RET_PTR_TO_SOCKET: 10606 mark_reg_known_zero(env, regs, BPF_REG_0); 10607 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10608 break; 10609 case RET_PTR_TO_SOCK_COMMON: 10610 mark_reg_known_zero(env, regs, BPF_REG_0); 10611 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10612 break; 10613 case RET_PTR_TO_TCP_SOCK: 10614 mark_reg_known_zero(env, regs, BPF_REG_0); 10615 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10616 break; 10617 case RET_PTR_TO_MEM: 10618 mark_reg_known_zero(env, regs, BPF_REG_0); 10619 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10620 regs[BPF_REG_0].mem_size = meta.mem_size; 10621 break; 10622 case RET_PTR_TO_MEM_OR_BTF_ID: 10623 { 10624 const struct btf_type *t; 10625 10626 mark_reg_known_zero(env, regs, BPF_REG_0); 10627 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10628 if (!btf_type_is_struct(t)) { 10629 u32 tsize; 10630 const struct btf_type *ret; 10631 const char *tname; 10632 10633 /* resolve the type size of ksym. */ 10634 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10635 if (IS_ERR(ret)) { 10636 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10637 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10638 tname, PTR_ERR(ret)); 10639 return -EINVAL; 10640 } 10641 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10642 regs[BPF_REG_0].mem_size = tsize; 10643 } else { 10644 if (returns_cpu_specific_alloc_ptr) { 10645 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10646 } else { 10647 /* MEM_RDONLY may be carried from ret_flag, but it 10648 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10649 * it will confuse the check of PTR_TO_BTF_ID in 10650 * check_mem_access(). 10651 */ 10652 ret_flag &= ~MEM_RDONLY; 10653 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10654 } 10655 10656 regs[BPF_REG_0].btf = meta.ret_btf; 10657 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10658 } 10659 break; 10660 } 10661 case RET_PTR_TO_BTF_ID: 10662 { 10663 struct btf *ret_btf; 10664 int ret_btf_id; 10665 10666 mark_reg_known_zero(env, regs, BPF_REG_0); 10667 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10668 if (func_id == BPF_FUNC_kptr_xchg) { 10669 ret_btf = meta.kptr_field->kptr.btf; 10670 ret_btf_id = meta.kptr_field->kptr.btf_id; 10671 if (!btf_is_kernel(ret_btf)) { 10672 regs[BPF_REG_0].type |= MEM_ALLOC; 10673 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10674 regs[BPF_REG_0].type |= MEM_PERCPU; 10675 } 10676 } else { 10677 if (fn->ret_btf_id == BPF_PTR_POISON) { 10678 verbose(env, "verifier internal error:"); 10679 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10680 func_id_name(func_id)); 10681 return -EINVAL; 10682 } 10683 ret_btf = btf_vmlinux; 10684 ret_btf_id = *fn->ret_btf_id; 10685 } 10686 if (ret_btf_id == 0) { 10687 verbose(env, "invalid return type %u of func %s#%d\n", 10688 base_type(ret_type), func_id_name(func_id), 10689 func_id); 10690 return -EINVAL; 10691 } 10692 regs[BPF_REG_0].btf = ret_btf; 10693 regs[BPF_REG_0].btf_id = ret_btf_id; 10694 break; 10695 } 10696 default: 10697 verbose(env, "unknown return type %u of func %s#%d\n", 10698 base_type(ret_type), func_id_name(func_id), func_id); 10699 return -EINVAL; 10700 } 10701 10702 if (type_may_be_null(regs[BPF_REG_0].type)) 10703 regs[BPF_REG_0].id = ++env->id_gen; 10704 10705 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10706 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10707 func_id_name(func_id), func_id); 10708 return -EFAULT; 10709 } 10710 10711 if (is_dynptr_ref_function(func_id)) 10712 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10713 10714 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10715 /* For release_reference() */ 10716 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10717 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10718 int id = acquire_reference_state(env, insn_idx); 10719 10720 if (id < 0) 10721 return id; 10722 /* For mark_ptr_or_null_reg() */ 10723 regs[BPF_REG_0].id = id; 10724 /* For release_reference() */ 10725 regs[BPF_REG_0].ref_obj_id = id; 10726 } 10727 10728 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10729 if (err) 10730 return err; 10731 10732 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10733 if (err) 10734 return err; 10735 10736 if ((func_id == BPF_FUNC_get_stack || 10737 func_id == BPF_FUNC_get_task_stack) && 10738 !env->prog->has_callchain_buf) { 10739 const char *err_str; 10740 10741 #ifdef CONFIG_PERF_EVENTS 10742 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10743 err_str = "cannot get callchain buffer for func %s#%d\n"; 10744 #else 10745 err = -ENOTSUPP; 10746 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10747 #endif 10748 if (err) { 10749 verbose(env, err_str, func_id_name(func_id), func_id); 10750 return err; 10751 } 10752 10753 env->prog->has_callchain_buf = true; 10754 } 10755 10756 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10757 env->prog->call_get_stack = true; 10758 10759 if (func_id == BPF_FUNC_get_func_ip) { 10760 if (check_get_func_ip(env)) 10761 return -ENOTSUPP; 10762 env->prog->call_get_func_ip = true; 10763 } 10764 10765 if (changes_data) 10766 clear_all_pkt_pointers(env); 10767 return 0; 10768 } 10769 10770 /* mark_btf_func_reg_size() is used when the reg size is determined by 10771 * the BTF func_proto's return value size and argument. 10772 */ 10773 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10774 size_t reg_size) 10775 { 10776 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10777 10778 if (regno == BPF_REG_0) { 10779 /* Function return value */ 10780 reg->live |= REG_LIVE_WRITTEN; 10781 reg->subreg_def = reg_size == sizeof(u64) ? 10782 DEF_NOT_SUBREG : env->insn_idx + 1; 10783 } else { 10784 /* Function argument */ 10785 if (reg_size == sizeof(u64)) { 10786 mark_insn_zext(env, reg); 10787 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10788 } else { 10789 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10790 } 10791 } 10792 } 10793 10794 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10795 { 10796 return meta->kfunc_flags & KF_ACQUIRE; 10797 } 10798 10799 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10800 { 10801 return meta->kfunc_flags & KF_RELEASE; 10802 } 10803 10804 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10805 { 10806 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10807 } 10808 10809 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10810 { 10811 return meta->kfunc_flags & KF_SLEEPABLE; 10812 } 10813 10814 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10815 { 10816 return meta->kfunc_flags & KF_DESTRUCTIVE; 10817 } 10818 10819 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10820 { 10821 return meta->kfunc_flags & KF_RCU; 10822 } 10823 10824 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10825 { 10826 return meta->kfunc_flags & KF_RCU_PROTECTED; 10827 } 10828 10829 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10830 const struct btf_param *arg, 10831 const struct bpf_reg_state *reg) 10832 { 10833 const struct btf_type *t; 10834 10835 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10836 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10837 return false; 10838 10839 return btf_param_match_suffix(btf, arg, "__sz"); 10840 } 10841 10842 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10843 const struct btf_param *arg, 10844 const struct bpf_reg_state *reg) 10845 { 10846 const struct btf_type *t; 10847 10848 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10849 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10850 return false; 10851 10852 return btf_param_match_suffix(btf, arg, "__szk"); 10853 } 10854 10855 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10856 { 10857 return btf_param_match_suffix(btf, arg, "__opt"); 10858 } 10859 10860 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10861 { 10862 return btf_param_match_suffix(btf, arg, "__k"); 10863 } 10864 10865 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10866 { 10867 return btf_param_match_suffix(btf, arg, "__ign"); 10868 } 10869 10870 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10871 { 10872 return btf_param_match_suffix(btf, arg, "__map"); 10873 } 10874 10875 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10876 { 10877 return btf_param_match_suffix(btf, arg, "__alloc"); 10878 } 10879 10880 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10881 { 10882 return btf_param_match_suffix(btf, arg, "__uninit"); 10883 } 10884 10885 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10886 { 10887 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10888 } 10889 10890 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10891 { 10892 return btf_param_match_suffix(btf, arg, "__nullable"); 10893 } 10894 10895 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10896 { 10897 return btf_param_match_suffix(btf, arg, "__str"); 10898 } 10899 10900 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10901 const struct btf_param *arg, 10902 const char *name) 10903 { 10904 int len, target_len = strlen(name); 10905 const char *param_name; 10906 10907 param_name = btf_name_by_offset(btf, arg->name_off); 10908 if (str_is_empty(param_name)) 10909 return false; 10910 len = strlen(param_name); 10911 if (len != target_len) 10912 return false; 10913 if (strcmp(param_name, name)) 10914 return false; 10915 10916 return true; 10917 } 10918 10919 enum { 10920 KF_ARG_DYNPTR_ID, 10921 KF_ARG_LIST_HEAD_ID, 10922 KF_ARG_LIST_NODE_ID, 10923 KF_ARG_RB_ROOT_ID, 10924 KF_ARG_RB_NODE_ID, 10925 KF_ARG_WORKQUEUE_ID, 10926 }; 10927 10928 BTF_ID_LIST(kf_arg_btf_ids) 10929 BTF_ID(struct, bpf_dynptr) 10930 BTF_ID(struct, bpf_list_head) 10931 BTF_ID(struct, bpf_list_node) 10932 BTF_ID(struct, bpf_rb_root) 10933 BTF_ID(struct, bpf_rb_node) 10934 BTF_ID(struct, bpf_wq) 10935 10936 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10937 const struct btf_param *arg, int type) 10938 { 10939 const struct btf_type *t; 10940 u32 res_id; 10941 10942 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10943 if (!t) 10944 return false; 10945 if (!btf_type_is_ptr(t)) 10946 return false; 10947 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10948 if (!t) 10949 return false; 10950 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10951 } 10952 10953 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10954 { 10955 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10956 } 10957 10958 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10959 { 10960 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10961 } 10962 10963 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10964 { 10965 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10966 } 10967 10968 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10969 { 10970 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10971 } 10972 10973 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10974 { 10975 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10976 } 10977 10978 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10979 { 10980 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10981 } 10982 10983 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10984 const struct btf_param *arg) 10985 { 10986 const struct btf_type *t; 10987 10988 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10989 if (!t) 10990 return false; 10991 10992 return true; 10993 } 10994 10995 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10996 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10997 const struct btf *btf, 10998 const struct btf_type *t, int rec) 10999 { 11000 const struct btf_type *member_type; 11001 const struct btf_member *member; 11002 u32 i; 11003 11004 if (!btf_type_is_struct(t)) 11005 return false; 11006 11007 for_each_member(i, t, member) { 11008 const struct btf_array *array; 11009 11010 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11011 if (btf_type_is_struct(member_type)) { 11012 if (rec >= 3) { 11013 verbose(env, "max struct nesting depth exceeded\n"); 11014 return false; 11015 } 11016 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11017 return false; 11018 continue; 11019 } 11020 if (btf_type_is_array(member_type)) { 11021 array = btf_array(member_type); 11022 if (!array->nelems) 11023 return false; 11024 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11025 if (!btf_type_is_scalar(member_type)) 11026 return false; 11027 continue; 11028 } 11029 if (!btf_type_is_scalar(member_type)) 11030 return false; 11031 } 11032 return true; 11033 } 11034 11035 enum kfunc_ptr_arg_type { 11036 KF_ARG_PTR_TO_CTX, 11037 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11038 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11039 KF_ARG_PTR_TO_DYNPTR, 11040 KF_ARG_PTR_TO_ITER, 11041 KF_ARG_PTR_TO_LIST_HEAD, 11042 KF_ARG_PTR_TO_LIST_NODE, 11043 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11044 KF_ARG_PTR_TO_MEM, 11045 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11046 KF_ARG_PTR_TO_CALLBACK, 11047 KF_ARG_PTR_TO_RB_ROOT, 11048 KF_ARG_PTR_TO_RB_NODE, 11049 KF_ARG_PTR_TO_NULL, 11050 KF_ARG_PTR_TO_CONST_STR, 11051 KF_ARG_PTR_TO_MAP, 11052 KF_ARG_PTR_TO_WORKQUEUE, 11053 }; 11054 11055 enum special_kfunc_type { 11056 KF_bpf_obj_new_impl, 11057 KF_bpf_obj_drop_impl, 11058 KF_bpf_refcount_acquire_impl, 11059 KF_bpf_list_push_front_impl, 11060 KF_bpf_list_push_back_impl, 11061 KF_bpf_list_pop_front, 11062 KF_bpf_list_pop_back, 11063 KF_bpf_cast_to_kern_ctx, 11064 KF_bpf_rdonly_cast, 11065 KF_bpf_rcu_read_lock, 11066 KF_bpf_rcu_read_unlock, 11067 KF_bpf_rbtree_remove, 11068 KF_bpf_rbtree_add_impl, 11069 KF_bpf_rbtree_first, 11070 KF_bpf_dynptr_from_skb, 11071 KF_bpf_dynptr_from_xdp, 11072 KF_bpf_dynptr_slice, 11073 KF_bpf_dynptr_slice_rdwr, 11074 KF_bpf_dynptr_clone, 11075 KF_bpf_percpu_obj_new_impl, 11076 KF_bpf_percpu_obj_drop_impl, 11077 KF_bpf_throw, 11078 KF_bpf_wq_set_callback_impl, 11079 KF_bpf_preempt_disable, 11080 KF_bpf_preempt_enable, 11081 KF_bpf_iter_css_task_new, 11082 KF_bpf_session_cookie, 11083 }; 11084 11085 BTF_SET_START(special_kfunc_set) 11086 BTF_ID(func, bpf_obj_new_impl) 11087 BTF_ID(func, bpf_obj_drop_impl) 11088 BTF_ID(func, bpf_refcount_acquire_impl) 11089 BTF_ID(func, bpf_list_push_front_impl) 11090 BTF_ID(func, bpf_list_push_back_impl) 11091 BTF_ID(func, bpf_list_pop_front) 11092 BTF_ID(func, bpf_list_pop_back) 11093 BTF_ID(func, bpf_cast_to_kern_ctx) 11094 BTF_ID(func, bpf_rdonly_cast) 11095 BTF_ID(func, bpf_rbtree_remove) 11096 BTF_ID(func, bpf_rbtree_add_impl) 11097 BTF_ID(func, bpf_rbtree_first) 11098 BTF_ID(func, bpf_dynptr_from_skb) 11099 BTF_ID(func, bpf_dynptr_from_xdp) 11100 BTF_ID(func, bpf_dynptr_slice) 11101 BTF_ID(func, bpf_dynptr_slice_rdwr) 11102 BTF_ID(func, bpf_dynptr_clone) 11103 BTF_ID(func, bpf_percpu_obj_new_impl) 11104 BTF_ID(func, bpf_percpu_obj_drop_impl) 11105 BTF_ID(func, bpf_throw) 11106 BTF_ID(func, bpf_wq_set_callback_impl) 11107 #ifdef CONFIG_CGROUPS 11108 BTF_ID(func, bpf_iter_css_task_new) 11109 #endif 11110 BTF_SET_END(special_kfunc_set) 11111 11112 BTF_ID_LIST(special_kfunc_list) 11113 BTF_ID(func, bpf_obj_new_impl) 11114 BTF_ID(func, bpf_obj_drop_impl) 11115 BTF_ID(func, bpf_refcount_acquire_impl) 11116 BTF_ID(func, bpf_list_push_front_impl) 11117 BTF_ID(func, bpf_list_push_back_impl) 11118 BTF_ID(func, bpf_list_pop_front) 11119 BTF_ID(func, bpf_list_pop_back) 11120 BTF_ID(func, bpf_cast_to_kern_ctx) 11121 BTF_ID(func, bpf_rdonly_cast) 11122 BTF_ID(func, bpf_rcu_read_lock) 11123 BTF_ID(func, bpf_rcu_read_unlock) 11124 BTF_ID(func, bpf_rbtree_remove) 11125 BTF_ID(func, bpf_rbtree_add_impl) 11126 BTF_ID(func, bpf_rbtree_first) 11127 BTF_ID(func, bpf_dynptr_from_skb) 11128 BTF_ID(func, bpf_dynptr_from_xdp) 11129 BTF_ID(func, bpf_dynptr_slice) 11130 BTF_ID(func, bpf_dynptr_slice_rdwr) 11131 BTF_ID(func, bpf_dynptr_clone) 11132 BTF_ID(func, bpf_percpu_obj_new_impl) 11133 BTF_ID(func, bpf_percpu_obj_drop_impl) 11134 BTF_ID(func, bpf_throw) 11135 BTF_ID(func, bpf_wq_set_callback_impl) 11136 BTF_ID(func, bpf_preempt_disable) 11137 BTF_ID(func, bpf_preempt_enable) 11138 #ifdef CONFIG_CGROUPS 11139 BTF_ID(func, bpf_iter_css_task_new) 11140 #else 11141 BTF_ID_UNUSED 11142 #endif 11143 #ifdef CONFIG_BPF_EVENTS 11144 BTF_ID(func, bpf_session_cookie) 11145 #else 11146 BTF_ID_UNUSED 11147 #endif 11148 11149 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11150 { 11151 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11152 meta->arg_owning_ref) { 11153 return false; 11154 } 11155 11156 return meta->kfunc_flags & KF_RET_NULL; 11157 } 11158 11159 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11160 { 11161 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11162 } 11163 11164 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11165 { 11166 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11167 } 11168 11169 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11170 { 11171 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11172 } 11173 11174 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11175 { 11176 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11177 } 11178 11179 static enum kfunc_ptr_arg_type 11180 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11181 struct bpf_kfunc_call_arg_meta *meta, 11182 const struct btf_type *t, const struct btf_type *ref_t, 11183 const char *ref_tname, const struct btf_param *args, 11184 int argno, int nargs) 11185 { 11186 u32 regno = argno + 1; 11187 struct bpf_reg_state *regs = cur_regs(env); 11188 struct bpf_reg_state *reg = ®s[regno]; 11189 bool arg_mem_size = false; 11190 11191 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11192 return KF_ARG_PTR_TO_CTX; 11193 11194 /* In this function, we verify the kfunc's BTF as per the argument type, 11195 * leaving the rest of the verification with respect to the register 11196 * type to our caller. When a set of conditions hold in the BTF type of 11197 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11198 */ 11199 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11200 return KF_ARG_PTR_TO_CTX; 11201 11202 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11203 return KF_ARG_PTR_TO_NULL; 11204 11205 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11206 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11207 11208 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11209 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11210 11211 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11212 return KF_ARG_PTR_TO_DYNPTR; 11213 11214 if (is_kfunc_arg_iter(meta, argno)) 11215 return KF_ARG_PTR_TO_ITER; 11216 11217 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11218 return KF_ARG_PTR_TO_LIST_HEAD; 11219 11220 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11221 return KF_ARG_PTR_TO_LIST_NODE; 11222 11223 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11224 return KF_ARG_PTR_TO_RB_ROOT; 11225 11226 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11227 return KF_ARG_PTR_TO_RB_NODE; 11228 11229 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11230 return KF_ARG_PTR_TO_CONST_STR; 11231 11232 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11233 return KF_ARG_PTR_TO_MAP; 11234 11235 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11236 return KF_ARG_PTR_TO_WORKQUEUE; 11237 11238 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11239 if (!btf_type_is_struct(ref_t)) { 11240 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11241 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11242 return -EINVAL; 11243 } 11244 return KF_ARG_PTR_TO_BTF_ID; 11245 } 11246 11247 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11248 return KF_ARG_PTR_TO_CALLBACK; 11249 11250 if (argno + 1 < nargs && 11251 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11252 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11253 arg_mem_size = true; 11254 11255 /* This is the catch all argument type of register types supported by 11256 * check_helper_mem_access. However, we only allow when argument type is 11257 * pointer to scalar, or struct composed (recursively) of scalars. When 11258 * arg_mem_size is true, the pointer can be void *. 11259 */ 11260 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11261 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11262 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11263 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11264 return -EINVAL; 11265 } 11266 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11267 } 11268 11269 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11270 struct bpf_reg_state *reg, 11271 const struct btf_type *ref_t, 11272 const char *ref_tname, u32 ref_id, 11273 struct bpf_kfunc_call_arg_meta *meta, 11274 int argno) 11275 { 11276 const struct btf_type *reg_ref_t; 11277 bool strict_type_match = false; 11278 const struct btf *reg_btf; 11279 const char *reg_ref_tname; 11280 bool taking_projection; 11281 bool struct_same; 11282 u32 reg_ref_id; 11283 11284 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11285 reg_btf = reg->btf; 11286 reg_ref_id = reg->btf_id; 11287 } else { 11288 reg_btf = btf_vmlinux; 11289 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11290 } 11291 11292 /* Enforce strict type matching for calls to kfuncs that are acquiring 11293 * or releasing a reference, or are no-cast aliases. We do _not_ 11294 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11295 * as we want to enable BPF programs to pass types that are bitwise 11296 * equivalent without forcing them to explicitly cast with something 11297 * like bpf_cast_to_kern_ctx(). 11298 * 11299 * For example, say we had a type like the following: 11300 * 11301 * struct bpf_cpumask { 11302 * cpumask_t cpumask; 11303 * refcount_t usage; 11304 * }; 11305 * 11306 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11307 * to a struct cpumask, so it would be safe to pass a struct 11308 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11309 * 11310 * The philosophy here is similar to how we allow scalars of different 11311 * types to be passed to kfuncs as long as the size is the same. The 11312 * only difference here is that we're simply allowing 11313 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11314 * resolve types. 11315 */ 11316 if (is_kfunc_acquire(meta) || 11317 (is_kfunc_release(meta) && reg->ref_obj_id) || 11318 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11319 strict_type_match = true; 11320 11321 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11322 11323 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11324 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11325 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 11326 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11327 * actually use it -- it must cast to the underlying type. So we allow 11328 * caller to pass in the underlying type. 11329 */ 11330 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11331 if (!taking_projection && !struct_same) { 11332 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11333 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11334 btf_type_str(reg_ref_t), reg_ref_tname); 11335 return -EINVAL; 11336 } 11337 return 0; 11338 } 11339 11340 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11341 { 11342 struct bpf_verifier_state *state = env->cur_state; 11343 struct btf_record *rec = reg_btf_record(reg); 11344 11345 if (!state->active_lock.ptr) { 11346 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11347 return -EFAULT; 11348 } 11349 11350 if (type_flag(reg->type) & NON_OWN_REF) { 11351 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11352 return -EFAULT; 11353 } 11354 11355 reg->type |= NON_OWN_REF; 11356 if (rec->refcount_off >= 0) 11357 reg->type |= MEM_RCU; 11358 11359 return 0; 11360 } 11361 11362 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11363 { 11364 struct bpf_func_state *state, *unused; 11365 struct bpf_reg_state *reg; 11366 int i; 11367 11368 state = cur_func(env); 11369 11370 if (!ref_obj_id) { 11371 verbose(env, "verifier internal error: ref_obj_id is zero for " 11372 "owning -> non-owning conversion\n"); 11373 return -EFAULT; 11374 } 11375 11376 for (i = 0; i < state->acquired_refs; i++) { 11377 if (state->refs[i].id != ref_obj_id) 11378 continue; 11379 11380 /* Clear ref_obj_id here so release_reference doesn't clobber 11381 * the whole reg 11382 */ 11383 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11384 if (reg->ref_obj_id == ref_obj_id) { 11385 reg->ref_obj_id = 0; 11386 ref_set_non_owning(env, reg); 11387 } 11388 })); 11389 return 0; 11390 } 11391 11392 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11393 return -EFAULT; 11394 } 11395 11396 /* Implementation details: 11397 * 11398 * Each register points to some region of memory, which we define as an 11399 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11400 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11401 * allocation. The lock and the data it protects are colocated in the same 11402 * memory region. 11403 * 11404 * Hence, everytime a register holds a pointer value pointing to such 11405 * allocation, the verifier preserves a unique reg->id for it. 11406 * 11407 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11408 * bpf_spin_lock is called. 11409 * 11410 * To enable this, lock state in the verifier captures two values: 11411 * active_lock.ptr = Register's type specific pointer 11412 * active_lock.id = A unique ID for each register pointer value 11413 * 11414 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11415 * supported register types. 11416 * 11417 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11418 * allocated objects is the reg->btf pointer. 11419 * 11420 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11421 * can establish the provenance of the map value statically for each distinct 11422 * lookup into such maps. They always contain a single map value hence unique 11423 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11424 * 11425 * So, in case of global variables, they use array maps with max_entries = 1, 11426 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11427 * into the same map value as max_entries is 1, as described above). 11428 * 11429 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11430 * outer map pointer (in verifier context), but each lookup into an inner map 11431 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11432 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11433 * will get different reg->id assigned to each lookup, hence different 11434 * active_lock.id. 11435 * 11436 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11437 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11438 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11439 */ 11440 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11441 { 11442 void *ptr; 11443 u32 id; 11444 11445 switch ((int)reg->type) { 11446 case PTR_TO_MAP_VALUE: 11447 ptr = reg->map_ptr; 11448 break; 11449 case PTR_TO_BTF_ID | MEM_ALLOC: 11450 ptr = reg->btf; 11451 break; 11452 default: 11453 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11454 return -EFAULT; 11455 } 11456 id = reg->id; 11457 11458 if (!env->cur_state->active_lock.ptr) 11459 return -EINVAL; 11460 if (env->cur_state->active_lock.ptr != ptr || 11461 env->cur_state->active_lock.id != id) { 11462 verbose(env, "held lock and object are not in the same allocation\n"); 11463 return -EINVAL; 11464 } 11465 return 0; 11466 } 11467 11468 static bool is_bpf_list_api_kfunc(u32 btf_id) 11469 { 11470 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11471 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11472 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11473 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11474 } 11475 11476 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11477 { 11478 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11479 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11480 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11481 } 11482 11483 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11484 { 11485 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11486 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11487 } 11488 11489 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11490 { 11491 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11492 } 11493 11494 static bool is_async_callback_calling_kfunc(u32 btf_id) 11495 { 11496 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11497 } 11498 11499 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11500 { 11501 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11502 insn->imm == special_kfunc_list[KF_bpf_throw]; 11503 } 11504 11505 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 11506 { 11507 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 11508 } 11509 11510 static bool is_callback_calling_kfunc(u32 btf_id) 11511 { 11512 return is_sync_callback_calling_kfunc(btf_id) || 11513 is_async_callback_calling_kfunc(btf_id); 11514 } 11515 11516 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11517 { 11518 return is_bpf_rbtree_api_kfunc(btf_id); 11519 } 11520 11521 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11522 enum btf_field_type head_field_type, 11523 u32 kfunc_btf_id) 11524 { 11525 bool ret; 11526 11527 switch (head_field_type) { 11528 case BPF_LIST_HEAD: 11529 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11530 break; 11531 case BPF_RB_ROOT: 11532 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11533 break; 11534 default: 11535 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11536 btf_field_type_name(head_field_type)); 11537 return false; 11538 } 11539 11540 if (!ret) 11541 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11542 btf_field_type_name(head_field_type)); 11543 return ret; 11544 } 11545 11546 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11547 enum btf_field_type node_field_type, 11548 u32 kfunc_btf_id) 11549 { 11550 bool ret; 11551 11552 switch (node_field_type) { 11553 case BPF_LIST_NODE: 11554 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11555 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11556 break; 11557 case BPF_RB_NODE: 11558 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11559 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11560 break; 11561 default: 11562 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11563 btf_field_type_name(node_field_type)); 11564 return false; 11565 } 11566 11567 if (!ret) 11568 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11569 btf_field_type_name(node_field_type)); 11570 return ret; 11571 } 11572 11573 static int 11574 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11575 struct bpf_reg_state *reg, u32 regno, 11576 struct bpf_kfunc_call_arg_meta *meta, 11577 enum btf_field_type head_field_type, 11578 struct btf_field **head_field) 11579 { 11580 const char *head_type_name; 11581 struct btf_field *field; 11582 struct btf_record *rec; 11583 u32 head_off; 11584 11585 if (meta->btf != btf_vmlinux) { 11586 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11587 return -EFAULT; 11588 } 11589 11590 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11591 return -EFAULT; 11592 11593 head_type_name = btf_field_type_name(head_field_type); 11594 if (!tnum_is_const(reg->var_off)) { 11595 verbose(env, 11596 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11597 regno, head_type_name); 11598 return -EINVAL; 11599 } 11600 11601 rec = reg_btf_record(reg); 11602 head_off = reg->off + reg->var_off.value; 11603 field = btf_record_find(rec, head_off, head_field_type); 11604 if (!field) { 11605 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11606 return -EINVAL; 11607 } 11608 11609 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11610 if (check_reg_allocation_locked(env, reg)) { 11611 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11612 rec->spin_lock_off, head_type_name); 11613 return -EINVAL; 11614 } 11615 11616 if (*head_field) { 11617 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11618 return -EFAULT; 11619 } 11620 *head_field = field; 11621 return 0; 11622 } 11623 11624 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11625 struct bpf_reg_state *reg, u32 regno, 11626 struct bpf_kfunc_call_arg_meta *meta) 11627 { 11628 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11629 &meta->arg_list_head.field); 11630 } 11631 11632 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11633 struct bpf_reg_state *reg, u32 regno, 11634 struct bpf_kfunc_call_arg_meta *meta) 11635 { 11636 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11637 &meta->arg_rbtree_root.field); 11638 } 11639 11640 static int 11641 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11642 struct bpf_reg_state *reg, u32 regno, 11643 struct bpf_kfunc_call_arg_meta *meta, 11644 enum btf_field_type head_field_type, 11645 enum btf_field_type node_field_type, 11646 struct btf_field **node_field) 11647 { 11648 const char *node_type_name; 11649 const struct btf_type *et, *t; 11650 struct btf_field *field; 11651 u32 node_off; 11652 11653 if (meta->btf != btf_vmlinux) { 11654 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11655 return -EFAULT; 11656 } 11657 11658 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11659 return -EFAULT; 11660 11661 node_type_name = btf_field_type_name(node_field_type); 11662 if (!tnum_is_const(reg->var_off)) { 11663 verbose(env, 11664 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11665 regno, node_type_name); 11666 return -EINVAL; 11667 } 11668 11669 node_off = reg->off + reg->var_off.value; 11670 field = reg_find_field_offset(reg, node_off, node_field_type); 11671 if (!field) { 11672 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11673 return -EINVAL; 11674 } 11675 11676 field = *node_field; 11677 11678 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11679 t = btf_type_by_id(reg->btf, reg->btf_id); 11680 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11681 field->graph_root.value_btf_id, true)) { 11682 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11683 "in struct %s, but arg is at offset=%d in struct %s\n", 11684 btf_field_type_name(head_field_type), 11685 btf_field_type_name(node_field_type), 11686 field->graph_root.node_offset, 11687 btf_name_by_offset(field->graph_root.btf, et->name_off), 11688 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11689 return -EINVAL; 11690 } 11691 meta->arg_btf = reg->btf; 11692 meta->arg_btf_id = reg->btf_id; 11693 11694 if (node_off != field->graph_root.node_offset) { 11695 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11696 node_off, btf_field_type_name(node_field_type), 11697 field->graph_root.node_offset, 11698 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11699 return -EINVAL; 11700 } 11701 11702 return 0; 11703 } 11704 11705 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11706 struct bpf_reg_state *reg, u32 regno, 11707 struct bpf_kfunc_call_arg_meta *meta) 11708 { 11709 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11710 BPF_LIST_HEAD, BPF_LIST_NODE, 11711 &meta->arg_list_head.field); 11712 } 11713 11714 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11715 struct bpf_reg_state *reg, u32 regno, 11716 struct bpf_kfunc_call_arg_meta *meta) 11717 { 11718 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11719 BPF_RB_ROOT, BPF_RB_NODE, 11720 &meta->arg_rbtree_root.field); 11721 } 11722 11723 /* 11724 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11725 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11726 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11727 * them can only be attached to some specific hook points. 11728 */ 11729 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11730 { 11731 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11732 11733 switch (prog_type) { 11734 case BPF_PROG_TYPE_LSM: 11735 return true; 11736 case BPF_PROG_TYPE_TRACING: 11737 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11738 return true; 11739 fallthrough; 11740 default: 11741 return in_sleepable(env); 11742 } 11743 } 11744 11745 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11746 int insn_idx) 11747 { 11748 const char *func_name = meta->func_name, *ref_tname; 11749 const struct btf *btf = meta->btf; 11750 const struct btf_param *args; 11751 struct btf_record *rec; 11752 u32 i, nargs; 11753 int ret; 11754 11755 args = (const struct btf_param *)(meta->func_proto + 1); 11756 nargs = btf_type_vlen(meta->func_proto); 11757 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11758 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11759 MAX_BPF_FUNC_REG_ARGS); 11760 return -EINVAL; 11761 } 11762 11763 /* Check that BTF function arguments match actual types that the 11764 * verifier sees. 11765 */ 11766 for (i = 0; i < nargs; i++) { 11767 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11768 const struct btf_type *t, *ref_t, *resolve_ret; 11769 enum bpf_arg_type arg_type = ARG_DONTCARE; 11770 u32 regno = i + 1, ref_id, type_size; 11771 bool is_ret_buf_sz = false; 11772 int kf_arg_type; 11773 11774 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11775 11776 if (is_kfunc_arg_ignore(btf, &args[i])) 11777 continue; 11778 11779 if (btf_type_is_scalar(t)) { 11780 if (reg->type != SCALAR_VALUE) { 11781 verbose(env, "R%d is not a scalar\n", regno); 11782 return -EINVAL; 11783 } 11784 11785 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11786 if (meta->arg_constant.found) { 11787 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11788 return -EFAULT; 11789 } 11790 if (!tnum_is_const(reg->var_off)) { 11791 verbose(env, "R%d must be a known constant\n", regno); 11792 return -EINVAL; 11793 } 11794 ret = mark_chain_precision(env, regno); 11795 if (ret < 0) 11796 return ret; 11797 meta->arg_constant.found = true; 11798 meta->arg_constant.value = reg->var_off.value; 11799 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11800 meta->r0_rdonly = true; 11801 is_ret_buf_sz = true; 11802 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11803 is_ret_buf_sz = true; 11804 } 11805 11806 if (is_ret_buf_sz) { 11807 if (meta->r0_size) { 11808 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11809 return -EINVAL; 11810 } 11811 11812 if (!tnum_is_const(reg->var_off)) { 11813 verbose(env, "R%d is not a const\n", regno); 11814 return -EINVAL; 11815 } 11816 11817 meta->r0_size = reg->var_off.value; 11818 ret = mark_chain_precision(env, regno); 11819 if (ret) 11820 return ret; 11821 } 11822 continue; 11823 } 11824 11825 if (!btf_type_is_ptr(t)) { 11826 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11827 return -EINVAL; 11828 } 11829 11830 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11831 (register_is_null(reg) || type_may_be_null(reg->type)) && 11832 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11833 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11834 return -EACCES; 11835 } 11836 11837 if (reg->ref_obj_id) { 11838 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11839 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11840 regno, reg->ref_obj_id, 11841 meta->ref_obj_id); 11842 return -EFAULT; 11843 } 11844 meta->ref_obj_id = reg->ref_obj_id; 11845 if (is_kfunc_release(meta)) 11846 meta->release_regno = regno; 11847 } 11848 11849 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11850 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11851 11852 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11853 if (kf_arg_type < 0) 11854 return kf_arg_type; 11855 11856 switch (kf_arg_type) { 11857 case KF_ARG_PTR_TO_NULL: 11858 continue; 11859 case KF_ARG_PTR_TO_MAP: 11860 if (!reg->map_ptr) { 11861 verbose(env, "pointer in R%d isn't map pointer\n", regno); 11862 return -EINVAL; 11863 } 11864 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 11865 /* Use map_uid (which is unique id of inner map) to reject: 11866 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 11867 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 11868 * if (inner_map1 && inner_map2) { 11869 * wq = bpf_map_lookup_elem(inner_map1); 11870 * if (wq) 11871 * // mismatch would have been allowed 11872 * bpf_wq_init(wq, inner_map2); 11873 * } 11874 * 11875 * Comparing map_ptr is enough to distinguish normal and outer maps. 11876 */ 11877 if (meta->map.ptr != reg->map_ptr || 11878 meta->map.uid != reg->map_uid) { 11879 verbose(env, 11880 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 11881 meta->map.uid, reg->map_uid); 11882 return -EINVAL; 11883 } 11884 } 11885 meta->map.ptr = reg->map_ptr; 11886 meta->map.uid = reg->map_uid; 11887 fallthrough; 11888 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11889 case KF_ARG_PTR_TO_BTF_ID: 11890 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11891 break; 11892 11893 if (!is_trusted_reg(reg)) { 11894 if (!is_kfunc_rcu(meta)) { 11895 verbose(env, "R%d must be referenced or trusted\n", regno); 11896 return -EINVAL; 11897 } 11898 if (!is_rcu_reg(reg)) { 11899 verbose(env, "R%d must be a rcu pointer\n", regno); 11900 return -EINVAL; 11901 } 11902 } 11903 11904 fallthrough; 11905 case KF_ARG_PTR_TO_CTX: 11906 /* Trusted arguments have the same offset checks as release arguments */ 11907 arg_type |= OBJ_RELEASE; 11908 break; 11909 case KF_ARG_PTR_TO_DYNPTR: 11910 case KF_ARG_PTR_TO_ITER: 11911 case KF_ARG_PTR_TO_LIST_HEAD: 11912 case KF_ARG_PTR_TO_LIST_NODE: 11913 case KF_ARG_PTR_TO_RB_ROOT: 11914 case KF_ARG_PTR_TO_RB_NODE: 11915 case KF_ARG_PTR_TO_MEM: 11916 case KF_ARG_PTR_TO_MEM_SIZE: 11917 case KF_ARG_PTR_TO_CALLBACK: 11918 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11919 case KF_ARG_PTR_TO_CONST_STR: 11920 case KF_ARG_PTR_TO_WORKQUEUE: 11921 /* Trusted by default */ 11922 break; 11923 default: 11924 WARN_ON_ONCE(1); 11925 return -EFAULT; 11926 } 11927 11928 if (is_kfunc_release(meta) && reg->ref_obj_id) 11929 arg_type |= OBJ_RELEASE; 11930 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11931 if (ret < 0) 11932 return ret; 11933 11934 switch (kf_arg_type) { 11935 case KF_ARG_PTR_TO_CTX: 11936 if (reg->type != PTR_TO_CTX) { 11937 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11938 return -EINVAL; 11939 } 11940 11941 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11942 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11943 if (ret < 0) 11944 return -EINVAL; 11945 meta->ret_btf_id = ret; 11946 } 11947 break; 11948 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11949 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11950 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11951 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11952 return -EINVAL; 11953 } 11954 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11955 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11956 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11957 return -EINVAL; 11958 } 11959 } else { 11960 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11961 return -EINVAL; 11962 } 11963 if (!reg->ref_obj_id) { 11964 verbose(env, "allocated object must be referenced\n"); 11965 return -EINVAL; 11966 } 11967 if (meta->btf == btf_vmlinux) { 11968 meta->arg_btf = reg->btf; 11969 meta->arg_btf_id = reg->btf_id; 11970 } 11971 break; 11972 case KF_ARG_PTR_TO_DYNPTR: 11973 { 11974 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11975 int clone_ref_obj_id = 0; 11976 11977 if (reg->type != PTR_TO_STACK && 11978 reg->type != CONST_PTR_TO_DYNPTR) { 11979 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11980 return -EINVAL; 11981 } 11982 11983 if (reg->type == CONST_PTR_TO_DYNPTR) 11984 dynptr_arg_type |= MEM_RDONLY; 11985 11986 if (is_kfunc_arg_uninit(btf, &args[i])) 11987 dynptr_arg_type |= MEM_UNINIT; 11988 11989 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11990 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11991 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11992 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11993 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11994 (dynptr_arg_type & MEM_UNINIT)) { 11995 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11996 11997 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11998 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11999 return -EFAULT; 12000 } 12001 12002 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12003 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12004 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12005 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 12006 return -EFAULT; 12007 } 12008 } 12009 12010 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 12011 if (ret < 0) 12012 return ret; 12013 12014 if (!(dynptr_arg_type & MEM_UNINIT)) { 12015 int id = dynptr_id(env, reg); 12016 12017 if (id < 0) { 12018 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 12019 return id; 12020 } 12021 meta->initialized_dynptr.id = id; 12022 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12023 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12024 } 12025 12026 break; 12027 } 12028 case KF_ARG_PTR_TO_ITER: 12029 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12030 if (!check_css_task_iter_allowlist(env)) { 12031 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12032 return -EINVAL; 12033 } 12034 } 12035 ret = process_iter_arg(env, regno, insn_idx, meta); 12036 if (ret < 0) 12037 return ret; 12038 break; 12039 case KF_ARG_PTR_TO_LIST_HEAD: 12040 if (reg->type != PTR_TO_MAP_VALUE && 12041 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12042 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12043 return -EINVAL; 12044 } 12045 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12046 verbose(env, "allocated object must be referenced\n"); 12047 return -EINVAL; 12048 } 12049 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12050 if (ret < 0) 12051 return ret; 12052 break; 12053 case KF_ARG_PTR_TO_RB_ROOT: 12054 if (reg->type != PTR_TO_MAP_VALUE && 12055 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12056 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12057 return -EINVAL; 12058 } 12059 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12060 verbose(env, "allocated object must be referenced\n"); 12061 return -EINVAL; 12062 } 12063 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12064 if (ret < 0) 12065 return ret; 12066 break; 12067 case KF_ARG_PTR_TO_LIST_NODE: 12068 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12069 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12070 return -EINVAL; 12071 } 12072 if (!reg->ref_obj_id) { 12073 verbose(env, "allocated object must be referenced\n"); 12074 return -EINVAL; 12075 } 12076 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12077 if (ret < 0) 12078 return ret; 12079 break; 12080 case KF_ARG_PTR_TO_RB_NODE: 12081 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 12082 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 12083 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 12084 return -EINVAL; 12085 } 12086 if (in_rbtree_lock_required_cb(env)) { 12087 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 12088 return -EINVAL; 12089 } 12090 } else { 12091 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12092 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12093 return -EINVAL; 12094 } 12095 if (!reg->ref_obj_id) { 12096 verbose(env, "allocated object must be referenced\n"); 12097 return -EINVAL; 12098 } 12099 } 12100 12101 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12102 if (ret < 0) 12103 return ret; 12104 break; 12105 case KF_ARG_PTR_TO_MAP: 12106 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12107 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12108 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12109 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12110 fallthrough; 12111 case KF_ARG_PTR_TO_BTF_ID: 12112 /* Only base_type is checked, further checks are done here */ 12113 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12114 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12115 !reg2btf_ids[base_type(reg->type)]) { 12116 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12117 verbose(env, "expected %s or socket\n", 12118 reg_type_str(env, base_type(reg->type) | 12119 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12120 return -EINVAL; 12121 } 12122 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12123 if (ret < 0) 12124 return ret; 12125 break; 12126 case KF_ARG_PTR_TO_MEM: 12127 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12128 if (IS_ERR(resolve_ret)) { 12129 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12130 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12131 return -EINVAL; 12132 } 12133 ret = check_mem_reg(env, reg, regno, type_size); 12134 if (ret < 0) 12135 return ret; 12136 break; 12137 case KF_ARG_PTR_TO_MEM_SIZE: 12138 { 12139 struct bpf_reg_state *buff_reg = ®s[regno]; 12140 const struct btf_param *buff_arg = &args[i]; 12141 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12142 const struct btf_param *size_arg = &args[i + 1]; 12143 12144 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 12145 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12146 if (ret < 0) { 12147 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12148 return ret; 12149 } 12150 } 12151 12152 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12153 if (meta->arg_constant.found) { 12154 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12155 return -EFAULT; 12156 } 12157 if (!tnum_is_const(size_reg->var_off)) { 12158 verbose(env, "R%d must be a known constant\n", regno + 1); 12159 return -EINVAL; 12160 } 12161 meta->arg_constant.found = true; 12162 meta->arg_constant.value = size_reg->var_off.value; 12163 } 12164 12165 /* Skip next '__sz' or '__szk' argument */ 12166 i++; 12167 break; 12168 } 12169 case KF_ARG_PTR_TO_CALLBACK: 12170 if (reg->type != PTR_TO_FUNC) { 12171 verbose(env, "arg%d expected pointer to func\n", i); 12172 return -EINVAL; 12173 } 12174 meta->subprogno = reg->subprogno; 12175 break; 12176 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12177 if (!type_is_ptr_alloc_obj(reg->type)) { 12178 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12179 return -EINVAL; 12180 } 12181 if (!type_is_non_owning_ref(reg->type)) 12182 meta->arg_owning_ref = true; 12183 12184 rec = reg_btf_record(reg); 12185 if (!rec) { 12186 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12187 return -EFAULT; 12188 } 12189 12190 if (rec->refcount_off < 0) { 12191 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12192 return -EINVAL; 12193 } 12194 12195 meta->arg_btf = reg->btf; 12196 meta->arg_btf_id = reg->btf_id; 12197 break; 12198 case KF_ARG_PTR_TO_CONST_STR: 12199 if (reg->type != PTR_TO_MAP_VALUE) { 12200 verbose(env, "arg#%d doesn't point to a const string\n", i); 12201 return -EINVAL; 12202 } 12203 ret = check_reg_const_str(env, reg, regno); 12204 if (ret) 12205 return ret; 12206 break; 12207 case KF_ARG_PTR_TO_WORKQUEUE: 12208 if (reg->type != PTR_TO_MAP_VALUE) { 12209 verbose(env, "arg#%d doesn't point to a map value\n", i); 12210 return -EINVAL; 12211 } 12212 ret = process_wq_func(env, regno, meta); 12213 if (ret < 0) 12214 return ret; 12215 break; 12216 } 12217 } 12218 12219 if (is_kfunc_release(meta) && !meta->release_regno) { 12220 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12221 func_name); 12222 return -EINVAL; 12223 } 12224 12225 return 0; 12226 } 12227 12228 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12229 struct bpf_insn *insn, 12230 struct bpf_kfunc_call_arg_meta *meta, 12231 const char **kfunc_name) 12232 { 12233 const struct btf_type *func, *func_proto; 12234 u32 func_id, *kfunc_flags; 12235 const char *func_name; 12236 struct btf *desc_btf; 12237 12238 if (kfunc_name) 12239 *kfunc_name = NULL; 12240 12241 if (!insn->imm) 12242 return -EINVAL; 12243 12244 desc_btf = find_kfunc_desc_btf(env, insn->off); 12245 if (IS_ERR(desc_btf)) 12246 return PTR_ERR(desc_btf); 12247 12248 func_id = insn->imm; 12249 func = btf_type_by_id(desc_btf, func_id); 12250 func_name = btf_name_by_offset(desc_btf, func->name_off); 12251 if (kfunc_name) 12252 *kfunc_name = func_name; 12253 func_proto = btf_type_by_id(desc_btf, func->type); 12254 12255 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12256 if (!kfunc_flags) { 12257 return -EACCES; 12258 } 12259 12260 memset(meta, 0, sizeof(*meta)); 12261 meta->btf = desc_btf; 12262 meta->func_id = func_id; 12263 meta->kfunc_flags = *kfunc_flags; 12264 meta->func_proto = func_proto; 12265 meta->func_name = func_name; 12266 12267 return 0; 12268 } 12269 12270 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12271 12272 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12273 int *insn_idx_p) 12274 { 12275 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12276 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12277 struct bpf_reg_state *regs = cur_regs(env); 12278 const char *func_name, *ptr_type_name; 12279 const struct btf_type *t, *ptr_type; 12280 struct bpf_kfunc_call_arg_meta meta; 12281 struct bpf_insn_aux_data *insn_aux; 12282 int err, insn_idx = *insn_idx_p; 12283 const struct btf_param *args; 12284 const struct btf_type *ret_t; 12285 struct btf *desc_btf; 12286 12287 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12288 if (!insn->imm) 12289 return 0; 12290 12291 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12292 if (err == -EACCES && func_name) 12293 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12294 if (err) 12295 return err; 12296 desc_btf = meta.btf; 12297 insn_aux = &env->insn_aux_data[insn_idx]; 12298 12299 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12300 12301 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12302 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12303 return -EACCES; 12304 } 12305 12306 sleepable = is_kfunc_sleepable(&meta); 12307 if (sleepable && !in_sleepable(env)) { 12308 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12309 return -EACCES; 12310 } 12311 12312 /* Check the arguments */ 12313 err = check_kfunc_args(env, &meta, insn_idx); 12314 if (err < 0) 12315 return err; 12316 12317 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12318 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12319 set_rbtree_add_callback_state); 12320 if (err) { 12321 verbose(env, "kfunc %s#%d failed callback verification\n", 12322 func_name, meta.func_id); 12323 return err; 12324 } 12325 } 12326 12327 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12328 meta.r0_size = sizeof(u64); 12329 meta.r0_rdonly = false; 12330 } 12331 12332 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 12333 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12334 set_timer_callback_state); 12335 if (err) { 12336 verbose(env, "kfunc %s#%d failed callback verification\n", 12337 func_name, meta.func_id); 12338 return err; 12339 } 12340 } 12341 12342 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12343 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12344 12345 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12346 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12347 12348 if (env->cur_state->active_rcu_lock) { 12349 struct bpf_func_state *state; 12350 struct bpf_reg_state *reg; 12351 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12352 12353 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12354 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12355 return -EACCES; 12356 } 12357 12358 if (rcu_lock) { 12359 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12360 return -EINVAL; 12361 } else if (rcu_unlock) { 12362 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12363 if (reg->type & MEM_RCU) { 12364 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12365 reg->type |= PTR_UNTRUSTED; 12366 } 12367 })); 12368 env->cur_state->active_rcu_lock = false; 12369 } else if (sleepable) { 12370 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12371 return -EACCES; 12372 } 12373 } else if (rcu_lock) { 12374 env->cur_state->active_rcu_lock = true; 12375 } else if (rcu_unlock) { 12376 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12377 return -EINVAL; 12378 } 12379 12380 if (env->cur_state->active_preempt_lock) { 12381 if (preempt_disable) { 12382 env->cur_state->active_preempt_lock++; 12383 } else if (preempt_enable) { 12384 env->cur_state->active_preempt_lock--; 12385 } else if (sleepable) { 12386 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 12387 return -EACCES; 12388 } 12389 } else if (preempt_disable) { 12390 env->cur_state->active_preempt_lock++; 12391 } else if (preempt_enable) { 12392 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12393 return -EINVAL; 12394 } 12395 12396 /* In case of release function, we get register number of refcounted 12397 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12398 */ 12399 if (meta.release_regno) { 12400 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12401 if (err) { 12402 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12403 func_name, meta.func_id); 12404 return err; 12405 } 12406 } 12407 12408 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12409 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12410 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12411 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12412 insn_aux->insert_off = regs[BPF_REG_2].off; 12413 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12414 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12415 if (err) { 12416 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12417 func_name, meta.func_id); 12418 return err; 12419 } 12420 12421 err = release_reference(env, release_ref_obj_id); 12422 if (err) { 12423 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12424 func_name, meta.func_id); 12425 return err; 12426 } 12427 } 12428 12429 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12430 if (!bpf_jit_supports_exceptions()) { 12431 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12432 func_name, meta.func_id); 12433 return -ENOTSUPP; 12434 } 12435 env->seen_exception = true; 12436 12437 /* In the case of the default callback, the cookie value passed 12438 * to bpf_throw becomes the return value of the program. 12439 */ 12440 if (!env->exception_callback_subprog) { 12441 err = check_return_code(env, BPF_REG_1, "R1"); 12442 if (err < 0) 12443 return err; 12444 } 12445 } 12446 12447 for (i = 0; i < CALLER_SAVED_REGS; i++) 12448 mark_reg_not_init(env, regs, caller_saved[i]); 12449 12450 /* Check return type */ 12451 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12452 12453 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12454 /* Only exception is bpf_obj_new_impl */ 12455 if (meta.btf != btf_vmlinux || 12456 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12457 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12458 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12459 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12460 return -EINVAL; 12461 } 12462 } 12463 12464 if (btf_type_is_scalar(t)) { 12465 mark_reg_unknown(env, regs, BPF_REG_0); 12466 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12467 } else if (btf_type_is_ptr(t)) { 12468 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12469 12470 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12471 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12472 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12473 struct btf_struct_meta *struct_meta; 12474 struct btf *ret_btf; 12475 u32 ret_btf_id; 12476 12477 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12478 return -ENOMEM; 12479 12480 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12481 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12482 return -EINVAL; 12483 } 12484 12485 ret_btf = env->prog->aux->btf; 12486 ret_btf_id = meta.arg_constant.value; 12487 12488 /* This may be NULL due to user not supplying a BTF */ 12489 if (!ret_btf) { 12490 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12491 return -EINVAL; 12492 } 12493 12494 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12495 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12496 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12497 return -EINVAL; 12498 } 12499 12500 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12501 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12502 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12503 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12504 return -EINVAL; 12505 } 12506 12507 if (!bpf_global_percpu_ma_set) { 12508 mutex_lock(&bpf_percpu_ma_lock); 12509 if (!bpf_global_percpu_ma_set) { 12510 /* Charge memory allocated with bpf_global_percpu_ma to 12511 * root memcg. The obj_cgroup for root memcg is NULL. 12512 */ 12513 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12514 if (!err) 12515 bpf_global_percpu_ma_set = true; 12516 } 12517 mutex_unlock(&bpf_percpu_ma_lock); 12518 if (err) 12519 return err; 12520 } 12521 12522 mutex_lock(&bpf_percpu_ma_lock); 12523 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12524 mutex_unlock(&bpf_percpu_ma_lock); 12525 if (err) 12526 return err; 12527 } 12528 12529 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12530 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12531 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12532 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12533 return -EINVAL; 12534 } 12535 12536 if (struct_meta) { 12537 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12538 return -EINVAL; 12539 } 12540 } 12541 12542 mark_reg_known_zero(env, regs, BPF_REG_0); 12543 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12544 regs[BPF_REG_0].btf = ret_btf; 12545 regs[BPF_REG_0].btf_id = ret_btf_id; 12546 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12547 regs[BPF_REG_0].type |= MEM_PERCPU; 12548 12549 insn_aux->obj_new_size = ret_t->size; 12550 insn_aux->kptr_struct_meta = struct_meta; 12551 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12552 mark_reg_known_zero(env, regs, BPF_REG_0); 12553 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12554 regs[BPF_REG_0].btf = meta.arg_btf; 12555 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12556 12557 insn_aux->kptr_struct_meta = 12558 btf_find_struct_meta(meta.arg_btf, 12559 meta.arg_btf_id); 12560 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12561 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12562 struct btf_field *field = meta.arg_list_head.field; 12563 12564 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12565 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12566 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12567 struct btf_field *field = meta.arg_rbtree_root.field; 12568 12569 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12570 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12571 mark_reg_known_zero(env, regs, BPF_REG_0); 12572 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12573 regs[BPF_REG_0].btf = desc_btf; 12574 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12575 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12576 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12577 if (!ret_t || !btf_type_is_struct(ret_t)) { 12578 verbose(env, 12579 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12580 return -EINVAL; 12581 } 12582 12583 mark_reg_known_zero(env, regs, BPF_REG_0); 12584 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12585 regs[BPF_REG_0].btf = desc_btf; 12586 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12587 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12588 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12589 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12590 12591 mark_reg_known_zero(env, regs, BPF_REG_0); 12592 12593 if (!meta.arg_constant.found) { 12594 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12595 return -EFAULT; 12596 } 12597 12598 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12599 12600 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12601 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12602 12603 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12604 regs[BPF_REG_0].type |= MEM_RDONLY; 12605 } else { 12606 /* this will set env->seen_direct_write to true */ 12607 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12608 verbose(env, "the prog does not allow writes to packet data\n"); 12609 return -EINVAL; 12610 } 12611 } 12612 12613 if (!meta.initialized_dynptr.id) { 12614 verbose(env, "verifier internal error: no dynptr id\n"); 12615 return -EFAULT; 12616 } 12617 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12618 12619 /* we don't need to set BPF_REG_0's ref obj id 12620 * because packet slices are not refcounted (see 12621 * dynptr_type_refcounted) 12622 */ 12623 } else { 12624 verbose(env, "kernel function %s unhandled dynamic return type\n", 12625 meta.func_name); 12626 return -EFAULT; 12627 } 12628 } else if (btf_type_is_void(ptr_type)) { 12629 /* kfunc returning 'void *' is equivalent to returning scalar */ 12630 mark_reg_unknown(env, regs, BPF_REG_0); 12631 } else if (!__btf_type_is_struct(ptr_type)) { 12632 if (!meta.r0_size) { 12633 __u32 sz; 12634 12635 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12636 meta.r0_size = sz; 12637 meta.r0_rdonly = true; 12638 } 12639 } 12640 if (!meta.r0_size) { 12641 ptr_type_name = btf_name_by_offset(desc_btf, 12642 ptr_type->name_off); 12643 verbose(env, 12644 "kernel function %s returns pointer type %s %s is not supported\n", 12645 func_name, 12646 btf_type_str(ptr_type), 12647 ptr_type_name); 12648 return -EINVAL; 12649 } 12650 12651 mark_reg_known_zero(env, regs, BPF_REG_0); 12652 regs[BPF_REG_0].type = PTR_TO_MEM; 12653 regs[BPF_REG_0].mem_size = meta.r0_size; 12654 12655 if (meta.r0_rdonly) 12656 regs[BPF_REG_0].type |= MEM_RDONLY; 12657 12658 /* Ensures we don't access the memory after a release_reference() */ 12659 if (meta.ref_obj_id) 12660 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12661 } else { 12662 mark_reg_known_zero(env, regs, BPF_REG_0); 12663 regs[BPF_REG_0].btf = desc_btf; 12664 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12665 regs[BPF_REG_0].btf_id = ptr_type_id; 12666 } 12667 12668 if (is_kfunc_ret_null(&meta)) { 12669 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12670 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12671 regs[BPF_REG_0].id = ++env->id_gen; 12672 } 12673 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12674 if (is_kfunc_acquire(&meta)) { 12675 int id = acquire_reference_state(env, insn_idx); 12676 12677 if (id < 0) 12678 return id; 12679 if (is_kfunc_ret_null(&meta)) 12680 regs[BPF_REG_0].id = id; 12681 regs[BPF_REG_0].ref_obj_id = id; 12682 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12683 ref_set_non_owning(env, ®s[BPF_REG_0]); 12684 } 12685 12686 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12687 regs[BPF_REG_0].id = ++env->id_gen; 12688 } else if (btf_type_is_void(t)) { 12689 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12690 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12691 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12692 insn_aux->kptr_struct_meta = 12693 btf_find_struct_meta(meta.arg_btf, 12694 meta.arg_btf_id); 12695 } 12696 } 12697 } 12698 12699 nargs = btf_type_vlen(meta.func_proto); 12700 args = (const struct btf_param *)(meta.func_proto + 1); 12701 for (i = 0; i < nargs; i++) { 12702 u32 regno = i + 1; 12703 12704 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12705 if (btf_type_is_ptr(t)) 12706 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12707 else 12708 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12709 mark_btf_func_reg_size(env, regno, t->size); 12710 } 12711 12712 if (is_iter_next_kfunc(&meta)) { 12713 err = process_iter_next_call(env, insn_idx, &meta); 12714 if (err) 12715 return err; 12716 } 12717 12718 return 0; 12719 } 12720 12721 static bool signed_add_overflows(s64 a, s64 b) 12722 { 12723 /* Do the add in u64, where overflow is well-defined */ 12724 s64 res = (s64)((u64)a + (u64)b); 12725 12726 if (b < 0) 12727 return res > a; 12728 return res < a; 12729 } 12730 12731 static bool signed_add32_overflows(s32 a, s32 b) 12732 { 12733 /* Do the add in u32, where overflow is well-defined */ 12734 s32 res = (s32)((u32)a + (u32)b); 12735 12736 if (b < 0) 12737 return res > a; 12738 return res < a; 12739 } 12740 12741 static bool signed_sub_overflows(s64 a, s64 b) 12742 { 12743 /* Do the sub in u64, where overflow is well-defined */ 12744 s64 res = (s64)((u64)a - (u64)b); 12745 12746 if (b < 0) 12747 return res < a; 12748 return res > a; 12749 } 12750 12751 static bool signed_sub32_overflows(s32 a, s32 b) 12752 { 12753 /* Do the sub in u32, where overflow is well-defined */ 12754 s32 res = (s32)((u32)a - (u32)b); 12755 12756 if (b < 0) 12757 return res < a; 12758 return res > a; 12759 } 12760 12761 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12762 const struct bpf_reg_state *reg, 12763 enum bpf_reg_type type) 12764 { 12765 bool known = tnum_is_const(reg->var_off); 12766 s64 val = reg->var_off.value; 12767 s64 smin = reg->smin_value; 12768 12769 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12770 verbose(env, "math between %s pointer and %lld is not allowed\n", 12771 reg_type_str(env, type), val); 12772 return false; 12773 } 12774 12775 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12776 verbose(env, "%s pointer offset %d is not allowed\n", 12777 reg_type_str(env, type), reg->off); 12778 return false; 12779 } 12780 12781 if (smin == S64_MIN) { 12782 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12783 reg_type_str(env, type)); 12784 return false; 12785 } 12786 12787 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12788 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12789 smin, reg_type_str(env, type)); 12790 return false; 12791 } 12792 12793 return true; 12794 } 12795 12796 enum { 12797 REASON_BOUNDS = -1, 12798 REASON_TYPE = -2, 12799 REASON_PATHS = -3, 12800 REASON_LIMIT = -4, 12801 REASON_STACK = -5, 12802 }; 12803 12804 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12805 u32 *alu_limit, bool mask_to_left) 12806 { 12807 u32 max = 0, ptr_limit = 0; 12808 12809 switch (ptr_reg->type) { 12810 case PTR_TO_STACK: 12811 /* Offset 0 is out-of-bounds, but acceptable start for the 12812 * left direction, see BPF_REG_FP. Also, unknown scalar 12813 * offset where we would need to deal with min/max bounds is 12814 * currently prohibited for unprivileged. 12815 */ 12816 max = MAX_BPF_STACK + mask_to_left; 12817 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12818 break; 12819 case PTR_TO_MAP_VALUE: 12820 max = ptr_reg->map_ptr->value_size; 12821 ptr_limit = (mask_to_left ? 12822 ptr_reg->smin_value : 12823 ptr_reg->umax_value) + ptr_reg->off; 12824 break; 12825 default: 12826 return REASON_TYPE; 12827 } 12828 12829 if (ptr_limit >= max) 12830 return REASON_LIMIT; 12831 *alu_limit = ptr_limit; 12832 return 0; 12833 } 12834 12835 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12836 const struct bpf_insn *insn) 12837 { 12838 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12839 } 12840 12841 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12842 u32 alu_state, u32 alu_limit) 12843 { 12844 /* If we arrived here from different branches with different 12845 * state or limits to sanitize, then this won't work. 12846 */ 12847 if (aux->alu_state && 12848 (aux->alu_state != alu_state || 12849 aux->alu_limit != alu_limit)) 12850 return REASON_PATHS; 12851 12852 /* Corresponding fixup done in do_misc_fixups(). */ 12853 aux->alu_state = alu_state; 12854 aux->alu_limit = alu_limit; 12855 return 0; 12856 } 12857 12858 static int sanitize_val_alu(struct bpf_verifier_env *env, 12859 struct bpf_insn *insn) 12860 { 12861 struct bpf_insn_aux_data *aux = cur_aux(env); 12862 12863 if (can_skip_alu_sanitation(env, insn)) 12864 return 0; 12865 12866 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12867 } 12868 12869 static bool sanitize_needed(u8 opcode) 12870 { 12871 return opcode == BPF_ADD || opcode == BPF_SUB; 12872 } 12873 12874 struct bpf_sanitize_info { 12875 struct bpf_insn_aux_data aux; 12876 bool mask_to_left; 12877 }; 12878 12879 static struct bpf_verifier_state * 12880 sanitize_speculative_path(struct bpf_verifier_env *env, 12881 const struct bpf_insn *insn, 12882 u32 next_idx, u32 curr_idx) 12883 { 12884 struct bpf_verifier_state *branch; 12885 struct bpf_reg_state *regs; 12886 12887 branch = push_stack(env, next_idx, curr_idx, true); 12888 if (branch && insn) { 12889 regs = branch->frame[branch->curframe]->regs; 12890 if (BPF_SRC(insn->code) == BPF_K) { 12891 mark_reg_unknown(env, regs, insn->dst_reg); 12892 } else if (BPF_SRC(insn->code) == BPF_X) { 12893 mark_reg_unknown(env, regs, insn->dst_reg); 12894 mark_reg_unknown(env, regs, insn->src_reg); 12895 } 12896 } 12897 return branch; 12898 } 12899 12900 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12901 struct bpf_insn *insn, 12902 const struct bpf_reg_state *ptr_reg, 12903 const struct bpf_reg_state *off_reg, 12904 struct bpf_reg_state *dst_reg, 12905 struct bpf_sanitize_info *info, 12906 const bool commit_window) 12907 { 12908 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12909 struct bpf_verifier_state *vstate = env->cur_state; 12910 bool off_is_imm = tnum_is_const(off_reg->var_off); 12911 bool off_is_neg = off_reg->smin_value < 0; 12912 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12913 u8 opcode = BPF_OP(insn->code); 12914 u32 alu_state, alu_limit; 12915 struct bpf_reg_state tmp; 12916 bool ret; 12917 int err; 12918 12919 if (can_skip_alu_sanitation(env, insn)) 12920 return 0; 12921 12922 /* We already marked aux for masking from non-speculative 12923 * paths, thus we got here in the first place. We only care 12924 * to explore bad access from here. 12925 */ 12926 if (vstate->speculative) 12927 goto do_sim; 12928 12929 if (!commit_window) { 12930 if (!tnum_is_const(off_reg->var_off) && 12931 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12932 return REASON_BOUNDS; 12933 12934 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12935 (opcode == BPF_SUB && !off_is_neg); 12936 } 12937 12938 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12939 if (err < 0) 12940 return err; 12941 12942 if (commit_window) { 12943 /* In commit phase we narrow the masking window based on 12944 * the observed pointer move after the simulated operation. 12945 */ 12946 alu_state = info->aux.alu_state; 12947 alu_limit = abs(info->aux.alu_limit - alu_limit); 12948 } else { 12949 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12950 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12951 alu_state |= ptr_is_dst_reg ? 12952 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12953 12954 /* Limit pruning on unknown scalars to enable deep search for 12955 * potential masking differences from other program paths. 12956 */ 12957 if (!off_is_imm) 12958 env->explore_alu_limits = true; 12959 } 12960 12961 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12962 if (err < 0) 12963 return err; 12964 do_sim: 12965 /* If we're in commit phase, we're done here given we already 12966 * pushed the truncated dst_reg into the speculative verification 12967 * stack. 12968 * 12969 * Also, when register is a known constant, we rewrite register-based 12970 * operation to immediate-based, and thus do not need masking (and as 12971 * a consequence, do not need to simulate the zero-truncation either). 12972 */ 12973 if (commit_window || off_is_imm) 12974 return 0; 12975 12976 /* Simulate and find potential out-of-bounds access under 12977 * speculative execution from truncation as a result of 12978 * masking when off was not within expected range. If off 12979 * sits in dst, then we temporarily need to move ptr there 12980 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12981 * for cases where we use K-based arithmetic in one direction 12982 * and truncated reg-based in the other in order to explore 12983 * bad access. 12984 */ 12985 if (!ptr_is_dst_reg) { 12986 tmp = *dst_reg; 12987 copy_register_state(dst_reg, ptr_reg); 12988 } 12989 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12990 env->insn_idx); 12991 if (!ptr_is_dst_reg && ret) 12992 *dst_reg = tmp; 12993 return !ret ? REASON_STACK : 0; 12994 } 12995 12996 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12997 { 12998 struct bpf_verifier_state *vstate = env->cur_state; 12999 13000 /* If we simulate paths under speculation, we don't update the 13001 * insn as 'seen' such that when we verify unreachable paths in 13002 * the non-speculative domain, sanitize_dead_code() can still 13003 * rewrite/sanitize them. 13004 */ 13005 if (!vstate->speculative) 13006 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13007 } 13008 13009 static int sanitize_err(struct bpf_verifier_env *env, 13010 const struct bpf_insn *insn, int reason, 13011 const struct bpf_reg_state *off_reg, 13012 const struct bpf_reg_state *dst_reg) 13013 { 13014 static const char *err = "pointer arithmetic with it prohibited for !root"; 13015 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13016 u32 dst = insn->dst_reg, src = insn->src_reg; 13017 13018 switch (reason) { 13019 case REASON_BOUNDS: 13020 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13021 off_reg == dst_reg ? dst : src, err); 13022 break; 13023 case REASON_TYPE: 13024 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13025 off_reg == dst_reg ? src : dst, err); 13026 break; 13027 case REASON_PATHS: 13028 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13029 dst, op, err); 13030 break; 13031 case REASON_LIMIT: 13032 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13033 dst, op, err); 13034 break; 13035 case REASON_STACK: 13036 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13037 dst, err); 13038 break; 13039 default: 13040 verbose(env, "verifier internal error: unknown reason (%d)\n", 13041 reason); 13042 break; 13043 } 13044 13045 return -EACCES; 13046 } 13047 13048 /* check that stack access falls within stack limits and that 'reg' doesn't 13049 * have a variable offset. 13050 * 13051 * Variable offset is prohibited for unprivileged mode for simplicity since it 13052 * requires corresponding support in Spectre masking for stack ALU. See also 13053 * retrieve_ptr_limit(). 13054 * 13055 * 13056 * 'off' includes 'reg->off'. 13057 */ 13058 static int check_stack_access_for_ptr_arithmetic( 13059 struct bpf_verifier_env *env, 13060 int regno, 13061 const struct bpf_reg_state *reg, 13062 int off) 13063 { 13064 if (!tnum_is_const(reg->var_off)) { 13065 char tn_buf[48]; 13066 13067 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13068 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13069 regno, tn_buf, off); 13070 return -EACCES; 13071 } 13072 13073 if (off >= 0 || off < -MAX_BPF_STACK) { 13074 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13075 "prohibited for !root; off=%d\n", regno, off); 13076 return -EACCES; 13077 } 13078 13079 return 0; 13080 } 13081 13082 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13083 const struct bpf_insn *insn, 13084 const struct bpf_reg_state *dst_reg) 13085 { 13086 u32 dst = insn->dst_reg; 13087 13088 /* For unprivileged we require that resulting offset must be in bounds 13089 * in order to be able to sanitize access later on. 13090 */ 13091 if (env->bypass_spec_v1) 13092 return 0; 13093 13094 switch (dst_reg->type) { 13095 case PTR_TO_STACK: 13096 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13097 dst_reg->off + dst_reg->var_off.value)) 13098 return -EACCES; 13099 break; 13100 case PTR_TO_MAP_VALUE: 13101 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 13102 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13103 "prohibited for !root\n", dst); 13104 return -EACCES; 13105 } 13106 break; 13107 default: 13108 break; 13109 } 13110 13111 return 0; 13112 } 13113 13114 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13115 * Caller should also handle BPF_MOV case separately. 13116 * If we return -EACCES, caller may want to try again treating pointer as a 13117 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13118 */ 13119 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13120 struct bpf_insn *insn, 13121 const struct bpf_reg_state *ptr_reg, 13122 const struct bpf_reg_state *off_reg) 13123 { 13124 struct bpf_verifier_state *vstate = env->cur_state; 13125 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13126 struct bpf_reg_state *regs = state->regs, *dst_reg; 13127 bool known = tnum_is_const(off_reg->var_off); 13128 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13129 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13130 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13131 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13132 struct bpf_sanitize_info info = {}; 13133 u8 opcode = BPF_OP(insn->code); 13134 u32 dst = insn->dst_reg; 13135 int ret; 13136 13137 dst_reg = ®s[dst]; 13138 13139 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13140 smin_val > smax_val || umin_val > umax_val) { 13141 /* Taint dst register if offset had invalid bounds derived from 13142 * e.g. dead branches. 13143 */ 13144 __mark_reg_unknown(env, dst_reg); 13145 return 0; 13146 } 13147 13148 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13149 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13150 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13151 __mark_reg_unknown(env, dst_reg); 13152 return 0; 13153 } 13154 13155 verbose(env, 13156 "R%d 32-bit pointer arithmetic prohibited\n", 13157 dst); 13158 return -EACCES; 13159 } 13160 13161 if (ptr_reg->type & PTR_MAYBE_NULL) { 13162 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13163 dst, reg_type_str(env, ptr_reg->type)); 13164 return -EACCES; 13165 } 13166 13167 switch (base_type(ptr_reg->type)) { 13168 case PTR_TO_CTX: 13169 case PTR_TO_MAP_VALUE: 13170 case PTR_TO_MAP_KEY: 13171 case PTR_TO_STACK: 13172 case PTR_TO_PACKET_META: 13173 case PTR_TO_PACKET: 13174 case PTR_TO_TP_BUFFER: 13175 case PTR_TO_BTF_ID: 13176 case PTR_TO_MEM: 13177 case PTR_TO_BUF: 13178 case PTR_TO_FUNC: 13179 case CONST_PTR_TO_DYNPTR: 13180 break; 13181 case PTR_TO_FLOW_KEYS: 13182 if (known) 13183 break; 13184 fallthrough; 13185 case CONST_PTR_TO_MAP: 13186 /* smin_val represents the known value */ 13187 if (known && smin_val == 0 && opcode == BPF_ADD) 13188 break; 13189 fallthrough; 13190 default: 13191 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13192 dst, reg_type_str(env, ptr_reg->type)); 13193 return -EACCES; 13194 } 13195 13196 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13197 * The id may be overwritten later if we create a new variable offset. 13198 */ 13199 dst_reg->type = ptr_reg->type; 13200 dst_reg->id = ptr_reg->id; 13201 13202 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 13203 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 13204 return -EINVAL; 13205 13206 /* pointer types do not carry 32-bit bounds at the moment. */ 13207 __mark_reg32_unbounded(dst_reg); 13208 13209 if (sanitize_needed(opcode)) { 13210 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13211 &info, false); 13212 if (ret < 0) 13213 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13214 } 13215 13216 switch (opcode) { 13217 case BPF_ADD: 13218 /* We can take a fixed offset as long as it doesn't overflow 13219 * the s32 'off' field 13220 */ 13221 if (known && (ptr_reg->off + smin_val == 13222 (s64)(s32)(ptr_reg->off + smin_val))) { 13223 /* pointer += K. Accumulate it into fixed offset */ 13224 dst_reg->smin_value = smin_ptr; 13225 dst_reg->smax_value = smax_ptr; 13226 dst_reg->umin_value = umin_ptr; 13227 dst_reg->umax_value = umax_ptr; 13228 dst_reg->var_off = ptr_reg->var_off; 13229 dst_reg->off = ptr_reg->off + smin_val; 13230 dst_reg->raw = ptr_reg->raw; 13231 break; 13232 } 13233 /* A new variable offset is created. Note that off_reg->off 13234 * == 0, since it's a scalar. 13235 * dst_reg gets the pointer type and since some positive 13236 * integer value was added to the pointer, give it a new 'id' 13237 * if it's a PTR_TO_PACKET. 13238 * this creates a new 'base' pointer, off_reg (variable) gets 13239 * added into the variable offset, and we copy the fixed offset 13240 * from ptr_reg. 13241 */ 13242 if (signed_add_overflows(smin_ptr, smin_val) || 13243 signed_add_overflows(smax_ptr, smax_val)) { 13244 dst_reg->smin_value = S64_MIN; 13245 dst_reg->smax_value = S64_MAX; 13246 } else { 13247 dst_reg->smin_value = smin_ptr + smin_val; 13248 dst_reg->smax_value = smax_ptr + smax_val; 13249 } 13250 if (umin_ptr + umin_val < umin_ptr || 13251 umax_ptr + umax_val < umax_ptr) { 13252 dst_reg->umin_value = 0; 13253 dst_reg->umax_value = U64_MAX; 13254 } else { 13255 dst_reg->umin_value = umin_ptr + umin_val; 13256 dst_reg->umax_value = umax_ptr + umax_val; 13257 } 13258 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13259 dst_reg->off = ptr_reg->off; 13260 dst_reg->raw = ptr_reg->raw; 13261 if (reg_is_pkt_pointer(ptr_reg)) { 13262 dst_reg->id = ++env->id_gen; 13263 /* something was added to pkt_ptr, set range to zero */ 13264 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13265 } 13266 break; 13267 case BPF_SUB: 13268 if (dst_reg == off_reg) { 13269 /* scalar -= pointer. Creates an unknown scalar */ 13270 verbose(env, "R%d tried to subtract pointer from scalar\n", 13271 dst); 13272 return -EACCES; 13273 } 13274 /* We don't allow subtraction from FP, because (according to 13275 * test_verifier.c test "invalid fp arithmetic", JITs might not 13276 * be able to deal with it. 13277 */ 13278 if (ptr_reg->type == PTR_TO_STACK) { 13279 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13280 dst); 13281 return -EACCES; 13282 } 13283 if (known && (ptr_reg->off - smin_val == 13284 (s64)(s32)(ptr_reg->off - smin_val))) { 13285 /* pointer -= K. Subtract it from fixed offset */ 13286 dst_reg->smin_value = smin_ptr; 13287 dst_reg->smax_value = smax_ptr; 13288 dst_reg->umin_value = umin_ptr; 13289 dst_reg->umax_value = umax_ptr; 13290 dst_reg->var_off = ptr_reg->var_off; 13291 dst_reg->id = ptr_reg->id; 13292 dst_reg->off = ptr_reg->off - smin_val; 13293 dst_reg->raw = ptr_reg->raw; 13294 break; 13295 } 13296 /* A new variable offset is created. If the subtrahend is known 13297 * nonnegative, then any reg->range we had before is still good. 13298 */ 13299 if (signed_sub_overflows(smin_ptr, smax_val) || 13300 signed_sub_overflows(smax_ptr, smin_val)) { 13301 /* Overflow possible, we know nothing */ 13302 dst_reg->smin_value = S64_MIN; 13303 dst_reg->smax_value = S64_MAX; 13304 } else { 13305 dst_reg->smin_value = smin_ptr - smax_val; 13306 dst_reg->smax_value = smax_ptr - smin_val; 13307 } 13308 if (umin_ptr < umax_val) { 13309 /* Overflow possible, we know nothing */ 13310 dst_reg->umin_value = 0; 13311 dst_reg->umax_value = U64_MAX; 13312 } else { 13313 /* Cannot overflow (as long as bounds are consistent) */ 13314 dst_reg->umin_value = umin_ptr - umax_val; 13315 dst_reg->umax_value = umax_ptr - umin_val; 13316 } 13317 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13318 dst_reg->off = ptr_reg->off; 13319 dst_reg->raw = ptr_reg->raw; 13320 if (reg_is_pkt_pointer(ptr_reg)) { 13321 dst_reg->id = ++env->id_gen; 13322 /* something was added to pkt_ptr, set range to zero */ 13323 if (smin_val < 0) 13324 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13325 } 13326 break; 13327 case BPF_AND: 13328 case BPF_OR: 13329 case BPF_XOR: 13330 /* bitwise ops on pointers are troublesome, prohibit. */ 13331 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13332 dst, bpf_alu_string[opcode >> 4]); 13333 return -EACCES; 13334 default: 13335 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13336 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13337 dst, bpf_alu_string[opcode >> 4]); 13338 return -EACCES; 13339 } 13340 13341 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13342 return -EINVAL; 13343 reg_bounds_sync(dst_reg); 13344 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13345 return -EACCES; 13346 if (sanitize_needed(opcode)) { 13347 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13348 &info, true); 13349 if (ret < 0) 13350 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13351 } 13352 13353 return 0; 13354 } 13355 13356 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13357 struct bpf_reg_state *src_reg) 13358 { 13359 s32 smin_val = src_reg->s32_min_value; 13360 s32 smax_val = src_reg->s32_max_value; 13361 u32 umin_val = src_reg->u32_min_value; 13362 u32 umax_val = src_reg->u32_max_value; 13363 13364 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13365 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13366 dst_reg->s32_min_value = S32_MIN; 13367 dst_reg->s32_max_value = S32_MAX; 13368 } else { 13369 dst_reg->s32_min_value += smin_val; 13370 dst_reg->s32_max_value += smax_val; 13371 } 13372 if (dst_reg->u32_min_value + umin_val < umin_val || 13373 dst_reg->u32_max_value + umax_val < umax_val) { 13374 dst_reg->u32_min_value = 0; 13375 dst_reg->u32_max_value = U32_MAX; 13376 } else { 13377 dst_reg->u32_min_value += umin_val; 13378 dst_reg->u32_max_value += umax_val; 13379 } 13380 } 13381 13382 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13383 struct bpf_reg_state *src_reg) 13384 { 13385 s64 smin_val = src_reg->smin_value; 13386 s64 smax_val = src_reg->smax_value; 13387 u64 umin_val = src_reg->umin_value; 13388 u64 umax_val = src_reg->umax_value; 13389 13390 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13391 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13392 dst_reg->smin_value = S64_MIN; 13393 dst_reg->smax_value = S64_MAX; 13394 } else { 13395 dst_reg->smin_value += smin_val; 13396 dst_reg->smax_value += smax_val; 13397 } 13398 if (dst_reg->umin_value + umin_val < umin_val || 13399 dst_reg->umax_value + umax_val < umax_val) { 13400 dst_reg->umin_value = 0; 13401 dst_reg->umax_value = U64_MAX; 13402 } else { 13403 dst_reg->umin_value += umin_val; 13404 dst_reg->umax_value += umax_val; 13405 } 13406 } 13407 13408 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13409 struct bpf_reg_state *src_reg) 13410 { 13411 s32 smin_val = src_reg->s32_min_value; 13412 s32 smax_val = src_reg->s32_max_value; 13413 u32 umin_val = src_reg->u32_min_value; 13414 u32 umax_val = src_reg->u32_max_value; 13415 13416 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13417 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13418 /* Overflow possible, we know nothing */ 13419 dst_reg->s32_min_value = S32_MIN; 13420 dst_reg->s32_max_value = S32_MAX; 13421 } else { 13422 dst_reg->s32_min_value -= smax_val; 13423 dst_reg->s32_max_value -= smin_val; 13424 } 13425 if (dst_reg->u32_min_value < umax_val) { 13426 /* Overflow possible, we know nothing */ 13427 dst_reg->u32_min_value = 0; 13428 dst_reg->u32_max_value = U32_MAX; 13429 } else { 13430 /* Cannot overflow (as long as bounds are consistent) */ 13431 dst_reg->u32_min_value -= umax_val; 13432 dst_reg->u32_max_value -= umin_val; 13433 } 13434 } 13435 13436 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13437 struct bpf_reg_state *src_reg) 13438 { 13439 s64 smin_val = src_reg->smin_value; 13440 s64 smax_val = src_reg->smax_value; 13441 u64 umin_val = src_reg->umin_value; 13442 u64 umax_val = src_reg->umax_value; 13443 13444 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13445 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13446 /* Overflow possible, we know nothing */ 13447 dst_reg->smin_value = S64_MIN; 13448 dst_reg->smax_value = S64_MAX; 13449 } else { 13450 dst_reg->smin_value -= smax_val; 13451 dst_reg->smax_value -= smin_val; 13452 } 13453 if (dst_reg->umin_value < umax_val) { 13454 /* Overflow possible, we know nothing */ 13455 dst_reg->umin_value = 0; 13456 dst_reg->umax_value = U64_MAX; 13457 } else { 13458 /* Cannot overflow (as long as bounds are consistent) */ 13459 dst_reg->umin_value -= umax_val; 13460 dst_reg->umax_value -= umin_val; 13461 } 13462 } 13463 13464 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13465 struct bpf_reg_state *src_reg) 13466 { 13467 s32 smin_val = src_reg->s32_min_value; 13468 u32 umin_val = src_reg->u32_min_value; 13469 u32 umax_val = src_reg->u32_max_value; 13470 13471 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13472 /* Ain't nobody got time to multiply that sign */ 13473 __mark_reg32_unbounded(dst_reg); 13474 return; 13475 } 13476 /* Both values are positive, so we can work with unsigned and 13477 * copy the result to signed (unless it exceeds S32_MAX). 13478 */ 13479 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13480 /* Potential overflow, we know nothing */ 13481 __mark_reg32_unbounded(dst_reg); 13482 return; 13483 } 13484 dst_reg->u32_min_value *= umin_val; 13485 dst_reg->u32_max_value *= umax_val; 13486 if (dst_reg->u32_max_value > S32_MAX) { 13487 /* Overflow possible, we know nothing */ 13488 dst_reg->s32_min_value = S32_MIN; 13489 dst_reg->s32_max_value = S32_MAX; 13490 } else { 13491 dst_reg->s32_min_value = dst_reg->u32_min_value; 13492 dst_reg->s32_max_value = dst_reg->u32_max_value; 13493 } 13494 } 13495 13496 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13497 struct bpf_reg_state *src_reg) 13498 { 13499 s64 smin_val = src_reg->smin_value; 13500 u64 umin_val = src_reg->umin_value; 13501 u64 umax_val = src_reg->umax_value; 13502 13503 if (smin_val < 0 || dst_reg->smin_value < 0) { 13504 /* Ain't nobody got time to multiply that sign */ 13505 __mark_reg64_unbounded(dst_reg); 13506 return; 13507 } 13508 /* Both values are positive, so we can work with unsigned and 13509 * copy the result to signed (unless it exceeds S64_MAX). 13510 */ 13511 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13512 /* Potential overflow, we know nothing */ 13513 __mark_reg64_unbounded(dst_reg); 13514 return; 13515 } 13516 dst_reg->umin_value *= umin_val; 13517 dst_reg->umax_value *= umax_val; 13518 if (dst_reg->umax_value > S64_MAX) { 13519 /* Overflow possible, we know nothing */ 13520 dst_reg->smin_value = S64_MIN; 13521 dst_reg->smax_value = S64_MAX; 13522 } else { 13523 dst_reg->smin_value = dst_reg->umin_value; 13524 dst_reg->smax_value = dst_reg->umax_value; 13525 } 13526 } 13527 13528 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13529 struct bpf_reg_state *src_reg) 13530 { 13531 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13532 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13533 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13534 u32 umax_val = src_reg->u32_max_value; 13535 13536 if (src_known && dst_known) { 13537 __mark_reg32_known(dst_reg, var32_off.value); 13538 return; 13539 } 13540 13541 /* We get our minimum from the var_off, since that's inherently 13542 * bitwise. Our maximum is the minimum of the operands' maxima. 13543 */ 13544 dst_reg->u32_min_value = var32_off.value; 13545 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13546 13547 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13548 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13549 */ 13550 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13551 dst_reg->s32_min_value = dst_reg->u32_min_value; 13552 dst_reg->s32_max_value = dst_reg->u32_max_value; 13553 } else { 13554 dst_reg->s32_min_value = S32_MIN; 13555 dst_reg->s32_max_value = S32_MAX; 13556 } 13557 } 13558 13559 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13560 struct bpf_reg_state *src_reg) 13561 { 13562 bool src_known = tnum_is_const(src_reg->var_off); 13563 bool dst_known = tnum_is_const(dst_reg->var_off); 13564 u64 umax_val = src_reg->umax_value; 13565 13566 if (src_known && dst_known) { 13567 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13568 return; 13569 } 13570 13571 /* We get our minimum from the var_off, since that's inherently 13572 * bitwise. Our maximum is the minimum of the operands' maxima. 13573 */ 13574 dst_reg->umin_value = dst_reg->var_off.value; 13575 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13576 13577 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13578 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13579 */ 13580 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13581 dst_reg->smin_value = dst_reg->umin_value; 13582 dst_reg->smax_value = dst_reg->umax_value; 13583 } else { 13584 dst_reg->smin_value = S64_MIN; 13585 dst_reg->smax_value = S64_MAX; 13586 } 13587 /* We may learn something more from the var_off */ 13588 __update_reg_bounds(dst_reg); 13589 } 13590 13591 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13592 struct bpf_reg_state *src_reg) 13593 { 13594 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13595 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13596 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13597 u32 umin_val = src_reg->u32_min_value; 13598 13599 if (src_known && dst_known) { 13600 __mark_reg32_known(dst_reg, var32_off.value); 13601 return; 13602 } 13603 13604 /* We get our maximum from the var_off, and our minimum is the 13605 * maximum of the operands' minima 13606 */ 13607 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13608 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13609 13610 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13611 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13612 */ 13613 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13614 dst_reg->s32_min_value = dst_reg->u32_min_value; 13615 dst_reg->s32_max_value = dst_reg->u32_max_value; 13616 } else { 13617 dst_reg->s32_min_value = S32_MIN; 13618 dst_reg->s32_max_value = S32_MAX; 13619 } 13620 } 13621 13622 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13623 struct bpf_reg_state *src_reg) 13624 { 13625 bool src_known = tnum_is_const(src_reg->var_off); 13626 bool dst_known = tnum_is_const(dst_reg->var_off); 13627 u64 umin_val = src_reg->umin_value; 13628 13629 if (src_known && dst_known) { 13630 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13631 return; 13632 } 13633 13634 /* We get our maximum from the var_off, and our minimum is the 13635 * maximum of the operands' minima 13636 */ 13637 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13638 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13639 13640 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13641 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13642 */ 13643 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13644 dst_reg->smin_value = dst_reg->umin_value; 13645 dst_reg->smax_value = dst_reg->umax_value; 13646 } else { 13647 dst_reg->smin_value = S64_MIN; 13648 dst_reg->smax_value = S64_MAX; 13649 } 13650 /* We may learn something more from the var_off */ 13651 __update_reg_bounds(dst_reg); 13652 } 13653 13654 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13655 struct bpf_reg_state *src_reg) 13656 { 13657 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13658 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13659 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13660 13661 if (src_known && dst_known) { 13662 __mark_reg32_known(dst_reg, var32_off.value); 13663 return; 13664 } 13665 13666 /* We get both minimum and maximum from the var32_off. */ 13667 dst_reg->u32_min_value = var32_off.value; 13668 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13669 13670 /* Safe to set s32 bounds by casting u32 result into s32 when u32 13671 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 13672 */ 13673 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 13674 dst_reg->s32_min_value = dst_reg->u32_min_value; 13675 dst_reg->s32_max_value = dst_reg->u32_max_value; 13676 } else { 13677 dst_reg->s32_min_value = S32_MIN; 13678 dst_reg->s32_max_value = S32_MAX; 13679 } 13680 } 13681 13682 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13683 struct bpf_reg_state *src_reg) 13684 { 13685 bool src_known = tnum_is_const(src_reg->var_off); 13686 bool dst_known = tnum_is_const(dst_reg->var_off); 13687 13688 if (src_known && dst_known) { 13689 /* dst_reg->var_off.value has been updated earlier */ 13690 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13691 return; 13692 } 13693 13694 /* We get both minimum and maximum from the var_off. */ 13695 dst_reg->umin_value = dst_reg->var_off.value; 13696 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13697 13698 /* Safe to set s64 bounds by casting u64 result into s64 when u64 13699 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 13700 */ 13701 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 13702 dst_reg->smin_value = dst_reg->umin_value; 13703 dst_reg->smax_value = dst_reg->umax_value; 13704 } else { 13705 dst_reg->smin_value = S64_MIN; 13706 dst_reg->smax_value = S64_MAX; 13707 } 13708 13709 __update_reg_bounds(dst_reg); 13710 } 13711 13712 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13713 u64 umin_val, u64 umax_val) 13714 { 13715 /* We lose all sign bit information (except what we can pick 13716 * up from var_off) 13717 */ 13718 dst_reg->s32_min_value = S32_MIN; 13719 dst_reg->s32_max_value = S32_MAX; 13720 /* If we might shift our top bit out, then we know nothing */ 13721 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13722 dst_reg->u32_min_value = 0; 13723 dst_reg->u32_max_value = U32_MAX; 13724 } else { 13725 dst_reg->u32_min_value <<= umin_val; 13726 dst_reg->u32_max_value <<= umax_val; 13727 } 13728 } 13729 13730 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13731 struct bpf_reg_state *src_reg) 13732 { 13733 u32 umax_val = src_reg->u32_max_value; 13734 u32 umin_val = src_reg->u32_min_value; 13735 /* u32 alu operation will zext upper bits */ 13736 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13737 13738 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13739 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13740 /* Not required but being careful mark reg64 bounds as unknown so 13741 * that we are forced to pick them up from tnum and zext later and 13742 * if some path skips this step we are still safe. 13743 */ 13744 __mark_reg64_unbounded(dst_reg); 13745 __update_reg32_bounds(dst_reg); 13746 } 13747 13748 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13749 u64 umin_val, u64 umax_val) 13750 { 13751 /* Special case <<32 because it is a common compiler pattern to sign 13752 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13753 * positive we know this shift will also be positive so we can track 13754 * bounds correctly. Otherwise we lose all sign bit information except 13755 * what we can pick up from var_off. Perhaps we can generalize this 13756 * later to shifts of any length. 13757 */ 13758 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13759 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13760 else 13761 dst_reg->smax_value = S64_MAX; 13762 13763 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13764 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13765 else 13766 dst_reg->smin_value = S64_MIN; 13767 13768 /* If we might shift our top bit out, then we know nothing */ 13769 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13770 dst_reg->umin_value = 0; 13771 dst_reg->umax_value = U64_MAX; 13772 } else { 13773 dst_reg->umin_value <<= umin_val; 13774 dst_reg->umax_value <<= umax_val; 13775 } 13776 } 13777 13778 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13779 struct bpf_reg_state *src_reg) 13780 { 13781 u64 umax_val = src_reg->umax_value; 13782 u64 umin_val = src_reg->umin_value; 13783 13784 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13785 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13786 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13787 13788 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13789 /* We may learn something more from the var_off */ 13790 __update_reg_bounds(dst_reg); 13791 } 13792 13793 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13794 struct bpf_reg_state *src_reg) 13795 { 13796 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13797 u32 umax_val = src_reg->u32_max_value; 13798 u32 umin_val = src_reg->u32_min_value; 13799 13800 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13801 * be negative, then either: 13802 * 1) src_reg might be zero, so the sign bit of the result is 13803 * unknown, so we lose our signed bounds 13804 * 2) it's known negative, thus the unsigned bounds capture the 13805 * signed bounds 13806 * 3) the signed bounds cross zero, so they tell us nothing 13807 * about the result 13808 * If the value in dst_reg is known nonnegative, then again the 13809 * unsigned bounds capture the signed bounds. 13810 * Thus, in all cases it suffices to blow away our signed bounds 13811 * and rely on inferring new ones from the unsigned bounds and 13812 * var_off of the result. 13813 */ 13814 dst_reg->s32_min_value = S32_MIN; 13815 dst_reg->s32_max_value = S32_MAX; 13816 13817 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13818 dst_reg->u32_min_value >>= umax_val; 13819 dst_reg->u32_max_value >>= umin_val; 13820 13821 __mark_reg64_unbounded(dst_reg); 13822 __update_reg32_bounds(dst_reg); 13823 } 13824 13825 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13826 struct bpf_reg_state *src_reg) 13827 { 13828 u64 umax_val = src_reg->umax_value; 13829 u64 umin_val = src_reg->umin_value; 13830 13831 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13832 * be negative, then either: 13833 * 1) src_reg might be zero, so the sign bit of the result is 13834 * unknown, so we lose our signed bounds 13835 * 2) it's known negative, thus the unsigned bounds capture the 13836 * signed bounds 13837 * 3) the signed bounds cross zero, so they tell us nothing 13838 * about the result 13839 * If the value in dst_reg is known nonnegative, then again the 13840 * unsigned bounds capture the signed bounds. 13841 * Thus, in all cases it suffices to blow away our signed bounds 13842 * and rely on inferring new ones from the unsigned bounds and 13843 * var_off of the result. 13844 */ 13845 dst_reg->smin_value = S64_MIN; 13846 dst_reg->smax_value = S64_MAX; 13847 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13848 dst_reg->umin_value >>= umax_val; 13849 dst_reg->umax_value >>= umin_val; 13850 13851 /* Its not easy to operate on alu32 bounds here because it depends 13852 * on bits being shifted in. Take easy way out and mark unbounded 13853 * so we can recalculate later from tnum. 13854 */ 13855 __mark_reg32_unbounded(dst_reg); 13856 __update_reg_bounds(dst_reg); 13857 } 13858 13859 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13860 struct bpf_reg_state *src_reg) 13861 { 13862 u64 umin_val = src_reg->u32_min_value; 13863 13864 /* Upon reaching here, src_known is true and 13865 * umax_val is equal to umin_val. 13866 */ 13867 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13868 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13869 13870 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13871 13872 /* blow away the dst_reg umin_value/umax_value and rely on 13873 * dst_reg var_off to refine the result. 13874 */ 13875 dst_reg->u32_min_value = 0; 13876 dst_reg->u32_max_value = U32_MAX; 13877 13878 __mark_reg64_unbounded(dst_reg); 13879 __update_reg32_bounds(dst_reg); 13880 } 13881 13882 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13883 struct bpf_reg_state *src_reg) 13884 { 13885 u64 umin_val = src_reg->umin_value; 13886 13887 /* Upon reaching here, src_known is true and umax_val is equal 13888 * to umin_val. 13889 */ 13890 dst_reg->smin_value >>= umin_val; 13891 dst_reg->smax_value >>= umin_val; 13892 13893 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13894 13895 /* blow away the dst_reg umin_value/umax_value and rely on 13896 * dst_reg var_off to refine the result. 13897 */ 13898 dst_reg->umin_value = 0; 13899 dst_reg->umax_value = U64_MAX; 13900 13901 /* Its not easy to operate on alu32 bounds here because it depends 13902 * on bits being shifted in from upper 32-bits. Take easy way out 13903 * and mark unbounded so we can recalculate later from tnum. 13904 */ 13905 __mark_reg32_unbounded(dst_reg); 13906 __update_reg_bounds(dst_reg); 13907 } 13908 13909 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 13910 const struct bpf_reg_state *src_reg) 13911 { 13912 bool src_is_const = false; 13913 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13914 13915 if (insn_bitness == 32) { 13916 if (tnum_subreg_is_const(src_reg->var_off) 13917 && src_reg->s32_min_value == src_reg->s32_max_value 13918 && src_reg->u32_min_value == src_reg->u32_max_value) 13919 src_is_const = true; 13920 } else { 13921 if (tnum_is_const(src_reg->var_off) 13922 && src_reg->smin_value == src_reg->smax_value 13923 && src_reg->umin_value == src_reg->umax_value) 13924 src_is_const = true; 13925 } 13926 13927 switch (BPF_OP(insn->code)) { 13928 case BPF_ADD: 13929 case BPF_SUB: 13930 case BPF_AND: 13931 case BPF_XOR: 13932 case BPF_OR: 13933 case BPF_MUL: 13934 return true; 13935 13936 /* Shift operators range is only computable if shift dimension operand 13937 * is a constant. Shifts greater than 31 or 63 are undefined. This 13938 * includes shifts by a negative number. 13939 */ 13940 case BPF_LSH: 13941 case BPF_RSH: 13942 case BPF_ARSH: 13943 return (src_is_const && src_reg->umax_value < insn_bitness); 13944 default: 13945 return false; 13946 } 13947 } 13948 13949 /* WARNING: This function does calculations on 64-bit values, but the actual 13950 * execution may occur on 32-bit values. Therefore, things like bitshifts 13951 * need extra checks in the 32-bit case. 13952 */ 13953 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13954 struct bpf_insn *insn, 13955 struct bpf_reg_state *dst_reg, 13956 struct bpf_reg_state src_reg) 13957 { 13958 u8 opcode = BPF_OP(insn->code); 13959 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13960 int ret; 13961 13962 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 13963 __mark_reg_unknown(env, dst_reg); 13964 return 0; 13965 } 13966 13967 if (sanitize_needed(opcode)) { 13968 ret = sanitize_val_alu(env, insn); 13969 if (ret < 0) 13970 return sanitize_err(env, insn, ret, NULL, NULL); 13971 } 13972 13973 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13974 * There are two classes of instructions: The first class we track both 13975 * alu32 and alu64 sign/unsigned bounds independently this provides the 13976 * greatest amount of precision when alu operations are mixed with jmp32 13977 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13978 * and BPF_OR. This is possible because these ops have fairly easy to 13979 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13980 * See alu32 verifier tests for examples. The second class of 13981 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13982 * with regards to tracking sign/unsigned bounds because the bits may 13983 * cross subreg boundaries in the alu64 case. When this happens we mark 13984 * the reg unbounded in the subreg bound space and use the resulting 13985 * tnum to calculate an approximation of the sign/unsigned bounds. 13986 */ 13987 switch (opcode) { 13988 case BPF_ADD: 13989 scalar32_min_max_add(dst_reg, &src_reg); 13990 scalar_min_max_add(dst_reg, &src_reg); 13991 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13992 break; 13993 case BPF_SUB: 13994 scalar32_min_max_sub(dst_reg, &src_reg); 13995 scalar_min_max_sub(dst_reg, &src_reg); 13996 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13997 break; 13998 case BPF_MUL: 13999 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14000 scalar32_min_max_mul(dst_reg, &src_reg); 14001 scalar_min_max_mul(dst_reg, &src_reg); 14002 break; 14003 case BPF_AND: 14004 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14005 scalar32_min_max_and(dst_reg, &src_reg); 14006 scalar_min_max_and(dst_reg, &src_reg); 14007 break; 14008 case BPF_OR: 14009 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14010 scalar32_min_max_or(dst_reg, &src_reg); 14011 scalar_min_max_or(dst_reg, &src_reg); 14012 break; 14013 case BPF_XOR: 14014 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14015 scalar32_min_max_xor(dst_reg, &src_reg); 14016 scalar_min_max_xor(dst_reg, &src_reg); 14017 break; 14018 case BPF_LSH: 14019 if (alu32) 14020 scalar32_min_max_lsh(dst_reg, &src_reg); 14021 else 14022 scalar_min_max_lsh(dst_reg, &src_reg); 14023 break; 14024 case BPF_RSH: 14025 if (alu32) 14026 scalar32_min_max_rsh(dst_reg, &src_reg); 14027 else 14028 scalar_min_max_rsh(dst_reg, &src_reg); 14029 break; 14030 case BPF_ARSH: 14031 if (alu32) 14032 scalar32_min_max_arsh(dst_reg, &src_reg); 14033 else 14034 scalar_min_max_arsh(dst_reg, &src_reg); 14035 break; 14036 default: 14037 break; 14038 } 14039 14040 /* ALU32 ops are zero extended into 64bit register */ 14041 if (alu32) 14042 zext_32_to_64(dst_reg); 14043 reg_bounds_sync(dst_reg); 14044 return 0; 14045 } 14046 14047 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14048 * and var_off. 14049 */ 14050 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14051 struct bpf_insn *insn) 14052 { 14053 struct bpf_verifier_state *vstate = env->cur_state; 14054 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14055 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14056 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14057 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14058 u8 opcode = BPF_OP(insn->code); 14059 int err; 14060 14061 dst_reg = ®s[insn->dst_reg]; 14062 src_reg = NULL; 14063 14064 if (dst_reg->type == PTR_TO_ARENA) { 14065 struct bpf_insn_aux_data *aux = cur_aux(env); 14066 14067 if (BPF_CLASS(insn->code) == BPF_ALU64) 14068 /* 14069 * 32-bit operations zero upper bits automatically. 14070 * 64-bit operations need to be converted to 32. 14071 */ 14072 aux->needs_zext = true; 14073 14074 /* Any arithmetic operations are allowed on arena pointers */ 14075 return 0; 14076 } 14077 14078 if (dst_reg->type != SCALAR_VALUE) 14079 ptr_reg = dst_reg; 14080 14081 if (BPF_SRC(insn->code) == BPF_X) { 14082 src_reg = ®s[insn->src_reg]; 14083 if (src_reg->type != SCALAR_VALUE) { 14084 if (dst_reg->type != SCALAR_VALUE) { 14085 /* Combining two pointers by any ALU op yields 14086 * an arbitrary scalar. Disallow all math except 14087 * pointer subtraction 14088 */ 14089 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14090 mark_reg_unknown(env, regs, insn->dst_reg); 14091 return 0; 14092 } 14093 verbose(env, "R%d pointer %s pointer prohibited\n", 14094 insn->dst_reg, 14095 bpf_alu_string[opcode >> 4]); 14096 return -EACCES; 14097 } else { 14098 /* scalar += pointer 14099 * This is legal, but we have to reverse our 14100 * src/dest handling in computing the range 14101 */ 14102 err = mark_chain_precision(env, insn->dst_reg); 14103 if (err) 14104 return err; 14105 return adjust_ptr_min_max_vals(env, insn, 14106 src_reg, dst_reg); 14107 } 14108 } else if (ptr_reg) { 14109 /* pointer += scalar */ 14110 err = mark_chain_precision(env, insn->src_reg); 14111 if (err) 14112 return err; 14113 return adjust_ptr_min_max_vals(env, insn, 14114 dst_reg, src_reg); 14115 } else if (dst_reg->precise) { 14116 /* if dst_reg is precise, src_reg should be precise as well */ 14117 err = mark_chain_precision(env, insn->src_reg); 14118 if (err) 14119 return err; 14120 } 14121 } else { 14122 /* Pretend the src is a reg with a known value, since we only 14123 * need to be able to read from this state. 14124 */ 14125 off_reg.type = SCALAR_VALUE; 14126 __mark_reg_known(&off_reg, insn->imm); 14127 src_reg = &off_reg; 14128 if (ptr_reg) /* pointer += K */ 14129 return adjust_ptr_min_max_vals(env, insn, 14130 ptr_reg, src_reg); 14131 } 14132 14133 /* Got here implies adding two SCALAR_VALUEs */ 14134 if (WARN_ON_ONCE(ptr_reg)) { 14135 print_verifier_state(env, state, true); 14136 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14137 return -EINVAL; 14138 } 14139 if (WARN_ON(!src_reg)) { 14140 print_verifier_state(env, state, true); 14141 verbose(env, "verifier internal error: no src_reg\n"); 14142 return -EINVAL; 14143 } 14144 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14145 if (err) 14146 return err; 14147 /* 14148 * Compilers can generate the code 14149 * r1 = r2 14150 * r1 += 0x1 14151 * if r2 < 1000 goto ... 14152 * use r1 in memory access 14153 * So remember constant delta between r2 and r1 and update r1 after 14154 * 'if' condition. 14155 */ 14156 if (env->bpf_capable && BPF_OP(insn->code) == BPF_ADD && 14157 dst_reg->id && is_reg_const(src_reg, alu32)) { 14158 u64 val = reg_const_value(src_reg, alu32); 14159 14160 if ((dst_reg->id & BPF_ADD_CONST) || 14161 /* prevent overflow in find_equal_scalars() later */ 14162 val > (u32)S32_MAX) { 14163 /* 14164 * If the register already went through rX += val 14165 * we cannot accumulate another val into rx->off. 14166 */ 14167 dst_reg->off = 0; 14168 dst_reg->id = 0; 14169 } else { 14170 dst_reg->id |= BPF_ADD_CONST; 14171 dst_reg->off = val; 14172 } 14173 } else { 14174 /* 14175 * Make sure ID is cleared otherwise dst_reg min/max could be 14176 * incorrectly propagated into other registers by find_equal_scalars() 14177 */ 14178 dst_reg->id = 0; 14179 } 14180 return 0; 14181 } 14182 14183 /* check validity of 32-bit and 64-bit arithmetic operations */ 14184 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14185 { 14186 struct bpf_reg_state *regs = cur_regs(env); 14187 u8 opcode = BPF_OP(insn->code); 14188 int err; 14189 14190 if (opcode == BPF_END || opcode == BPF_NEG) { 14191 if (opcode == BPF_NEG) { 14192 if (BPF_SRC(insn->code) != BPF_K || 14193 insn->src_reg != BPF_REG_0 || 14194 insn->off != 0 || insn->imm != 0) { 14195 verbose(env, "BPF_NEG uses reserved fields\n"); 14196 return -EINVAL; 14197 } 14198 } else { 14199 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 14200 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 14201 (BPF_CLASS(insn->code) == BPF_ALU64 && 14202 BPF_SRC(insn->code) != BPF_TO_LE)) { 14203 verbose(env, "BPF_END uses reserved fields\n"); 14204 return -EINVAL; 14205 } 14206 } 14207 14208 /* check src operand */ 14209 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14210 if (err) 14211 return err; 14212 14213 if (is_pointer_value(env, insn->dst_reg)) { 14214 verbose(env, "R%d pointer arithmetic prohibited\n", 14215 insn->dst_reg); 14216 return -EACCES; 14217 } 14218 14219 /* check dest operand */ 14220 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14221 if (err) 14222 return err; 14223 14224 } else if (opcode == BPF_MOV) { 14225 14226 if (BPF_SRC(insn->code) == BPF_X) { 14227 if (BPF_CLASS(insn->code) == BPF_ALU) { 14228 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14229 insn->imm) { 14230 verbose(env, "BPF_MOV uses reserved fields\n"); 14231 return -EINVAL; 14232 } 14233 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14234 if (insn->imm != 1 && insn->imm != 1u << 16) { 14235 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14236 return -EINVAL; 14237 } 14238 if (!env->prog->aux->arena) { 14239 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14240 return -EINVAL; 14241 } 14242 } else { 14243 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14244 insn->off != 32) || insn->imm) { 14245 verbose(env, "BPF_MOV uses reserved fields\n"); 14246 return -EINVAL; 14247 } 14248 } 14249 14250 /* check src operand */ 14251 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14252 if (err) 14253 return err; 14254 } else { 14255 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14256 verbose(env, "BPF_MOV uses reserved fields\n"); 14257 return -EINVAL; 14258 } 14259 } 14260 14261 /* check dest operand, mark as required later */ 14262 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14263 if (err) 14264 return err; 14265 14266 if (BPF_SRC(insn->code) == BPF_X) { 14267 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14268 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14269 14270 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14271 if (insn->imm) { 14272 /* off == BPF_ADDR_SPACE_CAST */ 14273 mark_reg_unknown(env, regs, insn->dst_reg); 14274 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14275 dst_reg->type = PTR_TO_ARENA; 14276 /* PTR_TO_ARENA is 32-bit */ 14277 dst_reg->subreg_def = env->insn_idx + 1; 14278 } 14279 } else if (insn->off == 0) { 14280 /* case: R1 = R2 14281 * copy register state to dest reg 14282 */ 14283 assign_scalar_id_before_mov(env, src_reg); 14284 copy_register_state(dst_reg, src_reg); 14285 dst_reg->live |= REG_LIVE_WRITTEN; 14286 dst_reg->subreg_def = DEF_NOT_SUBREG; 14287 } else { 14288 /* case: R1 = (s8, s16 s32)R2 */ 14289 if (is_pointer_value(env, insn->src_reg)) { 14290 verbose(env, 14291 "R%d sign-extension part of pointer\n", 14292 insn->src_reg); 14293 return -EACCES; 14294 } else if (src_reg->type == SCALAR_VALUE) { 14295 bool no_sext; 14296 14297 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14298 if (no_sext) 14299 assign_scalar_id_before_mov(env, src_reg); 14300 copy_register_state(dst_reg, src_reg); 14301 if (!no_sext) 14302 dst_reg->id = 0; 14303 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14304 dst_reg->live |= REG_LIVE_WRITTEN; 14305 dst_reg->subreg_def = DEF_NOT_SUBREG; 14306 } else { 14307 mark_reg_unknown(env, regs, insn->dst_reg); 14308 } 14309 } 14310 } else { 14311 /* R1 = (u32) R2 */ 14312 if (is_pointer_value(env, insn->src_reg)) { 14313 verbose(env, 14314 "R%d partial copy of pointer\n", 14315 insn->src_reg); 14316 return -EACCES; 14317 } else if (src_reg->type == SCALAR_VALUE) { 14318 if (insn->off == 0) { 14319 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14320 14321 if (is_src_reg_u32) 14322 assign_scalar_id_before_mov(env, src_reg); 14323 copy_register_state(dst_reg, src_reg); 14324 /* Make sure ID is cleared if src_reg is not in u32 14325 * range otherwise dst_reg min/max could be incorrectly 14326 * propagated into src_reg by find_equal_scalars() 14327 */ 14328 if (!is_src_reg_u32) 14329 dst_reg->id = 0; 14330 dst_reg->live |= REG_LIVE_WRITTEN; 14331 dst_reg->subreg_def = env->insn_idx + 1; 14332 } else { 14333 /* case: W1 = (s8, s16)W2 */ 14334 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14335 14336 if (no_sext) 14337 assign_scalar_id_before_mov(env, src_reg); 14338 copy_register_state(dst_reg, src_reg); 14339 if (!no_sext) 14340 dst_reg->id = 0; 14341 dst_reg->live |= REG_LIVE_WRITTEN; 14342 dst_reg->subreg_def = env->insn_idx + 1; 14343 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14344 } 14345 } else { 14346 mark_reg_unknown(env, regs, 14347 insn->dst_reg); 14348 } 14349 zext_32_to_64(dst_reg); 14350 reg_bounds_sync(dst_reg); 14351 } 14352 } else { 14353 /* case: R = imm 14354 * remember the value we stored into this reg 14355 */ 14356 /* clear any state __mark_reg_known doesn't set */ 14357 mark_reg_unknown(env, regs, insn->dst_reg); 14358 regs[insn->dst_reg].type = SCALAR_VALUE; 14359 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14360 __mark_reg_known(regs + insn->dst_reg, 14361 insn->imm); 14362 } else { 14363 __mark_reg_known(regs + insn->dst_reg, 14364 (u32)insn->imm); 14365 } 14366 } 14367 14368 } else if (opcode > BPF_END) { 14369 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14370 return -EINVAL; 14371 14372 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14373 14374 if (BPF_SRC(insn->code) == BPF_X) { 14375 if (insn->imm != 0 || insn->off > 1 || 14376 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14377 verbose(env, "BPF_ALU uses reserved fields\n"); 14378 return -EINVAL; 14379 } 14380 /* check src1 operand */ 14381 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14382 if (err) 14383 return err; 14384 } else { 14385 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14386 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14387 verbose(env, "BPF_ALU uses reserved fields\n"); 14388 return -EINVAL; 14389 } 14390 } 14391 14392 /* check src2 operand */ 14393 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14394 if (err) 14395 return err; 14396 14397 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14398 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14399 verbose(env, "div by zero\n"); 14400 return -EINVAL; 14401 } 14402 14403 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14404 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14405 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14406 14407 if (insn->imm < 0 || insn->imm >= size) { 14408 verbose(env, "invalid shift %d\n", insn->imm); 14409 return -EINVAL; 14410 } 14411 } 14412 14413 /* check dest operand */ 14414 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14415 err = err ?: adjust_reg_min_max_vals(env, insn); 14416 if (err) 14417 return err; 14418 } 14419 14420 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14421 } 14422 14423 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14424 struct bpf_reg_state *dst_reg, 14425 enum bpf_reg_type type, 14426 bool range_right_open) 14427 { 14428 struct bpf_func_state *state; 14429 struct bpf_reg_state *reg; 14430 int new_range; 14431 14432 if (dst_reg->off < 0 || 14433 (dst_reg->off == 0 && range_right_open)) 14434 /* This doesn't give us any range */ 14435 return; 14436 14437 if (dst_reg->umax_value > MAX_PACKET_OFF || 14438 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14439 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14440 * than pkt_end, but that's because it's also less than pkt. 14441 */ 14442 return; 14443 14444 new_range = dst_reg->off; 14445 if (range_right_open) 14446 new_range++; 14447 14448 /* Examples for register markings: 14449 * 14450 * pkt_data in dst register: 14451 * 14452 * r2 = r3; 14453 * r2 += 8; 14454 * if (r2 > pkt_end) goto <handle exception> 14455 * <access okay> 14456 * 14457 * r2 = r3; 14458 * r2 += 8; 14459 * if (r2 < pkt_end) goto <access okay> 14460 * <handle exception> 14461 * 14462 * Where: 14463 * r2 == dst_reg, pkt_end == src_reg 14464 * r2=pkt(id=n,off=8,r=0) 14465 * r3=pkt(id=n,off=0,r=0) 14466 * 14467 * pkt_data in src register: 14468 * 14469 * r2 = r3; 14470 * r2 += 8; 14471 * if (pkt_end >= r2) goto <access okay> 14472 * <handle exception> 14473 * 14474 * r2 = r3; 14475 * r2 += 8; 14476 * if (pkt_end <= r2) goto <handle exception> 14477 * <access okay> 14478 * 14479 * Where: 14480 * pkt_end == dst_reg, r2 == src_reg 14481 * r2=pkt(id=n,off=8,r=0) 14482 * r3=pkt(id=n,off=0,r=0) 14483 * 14484 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14485 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14486 * and [r3, r3 + 8-1) respectively is safe to access depending on 14487 * the check. 14488 */ 14489 14490 /* If our ids match, then we must have the same max_value. And we 14491 * don't care about the other reg's fixed offset, since if it's too big 14492 * the range won't allow anything. 14493 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14494 */ 14495 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14496 if (reg->type == type && reg->id == dst_reg->id) 14497 /* keep the maximum range already checked */ 14498 reg->range = max(reg->range, new_range); 14499 })); 14500 } 14501 14502 /* 14503 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14504 */ 14505 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14506 u8 opcode, bool is_jmp32) 14507 { 14508 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14509 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14510 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14511 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14512 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14513 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14514 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14515 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14516 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14517 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14518 14519 switch (opcode) { 14520 case BPF_JEQ: 14521 /* constants, umin/umax and smin/smax checks would be 14522 * redundant in this case because they all should match 14523 */ 14524 if (tnum_is_const(t1) && tnum_is_const(t2)) 14525 return t1.value == t2.value; 14526 /* non-overlapping ranges */ 14527 if (umin1 > umax2 || umax1 < umin2) 14528 return 0; 14529 if (smin1 > smax2 || smax1 < smin2) 14530 return 0; 14531 if (!is_jmp32) { 14532 /* if 64-bit ranges are inconclusive, see if we can 14533 * utilize 32-bit subrange knowledge to eliminate 14534 * branches that can't be taken a priori 14535 */ 14536 if (reg1->u32_min_value > reg2->u32_max_value || 14537 reg1->u32_max_value < reg2->u32_min_value) 14538 return 0; 14539 if (reg1->s32_min_value > reg2->s32_max_value || 14540 reg1->s32_max_value < reg2->s32_min_value) 14541 return 0; 14542 } 14543 break; 14544 case BPF_JNE: 14545 /* constants, umin/umax and smin/smax checks would be 14546 * redundant in this case because they all should match 14547 */ 14548 if (tnum_is_const(t1) && tnum_is_const(t2)) 14549 return t1.value != t2.value; 14550 /* non-overlapping ranges */ 14551 if (umin1 > umax2 || umax1 < umin2) 14552 return 1; 14553 if (smin1 > smax2 || smax1 < smin2) 14554 return 1; 14555 if (!is_jmp32) { 14556 /* if 64-bit ranges are inconclusive, see if we can 14557 * utilize 32-bit subrange knowledge to eliminate 14558 * branches that can't be taken a priori 14559 */ 14560 if (reg1->u32_min_value > reg2->u32_max_value || 14561 reg1->u32_max_value < reg2->u32_min_value) 14562 return 1; 14563 if (reg1->s32_min_value > reg2->s32_max_value || 14564 reg1->s32_max_value < reg2->s32_min_value) 14565 return 1; 14566 } 14567 break; 14568 case BPF_JSET: 14569 if (!is_reg_const(reg2, is_jmp32)) { 14570 swap(reg1, reg2); 14571 swap(t1, t2); 14572 } 14573 if (!is_reg_const(reg2, is_jmp32)) 14574 return -1; 14575 if ((~t1.mask & t1.value) & t2.value) 14576 return 1; 14577 if (!((t1.mask | t1.value) & t2.value)) 14578 return 0; 14579 break; 14580 case BPF_JGT: 14581 if (umin1 > umax2) 14582 return 1; 14583 else if (umax1 <= umin2) 14584 return 0; 14585 break; 14586 case BPF_JSGT: 14587 if (smin1 > smax2) 14588 return 1; 14589 else if (smax1 <= smin2) 14590 return 0; 14591 break; 14592 case BPF_JLT: 14593 if (umax1 < umin2) 14594 return 1; 14595 else if (umin1 >= umax2) 14596 return 0; 14597 break; 14598 case BPF_JSLT: 14599 if (smax1 < smin2) 14600 return 1; 14601 else if (smin1 >= smax2) 14602 return 0; 14603 break; 14604 case BPF_JGE: 14605 if (umin1 >= umax2) 14606 return 1; 14607 else if (umax1 < umin2) 14608 return 0; 14609 break; 14610 case BPF_JSGE: 14611 if (smin1 >= smax2) 14612 return 1; 14613 else if (smax1 < smin2) 14614 return 0; 14615 break; 14616 case BPF_JLE: 14617 if (umax1 <= umin2) 14618 return 1; 14619 else if (umin1 > umax2) 14620 return 0; 14621 break; 14622 case BPF_JSLE: 14623 if (smax1 <= smin2) 14624 return 1; 14625 else if (smin1 > smax2) 14626 return 0; 14627 break; 14628 } 14629 14630 return -1; 14631 } 14632 14633 static int flip_opcode(u32 opcode) 14634 { 14635 /* How can we transform "a <op> b" into "b <op> a"? */ 14636 static const u8 opcode_flip[16] = { 14637 /* these stay the same */ 14638 [BPF_JEQ >> 4] = BPF_JEQ, 14639 [BPF_JNE >> 4] = BPF_JNE, 14640 [BPF_JSET >> 4] = BPF_JSET, 14641 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14642 [BPF_JGE >> 4] = BPF_JLE, 14643 [BPF_JGT >> 4] = BPF_JLT, 14644 [BPF_JLE >> 4] = BPF_JGE, 14645 [BPF_JLT >> 4] = BPF_JGT, 14646 [BPF_JSGE >> 4] = BPF_JSLE, 14647 [BPF_JSGT >> 4] = BPF_JSLT, 14648 [BPF_JSLE >> 4] = BPF_JSGE, 14649 [BPF_JSLT >> 4] = BPF_JSGT 14650 }; 14651 return opcode_flip[opcode >> 4]; 14652 } 14653 14654 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14655 struct bpf_reg_state *src_reg, 14656 u8 opcode) 14657 { 14658 struct bpf_reg_state *pkt; 14659 14660 if (src_reg->type == PTR_TO_PACKET_END) { 14661 pkt = dst_reg; 14662 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14663 pkt = src_reg; 14664 opcode = flip_opcode(opcode); 14665 } else { 14666 return -1; 14667 } 14668 14669 if (pkt->range >= 0) 14670 return -1; 14671 14672 switch (opcode) { 14673 case BPF_JLE: 14674 /* pkt <= pkt_end */ 14675 fallthrough; 14676 case BPF_JGT: 14677 /* pkt > pkt_end */ 14678 if (pkt->range == BEYOND_PKT_END) 14679 /* pkt has at last one extra byte beyond pkt_end */ 14680 return opcode == BPF_JGT; 14681 break; 14682 case BPF_JLT: 14683 /* pkt < pkt_end */ 14684 fallthrough; 14685 case BPF_JGE: 14686 /* pkt >= pkt_end */ 14687 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14688 return opcode == BPF_JGE; 14689 break; 14690 } 14691 return -1; 14692 } 14693 14694 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14695 * and return: 14696 * 1 - branch will be taken and "goto target" will be executed 14697 * 0 - branch will not be taken and fall-through to next insn 14698 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14699 * range [0,10] 14700 */ 14701 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14702 u8 opcode, bool is_jmp32) 14703 { 14704 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14705 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14706 14707 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14708 u64 val; 14709 14710 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14711 if (!is_reg_const(reg2, is_jmp32)) { 14712 opcode = flip_opcode(opcode); 14713 swap(reg1, reg2); 14714 } 14715 /* and ensure that reg2 is a constant */ 14716 if (!is_reg_const(reg2, is_jmp32)) 14717 return -1; 14718 14719 if (!reg_not_null(reg1)) 14720 return -1; 14721 14722 /* If pointer is valid tests against zero will fail so we can 14723 * use this to direct branch taken. 14724 */ 14725 val = reg_const_value(reg2, is_jmp32); 14726 if (val != 0) 14727 return -1; 14728 14729 switch (opcode) { 14730 case BPF_JEQ: 14731 return 0; 14732 case BPF_JNE: 14733 return 1; 14734 default: 14735 return -1; 14736 } 14737 } 14738 14739 /* now deal with two scalars, but not necessarily constants */ 14740 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14741 } 14742 14743 /* Opcode that corresponds to a *false* branch condition. 14744 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14745 */ 14746 static u8 rev_opcode(u8 opcode) 14747 { 14748 switch (opcode) { 14749 case BPF_JEQ: return BPF_JNE; 14750 case BPF_JNE: return BPF_JEQ; 14751 /* JSET doesn't have it's reverse opcode in BPF, so add 14752 * BPF_X flag to denote the reverse of that operation 14753 */ 14754 case BPF_JSET: return BPF_JSET | BPF_X; 14755 case BPF_JSET | BPF_X: return BPF_JSET; 14756 case BPF_JGE: return BPF_JLT; 14757 case BPF_JGT: return BPF_JLE; 14758 case BPF_JLE: return BPF_JGT; 14759 case BPF_JLT: return BPF_JGE; 14760 case BPF_JSGE: return BPF_JSLT; 14761 case BPF_JSGT: return BPF_JSLE; 14762 case BPF_JSLE: return BPF_JSGT; 14763 case BPF_JSLT: return BPF_JSGE; 14764 default: return 0; 14765 } 14766 } 14767 14768 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14769 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14770 u8 opcode, bool is_jmp32) 14771 { 14772 struct tnum t; 14773 u64 val; 14774 14775 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 14776 switch (opcode) { 14777 case BPF_JGE: 14778 case BPF_JGT: 14779 case BPF_JSGE: 14780 case BPF_JSGT: 14781 opcode = flip_opcode(opcode); 14782 swap(reg1, reg2); 14783 break; 14784 default: 14785 break; 14786 } 14787 14788 switch (opcode) { 14789 case BPF_JEQ: 14790 if (is_jmp32) { 14791 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14792 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14793 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14794 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14795 reg2->u32_min_value = reg1->u32_min_value; 14796 reg2->u32_max_value = reg1->u32_max_value; 14797 reg2->s32_min_value = reg1->s32_min_value; 14798 reg2->s32_max_value = reg1->s32_max_value; 14799 14800 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14801 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14802 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14803 } else { 14804 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14805 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14806 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14807 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14808 reg2->umin_value = reg1->umin_value; 14809 reg2->umax_value = reg1->umax_value; 14810 reg2->smin_value = reg1->smin_value; 14811 reg2->smax_value = reg1->smax_value; 14812 14813 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14814 reg2->var_off = reg1->var_off; 14815 } 14816 break; 14817 case BPF_JNE: 14818 if (!is_reg_const(reg2, is_jmp32)) 14819 swap(reg1, reg2); 14820 if (!is_reg_const(reg2, is_jmp32)) 14821 break; 14822 14823 /* try to recompute the bound of reg1 if reg2 is a const and 14824 * is exactly the edge of reg1. 14825 */ 14826 val = reg_const_value(reg2, is_jmp32); 14827 if (is_jmp32) { 14828 /* u32_min_value is not equal to 0xffffffff at this point, 14829 * because otherwise u32_max_value is 0xffffffff as well, 14830 * in such a case both reg1 and reg2 would be constants, 14831 * jump would be predicted and reg_set_min_max() won't 14832 * be called. 14833 * 14834 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14835 * below. 14836 */ 14837 if (reg1->u32_min_value == (u32)val) 14838 reg1->u32_min_value++; 14839 if (reg1->u32_max_value == (u32)val) 14840 reg1->u32_max_value--; 14841 if (reg1->s32_min_value == (s32)val) 14842 reg1->s32_min_value++; 14843 if (reg1->s32_max_value == (s32)val) 14844 reg1->s32_max_value--; 14845 } else { 14846 if (reg1->umin_value == (u64)val) 14847 reg1->umin_value++; 14848 if (reg1->umax_value == (u64)val) 14849 reg1->umax_value--; 14850 if (reg1->smin_value == (s64)val) 14851 reg1->smin_value++; 14852 if (reg1->smax_value == (s64)val) 14853 reg1->smax_value--; 14854 } 14855 break; 14856 case BPF_JSET: 14857 if (!is_reg_const(reg2, is_jmp32)) 14858 swap(reg1, reg2); 14859 if (!is_reg_const(reg2, is_jmp32)) 14860 break; 14861 val = reg_const_value(reg2, is_jmp32); 14862 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14863 * requires single bit to learn something useful. E.g., if we 14864 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14865 * are actually set? We can learn something definite only if 14866 * it's a single-bit value to begin with. 14867 * 14868 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14869 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14870 * bit 1 is set, which we can readily use in adjustments. 14871 */ 14872 if (!is_power_of_2(val)) 14873 break; 14874 if (is_jmp32) { 14875 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14876 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14877 } else { 14878 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14879 } 14880 break; 14881 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14882 if (!is_reg_const(reg2, is_jmp32)) 14883 swap(reg1, reg2); 14884 if (!is_reg_const(reg2, is_jmp32)) 14885 break; 14886 val = reg_const_value(reg2, is_jmp32); 14887 if (is_jmp32) { 14888 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14889 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14890 } else { 14891 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14892 } 14893 break; 14894 case BPF_JLE: 14895 if (is_jmp32) { 14896 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14897 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14898 } else { 14899 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14900 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14901 } 14902 break; 14903 case BPF_JLT: 14904 if (is_jmp32) { 14905 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14906 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14907 } else { 14908 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14909 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14910 } 14911 break; 14912 case BPF_JSLE: 14913 if (is_jmp32) { 14914 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14915 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14916 } else { 14917 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14918 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14919 } 14920 break; 14921 case BPF_JSLT: 14922 if (is_jmp32) { 14923 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14924 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14925 } else { 14926 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14927 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14928 } 14929 break; 14930 default: 14931 return; 14932 } 14933 } 14934 14935 /* Adjusts the register min/max values in the case that the dst_reg and 14936 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14937 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 14938 * Technically we can do similar adjustments for pointers to the same object, 14939 * but we don't support that right now. 14940 */ 14941 static int reg_set_min_max(struct bpf_verifier_env *env, 14942 struct bpf_reg_state *true_reg1, 14943 struct bpf_reg_state *true_reg2, 14944 struct bpf_reg_state *false_reg1, 14945 struct bpf_reg_state *false_reg2, 14946 u8 opcode, bool is_jmp32) 14947 { 14948 int err; 14949 14950 /* If either register is a pointer, we can't learn anything about its 14951 * variable offset from the compare (unless they were a pointer into 14952 * the same object, but we don't bother with that). 14953 */ 14954 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14955 return 0; 14956 14957 /* fallthrough (FALSE) branch */ 14958 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14959 reg_bounds_sync(false_reg1); 14960 reg_bounds_sync(false_reg2); 14961 14962 /* jump (TRUE) branch */ 14963 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14964 reg_bounds_sync(true_reg1); 14965 reg_bounds_sync(true_reg2); 14966 14967 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14968 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14969 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14970 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14971 return err; 14972 } 14973 14974 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14975 struct bpf_reg_state *reg, u32 id, 14976 bool is_null) 14977 { 14978 if (type_may_be_null(reg->type) && reg->id == id && 14979 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14980 /* Old offset (both fixed and variable parts) should have been 14981 * known-zero, because we don't allow pointer arithmetic on 14982 * pointers that might be NULL. If we see this happening, don't 14983 * convert the register. 14984 * 14985 * But in some cases, some helpers that return local kptrs 14986 * advance offset for the returned pointer. In those cases, it 14987 * is fine to expect to see reg->off. 14988 */ 14989 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14990 return; 14991 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14992 WARN_ON_ONCE(reg->off)) 14993 return; 14994 14995 if (is_null) { 14996 reg->type = SCALAR_VALUE; 14997 /* We don't need id and ref_obj_id from this point 14998 * onwards anymore, thus we should better reset it, 14999 * so that state pruning has chances to take effect. 15000 */ 15001 reg->id = 0; 15002 reg->ref_obj_id = 0; 15003 15004 return; 15005 } 15006 15007 mark_ptr_not_null_reg(reg); 15008 15009 if (!reg_may_point_to_spin_lock(reg)) { 15010 /* For not-NULL ptr, reg->ref_obj_id will be reset 15011 * in release_reference(). 15012 * 15013 * reg->id is still used by spin_lock ptr. Other 15014 * than spin_lock ptr type, reg->id can be reset. 15015 */ 15016 reg->id = 0; 15017 } 15018 } 15019 } 15020 15021 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15022 * be folded together at some point. 15023 */ 15024 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15025 bool is_null) 15026 { 15027 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15028 struct bpf_reg_state *regs = state->regs, *reg; 15029 u32 ref_obj_id = regs[regno].ref_obj_id; 15030 u32 id = regs[regno].id; 15031 15032 if (ref_obj_id && ref_obj_id == id && is_null) 15033 /* regs[regno] is in the " == NULL" branch. 15034 * No one could have freed the reference state before 15035 * doing the NULL check. 15036 */ 15037 WARN_ON_ONCE(release_reference_state(state, id)); 15038 15039 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15040 mark_ptr_or_null_reg(state, reg, id, is_null); 15041 })); 15042 } 15043 15044 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15045 struct bpf_reg_state *dst_reg, 15046 struct bpf_reg_state *src_reg, 15047 struct bpf_verifier_state *this_branch, 15048 struct bpf_verifier_state *other_branch) 15049 { 15050 if (BPF_SRC(insn->code) != BPF_X) 15051 return false; 15052 15053 /* Pointers are always 64-bit. */ 15054 if (BPF_CLASS(insn->code) == BPF_JMP32) 15055 return false; 15056 15057 switch (BPF_OP(insn->code)) { 15058 case BPF_JGT: 15059 if ((dst_reg->type == PTR_TO_PACKET && 15060 src_reg->type == PTR_TO_PACKET_END) || 15061 (dst_reg->type == PTR_TO_PACKET_META && 15062 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15063 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15064 find_good_pkt_pointers(this_branch, dst_reg, 15065 dst_reg->type, false); 15066 mark_pkt_end(other_branch, insn->dst_reg, true); 15067 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15068 src_reg->type == PTR_TO_PACKET) || 15069 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15070 src_reg->type == PTR_TO_PACKET_META)) { 15071 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15072 find_good_pkt_pointers(other_branch, src_reg, 15073 src_reg->type, true); 15074 mark_pkt_end(this_branch, insn->src_reg, false); 15075 } else { 15076 return false; 15077 } 15078 break; 15079 case BPF_JLT: 15080 if ((dst_reg->type == PTR_TO_PACKET && 15081 src_reg->type == PTR_TO_PACKET_END) || 15082 (dst_reg->type == PTR_TO_PACKET_META && 15083 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15084 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15085 find_good_pkt_pointers(other_branch, dst_reg, 15086 dst_reg->type, true); 15087 mark_pkt_end(this_branch, insn->dst_reg, false); 15088 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15089 src_reg->type == PTR_TO_PACKET) || 15090 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15091 src_reg->type == PTR_TO_PACKET_META)) { 15092 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15093 find_good_pkt_pointers(this_branch, src_reg, 15094 src_reg->type, false); 15095 mark_pkt_end(other_branch, insn->src_reg, true); 15096 } else { 15097 return false; 15098 } 15099 break; 15100 case BPF_JGE: 15101 if ((dst_reg->type == PTR_TO_PACKET && 15102 src_reg->type == PTR_TO_PACKET_END) || 15103 (dst_reg->type == PTR_TO_PACKET_META && 15104 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15105 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15106 find_good_pkt_pointers(this_branch, dst_reg, 15107 dst_reg->type, true); 15108 mark_pkt_end(other_branch, insn->dst_reg, false); 15109 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15110 src_reg->type == PTR_TO_PACKET) || 15111 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15112 src_reg->type == PTR_TO_PACKET_META)) { 15113 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15114 find_good_pkt_pointers(other_branch, src_reg, 15115 src_reg->type, false); 15116 mark_pkt_end(this_branch, insn->src_reg, true); 15117 } else { 15118 return false; 15119 } 15120 break; 15121 case BPF_JLE: 15122 if ((dst_reg->type == PTR_TO_PACKET && 15123 src_reg->type == PTR_TO_PACKET_END) || 15124 (dst_reg->type == PTR_TO_PACKET_META && 15125 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15126 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15127 find_good_pkt_pointers(other_branch, dst_reg, 15128 dst_reg->type, false); 15129 mark_pkt_end(this_branch, insn->dst_reg, true); 15130 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15131 src_reg->type == PTR_TO_PACKET) || 15132 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15133 src_reg->type == PTR_TO_PACKET_META)) { 15134 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15135 find_good_pkt_pointers(this_branch, src_reg, 15136 src_reg->type, true); 15137 mark_pkt_end(other_branch, insn->src_reg, false); 15138 } else { 15139 return false; 15140 } 15141 break; 15142 default: 15143 return false; 15144 } 15145 15146 return true; 15147 } 15148 15149 static void find_equal_scalars(struct bpf_verifier_state *vstate, 15150 struct bpf_reg_state *known_reg) 15151 { 15152 struct bpf_reg_state fake_reg; 15153 struct bpf_func_state *state; 15154 struct bpf_reg_state *reg; 15155 15156 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15157 if (reg->type != SCALAR_VALUE || reg == known_reg) 15158 continue; 15159 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15160 continue; 15161 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15162 reg->off == known_reg->off) { 15163 copy_register_state(reg, known_reg); 15164 } else { 15165 s32 saved_off = reg->off; 15166 15167 fake_reg.type = SCALAR_VALUE; 15168 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 15169 15170 /* reg = known_reg; reg += delta */ 15171 copy_register_state(reg, known_reg); 15172 /* 15173 * Must preserve off, id and add_const flag, 15174 * otherwise another find_equal_scalars() will be incorrect. 15175 */ 15176 reg->off = saved_off; 15177 15178 scalar32_min_max_add(reg, &fake_reg); 15179 scalar_min_max_add(reg, &fake_reg); 15180 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15181 } 15182 })); 15183 } 15184 15185 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15186 struct bpf_insn *insn, int *insn_idx) 15187 { 15188 struct bpf_verifier_state *this_branch = env->cur_state; 15189 struct bpf_verifier_state *other_branch; 15190 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15191 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15192 struct bpf_reg_state *eq_branch_regs; 15193 struct bpf_reg_state fake_reg = {}; 15194 u8 opcode = BPF_OP(insn->code); 15195 bool is_jmp32; 15196 int pred = -1; 15197 int err; 15198 15199 /* Only conditional jumps are expected to reach here. */ 15200 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15201 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15202 return -EINVAL; 15203 } 15204 15205 if (opcode == BPF_JCOND) { 15206 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15207 int idx = *insn_idx; 15208 15209 if (insn->code != (BPF_JMP | BPF_JCOND) || 15210 insn->src_reg != BPF_MAY_GOTO || 15211 insn->dst_reg || insn->imm || insn->off == 0) { 15212 verbose(env, "invalid may_goto off %d imm %d\n", 15213 insn->off, insn->imm); 15214 return -EINVAL; 15215 } 15216 prev_st = find_prev_entry(env, cur_st->parent, idx); 15217 15218 /* branch out 'fallthrough' insn as a new state to explore */ 15219 queued_st = push_stack(env, idx + 1, idx, false); 15220 if (!queued_st) 15221 return -ENOMEM; 15222 15223 queued_st->may_goto_depth++; 15224 if (prev_st) 15225 widen_imprecise_scalars(env, prev_st, queued_st); 15226 *insn_idx += insn->off; 15227 return 0; 15228 } 15229 15230 /* check src2 operand */ 15231 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15232 if (err) 15233 return err; 15234 15235 dst_reg = ®s[insn->dst_reg]; 15236 if (BPF_SRC(insn->code) == BPF_X) { 15237 if (insn->imm != 0) { 15238 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15239 return -EINVAL; 15240 } 15241 15242 /* check src1 operand */ 15243 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15244 if (err) 15245 return err; 15246 15247 src_reg = ®s[insn->src_reg]; 15248 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15249 is_pointer_value(env, insn->src_reg)) { 15250 verbose(env, "R%d pointer comparison prohibited\n", 15251 insn->src_reg); 15252 return -EACCES; 15253 } 15254 } else { 15255 if (insn->src_reg != BPF_REG_0) { 15256 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15257 return -EINVAL; 15258 } 15259 src_reg = &fake_reg; 15260 src_reg->type = SCALAR_VALUE; 15261 __mark_reg_known(src_reg, insn->imm); 15262 } 15263 15264 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15265 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15266 if (pred >= 0) { 15267 /* If we get here with a dst_reg pointer type it is because 15268 * above is_branch_taken() special cased the 0 comparison. 15269 */ 15270 if (!__is_pointer_value(false, dst_reg)) 15271 err = mark_chain_precision(env, insn->dst_reg); 15272 if (BPF_SRC(insn->code) == BPF_X && !err && 15273 !__is_pointer_value(false, src_reg)) 15274 err = mark_chain_precision(env, insn->src_reg); 15275 if (err) 15276 return err; 15277 } 15278 15279 if (pred == 1) { 15280 /* Only follow the goto, ignore fall-through. If needed, push 15281 * the fall-through branch for simulation under speculative 15282 * execution. 15283 */ 15284 if (!env->bypass_spec_v1 && 15285 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15286 *insn_idx)) 15287 return -EFAULT; 15288 if (env->log.level & BPF_LOG_LEVEL) 15289 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15290 *insn_idx += insn->off; 15291 return 0; 15292 } else if (pred == 0) { 15293 /* Only follow the fall-through branch, since that's where the 15294 * program will go. If needed, push the goto branch for 15295 * simulation under speculative execution. 15296 */ 15297 if (!env->bypass_spec_v1 && 15298 !sanitize_speculative_path(env, insn, 15299 *insn_idx + insn->off + 1, 15300 *insn_idx)) 15301 return -EFAULT; 15302 if (env->log.level & BPF_LOG_LEVEL) 15303 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15304 return 0; 15305 } 15306 15307 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15308 false); 15309 if (!other_branch) 15310 return -EFAULT; 15311 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15312 15313 if (BPF_SRC(insn->code) == BPF_X) { 15314 err = reg_set_min_max(env, 15315 &other_branch_regs[insn->dst_reg], 15316 &other_branch_regs[insn->src_reg], 15317 dst_reg, src_reg, opcode, is_jmp32); 15318 } else /* BPF_SRC(insn->code) == BPF_K */ { 15319 err = reg_set_min_max(env, 15320 &other_branch_regs[insn->dst_reg], 15321 src_reg /* fake one */, 15322 dst_reg, src_reg /* same fake one */, 15323 opcode, is_jmp32); 15324 } 15325 if (err) 15326 return err; 15327 15328 if (BPF_SRC(insn->code) == BPF_X && 15329 src_reg->type == SCALAR_VALUE && src_reg->id && 15330 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15331 find_equal_scalars(this_branch, src_reg); 15332 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 15333 } 15334 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15335 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15336 find_equal_scalars(this_branch, dst_reg); 15337 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 15338 } 15339 15340 /* if one pointer register is compared to another pointer 15341 * register check if PTR_MAYBE_NULL could be lifted. 15342 * E.g. register A - maybe null 15343 * register B - not null 15344 * for JNE A, B, ... - A is not null in the false branch; 15345 * for JEQ A, B, ... - A is not null in the true branch. 15346 * 15347 * Since PTR_TO_BTF_ID points to a kernel struct that does 15348 * not need to be null checked by the BPF program, i.e., 15349 * could be null even without PTR_MAYBE_NULL marking, so 15350 * only propagate nullness when neither reg is that type. 15351 */ 15352 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15353 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15354 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15355 base_type(src_reg->type) != PTR_TO_BTF_ID && 15356 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15357 eq_branch_regs = NULL; 15358 switch (opcode) { 15359 case BPF_JEQ: 15360 eq_branch_regs = other_branch_regs; 15361 break; 15362 case BPF_JNE: 15363 eq_branch_regs = regs; 15364 break; 15365 default: 15366 /* do nothing */ 15367 break; 15368 } 15369 if (eq_branch_regs) { 15370 if (type_may_be_null(src_reg->type)) 15371 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15372 else 15373 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15374 } 15375 } 15376 15377 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15378 * NOTE: these optimizations below are related with pointer comparison 15379 * which will never be JMP32. 15380 */ 15381 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15382 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15383 type_may_be_null(dst_reg->type)) { 15384 /* Mark all identical registers in each branch as either 15385 * safe or unknown depending R == 0 or R != 0 conditional. 15386 */ 15387 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15388 opcode == BPF_JNE); 15389 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15390 opcode == BPF_JEQ); 15391 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15392 this_branch, other_branch) && 15393 is_pointer_value(env, insn->dst_reg)) { 15394 verbose(env, "R%d pointer comparison prohibited\n", 15395 insn->dst_reg); 15396 return -EACCES; 15397 } 15398 if (env->log.level & BPF_LOG_LEVEL) 15399 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15400 return 0; 15401 } 15402 15403 /* verify BPF_LD_IMM64 instruction */ 15404 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15405 { 15406 struct bpf_insn_aux_data *aux = cur_aux(env); 15407 struct bpf_reg_state *regs = cur_regs(env); 15408 struct bpf_reg_state *dst_reg; 15409 struct bpf_map *map; 15410 int err; 15411 15412 if (BPF_SIZE(insn->code) != BPF_DW) { 15413 verbose(env, "invalid BPF_LD_IMM insn\n"); 15414 return -EINVAL; 15415 } 15416 if (insn->off != 0) { 15417 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15418 return -EINVAL; 15419 } 15420 15421 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15422 if (err) 15423 return err; 15424 15425 dst_reg = ®s[insn->dst_reg]; 15426 if (insn->src_reg == 0) { 15427 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15428 15429 dst_reg->type = SCALAR_VALUE; 15430 __mark_reg_known(®s[insn->dst_reg], imm); 15431 return 0; 15432 } 15433 15434 /* All special src_reg cases are listed below. From this point onwards 15435 * we either succeed and assign a corresponding dst_reg->type after 15436 * zeroing the offset, or fail and reject the program. 15437 */ 15438 mark_reg_known_zero(env, regs, insn->dst_reg); 15439 15440 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15441 dst_reg->type = aux->btf_var.reg_type; 15442 switch (base_type(dst_reg->type)) { 15443 case PTR_TO_MEM: 15444 dst_reg->mem_size = aux->btf_var.mem_size; 15445 break; 15446 case PTR_TO_BTF_ID: 15447 dst_reg->btf = aux->btf_var.btf; 15448 dst_reg->btf_id = aux->btf_var.btf_id; 15449 break; 15450 default: 15451 verbose(env, "bpf verifier is misconfigured\n"); 15452 return -EFAULT; 15453 } 15454 return 0; 15455 } 15456 15457 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15458 struct bpf_prog_aux *aux = env->prog->aux; 15459 u32 subprogno = find_subprog(env, 15460 env->insn_idx + insn->imm + 1); 15461 15462 if (!aux->func_info) { 15463 verbose(env, "missing btf func_info\n"); 15464 return -EINVAL; 15465 } 15466 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15467 verbose(env, "callback function not static\n"); 15468 return -EINVAL; 15469 } 15470 15471 dst_reg->type = PTR_TO_FUNC; 15472 dst_reg->subprogno = subprogno; 15473 return 0; 15474 } 15475 15476 map = env->used_maps[aux->map_index]; 15477 dst_reg->map_ptr = map; 15478 15479 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15480 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15481 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15482 __mark_reg_unknown(env, dst_reg); 15483 return 0; 15484 } 15485 dst_reg->type = PTR_TO_MAP_VALUE; 15486 dst_reg->off = aux->map_off; 15487 WARN_ON_ONCE(map->max_entries != 1); 15488 /* We want reg->id to be same (0) as map_value is not distinct */ 15489 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15490 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15491 dst_reg->type = CONST_PTR_TO_MAP; 15492 } else { 15493 verbose(env, "bpf verifier is misconfigured\n"); 15494 return -EINVAL; 15495 } 15496 15497 return 0; 15498 } 15499 15500 static bool may_access_skb(enum bpf_prog_type type) 15501 { 15502 switch (type) { 15503 case BPF_PROG_TYPE_SOCKET_FILTER: 15504 case BPF_PROG_TYPE_SCHED_CLS: 15505 case BPF_PROG_TYPE_SCHED_ACT: 15506 return true; 15507 default: 15508 return false; 15509 } 15510 } 15511 15512 /* verify safety of LD_ABS|LD_IND instructions: 15513 * - they can only appear in the programs where ctx == skb 15514 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15515 * preserve R6-R9, and store return value into R0 15516 * 15517 * Implicit input: 15518 * ctx == skb == R6 == CTX 15519 * 15520 * Explicit input: 15521 * SRC == any register 15522 * IMM == 32-bit immediate 15523 * 15524 * Output: 15525 * R0 - 8/16/32-bit skb data converted to cpu endianness 15526 */ 15527 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15528 { 15529 struct bpf_reg_state *regs = cur_regs(env); 15530 static const int ctx_reg = BPF_REG_6; 15531 u8 mode = BPF_MODE(insn->code); 15532 int i, err; 15533 15534 if (!may_access_skb(resolve_prog_type(env->prog))) { 15535 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15536 return -EINVAL; 15537 } 15538 15539 if (!env->ops->gen_ld_abs) { 15540 verbose(env, "bpf verifier is misconfigured\n"); 15541 return -EINVAL; 15542 } 15543 15544 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15545 BPF_SIZE(insn->code) == BPF_DW || 15546 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15547 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15548 return -EINVAL; 15549 } 15550 15551 /* check whether implicit source operand (register R6) is readable */ 15552 err = check_reg_arg(env, ctx_reg, SRC_OP); 15553 if (err) 15554 return err; 15555 15556 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15557 * gen_ld_abs() may terminate the program at runtime, leading to 15558 * reference leak. 15559 */ 15560 err = check_reference_leak(env, false); 15561 if (err) { 15562 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15563 return err; 15564 } 15565 15566 if (env->cur_state->active_lock.ptr) { 15567 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15568 return -EINVAL; 15569 } 15570 15571 if (env->cur_state->active_rcu_lock) { 15572 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15573 return -EINVAL; 15574 } 15575 15576 if (env->cur_state->active_preempt_lock) { 15577 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_preempt_disable-ed region\n"); 15578 return -EINVAL; 15579 } 15580 15581 if (regs[ctx_reg].type != PTR_TO_CTX) { 15582 verbose(env, 15583 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15584 return -EINVAL; 15585 } 15586 15587 if (mode == BPF_IND) { 15588 /* check explicit source operand */ 15589 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15590 if (err) 15591 return err; 15592 } 15593 15594 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15595 if (err < 0) 15596 return err; 15597 15598 /* reset caller saved regs to unreadable */ 15599 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15600 mark_reg_not_init(env, regs, caller_saved[i]); 15601 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15602 } 15603 15604 /* mark destination R0 register as readable, since it contains 15605 * the value fetched from the packet. 15606 * Already marked as written above. 15607 */ 15608 mark_reg_unknown(env, regs, BPF_REG_0); 15609 /* ld_abs load up to 32-bit skb data. */ 15610 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15611 return 0; 15612 } 15613 15614 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15615 { 15616 const char *exit_ctx = "At program exit"; 15617 struct tnum enforce_attach_type_range = tnum_unknown; 15618 const struct bpf_prog *prog = env->prog; 15619 struct bpf_reg_state *reg; 15620 struct bpf_retval_range range = retval_range(0, 1); 15621 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15622 int err; 15623 struct bpf_func_state *frame = env->cur_state->frame[0]; 15624 const bool is_subprog = frame->subprogno; 15625 15626 /* LSM and struct_ops func-ptr's return type could be "void" */ 15627 if (!is_subprog || frame->in_exception_callback_fn) { 15628 switch (prog_type) { 15629 case BPF_PROG_TYPE_LSM: 15630 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15631 /* See below, can be 0 or 0-1 depending on hook. */ 15632 break; 15633 fallthrough; 15634 case BPF_PROG_TYPE_STRUCT_OPS: 15635 if (!prog->aux->attach_func_proto->type) 15636 return 0; 15637 break; 15638 default: 15639 break; 15640 } 15641 } 15642 15643 /* eBPF calling convention is such that R0 is used 15644 * to return the value from eBPF program. 15645 * Make sure that it's readable at this time 15646 * of bpf_exit, which means that program wrote 15647 * something into it earlier 15648 */ 15649 err = check_reg_arg(env, regno, SRC_OP); 15650 if (err) 15651 return err; 15652 15653 if (is_pointer_value(env, regno)) { 15654 verbose(env, "R%d leaks addr as return value\n", regno); 15655 return -EACCES; 15656 } 15657 15658 reg = cur_regs(env) + regno; 15659 15660 if (frame->in_async_callback_fn) { 15661 /* enforce return zero from async callbacks like timer */ 15662 exit_ctx = "At async callback return"; 15663 range = retval_range(0, 0); 15664 goto enforce_retval; 15665 } 15666 15667 if (is_subprog && !frame->in_exception_callback_fn) { 15668 if (reg->type != SCALAR_VALUE) { 15669 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15670 regno, reg_type_str(env, reg->type)); 15671 return -EINVAL; 15672 } 15673 return 0; 15674 } 15675 15676 switch (prog_type) { 15677 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15678 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15679 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15680 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15681 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15682 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15683 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15684 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15685 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15686 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15687 range = retval_range(1, 1); 15688 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15689 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15690 range = retval_range(0, 3); 15691 break; 15692 case BPF_PROG_TYPE_CGROUP_SKB: 15693 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15694 range = retval_range(0, 3); 15695 enforce_attach_type_range = tnum_range(2, 3); 15696 } 15697 break; 15698 case BPF_PROG_TYPE_CGROUP_SOCK: 15699 case BPF_PROG_TYPE_SOCK_OPS: 15700 case BPF_PROG_TYPE_CGROUP_DEVICE: 15701 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15702 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15703 break; 15704 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15705 if (!env->prog->aux->attach_btf_id) 15706 return 0; 15707 range = retval_range(0, 0); 15708 break; 15709 case BPF_PROG_TYPE_TRACING: 15710 switch (env->prog->expected_attach_type) { 15711 case BPF_TRACE_FENTRY: 15712 case BPF_TRACE_FEXIT: 15713 range = retval_range(0, 0); 15714 break; 15715 case BPF_TRACE_RAW_TP: 15716 case BPF_MODIFY_RETURN: 15717 return 0; 15718 case BPF_TRACE_ITER: 15719 break; 15720 default: 15721 return -ENOTSUPP; 15722 } 15723 break; 15724 case BPF_PROG_TYPE_SK_LOOKUP: 15725 range = retval_range(SK_DROP, SK_PASS); 15726 break; 15727 15728 case BPF_PROG_TYPE_LSM: 15729 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15730 /* Regular BPF_PROG_TYPE_LSM programs can return 15731 * any value. 15732 */ 15733 return 0; 15734 } 15735 if (!env->prog->aux->attach_func_proto->type) { 15736 /* Make sure programs that attach to void 15737 * hooks don't try to modify return value. 15738 */ 15739 range = retval_range(1, 1); 15740 } 15741 break; 15742 15743 case BPF_PROG_TYPE_NETFILTER: 15744 range = retval_range(NF_DROP, NF_ACCEPT); 15745 break; 15746 case BPF_PROG_TYPE_EXT: 15747 /* freplace program can return anything as its return value 15748 * depends on the to-be-replaced kernel func or bpf program. 15749 */ 15750 default: 15751 return 0; 15752 } 15753 15754 enforce_retval: 15755 if (reg->type != SCALAR_VALUE) { 15756 verbose(env, "%s the register R%d is not a known value (%s)\n", 15757 exit_ctx, regno, reg_type_str(env, reg->type)); 15758 return -EINVAL; 15759 } 15760 15761 err = mark_chain_precision(env, regno); 15762 if (err) 15763 return err; 15764 15765 if (!retval_range_within(range, reg)) { 15766 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15767 if (!is_subprog && 15768 prog->expected_attach_type == BPF_LSM_CGROUP && 15769 prog_type == BPF_PROG_TYPE_LSM && 15770 !prog->aux->attach_func_proto->type) 15771 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15772 return -EINVAL; 15773 } 15774 15775 if (!tnum_is_unknown(enforce_attach_type_range) && 15776 tnum_in(enforce_attach_type_range, reg->var_off)) 15777 env->prog->enforce_expected_attach_type = 1; 15778 return 0; 15779 } 15780 15781 /* non-recursive DFS pseudo code 15782 * 1 procedure DFS-iterative(G,v): 15783 * 2 label v as discovered 15784 * 3 let S be a stack 15785 * 4 S.push(v) 15786 * 5 while S is not empty 15787 * 6 t <- S.peek() 15788 * 7 if t is what we're looking for: 15789 * 8 return t 15790 * 9 for all edges e in G.adjacentEdges(t) do 15791 * 10 if edge e is already labelled 15792 * 11 continue with the next edge 15793 * 12 w <- G.adjacentVertex(t,e) 15794 * 13 if vertex w is not discovered and not explored 15795 * 14 label e as tree-edge 15796 * 15 label w as discovered 15797 * 16 S.push(w) 15798 * 17 continue at 5 15799 * 18 else if vertex w is discovered 15800 * 19 label e as back-edge 15801 * 20 else 15802 * 21 // vertex w is explored 15803 * 22 label e as forward- or cross-edge 15804 * 23 label t as explored 15805 * 24 S.pop() 15806 * 15807 * convention: 15808 * 0x10 - discovered 15809 * 0x11 - discovered and fall-through edge labelled 15810 * 0x12 - discovered and fall-through and branch edges labelled 15811 * 0x20 - explored 15812 */ 15813 15814 enum { 15815 DISCOVERED = 0x10, 15816 EXPLORED = 0x20, 15817 FALLTHROUGH = 1, 15818 BRANCH = 2, 15819 }; 15820 15821 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15822 { 15823 env->insn_aux_data[idx].prune_point = true; 15824 } 15825 15826 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15827 { 15828 return env->insn_aux_data[insn_idx].prune_point; 15829 } 15830 15831 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15832 { 15833 env->insn_aux_data[idx].force_checkpoint = true; 15834 } 15835 15836 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15837 { 15838 return env->insn_aux_data[insn_idx].force_checkpoint; 15839 } 15840 15841 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15842 { 15843 env->insn_aux_data[idx].calls_callback = true; 15844 } 15845 15846 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15847 { 15848 return env->insn_aux_data[insn_idx].calls_callback; 15849 } 15850 15851 enum { 15852 DONE_EXPLORING = 0, 15853 KEEP_EXPLORING = 1, 15854 }; 15855 15856 /* t, w, e - match pseudo-code above: 15857 * t - index of current instruction 15858 * w - next instruction 15859 * e - edge 15860 */ 15861 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15862 { 15863 int *insn_stack = env->cfg.insn_stack; 15864 int *insn_state = env->cfg.insn_state; 15865 15866 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15867 return DONE_EXPLORING; 15868 15869 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15870 return DONE_EXPLORING; 15871 15872 if (w < 0 || w >= env->prog->len) { 15873 verbose_linfo(env, t, "%d: ", t); 15874 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15875 return -EINVAL; 15876 } 15877 15878 if (e == BRANCH) { 15879 /* mark branch target for state pruning */ 15880 mark_prune_point(env, w); 15881 mark_jmp_point(env, w); 15882 } 15883 15884 if (insn_state[w] == 0) { 15885 /* tree-edge */ 15886 insn_state[t] = DISCOVERED | e; 15887 insn_state[w] = DISCOVERED; 15888 if (env->cfg.cur_stack >= env->prog->len) 15889 return -E2BIG; 15890 insn_stack[env->cfg.cur_stack++] = w; 15891 return KEEP_EXPLORING; 15892 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15893 if (env->bpf_capable) 15894 return DONE_EXPLORING; 15895 verbose_linfo(env, t, "%d: ", t); 15896 verbose_linfo(env, w, "%d: ", w); 15897 verbose(env, "back-edge from insn %d to %d\n", t, w); 15898 return -EINVAL; 15899 } else if (insn_state[w] == EXPLORED) { 15900 /* forward- or cross-edge */ 15901 insn_state[t] = DISCOVERED | e; 15902 } else { 15903 verbose(env, "insn state internal bug\n"); 15904 return -EFAULT; 15905 } 15906 return DONE_EXPLORING; 15907 } 15908 15909 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15910 struct bpf_verifier_env *env, 15911 bool visit_callee) 15912 { 15913 int ret, insn_sz; 15914 15915 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15916 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15917 if (ret) 15918 return ret; 15919 15920 mark_prune_point(env, t + insn_sz); 15921 /* when we exit from subprog, we need to record non-linear history */ 15922 mark_jmp_point(env, t + insn_sz); 15923 15924 if (visit_callee) { 15925 mark_prune_point(env, t); 15926 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15927 } 15928 return ret; 15929 } 15930 15931 /* Visits the instruction at index t and returns one of the following: 15932 * < 0 - an error occurred 15933 * DONE_EXPLORING - the instruction was fully explored 15934 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15935 */ 15936 static int visit_insn(int t, struct bpf_verifier_env *env) 15937 { 15938 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15939 int ret, off, insn_sz; 15940 15941 if (bpf_pseudo_func(insn)) 15942 return visit_func_call_insn(t, insns, env, true); 15943 15944 /* All non-branch instructions have a single fall-through edge. */ 15945 if (BPF_CLASS(insn->code) != BPF_JMP && 15946 BPF_CLASS(insn->code) != BPF_JMP32) { 15947 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15948 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15949 } 15950 15951 switch (BPF_OP(insn->code)) { 15952 case BPF_EXIT: 15953 return DONE_EXPLORING; 15954 15955 case BPF_CALL: 15956 if (is_async_callback_calling_insn(insn)) 15957 /* Mark this call insn as a prune point to trigger 15958 * is_state_visited() check before call itself is 15959 * processed by __check_func_call(). Otherwise new 15960 * async state will be pushed for further exploration. 15961 */ 15962 mark_prune_point(env, t); 15963 /* For functions that invoke callbacks it is not known how many times 15964 * callback would be called. Verifier models callback calling functions 15965 * by repeatedly visiting callback bodies and returning to origin call 15966 * instruction. 15967 * In order to stop such iteration verifier needs to identify when a 15968 * state identical some state from a previous iteration is reached. 15969 * Check below forces creation of checkpoint before callback calling 15970 * instruction to allow search for such identical states. 15971 */ 15972 if (is_sync_callback_calling_insn(insn)) { 15973 mark_calls_callback(env, t); 15974 mark_force_checkpoint(env, t); 15975 mark_prune_point(env, t); 15976 mark_jmp_point(env, t); 15977 } 15978 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15979 struct bpf_kfunc_call_arg_meta meta; 15980 15981 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15982 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15983 mark_prune_point(env, t); 15984 /* Checking and saving state checkpoints at iter_next() call 15985 * is crucial for fast convergence of open-coded iterator loop 15986 * logic, so we need to force it. If we don't do that, 15987 * is_state_visited() might skip saving a checkpoint, causing 15988 * unnecessarily long sequence of not checkpointed 15989 * instructions and jumps, leading to exhaustion of jump 15990 * history buffer, and potentially other undesired outcomes. 15991 * It is expected that with correct open-coded iterators 15992 * convergence will happen quickly, so we don't run a risk of 15993 * exhausting memory. 15994 */ 15995 mark_force_checkpoint(env, t); 15996 } 15997 } 15998 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15999 16000 case BPF_JA: 16001 if (BPF_SRC(insn->code) != BPF_K) 16002 return -EINVAL; 16003 16004 if (BPF_CLASS(insn->code) == BPF_JMP) 16005 off = insn->off; 16006 else 16007 off = insn->imm; 16008 16009 /* unconditional jump with single edge */ 16010 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 16011 if (ret) 16012 return ret; 16013 16014 mark_prune_point(env, t + off + 1); 16015 mark_jmp_point(env, t + off + 1); 16016 16017 return ret; 16018 16019 default: 16020 /* conditional jump with two edges */ 16021 mark_prune_point(env, t); 16022 if (is_may_goto_insn(insn)) 16023 mark_force_checkpoint(env, t); 16024 16025 ret = push_insn(t, t + 1, FALLTHROUGH, env); 16026 if (ret) 16027 return ret; 16028 16029 return push_insn(t, t + insn->off + 1, BRANCH, env); 16030 } 16031 } 16032 16033 /* non-recursive depth-first-search to detect loops in BPF program 16034 * loop == back-edge in directed graph 16035 */ 16036 static int check_cfg(struct bpf_verifier_env *env) 16037 { 16038 int insn_cnt = env->prog->len; 16039 int *insn_stack, *insn_state; 16040 int ex_insn_beg, i, ret = 0; 16041 bool ex_done = false; 16042 16043 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16044 if (!insn_state) 16045 return -ENOMEM; 16046 16047 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 16048 if (!insn_stack) { 16049 kvfree(insn_state); 16050 return -ENOMEM; 16051 } 16052 16053 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 16054 insn_stack[0] = 0; /* 0 is the first instruction */ 16055 env->cfg.cur_stack = 1; 16056 16057 walk_cfg: 16058 while (env->cfg.cur_stack > 0) { 16059 int t = insn_stack[env->cfg.cur_stack - 1]; 16060 16061 ret = visit_insn(t, env); 16062 switch (ret) { 16063 case DONE_EXPLORING: 16064 insn_state[t] = EXPLORED; 16065 env->cfg.cur_stack--; 16066 break; 16067 case KEEP_EXPLORING: 16068 break; 16069 default: 16070 if (ret > 0) { 16071 verbose(env, "visit_insn internal bug\n"); 16072 ret = -EFAULT; 16073 } 16074 goto err_free; 16075 } 16076 } 16077 16078 if (env->cfg.cur_stack < 0) { 16079 verbose(env, "pop stack internal bug\n"); 16080 ret = -EFAULT; 16081 goto err_free; 16082 } 16083 16084 if (env->exception_callback_subprog && !ex_done) { 16085 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 16086 16087 insn_state[ex_insn_beg] = DISCOVERED; 16088 insn_stack[0] = ex_insn_beg; 16089 env->cfg.cur_stack = 1; 16090 ex_done = true; 16091 goto walk_cfg; 16092 } 16093 16094 for (i = 0; i < insn_cnt; i++) { 16095 struct bpf_insn *insn = &env->prog->insnsi[i]; 16096 16097 if (insn_state[i] != EXPLORED) { 16098 verbose(env, "unreachable insn %d\n", i); 16099 ret = -EINVAL; 16100 goto err_free; 16101 } 16102 if (bpf_is_ldimm64(insn)) { 16103 if (insn_state[i + 1] != 0) { 16104 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 16105 ret = -EINVAL; 16106 goto err_free; 16107 } 16108 i++; /* skip second half of ldimm64 */ 16109 } 16110 } 16111 ret = 0; /* cfg looks good */ 16112 16113 err_free: 16114 kvfree(insn_state); 16115 kvfree(insn_stack); 16116 env->cfg.insn_state = env->cfg.insn_stack = NULL; 16117 return ret; 16118 } 16119 16120 static int check_abnormal_return(struct bpf_verifier_env *env) 16121 { 16122 int i; 16123 16124 for (i = 1; i < env->subprog_cnt; i++) { 16125 if (env->subprog_info[i].has_ld_abs) { 16126 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 16127 return -EINVAL; 16128 } 16129 if (env->subprog_info[i].has_tail_call) { 16130 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 16131 return -EINVAL; 16132 } 16133 } 16134 return 0; 16135 } 16136 16137 /* The minimum supported BTF func info size */ 16138 #define MIN_BPF_FUNCINFO_SIZE 8 16139 #define MAX_FUNCINFO_REC_SIZE 252 16140 16141 static int check_btf_func_early(struct bpf_verifier_env *env, 16142 const union bpf_attr *attr, 16143 bpfptr_t uattr) 16144 { 16145 u32 krec_size = sizeof(struct bpf_func_info); 16146 const struct btf_type *type, *func_proto; 16147 u32 i, nfuncs, urec_size, min_size; 16148 struct bpf_func_info *krecord; 16149 struct bpf_prog *prog; 16150 const struct btf *btf; 16151 u32 prev_offset = 0; 16152 bpfptr_t urecord; 16153 int ret = -ENOMEM; 16154 16155 nfuncs = attr->func_info_cnt; 16156 if (!nfuncs) { 16157 if (check_abnormal_return(env)) 16158 return -EINVAL; 16159 return 0; 16160 } 16161 16162 urec_size = attr->func_info_rec_size; 16163 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 16164 urec_size > MAX_FUNCINFO_REC_SIZE || 16165 urec_size % sizeof(u32)) { 16166 verbose(env, "invalid func info rec size %u\n", urec_size); 16167 return -EINVAL; 16168 } 16169 16170 prog = env->prog; 16171 btf = prog->aux->btf; 16172 16173 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16174 min_size = min_t(u32, krec_size, urec_size); 16175 16176 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 16177 if (!krecord) 16178 return -ENOMEM; 16179 16180 for (i = 0; i < nfuncs; i++) { 16181 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 16182 if (ret) { 16183 if (ret == -E2BIG) { 16184 verbose(env, "nonzero tailing record in func info"); 16185 /* set the size kernel expects so loader can zero 16186 * out the rest of the record. 16187 */ 16188 if (copy_to_bpfptr_offset(uattr, 16189 offsetof(union bpf_attr, func_info_rec_size), 16190 &min_size, sizeof(min_size))) 16191 ret = -EFAULT; 16192 } 16193 goto err_free; 16194 } 16195 16196 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 16197 ret = -EFAULT; 16198 goto err_free; 16199 } 16200 16201 /* check insn_off */ 16202 ret = -EINVAL; 16203 if (i == 0) { 16204 if (krecord[i].insn_off) { 16205 verbose(env, 16206 "nonzero insn_off %u for the first func info record", 16207 krecord[i].insn_off); 16208 goto err_free; 16209 } 16210 } else if (krecord[i].insn_off <= prev_offset) { 16211 verbose(env, 16212 "same or smaller insn offset (%u) than previous func info record (%u)", 16213 krecord[i].insn_off, prev_offset); 16214 goto err_free; 16215 } 16216 16217 /* check type_id */ 16218 type = btf_type_by_id(btf, krecord[i].type_id); 16219 if (!type || !btf_type_is_func(type)) { 16220 verbose(env, "invalid type id %d in func info", 16221 krecord[i].type_id); 16222 goto err_free; 16223 } 16224 16225 func_proto = btf_type_by_id(btf, type->type); 16226 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 16227 /* btf_func_check() already verified it during BTF load */ 16228 goto err_free; 16229 16230 prev_offset = krecord[i].insn_off; 16231 bpfptr_add(&urecord, urec_size); 16232 } 16233 16234 prog->aux->func_info = krecord; 16235 prog->aux->func_info_cnt = nfuncs; 16236 return 0; 16237 16238 err_free: 16239 kvfree(krecord); 16240 return ret; 16241 } 16242 16243 static int check_btf_func(struct bpf_verifier_env *env, 16244 const union bpf_attr *attr, 16245 bpfptr_t uattr) 16246 { 16247 const struct btf_type *type, *func_proto, *ret_type; 16248 u32 i, nfuncs, urec_size; 16249 struct bpf_func_info *krecord; 16250 struct bpf_func_info_aux *info_aux = NULL; 16251 struct bpf_prog *prog; 16252 const struct btf *btf; 16253 bpfptr_t urecord; 16254 bool scalar_return; 16255 int ret = -ENOMEM; 16256 16257 nfuncs = attr->func_info_cnt; 16258 if (!nfuncs) { 16259 if (check_abnormal_return(env)) 16260 return -EINVAL; 16261 return 0; 16262 } 16263 if (nfuncs != env->subprog_cnt) { 16264 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16265 return -EINVAL; 16266 } 16267 16268 urec_size = attr->func_info_rec_size; 16269 16270 prog = env->prog; 16271 btf = prog->aux->btf; 16272 16273 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16274 16275 krecord = prog->aux->func_info; 16276 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16277 if (!info_aux) 16278 return -ENOMEM; 16279 16280 for (i = 0; i < nfuncs; i++) { 16281 /* check insn_off */ 16282 ret = -EINVAL; 16283 16284 if (env->subprog_info[i].start != krecord[i].insn_off) { 16285 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16286 goto err_free; 16287 } 16288 16289 /* Already checked type_id */ 16290 type = btf_type_by_id(btf, krecord[i].type_id); 16291 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16292 /* Already checked func_proto */ 16293 func_proto = btf_type_by_id(btf, type->type); 16294 16295 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16296 scalar_return = 16297 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16298 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16299 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16300 goto err_free; 16301 } 16302 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16303 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16304 goto err_free; 16305 } 16306 16307 bpfptr_add(&urecord, urec_size); 16308 } 16309 16310 prog->aux->func_info_aux = info_aux; 16311 return 0; 16312 16313 err_free: 16314 kfree(info_aux); 16315 return ret; 16316 } 16317 16318 static void adjust_btf_func(struct bpf_verifier_env *env) 16319 { 16320 struct bpf_prog_aux *aux = env->prog->aux; 16321 int i; 16322 16323 if (!aux->func_info) 16324 return; 16325 16326 /* func_info is not available for hidden subprogs */ 16327 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16328 aux->func_info[i].insn_off = env->subprog_info[i].start; 16329 } 16330 16331 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16332 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16333 16334 static int check_btf_line(struct bpf_verifier_env *env, 16335 const union bpf_attr *attr, 16336 bpfptr_t uattr) 16337 { 16338 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16339 struct bpf_subprog_info *sub; 16340 struct bpf_line_info *linfo; 16341 struct bpf_prog *prog; 16342 const struct btf *btf; 16343 bpfptr_t ulinfo; 16344 int err; 16345 16346 nr_linfo = attr->line_info_cnt; 16347 if (!nr_linfo) 16348 return 0; 16349 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16350 return -EINVAL; 16351 16352 rec_size = attr->line_info_rec_size; 16353 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16354 rec_size > MAX_LINEINFO_REC_SIZE || 16355 rec_size & (sizeof(u32) - 1)) 16356 return -EINVAL; 16357 16358 /* Need to zero it in case the userspace may 16359 * pass in a smaller bpf_line_info object. 16360 */ 16361 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16362 GFP_KERNEL | __GFP_NOWARN); 16363 if (!linfo) 16364 return -ENOMEM; 16365 16366 prog = env->prog; 16367 btf = prog->aux->btf; 16368 16369 s = 0; 16370 sub = env->subprog_info; 16371 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16372 expected_size = sizeof(struct bpf_line_info); 16373 ncopy = min_t(u32, expected_size, rec_size); 16374 for (i = 0; i < nr_linfo; i++) { 16375 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16376 if (err) { 16377 if (err == -E2BIG) { 16378 verbose(env, "nonzero tailing record in line_info"); 16379 if (copy_to_bpfptr_offset(uattr, 16380 offsetof(union bpf_attr, line_info_rec_size), 16381 &expected_size, sizeof(expected_size))) 16382 err = -EFAULT; 16383 } 16384 goto err_free; 16385 } 16386 16387 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16388 err = -EFAULT; 16389 goto err_free; 16390 } 16391 16392 /* 16393 * Check insn_off to ensure 16394 * 1) strictly increasing AND 16395 * 2) bounded by prog->len 16396 * 16397 * The linfo[0].insn_off == 0 check logically falls into 16398 * the later "missing bpf_line_info for func..." case 16399 * because the first linfo[0].insn_off must be the 16400 * first sub also and the first sub must have 16401 * subprog_info[0].start == 0. 16402 */ 16403 if ((i && linfo[i].insn_off <= prev_offset) || 16404 linfo[i].insn_off >= prog->len) { 16405 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16406 i, linfo[i].insn_off, prev_offset, 16407 prog->len); 16408 err = -EINVAL; 16409 goto err_free; 16410 } 16411 16412 if (!prog->insnsi[linfo[i].insn_off].code) { 16413 verbose(env, 16414 "Invalid insn code at line_info[%u].insn_off\n", 16415 i); 16416 err = -EINVAL; 16417 goto err_free; 16418 } 16419 16420 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16421 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16422 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16423 err = -EINVAL; 16424 goto err_free; 16425 } 16426 16427 if (s != env->subprog_cnt) { 16428 if (linfo[i].insn_off == sub[s].start) { 16429 sub[s].linfo_idx = i; 16430 s++; 16431 } else if (sub[s].start < linfo[i].insn_off) { 16432 verbose(env, "missing bpf_line_info for func#%u\n", s); 16433 err = -EINVAL; 16434 goto err_free; 16435 } 16436 } 16437 16438 prev_offset = linfo[i].insn_off; 16439 bpfptr_add(&ulinfo, rec_size); 16440 } 16441 16442 if (s != env->subprog_cnt) { 16443 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16444 env->subprog_cnt - s, s); 16445 err = -EINVAL; 16446 goto err_free; 16447 } 16448 16449 prog->aux->linfo = linfo; 16450 prog->aux->nr_linfo = nr_linfo; 16451 16452 return 0; 16453 16454 err_free: 16455 kvfree(linfo); 16456 return err; 16457 } 16458 16459 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16460 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16461 16462 static int check_core_relo(struct bpf_verifier_env *env, 16463 const union bpf_attr *attr, 16464 bpfptr_t uattr) 16465 { 16466 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16467 struct bpf_core_relo core_relo = {}; 16468 struct bpf_prog *prog = env->prog; 16469 const struct btf *btf = prog->aux->btf; 16470 struct bpf_core_ctx ctx = { 16471 .log = &env->log, 16472 .btf = btf, 16473 }; 16474 bpfptr_t u_core_relo; 16475 int err; 16476 16477 nr_core_relo = attr->core_relo_cnt; 16478 if (!nr_core_relo) 16479 return 0; 16480 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16481 return -EINVAL; 16482 16483 rec_size = attr->core_relo_rec_size; 16484 if (rec_size < MIN_CORE_RELO_SIZE || 16485 rec_size > MAX_CORE_RELO_SIZE || 16486 rec_size % sizeof(u32)) 16487 return -EINVAL; 16488 16489 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16490 expected_size = sizeof(struct bpf_core_relo); 16491 ncopy = min_t(u32, expected_size, rec_size); 16492 16493 /* Unlike func_info and line_info, copy and apply each CO-RE 16494 * relocation record one at a time. 16495 */ 16496 for (i = 0; i < nr_core_relo; i++) { 16497 /* future proofing when sizeof(bpf_core_relo) changes */ 16498 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16499 if (err) { 16500 if (err == -E2BIG) { 16501 verbose(env, "nonzero tailing record in core_relo"); 16502 if (copy_to_bpfptr_offset(uattr, 16503 offsetof(union bpf_attr, core_relo_rec_size), 16504 &expected_size, sizeof(expected_size))) 16505 err = -EFAULT; 16506 } 16507 break; 16508 } 16509 16510 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16511 err = -EFAULT; 16512 break; 16513 } 16514 16515 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16516 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16517 i, core_relo.insn_off, prog->len); 16518 err = -EINVAL; 16519 break; 16520 } 16521 16522 err = bpf_core_apply(&ctx, &core_relo, i, 16523 &prog->insnsi[core_relo.insn_off / 8]); 16524 if (err) 16525 break; 16526 bpfptr_add(&u_core_relo, rec_size); 16527 } 16528 return err; 16529 } 16530 16531 static int check_btf_info_early(struct bpf_verifier_env *env, 16532 const union bpf_attr *attr, 16533 bpfptr_t uattr) 16534 { 16535 struct btf *btf; 16536 int err; 16537 16538 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16539 if (check_abnormal_return(env)) 16540 return -EINVAL; 16541 return 0; 16542 } 16543 16544 btf = btf_get_by_fd(attr->prog_btf_fd); 16545 if (IS_ERR(btf)) 16546 return PTR_ERR(btf); 16547 if (btf_is_kernel(btf)) { 16548 btf_put(btf); 16549 return -EACCES; 16550 } 16551 env->prog->aux->btf = btf; 16552 16553 err = check_btf_func_early(env, attr, uattr); 16554 if (err) 16555 return err; 16556 return 0; 16557 } 16558 16559 static int check_btf_info(struct bpf_verifier_env *env, 16560 const union bpf_attr *attr, 16561 bpfptr_t uattr) 16562 { 16563 int err; 16564 16565 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16566 if (check_abnormal_return(env)) 16567 return -EINVAL; 16568 return 0; 16569 } 16570 16571 err = check_btf_func(env, attr, uattr); 16572 if (err) 16573 return err; 16574 16575 err = check_btf_line(env, attr, uattr); 16576 if (err) 16577 return err; 16578 16579 err = check_core_relo(env, attr, uattr); 16580 if (err) 16581 return err; 16582 16583 return 0; 16584 } 16585 16586 /* check %cur's range satisfies %old's */ 16587 static bool range_within(const struct bpf_reg_state *old, 16588 const struct bpf_reg_state *cur) 16589 { 16590 return old->umin_value <= cur->umin_value && 16591 old->umax_value >= cur->umax_value && 16592 old->smin_value <= cur->smin_value && 16593 old->smax_value >= cur->smax_value && 16594 old->u32_min_value <= cur->u32_min_value && 16595 old->u32_max_value >= cur->u32_max_value && 16596 old->s32_min_value <= cur->s32_min_value && 16597 old->s32_max_value >= cur->s32_max_value; 16598 } 16599 16600 /* If in the old state two registers had the same id, then they need to have 16601 * the same id in the new state as well. But that id could be different from 16602 * the old state, so we need to track the mapping from old to new ids. 16603 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16604 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16605 * regs with a different old id could still have new id 9, we don't care about 16606 * that. 16607 * So we look through our idmap to see if this old id has been seen before. If 16608 * so, we require the new id to match; otherwise, we add the id pair to the map. 16609 */ 16610 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16611 { 16612 struct bpf_id_pair *map = idmap->map; 16613 unsigned int i; 16614 16615 /* either both IDs should be set or both should be zero */ 16616 if (!!old_id != !!cur_id) 16617 return false; 16618 16619 if (old_id == 0) /* cur_id == 0 as well */ 16620 return true; 16621 16622 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16623 if (!map[i].old) { 16624 /* Reached an empty slot; haven't seen this id before */ 16625 map[i].old = old_id; 16626 map[i].cur = cur_id; 16627 return true; 16628 } 16629 if (map[i].old == old_id) 16630 return map[i].cur == cur_id; 16631 if (map[i].cur == cur_id) 16632 return false; 16633 } 16634 /* We ran out of idmap slots, which should be impossible */ 16635 WARN_ON_ONCE(1); 16636 return false; 16637 } 16638 16639 /* Similar to check_ids(), but allocate a unique temporary ID 16640 * for 'old_id' or 'cur_id' of zero. 16641 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16642 */ 16643 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16644 { 16645 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16646 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16647 16648 return check_ids(old_id, cur_id, idmap); 16649 } 16650 16651 static void clean_func_state(struct bpf_verifier_env *env, 16652 struct bpf_func_state *st) 16653 { 16654 enum bpf_reg_liveness live; 16655 int i, j; 16656 16657 for (i = 0; i < BPF_REG_FP; i++) { 16658 live = st->regs[i].live; 16659 /* liveness must not touch this register anymore */ 16660 st->regs[i].live |= REG_LIVE_DONE; 16661 if (!(live & REG_LIVE_READ)) 16662 /* since the register is unused, clear its state 16663 * to make further comparison simpler 16664 */ 16665 __mark_reg_not_init(env, &st->regs[i]); 16666 } 16667 16668 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16669 live = st->stack[i].spilled_ptr.live; 16670 /* liveness must not touch this stack slot anymore */ 16671 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16672 if (!(live & REG_LIVE_READ)) { 16673 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16674 for (j = 0; j < BPF_REG_SIZE; j++) 16675 st->stack[i].slot_type[j] = STACK_INVALID; 16676 } 16677 } 16678 } 16679 16680 static void clean_verifier_state(struct bpf_verifier_env *env, 16681 struct bpf_verifier_state *st) 16682 { 16683 int i; 16684 16685 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16686 /* all regs in this state in all frames were already marked */ 16687 return; 16688 16689 for (i = 0; i <= st->curframe; i++) 16690 clean_func_state(env, st->frame[i]); 16691 } 16692 16693 /* the parentage chains form a tree. 16694 * the verifier states are added to state lists at given insn and 16695 * pushed into state stack for future exploration. 16696 * when the verifier reaches bpf_exit insn some of the verifer states 16697 * stored in the state lists have their final liveness state already, 16698 * but a lot of states will get revised from liveness point of view when 16699 * the verifier explores other branches. 16700 * Example: 16701 * 1: r0 = 1 16702 * 2: if r1 == 100 goto pc+1 16703 * 3: r0 = 2 16704 * 4: exit 16705 * when the verifier reaches exit insn the register r0 in the state list of 16706 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16707 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16708 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16709 * 16710 * Since the verifier pushes the branch states as it sees them while exploring 16711 * the program the condition of walking the branch instruction for the second 16712 * time means that all states below this branch were already explored and 16713 * their final liveness marks are already propagated. 16714 * Hence when the verifier completes the search of state list in is_state_visited() 16715 * we can call this clean_live_states() function to mark all liveness states 16716 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16717 * will not be used. 16718 * This function also clears the registers and stack for states that !READ 16719 * to simplify state merging. 16720 * 16721 * Important note here that walking the same branch instruction in the callee 16722 * doesn't meant that the states are DONE. The verifier has to compare 16723 * the callsites 16724 */ 16725 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16726 struct bpf_verifier_state *cur) 16727 { 16728 struct bpf_verifier_state_list *sl; 16729 16730 sl = *explored_state(env, insn); 16731 while (sl) { 16732 if (sl->state.branches) 16733 goto next; 16734 if (sl->state.insn_idx != insn || 16735 !same_callsites(&sl->state, cur)) 16736 goto next; 16737 clean_verifier_state(env, &sl->state); 16738 next: 16739 sl = sl->next; 16740 } 16741 } 16742 16743 static bool regs_exact(const struct bpf_reg_state *rold, 16744 const struct bpf_reg_state *rcur, 16745 struct bpf_idmap *idmap) 16746 { 16747 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16748 check_ids(rold->id, rcur->id, idmap) && 16749 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16750 } 16751 16752 enum exact_level { 16753 NOT_EXACT, 16754 EXACT, 16755 RANGE_WITHIN 16756 }; 16757 16758 /* Returns true if (rold safe implies rcur safe) */ 16759 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16760 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 16761 enum exact_level exact) 16762 { 16763 if (exact == EXACT) 16764 return regs_exact(rold, rcur, idmap); 16765 16766 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 16767 /* explored state didn't use this */ 16768 return true; 16769 if (rold->type == NOT_INIT) { 16770 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 16771 /* explored state can't have used this */ 16772 return true; 16773 } 16774 16775 /* Enforce that register types have to match exactly, including their 16776 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16777 * rule. 16778 * 16779 * One can make a point that using a pointer register as unbounded 16780 * SCALAR would be technically acceptable, but this could lead to 16781 * pointer leaks because scalars are allowed to leak while pointers 16782 * are not. We could make this safe in special cases if root is 16783 * calling us, but it's probably not worth the hassle. 16784 * 16785 * Also, register types that are *not* MAYBE_NULL could technically be 16786 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16787 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16788 * to the same map). 16789 * However, if the old MAYBE_NULL register then got NULL checked, 16790 * doing so could have affected others with the same id, and we can't 16791 * check for that because we lost the id when we converted to 16792 * a non-MAYBE_NULL variant. 16793 * So, as a general rule we don't allow mixing MAYBE_NULL and 16794 * non-MAYBE_NULL registers as well. 16795 */ 16796 if (rold->type != rcur->type) 16797 return false; 16798 16799 switch (base_type(rold->type)) { 16800 case SCALAR_VALUE: 16801 if (env->explore_alu_limits) { 16802 /* explore_alu_limits disables tnum_in() and range_within() 16803 * logic and requires everything to be strict 16804 */ 16805 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16806 check_scalar_ids(rold->id, rcur->id, idmap); 16807 } 16808 if (!rold->precise && exact == NOT_EXACT) 16809 return true; 16810 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 16811 return false; 16812 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 16813 return false; 16814 /* Why check_ids() for scalar registers? 16815 * 16816 * Consider the following BPF code: 16817 * 1: r6 = ... unbound scalar, ID=a ... 16818 * 2: r7 = ... unbound scalar, ID=b ... 16819 * 3: if (r6 > r7) goto +1 16820 * 4: r6 = r7 16821 * 5: if (r6 > X) goto ... 16822 * 6: ... memory operation using r7 ... 16823 * 16824 * First verification path is [1-6]: 16825 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16826 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16827 * r7 <= X, because r6 and r7 share same id. 16828 * Next verification path is [1-4, 6]. 16829 * 16830 * Instruction (6) would be reached in two states: 16831 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16832 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16833 * 16834 * Use check_ids() to distinguish these states. 16835 * --- 16836 * Also verify that new value satisfies old value range knowledge. 16837 */ 16838 return range_within(rold, rcur) && 16839 tnum_in(rold->var_off, rcur->var_off) && 16840 check_scalar_ids(rold->id, rcur->id, idmap); 16841 case PTR_TO_MAP_KEY: 16842 case PTR_TO_MAP_VALUE: 16843 case PTR_TO_MEM: 16844 case PTR_TO_BUF: 16845 case PTR_TO_TP_BUFFER: 16846 /* If the new min/max/var_off satisfy the old ones and 16847 * everything else matches, we are OK. 16848 */ 16849 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16850 range_within(rold, rcur) && 16851 tnum_in(rold->var_off, rcur->var_off) && 16852 check_ids(rold->id, rcur->id, idmap) && 16853 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16854 case PTR_TO_PACKET_META: 16855 case PTR_TO_PACKET: 16856 /* We must have at least as much range as the old ptr 16857 * did, so that any accesses which were safe before are 16858 * still safe. This is true even if old range < old off, 16859 * since someone could have accessed through (ptr - k), or 16860 * even done ptr -= k in a register, to get a safe access. 16861 */ 16862 if (rold->range > rcur->range) 16863 return false; 16864 /* If the offsets don't match, we can't trust our alignment; 16865 * nor can we be sure that we won't fall out of range. 16866 */ 16867 if (rold->off != rcur->off) 16868 return false; 16869 /* id relations must be preserved */ 16870 if (!check_ids(rold->id, rcur->id, idmap)) 16871 return false; 16872 /* new val must satisfy old val knowledge */ 16873 return range_within(rold, rcur) && 16874 tnum_in(rold->var_off, rcur->var_off); 16875 case PTR_TO_STACK: 16876 /* two stack pointers are equal only if they're pointing to 16877 * the same stack frame, since fp-8 in foo != fp-8 in bar 16878 */ 16879 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16880 case PTR_TO_ARENA: 16881 return true; 16882 default: 16883 return regs_exact(rold, rcur, idmap); 16884 } 16885 } 16886 16887 static struct bpf_reg_state unbound_reg; 16888 16889 static __init int unbound_reg_init(void) 16890 { 16891 __mark_reg_unknown_imprecise(&unbound_reg); 16892 unbound_reg.live |= REG_LIVE_READ; 16893 return 0; 16894 } 16895 late_initcall(unbound_reg_init); 16896 16897 static bool is_stack_all_misc(struct bpf_verifier_env *env, 16898 struct bpf_stack_state *stack) 16899 { 16900 u32 i; 16901 16902 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 16903 if ((stack->slot_type[i] == STACK_MISC) || 16904 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 16905 continue; 16906 return false; 16907 } 16908 16909 return true; 16910 } 16911 16912 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 16913 struct bpf_stack_state *stack) 16914 { 16915 if (is_spilled_scalar_reg64(stack)) 16916 return &stack->spilled_ptr; 16917 16918 if (is_stack_all_misc(env, stack)) 16919 return &unbound_reg; 16920 16921 return NULL; 16922 } 16923 16924 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16925 struct bpf_func_state *cur, struct bpf_idmap *idmap, 16926 enum exact_level exact) 16927 { 16928 int i, spi; 16929 16930 /* walk slots of the explored stack and ignore any additional 16931 * slots in the current stack, since explored(safe) state 16932 * didn't use them 16933 */ 16934 for (i = 0; i < old->allocated_stack; i++) { 16935 struct bpf_reg_state *old_reg, *cur_reg; 16936 16937 spi = i / BPF_REG_SIZE; 16938 16939 if (exact != NOT_EXACT && 16940 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16941 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16942 return false; 16943 16944 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 16945 && exact == NOT_EXACT) { 16946 i += BPF_REG_SIZE - 1; 16947 /* explored state didn't use this */ 16948 continue; 16949 } 16950 16951 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16952 continue; 16953 16954 if (env->allow_uninit_stack && 16955 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16956 continue; 16957 16958 /* explored stack has more populated slots than current stack 16959 * and these slots were used 16960 */ 16961 if (i >= cur->allocated_stack) 16962 return false; 16963 16964 /* 64-bit scalar spill vs all slots MISC and vice versa. 16965 * Load from all slots MISC produces unbound scalar. 16966 * Construct a fake register for such stack and call 16967 * regsafe() to ensure scalar ids are compared. 16968 */ 16969 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 16970 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 16971 if (old_reg && cur_reg) { 16972 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 16973 return false; 16974 i += BPF_REG_SIZE - 1; 16975 continue; 16976 } 16977 16978 /* if old state was safe with misc data in the stack 16979 * it will be safe with zero-initialized stack. 16980 * The opposite is not true 16981 */ 16982 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16983 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16984 continue; 16985 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16986 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16987 /* Ex: old explored (safe) state has STACK_SPILL in 16988 * this stack slot, but current has STACK_MISC -> 16989 * this verifier states are not equivalent, 16990 * return false to continue verification of this path 16991 */ 16992 return false; 16993 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16994 continue; 16995 /* Both old and cur are having same slot_type */ 16996 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16997 case STACK_SPILL: 16998 /* when explored and current stack slot are both storing 16999 * spilled registers, check that stored pointers types 17000 * are the same as well. 17001 * Ex: explored safe path could have stored 17002 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 17003 * but current path has stored: 17004 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 17005 * such verifier states are not equivalent. 17006 * return false to continue verification of this path 17007 */ 17008 if (!regsafe(env, &old->stack[spi].spilled_ptr, 17009 &cur->stack[spi].spilled_ptr, idmap, exact)) 17010 return false; 17011 break; 17012 case STACK_DYNPTR: 17013 old_reg = &old->stack[spi].spilled_ptr; 17014 cur_reg = &cur->stack[spi].spilled_ptr; 17015 if (old_reg->dynptr.type != cur_reg->dynptr.type || 17016 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 17017 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17018 return false; 17019 break; 17020 case STACK_ITER: 17021 old_reg = &old->stack[spi].spilled_ptr; 17022 cur_reg = &cur->stack[spi].spilled_ptr; 17023 /* iter.depth is not compared between states as it 17024 * doesn't matter for correctness and would otherwise 17025 * prevent convergence; we maintain it only to prevent 17026 * infinite loop check triggering, see 17027 * iter_active_depths_differ() 17028 */ 17029 if (old_reg->iter.btf != cur_reg->iter.btf || 17030 old_reg->iter.btf_id != cur_reg->iter.btf_id || 17031 old_reg->iter.state != cur_reg->iter.state || 17032 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 17033 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 17034 return false; 17035 break; 17036 case STACK_MISC: 17037 case STACK_ZERO: 17038 case STACK_INVALID: 17039 continue; 17040 /* Ensure that new unhandled slot types return false by default */ 17041 default: 17042 return false; 17043 } 17044 } 17045 return true; 17046 } 17047 17048 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 17049 struct bpf_idmap *idmap) 17050 { 17051 int i; 17052 17053 if (old->acquired_refs != cur->acquired_refs) 17054 return false; 17055 17056 for (i = 0; i < old->acquired_refs; i++) { 17057 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 17058 return false; 17059 } 17060 17061 return true; 17062 } 17063 17064 /* compare two verifier states 17065 * 17066 * all states stored in state_list are known to be valid, since 17067 * verifier reached 'bpf_exit' instruction through them 17068 * 17069 * this function is called when verifier exploring different branches of 17070 * execution popped from the state stack. If it sees an old state that has 17071 * more strict register state and more strict stack state then this execution 17072 * branch doesn't need to be explored further, since verifier already 17073 * concluded that more strict state leads to valid finish. 17074 * 17075 * Therefore two states are equivalent if register state is more conservative 17076 * and explored stack state is more conservative than the current one. 17077 * Example: 17078 * explored current 17079 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 17080 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 17081 * 17082 * In other words if current stack state (one being explored) has more 17083 * valid slots than old one that already passed validation, it means 17084 * the verifier can stop exploring and conclude that current state is valid too 17085 * 17086 * Similarly with registers. If explored state has register type as invalid 17087 * whereas register type in current state is meaningful, it means that 17088 * the current state will reach 'bpf_exit' instruction safely 17089 */ 17090 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 17091 struct bpf_func_state *cur, enum exact_level exact) 17092 { 17093 int i; 17094 17095 if (old->callback_depth > cur->callback_depth) 17096 return false; 17097 17098 for (i = 0; i < MAX_BPF_REG; i++) 17099 if (!regsafe(env, &old->regs[i], &cur->regs[i], 17100 &env->idmap_scratch, exact)) 17101 return false; 17102 17103 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 17104 return false; 17105 17106 if (!refsafe(old, cur, &env->idmap_scratch)) 17107 return false; 17108 17109 return true; 17110 } 17111 17112 static void reset_idmap_scratch(struct bpf_verifier_env *env) 17113 { 17114 env->idmap_scratch.tmp_id_gen = env->id_gen; 17115 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 17116 } 17117 17118 static bool states_equal(struct bpf_verifier_env *env, 17119 struct bpf_verifier_state *old, 17120 struct bpf_verifier_state *cur, 17121 enum exact_level exact) 17122 { 17123 int i; 17124 17125 if (old->curframe != cur->curframe) 17126 return false; 17127 17128 reset_idmap_scratch(env); 17129 17130 /* Verification state from speculative execution simulation 17131 * must never prune a non-speculative execution one. 17132 */ 17133 if (old->speculative && !cur->speculative) 17134 return false; 17135 17136 if (old->active_lock.ptr != cur->active_lock.ptr) 17137 return false; 17138 17139 /* Old and cur active_lock's have to be either both present 17140 * or both absent. 17141 */ 17142 if (!!old->active_lock.id != !!cur->active_lock.id) 17143 return false; 17144 17145 if (old->active_lock.id && 17146 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 17147 return false; 17148 17149 if (old->active_rcu_lock != cur->active_rcu_lock) 17150 return false; 17151 17152 if (old->active_preempt_lock != cur->active_preempt_lock) 17153 return false; 17154 17155 if (old->in_sleepable != cur->in_sleepable) 17156 return false; 17157 17158 /* for states to be equal callsites have to be the same 17159 * and all frame states need to be equivalent 17160 */ 17161 for (i = 0; i <= old->curframe; i++) { 17162 if (old->frame[i]->callsite != cur->frame[i]->callsite) 17163 return false; 17164 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 17165 return false; 17166 } 17167 return true; 17168 } 17169 17170 /* Return 0 if no propagation happened. Return negative error code if error 17171 * happened. Otherwise, return the propagated bit. 17172 */ 17173 static int propagate_liveness_reg(struct bpf_verifier_env *env, 17174 struct bpf_reg_state *reg, 17175 struct bpf_reg_state *parent_reg) 17176 { 17177 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 17178 u8 flag = reg->live & REG_LIVE_READ; 17179 int err; 17180 17181 /* When comes here, read flags of PARENT_REG or REG could be any of 17182 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 17183 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 17184 */ 17185 if (parent_flag == REG_LIVE_READ64 || 17186 /* Or if there is no read flag from REG. */ 17187 !flag || 17188 /* Or if the read flag from REG is the same as PARENT_REG. */ 17189 parent_flag == flag) 17190 return 0; 17191 17192 err = mark_reg_read(env, reg, parent_reg, flag); 17193 if (err) 17194 return err; 17195 17196 return flag; 17197 } 17198 17199 /* A write screens off any subsequent reads; but write marks come from the 17200 * straight-line code between a state and its parent. When we arrive at an 17201 * equivalent state (jump target or such) we didn't arrive by the straight-line 17202 * code, so read marks in the state must propagate to the parent regardless 17203 * of the state's write marks. That's what 'parent == state->parent' comparison 17204 * in mark_reg_read() is for. 17205 */ 17206 static int propagate_liveness(struct bpf_verifier_env *env, 17207 const struct bpf_verifier_state *vstate, 17208 struct bpf_verifier_state *vparent) 17209 { 17210 struct bpf_reg_state *state_reg, *parent_reg; 17211 struct bpf_func_state *state, *parent; 17212 int i, frame, err = 0; 17213 17214 if (vparent->curframe != vstate->curframe) { 17215 WARN(1, "propagate_live: parent frame %d current frame %d\n", 17216 vparent->curframe, vstate->curframe); 17217 return -EFAULT; 17218 } 17219 /* Propagate read liveness of registers... */ 17220 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 17221 for (frame = 0; frame <= vstate->curframe; frame++) { 17222 parent = vparent->frame[frame]; 17223 state = vstate->frame[frame]; 17224 parent_reg = parent->regs; 17225 state_reg = state->regs; 17226 /* We don't need to worry about FP liveness, it's read-only */ 17227 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 17228 err = propagate_liveness_reg(env, &state_reg[i], 17229 &parent_reg[i]); 17230 if (err < 0) 17231 return err; 17232 if (err == REG_LIVE_READ64) 17233 mark_insn_zext(env, &parent_reg[i]); 17234 } 17235 17236 /* Propagate stack slots. */ 17237 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 17238 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 17239 parent_reg = &parent->stack[i].spilled_ptr; 17240 state_reg = &state->stack[i].spilled_ptr; 17241 err = propagate_liveness_reg(env, state_reg, 17242 parent_reg); 17243 if (err < 0) 17244 return err; 17245 } 17246 } 17247 return 0; 17248 } 17249 17250 /* find precise scalars in the previous equivalent state and 17251 * propagate them into the current state 17252 */ 17253 static int propagate_precision(struct bpf_verifier_env *env, 17254 const struct bpf_verifier_state *old) 17255 { 17256 struct bpf_reg_state *state_reg; 17257 struct bpf_func_state *state; 17258 int i, err = 0, fr; 17259 bool first; 17260 17261 for (fr = old->curframe; fr >= 0; fr--) { 17262 state = old->frame[fr]; 17263 state_reg = state->regs; 17264 first = true; 17265 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17266 if (state_reg->type != SCALAR_VALUE || 17267 !state_reg->precise || 17268 !(state_reg->live & REG_LIVE_READ)) 17269 continue; 17270 if (env->log.level & BPF_LOG_LEVEL2) { 17271 if (first) 17272 verbose(env, "frame %d: propagating r%d", fr, i); 17273 else 17274 verbose(env, ",r%d", i); 17275 } 17276 bt_set_frame_reg(&env->bt, fr, i); 17277 first = false; 17278 } 17279 17280 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17281 if (!is_spilled_reg(&state->stack[i])) 17282 continue; 17283 state_reg = &state->stack[i].spilled_ptr; 17284 if (state_reg->type != SCALAR_VALUE || 17285 !state_reg->precise || 17286 !(state_reg->live & REG_LIVE_READ)) 17287 continue; 17288 if (env->log.level & BPF_LOG_LEVEL2) { 17289 if (first) 17290 verbose(env, "frame %d: propagating fp%d", 17291 fr, (-i - 1) * BPF_REG_SIZE); 17292 else 17293 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17294 } 17295 bt_set_frame_slot(&env->bt, fr, i); 17296 first = false; 17297 } 17298 if (!first) 17299 verbose(env, "\n"); 17300 } 17301 17302 err = mark_chain_precision_batch(env); 17303 if (err < 0) 17304 return err; 17305 17306 return 0; 17307 } 17308 17309 static bool states_maybe_looping(struct bpf_verifier_state *old, 17310 struct bpf_verifier_state *cur) 17311 { 17312 struct bpf_func_state *fold, *fcur; 17313 int i, fr = cur->curframe; 17314 17315 if (old->curframe != fr) 17316 return false; 17317 17318 fold = old->frame[fr]; 17319 fcur = cur->frame[fr]; 17320 for (i = 0; i < MAX_BPF_REG; i++) 17321 if (memcmp(&fold->regs[i], &fcur->regs[i], 17322 offsetof(struct bpf_reg_state, parent))) 17323 return false; 17324 return true; 17325 } 17326 17327 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17328 { 17329 return env->insn_aux_data[insn_idx].is_iter_next; 17330 } 17331 17332 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17333 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17334 * states to match, which otherwise would look like an infinite loop. So while 17335 * iter_next() calls are taken care of, we still need to be careful and 17336 * prevent erroneous and too eager declaration of "ininite loop", when 17337 * iterators are involved. 17338 * 17339 * Here's a situation in pseudo-BPF assembly form: 17340 * 17341 * 0: again: ; set up iter_next() call args 17342 * 1: r1 = &it ; <CHECKPOINT HERE> 17343 * 2: call bpf_iter_num_next ; this is iter_next() call 17344 * 3: if r0 == 0 goto done 17345 * 4: ... something useful here ... 17346 * 5: goto again ; another iteration 17347 * 6: done: 17348 * 7: r1 = &it 17349 * 8: call bpf_iter_num_destroy ; clean up iter state 17350 * 9: exit 17351 * 17352 * This is a typical loop. Let's assume that we have a prune point at 1:, 17353 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17354 * again`, assuming other heuristics don't get in a way). 17355 * 17356 * When we first time come to 1:, let's say we have some state X. We proceed 17357 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17358 * Now we come back to validate that forked ACTIVE state. We proceed through 17359 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17360 * are converging. But the problem is that we don't know that yet, as this 17361 * convergence has to happen at iter_next() call site only. So if nothing is 17362 * done, at 1: verifier will use bounded loop logic and declare infinite 17363 * looping (and would be *technically* correct, if not for iterator's 17364 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17365 * don't want that. So what we do in process_iter_next_call() when we go on 17366 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17367 * a different iteration. So when we suspect an infinite loop, we additionally 17368 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17369 * pretend we are not looping and wait for next iter_next() call. 17370 * 17371 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17372 * loop, because that would actually mean infinite loop, as DRAINED state is 17373 * "sticky", and so we'll keep returning into the same instruction with the 17374 * same state (at least in one of possible code paths). 17375 * 17376 * This approach allows to keep infinite loop heuristic even in the face of 17377 * active iterator. E.g., C snippet below is and will be detected as 17378 * inifintely looping: 17379 * 17380 * struct bpf_iter_num it; 17381 * int *p, x; 17382 * 17383 * bpf_iter_num_new(&it, 0, 10); 17384 * while ((p = bpf_iter_num_next(&t))) { 17385 * x = p; 17386 * while (x--) {} // <<-- infinite loop here 17387 * } 17388 * 17389 */ 17390 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17391 { 17392 struct bpf_reg_state *slot, *cur_slot; 17393 struct bpf_func_state *state; 17394 int i, fr; 17395 17396 for (fr = old->curframe; fr >= 0; fr--) { 17397 state = old->frame[fr]; 17398 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17399 if (state->stack[i].slot_type[0] != STACK_ITER) 17400 continue; 17401 17402 slot = &state->stack[i].spilled_ptr; 17403 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17404 continue; 17405 17406 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17407 if (cur_slot->iter.depth != slot->iter.depth) 17408 return true; 17409 } 17410 } 17411 return false; 17412 } 17413 17414 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17415 { 17416 struct bpf_verifier_state_list *new_sl; 17417 struct bpf_verifier_state_list *sl, **pprev; 17418 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17419 int i, j, n, err, states_cnt = 0; 17420 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 17421 bool add_new_state = force_new_state; 17422 bool force_exact; 17423 17424 /* bpf progs typically have pruning point every 4 instructions 17425 * http://vger.kernel.org/bpfconf2019.html#session-1 17426 * Do not add new state for future pruning if the verifier hasn't seen 17427 * at least 2 jumps and at least 8 instructions. 17428 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17429 * In tests that amounts to up to 50% reduction into total verifier 17430 * memory consumption and 20% verifier time speedup. 17431 */ 17432 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17433 env->insn_processed - env->prev_insn_processed >= 8) 17434 add_new_state = true; 17435 17436 pprev = explored_state(env, insn_idx); 17437 sl = *pprev; 17438 17439 clean_live_states(env, insn_idx, cur); 17440 17441 while (sl) { 17442 states_cnt++; 17443 if (sl->state.insn_idx != insn_idx) 17444 goto next; 17445 17446 if (sl->state.branches) { 17447 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17448 17449 if (frame->in_async_callback_fn && 17450 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17451 /* Different async_entry_cnt means that the verifier is 17452 * processing another entry into async callback. 17453 * Seeing the same state is not an indication of infinite 17454 * loop or infinite recursion. 17455 * But finding the same state doesn't mean that it's safe 17456 * to stop processing the current state. The previous state 17457 * hasn't yet reached bpf_exit, since state.branches > 0. 17458 * Checking in_async_callback_fn alone is not enough either. 17459 * Since the verifier still needs to catch infinite loops 17460 * inside async callbacks. 17461 */ 17462 goto skip_inf_loop_check; 17463 } 17464 /* BPF open-coded iterators loop detection is special. 17465 * states_maybe_looping() logic is too simplistic in detecting 17466 * states that *might* be equivalent, because it doesn't know 17467 * about ID remapping, so don't even perform it. 17468 * See process_iter_next_call() and iter_active_depths_differ() 17469 * for overview of the logic. When current and one of parent 17470 * states are detected as equivalent, it's a good thing: we prove 17471 * convergence and can stop simulating further iterations. 17472 * It's safe to assume that iterator loop will finish, taking into 17473 * account iter_next() contract of eventually returning 17474 * sticky NULL result. 17475 * 17476 * Note, that states have to be compared exactly in this case because 17477 * read and precision marks might not be finalized inside the loop. 17478 * E.g. as in the program below: 17479 * 17480 * 1. r7 = -16 17481 * 2. r6 = bpf_get_prandom_u32() 17482 * 3. while (bpf_iter_num_next(&fp[-8])) { 17483 * 4. if (r6 != 42) { 17484 * 5. r7 = -32 17485 * 6. r6 = bpf_get_prandom_u32() 17486 * 7. continue 17487 * 8. } 17488 * 9. r0 = r10 17489 * 10. r0 += r7 17490 * 11. r8 = *(u64 *)(r0 + 0) 17491 * 12. r6 = bpf_get_prandom_u32() 17492 * 13. } 17493 * 17494 * Here verifier would first visit path 1-3, create a checkpoint at 3 17495 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17496 * not have read or precision mark for r7 yet, thus inexact states 17497 * comparison would discard current state with r7=-32 17498 * => unsafe memory access at 11 would not be caught. 17499 */ 17500 if (is_iter_next_insn(env, insn_idx)) { 17501 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17502 struct bpf_func_state *cur_frame; 17503 struct bpf_reg_state *iter_state, *iter_reg; 17504 int spi; 17505 17506 cur_frame = cur->frame[cur->curframe]; 17507 /* btf_check_iter_kfuncs() enforces that 17508 * iter state pointer is always the first arg 17509 */ 17510 iter_reg = &cur_frame->regs[BPF_REG_1]; 17511 /* current state is valid due to states_equal(), 17512 * so we can assume valid iter and reg state, 17513 * no need for extra (re-)validations 17514 */ 17515 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17516 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17517 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17518 update_loop_entry(cur, &sl->state); 17519 goto hit; 17520 } 17521 } 17522 goto skip_inf_loop_check; 17523 } 17524 if (is_may_goto_insn_at(env, insn_idx)) { 17525 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17526 update_loop_entry(cur, &sl->state); 17527 goto hit; 17528 } 17529 goto skip_inf_loop_check; 17530 } 17531 if (calls_callback(env, insn_idx)) { 17532 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 17533 goto hit; 17534 goto skip_inf_loop_check; 17535 } 17536 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17537 if (states_maybe_looping(&sl->state, cur) && 17538 states_equal(env, &sl->state, cur, EXACT) && 17539 !iter_active_depths_differ(&sl->state, cur) && 17540 sl->state.may_goto_depth == cur->may_goto_depth && 17541 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17542 verbose_linfo(env, insn_idx, "; "); 17543 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17544 verbose(env, "cur state:"); 17545 print_verifier_state(env, cur->frame[cur->curframe], true); 17546 verbose(env, "old state:"); 17547 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17548 return -EINVAL; 17549 } 17550 /* if the verifier is processing a loop, avoid adding new state 17551 * too often, since different loop iterations have distinct 17552 * states and may not help future pruning. 17553 * This threshold shouldn't be too low to make sure that 17554 * a loop with large bound will be rejected quickly. 17555 * The most abusive loop will be: 17556 * r1 += 1 17557 * if r1 < 1000000 goto pc-2 17558 * 1M insn_procssed limit / 100 == 10k peak states. 17559 * This threshold shouldn't be too high either, since states 17560 * at the end of the loop are likely to be useful in pruning. 17561 */ 17562 skip_inf_loop_check: 17563 if (!force_new_state && 17564 env->jmps_processed - env->prev_jmps_processed < 20 && 17565 env->insn_processed - env->prev_insn_processed < 100) 17566 add_new_state = false; 17567 goto miss; 17568 } 17569 /* If sl->state is a part of a loop and this loop's entry is a part of 17570 * current verification path then states have to be compared exactly. 17571 * 'force_exact' is needed to catch the following case: 17572 * 17573 * initial Here state 'succ' was processed first, 17574 * | it was eventually tracked to produce a 17575 * V state identical to 'hdr'. 17576 * .---------> hdr All branches from 'succ' had been explored 17577 * | | and thus 'succ' has its .branches == 0. 17578 * | V 17579 * | .------... Suppose states 'cur' and 'succ' correspond 17580 * | | | to the same instruction + callsites. 17581 * | V V In such case it is necessary to check 17582 * | ... ... if 'succ' and 'cur' are states_equal(). 17583 * | | | If 'succ' and 'cur' are a part of the 17584 * | V V same loop exact flag has to be set. 17585 * | succ <- cur To check if that is the case, verify 17586 * | | if loop entry of 'succ' is in current 17587 * | V DFS path. 17588 * | ... 17589 * | | 17590 * '----' 17591 * 17592 * Additional details are in the comment before get_loop_entry(). 17593 */ 17594 loop_entry = get_loop_entry(&sl->state); 17595 force_exact = loop_entry && loop_entry->branches > 0; 17596 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 17597 if (force_exact) 17598 update_loop_entry(cur, loop_entry); 17599 hit: 17600 sl->hit_cnt++; 17601 /* reached equivalent register/stack state, 17602 * prune the search. 17603 * Registers read by the continuation are read by us. 17604 * If we have any write marks in env->cur_state, they 17605 * will prevent corresponding reads in the continuation 17606 * from reaching our parent (an explored_state). Our 17607 * own state will get the read marks recorded, but 17608 * they'll be immediately forgotten as we're pruning 17609 * this state and will pop a new one. 17610 */ 17611 err = propagate_liveness(env, &sl->state, cur); 17612 17613 /* if previous state reached the exit with precision and 17614 * current state is equivalent to it (except precision marks) 17615 * the precision needs to be propagated back in 17616 * the current state. 17617 */ 17618 if (is_jmp_point(env, env->insn_idx)) 17619 err = err ? : push_jmp_history(env, cur, 0); 17620 err = err ? : propagate_precision(env, &sl->state); 17621 if (err) 17622 return err; 17623 return 1; 17624 } 17625 miss: 17626 /* when new state is not going to be added do not increase miss count. 17627 * Otherwise several loop iterations will remove the state 17628 * recorded earlier. The goal of these heuristics is to have 17629 * states from some iterations of the loop (some in the beginning 17630 * and some at the end) to help pruning. 17631 */ 17632 if (add_new_state) 17633 sl->miss_cnt++; 17634 /* heuristic to determine whether this state is beneficial 17635 * to keep checking from state equivalence point of view. 17636 * Higher numbers increase max_states_per_insn and verification time, 17637 * but do not meaningfully decrease insn_processed. 17638 * 'n' controls how many times state could miss before eviction. 17639 * Use bigger 'n' for checkpoints because evicting checkpoint states 17640 * too early would hinder iterator convergence. 17641 */ 17642 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17643 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17644 /* the state is unlikely to be useful. Remove it to 17645 * speed up verification 17646 */ 17647 *pprev = sl->next; 17648 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17649 !sl->state.used_as_loop_entry) { 17650 u32 br = sl->state.branches; 17651 17652 WARN_ONCE(br, 17653 "BUG live_done but branches_to_explore %d\n", 17654 br); 17655 free_verifier_state(&sl->state, false); 17656 kfree(sl); 17657 env->peak_states--; 17658 } else { 17659 /* cannot free this state, since parentage chain may 17660 * walk it later. Add it for free_list instead to 17661 * be freed at the end of verification 17662 */ 17663 sl->next = env->free_list; 17664 env->free_list = sl; 17665 } 17666 sl = *pprev; 17667 continue; 17668 } 17669 next: 17670 pprev = &sl->next; 17671 sl = *pprev; 17672 } 17673 17674 if (env->max_states_per_insn < states_cnt) 17675 env->max_states_per_insn = states_cnt; 17676 17677 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17678 return 0; 17679 17680 if (!add_new_state) 17681 return 0; 17682 17683 /* There were no equivalent states, remember the current one. 17684 * Technically the current state is not proven to be safe yet, 17685 * but it will either reach outer most bpf_exit (which means it's safe) 17686 * or it will be rejected. When there are no loops the verifier won't be 17687 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17688 * again on the way to bpf_exit. 17689 * When looping the sl->state.branches will be > 0 and this state 17690 * will not be considered for equivalence until branches == 0. 17691 */ 17692 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17693 if (!new_sl) 17694 return -ENOMEM; 17695 env->total_states++; 17696 env->peak_states++; 17697 env->prev_jmps_processed = env->jmps_processed; 17698 env->prev_insn_processed = env->insn_processed; 17699 17700 /* forget precise markings we inherited, see __mark_chain_precision */ 17701 if (env->bpf_capable) 17702 mark_all_scalars_imprecise(env, cur); 17703 17704 /* add new state to the head of linked list */ 17705 new = &new_sl->state; 17706 err = copy_verifier_state(new, cur); 17707 if (err) { 17708 free_verifier_state(new, false); 17709 kfree(new_sl); 17710 return err; 17711 } 17712 new->insn_idx = insn_idx; 17713 WARN_ONCE(new->branches != 1, 17714 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17715 17716 cur->parent = new; 17717 cur->first_insn_idx = insn_idx; 17718 cur->dfs_depth = new->dfs_depth + 1; 17719 clear_jmp_history(cur); 17720 new_sl->next = *explored_state(env, insn_idx); 17721 *explored_state(env, insn_idx) = new_sl; 17722 /* connect new state to parentage chain. Current frame needs all 17723 * registers connected. Only r6 - r9 of the callers are alive (pushed 17724 * to the stack implicitly by JITs) so in callers' frames connect just 17725 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17726 * the state of the call instruction (with WRITTEN set), and r0 comes 17727 * from callee with its full parentage chain, anyway. 17728 */ 17729 /* clear write marks in current state: the writes we did are not writes 17730 * our child did, so they don't screen off its reads from us. 17731 * (There are no read marks in current state, because reads always mark 17732 * their parent and current state never has children yet. Only 17733 * explored_states can get read marks.) 17734 */ 17735 for (j = 0; j <= cur->curframe; j++) { 17736 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17737 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17738 for (i = 0; i < BPF_REG_FP; i++) 17739 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17740 } 17741 17742 /* all stack frames are accessible from callee, clear them all */ 17743 for (j = 0; j <= cur->curframe; j++) { 17744 struct bpf_func_state *frame = cur->frame[j]; 17745 struct bpf_func_state *newframe = new->frame[j]; 17746 17747 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17748 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17749 frame->stack[i].spilled_ptr.parent = 17750 &newframe->stack[i].spilled_ptr; 17751 } 17752 } 17753 return 0; 17754 } 17755 17756 /* Return true if it's OK to have the same insn return a different type. */ 17757 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17758 { 17759 switch (base_type(type)) { 17760 case PTR_TO_CTX: 17761 case PTR_TO_SOCKET: 17762 case PTR_TO_SOCK_COMMON: 17763 case PTR_TO_TCP_SOCK: 17764 case PTR_TO_XDP_SOCK: 17765 case PTR_TO_BTF_ID: 17766 case PTR_TO_ARENA: 17767 return false; 17768 default: 17769 return true; 17770 } 17771 } 17772 17773 /* If an instruction was previously used with particular pointer types, then we 17774 * need to be careful to avoid cases such as the below, where it may be ok 17775 * for one branch accessing the pointer, but not ok for the other branch: 17776 * 17777 * R1 = sock_ptr 17778 * goto X; 17779 * ... 17780 * R1 = some_other_valid_ptr; 17781 * goto X; 17782 * ... 17783 * R2 = *(u32 *)(R1 + 0); 17784 */ 17785 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17786 { 17787 return src != prev && (!reg_type_mismatch_ok(src) || 17788 !reg_type_mismatch_ok(prev)); 17789 } 17790 17791 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17792 bool allow_trust_mismatch) 17793 { 17794 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17795 17796 if (*prev_type == NOT_INIT) { 17797 /* Saw a valid insn 17798 * dst_reg = *(u32 *)(src_reg + off) 17799 * save type to validate intersecting paths 17800 */ 17801 *prev_type = type; 17802 } else if (reg_type_mismatch(type, *prev_type)) { 17803 /* Abuser program is trying to use the same insn 17804 * dst_reg = *(u32*) (src_reg + off) 17805 * with different pointer types: 17806 * src_reg == ctx in one branch and 17807 * src_reg == stack|map in some other branch. 17808 * Reject it. 17809 */ 17810 if (allow_trust_mismatch && 17811 base_type(type) == PTR_TO_BTF_ID && 17812 base_type(*prev_type) == PTR_TO_BTF_ID) { 17813 /* 17814 * Have to support a use case when one path through 17815 * the program yields TRUSTED pointer while another 17816 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17817 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17818 */ 17819 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17820 } else { 17821 verbose(env, "same insn cannot be used with different pointers\n"); 17822 return -EINVAL; 17823 } 17824 } 17825 17826 return 0; 17827 } 17828 17829 static int do_check(struct bpf_verifier_env *env) 17830 { 17831 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17832 struct bpf_verifier_state *state = env->cur_state; 17833 struct bpf_insn *insns = env->prog->insnsi; 17834 struct bpf_reg_state *regs; 17835 int insn_cnt = env->prog->len; 17836 bool do_print_state = false; 17837 int prev_insn_idx = -1; 17838 17839 for (;;) { 17840 bool exception_exit = false; 17841 struct bpf_insn *insn; 17842 u8 class; 17843 int err; 17844 17845 /* reset current history entry on each new instruction */ 17846 env->cur_hist_ent = NULL; 17847 17848 env->prev_insn_idx = prev_insn_idx; 17849 if (env->insn_idx >= insn_cnt) { 17850 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17851 env->insn_idx, insn_cnt); 17852 return -EFAULT; 17853 } 17854 17855 insn = &insns[env->insn_idx]; 17856 class = BPF_CLASS(insn->code); 17857 17858 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17859 verbose(env, 17860 "BPF program is too large. Processed %d insn\n", 17861 env->insn_processed); 17862 return -E2BIG; 17863 } 17864 17865 state->last_insn_idx = env->prev_insn_idx; 17866 17867 if (is_prune_point(env, env->insn_idx)) { 17868 err = is_state_visited(env, env->insn_idx); 17869 if (err < 0) 17870 return err; 17871 if (err == 1) { 17872 /* found equivalent state, can prune the search */ 17873 if (env->log.level & BPF_LOG_LEVEL) { 17874 if (do_print_state) 17875 verbose(env, "\nfrom %d to %d%s: safe\n", 17876 env->prev_insn_idx, env->insn_idx, 17877 env->cur_state->speculative ? 17878 " (speculative execution)" : ""); 17879 else 17880 verbose(env, "%d: safe\n", env->insn_idx); 17881 } 17882 goto process_bpf_exit; 17883 } 17884 } 17885 17886 if (is_jmp_point(env, env->insn_idx)) { 17887 err = push_jmp_history(env, state, 0); 17888 if (err) 17889 return err; 17890 } 17891 17892 if (signal_pending(current)) 17893 return -EAGAIN; 17894 17895 if (need_resched()) 17896 cond_resched(); 17897 17898 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17899 verbose(env, "\nfrom %d to %d%s:", 17900 env->prev_insn_idx, env->insn_idx, 17901 env->cur_state->speculative ? 17902 " (speculative execution)" : ""); 17903 print_verifier_state(env, state->frame[state->curframe], true); 17904 do_print_state = false; 17905 } 17906 17907 if (env->log.level & BPF_LOG_LEVEL) { 17908 const struct bpf_insn_cbs cbs = { 17909 .cb_call = disasm_kfunc_name, 17910 .cb_print = verbose, 17911 .private_data = env, 17912 }; 17913 17914 if (verifier_state_scratched(env)) 17915 print_insn_state(env, state->frame[state->curframe]); 17916 17917 verbose_linfo(env, env->insn_idx, "; "); 17918 env->prev_log_pos = env->log.end_pos; 17919 verbose(env, "%d: ", env->insn_idx); 17920 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17921 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17922 env->prev_log_pos = env->log.end_pos; 17923 } 17924 17925 if (bpf_prog_is_offloaded(env->prog->aux)) { 17926 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17927 env->prev_insn_idx); 17928 if (err) 17929 return err; 17930 } 17931 17932 regs = cur_regs(env); 17933 sanitize_mark_insn_seen(env); 17934 prev_insn_idx = env->insn_idx; 17935 17936 if (class == BPF_ALU || class == BPF_ALU64) { 17937 err = check_alu_op(env, insn); 17938 if (err) 17939 return err; 17940 17941 } else if (class == BPF_LDX) { 17942 enum bpf_reg_type src_reg_type; 17943 17944 /* check for reserved fields is already done */ 17945 17946 /* check src operand */ 17947 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17948 if (err) 17949 return err; 17950 17951 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17952 if (err) 17953 return err; 17954 17955 src_reg_type = regs[insn->src_reg].type; 17956 17957 /* check that memory (src_reg + off) is readable, 17958 * the state of dst_reg will be updated by this func 17959 */ 17960 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17961 insn->off, BPF_SIZE(insn->code), 17962 BPF_READ, insn->dst_reg, false, 17963 BPF_MODE(insn->code) == BPF_MEMSX); 17964 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17965 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17966 if (err) 17967 return err; 17968 } else if (class == BPF_STX) { 17969 enum bpf_reg_type dst_reg_type; 17970 17971 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17972 err = check_atomic(env, env->insn_idx, insn); 17973 if (err) 17974 return err; 17975 env->insn_idx++; 17976 continue; 17977 } 17978 17979 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17980 verbose(env, "BPF_STX uses reserved fields\n"); 17981 return -EINVAL; 17982 } 17983 17984 /* check src1 operand */ 17985 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17986 if (err) 17987 return err; 17988 /* check src2 operand */ 17989 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17990 if (err) 17991 return err; 17992 17993 dst_reg_type = regs[insn->dst_reg].type; 17994 17995 /* check that memory (dst_reg + off) is writeable */ 17996 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17997 insn->off, BPF_SIZE(insn->code), 17998 BPF_WRITE, insn->src_reg, false, false); 17999 if (err) 18000 return err; 18001 18002 err = save_aux_ptr_type(env, dst_reg_type, false); 18003 if (err) 18004 return err; 18005 } else if (class == BPF_ST) { 18006 enum bpf_reg_type dst_reg_type; 18007 18008 if (BPF_MODE(insn->code) != BPF_MEM || 18009 insn->src_reg != BPF_REG_0) { 18010 verbose(env, "BPF_ST uses reserved fields\n"); 18011 return -EINVAL; 18012 } 18013 /* check src operand */ 18014 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 18015 if (err) 18016 return err; 18017 18018 dst_reg_type = regs[insn->dst_reg].type; 18019 18020 /* check that memory (dst_reg + off) is writeable */ 18021 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 18022 insn->off, BPF_SIZE(insn->code), 18023 BPF_WRITE, -1, false, false); 18024 if (err) 18025 return err; 18026 18027 err = save_aux_ptr_type(env, dst_reg_type, false); 18028 if (err) 18029 return err; 18030 } else if (class == BPF_JMP || class == BPF_JMP32) { 18031 u8 opcode = BPF_OP(insn->code); 18032 18033 env->jmps_processed++; 18034 if (opcode == BPF_CALL) { 18035 if (BPF_SRC(insn->code) != BPF_K || 18036 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 18037 && insn->off != 0) || 18038 (insn->src_reg != BPF_REG_0 && 18039 insn->src_reg != BPF_PSEUDO_CALL && 18040 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18041 insn->dst_reg != BPF_REG_0 || 18042 class == BPF_JMP32) { 18043 verbose(env, "BPF_CALL uses reserved fields\n"); 18044 return -EINVAL; 18045 } 18046 18047 if (env->cur_state->active_lock.ptr) { 18048 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 18049 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 18050 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 18051 verbose(env, "function calls are not allowed while holding a lock\n"); 18052 return -EINVAL; 18053 } 18054 } 18055 if (insn->src_reg == BPF_PSEUDO_CALL) { 18056 err = check_func_call(env, insn, &env->insn_idx); 18057 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 18058 err = check_kfunc_call(env, insn, &env->insn_idx); 18059 if (!err && is_bpf_throw_kfunc(insn)) { 18060 exception_exit = true; 18061 goto process_bpf_exit_full; 18062 } 18063 } else { 18064 err = check_helper_call(env, insn, &env->insn_idx); 18065 } 18066 if (err) 18067 return err; 18068 18069 mark_reg_scratched(env, BPF_REG_0); 18070 } else if (opcode == BPF_JA) { 18071 if (BPF_SRC(insn->code) != BPF_K || 18072 insn->src_reg != BPF_REG_0 || 18073 insn->dst_reg != BPF_REG_0 || 18074 (class == BPF_JMP && insn->imm != 0) || 18075 (class == BPF_JMP32 && insn->off != 0)) { 18076 verbose(env, "BPF_JA uses reserved fields\n"); 18077 return -EINVAL; 18078 } 18079 18080 if (class == BPF_JMP) 18081 env->insn_idx += insn->off + 1; 18082 else 18083 env->insn_idx += insn->imm + 1; 18084 continue; 18085 18086 } else if (opcode == BPF_EXIT) { 18087 if (BPF_SRC(insn->code) != BPF_K || 18088 insn->imm != 0 || 18089 insn->src_reg != BPF_REG_0 || 18090 insn->dst_reg != BPF_REG_0 || 18091 class == BPF_JMP32) { 18092 verbose(env, "BPF_EXIT uses reserved fields\n"); 18093 return -EINVAL; 18094 } 18095 process_bpf_exit_full: 18096 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 18097 verbose(env, "bpf_spin_unlock is missing\n"); 18098 return -EINVAL; 18099 } 18100 18101 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 18102 verbose(env, "bpf_rcu_read_unlock is missing\n"); 18103 return -EINVAL; 18104 } 18105 18106 if (env->cur_state->active_preempt_lock && !env->cur_state->curframe) { 18107 verbose(env, "%d bpf_preempt_enable%s missing\n", 18108 env->cur_state->active_preempt_lock, 18109 env->cur_state->active_preempt_lock == 1 ? " is" : "(s) are"); 18110 return -EINVAL; 18111 } 18112 18113 /* We must do check_reference_leak here before 18114 * prepare_func_exit to handle the case when 18115 * state->curframe > 0, it may be a callback 18116 * function, for which reference_state must 18117 * match caller reference state when it exits. 18118 */ 18119 err = check_reference_leak(env, exception_exit); 18120 if (err) 18121 return err; 18122 18123 /* The side effect of the prepare_func_exit 18124 * which is being skipped is that it frees 18125 * bpf_func_state. Typically, process_bpf_exit 18126 * will only be hit with outermost exit. 18127 * copy_verifier_state in pop_stack will handle 18128 * freeing of any extra bpf_func_state left over 18129 * from not processing all nested function 18130 * exits. We also skip return code checks as 18131 * they are not needed for exceptional exits. 18132 */ 18133 if (exception_exit) 18134 goto process_bpf_exit; 18135 18136 if (state->curframe) { 18137 /* exit from nested function */ 18138 err = prepare_func_exit(env, &env->insn_idx); 18139 if (err) 18140 return err; 18141 do_print_state = true; 18142 continue; 18143 } 18144 18145 err = check_return_code(env, BPF_REG_0, "R0"); 18146 if (err) 18147 return err; 18148 process_bpf_exit: 18149 mark_verifier_state_scratched(env); 18150 update_branch_counts(env, env->cur_state); 18151 err = pop_stack(env, &prev_insn_idx, 18152 &env->insn_idx, pop_log); 18153 if (err < 0) { 18154 if (err != -ENOENT) 18155 return err; 18156 break; 18157 } else { 18158 do_print_state = true; 18159 continue; 18160 } 18161 } else { 18162 err = check_cond_jmp_op(env, insn, &env->insn_idx); 18163 if (err) 18164 return err; 18165 } 18166 } else if (class == BPF_LD) { 18167 u8 mode = BPF_MODE(insn->code); 18168 18169 if (mode == BPF_ABS || mode == BPF_IND) { 18170 err = check_ld_abs(env, insn); 18171 if (err) 18172 return err; 18173 18174 } else if (mode == BPF_IMM) { 18175 err = check_ld_imm(env, insn); 18176 if (err) 18177 return err; 18178 18179 env->insn_idx++; 18180 sanitize_mark_insn_seen(env); 18181 } else { 18182 verbose(env, "invalid BPF_LD mode\n"); 18183 return -EINVAL; 18184 } 18185 } else { 18186 verbose(env, "unknown insn class %d\n", class); 18187 return -EINVAL; 18188 } 18189 18190 env->insn_idx++; 18191 } 18192 18193 return 0; 18194 } 18195 18196 static int find_btf_percpu_datasec(struct btf *btf) 18197 { 18198 const struct btf_type *t; 18199 const char *tname; 18200 int i, n; 18201 18202 /* 18203 * Both vmlinux and module each have their own ".data..percpu" 18204 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 18205 * types to look at only module's own BTF types. 18206 */ 18207 n = btf_nr_types(btf); 18208 if (btf_is_module(btf)) 18209 i = btf_nr_types(btf_vmlinux); 18210 else 18211 i = 1; 18212 18213 for(; i < n; i++) { 18214 t = btf_type_by_id(btf, i); 18215 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 18216 continue; 18217 18218 tname = btf_name_by_offset(btf, t->name_off); 18219 if (!strcmp(tname, ".data..percpu")) 18220 return i; 18221 } 18222 18223 return -ENOENT; 18224 } 18225 18226 /* replace pseudo btf_id with kernel symbol address */ 18227 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18228 struct bpf_insn *insn, 18229 struct bpf_insn_aux_data *aux) 18230 { 18231 const struct btf_var_secinfo *vsi; 18232 const struct btf_type *datasec; 18233 struct btf_mod_pair *btf_mod; 18234 const struct btf_type *t; 18235 const char *sym_name; 18236 bool percpu = false; 18237 u32 type, id = insn->imm; 18238 struct btf *btf; 18239 s32 datasec_id; 18240 u64 addr; 18241 int i, btf_fd, err; 18242 18243 btf_fd = insn[1].imm; 18244 if (btf_fd) { 18245 btf = btf_get_by_fd(btf_fd); 18246 if (IS_ERR(btf)) { 18247 verbose(env, "invalid module BTF object FD specified.\n"); 18248 return -EINVAL; 18249 } 18250 } else { 18251 if (!btf_vmlinux) { 18252 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18253 return -EINVAL; 18254 } 18255 btf = btf_vmlinux; 18256 btf_get(btf); 18257 } 18258 18259 t = btf_type_by_id(btf, id); 18260 if (!t) { 18261 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 18262 err = -ENOENT; 18263 goto err_put; 18264 } 18265 18266 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18267 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18268 err = -EINVAL; 18269 goto err_put; 18270 } 18271 18272 sym_name = btf_name_by_offset(btf, t->name_off); 18273 addr = kallsyms_lookup_name(sym_name); 18274 if (!addr) { 18275 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18276 sym_name); 18277 err = -ENOENT; 18278 goto err_put; 18279 } 18280 insn[0].imm = (u32)addr; 18281 insn[1].imm = addr >> 32; 18282 18283 if (btf_type_is_func(t)) { 18284 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18285 aux->btf_var.mem_size = 0; 18286 goto check_btf; 18287 } 18288 18289 datasec_id = find_btf_percpu_datasec(btf); 18290 if (datasec_id > 0) { 18291 datasec = btf_type_by_id(btf, datasec_id); 18292 for_each_vsi(i, datasec, vsi) { 18293 if (vsi->type == id) { 18294 percpu = true; 18295 break; 18296 } 18297 } 18298 } 18299 18300 type = t->type; 18301 t = btf_type_skip_modifiers(btf, type, NULL); 18302 if (percpu) { 18303 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18304 aux->btf_var.btf = btf; 18305 aux->btf_var.btf_id = type; 18306 } else if (!btf_type_is_struct(t)) { 18307 const struct btf_type *ret; 18308 const char *tname; 18309 u32 tsize; 18310 18311 /* resolve the type size of ksym. */ 18312 ret = btf_resolve_size(btf, t, &tsize); 18313 if (IS_ERR(ret)) { 18314 tname = btf_name_by_offset(btf, t->name_off); 18315 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18316 tname, PTR_ERR(ret)); 18317 err = -EINVAL; 18318 goto err_put; 18319 } 18320 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18321 aux->btf_var.mem_size = tsize; 18322 } else { 18323 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18324 aux->btf_var.btf = btf; 18325 aux->btf_var.btf_id = type; 18326 } 18327 check_btf: 18328 /* check whether we recorded this BTF (and maybe module) already */ 18329 for (i = 0; i < env->used_btf_cnt; i++) { 18330 if (env->used_btfs[i].btf == btf) { 18331 btf_put(btf); 18332 return 0; 18333 } 18334 } 18335 18336 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18337 err = -E2BIG; 18338 goto err_put; 18339 } 18340 18341 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18342 btf_mod->btf = btf; 18343 btf_mod->module = NULL; 18344 18345 /* if we reference variables from kernel module, bump its refcount */ 18346 if (btf_is_module(btf)) { 18347 btf_mod->module = btf_try_get_module(btf); 18348 if (!btf_mod->module) { 18349 err = -ENXIO; 18350 goto err_put; 18351 } 18352 } 18353 18354 env->used_btf_cnt++; 18355 18356 return 0; 18357 err_put: 18358 btf_put(btf); 18359 return err; 18360 } 18361 18362 static bool is_tracing_prog_type(enum bpf_prog_type type) 18363 { 18364 switch (type) { 18365 case BPF_PROG_TYPE_KPROBE: 18366 case BPF_PROG_TYPE_TRACEPOINT: 18367 case BPF_PROG_TYPE_PERF_EVENT: 18368 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18369 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18370 return true; 18371 default: 18372 return false; 18373 } 18374 } 18375 18376 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18377 struct bpf_map *map, 18378 struct bpf_prog *prog) 18379 18380 { 18381 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18382 18383 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18384 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18385 if (is_tracing_prog_type(prog_type)) { 18386 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18387 return -EINVAL; 18388 } 18389 } 18390 18391 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18392 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18393 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18394 return -EINVAL; 18395 } 18396 18397 if (is_tracing_prog_type(prog_type)) { 18398 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18399 return -EINVAL; 18400 } 18401 } 18402 18403 if (btf_record_has_field(map->record, BPF_TIMER)) { 18404 if (is_tracing_prog_type(prog_type)) { 18405 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18406 return -EINVAL; 18407 } 18408 } 18409 18410 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 18411 if (is_tracing_prog_type(prog_type)) { 18412 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 18413 return -EINVAL; 18414 } 18415 } 18416 18417 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18418 !bpf_offload_prog_map_match(prog, map)) { 18419 verbose(env, "offload device mismatch between prog and map\n"); 18420 return -EINVAL; 18421 } 18422 18423 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18424 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18425 return -EINVAL; 18426 } 18427 18428 if (prog->sleepable) 18429 switch (map->map_type) { 18430 case BPF_MAP_TYPE_HASH: 18431 case BPF_MAP_TYPE_LRU_HASH: 18432 case BPF_MAP_TYPE_ARRAY: 18433 case BPF_MAP_TYPE_PERCPU_HASH: 18434 case BPF_MAP_TYPE_PERCPU_ARRAY: 18435 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18436 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18437 case BPF_MAP_TYPE_HASH_OF_MAPS: 18438 case BPF_MAP_TYPE_RINGBUF: 18439 case BPF_MAP_TYPE_USER_RINGBUF: 18440 case BPF_MAP_TYPE_INODE_STORAGE: 18441 case BPF_MAP_TYPE_SK_STORAGE: 18442 case BPF_MAP_TYPE_TASK_STORAGE: 18443 case BPF_MAP_TYPE_CGRP_STORAGE: 18444 case BPF_MAP_TYPE_QUEUE: 18445 case BPF_MAP_TYPE_STACK: 18446 case BPF_MAP_TYPE_ARENA: 18447 break; 18448 default: 18449 verbose(env, 18450 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18451 return -EINVAL; 18452 } 18453 18454 return 0; 18455 } 18456 18457 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18458 { 18459 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18460 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18461 } 18462 18463 /* find and rewrite pseudo imm in ld_imm64 instructions: 18464 * 18465 * 1. if it accesses map FD, replace it with actual map pointer. 18466 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18467 * 18468 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18469 */ 18470 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18471 { 18472 struct bpf_insn *insn = env->prog->insnsi; 18473 int insn_cnt = env->prog->len; 18474 int i, j, err; 18475 18476 err = bpf_prog_calc_tag(env->prog); 18477 if (err) 18478 return err; 18479 18480 for (i = 0; i < insn_cnt; i++, insn++) { 18481 if (BPF_CLASS(insn->code) == BPF_LDX && 18482 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18483 insn->imm != 0)) { 18484 verbose(env, "BPF_LDX uses reserved fields\n"); 18485 return -EINVAL; 18486 } 18487 18488 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18489 struct bpf_insn_aux_data *aux; 18490 struct bpf_map *map; 18491 struct fd f; 18492 u64 addr; 18493 u32 fd; 18494 18495 if (i == insn_cnt - 1 || insn[1].code != 0 || 18496 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18497 insn[1].off != 0) { 18498 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18499 return -EINVAL; 18500 } 18501 18502 if (insn[0].src_reg == 0) 18503 /* valid generic load 64-bit imm */ 18504 goto next_insn; 18505 18506 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18507 aux = &env->insn_aux_data[i]; 18508 err = check_pseudo_btf_id(env, insn, aux); 18509 if (err) 18510 return err; 18511 goto next_insn; 18512 } 18513 18514 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18515 aux = &env->insn_aux_data[i]; 18516 aux->ptr_type = PTR_TO_FUNC; 18517 goto next_insn; 18518 } 18519 18520 /* In final convert_pseudo_ld_imm64() step, this is 18521 * converted into regular 64-bit imm load insn. 18522 */ 18523 switch (insn[0].src_reg) { 18524 case BPF_PSEUDO_MAP_VALUE: 18525 case BPF_PSEUDO_MAP_IDX_VALUE: 18526 break; 18527 case BPF_PSEUDO_MAP_FD: 18528 case BPF_PSEUDO_MAP_IDX: 18529 if (insn[1].imm == 0) 18530 break; 18531 fallthrough; 18532 default: 18533 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18534 return -EINVAL; 18535 } 18536 18537 switch (insn[0].src_reg) { 18538 case BPF_PSEUDO_MAP_IDX_VALUE: 18539 case BPF_PSEUDO_MAP_IDX: 18540 if (bpfptr_is_null(env->fd_array)) { 18541 verbose(env, "fd_idx without fd_array is invalid\n"); 18542 return -EPROTO; 18543 } 18544 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18545 insn[0].imm * sizeof(fd), 18546 sizeof(fd))) 18547 return -EFAULT; 18548 break; 18549 default: 18550 fd = insn[0].imm; 18551 break; 18552 } 18553 18554 f = fdget(fd); 18555 map = __bpf_map_get(f); 18556 if (IS_ERR(map)) { 18557 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 18558 return PTR_ERR(map); 18559 } 18560 18561 err = check_map_prog_compatibility(env, map, env->prog); 18562 if (err) { 18563 fdput(f); 18564 return err; 18565 } 18566 18567 aux = &env->insn_aux_data[i]; 18568 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18569 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18570 addr = (unsigned long)map; 18571 } else { 18572 u32 off = insn[1].imm; 18573 18574 if (off >= BPF_MAX_VAR_OFF) { 18575 verbose(env, "direct value offset of %u is not allowed\n", off); 18576 fdput(f); 18577 return -EINVAL; 18578 } 18579 18580 if (!map->ops->map_direct_value_addr) { 18581 verbose(env, "no direct value access support for this map type\n"); 18582 fdput(f); 18583 return -EINVAL; 18584 } 18585 18586 err = map->ops->map_direct_value_addr(map, &addr, off); 18587 if (err) { 18588 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18589 map->value_size, off); 18590 fdput(f); 18591 return err; 18592 } 18593 18594 aux->map_off = off; 18595 addr += off; 18596 } 18597 18598 insn[0].imm = (u32)addr; 18599 insn[1].imm = addr >> 32; 18600 18601 /* check whether we recorded this map already */ 18602 for (j = 0; j < env->used_map_cnt; j++) { 18603 if (env->used_maps[j] == map) { 18604 aux->map_index = j; 18605 fdput(f); 18606 goto next_insn; 18607 } 18608 } 18609 18610 if (env->used_map_cnt >= MAX_USED_MAPS) { 18611 verbose(env, "The total number of maps per program has reached the limit of %u\n", 18612 MAX_USED_MAPS); 18613 fdput(f); 18614 return -E2BIG; 18615 } 18616 18617 if (env->prog->sleepable) 18618 atomic64_inc(&map->sleepable_refcnt); 18619 /* hold the map. If the program is rejected by verifier, 18620 * the map will be released by release_maps() or it 18621 * will be used by the valid program until it's unloaded 18622 * and all maps are released in bpf_free_used_maps() 18623 */ 18624 bpf_map_inc(map); 18625 18626 aux->map_index = env->used_map_cnt; 18627 env->used_maps[env->used_map_cnt++] = map; 18628 18629 if (bpf_map_is_cgroup_storage(map) && 18630 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18631 verbose(env, "only one cgroup storage of each type is allowed\n"); 18632 fdput(f); 18633 return -EBUSY; 18634 } 18635 if (map->map_type == BPF_MAP_TYPE_ARENA) { 18636 if (env->prog->aux->arena) { 18637 verbose(env, "Only one arena per program\n"); 18638 fdput(f); 18639 return -EBUSY; 18640 } 18641 if (!env->allow_ptr_leaks || !env->bpf_capable) { 18642 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 18643 fdput(f); 18644 return -EPERM; 18645 } 18646 if (!env->prog->jit_requested) { 18647 verbose(env, "JIT is required to use arena\n"); 18648 fdput(f); 18649 return -EOPNOTSUPP; 18650 } 18651 if (!bpf_jit_supports_arena()) { 18652 verbose(env, "JIT doesn't support arena\n"); 18653 fdput(f); 18654 return -EOPNOTSUPP; 18655 } 18656 env->prog->aux->arena = (void *)map; 18657 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 18658 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 18659 fdput(f); 18660 return -EINVAL; 18661 } 18662 } 18663 18664 fdput(f); 18665 next_insn: 18666 insn++; 18667 i++; 18668 continue; 18669 } 18670 18671 /* Basic sanity check before we invest more work here. */ 18672 if (!bpf_opcode_in_insntable(insn->code)) { 18673 verbose(env, "unknown opcode %02x\n", insn->code); 18674 return -EINVAL; 18675 } 18676 } 18677 18678 /* now all pseudo BPF_LD_IMM64 instructions load valid 18679 * 'struct bpf_map *' into a register instead of user map_fd. 18680 * These pointers will be used later by verifier to validate map access. 18681 */ 18682 return 0; 18683 } 18684 18685 /* drop refcnt of maps used by the rejected program */ 18686 static void release_maps(struct bpf_verifier_env *env) 18687 { 18688 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18689 env->used_map_cnt); 18690 } 18691 18692 /* drop refcnt of maps used by the rejected program */ 18693 static void release_btfs(struct bpf_verifier_env *env) 18694 { 18695 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18696 env->used_btf_cnt); 18697 } 18698 18699 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18700 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18701 { 18702 struct bpf_insn *insn = env->prog->insnsi; 18703 int insn_cnt = env->prog->len; 18704 int i; 18705 18706 for (i = 0; i < insn_cnt; i++, insn++) { 18707 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18708 continue; 18709 if (insn->src_reg == BPF_PSEUDO_FUNC) 18710 continue; 18711 insn->src_reg = 0; 18712 } 18713 } 18714 18715 /* single env->prog->insni[off] instruction was replaced with the range 18716 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18717 * [0, off) and [off, end) to new locations, so the patched range stays zero 18718 */ 18719 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18720 struct bpf_insn_aux_data *new_data, 18721 struct bpf_prog *new_prog, u32 off, u32 cnt) 18722 { 18723 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18724 struct bpf_insn *insn = new_prog->insnsi; 18725 u32 old_seen = old_data[off].seen; 18726 u32 prog_len; 18727 int i; 18728 18729 /* aux info at OFF always needs adjustment, no matter fast path 18730 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18731 * original insn at old prog. 18732 */ 18733 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18734 18735 if (cnt == 1) 18736 return; 18737 prog_len = new_prog->len; 18738 18739 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18740 memcpy(new_data + off + cnt - 1, old_data + off, 18741 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18742 for (i = off; i < off + cnt - 1; i++) { 18743 /* Expand insni[off]'s seen count to the patched range. */ 18744 new_data[i].seen = old_seen; 18745 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18746 } 18747 env->insn_aux_data = new_data; 18748 vfree(old_data); 18749 } 18750 18751 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18752 { 18753 int i; 18754 18755 if (len == 1) 18756 return; 18757 /* NOTE: fake 'exit' subprog should be updated as well. */ 18758 for (i = 0; i <= env->subprog_cnt; i++) { 18759 if (env->subprog_info[i].start <= off) 18760 continue; 18761 env->subprog_info[i].start += len - 1; 18762 } 18763 } 18764 18765 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18766 { 18767 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18768 int i, sz = prog->aux->size_poke_tab; 18769 struct bpf_jit_poke_descriptor *desc; 18770 18771 for (i = 0; i < sz; i++) { 18772 desc = &tab[i]; 18773 if (desc->insn_idx <= off) 18774 continue; 18775 desc->insn_idx += len - 1; 18776 } 18777 } 18778 18779 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18780 const struct bpf_insn *patch, u32 len) 18781 { 18782 struct bpf_prog *new_prog; 18783 struct bpf_insn_aux_data *new_data = NULL; 18784 18785 if (len > 1) { 18786 new_data = vzalloc(array_size(env->prog->len + len - 1, 18787 sizeof(struct bpf_insn_aux_data))); 18788 if (!new_data) 18789 return NULL; 18790 } 18791 18792 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18793 if (IS_ERR(new_prog)) { 18794 if (PTR_ERR(new_prog) == -ERANGE) 18795 verbose(env, 18796 "insn %d cannot be patched due to 16-bit range\n", 18797 env->insn_aux_data[off].orig_idx); 18798 vfree(new_data); 18799 return NULL; 18800 } 18801 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18802 adjust_subprog_starts(env, off, len); 18803 adjust_poke_descs(new_prog, off, len); 18804 return new_prog; 18805 } 18806 18807 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18808 u32 off, u32 cnt) 18809 { 18810 int i, j; 18811 18812 /* find first prog starting at or after off (first to remove) */ 18813 for (i = 0; i < env->subprog_cnt; i++) 18814 if (env->subprog_info[i].start >= off) 18815 break; 18816 /* find first prog starting at or after off + cnt (first to stay) */ 18817 for (j = i; j < env->subprog_cnt; j++) 18818 if (env->subprog_info[j].start >= off + cnt) 18819 break; 18820 /* if j doesn't start exactly at off + cnt, we are just removing 18821 * the front of previous prog 18822 */ 18823 if (env->subprog_info[j].start != off + cnt) 18824 j--; 18825 18826 if (j > i) { 18827 struct bpf_prog_aux *aux = env->prog->aux; 18828 int move; 18829 18830 /* move fake 'exit' subprog as well */ 18831 move = env->subprog_cnt + 1 - j; 18832 18833 memmove(env->subprog_info + i, 18834 env->subprog_info + j, 18835 sizeof(*env->subprog_info) * move); 18836 env->subprog_cnt -= j - i; 18837 18838 /* remove func_info */ 18839 if (aux->func_info) { 18840 move = aux->func_info_cnt - j; 18841 18842 memmove(aux->func_info + i, 18843 aux->func_info + j, 18844 sizeof(*aux->func_info) * move); 18845 aux->func_info_cnt -= j - i; 18846 /* func_info->insn_off is set after all code rewrites, 18847 * in adjust_btf_func() - no need to adjust 18848 */ 18849 } 18850 } else { 18851 /* convert i from "first prog to remove" to "first to adjust" */ 18852 if (env->subprog_info[i].start == off) 18853 i++; 18854 } 18855 18856 /* update fake 'exit' subprog as well */ 18857 for (; i <= env->subprog_cnt; i++) 18858 env->subprog_info[i].start -= cnt; 18859 18860 return 0; 18861 } 18862 18863 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18864 u32 cnt) 18865 { 18866 struct bpf_prog *prog = env->prog; 18867 u32 i, l_off, l_cnt, nr_linfo; 18868 struct bpf_line_info *linfo; 18869 18870 nr_linfo = prog->aux->nr_linfo; 18871 if (!nr_linfo) 18872 return 0; 18873 18874 linfo = prog->aux->linfo; 18875 18876 /* find first line info to remove, count lines to be removed */ 18877 for (i = 0; i < nr_linfo; i++) 18878 if (linfo[i].insn_off >= off) 18879 break; 18880 18881 l_off = i; 18882 l_cnt = 0; 18883 for (; i < nr_linfo; i++) 18884 if (linfo[i].insn_off < off + cnt) 18885 l_cnt++; 18886 else 18887 break; 18888 18889 /* First live insn doesn't match first live linfo, it needs to "inherit" 18890 * last removed linfo. prog is already modified, so prog->len == off 18891 * means no live instructions after (tail of the program was removed). 18892 */ 18893 if (prog->len != off && l_cnt && 18894 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18895 l_cnt--; 18896 linfo[--i].insn_off = off + cnt; 18897 } 18898 18899 /* remove the line info which refer to the removed instructions */ 18900 if (l_cnt) { 18901 memmove(linfo + l_off, linfo + i, 18902 sizeof(*linfo) * (nr_linfo - i)); 18903 18904 prog->aux->nr_linfo -= l_cnt; 18905 nr_linfo = prog->aux->nr_linfo; 18906 } 18907 18908 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18909 for (i = l_off; i < nr_linfo; i++) 18910 linfo[i].insn_off -= cnt; 18911 18912 /* fix up all subprogs (incl. 'exit') which start >= off */ 18913 for (i = 0; i <= env->subprog_cnt; i++) 18914 if (env->subprog_info[i].linfo_idx > l_off) { 18915 /* program may have started in the removed region but 18916 * may not be fully removed 18917 */ 18918 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18919 env->subprog_info[i].linfo_idx -= l_cnt; 18920 else 18921 env->subprog_info[i].linfo_idx = l_off; 18922 } 18923 18924 return 0; 18925 } 18926 18927 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18928 { 18929 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18930 unsigned int orig_prog_len = env->prog->len; 18931 int err; 18932 18933 if (bpf_prog_is_offloaded(env->prog->aux)) 18934 bpf_prog_offload_remove_insns(env, off, cnt); 18935 18936 err = bpf_remove_insns(env->prog, off, cnt); 18937 if (err) 18938 return err; 18939 18940 err = adjust_subprog_starts_after_remove(env, off, cnt); 18941 if (err) 18942 return err; 18943 18944 err = bpf_adj_linfo_after_remove(env, off, cnt); 18945 if (err) 18946 return err; 18947 18948 memmove(aux_data + off, aux_data + off + cnt, 18949 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18950 18951 return 0; 18952 } 18953 18954 /* The verifier does more data flow analysis than llvm and will not 18955 * explore branches that are dead at run time. Malicious programs can 18956 * have dead code too. Therefore replace all dead at-run-time code 18957 * with 'ja -1'. 18958 * 18959 * Just nops are not optimal, e.g. if they would sit at the end of the 18960 * program and through another bug we would manage to jump there, then 18961 * we'd execute beyond program memory otherwise. Returning exception 18962 * code also wouldn't work since we can have subprogs where the dead 18963 * code could be located. 18964 */ 18965 static void sanitize_dead_code(struct bpf_verifier_env *env) 18966 { 18967 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18968 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18969 struct bpf_insn *insn = env->prog->insnsi; 18970 const int insn_cnt = env->prog->len; 18971 int i; 18972 18973 for (i = 0; i < insn_cnt; i++) { 18974 if (aux_data[i].seen) 18975 continue; 18976 memcpy(insn + i, &trap, sizeof(trap)); 18977 aux_data[i].zext_dst = false; 18978 } 18979 } 18980 18981 static bool insn_is_cond_jump(u8 code) 18982 { 18983 u8 op; 18984 18985 op = BPF_OP(code); 18986 if (BPF_CLASS(code) == BPF_JMP32) 18987 return op != BPF_JA; 18988 18989 if (BPF_CLASS(code) != BPF_JMP) 18990 return false; 18991 18992 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18993 } 18994 18995 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18996 { 18997 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18998 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18999 struct bpf_insn *insn = env->prog->insnsi; 19000 const int insn_cnt = env->prog->len; 19001 int i; 19002 19003 for (i = 0; i < insn_cnt; i++, insn++) { 19004 if (!insn_is_cond_jump(insn->code)) 19005 continue; 19006 19007 if (!aux_data[i + 1].seen) 19008 ja.off = insn->off; 19009 else if (!aux_data[i + 1 + insn->off].seen) 19010 ja.off = 0; 19011 else 19012 continue; 19013 19014 if (bpf_prog_is_offloaded(env->prog->aux)) 19015 bpf_prog_offload_replace_insn(env, i, &ja); 19016 19017 memcpy(insn, &ja, sizeof(ja)); 19018 } 19019 } 19020 19021 static int opt_remove_dead_code(struct bpf_verifier_env *env) 19022 { 19023 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 19024 int insn_cnt = env->prog->len; 19025 int i, err; 19026 19027 for (i = 0; i < insn_cnt; i++) { 19028 int j; 19029 19030 j = 0; 19031 while (i + j < insn_cnt && !aux_data[i + j].seen) 19032 j++; 19033 if (!j) 19034 continue; 19035 19036 err = verifier_remove_insns(env, i, j); 19037 if (err) 19038 return err; 19039 insn_cnt = env->prog->len; 19040 } 19041 19042 return 0; 19043 } 19044 19045 static int opt_remove_nops(struct bpf_verifier_env *env) 19046 { 19047 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 19048 struct bpf_insn *insn = env->prog->insnsi; 19049 int insn_cnt = env->prog->len; 19050 int i, err; 19051 19052 for (i = 0; i < insn_cnt; i++) { 19053 if (memcmp(&insn[i], &ja, sizeof(ja))) 19054 continue; 19055 19056 err = verifier_remove_insns(env, i, 1); 19057 if (err) 19058 return err; 19059 insn_cnt--; 19060 i--; 19061 } 19062 19063 return 0; 19064 } 19065 19066 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 19067 const union bpf_attr *attr) 19068 { 19069 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 19070 struct bpf_insn_aux_data *aux = env->insn_aux_data; 19071 int i, patch_len, delta = 0, len = env->prog->len; 19072 struct bpf_insn *insns = env->prog->insnsi; 19073 struct bpf_prog *new_prog; 19074 bool rnd_hi32; 19075 19076 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 19077 zext_patch[1] = BPF_ZEXT_REG(0); 19078 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 19079 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 19080 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 19081 for (i = 0; i < len; i++) { 19082 int adj_idx = i + delta; 19083 struct bpf_insn insn; 19084 int load_reg; 19085 19086 insn = insns[adj_idx]; 19087 load_reg = insn_def_regno(&insn); 19088 if (!aux[adj_idx].zext_dst) { 19089 u8 code, class; 19090 u32 imm_rnd; 19091 19092 if (!rnd_hi32) 19093 continue; 19094 19095 code = insn.code; 19096 class = BPF_CLASS(code); 19097 if (load_reg == -1) 19098 continue; 19099 19100 /* NOTE: arg "reg" (the fourth one) is only used for 19101 * BPF_STX + SRC_OP, so it is safe to pass NULL 19102 * here. 19103 */ 19104 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 19105 if (class == BPF_LD && 19106 BPF_MODE(code) == BPF_IMM) 19107 i++; 19108 continue; 19109 } 19110 19111 /* ctx load could be transformed into wider load. */ 19112 if (class == BPF_LDX && 19113 aux[adj_idx].ptr_type == PTR_TO_CTX) 19114 continue; 19115 19116 imm_rnd = get_random_u32(); 19117 rnd_hi32_patch[0] = insn; 19118 rnd_hi32_patch[1].imm = imm_rnd; 19119 rnd_hi32_patch[3].dst_reg = load_reg; 19120 patch = rnd_hi32_patch; 19121 patch_len = 4; 19122 goto apply_patch_buffer; 19123 } 19124 19125 /* Add in an zero-extend instruction if a) the JIT has requested 19126 * it or b) it's a CMPXCHG. 19127 * 19128 * The latter is because: BPF_CMPXCHG always loads a value into 19129 * R0, therefore always zero-extends. However some archs' 19130 * equivalent instruction only does this load when the 19131 * comparison is successful. This detail of CMPXCHG is 19132 * orthogonal to the general zero-extension behaviour of the 19133 * CPU, so it's treated independently of bpf_jit_needs_zext. 19134 */ 19135 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 19136 continue; 19137 19138 /* Zero-extension is done by the caller. */ 19139 if (bpf_pseudo_kfunc_call(&insn)) 19140 continue; 19141 19142 if (WARN_ON(load_reg == -1)) { 19143 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 19144 return -EFAULT; 19145 } 19146 19147 zext_patch[0] = insn; 19148 zext_patch[1].dst_reg = load_reg; 19149 zext_patch[1].src_reg = load_reg; 19150 patch = zext_patch; 19151 patch_len = 2; 19152 apply_patch_buffer: 19153 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 19154 if (!new_prog) 19155 return -ENOMEM; 19156 env->prog = new_prog; 19157 insns = new_prog->insnsi; 19158 aux = env->insn_aux_data; 19159 delta += patch_len - 1; 19160 } 19161 19162 return 0; 19163 } 19164 19165 /* convert load instructions that access fields of a context type into a 19166 * sequence of instructions that access fields of the underlying structure: 19167 * struct __sk_buff -> struct sk_buff 19168 * struct bpf_sock_ops -> struct sock 19169 */ 19170 static int convert_ctx_accesses(struct bpf_verifier_env *env) 19171 { 19172 const struct bpf_verifier_ops *ops = env->ops; 19173 int i, cnt, size, ctx_field_size, delta = 0; 19174 const int insn_cnt = env->prog->len; 19175 struct bpf_insn insn_buf[16], *insn; 19176 u32 target_size, size_default, off; 19177 struct bpf_prog *new_prog; 19178 enum bpf_access_type type; 19179 bool is_narrower_load; 19180 19181 if (ops->gen_prologue || env->seen_direct_write) { 19182 if (!ops->gen_prologue) { 19183 verbose(env, "bpf verifier is misconfigured\n"); 19184 return -EINVAL; 19185 } 19186 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 19187 env->prog); 19188 if (cnt >= ARRAY_SIZE(insn_buf)) { 19189 verbose(env, "bpf verifier is misconfigured\n"); 19190 return -EINVAL; 19191 } else if (cnt) { 19192 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 19193 if (!new_prog) 19194 return -ENOMEM; 19195 19196 env->prog = new_prog; 19197 delta += cnt - 1; 19198 } 19199 } 19200 19201 if (bpf_prog_is_offloaded(env->prog->aux)) 19202 return 0; 19203 19204 insn = env->prog->insnsi + delta; 19205 19206 for (i = 0; i < insn_cnt; i++, insn++) { 19207 bpf_convert_ctx_access_t convert_ctx_access; 19208 u8 mode; 19209 19210 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 19211 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 19212 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 19213 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 19214 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 19215 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 19216 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 19217 type = BPF_READ; 19218 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 19219 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 19220 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 19221 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 19222 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 19223 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 19224 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 19225 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 19226 type = BPF_WRITE; 19227 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 19228 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 19229 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 19230 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 19231 env->prog->aux->num_exentries++; 19232 continue; 19233 } else { 19234 continue; 19235 } 19236 19237 if (type == BPF_WRITE && 19238 env->insn_aux_data[i + delta].sanitize_stack_spill) { 19239 struct bpf_insn patch[] = { 19240 *insn, 19241 BPF_ST_NOSPEC(), 19242 }; 19243 19244 cnt = ARRAY_SIZE(patch); 19245 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 19246 if (!new_prog) 19247 return -ENOMEM; 19248 19249 delta += cnt - 1; 19250 env->prog = new_prog; 19251 insn = new_prog->insnsi + i + delta; 19252 continue; 19253 } 19254 19255 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 19256 case PTR_TO_CTX: 19257 if (!ops->convert_ctx_access) 19258 continue; 19259 convert_ctx_access = ops->convert_ctx_access; 19260 break; 19261 case PTR_TO_SOCKET: 19262 case PTR_TO_SOCK_COMMON: 19263 convert_ctx_access = bpf_sock_convert_ctx_access; 19264 break; 19265 case PTR_TO_TCP_SOCK: 19266 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 19267 break; 19268 case PTR_TO_XDP_SOCK: 19269 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 19270 break; 19271 case PTR_TO_BTF_ID: 19272 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 19273 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 19274 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 19275 * be said once it is marked PTR_UNTRUSTED, hence we must handle 19276 * any faults for loads into such types. BPF_WRITE is disallowed 19277 * for this case. 19278 */ 19279 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19280 if (type == BPF_READ) { 19281 if (BPF_MODE(insn->code) == BPF_MEM) 19282 insn->code = BPF_LDX | BPF_PROBE_MEM | 19283 BPF_SIZE((insn)->code); 19284 else 19285 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19286 BPF_SIZE((insn)->code); 19287 env->prog->aux->num_exentries++; 19288 } 19289 continue; 19290 case PTR_TO_ARENA: 19291 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19292 verbose(env, "sign extending loads from arena are not supported yet\n"); 19293 return -EOPNOTSUPP; 19294 } 19295 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19296 env->prog->aux->num_exentries++; 19297 continue; 19298 default: 19299 continue; 19300 } 19301 19302 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19303 size = BPF_LDST_BYTES(insn); 19304 mode = BPF_MODE(insn->code); 19305 19306 /* If the read access is a narrower load of the field, 19307 * convert to a 4/8-byte load, to minimum program type specific 19308 * convert_ctx_access changes. If conversion is successful, 19309 * we will apply proper mask to the result. 19310 */ 19311 is_narrower_load = size < ctx_field_size; 19312 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19313 off = insn->off; 19314 if (is_narrower_load) { 19315 u8 size_code; 19316 19317 if (type == BPF_WRITE) { 19318 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19319 return -EINVAL; 19320 } 19321 19322 size_code = BPF_H; 19323 if (ctx_field_size == 4) 19324 size_code = BPF_W; 19325 else if (ctx_field_size == 8) 19326 size_code = BPF_DW; 19327 19328 insn->off = off & ~(size_default - 1); 19329 insn->code = BPF_LDX | BPF_MEM | size_code; 19330 } 19331 19332 target_size = 0; 19333 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19334 &target_size); 19335 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 19336 (ctx_field_size && !target_size)) { 19337 verbose(env, "bpf verifier is misconfigured\n"); 19338 return -EINVAL; 19339 } 19340 19341 if (is_narrower_load && size < target_size) { 19342 u8 shift = bpf_ctx_narrow_access_offset( 19343 off, size, size_default) * 8; 19344 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 19345 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19346 return -EINVAL; 19347 } 19348 if (ctx_field_size <= 4) { 19349 if (shift) 19350 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19351 insn->dst_reg, 19352 shift); 19353 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19354 (1 << size * 8) - 1); 19355 } else { 19356 if (shift) 19357 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19358 insn->dst_reg, 19359 shift); 19360 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19361 (1ULL << size * 8) - 1); 19362 } 19363 } 19364 if (mode == BPF_MEMSX) 19365 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19366 insn->dst_reg, insn->dst_reg, 19367 size * 8, 0); 19368 19369 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19370 if (!new_prog) 19371 return -ENOMEM; 19372 19373 delta += cnt - 1; 19374 19375 /* keep walking new program and skip insns we just inserted */ 19376 env->prog = new_prog; 19377 insn = new_prog->insnsi + i + delta; 19378 } 19379 19380 return 0; 19381 } 19382 19383 static int jit_subprogs(struct bpf_verifier_env *env) 19384 { 19385 struct bpf_prog *prog = env->prog, **func, *tmp; 19386 int i, j, subprog_start, subprog_end = 0, len, subprog; 19387 struct bpf_map *map_ptr; 19388 struct bpf_insn *insn; 19389 void *old_bpf_func; 19390 int err, num_exentries; 19391 19392 if (env->subprog_cnt <= 1) 19393 return 0; 19394 19395 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19396 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19397 continue; 19398 19399 /* Upon error here we cannot fall back to interpreter but 19400 * need a hard reject of the program. Thus -EFAULT is 19401 * propagated in any case. 19402 */ 19403 subprog = find_subprog(env, i + insn->imm + 1); 19404 if (subprog < 0) { 19405 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19406 i + insn->imm + 1); 19407 return -EFAULT; 19408 } 19409 /* temporarily remember subprog id inside insn instead of 19410 * aux_data, since next loop will split up all insns into funcs 19411 */ 19412 insn->off = subprog; 19413 /* remember original imm in case JIT fails and fallback 19414 * to interpreter will be needed 19415 */ 19416 env->insn_aux_data[i].call_imm = insn->imm; 19417 /* point imm to __bpf_call_base+1 from JITs point of view */ 19418 insn->imm = 1; 19419 if (bpf_pseudo_func(insn)) { 19420 #if defined(MODULES_VADDR) 19421 u64 addr = MODULES_VADDR; 19422 #else 19423 u64 addr = VMALLOC_START; 19424 #endif 19425 /* jit (e.g. x86_64) may emit fewer instructions 19426 * if it learns a u32 imm is the same as a u64 imm. 19427 * Set close enough to possible prog address. 19428 */ 19429 insn[0].imm = (u32)addr; 19430 insn[1].imm = addr >> 32; 19431 } 19432 } 19433 19434 err = bpf_prog_alloc_jited_linfo(prog); 19435 if (err) 19436 goto out_undo_insn; 19437 19438 err = -ENOMEM; 19439 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 19440 if (!func) 19441 goto out_undo_insn; 19442 19443 for (i = 0; i < env->subprog_cnt; i++) { 19444 subprog_start = subprog_end; 19445 subprog_end = env->subprog_info[i + 1].start; 19446 19447 len = subprog_end - subprog_start; 19448 /* bpf_prog_run() doesn't call subprogs directly, 19449 * hence main prog stats include the runtime of subprogs. 19450 * subprogs don't have IDs and not reachable via prog_get_next_id 19451 * func[i]->stats will never be accessed and stays NULL 19452 */ 19453 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 19454 if (!func[i]) 19455 goto out_free; 19456 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 19457 len * sizeof(struct bpf_insn)); 19458 func[i]->type = prog->type; 19459 func[i]->len = len; 19460 if (bpf_prog_calc_tag(func[i])) 19461 goto out_free; 19462 func[i]->is_func = 1; 19463 func[i]->sleepable = prog->sleepable; 19464 func[i]->aux->func_idx = i; 19465 /* Below members will be freed only at prog->aux */ 19466 func[i]->aux->btf = prog->aux->btf; 19467 func[i]->aux->func_info = prog->aux->func_info; 19468 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 19469 func[i]->aux->poke_tab = prog->aux->poke_tab; 19470 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 19471 19472 for (j = 0; j < prog->aux->size_poke_tab; j++) { 19473 struct bpf_jit_poke_descriptor *poke; 19474 19475 poke = &prog->aux->poke_tab[j]; 19476 if (poke->insn_idx < subprog_end && 19477 poke->insn_idx >= subprog_start) 19478 poke->aux = func[i]->aux; 19479 } 19480 19481 func[i]->aux->name[0] = 'F'; 19482 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 19483 func[i]->jit_requested = 1; 19484 func[i]->blinding_requested = prog->blinding_requested; 19485 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 19486 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 19487 func[i]->aux->linfo = prog->aux->linfo; 19488 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 19489 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 19490 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 19491 func[i]->aux->arena = prog->aux->arena; 19492 num_exentries = 0; 19493 insn = func[i]->insnsi; 19494 for (j = 0; j < func[i]->len; j++, insn++) { 19495 if (BPF_CLASS(insn->code) == BPF_LDX && 19496 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19497 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 19498 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 19499 num_exentries++; 19500 if ((BPF_CLASS(insn->code) == BPF_STX || 19501 BPF_CLASS(insn->code) == BPF_ST) && 19502 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 19503 num_exentries++; 19504 if (BPF_CLASS(insn->code) == BPF_STX && 19505 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 19506 num_exentries++; 19507 } 19508 func[i]->aux->num_exentries = num_exentries; 19509 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 19510 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 19511 if (!i) 19512 func[i]->aux->exception_boundary = env->seen_exception; 19513 func[i] = bpf_int_jit_compile(func[i]); 19514 if (!func[i]->jited) { 19515 err = -ENOTSUPP; 19516 goto out_free; 19517 } 19518 cond_resched(); 19519 } 19520 19521 /* at this point all bpf functions were successfully JITed 19522 * now populate all bpf_calls with correct addresses and 19523 * run last pass of JIT 19524 */ 19525 for (i = 0; i < env->subprog_cnt; i++) { 19526 insn = func[i]->insnsi; 19527 for (j = 0; j < func[i]->len; j++, insn++) { 19528 if (bpf_pseudo_func(insn)) { 19529 subprog = insn->off; 19530 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 19531 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 19532 continue; 19533 } 19534 if (!bpf_pseudo_call(insn)) 19535 continue; 19536 subprog = insn->off; 19537 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 19538 } 19539 19540 /* we use the aux data to keep a list of the start addresses 19541 * of the JITed images for each function in the program 19542 * 19543 * for some architectures, such as powerpc64, the imm field 19544 * might not be large enough to hold the offset of the start 19545 * address of the callee's JITed image from __bpf_call_base 19546 * 19547 * in such cases, we can lookup the start address of a callee 19548 * by using its subprog id, available from the off field of 19549 * the call instruction, as an index for this list 19550 */ 19551 func[i]->aux->func = func; 19552 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19553 func[i]->aux->real_func_cnt = env->subprog_cnt; 19554 } 19555 for (i = 0; i < env->subprog_cnt; i++) { 19556 old_bpf_func = func[i]->bpf_func; 19557 tmp = bpf_int_jit_compile(func[i]); 19558 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 19559 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 19560 err = -ENOTSUPP; 19561 goto out_free; 19562 } 19563 cond_resched(); 19564 } 19565 19566 /* finally lock prog and jit images for all functions and 19567 * populate kallsysm. Begin at the first subprogram, since 19568 * bpf_prog_load will add the kallsyms for the main program. 19569 */ 19570 for (i = 1; i < env->subprog_cnt; i++) { 19571 err = bpf_prog_lock_ro(func[i]); 19572 if (err) 19573 goto out_free; 19574 } 19575 19576 for (i = 1; i < env->subprog_cnt; i++) 19577 bpf_prog_kallsyms_add(func[i]); 19578 19579 /* Last step: make now unused interpreter insns from main 19580 * prog consistent for later dump requests, so they can 19581 * later look the same as if they were interpreted only. 19582 */ 19583 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19584 if (bpf_pseudo_func(insn)) { 19585 insn[0].imm = env->insn_aux_data[i].call_imm; 19586 insn[1].imm = insn->off; 19587 insn->off = 0; 19588 continue; 19589 } 19590 if (!bpf_pseudo_call(insn)) 19591 continue; 19592 insn->off = env->insn_aux_data[i].call_imm; 19593 subprog = find_subprog(env, i + insn->off + 1); 19594 insn->imm = subprog; 19595 } 19596 19597 prog->jited = 1; 19598 prog->bpf_func = func[0]->bpf_func; 19599 prog->jited_len = func[0]->jited_len; 19600 prog->aux->extable = func[0]->aux->extable; 19601 prog->aux->num_exentries = func[0]->aux->num_exentries; 19602 prog->aux->func = func; 19603 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19604 prog->aux->real_func_cnt = env->subprog_cnt; 19605 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19606 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19607 bpf_prog_jit_attempt_done(prog); 19608 return 0; 19609 out_free: 19610 /* We failed JIT'ing, so at this point we need to unregister poke 19611 * descriptors from subprogs, so that kernel is not attempting to 19612 * patch it anymore as we're freeing the subprog JIT memory. 19613 */ 19614 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19615 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19616 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19617 } 19618 /* At this point we're guaranteed that poke descriptors are not 19619 * live anymore. We can just unlink its descriptor table as it's 19620 * released with the main prog. 19621 */ 19622 for (i = 0; i < env->subprog_cnt; i++) { 19623 if (!func[i]) 19624 continue; 19625 func[i]->aux->poke_tab = NULL; 19626 bpf_jit_free(func[i]); 19627 } 19628 kfree(func); 19629 out_undo_insn: 19630 /* cleanup main prog to be interpreted */ 19631 prog->jit_requested = 0; 19632 prog->blinding_requested = 0; 19633 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19634 if (!bpf_pseudo_call(insn)) 19635 continue; 19636 insn->off = 0; 19637 insn->imm = env->insn_aux_data[i].call_imm; 19638 } 19639 bpf_prog_jit_attempt_done(prog); 19640 return err; 19641 } 19642 19643 static int fixup_call_args(struct bpf_verifier_env *env) 19644 { 19645 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19646 struct bpf_prog *prog = env->prog; 19647 struct bpf_insn *insn = prog->insnsi; 19648 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19649 int i, depth; 19650 #endif 19651 int err = 0; 19652 19653 if (env->prog->jit_requested && 19654 !bpf_prog_is_offloaded(env->prog->aux)) { 19655 err = jit_subprogs(env); 19656 if (err == 0) 19657 return 0; 19658 if (err == -EFAULT) 19659 return err; 19660 } 19661 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19662 if (has_kfunc_call) { 19663 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19664 return -EINVAL; 19665 } 19666 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19667 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19668 * have to be rejected, since interpreter doesn't support them yet. 19669 */ 19670 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19671 return -EINVAL; 19672 } 19673 for (i = 0; i < prog->len; i++, insn++) { 19674 if (bpf_pseudo_func(insn)) { 19675 /* When JIT fails the progs with callback calls 19676 * have to be rejected, since interpreter doesn't support them yet. 19677 */ 19678 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19679 return -EINVAL; 19680 } 19681 19682 if (!bpf_pseudo_call(insn)) 19683 continue; 19684 depth = get_callee_stack_depth(env, insn, i); 19685 if (depth < 0) 19686 return depth; 19687 bpf_patch_call_args(insn, depth); 19688 } 19689 err = 0; 19690 #endif 19691 return err; 19692 } 19693 19694 /* replace a generic kfunc with a specialized version if necessary */ 19695 static void specialize_kfunc(struct bpf_verifier_env *env, 19696 u32 func_id, u16 offset, unsigned long *addr) 19697 { 19698 struct bpf_prog *prog = env->prog; 19699 bool seen_direct_write; 19700 void *xdp_kfunc; 19701 bool is_rdonly; 19702 19703 if (bpf_dev_bound_kfunc_id(func_id)) { 19704 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19705 if (xdp_kfunc) { 19706 *addr = (unsigned long)xdp_kfunc; 19707 return; 19708 } 19709 /* fallback to default kfunc when not supported by netdev */ 19710 } 19711 19712 if (offset) 19713 return; 19714 19715 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19716 seen_direct_write = env->seen_direct_write; 19717 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19718 19719 if (is_rdonly) 19720 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19721 19722 /* restore env->seen_direct_write to its original value, since 19723 * may_access_direct_pkt_data mutates it 19724 */ 19725 env->seen_direct_write = seen_direct_write; 19726 } 19727 } 19728 19729 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19730 u16 struct_meta_reg, 19731 u16 node_offset_reg, 19732 struct bpf_insn *insn, 19733 struct bpf_insn *insn_buf, 19734 int *cnt) 19735 { 19736 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19737 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19738 19739 insn_buf[0] = addr[0]; 19740 insn_buf[1] = addr[1]; 19741 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19742 insn_buf[3] = *insn; 19743 *cnt = 4; 19744 } 19745 19746 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19747 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19748 { 19749 const struct bpf_kfunc_desc *desc; 19750 19751 if (!insn->imm) { 19752 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19753 return -EINVAL; 19754 } 19755 19756 *cnt = 0; 19757 19758 /* insn->imm has the btf func_id. Replace it with an offset relative to 19759 * __bpf_call_base, unless the JIT needs to call functions that are 19760 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19761 */ 19762 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19763 if (!desc) { 19764 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19765 insn->imm); 19766 return -EFAULT; 19767 } 19768 19769 if (!bpf_jit_supports_far_kfunc_call()) 19770 insn->imm = BPF_CALL_IMM(desc->addr); 19771 if (insn->off) 19772 return 0; 19773 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19774 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19775 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19776 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19777 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19778 19779 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19780 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19781 insn_idx); 19782 return -EFAULT; 19783 } 19784 19785 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19786 insn_buf[1] = addr[0]; 19787 insn_buf[2] = addr[1]; 19788 insn_buf[3] = *insn; 19789 *cnt = 4; 19790 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19791 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19792 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19793 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19794 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19795 19796 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19797 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19798 insn_idx); 19799 return -EFAULT; 19800 } 19801 19802 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19803 !kptr_struct_meta) { 19804 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19805 insn_idx); 19806 return -EFAULT; 19807 } 19808 19809 insn_buf[0] = addr[0]; 19810 insn_buf[1] = addr[1]; 19811 insn_buf[2] = *insn; 19812 *cnt = 3; 19813 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19814 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19815 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19816 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19817 int struct_meta_reg = BPF_REG_3; 19818 int node_offset_reg = BPF_REG_4; 19819 19820 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19821 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19822 struct_meta_reg = BPF_REG_4; 19823 node_offset_reg = BPF_REG_5; 19824 } 19825 19826 if (!kptr_struct_meta) { 19827 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19828 insn_idx); 19829 return -EFAULT; 19830 } 19831 19832 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19833 node_offset_reg, insn, insn_buf, cnt); 19834 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19835 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19836 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19837 *cnt = 1; 19838 } else if (is_bpf_wq_set_callback_impl_kfunc(desc->func_id)) { 19839 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(BPF_REG_4, (long)env->prog->aux) }; 19840 19841 insn_buf[0] = ld_addrs[0]; 19842 insn_buf[1] = ld_addrs[1]; 19843 insn_buf[2] = *insn; 19844 *cnt = 3; 19845 } 19846 return 0; 19847 } 19848 19849 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19850 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19851 { 19852 struct bpf_subprog_info *info = env->subprog_info; 19853 int cnt = env->subprog_cnt; 19854 struct bpf_prog *prog; 19855 19856 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19857 if (env->hidden_subprog_cnt) { 19858 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19859 return -EFAULT; 19860 } 19861 /* We're not patching any existing instruction, just appending the new 19862 * ones for the hidden subprog. Hence all of the adjustment operations 19863 * in bpf_patch_insn_data are no-ops. 19864 */ 19865 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19866 if (!prog) 19867 return -ENOMEM; 19868 env->prog = prog; 19869 info[cnt + 1].start = info[cnt].start; 19870 info[cnt].start = prog->len - len + 1; 19871 env->subprog_cnt++; 19872 env->hidden_subprog_cnt++; 19873 return 0; 19874 } 19875 19876 /* Do various post-verification rewrites in a single program pass. 19877 * These rewrites simplify JIT and interpreter implementations. 19878 */ 19879 static int do_misc_fixups(struct bpf_verifier_env *env) 19880 { 19881 struct bpf_prog *prog = env->prog; 19882 enum bpf_attach_type eatype = prog->expected_attach_type; 19883 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19884 struct bpf_insn *insn = prog->insnsi; 19885 const struct bpf_func_proto *fn; 19886 const int insn_cnt = prog->len; 19887 const struct bpf_map_ops *ops; 19888 struct bpf_insn_aux_data *aux; 19889 struct bpf_insn insn_buf[16]; 19890 struct bpf_prog *new_prog; 19891 struct bpf_map *map_ptr; 19892 int i, ret, cnt, delta = 0, cur_subprog = 0; 19893 struct bpf_subprog_info *subprogs = env->subprog_info; 19894 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19895 u16 stack_depth_extra = 0; 19896 19897 if (env->seen_exception && !env->exception_callback_subprog) { 19898 struct bpf_insn patch[] = { 19899 env->prog->insnsi[insn_cnt - 1], 19900 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19901 BPF_EXIT_INSN(), 19902 }; 19903 19904 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19905 if (ret < 0) 19906 return ret; 19907 prog = env->prog; 19908 insn = prog->insnsi; 19909 19910 env->exception_callback_subprog = env->subprog_cnt - 1; 19911 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19912 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19913 } 19914 19915 for (i = 0; i < insn_cnt;) { 19916 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 19917 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 19918 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 19919 /* convert to 32-bit mov that clears upper 32-bit */ 19920 insn->code = BPF_ALU | BPF_MOV | BPF_X; 19921 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 19922 insn->off = 0; 19923 insn->imm = 0; 19924 } /* cast from as(0) to as(1) should be handled by JIT */ 19925 goto next_insn; 19926 } 19927 19928 if (env->insn_aux_data[i + delta].needs_zext) 19929 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 19930 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 19931 19932 /* Make divide-by-zero exceptions impossible. */ 19933 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19934 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19935 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19936 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19937 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19938 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19939 struct bpf_insn *patchlet; 19940 struct bpf_insn chk_and_div[] = { 19941 /* [R,W]x div 0 -> 0 */ 19942 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19943 BPF_JNE | BPF_K, insn->src_reg, 19944 0, 2, 0), 19945 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19946 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19947 *insn, 19948 }; 19949 struct bpf_insn chk_and_mod[] = { 19950 /* [R,W]x mod 0 -> [R,W]x */ 19951 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19952 BPF_JEQ | BPF_K, insn->src_reg, 19953 0, 1 + (is64 ? 0 : 1), 0), 19954 *insn, 19955 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19956 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19957 }; 19958 19959 patchlet = isdiv ? chk_and_div : chk_and_mod; 19960 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19961 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19962 19963 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19964 if (!new_prog) 19965 return -ENOMEM; 19966 19967 delta += cnt - 1; 19968 env->prog = prog = new_prog; 19969 insn = new_prog->insnsi + i + delta; 19970 goto next_insn; 19971 } 19972 19973 /* Make it impossible to de-reference a userspace address */ 19974 if (BPF_CLASS(insn->code) == BPF_LDX && 19975 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19976 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 19977 struct bpf_insn *patch = &insn_buf[0]; 19978 u64 uaddress_limit = bpf_arch_uaddress_limit(); 19979 19980 if (!uaddress_limit) 19981 goto next_insn; 19982 19983 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 19984 if (insn->off) 19985 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 19986 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 19987 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 19988 *patch++ = *insn; 19989 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 19990 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 19991 19992 cnt = patch - insn_buf; 19993 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19994 if (!new_prog) 19995 return -ENOMEM; 19996 19997 delta += cnt - 1; 19998 env->prog = prog = new_prog; 19999 insn = new_prog->insnsi + i + delta; 20000 goto next_insn; 20001 } 20002 20003 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 20004 if (BPF_CLASS(insn->code) == BPF_LD && 20005 (BPF_MODE(insn->code) == BPF_ABS || 20006 BPF_MODE(insn->code) == BPF_IND)) { 20007 cnt = env->ops->gen_ld_abs(insn, insn_buf); 20008 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 20009 verbose(env, "bpf verifier is misconfigured\n"); 20010 return -EINVAL; 20011 } 20012 20013 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20014 if (!new_prog) 20015 return -ENOMEM; 20016 20017 delta += cnt - 1; 20018 env->prog = prog = new_prog; 20019 insn = new_prog->insnsi + i + delta; 20020 goto next_insn; 20021 } 20022 20023 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 20024 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 20025 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 20026 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 20027 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 20028 struct bpf_insn *patch = &insn_buf[0]; 20029 bool issrc, isneg, isimm; 20030 u32 off_reg; 20031 20032 aux = &env->insn_aux_data[i + delta]; 20033 if (!aux->alu_state || 20034 aux->alu_state == BPF_ALU_NON_POINTER) 20035 goto next_insn; 20036 20037 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 20038 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 20039 BPF_ALU_SANITIZE_SRC; 20040 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 20041 20042 off_reg = issrc ? insn->src_reg : insn->dst_reg; 20043 if (isimm) { 20044 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20045 } else { 20046 if (isneg) 20047 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20048 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 20049 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 20050 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 20051 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 20052 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 20053 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 20054 } 20055 if (!issrc) 20056 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 20057 insn->src_reg = BPF_REG_AX; 20058 if (isneg) 20059 insn->code = insn->code == code_add ? 20060 code_sub : code_add; 20061 *patch++ = *insn; 20062 if (issrc && isneg && !isimm) 20063 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 20064 cnt = patch - insn_buf; 20065 20066 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20067 if (!new_prog) 20068 return -ENOMEM; 20069 20070 delta += cnt - 1; 20071 env->prog = prog = new_prog; 20072 insn = new_prog->insnsi + i + delta; 20073 goto next_insn; 20074 } 20075 20076 if (is_may_goto_insn(insn)) { 20077 int stack_off = -stack_depth - 8; 20078 20079 stack_depth_extra = 8; 20080 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 20081 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 20082 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 20083 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 20084 cnt = 4; 20085 20086 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20087 if (!new_prog) 20088 return -ENOMEM; 20089 20090 delta += cnt - 1; 20091 env->prog = prog = new_prog; 20092 insn = new_prog->insnsi + i + delta; 20093 goto next_insn; 20094 } 20095 20096 if (insn->code != (BPF_JMP | BPF_CALL)) 20097 goto next_insn; 20098 if (insn->src_reg == BPF_PSEUDO_CALL) 20099 goto next_insn; 20100 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 20101 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 20102 if (ret) 20103 return ret; 20104 if (cnt == 0) 20105 goto next_insn; 20106 20107 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20108 if (!new_prog) 20109 return -ENOMEM; 20110 20111 delta += cnt - 1; 20112 env->prog = prog = new_prog; 20113 insn = new_prog->insnsi + i + delta; 20114 goto next_insn; 20115 } 20116 20117 /* Skip inlining the helper call if the JIT does it. */ 20118 if (bpf_jit_inlines_helper_call(insn->imm)) 20119 goto next_insn; 20120 20121 if (insn->imm == BPF_FUNC_get_route_realm) 20122 prog->dst_needed = 1; 20123 if (insn->imm == BPF_FUNC_get_prandom_u32) 20124 bpf_user_rnd_init_once(); 20125 if (insn->imm == BPF_FUNC_override_return) 20126 prog->kprobe_override = 1; 20127 if (insn->imm == BPF_FUNC_tail_call) { 20128 /* If we tail call into other programs, we 20129 * cannot make any assumptions since they can 20130 * be replaced dynamically during runtime in 20131 * the program array. 20132 */ 20133 prog->cb_access = 1; 20134 if (!allow_tail_call_in_subprogs(env)) 20135 prog->aux->stack_depth = MAX_BPF_STACK; 20136 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 20137 20138 /* mark bpf_tail_call as different opcode to avoid 20139 * conditional branch in the interpreter for every normal 20140 * call and to prevent accidental JITing by JIT compiler 20141 * that doesn't support bpf_tail_call yet 20142 */ 20143 insn->imm = 0; 20144 insn->code = BPF_JMP | BPF_TAIL_CALL; 20145 20146 aux = &env->insn_aux_data[i + delta]; 20147 if (env->bpf_capable && !prog->blinding_requested && 20148 prog->jit_requested && 20149 !bpf_map_key_poisoned(aux) && 20150 !bpf_map_ptr_poisoned(aux) && 20151 !bpf_map_ptr_unpriv(aux)) { 20152 struct bpf_jit_poke_descriptor desc = { 20153 .reason = BPF_POKE_REASON_TAIL_CALL, 20154 .tail_call.map = aux->map_ptr_state.map_ptr, 20155 .tail_call.key = bpf_map_key_immediate(aux), 20156 .insn_idx = i + delta, 20157 }; 20158 20159 ret = bpf_jit_add_poke_descriptor(prog, &desc); 20160 if (ret < 0) { 20161 verbose(env, "adding tail call poke descriptor failed\n"); 20162 return ret; 20163 } 20164 20165 insn->imm = ret + 1; 20166 goto next_insn; 20167 } 20168 20169 if (!bpf_map_ptr_unpriv(aux)) 20170 goto next_insn; 20171 20172 /* instead of changing every JIT dealing with tail_call 20173 * emit two extra insns: 20174 * if (index >= max_entries) goto out; 20175 * index &= array->index_mask; 20176 * to avoid out-of-bounds cpu speculation 20177 */ 20178 if (bpf_map_ptr_poisoned(aux)) { 20179 verbose(env, "tail_call abusing map_ptr\n"); 20180 return -EINVAL; 20181 } 20182 20183 map_ptr = aux->map_ptr_state.map_ptr; 20184 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 20185 map_ptr->max_entries, 2); 20186 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 20187 container_of(map_ptr, 20188 struct bpf_array, 20189 map)->index_mask); 20190 insn_buf[2] = *insn; 20191 cnt = 3; 20192 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20193 if (!new_prog) 20194 return -ENOMEM; 20195 20196 delta += cnt - 1; 20197 env->prog = prog = new_prog; 20198 insn = new_prog->insnsi + i + delta; 20199 goto next_insn; 20200 } 20201 20202 if (insn->imm == BPF_FUNC_timer_set_callback) { 20203 /* The verifier will process callback_fn as many times as necessary 20204 * with different maps and the register states prepared by 20205 * set_timer_callback_state will be accurate. 20206 * 20207 * The following use case is valid: 20208 * map1 is shared by prog1, prog2, prog3. 20209 * prog1 calls bpf_timer_init for some map1 elements 20210 * prog2 calls bpf_timer_set_callback for some map1 elements. 20211 * Those that were not bpf_timer_init-ed will return -EINVAL. 20212 * prog3 calls bpf_timer_start for some map1 elements. 20213 * Those that were not both bpf_timer_init-ed and 20214 * bpf_timer_set_callback-ed will return -EINVAL. 20215 */ 20216 struct bpf_insn ld_addrs[2] = { 20217 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 20218 }; 20219 20220 insn_buf[0] = ld_addrs[0]; 20221 insn_buf[1] = ld_addrs[1]; 20222 insn_buf[2] = *insn; 20223 cnt = 3; 20224 20225 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20226 if (!new_prog) 20227 return -ENOMEM; 20228 20229 delta += cnt - 1; 20230 env->prog = prog = new_prog; 20231 insn = new_prog->insnsi + i + delta; 20232 goto patch_call_imm; 20233 } 20234 20235 if (is_storage_get_function(insn->imm)) { 20236 if (!in_sleepable(env) || 20237 env->insn_aux_data[i + delta].storage_get_func_atomic) 20238 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 20239 else 20240 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 20241 insn_buf[1] = *insn; 20242 cnt = 2; 20243 20244 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20245 if (!new_prog) 20246 return -ENOMEM; 20247 20248 delta += cnt - 1; 20249 env->prog = prog = new_prog; 20250 insn = new_prog->insnsi + i + delta; 20251 goto patch_call_imm; 20252 } 20253 20254 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 20255 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 20256 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 20257 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 20258 */ 20259 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 20260 insn_buf[1] = *insn; 20261 cnt = 2; 20262 20263 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20264 if (!new_prog) 20265 return -ENOMEM; 20266 20267 delta += cnt - 1; 20268 env->prog = prog = new_prog; 20269 insn = new_prog->insnsi + i + delta; 20270 goto patch_call_imm; 20271 } 20272 20273 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 20274 * and other inlining handlers are currently limited to 64 bit 20275 * only. 20276 */ 20277 if (prog->jit_requested && BITS_PER_LONG == 64 && 20278 (insn->imm == BPF_FUNC_map_lookup_elem || 20279 insn->imm == BPF_FUNC_map_update_elem || 20280 insn->imm == BPF_FUNC_map_delete_elem || 20281 insn->imm == BPF_FUNC_map_push_elem || 20282 insn->imm == BPF_FUNC_map_pop_elem || 20283 insn->imm == BPF_FUNC_map_peek_elem || 20284 insn->imm == BPF_FUNC_redirect_map || 20285 insn->imm == BPF_FUNC_for_each_map_elem || 20286 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 20287 aux = &env->insn_aux_data[i + delta]; 20288 if (bpf_map_ptr_poisoned(aux)) 20289 goto patch_call_imm; 20290 20291 map_ptr = aux->map_ptr_state.map_ptr; 20292 ops = map_ptr->ops; 20293 if (insn->imm == BPF_FUNC_map_lookup_elem && 20294 ops->map_gen_lookup) { 20295 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 20296 if (cnt == -EOPNOTSUPP) 20297 goto patch_map_ops_generic; 20298 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 20299 verbose(env, "bpf verifier is misconfigured\n"); 20300 return -EINVAL; 20301 } 20302 20303 new_prog = bpf_patch_insn_data(env, i + delta, 20304 insn_buf, cnt); 20305 if (!new_prog) 20306 return -ENOMEM; 20307 20308 delta += cnt - 1; 20309 env->prog = prog = new_prog; 20310 insn = new_prog->insnsi + i + delta; 20311 goto next_insn; 20312 } 20313 20314 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 20315 (void *(*)(struct bpf_map *map, void *key))NULL)); 20316 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 20317 (long (*)(struct bpf_map *map, void *key))NULL)); 20318 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 20319 (long (*)(struct bpf_map *map, void *key, void *value, 20320 u64 flags))NULL)); 20321 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 20322 (long (*)(struct bpf_map *map, void *value, 20323 u64 flags))NULL)); 20324 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 20325 (long (*)(struct bpf_map *map, void *value))NULL)); 20326 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 20327 (long (*)(struct bpf_map *map, void *value))NULL)); 20328 BUILD_BUG_ON(!__same_type(ops->map_redirect, 20329 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 20330 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 20331 (long (*)(struct bpf_map *map, 20332 bpf_callback_t callback_fn, 20333 void *callback_ctx, 20334 u64 flags))NULL)); 20335 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20336 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20337 20338 patch_map_ops_generic: 20339 switch (insn->imm) { 20340 case BPF_FUNC_map_lookup_elem: 20341 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20342 goto next_insn; 20343 case BPF_FUNC_map_update_elem: 20344 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20345 goto next_insn; 20346 case BPF_FUNC_map_delete_elem: 20347 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20348 goto next_insn; 20349 case BPF_FUNC_map_push_elem: 20350 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 20351 goto next_insn; 20352 case BPF_FUNC_map_pop_elem: 20353 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 20354 goto next_insn; 20355 case BPF_FUNC_map_peek_elem: 20356 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 20357 goto next_insn; 20358 case BPF_FUNC_redirect_map: 20359 insn->imm = BPF_CALL_IMM(ops->map_redirect); 20360 goto next_insn; 20361 case BPF_FUNC_for_each_map_elem: 20362 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 20363 goto next_insn; 20364 case BPF_FUNC_map_lookup_percpu_elem: 20365 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 20366 goto next_insn; 20367 } 20368 20369 goto patch_call_imm; 20370 } 20371 20372 /* Implement bpf_jiffies64 inline. */ 20373 if (prog->jit_requested && BITS_PER_LONG == 64 && 20374 insn->imm == BPF_FUNC_jiffies64) { 20375 struct bpf_insn ld_jiffies_addr[2] = { 20376 BPF_LD_IMM64(BPF_REG_0, 20377 (unsigned long)&jiffies), 20378 }; 20379 20380 insn_buf[0] = ld_jiffies_addr[0]; 20381 insn_buf[1] = ld_jiffies_addr[1]; 20382 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 20383 BPF_REG_0, 0); 20384 cnt = 3; 20385 20386 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 20387 cnt); 20388 if (!new_prog) 20389 return -ENOMEM; 20390 20391 delta += cnt - 1; 20392 env->prog = prog = new_prog; 20393 insn = new_prog->insnsi + i + delta; 20394 goto next_insn; 20395 } 20396 20397 #ifdef CONFIG_X86_64 20398 /* Implement bpf_get_smp_processor_id() inline. */ 20399 if (insn->imm == BPF_FUNC_get_smp_processor_id && 20400 prog->jit_requested && bpf_jit_supports_percpu_insn()) { 20401 /* BPF_FUNC_get_smp_processor_id inlining is an 20402 * optimization, so if pcpu_hot.cpu_number is ever 20403 * changed in some incompatible and hard to support 20404 * way, it's fine to back out this inlining logic 20405 */ 20406 insn_buf[0] = BPF_MOV32_IMM(BPF_REG_0, (u32)(unsigned long)&pcpu_hot.cpu_number); 20407 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 20408 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 20409 cnt = 3; 20410 20411 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20412 if (!new_prog) 20413 return -ENOMEM; 20414 20415 delta += cnt - 1; 20416 env->prog = prog = new_prog; 20417 insn = new_prog->insnsi + i + delta; 20418 goto next_insn; 20419 } 20420 #endif 20421 /* Implement bpf_get_func_arg inline. */ 20422 if (prog_type == BPF_PROG_TYPE_TRACING && 20423 insn->imm == BPF_FUNC_get_func_arg) { 20424 /* Load nr_args from ctx - 8 */ 20425 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20426 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 20427 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 20428 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 20429 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 20430 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20431 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 20432 insn_buf[7] = BPF_JMP_A(1); 20433 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20434 cnt = 9; 20435 20436 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20437 if (!new_prog) 20438 return -ENOMEM; 20439 20440 delta += cnt - 1; 20441 env->prog = prog = new_prog; 20442 insn = new_prog->insnsi + i + delta; 20443 goto next_insn; 20444 } 20445 20446 /* Implement bpf_get_func_ret inline. */ 20447 if (prog_type == BPF_PROG_TYPE_TRACING && 20448 insn->imm == BPF_FUNC_get_func_ret) { 20449 if (eatype == BPF_TRACE_FEXIT || 20450 eatype == BPF_MODIFY_RETURN) { 20451 /* Load nr_args from ctx - 8 */ 20452 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20453 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 20454 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 20455 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20456 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 20457 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 20458 cnt = 6; 20459 } else { 20460 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 20461 cnt = 1; 20462 } 20463 20464 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20465 if (!new_prog) 20466 return -ENOMEM; 20467 20468 delta += cnt - 1; 20469 env->prog = prog = new_prog; 20470 insn = new_prog->insnsi + i + delta; 20471 goto next_insn; 20472 } 20473 20474 /* Implement get_func_arg_cnt inline. */ 20475 if (prog_type == BPF_PROG_TYPE_TRACING && 20476 insn->imm == BPF_FUNC_get_func_arg_cnt) { 20477 /* Load nr_args from ctx - 8 */ 20478 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20479 20480 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20481 if (!new_prog) 20482 return -ENOMEM; 20483 20484 env->prog = prog = new_prog; 20485 insn = new_prog->insnsi + i + delta; 20486 goto next_insn; 20487 } 20488 20489 /* Implement bpf_get_func_ip inline. */ 20490 if (prog_type == BPF_PROG_TYPE_TRACING && 20491 insn->imm == BPF_FUNC_get_func_ip) { 20492 /* Load IP address from ctx - 16 */ 20493 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 20494 20495 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20496 if (!new_prog) 20497 return -ENOMEM; 20498 20499 env->prog = prog = new_prog; 20500 insn = new_prog->insnsi + i + delta; 20501 goto next_insn; 20502 } 20503 20504 /* Implement bpf_get_branch_snapshot inline. */ 20505 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 20506 prog->jit_requested && BITS_PER_LONG == 64 && 20507 insn->imm == BPF_FUNC_get_branch_snapshot) { 20508 /* We are dealing with the following func protos: 20509 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 20510 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 20511 */ 20512 const u32 br_entry_size = sizeof(struct perf_branch_entry); 20513 20514 /* struct perf_branch_entry is part of UAPI and is 20515 * used as an array element, so extremely unlikely to 20516 * ever grow or shrink 20517 */ 20518 BUILD_BUG_ON(br_entry_size != 24); 20519 20520 /* if (unlikely(flags)) return -EINVAL */ 20521 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 20522 20523 /* Transform size (bytes) into number of entries (cnt = size / 24). 20524 * But to avoid expensive division instruction, we implement 20525 * divide-by-3 through multiplication, followed by further 20526 * division by 8 through 3-bit right shift. 20527 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 20528 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 20529 * 20530 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 20531 */ 20532 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 20533 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 20534 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 20535 20536 /* call perf_snapshot_branch_stack implementation */ 20537 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 20538 /* if (entry_cnt == 0) return -ENOENT */ 20539 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 20540 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 20541 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 20542 insn_buf[7] = BPF_JMP_A(3); 20543 /* return -EINVAL; */ 20544 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20545 insn_buf[9] = BPF_JMP_A(1); 20546 /* return -ENOENT; */ 20547 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 20548 cnt = 11; 20549 20550 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20551 if (!new_prog) 20552 return -ENOMEM; 20553 20554 delta += cnt - 1; 20555 env->prog = prog = new_prog; 20556 insn = new_prog->insnsi + i + delta; 20557 continue; 20558 } 20559 20560 /* Implement bpf_kptr_xchg inline */ 20561 if (prog->jit_requested && BITS_PER_LONG == 64 && 20562 insn->imm == BPF_FUNC_kptr_xchg && 20563 bpf_jit_supports_ptr_xchg()) { 20564 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 20565 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 20566 cnt = 2; 20567 20568 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20569 if (!new_prog) 20570 return -ENOMEM; 20571 20572 delta += cnt - 1; 20573 env->prog = prog = new_prog; 20574 insn = new_prog->insnsi + i + delta; 20575 goto next_insn; 20576 } 20577 patch_call_imm: 20578 fn = env->ops->get_func_proto(insn->imm, env->prog); 20579 /* all functions that have prototype and verifier allowed 20580 * programs to call them, must be real in-kernel functions 20581 */ 20582 if (!fn->func) { 20583 verbose(env, 20584 "kernel subsystem misconfigured func %s#%d\n", 20585 func_id_name(insn->imm), insn->imm); 20586 return -EFAULT; 20587 } 20588 insn->imm = fn->func - __bpf_call_base; 20589 next_insn: 20590 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20591 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20592 subprogs[cur_subprog].stack_extra = stack_depth_extra; 20593 cur_subprog++; 20594 stack_depth = subprogs[cur_subprog].stack_depth; 20595 stack_depth_extra = 0; 20596 } 20597 i++; 20598 insn++; 20599 } 20600 20601 env->prog->aux->stack_depth = subprogs[0].stack_depth; 20602 for (i = 0; i < env->subprog_cnt; i++) { 20603 int subprog_start = subprogs[i].start; 20604 int stack_slots = subprogs[i].stack_extra / 8; 20605 20606 if (!stack_slots) 20607 continue; 20608 if (stack_slots > 1) { 20609 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 20610 return -EFAULT; 20611 } 20612 20613 /* Add ST insn to subprog prologue to init extra stack */ 20614 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 20615 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 20616 /* Copy first actual insn to preserve it */ 20617 insn_buf[1] = env->prog->insnsi[subprog_start]; 20618 20619 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 20620 if (!new_prog) 20621 return -ENOMEM; 20622 env->prog = prog = new_prog; 20623 } 20624 20625 /* Since poke tab is now finalized, publish aux to tracker. */ 20626 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20627 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20628 if (!map_ptr->ops->map_poke_track || 20629 !map_ptr->ops->map_poke_untrack || 20630 !map_ptr->ops->map_poke_run) { 20631 verbose(env, "bpf verifier is misconfigured\n"); 20632 return -EINVAL; 20633 } 20634 20635 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 20636 if (ret < 0) { 20637 verbose(env, "tracking tail call prog failed\n"); 20638 return ret; 20639 } 20640 } 20641 20642 sort_kfunc_descs_by_imm_off(env->prog); 20643 20644 return 0; 20645 } 20646 20647 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 20648 int position, 20649 s32 stack_base, 20650 u32 callback_subprogno, 20651 u32 *cnt) 20652 { 20653 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 20654 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 20655 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 20656 int reg_loop_max = BPF_REG_6; 20657 int reg_loop_cnt = BPF_REG_7; 20658 int reg_loop_ctx = BPF_REG_8; 20659 20660 struct bpf_prog *new_prog; 20661 u32 callback_start; 20662 u32 call_insn_offset; 20663 s32 callback_offset; 20664 20665 /* This represents an inlined version of bpf_iter.c:bpf_loop, 20666 * be careful to modify this code in sync. 20667 */ 20668 struct bpf_insn insn_buf[] = { 20669 /* Return error and jump to the end of the patch if 20670 * expected number of iterations is too big. 20671 */ 20672 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 20673 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 20674 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 20675 /* spill R6, R7, R8 to use these as loop vars */ 20676 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 20677 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 20678 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 20679 /* initialize loop vars */ 20680 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 20681 BPF_MOV32_IMM(reg_loop_cnt, 0), 20682 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 20683 /* loop header, 20684 * if reg_loop_cnt >= reg_loop_max skip the loop body 20685 */ 20686 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 20687 /* callback call, 20688 * correct callback offset would be set after patching 20689 */ 20690 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 20691 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 20692 BPF_CALL_REL(0), 20693 /* increment loop counter */ 20694 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 20695 /* jump to loop header if callback returned 0 */ 20696 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 20697 /* return value of bpf_loop, 20698 * set R0 to the number of iterations 20699 */ 20700 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 20701 /* restore original values of R6, R7, R8 */ 20702 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 20703 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 20704 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 20705 }; 20706 20707 *cnt = ARRAY_SIZE(insn_buf); 20708 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 20709 if (!new_prog) 20710 return new_prog; 20711 20712 /* callback start is known only after patching */ 20713 callback_start = env->subprog_info[callback_subprogno].start; 20714 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 20715 call_insn_offset = position + 12; 20716 callback_offset = callback_start - call_insn_offset - 1; 20717 new_prog->insnsi[call_insn_offset].imm = callback_offset; 20718 20719 return new_prog; 20720 } 20721 20722 static bool is_bpf_loop_call(struct bpf_insn *insn) 20723 { 20724 return insn->code == (BPF_JMP | BPF_CALL) && 20725 insn->src_reg == 0 && 20726 insn->imm == BPF_FUNC_loop; 20727 } 20728 20729 /* For all sub-programs in the program (including main) check 20730 * insn_aux_data to see if there are bpf_loop calls that require 20731 * inlining. If such calls are found the calls are replaced with a 20732 * sequence of instructions produced by `inline_bpf_loop` function and 20733 * subprog stack_depth is increased by the size of 3 registers. 20734 * This stack space is used to spill values of the R6, R7, R8. These 20735 * registers are used to store the loop bound, counter and context 20736 * variables. 20737 */ 20738 static int optimize_bpf_loop(struct bpf_verifier_env *env) 20739 { 20740 struct bpf_subprog_info *subprogs = env->subprog_info; 20741 int i, cur_subprog = 0, cnt, delta = 0; 20742 struct bpf_insn *insn = env->prog->insnsi; 20743 int insn_cnt = env->prog->len; 20744 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20745 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20746 u16 stack_depth_extra = 0; 20747 20748 for (i = 0; i < insn_cnt; i++, insn++) { 20749 struct bpf_loop_inline_state *inline_state = 20750 &env->insn_aux_data[i + delta].loop_inline_state; 20751 20752 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 20753 struct bpf_prog *new_prog; 20754 20755 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 20756 new_prog = inline_bpf_loop(env, 20757 i + delta, 20758 -(stack_depth + stack_depth_extra), 20759 inline_state->callback_subprogno, 20760 &cnt); 20761 if (!new_prog) 20762 return -ENOMEM; 20763 20764 delta += cnt - 1; 20765 env->prog = new_prog; 20766 insn = new_prog->insnsi + i + delta; 20767 } 20768 20769 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20770 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20771 cur_subprog++; 20772 stack_depth = subprogs[cur_subprog].stack_depth; 20773 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20774 stack_depth_extra = 0; 20775 } 20776 } 20777 20778 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20779 20780 return 0; 20781 } 20782 20783 static void free_states(struct bpf_verifier_env *env) 20784 { 20785 struct bpf_verifier_state_list *sl, *sln; 20786 int i; 20787 20788 sl = env->free_list; 20789 while (sl) { 20790 sln = sl->next; 20791 free_verifier_state(&sl->state, false); 20792 kfree(sl); 20793 sl = sln; 20794 } 20795 env->free_list = NULL; 20796 20797 if (!env->explored_states) 20798 return; 20799 20800 for (i = 0; i < state_htab_size(env); i++) { 20801 sl = env->explored_states[i]; 20802 20803 while (sl) { 20804 sln = sl->next; 20805 free_verifier_state(&sl->state, false); 20806 kfree(sl); 20807 sl = sln; 20808 } 20809 env->explored_states[i] = NULL; 20810 } 20811 } 20812 20813 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20814 { 20815 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20816 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20817 struct bpf_verifier_state *state; 20818 struct bpf_reg_state *regs; 20819 int ret, i; 20820 20821 env->prev_linfo = NULL; 20822 env->pass_cnt++; 20823 20824 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20825 if (!state) 20826 return -ENOMEM; 20827 state->curframe = 0; 20828 state->speculative = false; 20829 state->branches = 1; 20830 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20831 if (!state->frame[0]) { 20832 kfree(state); 20833 return -ENOMEM; 20834 } 20835 env->cur_state = state; 20836 init_func_state(env, state->frame[0], 20837 BPF_MAIN_FUNC /* callsite */, 20838 0 /* frameno */, 20839 subprog); 20840 state->first_insn_idx = env->subprog_info[subprog].start; 20841 state->last_insn_idx = -1; 20842 20843 regs = state->frame[state->curframe]->regs; 20844 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20845 const char *sub_name = subprog_name(env, subprog); 20846 struct bpf_subprog_arg_info *arg; 20847 struct bpf_reg_state *reg; 20848 20849 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20850 ret = btf_prepare_func_args(env, subprog); 20851 if (ret) 20852 goto out; 20853 20854 if (subprog_is_exc_cb(env, subprog)) { 20855 state->frame[0]->in_exception_callback_fn = true; 20856 /* We have already ensured that the callback returns an integer, just 20857 * like all global subprogs. We need to determine it only has a single 20858 * scalar argument. 20859 */ 20860 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20861 verbose(env, "exception cb only supports single integer argument\n"); 20862 ret = -EINVAL; 20863 goto out; 20864 } 20865 } 20866 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20867 arg = &sub->args[i - BPF_REG_1]; 20868 reg = ®s[i]; 20869 20870 if (arg->arg_type == ARG_PTR_TO_CTX) { 20871 reg->type = PTR_TO_CTX; 20872 mark_reg_known_zero(env, regs, i); 20873 } else if (arg->arg_type == ARG_ANYTHING) { 20874 reg->type = SCALAR_VALUE; 20875 mark_reg_unknown(env, regs, i); 20876 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20877 /* assume unspecial LOCAL dynptr type */ 20878 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20879 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20880 reg->type = PTR_TO_MEM; 20881 if (arg->arg_type & PTR_MAYBE_NULL) 20882 reg->type |= PTR_MAYBE_NULL; 20883 mark_reg_known_zero(env, regs, i); 20884 reg->mem_size = arg->mem_size; 20885 reg->id = ++env->id_gen; 20886 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 20887 reg->type = PTR_TO_BTF_ID; 20888 if (arg->arg_type & PTR_MAYBE_NULL) 20889 reg->type |= PTR_MAYBE_NULL; 20890 if (arg->arg_type & PTR_UNTRUSTED) 20891 reg->type |= PTR_UNTRUSTED; 20892 if (arg->arg_type & PTR_TRUSTED) 20893 reg->type |= PTR_TRUSTED; 20894 mark_reg_known_zero(env, regs, i); 20895 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 20896 reg->btf_id = arg->btf_id; 20897 reg->id = ++env->id_gen; 20898 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 20899 /* caller can pass either PTR_TO_ARENA or SCALAR */ 20900 mark_reg_unknown(env, regs, i); 20901 } else { 20902 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20903 i - BPF_REG_1, arg->arg_type); 20904 ret = -EFAULT; 20905 goto out; 20906 } 20907 } 20908 } else { 20909 /* if main BPF program has associated BTF info, validate that 20910 * it's matching expected signature, and otherwise mark BTF 20911 * info for main program as unreliable 20912 */ 20913 if (env->prog->aux->func_info_aux) { 20914 ret = btf_prepare_func_args(env, 0); 20915 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20916 env->prog->aux->func_info_aux[0].unreliable = true; 20917 } 20918 20919 /* 1st arg to a function */ 20920 regs[BPF_REG_1].type = PTR_TO_CTX; 20921 mark_reg_known_zero(env, regs, BPF_REG_1); 20922 } 20923 20924 ret = do_check(env); 20925 out: 20926 /* check for NULL is necessary, since cur_state can be freed inside 20927 * do_check() under memory pressure. 20928 */ 20929 if (env->cur_state) { 20930 free_verifier_state(env->cur_state, true); 20931 env->cur_state = NULL; 20932 } 20933 while (!pop_stack(env, NULL, NULL, false)); 20934 if (!ret && pop_log) 20935 bpf_vlog_reset(&env->log, 0); 20936 free_states(env); 20937 return ret; 20938 } 20939 20940 /* Lazily verify all global functions based on their BTF, if they are called 20941 * from main BPF program or any of subprograms transitively. 20942 * BPF global subprogs called from dead code are not validated. 20943 * All callable global functions must pass verification. 20944 * Otherwise the whole program is rejected. 20945 * Consider: 20946 * int bar(int); 20947 * int foo(int f) 20948 * { 20949 * return bar(f); 20950 * } 20951 * int bar(int b) 20952 * { 20953 * ... 20954 * } 20955 * foo() will be verified first for R1=any_scalar_value. During verification it 20956 * will be assumed that bar() already verified successfully and call to bar() 20957 * from foo() will be checked for type match only. Later bar() will be verified 20958 * independently to check that it's safe for R1=any_scalar_value. 20959 */ 20960 static int do_check_subprogs(struct bpf_verifier_env *env) 20961 { 20962 struct bpf_prog_aux *aux = env->prog->aux; 20963 struct bpf_func_info_aux *sub_aux; 20964 int i, ret, new_cnt; 20965 20966 if (!aux->func_info) 20967 return 0; 20968 20969 /* exception callback is presumed to be always called */ 20970 if (env->exception_callback_subprog) 20971 subprog_aux(env, env->exception_callback_subprog)->called = true; 20972 20973 again: 20974 new_cnt = 0; 20975 for (i = 1; i < env->subprog_cnt; i++) { 20976 if (!subprog_is_global(env, i)) 20977 continue; 20978 20979 sub_aux = subprog_aux(env, i); 20980 if (!sub_aux->called || sub_aux->verified) 20981 continue; 20982 20983 env->insn_idx = env->subprog_info[i].start; 20984 WARN_ON_ONCE(env->insn_idx == 0); 20985 ret = do_check_common(env, i); 20986 if (ret) { 20987 return ret; 20988 } else if (env->log.level & BPF_LOG_LEVEL) { 20989 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20990 i, subprog_name(env, i)); 20991 } 20992 20993 /* We verified new global subprog, it might have called some 20994 * more global subprogs that we haven't verified yet, so we 20995 * need to do another pass over subprogs to verify those. 20996 */ 20997 sub_aux->verified = true; 20998 new_cnt++; 20999 } 21000 21001 /* We can't loop forever as we verify at least one global subprog on 21002 * each pass. 21003 */ 21004 if (new_cnt) 21005 goto again; 21006 21007 return 0; 21008 } 21009 21010 static int do_check_main(struct bpf_verifier_env *env) 21011 { 21012 int ret; 21013 21014 env->insn_idx = 0; 21015 ret = do_check_common(env, 0); 21016 if (!ret) 21017 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 21018 return ret; 21019 } 21020 21021 21022 static void print_verification_stats(struct bpf_verifier_env *env) 21023 { 21024 int i; 21025 21026 if (env->log.level & BPF_LOG_STATS) { 21027 verbose(env, "verification time %lld usec\n", 21028 div_u64(env->verification_time, 1000)); 21029 verbose(env, "stack depth "); 21030 for (i = 0; i < env->subprog_cnt; i++) { 21031 u32 depth = env->subprog_info[i].stack_depth; 21032 21033 verbose(env, "%d", depth); 21034 if (i + 1 < env->subprog_cnt) 21035 verbose(env, "+"); 21036 } 21037 verbose(env, "\n"); 21038 } 21039 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 21040 "total_states %d peak_states %d mark_read %d\n", 21041 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 21042 env->max_states_per_insn, env->total_states, 21043 env->peak_states, env->longest_mark_read_walk); 21044 } 21045 21046 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 21047 { 21048 const struct btf_type *t, *func_proto; 21049 const struct bpf_struct_ops_desc *st_ops_desc; 21050 const struct bpf_struct_ops *st_ops; 21051 const struct btf_member *member; 21052 struct bpf_prog *prog = env->prog; 21053 u32 btf_id, member_idx; 21054 struct btf *btf; 21055 const char *mname; 21056 21057 if (!prog->gpl_compatible) { 21058 verbose(env, "struct ops programs must have a GPL compatible license\n"); 21059 return -EINVAL; 21060 } 21061 21062 if (!prog->aux->attach_btf_id) 21063 return -ENOTSUPP; 21064 21065 btf = prog->aux->attach_btf; 21066 if (btf_is_module(btf)) { 21067 /* Make sure st_ops is valid through the lifetime of env */ 21068 env->attach_btf_mod = btf_try_get_module(btf); 21069 if (!env->attach_btf_mod) { 21070 verbose(env, "struct_ops module %s is not found\n", 21071 btf_get_name(btf)); 21072 return -ENOTSUPP; 21073 } 21074 } 21075 21076 btf_id = prog->aux->attach_btf_id; 21077 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 21078 if (!st_ops_desc) { 21079 verbose(env, "attach_btf_id %u is not a supported struct\n", 21080 btf_id); 21081 return -ENOTSUPP; 21082 } 21083 st_ops = st_ops_desc->st_ops; 21084 21085 t = st_ops_desc->type; 21086 member_idx = prog->expected_attach_type; 21087 if (member_idx >= btf_type_vlen(t)) { 21088 verbose(env, "attach to invalid member idx %u of struct %s\n", 21089 member_idx, st_ops->name); 21090 return -EINVAL; 21091 } 21092 21093 member = &btf_type_member(t)[member_idx]; 21094 mname = btf_name_by_offset(btf, member->name_off); 21095 func_proto = btf_type_resolve_func_ptr(btf, member->type, 21096 NULL); 21097 if (!func_proto) { 21098 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 21099 mname, member_idx, st_ops->name); 21100 return -EINVAL; 21101 } 21102 21103 if (st_ops->check_member) { 21104 int err = st_ops->check_member(t, member, prog); 21105 21106 if (err) { 21107 verbose(env, "attach to unsupported member %s of struct %s\n", 21108 mname, st_ops->name); 21109 return err; 21110 } 21111 } 21112 21113 /* btf_ctx_access() used this to provide argument type info */ 21114 prog->aux->ctx_arg_info = 21115 st_ops_desc->arg_info[member_idx].info; 21116 prog->aux->ctx_arg_info_size = 21117 st_ops_desc->arg_info[member_idx].cnt; 21118 21119 prog->aux->attach_func_proto = func_proto; 21120 prog->aux->attach_func_name = mname; 21121 env->ops = st_ops->verifier_ops; 21122 21123 return 0; 21124 } 21125 #define SECURITY_PREFIX "security_" 21126 21127 static int check_attach_modify_return(unsigned long addr, const char *func_name) 21128 { 21129 if (within_error_injection_list(addr) || 21130 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 21131 return 0; 21132 21133 return -EINVAL; 21134 } 21135 21136 /* list of non-sleepable functions that are otherwise on 21137 * ALLOW_ERROR_INJECTION list 21138 */ 21139 BTF_SET_START(btf_non_sleepable_error_inject) 21140 /* Three functions below can be called from sleepable and non-sleepable context. 21141 * Assume non-sleepable from bpf safety point of view. 21142 */ 21143 BTF_ID(func, __filemap_add_folio) 21144 BTF_ID(func, should_fail_alloc_page) 21145 BTF_ID(func, should_failslab) 21146 BTF_SET_END(btf_non_sleepable_error_inject) 21147 21148 static int check_non_sleepable_error_inject(u32 btf_id) 21149 { 21150 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 21151 } 21152 21153 int bpf_check_attach_target(struct bpf_verifier_log *log, 21154 const struct bpf_prog *prog, 21155 const struct bpf_prog *tgt_prog, 21156 u32 btf_id, 21157 struct bpf_attach_target_info *tgt_info) 21158 { 21159 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 21160 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 21161 const char prefix[] = "btf_trace_"; 21162 int ret = 0, subprog = -1, i; 21163 const struct btf_type *t; 21164 bool conservative = true; 21165 const char *tname; 21166 struct btf *btf; 21167 long addr = 0; 21168 struct module *mod = NULL; 21169 21170 if (!btf_id) { 21171 bpf_log(log, "Tracing programs must provide btf_id\n"); 21172 return -EINVAL; 21173 } 21174 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 21175 if (!btf) { 21176 bpf_log(log, 21177 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 21178 return -EINVAL; 21179 } 21180 t = btf_type_by_id(btf, btf_id); 21181 if (!t) { 21182 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 21183 return -EINVAL; 21184 } 21185 tname = btf_name_by_offset(btf, t->name_off); 21186 if (!tname) { 21187 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 21188 return -EINVAL; 21189 } 21190 if (tgt_prog) { 21191 struct bpf_prog_aux *aux = tgt_prog->aux; 21192 21193 if (bpf_prog_is_dev_bound(prog->aux) && 21194 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 21195 bpf_log(log, "Target program bound device mismatch"); 21196 return -EINVAL; 21197 } 21198 21199 for (i = 0; i < aux->func_info_cnt; i++) 21200 if (aux->func_info[i].type_id == btf_id) { 21201 subprog = i; 21202 break; 21203 } 21204 if (subprog == -1) { 21205 bpf_log(log, "Subprog %s doesn't exist\n", tname); 21206 return -EINVAL; 21207 } 21208 if (aux->func && aux->func[subprog]->aux->exception_cb) { 21209 bpf_log(log, 21210 "%s programs cannot attach to exception callback\n", 21211 prog_extension ? "Extension" : "FENTRY/FEXIT"); 21212 return -EINVAL; 21213 } 21214 conservative = aux->func_info_aux[subprog].unreliable; 21215 if (prog_extension) { 21216 if (conservative) { 21217 bpf_log(log, 21218 "Cannot replace static functions\n"); 21219 return -EINVAL; 21220 } 21221 if (!prog->jit_requested) { 21222 bpf_log(log, 21223 "Extension programs should be JITed\n"); 21224 return -EINVAL; 21225 } 21226 } 21227 if (!tgt_prog->jited) { 21228 bpf_log(log, "Can attach to only JITed progs\n"); 21229 return -EINVAL; 21230 } 21231 if (prog_tracing) { 21232 if (aux->attach_tracing_prog) { 21233 /* 21234 * Target program is an fentry/fexit which is already attached 21235 * to another tracing program. More levels of nesting 21236 * attachment are not allowed. 21237 */ 21238 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 21239 return -EINVAL; 21240 } 21241 } else if (tgt_prog->type == prog->type) { 21242 /* 21243 * To avoid potential call chain cycles, prevent attaching of a 21244 * program extension to another extension. It's ok to attach 21245 * fentry/fexit to extension program. 21246 */ 21247 bpf_log(log, "Cannot recursively attach\n"); 21248 return -EINVAL; 21249 } 21250 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 21251 prog_extension && 21252 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 21253 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 21254 /* Program extensions can extend all program types 21255 * except fentry/fexit. The reason is the following. 21256 * The fentry/fexit programs are used for performance 21257 * analysis, stats and can be attached to any program 21258 * type. When extension program is replacing XDP function 21259 * it is necessary to allow performance analysis of all 21260 * functions. Both original XDP program and its program 21261 * extension. Hence attaching fentry/fexit to 21262 * BPF_PROG_TYPE_EXT is allowed. If extending of 21263 * fentry/fexit was allowed it would be possible to create 21264 * long call chain fentry->extension->fentry->extension 21265 * beyond reasonable stack size. Hence extending fentry 21266 * is not allowed. 21267 */ 21268 bpf_log(log, "Cannot extend fentry/fexit\n"); 21269 return -EINVAL; 21270 } 21271 } else { 21272 if (prog_extension) { 21273 bpf_log(log, "Cannot replace kernel functions\n"); 21274 return -EINVAL; 21275 } 21276 } 21277 21278 switch (prog->expected_attach_type) { 21279 case BPF_TRACE_RAW_TP: 21280 if (tgt_prog) { 21281 bpf_log(log, 21282 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 21283 return -EINVAL; 21284 } 21285 if (!btf_type_is_typedef(t)) { 21286 bpf_log(log, "attach_btf_id %u is not a typedef\n", 21287 btf_id); 21288 return -EINVAL; 21289 } 21290 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 21291 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 21292 btf_id, tname); 21293 return -EINVAL; 21294 } 21295 tname += sizeof(prefix) - 1; 21296 t = btf_type_by_id(btf, t->type); 21297 if (!btf_type_is_ptr(t)) 21298 /* should never happen in valid vmlinux build */ 21299 return -EINVAL; 21300 t = btf_type_by_id(btf, t->type); 21301 if (!btf_type_is_func_proto(t)) 21302 /* should never happen in valid vmlinux build */ 21303 return -EINVAL; 21304 21305 break; 21306 case BPF_TRACE_ITER: 21307 if (!btf_type_is_func(t)) { 21308 bpf_log(log, "attach_btf_id %u is not a function\n", 21309 btf_id); 21310 return -EINVAL; 21311 } 21312 t = btf_type_by_id(btf, t->type); 21313 if (!btf_type_is_func_proto(t)) 21314 return -EINVAL; 21315 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21316 if (ret) 21317 return ret; 21318 break; 21319 default: 21320 if (!prog_extension) 21321 return -EINVAL; 21322 fallthrough; 21323 case BPF_MODIFY_RETURN: 21324 case BPF_LSM_MAC: 21325 case BPF_LSM_CGROUP: 21326 case BPF_TRACE_FENTRY: 21327 case BPF_TRACE_FEXIT: 21328 if (!btf_type_is_func(t)) { 21329 bpf_log(log, "attach_btf_id %u is not a function\n", 21330 btf_id); 21331 return -EINVAL; 21332 } 21333 if (prog_extension && 21334 btf_check_type_match(log, prog, btf, t)) 21335 return -EINVAL; 21336 t = btf_type_by_id(btf, t->type); 21337 if (!btf_type_is_func_proto(t)) 21338 return -EINVAL; 21339 21340 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 21341 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 21342 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 21343 return -EINVAL; 21344 21345 if (tgt_prog && conservative) 21346 t = NULL; 21347 21348 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 21349 if (ret < 0) 21350 return ret; 21351 21352 if (tgt_prog) { 21353 if (subprog == 0) 21354 addr = (long) tgt_prog->bpf_func; 21355 else 21356 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 21357 } else { 21358 if (btf_is_module(btf)) { 21359 mod = btf_try_get_module(btf); 21360 if (mod) 21361 addr = find_kallsyms_symbol_value(mod, tname); 21362 else 21363 addr = 0; 21364 } else { 21365 addr = kallsyms_lookup_name(tname); 21366 } 21367 if (!addr) { 21368 module_put(mod); 21369 bpf_log(log, 21370 "The address of function %s cannot be found\n", 21371 tname); 21372 return -ENOENT; 21373 } 21374 } 21375 21376 if (prog->sleepable) { 21377 ret = -EINVAL; 21378 switch (prog->type) { 21379 case BPF_PROG_TYPE_TRACING: 21380 21381 /* fentry/fexit/fmod_ret progs can be sleepable if they are 21382 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 21383 */ 21384 if (!check_non_sleepable_error_inject(btf_id) && 21385 within_error_injection_list(addr)) 21386 ret = 0; 21387 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 21388 * in the fmodret id set with the KF_SLEEPABLE flag. 21389 */ 21390 else { 21391 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 21392 prog); 21393 21394 if (flags && (*flags & KF_SLEEPABLE)) 21395 ret = 0; 21396 } 21397 break; 21398 case BPF_PROG_TYPE_LSM: 21399 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 21400 * Only some of them are sleepable. 21401 */ 21402 if (bpf_lsm_is_sleepable_hook(btf_id)) 21403 ret = 0; 21404 break; 21405 default: 21406 break; 21407 } 21408 if (ret) { 21409 module_put(mod); 21410 bpf_log(log, "%s is not sleepable\n", tname); 21411 return ret; 21412 } 21413 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 21414 if (tgt_prog) { 21415 module_put(mod); 21416 bpf_log(log, "can't modify return codes of BPF programs\n"); 21417 return -EINVAL; 21418 } 21419 ret = -EINVAL; 21420 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 21421 !check_attach_modify_return(addr, tname)) 21422 ret = 0; 21423 if (ret) { 21424 module_put(mod); 21425 bpf_log(log, "%s() is not modifiable\n", tname); 21426 return ret; 21427 } 21428 } 21429 21430 break; 21431 } 21432 tgt_info->tgt_addr = addr; 21433 tgt_info->tgt_name = tname; 21434 tgt_info->tgt_type = t; 21435 tgt_info->tgt_mod = mod; 21436 return 0; 21437 } 21438 21439 BTF_SET_START(btf_id_deny) 21440 BTF_ID_UNUSED 21441 #ifdef CONFIG_SMP 21442 BTF_ID(func, migrate_disable) 21443 BTF_ID(func, migrate_enable) 21444 #endif 21445 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 21446 BTF_ID(func, rcu_read_unlock_strict) 21447 #endif 21448 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 21449 BTF_ID(func, preempt_count_add) 21450 BTF_ID(func, preempt_count_sub) 21451 #endif 21452 #ifdef CONFIG_PREEMPT_RCU 21453 BTF_ID(func, __rcu_read_lock) 21454 BTF_ID(func, __rcu_read_unlock) 21455 #endif 21456 BTF_SET_END(btf_id_deny) 21457 21458 static bool can_be_sleepable(struct bpf_prog *prog) 21459 { 21460 if (prog->type == BPF_PROG_TYPE_TRACING) { 21461 switch (prog->expected_attach_type) { 21462 case BPF_TRACE_FENTRY: 21463 case BPF_TRACE_FEXIT: 21464 case BPF_MODIFY_RETURN: 21465 case BPF_TRACE_ITER: 21466 return true; 21467 default: 21468 return false; 21469 } 21470 } 21471 return prog->type == BPF_PROG_TYPE_LSM || 21472 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 21473 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 21474 } 21475 21476 static int check_attach_btf_id(struct bpf_verifier_env *env) 21477 { 21478 struct bpf_prog *prog = env->prog; 21479 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 21480 struct bpf_attach_target_info tgt_info = {}; 21481 u32 btf_id = prog->aux->attach_btf_id; 21482 struct bpf_trampoline *tr; 21483 int ret; 21484 u64 key; 21485 21486 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 21487 if (prog->sleepable) 21488 /* attach_btf_id checked to be zero already */ 21489 return 0; 21490 verbose(env, "Syscall programs can only be sleepable\n"); 21491 return -EINVAL; 21492 } 21493 21494 if (prog->sleepable && !can_be_sleepable(prog)) { 21495 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 21496 return -EINVAL; 21497 } 21498 21499 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 21500 return check_struct_ops_btf_id(env); 21501 21502 if (prog->type != BPF_PROG_TYPE_TRACING && 21503 prog->type != BPF_PROG_TYPE_LSM && 21504 prog->type != BPF_PROG_TYPE_EXT) 21505 return 0; 21506 21507 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 21508 if (ret) 21509 return ret; 21510 21511 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 21512 /* to make freplace equivalent to their targets, they need to 21513 * inherit env->ops and expected_attach_type for the rest of the 21514 * verification 21515 */ 21516 env->ops = bpf_verifier_ops[tgt_prog->type]; 21517 prog->expected_attach_type = tgt_prog->expected_attach_type; 21518 } 21519 21520 /* store info about the attachment target that will be used later */ 21521 prog->aux->attach_func_proto = tgt_info.tgt_type; 21522 prog->aux->attach_func_name = tgt_info.tgt_name; 21523 prog->aux->mod = tgt_info.tgt_mod; 21524 21525 if (tgt_prog) { 21526 prog->aux->saved_dst_prog_type = tgt_prog->type; 21527 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 21528 } 21529 21530 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 21531 prog->aux->attach_btf_trace = true; 21532 return 0; 21533 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 21534 if (!bpf_iter_prog_supported(prog)) 21535 return -EINVAL; 21536 return 0; 21537 } 21538 21539 if (prog->type == BPF_PROG_TYPE_LSM) { 21540 ret = bpf_lsm_verify_prog(&env->log, prog); 21541 if (ret < 0) 21542 return ret; 21543 } else if (prog->type == BPF_PROG_TYPE_TRACING && 21544 btf_id_set_contains(&btf_id_deny, btf_id)) { 21545 return -EINVAL; 21546 } 21547 21548 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 21549 tr = bpf_trampoline_get(key, &tgt_info); 21550 if (!tr) 21551 return -ENOMEM; 21552 21553 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 21554 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 21555 21556 prog->aux->dst_trampoline = tr; 21557 return 0; 21558 } 21559 21560 struct btf *bpf_get_btf_vmlinux(void) 21561 { 21562 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 21563 mutex_lock(&bpf_verifier_lock); 21564 if (!btf_vmlinux) 21565 btf_vmlinux = btf_parse_vmlinux(); 21566 mutex_unlock(&bpf_verifier_lock); 21567 } 21568 return btf_vmlinux; 21569 } 21570 21571 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 21572 { 21573 u64 start_time = ktime_get_ns(); 21574 struct bpf_verifier_env *env; 21575 int i, len, ret = -EINVAL, err; 21576 u32 log_true_size; 21577 bool is_priv; 21578 21579 /* no program is valid */ 21580 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 21581 return -EINVAL; 21582 21583 /* 'struct bpf_verifier_env' can be global, but since it's not small, 21584 * allocate/free it every time bpf_check() is called 21585 */ 21586 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 21587 if (!env) 21588 return -ENOMEM; 21589 21590 env->bt.env = env; 21591 21592 len = (*prog)->len; 21593 env->insn_aux_data = 21594 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 21595 ret = -ENOMEM; 21596 if (!env->insn_aux_data) 21597 goto err_free_env; 21598 for (i = 0; i < len; i++) 21599 env->insn_aux_data[i].orig_idx = i; 21600 env->prog = *prog; 21601 env->ops = bpf_verifier_ops[env->prog->type]; 21602 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 21603 21604 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 21605 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 21606 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 21607 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 21608 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 21609 21610 bpf_get_btf_vmlinux(); 21611 21612 /* grab the mutex to protect few globals used by verifier */ 21613 if (!is_priv) 21614 mutex_lock(&bpf_verifier_lock); 21615 21616 /* user could have requested verbose verifier output 21617 * and supplied buffer to store the verification trace 21618 */ 21619 ret = bpf_vlog_init(&env->log, attr->log_level, 21620 (char __user *) (unsigned long) attr->log_buf, 21621 attr->log_size); 21622 if (ret) 21623 goto err_unlock; 21624 21625 mark_verifier_state_clean(env); 21626 21627 if (IS_ERR(btf_vmlinux)) { 21628 /* Either gcc or pahole or kernel are broken. */ 21629 verbose(env, "in-kernel BTF is malformed\n"); 21630 ret = PTR_ERR(btf_vmlinux); 21631 goto skip_full_check; 21632 } 21633 21634 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 21635 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 21636 env->strict_alignment = true; 21637 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 21638 env->strict_alignment = false; 21639 21640 if (is_priv) 21641 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 21642 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 21643 21644 env->explored_states = kvcalloc(state_htab_size(env), 21645 sizeof(struct bpf_verifier_state_list *), 21646 GFP_USER); 21647 ret = -ENOMEM; 21648 if (!env->explored_states) 21649 goto skip_full_check; 21650 21651 ret = check_btf_info_early(env, attr, uattr); 21652 if (ret < 0) 21653 goto skip_full_check; 21654 21655 ret = add_subprog_and_kfunc(env); 21656 if (ret < 0) 21657 goto skip_full_check; 21658 21659 ret = check_subprogs(env); 21660 if (ret < 0) 21661 goto skip_full_check; 21662 21663 ret = check_btf_info(env, attr, uattr); 21664 if (ret < 0) 21665 goto skip_full_check; 21666 21667 ret = check_attach_btf_id(env); 21668 if (ret) 21669 goto skip_full_check; 21670 21671 ret = resolve_pseudo_ldimm64(env); 21672 if (ret < 0) 21673 goto skip_full_check; 21674 21675 if (bpf_prog_is_offloaded(env->prog->aux)) { 21676 ret = bpf_prog_offload_verifier_prep(env->prog); 21677 if (ret) 21678 goto skip_full_check; 21679 } 21680 21681 ret = check_cfg(env); 21682 if (ret < 0) 21683 goto skip_full_check; 21684 21685 ret = do_check_main(env); 21686 ret = ret ?: do_check_subprogs(env); 21687 21688 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 21689 ret = bpf_prog_offload_finalize(env); 21690 21691 skip_full_check: 21692 kvfree(env->explored_states); 21693 21694 if (ret == 0) 21695 ret = check_max_stack_depth(env); 21696 21697 /* instruction rewrites happen after this point */ 21698 if (ret == 0) 21699 ret = optimize_bpf_loop(env); 21700 21701 if (is_priv) { 21702 if (ret == 0) 21703 opt_hard_wire_dead_code_branches(env); 21704 if (ret == 0) 21705 ret = opt_remove_dead_code(env); 21706 if (ret == 0) 21707 ret = opt_remove_nops(env); 21708 } else { 21709 if (ret == 0) 21710 sanitize_dead_code(env); 21711 } 21712 21713 if (ret == 0) 21714 /* program is valid, convert *(u32*)(ctx + off) accesses */ 21715 ret = convert_ctx_accesses(env); 21716 21717 if (ret == 0) 21718 ret = do_misc_fixups(env); 21719 21720 /* do 32-bit optimization after insn patching has done so those patched 21721 * insns could be handled correctly. 21722 */ 21723 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 21724 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 21725 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 21726 : false; 21727 } 21728 21729 if (ret == 0) 21730 ret = fixup_call_args(env); 21731 21732 env->verification_time = ktime_get_ns() - start_time; 21733 print_verification_stats(env); 21734 env->prog->aux->verified_insns = env->insn_processed; 21735 21736 /* preserve original error even if log finalization is successful */ 21737 err = bpf_vlog_finalize(&env->log, &log_true_size); 21738 if (err) 21739 ret = err; 21740 21741 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 21742 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 21743 &log_true_size, sizeof(log_true_size))) { 21744 ret = -EFAULT; 21745 goto err_release_maps; 21746 } 21747 21748 if (ret) 21749 goto err_release_maps; 21750 21751 if (env->used_map_cnt) { 21752 /* if program passed verifier, update used_maps in bpf_prog_info */ 21753 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 21754 sizeof(env->used_maps[0]), 21755 GFP_KERNEL); 21756 21757 if (!env->prog->aux->used_maps) { 21758 ret = -ENOMEM; 21759 goto err_release_maps; 21760 } 21761 21762 memcpy(env->prog->aux->used_maps, env->used_maps, 21763 sizeof(env->used_maps[0]) * env->used_map_cnt); 21764 env->prog->aux->used_map_cnt = env->used_map_cnt; 21765 } 21766 if (env->used_btf_cnt) { 21767 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 21768 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 21769 sizeof(env->used_btfs[0]), 21770 GFP_KERNEL); 21771 if (!env->prog->aux->used_btfs) { 21772 ret = -ENOMEM; 21773 goto err_release_maps; 21774 } 21775 21776 memcpy(env->prog->aux->used_btfs, env->used_btfs, 21777 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 21778 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 21779 } 21780 if (env->used_map_cnt || env->used_btf_cnt) { 21781 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 21782 * bpf_ld_imm64 instructions 21783 */ 21784 convert_pseudo_ld_imm64(env); 21785 } 21786 21787 adjust_btf_func(env); 21788 21789 err_release_maps: 21790 if (!env->prog->aux->used_maps) 21791 /* if we didn't copy map pointers into bpf_prog_info, release 21792 * them now. Otherwise free_used_maps() will release them. 21793 */ 21794 release_maps(env); 21795 if (!env->prog->aux->used_btfs) 21796 release_btfs(env); 21797 21798 /* extension progs temporarily inherit the attach_type of their targets 21799 for verification purposes, so set it back to zero before returning 21800 */ 21801 if (env->prog->type == BPF_PROG_TYPE_EXT) 21802 env->prog->expected_attach_type = 0; 21803 21804 *prog = env->prog; 21805 21806 module_put(env->attach_btf_mod); 21807 err_unlock: 21808 if (!is_priv) 21809 mutex_unlock(&bpf_verifier_lock); 21810 vfree(env->insn_aux_data); 21811 err_free_env: 21812 kfree(env); 21813 return ret; 21814 } 21815